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/main.yaml b/.github/workflows/main.yaml index 785044868..67dfc6c6c 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -20,7 +20,7 @@ jobs: - id: check working-directory: . run: | - if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then + if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml index f69ed0790..d683bd883 100644 --- a/.github/workflows/respond-to-cubic.yaml +++ b/.github/workflows/respond-to-cubic.yaml @@ -27,6 +27,18 @@ jobs: echo "contains_mention=false" >> $GITHUB_OUTPUT fi + - name: Add eyes reaction to comment + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: ${{ github.event.comment.id }}, + content: 'eyes' + }); + - name: Checkout PR branch if: steps.check-mention.outputs.contains_mention == 'true' uses: actions/checkout@v5 @@ -37,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({ @@ -95,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: @@ -130,6 +142,18 @@ jobs: echo "contains_mention=false" >> $GITHUB_OUTPUT fi + - name: Add eyes reaction to comment + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForPullRequestReviewComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: ${{ github.event.comment.id }}, + content: 'eyes' + }); + - name: Checkout PR branch if: steps.check-mention.outputs.contains_mention == 'true' uses: actions/checkout@v5 @@ -187,7 +211,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/.prettierignore b/.prettierignore index 97c951ccc..51cd37d83 100644 --- a/.prettierignore +++ b/.prettierignore @@ -23,5 +23,5 @@ CHANGELOG.md **/CODEOWNERS core/vendor coverage -e2e +# e2e packages/continue-sdk \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3993294b4..21c645480 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the ### Our Git Workflow We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the -`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow +`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When -a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar +a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by . diff --git a/actions/detailed-review/action.yml b/actions/detailed-review/action.yml index 97c47018f..f8273cc50 100644 --- a/actions/detailed-review/action.yml +++ b/actions/detailed-review/action.yml @@ -73,7 +73,7 @@ runs: - name: Install Continue CLI if: env.SKIP_REVIEW != 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.25 + run: npm install -g @continuedev/cli@1.4.30 - name: Build Inline Review Prompt if: env.SKIP_REVIEW != 'true' @@ -194,6 +194,21 @@ runs: exit 1 fi + # Validate API key + if [ -z "$CONTINUE_API_KEY" ]; then + echo "Warning: CONTINUE_API_KEY environment variable is not set" + # Create fallback review and continue + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review skipped: CONTINUE_API_KEY not configured.", + "comments": [] + } + EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "SKIP_CLI=false" >> $GITHUB_ENV + fi + # Log the prompt for debugging echo "===== START REVIEW PROMPT =====" head -n 50 inline_review_prompt.txt @@ -201,23 +216,67 @@ runs: tail -n 20 inline_review_prompt.txt echo "===== END REVIEW PROMPT =====" - # Run the CLI and capture JSON output - cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json - - # Log the output for debugging - echo "Initial Continue CLI output:" - cat inline_review_raw.json - - # Validate JSON output and use it directly - if ! jq empty inline_review_raw.json 2>/dev/null; then - echo "Error: Invalid JSON output from Continue CLI" - exit 1 + # Test Continue CLI availability + if [ "$SKIP_CLI" != "true" ]; then + echo "Testing Continue CLI..." + if ! cn --version; then + echo "Warning: Continue CLI not found or not working" + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review skipped: Continue CLI installation failed.", + "comments": [] + } + EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "Continue CLI version: $(cn --version)" + fi + fi + + # Run the CLI and capture JSON output with error handling + if [ "$SKIP_CLI" != "true" ]; then + echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}" + + # Write prompt to temp file for better handling + PROMPT_FILE="/tmp/continue-prompt-$.txt" + cp inline_review_prompt.txt "$PROMPT_FILE" + + # Use timeout to prevent hanging (240 seconds = 4 minutes) + if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then + echo "Warning: Continue CLI command failed" + echo "CLI error log:" + cat cli_error.log + + # Create fallback review + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.", + "comments": [] + } + EOF + echo "Created fallback review due to CLI failure" + else + # Log the output for debugging + echo "Initial Continue CLI output:" + cat inline_review_raw.json + + # Validate JSON output and use it directly + if ! jq empty inline_review_raw.json 2>/dev/null; then + echo "Warning: Invalid JSON output from Continue CLI, using fallback" + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review completed but failed to parse output correctly.", + "comments": [] + } + EOF + else + # Use the JSON output directly + cp inline_review_raw.json inline_review.json + echo "Review output:" + cat inline_review.json + fi + fi fi - - # Use the JSON output directly - cp inline_review_raw.json inline_review.json - echo "Review output:" - cat inline_review.json - name: Post Inline Review Comments if: env.SKIP_REVIEW != 'true' diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index bf5e221e1..dd18c447a 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -68,7 +68,7 @@ runs: - name: Install Continue CLI if: env.SHOULD_RUN == 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.25 + run: npm install -g @continuedev/cli@1.4.30 - name: Build PR Review Prompt if: env.SHOULD_RUN == 'true' @@ -157,6 +157,24 @@ runs: echo "==================================" echo "" + # Validate API key + if [ -z "$CONTINUE_API_KEY" ]; then + echo "Warning: CONTINUE_API_KEY environment variable is not set" + # Create fallback review and continue + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review skipped: CONTINUE_API_KEY not configured. + +### Configuration Required +- Please set the CONTINUE_API_KEY secret in repository settings +- Verify that the organization and config path are valid +EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "SKIP_CLI=false" >> $GITHUB_ENV + fi + # Validate inputs to prevent command injection if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores." @@ -168,8 +186,55 @@ runs: exit 1 fi - # Run the CLI with validated config - cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md + # Test Continue CLI availability + if [ "$SKIP_CLI" != "true" ]; then + echo "Testing Continue CLI..." + if ! cn --version; then + echo "Warning: Continue CLI not found or not working" + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review skipped: Continue CLI installation failed. + +### Troubleshooting +- Check that npm installation succeeded +- Verify @continuedev/cli package is available +EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "Continue CLI version: $(cn --version)" + fi + fi + + # Run the CLI with validated config and error handling + if [ "$SKIP_CLI" != "true" ]; then + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" + + # Write prompt to temp file for better handling + PROMPT_FILE="/tmp/continue-prompt-$.txt" + cp review_prompt.txt "$PROMPT_FILE" + + # Use timeout to prevent hanging (240 seconds = 4 minutes) + if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then + echo "Error: Continue CLI command failed" + echo "CLI error log:" + cat cli_error.log + + # Create fallback review + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. + +### Troubleshooting +- Verify the CONTINUE_API_KEY secret is set correctly +- Check that the organization and config path are valid +- Ensure the Continue service is accessible +EOF + else + echo "Review generated successfully" + fi + fi - name: Upload Review Results if: env.SHOULD_RUN == 'true' && always() diff --git a/binary/package-lock.json b/binary/package-lock.json index 37f2d865d..92756d546 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -106,6 +106,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -140,6 +141,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 837bb2a39..2e7a65ca3 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -202,6 +202,8 @@ export class ConfigHandler { message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`, }); } + } else { + PolicySingleton.getInstance().policy = null; } // Load local org if not signed in or hub orgs fail try { diff --git a/core/config/load.ts b/core/config/load.ts index 065842052..370695bd3 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -57,6 +57,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { PolicySingleton } from "../control-plane/PolicySingleton"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import { getBaseToolDefinitions } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; @@ -544,16 +545,21 @@ async function intermediateToFinalConfig({ // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.setConnections( - (config.experimental?.modelContextProtocolServers ?? []).map( - (server, index) => ({ - id: `continue-mcp-server-${index + 1}`, - name: `MCP Server`, - ...server, - }), - ), - false, - ); + const orgPolicy = PolicySingleton.getInstance().policy; + if (orgPolicy?.policy?.allowMcpServers === false) { + await mcpManager.shutdown(); + } else { + mcpManager.setConnections( + (config.experimental?.modelContextProtocolServers ?? []).map( + (server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server`, + ...server, + }), + ), + false, + ); + } // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0b39489eb..fcb5f30bc 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -332,12 +332,14 @@ export default async function doLoadConfig(options: { } } - if ( - PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === - false - ) { + // Org policies + const policy = PolicySingleton.getInstance().policy?.policy; + if (policy?.allowAnonymousTelemetry === false) { newConfig.allowAnonymousTelemetry = false; } + if (policy?.allowCodebaseIndexing === false) { + newConfig.disableIndexing = true; + } // Setup telemetry only after (and if) we know it is enabled await Telemetry.setup( diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 7a9c9f634..65cb5e0ff 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -25,6 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../../tools"; import { getCleanUriPath } from "../../util/uri"; import { loadConfigContextProviders } from "../loadContextProviders"; @@ -378,21 +379,26 @@ async function configYamlToContinueConfig(options: { // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.setConnections( - (config.mcpServers ?? []).map((server) => ({ - id: server.name, - name: server.name, - sourceFile: server.sourceFile, - transport: { - type: "stdio", - args: [], - ...(server as any), // TODO: fix the types on mcpServers in config-yaml - }, - timeout: server.connectionTimeout, - })), - false, - { ide }, - ); + const orgPolicy = PolicySingleton.getInstance().policy; + if (orgPolicy?.policy?.allowMcpServers === false) { + await mcpManager.shutdown(); + } else { + mcpManager.setConnections( + (config.mcpServers ?? []).map((server) => ({ + id: server.name, + name: server.name, + sourceFile: server.sourceFile, + transport: { + type: "stdio", + args: [], + ...(server as any), // TODO: fix the types on mcpServers in config-yaml + }, + timeout: server.connectionTimeout, + })), + false, + { ide }, + ); + } return { config: continueConfig, errors: localErrors }; } diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 22495bef4..c9dc41929 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -48,6 +48,21 @@ export class MCPManagerSingleton { this.connections.delete(id); } + async shutdown() { + if (this.connections.size > 0) { + await Promise.allSettled( + Array.from(this.connections.entries()).map(([id, connection]) => { + try { + connection.abortController.abort(); + void connection.client.close(); + } finally { + this.connections.delete(id); + } + }), + ); + } + } + setConnections( servers: MCPOptions[], forceRefresh: boolean, diff --git a/core/core.ts b/core/core.ts index 65f2e4ede..6d8738f20 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1009,6 +1009,37 @@ export class Core { this.handleToolCall(toolCall), ); + on( + "tools/evaluatePolicy", + async ({ data: { toolName, basePolicy, args } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config.tools.find((t) => t.function.name === toolName); + if (!tool) { + // Tool not found, return base policy + return { policy: basePolicy }; + } + + // Extract display value for specific tools + let displayValue: string | undefined; + if (toolName === "runTerminalCommand" && args.command) { + displayValue = args.command as string; + } + + // If tool has evaluateToolCallPolicy function, use it + if (tool.evaluateToolCallPolicy) { + const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); + return { policy: evaluatedPolicy, displayValue }; + } + + // Otherwise return base policy unchanged + return { policy: basePolicy, displayValue }; + }, + ); + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); diff --git a/core/index.d.ts b/core/index.d.ts index 7c3f4a121..a31e02c67 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1070,11 +1070,6 @@ export interface ToolExtras { codeBaseIndexer?: CodebaseIndexer; } -export type ToolPolicy = - | "allowedWithPermission" - | "allowedWithoutPermission" - | "disabled"; - export interface Tool { type: "function"; function: { @@ -1099,6 +1094,10 @@ export interface Tool { exampleArgs?: Array<[string, string | number]>; }; defaultToolPolicy?: ToolPolicy; + evaluateToolCallPolicy?: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ) => ToolPolicy; } interface ToolChoice { diff --git a/core/package-lock.json b/core/package-lock.json index 974a50300..bf948e8a9 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -17,6 +17,7 @@ "@continuedev/fetch": "file:../packages/fetch", "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -67,6 +68,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -101,6 +103,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", @@ -236,6 +239,20 @@ "vitest": "^3.2.4" } }, + "../packages/terminal-security": { + "name": "@continuedev/terminal-security", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "shell-quote": "^1.8.1" + }, + "devDependencies": { + "@types/node": "^20.11.19", + "@types/shell-quote": "^1.7.5", + "typescript": "^5.5.2", + "vitest": "^1.6.0" + } + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -2955,6 +2972,10 @@ "resolved": "../packages/openai-adapters", "link": true }, + "node_modules/@continuedev/terminal-security": { + "resolved": "../packages/terminal-security", + "link": true + }, "node_modules/@dabh/diagnostics": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz", @@ -6892,6 +6913,13 @@ "node": ">= 0.12" } }, + "node_modules/@types/shell-quote": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz", + "integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/shimmer": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", @@ -17459,6 +17487,18 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/shiki": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz", diff --git a/core/package.json b/core/package.json index c7ca9158d..db53c661a 100644 --- a/core/package.json +++ b/core/package.json @@ -34,6 +34,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", @@ -61,6 +62,7 @@ "@continuedev/fetch": "file:../packages/fetch", "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -111,6 +113,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index b6d3ffe96..5add878be 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -4,6 +4,7 @@ import { DevDataLogEvent, ModelRole, } from "@continuedev/config-yaml"; +import { ToolPolicy } from "@continuedev/terminal-security"; import { AutocompleteInput, @@ -293,6 +294,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { { toolCall: ToolCall }, { contextItems: ContextItem[]; errorMessage?: string }, ]; + "tools/evaluatePolicy": [ + { toolName: string; basePolicy: ToolPolicy; args: Record }, + { policy: ToolPolicy; displayValue?: string }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index db1b9eb9a..91819a33d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -78,6 +78,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedProfile", "didChangeSelectedOrg", "tools/call", + "tools/evaluatePolicy", "controlPlane/getEnvironment", "controlPlane/getFreeTrialStatus", "controlPlane/getModelsAddOnUpgradeUrl", diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 3f740da1c..47cd6769f 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,5 +1,6 @@ export enum BuiltInToolNames { ReadFile = "read_file", + ReadFileRange = "read_file_range", EditExistingFile = "edit_existing_file", SingleFindAndReplace = "single_find_and_replace", MultiEdit = "multi_edit", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index f24210511..c1d203972 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -12,6 +12,8 @@ import { grepSearchImpl } from "./implementations/grepSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; import { readFileImpl } from "./implementations/readFile"; + +import { readFileRangeImpl } from "./implementations/readFileRange"; import { requestRuleImpl } from "./implementations/requestRule"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; @@ -145,6 +147,8 @@ export async function callBuiltInTool( switch (functionName) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + case BuiltInToolNames.ReadFileRange: + return await readFileRangeImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.GrepSearch: diff --git a/core/tools/definitions/index.ts b/core/tools/definitions/index.ts index 413157e4d..bf3dc02d9 100644 --- a/core/tools/definitions/index.ts +++ b/core/tools/definitions/index.ts @@ -9,6 +9,8 @@ export { lsTool } from "./ls"; export { multiEditTool } from "./multiEdit"; export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile"; export { readFileTool } from "./readFile"; + +export { readFileRangeTool } from "./readFileRange"; export { requestRuleTool } from "./requestRule"; export { runTerminalCommandTool } from "./runTerminalCommand"; export { searchWebTool } from "./searchWeb"; diff --git a/core/tools/definitions/readFileRange.ts b/core/tools/definitions/readFileRange.ts new file mode 100644 index 000000000..91e94d574 --- /dev/null +++ b/core/tools/definitions/readFileRange.ts @@ -0,0 +1,51 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const readFileRangeTool: Tool = { + type: "function", + displayTitle: "Read File Range", + wouldLikeTo: + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + isCurrently: + "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + hasAlready: + "viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + readonly: true, + isInstant: true, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.ReadFileRange, + description: + "Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.", + parameters: { + type: "object", + required: ["filepath", "startLine", "endLine"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", + }, + startLine: { + type: "number", + description: + "The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line", + }, + endLine: { + type: "number", + description: + "The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line", + }, + }, + }, + }, + systemMessageDescription: { + prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`, + exampleArgs: [ + ["filepath", "path/to/the_file.txt"], + ["startLine", 10], + ["endLine", 20], + ], + }, + defaultToolPolicy: "allowedWithoutPermission", +}; diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index b2dc74316..dbeaa5c05 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,6 +1,10 @@ import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { + evaluateTerminalCommandSecurity, + ToolPolicy, +} from "@continuedev/terminal-security"; /** * Get the preferred shell for the current platform @@ -56,6 +60,15 @@ export const runTerminalCommandTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ): ToolPolicy => { + return evaluateTerminalCommandSecurity( + basePolicy, + parsedArgs.command as string, + ); + }, systemMessageDescription: { prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool ${RUN_COMMAND_NOTES} diff --git a/core/tools/implementations/readFileRange.integration.vitest.ts b/core/tools/implementations/readFileRange.integration.vitest.ts new file mode 100644 index 000000000..945d03e41 --- /dev/null +++ b/core/tools/implementations/readFileRange.integration.vitest.ts @@ -0,0 +1,204 @@ +import { expect, test, vi } from "vitest"; +import { ToolExtras } from "../.."; +import { readFileRangeImpl } from "./readFileRange"; + +// Mock the dependencies +vi.mock("../../util/ideUtils", () => ({ + resolveRelativePathInDir: vi.fn(), +})); + +vi.mock("../../util/uri", () => ({ + getUriPathBasename: vi.fn(), +})); + +vi.mock("./readFileLimit", () => ({ + throwIfFileExceedsHalfOfContext: vi.fn(), +})); + +test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => { + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); + const { getUriPathBasename } = await import("../../util/uri"); + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); + + // Mock the utility functions + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); + + // Test case 1: Start line beyond end of file + const mockIdeOutOfBounds = { + readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string + }; + + const mockExtras1 = { + ide: mockIdeOutOfBounds, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result1 = await readFileRangeImpl( + { + filepath: "test.txt", + startLine: 100, // Beyond end of file + endLine: 105, + }, + mockExtras1, + ); + + expect(result1).toHaveLength(1); + expect(result1[0].content).toBe(""); + expect(result1[0].description).toBe("test.txt (lines 100-105)"); + + // Test case 2: End line beyond end of file + const mockIdePartialRange = { + readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content + }; + + const mockExtras2 = { + ide: mockIdePartialRange, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result2 = await readFileRangeImpl( + { + filepath: "test.txt", + startLine: 5, + endLine: 100, // Beyond end of file + }, + mockExtras2, + ); + + expect(result2).toHaveLength(1); + expect(result2[0].content).toBe("line5\nline6"); + expect(result2[0].description).toBe("test.txt (lines 5-100)"); + + // Verify that IDE methods were called with correct 0-based ranges + expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith( + "file:///test.txt", + { + start: { line: 99, character: 0 }, // 100 - 1 + end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1 + }, + ); + + expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith( + "file:///test.txt", + { + start: { line: 4, character: 0 }, // 5 - 1 + end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1 + }, + ); +}); + +test("readFileRangeImpl validates line number constraints", async () => { + const mockExtras = { + ide: { readRangeInFile: vi.fn(), readFile: vi.fn() }, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + // Test startLine < 1 (invalid) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 0, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow("startLine must be 1 or greater"); + + // Test negative startLine (no longer supported) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: -1, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow("Negative line numbers are not supported"); + + // Test endLine < 1 (invalid) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 1, + endLine: 0, + }, + mockExtras, + ), + ).rejects.toThrow("endLine must be 1 or greater"); + + // Test negative endLine (no longer supported) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 1, + endLine: -1, + }, + mockExtras, + ), + ).rejects.toThrow("Negative line numbers are not supported"); + + // Test endLine < startLine + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 10, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow( + "endLine (5) must be greater than or equal to startLine (10)", + ); +}); + +test("readFileRangeImpl handles normal ranges correctly", async () => { + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); + const { getUriPathBasename } = await import("../../util/uri"); + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); + + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); + + const mockIde = { + readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"), + }; + + const mockExtras = { + ide: mockIde, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result = await readFileRangeImpl( + { + filepath: "src/test.py", + startLine: 2, + endLine: 4, + }, + mockExtras, + ); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + name: "test.txt", + description: "src/test.py (lines 2-4)", + content: "line2\nline3\nline4", + uri: { + type: "file", + value: "file:///test.txt", + }, + }); + + // Verify correct 0-based conversion + expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", { + start: { line: 1, character: 0 }, // 2 - 1 + end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1 + }); +}); diff --git a/core/tools/implementations/readFileRange.ts b/core/tools/implementations/readFileRange.ts new file mode 100644 index 000000000..c313f4bff --- /dev/null +++ b/core/tools/implementations/readFileRange.ts @@ -0,0 +1,68 @@ +import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { getUriPathBasename } from "../../util/uri"; + +import { ToolImpl } from "."; +import { getNumberArg, getStringArg } from "../parseArgs"; +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; + +export const readFileRangeImpl: ToolImpl = async (args, extras) => { + const filepath = getStringArg(args, "filepath"); + const startLine = getNumberArg(args, "startLine"); + const endLine = getNumberArg(args, "endLine"); + + // Validate that line numbers are positive integers + if (startLine < 1) { + throw new Error( + "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", + ); + } + if (endLine < 1) { + throw new Error( + "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", + ); + } + if (endLine < startLine) { + throw new Error( + `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, + ); + } + + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); + if (!firstUriMatch) { + throw new Error( + `File "${filepath}" does not exist. You might want to check the path and try again.`, + ); + } + + // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) + const content = await extras.ide.readRangeInFile(firstUriMatch, { + start: { + line: startLine - 1, // Convert from 1-based to 0-based + character: 0, + }, + end: { + line: endLine - 1, // Convert from 1-based to 0-based + character: Number.MAX_SAFE_INTEGER, // Read to end of line + }, + }); + + await throwIfFileExceedsHalfOfContext( + filepath, + content, + extras.config.selectedModelByRole.chat, + ); + + const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; + + return [ + { + name: getUriPathBasename(firstUriMatch), + description: rangeDescription, + content, + uri: { + type: "file", + value: firstUriMatch, + }, + }, + ]; +}; diff --git a/core/tools/implementations/readFileRange.vitest.ts b/core/tools/implementations/readFileRange.vitest.ts new file mode 100644 index 000000000..b8a172d1c --- /dev/null +++ b/core/tools/implementations/readFileRange.vitest.ts @@ -0,0 +1,60 @@ +import { expect, test } from "vitest"; +import { getNumberArg } from "../parseArgs"; + +test("readFileRange should validate positive line number arguments", () => { + // Test positive startLine validation + expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow(); + expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow(); + expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow(); + + // Test positive endLine validation + expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow(); + expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow(); + expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow(); + + // Test missing arguments + expect(() => getNumberArg({}, "startLine")).toThrow( + "Argument `startLine` is required (type number)", + ); + expect(() => getNumberArg({}, "endLine")).toThrow( + "Argument `endLine` is required (type number)", + ); + + // Test invalid arguments + expect(() => + getNumberArg({ startLine: "not-a-number" }, "startLine"), + ).toThrow("Argument `startLine` must be a valid number"); + expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow( + "Argument `endLine` must be a valid number", + ); +}); + +test("readFileRange should handle line number conversion", () => { + // Test that our parsing function converts correctly + expect(getNumberArg({ line: 1 }, "line")).toBe(1); + expect(getNumberArg({ line: "5" }, "line")).toBe(5); + expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor + expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor +}); + +test("readFileRange parses negative numbers (validation happens in implementation)", () => { + // The parseArgs function should parse negative numbers correctly + // but the implementation will reject them with helpful error messages + expect(getNumberArg({ line: -1 }, "line")).toBe(-1); + expect(getNumberArg({ line: -10 }, "line")).toBe(-10); + expect(getNumberArg({ line: "-5" }, "line")).toBe(-5); +}); + +test("readFileRange handles out-of-bounds ranges gracefully", () => { + // IDE implementations handle out-of-bounds gracefully: + // - VS Code: Uses array.slice() which handles out-of-bounds gracefully + // - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds + // Both return empty content or available content without throwing errors + + expect(() => { + const startLine = getNumberArg({ startLine: 1000 }, "startLine"); + const endLine = getNumberArg({ endLine: 2000 }, "endLine"); + expect(startLine).toBe(1000); + expect(endLine).toBe(2000); + }).not.toThrow(); +}); diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.vitest.ts similarity index 76% rename from core/tools/implementations/runTerminalCommand.test.ts rename to core/tools/implementations/runTerminalCommand.vitest.ts index e744ea4f1..659163eb8 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.vitest.ts @@ -1,4 +1,12 @@ -import { jest } from "@jest/globals"; +import { + describe, + it, + expect, + beforeEach, + afterEach, + afterAll, + vi, +} from "vitest"; import * as childProcess from "node:child_process"; import * as fs from "node:fs"; import * as os from "node:os"; @@ -6,17 +14,18 @@ import * as path from "node:path"; import { IDE, ToolExtras } from "../.."; import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; import { runTerminalCommandImpl } from "./runTerminalCommand"; +import { runTerminalCommandTool } from "../definitions/runTerminalCommand"; // We're using real child processes, so ensure these aren't mocked -jest.unmock("node:child_process"); -jest.unmock("node:util"); +vi.unmock("node:child_process"); +vi.unmock("node:util"); describe("runTerminalCommandImpl", () => { // Setup mocks and spies - const mockGetIdeInfo = jest.fn(); - const mockGetWorkspaceDirs = jest.fn(); - const mockOnPartialOutput = jest.fn(); - const mockRunCommand = jest.fn(); + const mockGetIdeInfo = vi.fn(); + const mockGetWorkspaceDirs = vi.fn(); + const mockOnPartialOutput = vi.fn(); + const mockRunCommand = vi.fn(); // Use a simple approach to ensure background processes are terminated let testPid: number | null = null; @@ -27,7 +36,7 @@ describe("runTerminalCommandImpl", () => { ); beforeEach(() => { - jest.resetAllMocks(); + vi.resetAllMocks(); // Setup backgrounded processes handling - don't mock, just make sure it's empty // Get any processes that might be already tracked and clear them @@ -73,7 +82,7 @@ describe("runTerminalCommandImpl", () => { // Helper function to create a ToolExtras object const createMockExtras = ( overrides: Partial<{ - onPartialOutput?: jest.Mock; + onPartialOutput?: any; remoteName?: string; }> = {}, ): ToolExtras => { @@ -90,16 +99,16 @@ describe("runTerminalCommandImpl", () => { getWorkspaceDirs: mockGetWorkspaceDirs, runCommand: mockRunCommand, // Add stubs for other required IDE methods - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; // Create a base ToolExtras object with required properties @@ -147,7 +156,7 @@ describe("runTerminalCommandImpl", () => { "`; const args = { command, waitForCompletion: true }; - const mockOutputFn = jest.fn(); + const mockOutputFn = vi.fn(); const extras = createMockExtras({ onPartialOutput: mockOutputFn }); // Execute the command with streaming @@ -191,7 +200,7 @@ describe("runTerminalCommandImpl", () => { "`; const args = { command, waitForCompletion: false }; - const mockOutputFn = jest.fn(); + const mockOutputFn = vi.fn(); const extras = createMockExtras({ onPartialOutput: mockOutputFn }); const result = await runTerminalCommandImpl(args, extras); @@ -355,25 +364,25 @@ describe("runTerminalCommandImpl", () => { it("should handle missing workspace directory gracefully", async () => { // Mock IDE to return empty workspace directories - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest + getIdeInfo: vi .fn() .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, - runCommand: jest.fn(), - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + runCommand: vi.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; const extras = { @@ -402,7 +411,7 @@ describe("runTerminalCommandImpl", () => { it("should handle case where cwd fallbacks all fail", async () => { // Mock IDE to return empty workspace directories - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); // Save original environment variables and process.cwd const originalHome = process.env.HOME; @@ -413,27 +422,27 @@ describe("runTerminalCommandImpl", () => { // Mock all fallbacks to fail delete process.env.HOME; delete process.env.USERPROFILE; - process.cwd = jest.fn().mockImplementation(() => { + process.cwd = vi.fn().mockImplementation(() => { throw new Error("Current directory unavailable"); - }) as jest.MockedFunction<() => string>; + }) as any; // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest + getIdeInfo: vi .fn() .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, - runCommand: jest.fn(), - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + runCommand: vi.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; const extras = { @@ -472,3 +481,125 @@ describe("runTerminalCommandImpl", () => { } }); }); + +describe("runTerminalCommandTool.evaluateToolCallPolicy", () => { + it("should return base policy for safe commands like echo", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "echo hello world" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should respect disabled policy even for non-echo commands", () => { + const basePolicy = "disabled"; + const args = { command: "ls -la" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should respect disabled policy even for safe commands", () => { + const basePolicy = "disabled"; + const args = { command: "echo test" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should return base policy for non-echo commands", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "ls -la" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should return base policy for git commands", () => { + const basePolicy = "allowedWithPermission"; + const args = { command: "git status" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithPermission"); + }); + + it("should handle undefined command gracefully", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: undefined }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should handle null command gracefully", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: null }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should handle empty command string", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should disable dangerous commands like rm -rf /", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "rm -rf /" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should require permission for high-risk network commands", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "curl http://example.com" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithPermission"); + }); +}); diff --git a/core/tools/index.ts b/core/tools/index.ts index 0277da6a7..3a45ea295 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -4,6 +4,7 @@ import * as toolDefinitions from "./definitions"; // I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads. export const getBaseToolDefinitions = () => [ toolDefinitions.readFileTool, + toolDefinitions.createNewFileTool, toolDefinitions.runTerminalCommandTool, toolDefinitions.globSearchTool, @@ -33,6 +34,7 @@ export const getConfigDependentToolDefinitions = ( toolDefinitions.viewRepoMapTool, toolDefinitions.viewSubdirectoryTool, toolDefinitions.codebaseTool, + toolDefinitions.readFileRangeTool, ); } diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index a31267854..543e6ba53 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -40,6 +40,24 @@ export function getOptionalStringArg( return getStringArg(args, argName, allowEmpty); } +export function getNumberArg(args: any, argName: string): number { + if (!args || !(argName in args)) { + throw new Error(`Argument \`${argName}\` is required (type number)`); + } + const value = args[argName]; + if (typeof value === "string") { + const parsed = parseInt(value, 10); + if (isNaN(parsed)) { + throw new Error(`Argument \`${argName}\` must be a valid number`); + } + return parsed; + } + if (typeof value !== "number" || isNaN(value)) { + throw new Error(`Argument \`${argName}\` must be a valid number`); + } + return Math.floor(value); // Ensure integer for line numbers (supports negative numbers) +} + export function getBooleanArg(args: any, argName: string, required = false) { if (!args || !(argName in args)) { if (required) { diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts index b2cee9fc5..71bfc0cc5 100644 --- a/core/tools/parseArgs.vitest.ts +++ b/core/tools/parseArgs.vitest.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { ToolCallDelta } from ".."; import { getBooleanArg, + getNumberArg, getOptionalStringArg, getStringArg, safeParseToolCallArgs, @@ -246,3 +247,86 @@ describe("getBooleanArg", () => { ); }); }); + +describe("getNumberArg", () => { + it("should return number argument when valid", () => { + const args = { count: 42 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should parse string numbers", () => { + const args = { count: "42" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should floor decimal numbers", () => { + const args = { count: 42.7 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should parse and floor string decimal numbers", () => { + const args = { count: "42.7" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should throw error when argument is missing", () => { + const args = { otherArg: 42 }; + expect(() => getNumberArg(args, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + }); + + it("should throw error when argument is not a number", () => { + const argsString = { count: "not-a-number" }; + const argsBoolean = { count: true }; + const argsObject = { count: {} }; + + expect(() => getNumberArg(argsString, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + expect(() => getNumberArg(argsBoolean, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + expect(() => getNumberArg(argsObject, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + }); + + it("should throw error when argument is NaN", () => { + const args = { count: NaN }; + expect(() => getNumberArg(args, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + }); + + it("should handle negative numbers", () => { + const args = { count: -5 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(-5); + }); + + it("should handle negative string numbers", () => { + const args = { count: "-10" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(-10); + }); + + it("should handle zero", () => { + const args = { count: 0 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(0); + }); + + it("should handle null or undefined args", () => { + expect(() => getNumberArg(null, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + expect(() => getNumberArg(undefined, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + }); +}); diff --git a/docs/docs.json b/docs/docs.json index 8e06477f3..fa9e1604d 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -234,6 +234,7 @@ "guides/continuous-ai", "guides/plan-mode-guide", "guides/ollama-guide", + "guides/instinct", "guides/running-continue-without-internet", "guides/custom-code-rag", "guides/how-to-self-host-a-model" 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/features/autocomplete/next-edit.mdx b/docs/features/autocomplete/next-edit.mdx index edeb77463..9deb0c3af 100644 --- a/docs/features/autocomplete/next-edit.mdx +++ b/docs/features/autocomplete/next-edit.mdx @@ -4,7 +4,8 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your --- - Next Edit is currently an experimental feature. It requires [Mercury Coder + Next Edit is currently an experimental feature. It requires + [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in your Continue autocomplete settings and is not yet available for JetBrains use. @@ -71,18 +72,18 @@ Next Edit activates automatically when: Next Edit requires: -- Compatible AI models (Mercury Coder) +- Compatible AI models (Mercury Coder or Instinct) - Continue development team access - VS Code (JetBrains support coming soon) - **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview) - To use Next Edit, you must have the Mercury Coder model configured in your - Continue autocomplete model settings. This model is specifically designed for - next edit predictions. Once it's been loaded, you must reload VS Code to - activate it. + To use Next Edit, you must have the Instinct or Mercury Coder model configured + in your Continue autocomplete model settings. This model is specifically + designed for next edit predictions. Once it's been loaded, you must reload VS + Code to activate it. Next Edit Model Setup @@ -117,6 +118,7 @@ Next Edit requires: Next Edit requires AI models specifically trained for code prediction: - **Mercury Coder**: Primary model optimized for next edit prediction +- **Instinct**: The leading open Next Edit model, trained by Continue ### Automatic Detection diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx index 055055360..a79805a34 100644 --- a/docs/guides/codebase-documentation-awareness.mdx +++ b/docs/guides/codebase-documentation-awareness.mdx @@ -84,7 +84,6 @@ You can use the `gh` CLI to: #### DeepWiki MCP [DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository. -``` Once configured, your agent can explore repositories like: - "Explore the React repository structure" @@ -180,4 +179,4 @@ The new approach provides better integration with Continue's Agent features and - Learn more about [MCP servers](/reference/continue-mcp) - Explore [rules configuration](/customize/deep-dives/rules) -- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains \ No newline at end of file +- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains diff --git a/docs/guides/instinct.mdx b/docs/guides/instinct.mdx new file mode 100644 index 000000000..19f9bf7a1 --- /dev/null +++ b/docs/guides/instinct.mdx @@ -0,0 +1,39 @@ +--- +title: "Using Instinct with Ollama in Continue" +description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama" +--- + + + Instinct is a 7 billion parameter model. You should expect slow responses if + running on a laptop. To learn how to inference Instinct on a GPU, see our + [HuggingFace model card](https://huggingface.co/continuedev/instinct). + + +We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev). + + + + + +### 1. Install Ollama + +If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx). + +### 2. Download Instinct + +```bash +ollama run nate/instinct +``` + +### 3. Update your `config.yaml` + +Open your `config.yaml` and add Instinct to the models section: + +```yaml +# ... rest of config.yaml ... + +models: + - uses: continuedev/instinct +``` + +Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct. diff --git a/docs/images/features/autocomplete/images/instinct-autocomplete.png b/docs/images/features/autocomplete/images/instinct-autocomplete.png new file mode 100644 index 000000000..3da34143d Binary files /dev/null and b/docs/images/features/autocomplete/images/instinct-autocomplete.png differ diff --git a/docs/images/instinct.gif b/docs/images/instinct.gif new file mode 100644 index 000000000..840a8f304 Binary files /dev/null and b/docs/images/instinct.gif differ 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/docs/snippets/ModelRecommendations.jsx b/docs/snippets/ModelRecommendations.jsx index a65e04371..76d930aba 100644 --- a/docs/snippets/ModelRecommendations.jsx +++ b/docs/snippets/ModelRecommendations.jsx @@ -117,11 +117,11 @@ export const ModelRecommendations = ({ role = "all" }) => { notes: "Open models are beginning to emerge for this model role", }, next_edit: { - open: ["N/A"], + open: ["[Instinct](https://hub.continue.dev/continuedev/instinct)"], closed: [ "[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)", ], - notes: "Closed models are significantly better than open models", + notes: "Closed models are better than open models", }, }; diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs index f5f20778c..5f4e18656 100644 --- a/extensions/cli/build.mjs +++ b/extensions/cli/build.mjs @@ -68,6 +68,10 @@ try { __dirname, "../../packages/llm-info/dist/index.js", ), + "@continuedev/terminal-security": resolve( + __dirname, + "../../packages/terminal-security/dist/index.js", + ), }, // Add banner to create require for CommonJS packages diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 6510bc717..8bb910c94 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -18,6 +18,7 @@ "@continuedev/config-yaml": "file:../../packages/config-yaml", "@continuedev/openai-adapters": "file:../../packages/openai-adapters", "@continuedev/sdk": "^0.0.13", + "@continuedev/terminal-security": "file:../../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.17.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0", @@ -123,6 +124,7 @@ "@continuedev/fetch": "file:../packages/fetch", "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -173,6 +175,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -207,6 +210,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", @@ -294,6 +298,21 @@ "vitest": "^3.2.4" } }, + "../../packages/terminal-security": { + "name": "@continuedev/terminal-security", + "version": "1.0.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "shell-quote": "^1.8.1" + }, + "devDependencies": { + "@types/node": "^20.11.19", + "@types/shell-quote": "^1.7.5", + "typescript": "^5.5.2", + "vitest": "^1.6.0" + } + }, "node_modules/@alcalzone/ansi-tokenize": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.0.tgz", @@ -386,6 +405,10 @@ "openai": "^4.96.2" } }, + "node_modules/@continuedev/terminal-security": { + "resolved": "../../packages/terminal-security", + "link": true + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 1fefcd973..68594f379 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -15,7 +15,7 @@ "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:smoke": "node smoke-test.mjs", "build:tsc": "tsc -p tsconfig.build.json", - "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i", + "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../terminal-security && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i", "build:validate": "node validate-aliases.mjs", "build:bundle": "node build.mjs", "build": "npm run build:validate && npm run build:bundle", @@ -50,6 +50,7 @@ "@continuedev/config-yaml": "file:../../packages/config-yaml", "@continuedev/openai-adapters": "file:../../packages/openai-adapters", "@continuedev/sdk": "^0.0.13", + "@continuedev/terminal-security": "file:../../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.17.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0", diff --git a/extensions/cli/spec/ctrl-c-behavior.md b/extensions/cli/spec/ctrl-c-behavior.md new file mode 100644 index 000000000..9d11f26ab --- /dev/null +++ b/extensions/cli/spec/ctrl-c-behavior.md @@ -0,0 +1,32 @@ +# Ctrl+C Exit Behavior + +## Overview + +Ctrl+C operates on two levels: + +1. **Menus/Selectors**: Immediate cancellation and return to previous state +2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second + +## Two-Stage Exit (Main Application) + +### First Ctrl+C + +- Shows temporary status message "ctrl+c to exit" in bottom-left status bar +- Message automatically disappears after 1 second +- Clears any text in the input field (if focused) +- Does **not** exit the application + +### Second Ctrl+C (within 1 second) + +- Exits the application immediately +- Performs graceful shutdown + +### Second Ctrl+C (after 1 second) + +- Treated as a new "first Ctrl+C" +- Shows exit message again +- User must press Ctrl+C twice within 1 second window to actually exit + +## Menu/Selector Cancellation + +Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors. diff --git a/extensions/cli/spec/otlp-metrics.md b/extensions/cli/spec/otlp-metrics.md index 744709b10..f1398558f 100644 --- a/extensions/cli/spec/otlp-metrics.md +++ b/extensions/cli/spec/otlp-metrics.md @@ -51,7 +51,7 @@ All metrics and events share these standard attributes: ## Core Metrics -### ✅ `continue.cli.session.count` +### ✅ `continue_cli_session_count` **Type:** Counter **Unit:** `count` @@ -65,7 +65,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.lines_of_code.count` +### ✅ `continue_cli_lines_of_code_count` **Type:** Counter **Unit:** `count` @@ -80,7 +80,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.pull_request.count` +### ✅ `continue_cli_pull_request_count` **Type:** Counter **Unit:** `count` @@ -94,7 +94,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.commit.count` +### ✅ `continue_cli_commit_count` **Type:** Counter **Unit:** `count` @@ -108,7 +108,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.cost.usage` +### ✅ `continue_cli_cost_usage` **Type:** Counter **Unit:** `USD` @@ -123,7 +123,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.token.usage` +### ✅ `continue_cli_token_usage` **Type:** Counter **Unit:** `tokens` @@ -139,7 +139,7 @@ All metrics and events share these standard attributes: --- -### ❌ `continue.cli.code_edit_tool.decision` +### ❌ `continue_cli_code_edit_tool_decision` **Type:** Counter **Unit:** `count` @@ -156,7 +156,7 @@ All metrics and events share these standard attributes: --- -### ✅ `continue.cli.active_time.total` +### ✅ `continue_cli_active_time_total` **Type:** Counter **Unit:** `s` @@ -172,7 +172,7 @@ All metrics and events share these standard attributes: ### ✅ User Prompt Event -**Event Name:** `continue.cli.user_prompt` +**Event Name:** `continue_cli_user_prompt` **Attributes:** @@ -188,7 +188,7 @@ All metrics and events share these standard attributes: ### ✅ Tool Result Event -**Event Name:** `continue.cli.tool_result` +**Event Name:** `continue_cli_tool_result` **Attributes:** @@ -209,7 +209,7 @@ All metrics and events share these standard attributes: ### ✅ API Request Event -**Event Name:** `continue.cli.api_request` +**Event Name:** `continue_cli_api_request` **Attributes:** @@ -232,7 +232,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Authentication Metrics -#### ✅ `continue.cli.auth.attempts` +#### ✅ `continue_cli_auth_attempts` **Type:** Counter **Unit:** `{attempt}` @@ -248,7 +248,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### MCP Integration Metrics -#### ❌ `continue.cli.mcp.connections` +#### ❌ `continue_cli_mcp_connections` **Type:** Gauge **Unit:** `{connection}` @@ -264,7 +264,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Performance Metrics -#### ❌ `continue.cli.startup.time` +#### ❌ `continue_cli_startup_time` **Type:** Histogram **Unit:** `ms` @@ -278,7 +278,7 @@ These metrics are unique to Continue CLI and provide additional insights without **Implementation:** Track in `src/index.ts` and `src/commands/chat.ts` -#### ✅ `continue.cli.response_time` +#### ✅ `continue_cli_response_time` **Type:** Histogram **Unit:** `ms` @@ -297,7 +297,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Migration from Claude Code Dashboards -The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`. +The core metrics (`session_count`, `lines_of_code_count`, `token_usage`, `cost_usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code_*` to `continue_cli_*`. ### Privacy Considerations @@ -337,6 +337,6 @@ All metrics should include these resource attributes: **Missing implementations:** -- `continue.cli.code_edit_tool.decision` - requires user confirmation UI -- `continue.cli.mcp.connections` - needs MCP service monitoring -- `continue.cli.startup.time` - needs startup time tracking +- `continue_cli_code_edit_tool_decision` - requires user confirmation UI +- `continue_cli_mcp_connections` - needs MCP service monitoring +- `continue_cli_startup_time` - needs startup time tracking 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/__tests__/CtrlCProcessHandling.test.ts b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts new file mode 100644 index 000000000..563efbbe9 --- /dev/null +++ b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; + +describe("Process SIGINT handling functions", () => { + it("exports the necessary functions for exit message handling", async () => { + const indexModule = await import("../index.js"); + + // Verify the functions exist + expect(typeof indexModule.shouldShowExitMessage).toBe("function"); + expect(typeof indexModule.setExitMessageCallback).toBe("function"); + expect(typeof indexModule.setTUIUnmount).toBe("function"); + }); +}); diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 91b5a6c78..784dbe09b 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -23,6 +23,35 @@ import { logger } from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; import { getVersion } from "./version.js"; +// TUI lifecycle and two-stage exit state management +let tuiUnmount: (() => void) | null; +let showExitMessage: boolean; +let exitMessageCallback: (() => void) | null; +let lastCtrlCTime: number; + +// Initialize state immediately to avoid temporal dead zone issues with exported functions +(function initializeTUIState() { + tuiUnmount = null; + showExitMessage = false; + exitMessageCallback = null; + lastCtrlCTime = 0; +})(); + +// Register TUI cleanup function for graceful shutdown +export function setTUIUnmount(unmount: () => void) { + tuiUnmount = unmount; +} + +// Register callback to trigger UI updates when exit message state changes +export function setExitMessageCallback(callback: () => void) { + exitMessageCallback = callback; +} + +// Check if "ctrl+c to exit" message should be displayed +export function shouldShowExitMessage(): boolean { + return showExitMessage; +} + // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { logger.error("Unhandled Rejection at:", { promise, reason }); @@ -265,10 +294,39 @@ try { process.exit(1); } -// Graceful shutdown - flush Sentry data +// Graceful shutdown with two-stage Ctrl+C exit + +// Remove all existing SIGINT listeners first +process.removeAllListeners("SIGINT"); + process.on("SIGINT", async () => { - await sentryService.flush(); - process.exit(0); + const now = Date.now(); + const timeSinceLastCtrlC = now - lastCtrlCTime; + + if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) { + // Second Ctrl+C within 1 second - exit + showExitMessage = false; + if (tuiUnmount) { + tuiUnmount(); + } + await sentryService.flush(); + process.exit(0); + } else { + // First Ctrl+C or too much time elapsed - show exit message + lastCtrlCTime = now; + showExitMessage = true; + if (exitMessageCallback) { + exitMessageCallback(); + } + + // Hide message after 1 second + setTimeout(() => { + showExitMessage = false; + if (exitMessageCallback) { + exitMessageCallback(); + } + }, 1000); + } }); process.on("SIGTERM", async () => { diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts index c860a6454..b28034b40 100644 --- a/extensions/cli/src/permissions/permissionChecker.test.ts +++ b/extensions/cli/src/permissions/permissionChecker.test.ts @@ -1,3 +1,7 @@ +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; + +import * as toolsModule from "../tools/index.js"; + import { checkToolPermission, filterExcludedTools, @@ -593,4 +597,373 @@ describe("Permission Checker", () => { expect(filtered).toEqual(tools); }); }); + + describe("Hybrid Permission Model with Dynamic Evaluation", () => { + // Mock the runTerminalCommand tool with evaluateToolCallPolicy + const mockBashTool = { + name: "Bash", + displayName: "Bash", + description: "Execute bash commands", + parameters: {}, + isBuiltIn: true, + evaluateToolCallPolicy: vi.fn(), + run: vi.fn(), + }; + + beforeEach(() => { + vi.clearAllMocks(); + // Mock getAllBuiltinTools to return our test tool + vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([ + mockBashTool, + ]); + + // Reset mock between tests + mockBashTool.evaluateToolCallPolicy.mockClear(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("User has Bash in 'allow' mode", () => { + const permissions: ToolPermissions = { + policies: [ + { tool: "Bash", permission: "allow" }, + { tool: "*", permission: "ask" }, + ], + }; + + it("should allow safe commands (echo hello)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithoutPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "echo hello" } }, + permissions, + ); + + expect(result.permission).toBe("allow"); // User preference wins + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithoutPermission", // converted from "allow" + { command: "echo hello" }, + ); + }); + + it("should allow risky commands based on user preference (curl)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "curl https://example.com" } }, + permissions, + ); + + expect(result.permission).toBe("allow"); // User preference wins over "ask" + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithoutPermission", // converted from "allow" + { command: "curl https://example.com" }, + ); + }); + + it("should block dangerous commands despite user preference (eval)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "eval 'echo safe'" } }, + permissions, + ); + + expect(result.permission).toBe("exclude"); // Security wins + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithoutPermission", // converted from "allow" + { command: "eval 'echo safe'" }, + ); + }); + + it("should block sudo commands despite user preference", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "sudo rm -rf /" } }, + permissions, + ); + + expect(result.permission).toBe("exclude"); // Security wins + }); + }); + + describe("User has Bash in 'ask' mode (default)", () => { + const permissions: ToolPermissions = { + policies: [ + { tool: "Bash", permission: "ask" }, + { tool: "*", permission: "ask" }, + ], + }; + + it("should ask for safe commands based on user preference (echo)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithoutPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "echo hello" } }, + permissions, + ); + + expect(result.permission).toBe("ask"); // User preference wins + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithPermission", // converted from "ask" + { command: "echo hello" }, + ); + }); + + it("should ask for risky commands (curl)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "curl https://example.com" } }, + permissions, + ); + + expect(result.permission).toBe("ask"); // Both agree on "ask" + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithPermission", // converted from "ask" + { command: "curl https://example.com" }, + ); + }); + + it("should block dangerous commands (eval)", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "eval 'echo safe'" } }, + permissions, + ); + + expect(result.permission).toBe("exclude"); // Security wins + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithPermission", // converted from "ask" + { command: "eval 'echo safe'" }, + ); + }); + + it("should block rm -rf commands", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "rm -rf /tmp/important" } }, + permissions, + ); + + expect(result.permission).toBe("exclude"); // Security wins + }); + }); + + describe("User has Bash in 'exclude' mode", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "Bash", permission: "exclude" }], + }; + + it("should always exclude regardless of dynamic evaluation", () => { + // Even if dynamic evaluation would allow it + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithoutPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "echo hello" } }, + permissions, + ); + + expect(result.permission).toBe("exclude"); // User excluded the tool entirely + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "disabled", // converted from "exclude" + { command: "echo hello" }, + ); + }); + }); + + describe("Comprehensive command testing", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "Bash", permission: "allow" }], + }; + + const testCases = [ + // Safe commands + { + command: "ls", + dynamicResult: "allowedWithoutPermission", + expected: "allow", + }, + { + command: "pwd", + dynamicResult: "allowedWithoutPermission", + expected: "allow", + }, + { + command: "date", + dynamicResult: "allowedWithoutPermission", + expected: "allow", + }, + { + command: "echo test", + dynamicResult: "allowedWithoutPermission", + expected: "allow", + }, + { + command: "git status", + dynamicResult: "allowedWithoutPermission", + expected: "allow", + }, + + // Risky commands (user preference wins when not disabled) + { + command: "npm install pkg", + dynamicResult: "allowedWithPermission", + expected: "allow", + }, + { + command: "rm file.txt", + dynamicResult: "allowedWithPermission", + expected: "allow", + }, + { + command: "curl https://api.example.com", + dynamicResult: "allowedWithPermission", + expected: "allow", + }, + { + command: "wget https://example.com/file", + dynamicResult: "allowedWithPermission", + expected: "allow", + }, + + // Dangerous commands (always blocked) + { + command: "sudo rm -rf /", + dynamicResult: "disabled", + expected: "exclude", + }, + { + command: "exec bash", + dynamicResult: "disabled", + expected: "exclude", + }, + { + command: "eval 'malicious code'", + dynamicResult: "disabled", + expected: "exclude", + }, + { command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" }, + ]; + + testCases.forEach(({ command, dynamicResult, expected }) => { + it(`should handle '${command}' correctly`, () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult); + + const result = checkToolPermission( + { name: "Bash", arguments: { command } }, + permissions, + ); + + expect(result.permission).toBe(expected); + }); + }); + }); + + describe("Edge cases", () => { + it("should handle tools without dynamic evaluation", () => { + // Mock a Read tool without evaluateToolCallPolicy + const mockReadTool = { + name: "Read", + displayName: "Read", + description: "Read files", + parameters: {}, + isBuiltIn: true, + run: vi.fn(), + // No evaluateToolCallPolicy + }; + vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([ + mockReadTool, + mockBashTool, + ]); + + const permissions: ToolPermissions = { + policies: [{ tool: "Read", permission: "allow" }], + }; + + const result = checkToolPermission( + { name: "Read", arguments: { path: "/tmp/file.txt" } }, + permissions, + ); + + expect(result.permission).toBe("allow"); + expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled(); + }); + + it("should use default 'ask' when no policy matches", () => { + const permissions: ToolPermissions = { + policies: [], + }; + + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithPermission", + ); + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "echo test" } }, + permissions, + ); + + expect(result.permission).toBe("ask"); // Default fallback, user preference wins + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithPermission", // converted from default "ask" + { command: "echo test" }, + ); + }); + + it("should handle null/undefined arguments gracefully", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithPermission", + ); + + const permissions: ToolPermissions = { + policies: [{ tool: "Bash", permission: "allow" }], + }; + + const result = checkToolPermission( + { name: "Bash", arguments: {} }, + permissions, + ); + + expect(result.permission).toBe("allow"); + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( + "allowedWithoutPermission", + {}, + ); + }); + + it("should maintain matched policy information", () => { + mockBashTool.evaluateToolCallPolicy.mockReturnValue( + "allowedWithoutPermission", + ); + + const policy = { tool: "Bash", permission: "allow" as const }; + const permissions: ToolPermissions = { + policies: [policy], + }; + + const result = checkToolPermission( + { name: "Bash", arguments: { command: "ls" } }, + permissions, + ); + + expect(result.matchedPolicy).toBe(policy); + }); + }); + }); }); diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 9b2f5d557..55a4fbfab 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,10 +1,14 @@ +import type { ToolPolicy } from "@continuedev/terminal-security"; + import { getServiceSync } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/types.js"; import { SERVICE_NAMES } from "../services/types.js"; +import { getAllBuiltinTools } from "../tools/index.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, + PermissionPolicy, ToolCallRequest, ToolPermissions, } from "./types.js"; @@ -103,6 +107,24 @@ export function matchesArguments( return true; } +/** + * Converts CLI's PermissionPolicy to core's ToolPolicy + */ +function permissionPolicyToToolPolicy( + permission: PermissionPolicy, +): ToolPolicy { + switch (permission) { + case "allow": + return "allowedWithoutPermission"; + case "ask": + return "allowedWithPermission"; + case "exclude": + return "disabled"; + default: + return "allowedWithPermission"; + } +} + /** * Evaluates a tool call request against a set of permission policies. * Returns the permission for the first matching policy. @@ -129,21 +151,54 @@ export function checkToolPermission( } } + // First, get the base permission from static policies + let basePermission: PermissionPolicy = "ask"; + let matchedPolicy = undefined; + for (const policy of policies) { if ( matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) && matchesArguments(toolCall.arguments, policy.argumentMatches) ) { - return { - permission: policy.permission, - matchedPolicy: policy, - }; + basePermission = policy.permission; + matchedPolicy = policy; + break; } } - // Fallback to "ask" if no policy matches + // Check if tool has dynamic policy evaluation + const builtinTools = getAllBuiltinTools(); + const tool = builtinTools.find((t) => t.name === toolCall.name); + + if (tool?.evaluateToolCallPolicy) { + // Convert CLI permission to core policy + const basePolicy = permissionPolicyToToolPolicy(basePermission); + + // Evaluate the dynamic policy + const evaluatedPolicy = tool.evaluateToolCallPolicy( + basePolicy, + toolCall.arguments, + ); + + // If dynamic evaluation says disabled, that ALWAYS takes precedence + if (evaluatedPolicy === "disabled") { + return { + permission: "exclude", + matchedPolicy, + }; + } + + // Otherwise, user preference wins - return the original base permission + return { + permission: basePermission, + matchedPolicy, + }; + } + + // No dynamic evaluation, return static result return { - permission: "ask", + permission: basePermission, + matchedPolicy, }; } diff --git a/extensions/cli/src/services/MCPService.test.ts b/extensions/cli/src/services/MCPService.test.ts index 8fd14676e..f61be6946 100644 --- a/extensions/cli/src/services/MCPService.test.ts +++ b/extensions/cli/src/services/MCPService.test.ts @@ -1,5 +1,5 @@ import { AssistantConfig } from "@continuedev/sdk"; -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MCPService } from "./MCPService.js"; @@ -21,6 +21,14 @@ vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ StdioClientTransport: vi.fn(), })); +vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({ + SSEClientTransport: vi.fn(), +})); + +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ + StreamableHTTPClientTransport: vi.fn(), +})); + describe("MCPService", () => { let mcpService: MCPService; let mockAssistant: AssistantConfig; @@ -152,4 +160,56 @@ describe("MCPService", () => { await expect(mcpService.cleanup()).resolves.not.toThrow(); }); }); + + describe("transport types", () => { + it("should support SSE transport", async () => { + const sseAssistant: AssistantConfig = { + name: "sse-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "sse-server", + type: "sse", + url: "https://example.com/sse", + }, + ], + } as AssistantConfig; + + await expect(mcpService.initialize(sseAssistant)).resolves.not.toThrow(); + }); + + it("should support streamable-http transport", async () => { + const httpAssistant: AssistantConfig = { + name: "http-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "http-server", + type: "streamable-http", + url: "https://example.com/http", + }, + ], + } as AssistantConfig; + + await expect(mcpService.initialize(httpAssistant)).resolves.not.toThrow(); + }); + + it("should default to stdio transport when type is not specified", async () => { + const defaultAssistant: AssistantConfig = { + name: "default-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "default-server", + command: "npx", + args: ["-v"], + }, + ], + } as AssistantConfig; + + await expect( + mcpService.initialize(defaultAssistant), + ).resolves.not.toThrow(); + }); + }); }); diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index da56e0712..8088894e0 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -1,6 +1,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { getErrorString } from "../util/error.js"; import { logger } from "../util/logger.js"; @@ -9,9 +12,9 @@ import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { MCPConnectionInfo, + MCPServerConfig, MCPServiceState, SERVICE_NAMES, - MCPServerConfig, } from "./types.js"; interface ServerConnection extends MCPConnectionInfo { @@ -214,31 +217,12 @@ export class MCPService this.updateState(); try { - if (serverConfig.type && serverConfig.type !== "stdio") { - throw new Error( - `${serverConfig.type} MCP servers are not yet supported in the Continue CLI`, - ); - } - if (!serverConfig.command) { - throw new Error("MCP server command is not specified"); - } - const client = new Client( { name: "continue-cli-client", version: "1.0.0" }, { capabilities: {} }, ); - const env: Record = serverConfig.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - const transport = new StdioClientTransport({ - command: serverConfig.command, - args: serverConfig.args, - env, - stderr: "ignore", - }); + const transport = await this.constructTransport(serverConfig); logger.debug("Connecting to MCP server", { name: serverName, @@ -363,4 +347,68 @@ export class MCPService logger.debug("Shutting down MCPService"); await this.shutdownConnections(); } + + /** + * Construct transport based on server configuration + */ + private async constructTransport( + serverConfig: MCPServerConfig, + ): Promise { + const transportType = serverConfig.type || "stdio"; + + switch (transportType) { + case "stdio": + if (!serverConfig.command) { + throw new Error( + "MCP server command is not specified for stdio transport", + ); + } + + const env: Record = serverConfig.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } + + return new StdioClientTransport({ + command: serverConfig.command, + args: serverConfig.args || [], + env, + cwd: serverConfig.cwd, + stderr: "ignore", + }); + + case "sse": + if (!serverConfig.url) { + throw new Error("MCP server URL is not specified for SSE transport"); + } + return new SSEClientTransport(new URL(serverConfig.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...(serverConfig.requestOptions?.headers as + | Record + | undefined), + }, + }), + }, + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + + case "streamable-http": + if (!serverConfig.url) { + throw new Error( + "MCP server URL is not specified for streamable-http transport", + ); + } + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + + default: + throw new Error(`Unsupported transport type: ${transportType}`); + } + } } 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/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 69bace2ea..06e0a68c0 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -25,11 +25,17 @@ export function handlePermissionDenied( toolCall: PreprocessedToolCall, chatHistoryEntries: ChatCompletionToolMessageParam[], callbacks?: StreamCallbacks, + reason: "user" | "policy" = "user", ): void { - const deniedMessage = `Permission denied by user`; + const deniedMessage = + reason === "policy" + ? `Command blocked by security policy` + : `Permission denied by user`; + logger.info("Tool call denied", { name: toolCall.name, arguments: toolCall.arguments, + reason, }); chatHistoryEntries.push({ @@ -39,7 +45,7 @@ export function handlePermissionDenied( }); callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled"); - logger.debug("Tool call rejected - stopping stream"); + logger.debug(`Tool call rejected (${reason}) - stopping stream`); } // Helper function to handle headless mode permission @@ -114,22 +120,25 @@ export async function checkToolPermissionApproval( toolCall: PreprocessedToolCall, callbacks?: StreamCallbacks, isHeadless?: boolean, -): Promise { +): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> { const permissionCheck = checkToolPermission(toolCall); if (permissionCheck.permission === "allow") { - return true; + return { approved: true }; } else if (permissionCheck.permission === "ask") { if (isHeadless) { handleHeadlessPermission(toolCall); } - return await requestUserPermission(toolCall, callbacks); + const userApproved = await requestUserPermission(toolCall, callbacks); + return userApproved + ? { approved: true } + : { approved: false, denialReason: "user" }; } else if (permissionCheck.permission === "exclude") { - // This shouldn't happen as excluded tools are filtered out earlier - return false; + // Tool blocked by security policy + return { approved: false, denialReason: "policy" }; } - return false; + return { approved: false, denialReason: "policy" }; } // Helper function to track first token time @@ -401,18 +410,25 @@ export async function executeStreamedToolCalls( // Notify tool start before permission check to display in UI fallbacks callbacks?.onToolStart?.(call.name, call.arguments); - const approved = await checkToolPermissionApproval( + // Check tool permissions using helper + const permissionResult = await checkToolPermissionApproval( call, callbacks, isHeadless, ); - if (!approved) { + if (!permissionResult.approved) { // Permission denied: record and mark rejection + const denialReason = permissionResult.denialReason || "user"; + const deniedMessage = + denialReason === "policy" + ? `Command blocked by security policy` + : `Permission denied by user`; + const deniedEntry: ChatCompletionToolMessageParam = { role: "tool", tool_call_id: call.id, - content: `Permission denied by user`, + content: deniedMessage, }; entriesByIndex.set(index, deniedEntry); callbacks?.onToolResult?.( diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts index beffc672a..70cf90860 100644 --- a/extensions/cli/src/telemetry/telemetryService.ts +++ b/extensions/cli/src/telemetry/telemetryService.ts @@ -37,6 +37,7 @@ class TelemetryService { private startTime = Date.now(); private activeStartTime: number | null = null; private totalActiveTime = 0; + private shutdownHandlersRegistered = false; // Metrics private sessionCounter: any = null; @@ -114,7 +115,7 @@ class TelemetryService { ), }), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", + process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", ), }), ); @@ -124,7 +125,7 @@ class TelemetryService { new PeriodicExportingMetricReader({ exporter: new ConsoleMetricExporter(), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", + process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", ), }), ); @@ -143,15 +144,38 @@ class TelemetryService { this.initializeMetrics(); - logger.debug("Telemetry service initialized", { + // Set up graceful shutdown handlers + this.setupShutdownHandlers(); + + logger.info("Telemetry service initialized", { sessionId: this.config.sessionId, exporters: metricsExporters, + exportInterval: process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", }); } catch (error) { logger.error("Failed to initialize telemetry", error); } } + /** + * Set up process handlers to ensure metrics are flushed on shutdown + */ + private setupShutdownHandlers() { + if (this.shutdownHandlersRegistered) return; + + const shutdownHandler = async () => { + logger.debug("Process shutdown detected, flushing telemetry..."); + await this.shutdown(); + }; + + // Handle graceful shutdown - use once() to avoid duplicate handlers + process.once("beforeExit", shutdownHandler); + process.once("SIGINT", shutdownHandler); + process.once("SIGTERM", shutdownHandler); + + this.shutdownHandlersRegistered = true; + } + private parseHeaders(headersStr: string): Record { const headers: Record = {}; if (!headersStr) return headers; @@ -171,7 +195,7 @@ class TelemetryService { // Core metrics (Claude Code compatible) this.sessionCounter = this.meter.createCounter( - "continue.cli.session.count", + "continue_cli_session_count", { description: "Count of CLI sessions started", unit: "count", @@ -179,7 +203,7 @@ class TelemetryService { ); this.linesOfCodeCounter = this.meter.createCounter( - "continue.cli.lines_of_code.count", + "continue_cli_lines_of_code_count", { description: "Count of lines of code modified", unit: "count", @@ -187,30 +211,30 @@ class TelemetryService { ); this.pullRequestCounter = this.meter.createCounter( - "continue.cli.pull_request.count", + "continue_cli_pull_request_count", { description: "Number of pull requests created", unit: "count", }, ); - this.commitCounter = this.meter.createCounter("continue.cli.commit.count", { + this.commitCounter = this.meter.createCounter("continue_cli_commit_count", { description: "Number of git commits created", unit: "count", }); - this.costCounter = this.meter.createCounter("continue.cli.cost.usage", { + this.costCounter = this.meter.createCounter("continue_cli_cost_usage", { description: "Cost of the Continue CLI session", unit: "USD", }); - this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", { + this.tokenCounter = this.meter.createCounter("continue_cli_token_usage", { description: "Number of tokens used", unit: "tokens", }); this.codeEditDecisionCounter = this.meter.createCounter( - "continue.cli.code_edit_tool.decision", + "continue_cli_code_edit_tool_decision", { description: "Count of code editing tool permission decisions", unit: "count", @@ -218,7 +242,7 @@ class TelemetryService { ); this.activeTimeCounter = this.meter.createCounter( - "continue.cli.active_time.total", + "continue_cli_active_time_total", { description: "Total active time in seconds", unit: "s", @@ -227,7 +251,7 @@ class TelemetryService { // Additional Continue CLI specific metrics this.authAttemptsCounter = this.meter.createCounter( - "continue.cli.auth.attempts", + "continue_cli_auth_attempts", { description: "Authentication attempts", unit: "{attempt}", @@ -235,7 +259,7 @@ class TelemetryService { ); this.mcpConnectionsGauge = this.meter.createObservableGauge( - "continue.cli.mcp.connections", + "continue_cli_mcp_connections", { description: "Active MCP connections", unit: "{connection}", @@ -243,7 +267,7 @@ class TelemetryService { ); this.startupTimeHistogram = this.meter.createHistogram( - "continue.cli.startup.time", + "continue_cli_startup_time", { description: "Time from CLI start to ready state", unit: "ms", @@ -251,7 +275,7 @@ class TelemetryService { ); this.responseTimeHistogram = this.meter.createHistogram( - "continue.cli.response_time", + "continue_cli_response_time", { description: "LLM response time metrics", unit: "ms", @@ -312,6 +336,7 @@ class TelemetryService { public recordSessionStart() { if (!this.isEnabled()) return; + logger.debug("Recording session start with telemetry"); this.sessionCounter.add(1, this.getStandardAttributes()); this.recordStartupTime(Date.now() - this.startTime); } @@ -542,9 +567,26 @@ class TelemetryService { return this.config.sessionId; } - public shutdown() { + /** + * Shutdown telemetry service and ensure all metrics are flushed + */ + public async shutdown(): Promise { this.stopActiveTime(); - return this.meterProvider?.shutdown(); + + if (this.meterProvider) { + try { + logger.debug("Flushing telemetry metrics before shutdown..."); + // Force flush any pending metrics before shutdown + await this.meterProvider.forceFlush(); + logger.debug("Telemetry metrics flushed successfully"); + + // Now shutdown the provider + await this.meterProvider.shutdown(); + logger.debug("Telemetry service shut down successfully"); + } catch (error) { + logger.error("Failed to shutdown telemetry service", error); + } + } } } diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 9aefceb9b..58d3939e5 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -1,5 +1,10 @@ import { spawn } from "child_process"; +import { + evaluateTerminalCommandSecurity, + type ToolPolicy, +} from "@continuedev/terminal-security"; + import { telemetryService } from "../telemetry/telemetryService.js"; import { isGitCommitCommand, @@ -39,6 +44,15 @@ The command will be executed from the current working directory: ${process.cwd() }, readonly: false, isBuiltIn: true, + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ): ToolPolicy => { + return evaluateTerminalCommandSecurity( + basePolicy, + parsedArgs.command as string, + ); + }, preprocess: async (args) => { const command = args.command; if (!command || typeof command !== "string") { diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index e70c96e7b..04c164ad4 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -1,3 +1,5 @@ +import type { ToolPolicy } from "@continuedev/terminal-security"; + export type ToolParameters = Record< string, { @@ -31,6 +33,10 @@ export interface Tool { run: (args: any) => Promise; readonly?: boolean; // Indicates if the tool is readonly isBuiltIn: boolean; + evaluateToolCallPolicy?: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ) => ToolPolicy; } export interface ToolCall { diff --git a/extensions/cli/src/ui/ConfigSelector.tsx b/extensions/cli/src/ui/ConfigSelector.tsx index f47a97b1b..8c8d2ae55 100644 --- a/extensions/cli/src/ui/ConfigSelector.tsx +++ b/extensions/cli/src/ui/ConfigSelector.tsx @@ -12,6 +12,7 @@ import { } from "../auth/workos.js"; import { getApiClient } from "../config.js"; import { env } from "../env.js"; +import { services } from "../services/index.js"; import { Selector, SelectorOption } from "./Selector.js"; @@ -118,8 +119,10 @@ const ConfigSelector: React.FC = ({ displaySuffix: " (opens web)", }); - // Determine current config by checking auth config + // Determine current config by checking both auth config and service state const assistantSlug = getAssistantSlug(authConfig); + const currentConfigState = services.config.getState(); + if (assistantSlug) { // Find the matching config by slug and organization const matchingConfig = options.find( @@ -129,8 +132,12 @@ const ConfigSelector: React.FC = ({ opt.organizationId === currentOrganizationId, ); currentId = matchingConfig?.id || null; - } else if (fs.existsSync(CONFIG_PATH)) { - // No assistant slug means local config is current + } else if ( + currentConfigState.configPath === CONFIG_PATH && + fs.existsSync(CONFIG_PATH) + ) { + // Only mark local config as current if it's actually the active config path in the service + // This ensures we don't show a green checkmark for first-time users just because the file exists currentId = "local"; } diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx index 5a4638e2e..0943d8015 100644 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx @@ -15,6 +15,7 @@ import { import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; import { useNavigation } from "./context/NavigationContext.js"; +import { defaultBoxStyles } from "./styles.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); @@ -130,6 +131,18 @@ const FreeTrialTransitionUI: React.FC = ({ const hasOrganizations = organizations && organizations.length > 0; useInput((input, key) => { + // Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit + if (key.escape) { + closeCurrentScreen(); + return; + } + + // Handle Ctrl+C with two-stage exit (delegates to main process) + if (key.ctrl && input === "c") { + process.kill(process.pid, "SIGINT"); + return; + } + if (currentStep === "choice") { handleChoiceInput({ input, @@ -215,39 +228,38 @@ const FreeTrialTransitionUI: React.FC = ({ }; if (currentStep === "choice") { + const options = [ + { num: 1, text: "💳 Sign up for models add-on (recommended)" }, + { num: 2, text: "🔑 Enter your Anthropic API key" }, + { num: 3, text: "⚙️ Switch to a different configuration" }, + ]; + + if (hasOrganizations) { + options.push({ + num: 4, + text: "🏢 Switch to organization configuration", + }); + } + return ( - + 🚀 Free trial limit reached! Choose how you'd like to continue: - - {selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on - (recommended) - - - {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API - key - - - {selectedOption === 3 ? "▶ " : " "}3. ⚙️ Switch to a different - configuration - - {hasOrganizations && ( - - {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization - configuration + {options.map((option) => ( + + {selectedOption === option.num ? "➤ " : " "} + {option.num}. {option.text} - )} + ))} - Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, + ↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, Enter to confirm @@ -256,12 +268,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "enterApiKey") { return ( - + Enter your Anthropic API key @@ -278,12 +285,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "processing") { return ( - + Processing... @@ -294,12 +296,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "success") { return ( - + Success! @@ -316,12 +313,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "error") { return ( - + Error diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index fb84a4c60..f9db017ef 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -3,11 +3,18 @@ import React, { useState } from "react"; import { quote } from "shell-quote"; import { useServices } from "../hooks/useService.js"; -import { MCPServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + MCPConnectionInfo, + MCPServerStatus, + MCPServiceState, + SERVICE_NAMES, +} from "../services/types.js"; import { logger } from "../util/logger.js"; +import { defaultBoxStyles } from "./styles.js"; + // Utility function to get status icon and color based on server connection -const getServerStatusDisplay = (conn: any) => { +const getServerStatusDisplay = (conn: MCPConnectionInfo) => { let icon = "⚪️"; // note, white circle causes extra blank line bug let color: "green" | "yellow" | "red" | "white" | "dim" = "white"; let statusText = conn.status; @@ -22,7 +29,7 @@ const getServerStatusDisplay = (conn: any) => { if (conn.warnings && conn.warnings.length > 0) { icon = "🟡"; color = "yellow"; - statusText = "connected (with warnings)"; + statusText = "connected (with warnings)" as MCPServerStatus; } else { icon = "🟢"; color = "green"; @@ -170,7 +177,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add prompts if any */} {serverInfo.prompts.length > 0 && ( - 📝 Prompts: {serverInfo.prompts.length} + 📝 Prompts: {serverInfo.prompts.length} {serverInfo.prompts.map((prompt, index) => ( • {prompt.name} @@ -182,7 +189,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add tools if any */} {serverInfo.tools.length > 0 && ( - 🔧 Tools: {serverInfo.tools.length} + 🔧 Tools: {serverInfo.tools.length} {serverInfo.tools.map((tool, index) => ( • {tool.name} @@ -210,13 +217,14 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const maxIndex = Math.max(0, items.length - 1); useInput(async (input, key) => { - if (isLoading) return; - - if (key.escape) { + // Always allow escape/Ctrl+C so users can cancel even when loading + if (key.escape || (key.ctrl && input === "c")) { handleBack(); return; } + if (isLoading) return; + if (key.upArrow) { setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1); return; @@ -302,7 +310,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const renderHeader = () => { return ( - + {menuState === "server-detail" && selectedServer ? `Server: ${selectedServer}` : "MCP Servers"} @@ -336,13 +344,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { }; return ( - + {renderHeader()} {message && ( @@ -369,9 +371,8 @@ export const MCPSelector: React.FC = ({ onCancel }) => { key={`${item.value}-${index}`} color={isSelected ? "blue" : "white"} bold={isSelected} - inverse={isSelected} > - {isSelected ? "> " : " "} + {isSelected ? "➤ " : " "} {item.label} ); @@ -381,7 +382,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { - Use ↑/↓ to navigate, Enter to select, Esc to go back + ↑/↓ to navigate, Enter to select, Esc to go back diff --git a/extensions/cli/src/ui/Selector.tsx b/extensions/cli/src/ui/Selector.tsx index 6d00660f0..3e01a37e2 100644 --- a/extensions/cli/src/ui/Selector.tsx +++ b/extensions/cli/src/ui/Selector.tsx @@ -1,20 +1,14 @@ import { Box, Text, useInput } from "ink"; import React, { ReactNode } from "react"; +import { defaultBoxStyles } from "./styles.js"; + export interface SelectorOption { id: string; name: string; displaySuffix?: string; } -const boxStyles: React.ComponentProps = { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - borderStyle: "round", - borderColor: "blue", -}; - interface SelectorProps { title: string; options: T[]; @@ -46,8 +40,20 @@ export function Selector({ onNavigate, renderOption, }: SelectorProps) { + // Handle input for loading and error states useInput((input, key) => { - if (key.escape) { + if (loading || error) { + if (key.escape || (key.ctrl && input === "c")) { + onCancel(); + return; + } + } + }); + + useInput((input, key) => { + if (loading || error) return; // Skip normal input handling during loading/error + + if (key.escape || (key.ctrl && input === "c")) { onCancel(); return; } @@ -70,7 +76,7 @@ export function Selector({ if (loading) { return ( - + {title} @@ -84,13 +90,13 @@ export function Selector({ if (error) { return ( - + Error {error} - Press Escape to cancel + Press Esc to cancel ); @@ -106,7 +112,7 @@ export function Selector({ color={isSelected ? "blue" : isCurrent ? "green" : "white"} bold={isSelected} > - {isSelected ? "→ " : " "} + {isSelected ? "➤ " : " "} {option.name} {option.displaySuffix || ""} @@ -119,7 +125,7 @@ export function Selector({ ); return ( - + {title} @@ -136,7 +142,7 @@ export function Selector({ - ↑/↓ to navigate, Enter to select, Escape to cancel + ↑/↓ to navigate, Enter to select, Esc to cancel diff --git a/extensions/cli/src/ui/ServiceDebugger.tsx b/extensions/cli/src/ui/ServiceDebugger.tsx index 1f121bd0a..e10786dc5 100644 --- a/extensions/cli/src/ui/ServiceDebugger.tsx +++ b/extensions/cli/src/ui/ServiceDebugger.tsx @@ -9,6 +9,8 @@ import { ModelServiceState, } from "../services/types.js"; +import { defaultBoxStyles } from "./styles.js"; + interface ServiceDebuggerProps { services: { auth?: AuthServiceState; @@ -60,13 +62,7 @@ const ServiceDebugger: React.FC = ({ }; return ( - + 🔧 Service Debug Info diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx index 670ebf01d..2cf4927a4 100644 --- a/extensions/cli/src/ui/SessionSelector.tsx +++ b/extensions/cli/src/ui/SessionSelector.tsx @@ -1,10 +1,11 @@ -import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns"; +import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns"; import { Box, Text, useInput } from "ink"; import React, { useMemo, useState } from "react"; import { SessionMetadata } from "../session.js"; import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { defaultBoxStyles } from "./styles.js"; interface SessionSelectorProps { sessions: SessionMetadata[]; @@ -70,33 +71,31 @@ export function SessionSelector({ if (sessions.length === 0) { return ( - + No previous sessions found. Start a new conversation with: cn - Press ESC or Ctrl+D to exit + Press Esc to exit ); } return ( - + Recent Sessions - - Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit - + ↑/↓ to navigate, Enter to select, Esc to exit {displaySessions.map((session, index) => { const isSelected = index === selectedIndex; - const indicator = isSelected ? "► " : " "; - const color = isSelected ? "cyan" : "white"; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "blue" : "white"; return ( - + {indicator} {formatMessage(session.title)} diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index b4852933f..15d88bf29 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -73,7 +73,7 @@ const SlashCommandUI: React.FC = ({ {" "} {paddedCommandName} - {" "} + {" "} {command.description} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index b60013046..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; @@ -70,8 +141,21 @@ const UserInput: React.FC = ({ const [inputText, setInputText] = useState(""); const [cursorPosition, setCursorPosition] = useState(0); const [showSlashCommands, setShowSlashCommands] = useState(false); + + // Clear input function for Ctrl+C + const clearInput = useCallback(() => { + textBuffer.clear(); + setInputText(""); + 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); @@ -121,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 @@ -129,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, @@ -141,13 +240,8 @@ const UserInput: React.FC = ({ return; } - const afterSlash = beforeCursor.slice(1); - - // Check if we have whitespace in the command - if (afterSlash.includes(" ") || afterSlash.includes("\n")) { - setShowSlashCommands(false); - return; - } + // Get the complete slash command, not just the part before cursor + const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0]; // We're in a slash command context - check if it's a complete command const allCommands = getSlashCommands(); @@ -191,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("@"); @@ -229,6 +330,7 @@ const UserInput: React.FC = ({ setFileSearchFilter(afterAt); setSelectedFileIndex(0); setShowSlashCommands(false); + setShowBashMode(false); } } }; @@ -273,6 +375,7 @@ const UserInput: React.FC = ({ setInputText(newText); setCursorPosition(newCursorPos); setShowSlashCommands(false); + setShowBashMode(false); } }; @@ -432,6 +535,7 @@ const UserInput: React.FC = ({ setInputText(""); setCursorPosition(0); setShowSlashCommands(false); + setShowBashMode(false); } return true; } @@ -457,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(); @@ -478,16 +591,6 @@ const UserInput: React.FC = ({ return false; }; - // Clear input function - const clearInput = () => { - textBuffer.clear(); - setInputText(""); - setCursorPosition(0); - setShowSlashCommands(false); - setShowFileSearch(false); - inputHistory.resetNavigation(); - }; - // Handle text buffer updates for async operations like image pasting const handleTextBufferUpdate = () => { const newText = textBuffer.text; @@ -496,6 +599,7 @@ const UserInput: React.FC = ({ setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); }; @@ -592,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 ( <> @@ -682,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/__tests__/BottomStatusBarCtrlC.test.tsx b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx new file mode 100644 index 000000000..897228a96 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx @@ -0,0 +1,65 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { BottomStatusBar } from "../components/BottomStatusBar.js"; + +// Mock the index module functions +vi.mock("../../index.js", () => ({ + shouldShowExitMessage: vi.fn(() => false), + setExitMessageCallback: vi.fn(), +})); + +describe("BottomStatusBar Ctrl+C message", () => { + const defaultProps = { + currentMode: "normal" as const, + repoURLText: "github.com/user/repo", + isRemoteMode: false, + services: { model: { model: null } }, + navState: { currentScreen: "chat" }, + navigateTo: vi.fn(), + closeCurrentScreen: vi.fn(), + contextPercentage: undefined, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + // Reset mocks to default state + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("shows repo URL when not in exit message mode", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("github.com/user/repo"); + expect(lastFrame()).not.toContain("ctrl+c to exit"); + }); + + it("shows exit message when shouldShowExitMessage returns true", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(true); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("ctrl+c to exit"); + expect(lastFrame()).not.toContain("github.com/user/repo"); + }); + + it("registers exit message callback on mount", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + + render(); + + expect(indexModule.setExitMessageCallback).toHaveBeenCalledWith( + expect.any(Function), + ); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/CtrlC.test.tsx b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx new file mode 100644 index 000000000..f05154977 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx @@ -0,0 +1,115 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { ConfigSelector } from "../ConfigSelector.js"; +import { Selector } from "../Selector.js"; + +describe("Ctrl+C behavior", () => { + let mockOnCancel: ReturnType; + let mockOnSelect: ReturnType; + let mockProcess: any; + + beforeEach(() => { + mockOnCancel = vi.fn(); + mockOnSelect = vi.fn(); + + // Mock process.exit for testing + mockProcess = { + exit: vi.fn(), + kill: vi.fn(), + }; + vi.stubGlobal("process", mockProcess); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + }); + + describe("Selector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const options = [ + { id: "1", name: "Option 1" }, + { id: "2", name: "Option 2" }, + ]; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + expect(mockOnSelect).not.toHaveBeenCalled(); + }); + + it("calls onCancel when Ctrl+C is pressed during loading", () => { + const options: any[] = []; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C during loading + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + + it("calls onCancel when Ctrl+C is pressed during error state", () => { + const options: any[] = []; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C during error + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); + + describe("ConfigSelector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const { stdin } = render( + , + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx new file mode 100644 index 000000000..f40dd1414 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx @@ -0,0 +1,61 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { UserInput } from "../UserInput.js"; + +describe("Ctrl+C input clearing", () => { + let mockOnSubmit: ReturnType; + let mockProcessKill: any; + + beforeEach(() => { + mockOnSubmit = vi.fn(); + + // Mock process.kill using vi.spyOn + mockProcessKill = vi.spyOn(process, "kill").mockImplementation(() => { + return true; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.restoreAllMocks(); + }); + + it("sends SIGINT when Ctrl+C is pressed (input clearing tested implicitly)", () => { + const { stdin } = render( + , + ); + + // Type some text first + stdin.write("hello world"); + + // Simulate Ctrl+C using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should send SIGINT to process (which handles the two-stage exit) + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); + + it("sends SIGINT to main process for two-stage exit handling", () => { + const { stdin } = render( + , + ); + + // Simulate Ctrl+C using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should delegate to main process SIGINT handler + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx index 1fea1b3fb..dfb3b59ce 100644 --- a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +++ b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx @@ -37,7 +37,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { expect(frame).toContain("1. 💳 Sign up for models add-on"); expect(frame).toContain("2. 🔑 Enter your Anthropic API key"); expect(frame).toContain("3. ⚙️ Switch to a different configuration"); - expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select"); + expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select"); }); it("highlights first option by default", () => { @@ -46,10 +46,10 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { ); const frame = lastFrame(); - expect(frame).toContain("▶ 1. 💳 Sign up for models add-on"); - expect(frame).not.toContain("▶ 2. 🔑 Enter your Anthropic API key"); + expect(frame).toContain("➤ 1. 💳 Sign up for models add-on"); + expect(frame).not.toContain("➤ 2. 🔑 Enter your Anthropic API key"); expect(frame).not.toContain( - "▶ 3. ⚙️ Switch to a different configuration", + "➤ 3. ⚙️ Switch to a different configuration", ); }); @@ -85,7 +85,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { const frame = lastFrame(); expect(frame).toContain("Choose how you'd like to continue:"); expect(frame).toContain( - "Use ↑↓ arrows or 1/2/3 to select, Enter to confirm", + "↑/↓ to navigate or 1/2/3 to select, Enter to confirm", ); }); @@ -155,9 +155,9 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { line.includes("Switch to a different configuration"), ); - expect(modelsLine).toContain("▶"); - expect(apiKeyLine).not.toContain("▶"); - expect(configLine).not.toContain("▶"); + expect(modelsLine).toContain("➤"); + expect(apiKeyLine).not.toContain("➤"); + expect(configLine).not.toContain("➤"); }); }); diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index d31095f77..c780af456 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -1,6 +1,7 @@ import { Box, Text } from "ink"; -import React from "react"; +import React, { useEffect, useState } from "react"; +import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js"; import type { PermissionMode } from "../../permissions/types.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { FreeTrialStatus } from "../FreeTrialStatus.js"; @@ -31,51 +32,66 @@ export const BottomStatusBar: React.FC = ({ closeCurrentScreen, contextPercentage, hasImageInClipboard, -}) => ( - - - {currentMode === "normal" && ( - - {hasImageInClipboard ? ( - - Press Ctrl+V to paste image +}) => { + const [_refreshTrigger, setRefreshTrigger] = useState(0); + + useEffect(() => { + setExitMessageCallback(() => { + setRefreshTrigger((prev) => prev + 1); + }); + }, []); + + const showingExitMessage = shouldShowExitMessage(); + + return ( + + + {currentMode === "normal" && ( + + {hasImageInClipboard ? ( + + Press Ctrl+V to paste image + + ) : ( + + {showingExitMessage ? "ctrl+c to exit" : repoURLText} + + )} + + + )} + + {contextPercentage !== undefined && contextPercentage > 75 && ( + + + {" "} + •{" "} - ) : ( - - {repoURLText} - - )} - - - )} - - {contextPercentage !== undefined && contextPercentage > 75 && ( - - - {" "} - •{" "} - - - - )} + + + )} + + + {!isRemoteMode && services.model?.model && ( + { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if ( + !shouldShow && + navState.currentScreen === "free-trial" + ) { + closeCurrentScreen(); + } + }} + /> + )} + + + + - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if (!shouldShow && navState.currentScreen === "free-trial") { - closeCurrentScreen(); - } - }} - /> - )} - - - - - -); + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 1cb0c6d22..1af22c91a 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -140,6 +140,7 @@ export const ScreenContent: React.FC = ({ toolArgs={activePermissionRequest.toolArgs} requestId={activePermissionRequest.requestId} toolCallPreview={activePermissionRequest.toolCallPreview} + hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation} onResponse={handleToolPermissionResponse} /> ); diff --git a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx index 46abde7d2..f47ac23ec 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -4,6 +4,7 @@ import React, { useState } from "react"; import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; import { ToolCallPreview } from "../../tools/types.js"; +import { defaultBoxStyles } from "../styles.js"; import { ToolPreview } from "./ToolPreview.js"; @@ -21,6 +22,7 @@ interface ToolPermissionSelectorProps { toolArgs: any; requestId: string; toolCallPreview?: ToolCallPreview[]; + hasDynamicEvaluation?: boolean; onResponse: ( requestId: string, approved: boolean, @@ -29,36 +31,40 @@ interface ToolPermissionSelectorProps { ) => void; } -const PERMISSION_OPTIONS: PermissionOption[] = [ - { id: "approve", name: "Continue", color: "green", approved: true }, - { - id: "approve_policy", - name: "Continue + don't ask again", - color: "cyan", - approved: true, - createPolicy: true, - }, - { - id: "deny_stop", - name: "No, and tell Continue what to do differently", - color: "yellow", - approved: false, - stopStream: true, - }, -]; +const getPermissionOptions = (): PermissionOption[] => { + return [ + { id: "approve", name: "Continue", color: "green", approved: true }, + { + id: "approve_policy", + name: "Continue + don't ask again", + color: "cyan", + approved: true, + createPolicy: true, + }, + { + id: "deny_stop", + name: "No, and tell Continue what to do differently", + color: "yellow", + approved: false, + stopStream: true, + }, + ]; +}; export const ToolPermissionSelector: React.FC = ({ toolName, toolArgs, requestId, toolCallPreview, + hasDynamicEvaluation = false, onResponse, }) => { + const permissionOptions = getPermissionOptions(); const [selectedIndex, setSelectedIndex] = useState(0); useInput((input, key) => { if (key.return) { - const selectedOption = PERMISSION_OPTIONS[selectedIndex]; + const selectedOption = permissionOptions[selectedIndex]; onResponse( requestId, selectedOption.approved, @@ -80,8 +86,8 @@ export const ToolPermissionSelector: React.FC = ({ return; } - // Escape to reject with stop stream - if (key.escape) { + // Escape or Ctrl+C to reject with stop stream + if (key.escape || (key.ctrl && input === "c")) { onResponse(requestId, false, false, true); return; } @@ -90,7 +96,7 @@ export const ToolPermissionSelector: React.FC = ({ setSelectedIndex(Math.max(0, selectedIndex - 1)); } else if (key.downArrow) { setSelectedIndex( - Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1), + Math.min(permissionOptions.length - 1, selectedIndex + 1), ); } @@ -103,12 +109,7 @@ export const ToolPermissionSelector: React.FC = ({ }); return ( - + @@ -124,7 +125,15 @@ export const ToolPermissionSelector: React.FC = ({ Would you like to continue? - {PERMISSION_OPTIONS.map((option, index) => { + {hasDynamicEvaluation && ( + + + Note: Dangerous commands will be blocked regardless of your + preference. + + + )} + {permissionOptions.map((option, index) => { const isSelected = index === selectedIndex; let shortcut = ""; if (option.id === "approve") shortcut = "(tab)"; 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.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 213c0212f..3a31e458a 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,5 +1,6 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; +import { getAllBuiltinTools } from "src/tools/index.js"; import { logger } from "src/util/logger.js"; import { services } from "../../services/index.js"; @@ -201,11 +202,16 @@ export function createStreamCallbacks( requestId: string, toolCallPreview?: any[], ) => { + // Check if this tool has dynamic evaluation + const tool = getAllBuiltinTools().find((t: any) => t.name === toolName); + const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy; + setActivePermissionRequest({ toolName, toolArgs, requestId, toolCallPreview, + hasDynamicEvaluation, }); }, 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 c0d641b01..b8a48cd04 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -32,9 +32,14 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { onTextBufferUpdate, } = options; - // Handle Ctrl+C to clear input - if (key.ctrl && input === "c" && clearInput) { - clearInput(); + // Handle Ctrl+C with two-stage exit, Ctrl+D immediately exits + if (key.ctrl && input === "c") { + // Clear input box if clearInput function is provided + if (clearInput) { + clearInput(); + } + // Let the main process SIGINT handler handle Ctrl+C logic + process.kill(process.pid, "SIGINT"); return true; } @@ -99,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; } @@ -110,6 +116,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition, updateSlashCommandState, updateFileSearchState, + updateBashModeState, inputHistory, } = options; @@ -121,6 +128,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); } } diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index 3b4edece4..e9333155f 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -1,6 +1,7 @@ -import { render } from "ink"; +import { render, RenderOptions } from "ink"; import React from "react"; +import { setTUIUnmount } from "../index.js"; import { PermissionMode } from "../permissions/types.js"; import { initializeServices } from "../services/index.js"; import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; @@ -54,7 +55,9 @@ export async function startTUIChat( // Use static imports since we're always loading TUI when there's piped input // Start the TUI immediately - it will handle loading states - const renderOptions: any = {}; + const renderOptions: RenderOptions = { + exitOnCtrlC: false, // Disable Ink's default Ctrl+C handling so we can implement two-stage exit + }; if (customStdin) { renderOptions.stdin = customStdin; } @@ -73,11 +76,8 @@ export async function startTUIChat( renderOptions, ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); return { unmount }; } @@ -96,11 +96,8 @@ export async function startRemoteTUIChat( }), ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); return { unmount }; } diff --git a/extensions/cli/src/ui/styles.ts b/extensions/cli/src/ui/styles.ts new file mode 100644 index 000000000..4e767b0b8 --- /dev/null +++ b/extensions/cli/src/ui/styles.ts @@ -0,0 +1,17 @@ +import { Box } from "ink"; + +export const baseBoxStyles: React.ComponentProps = { + flexDirection: "column", + paddingX: 2, + paddingY: 1, + borderStyle: "round", +}; + +export const defaultBoxStyles = ( + borderColor: string, + overrides?: Partial>, +): React.ComponentProps => ({ + ...baseBoxStyles, + borderColor, + ...overrides, +}); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index 92f9bf970..21d83a536 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FimResult import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings @@ -41,8 +42,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { lastUuid = uuid() lastProject = project - // Check if Next Edit is supported - val isNextEditSupported = NextEditUtils.isNextEditSupported(project) + val isNextEditSupported = project.service().isNextEditEnabled() if (isNextEditSupported) { isUsingNextEdit = true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 0111c1173..f5a9a9000 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -142,6 +142,7 @@ class MessageTypes { "didChangeSelectedProfile", "didChangeSelectedOrg", "tools/call", + "tools/evaluatePolicy", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", 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/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index 616702466..274d8a87f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -14,6 +14,7 @@ import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.application import com.intellij.util.ui.JBUI +import com.intellij.util.ui.UIUtil import java.awt.* import javax.swing.JButton import javax.swing.JTextArea @@ -229,7 +230,7 @@ class VerticalDiffBlock( border = JBUI.Borders.empty() lineWrap = false wrapStyleWord = false - font = editor.colorsScheme.getFont(EditorFontType.PLAIN) + font = UIUtil.getFontWithFallback(editor.colorsScheme.getFont(EditorFontType.PLAIN)) } private fun getButtonsXYPositions(): Pair { 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/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt index 92dc3c2a3..a1d9b1f5d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt @@ -1,7 +1,9 @@ package com.github.continuedev.continueintellijextension.listeners import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.event.CaretEvent @@ -100,7 +102,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca // SelectionListener implementation override fun selectionChanged(event: SelectionEvent) { - if (isHandlingEvent || event.editor.isDisposed) return + if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return coroutineScope.launch { handleCursorMovement(event.editor, event.newRange.startOffset) @@ -109,7 +111,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca // CaretListener implementation override fun caretPositionChanged(event: CaretEvent) { - if (isHandlingEvent || event.editor.isDisposed) return + if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return coroutineScope.launch { handleCursorMovement(event.editor, event.caret?.offset ?: return@launch) @@ -168,6 +170,9 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca } } + private fun isNextEditEnabled() = + project.service().isNextEditEnabled() + fun dispose() { clearActiveHandler() coroutineScope.cancel() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt new file mode 100644 index 000000000..31e68e223 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt @@ -0,0 +1,115 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.auth.ContinueAuthService +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.text.endsWith + +/** + * This cache-like service is introduced to enable checking the Next Edit status in a non-blocking way (e.g., while + * moving the cursor/selection or triggering autocompletion). + * + * Checking this status is problematic on the EDT because it requires making a request to the binary (settings JSON) + * and decrypting the username from the PasswordSafe, which is considered a _slow operation_. + */ +@Service(Service.Level.PROJECT) +class NextEditStatusService(private val project: Project) { + + @Volatile + private var isEnabledLastValue: Boolean = false + private val updateInProgress = AtomicBoolean(false) + private val scope = CoroutineScope(Dispatchers.Default) + + fun isNextEditEnabled(): Boolean { + if (updateInProgress.compareAndSet(false, true)) + scope.launch { + try { + isEnabledLastValue = isNextEditEnabledAsync(project) + } catch (_: Exception) { + } finally { + updateInProgress.set(false) + } + } + return isEnabledLastValue + } + + // The code below is copied from NextEditUtils + // ------------------------------------------- + + private suspend fun isNextEditEnabledAsync(project: Project): Boolean { + return try { + // NOTE: Quick filter for non-continue users. + // Remove this once we have a FIM - Next Edit toggle UI. + val authService = project.service() + val sessionInfo = authService.loadControlPlaneSessionInfo() + val userEmail = sessionInfo?.account?.id + + if (userEmail == null || !userEmail.endsWith("@continue.dev")) { + return false + } + + val profileInfoService = project.service() + val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() + + // Use the existing utility function + val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull>() + + if (autocompleteModel != null) { + val modelName = autocompleteModel["model"] as? String ?: "" + val title = autocompleteModel["title"] as? String + val capabilities = autocompleteModel["capabilities"].castNestedOrNull>() + + isNextEditModel(modelName, title, capabilities) + } else { + false + } + } catch (e: Exception) { + println("Error checking Next Edit support: ${e.message}") + false + } + } + + private fun isNextEditModel( + model: String, + title: String?, + capabilities: Map? + ): Boolean { + // Check capabilities first - this takes precedence. + val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false + + // Check model name and title against known Next Edit models. + return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title) + } + + sealed class NextEditModelMatcher { + abstract fun matches(modelName: String?, title: String?): Boolean + + data object MercuryCoder : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("mercury-coder") == true || + title?.lowercase()?.contains("mercury coder") == true + } + + data object Instinct : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("instinct") == true || + title?.lowercase()?.contains("instinct") == true + } + + companion object { + private val allMatchers = listOf(MercuryCoder, Instinct) + + fun isSupported(modelName: String?, title: String?): Boolean { + return allMatchers.any { it.matches(modelName, title) } + } + } + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt index 4ad48cc6d..f61073fa3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -7,76 +7,8 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -sealed class NextEditModelMatcher { - abstract fun matches(modelName: String?, title: String?): Boolean - - data object MercuryCoder : NextEditModelMatcher() { - override fun matches(modelName: String?, title: String?): Boolean = - modelName?.lowercase()?.contains("mercury-coder") == true || - title?.lowercase()?.contains("mercury coder") == true - } - - data object Instinct : NextEditModelMatcher() { - override fun matches(modelName: String?, title: String?): Boolean = - modelName?.lowercase()?.contains("instinct") == true || - title?.lowercase()?.contains("instinct") == true - } - - companion object { - private val allMatchers = listOf(MercuryCoder, Instinct) - - fun isSupported(modelName: String?, title: String?): Boolean { - return allMatchers.any { it.matches(modelName, title) } - } - } -} - object NextEditUtils { - suspend fun isNextEditSupported(project: Project): Boolean { - return try { - // NOTE: Quick filter for non-continue users. - // Remove this once we have a FIM - Next Edit toggle UI. - val authService = project.service() - val sessionInfo = authService.loadControlPlaneSessionInfo() - val userEmail = sessionInfo?.account?.id - - if (userEmail == null || !userEmail.endsWith("@continue.dev")) { - return false - } - - val profileInfoService = project.service() - val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() - - // Use the existing utility function - val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull>() - - if (autocompleteModel != null) { - val modelName = autocompleteModel["model"] as? String ?: "" - val title = autocompleteModel["title"] as? String - val capabilities = autocompleteModel["capabilities"].castNestedOrNull>() - - isNextEditModel(modelName, title, capabilities) - } else { - false - } - } catch (e: Exception) { - println("Error checking Next Edit support: ${e.message}") - false - } - } - - private fun isNextEditModel( - model: String, - title: String?, - capabilities: Map? - ): Boolean { - // Check capabilities first - this takes precedence. - val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false - - // Check model name and title against known Next Edit models. - return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title) - } /** * Check if the diff is indeed a FIM (Fill-In-Middle). diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index daaecb123..ac5b2c7a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -8,6 +8,7 @@ import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerM import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory import com.github.continuedev.continueintellijextension.utils.uuid +import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.editor.EditorFactory @@ -20,7 +21,7 @@ import kotlinx.coroutines.cancel import kotlin.properties.Delegates @Service(Service.Level.PROJECT) -class ContinuePluginService(private val project: Project) : DumbAware { +class ContinuePluginService(private val project: Project) : Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var listener: (() -> Unit)? = null var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ -> @@ -57,7 +58,7 @@ class ContinuePluginService(private val project: Project) : DumbAware { } } - fun dispose() { + override fun dispose() { coroutineScope.cancel() coreMessenger?.coroutineScope?.let { it.cancel() diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index 1091c1a0a..38a6384c8 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -134,7 +134,7 @@ export class GUIActions { public static async toggleToolPolicy( view: WebView, toolName: string, - n: number, + desiredState: number | string, ) { const toolButton = await TestUtils.waitForSuccess(() => GUISelectors.getToolButton(view), @@ -145,9 +145,41 @@ export class GUIActions { ); await TestUtils.waitForTimeout(500); - // Enabled -> Excluded -> Ask first - for (let i = 0; i < n; i++) { - await TestUtils.waitForSuccess(() => toolPolicyButton.click()); + // Map old number format to state names for backward compatibility + // 0 = Automatic/Auto, 1 = Excluded/Off, 2 = Ask First/Ask + let targetStates: string[]; + if (typeof desiredState === "number") { + const stateMap = [ + ["Automatic", "Auto"], // 0 + ["Excluded", "Off"], // 1 + ["Ask First", "Ask"], // 2 + ]; + targetStates = stateMap[desiredState] || ["Ask First", "Ask"]; + } else { + targetStates = [desiredState]; + } + + // Keep clicking until we reach the desired state + let maxAttempts = 5; // Safety limit to prevent infinite loops + while (maxAttempts > 0) { + const currentText = await toolPolicyButton.getText(); + + // Check if we've reached any of the target states + if (targetStates.some((state) => currentText.includes(state))) { + break; + } + + // Click to move to next state + await toolPolicyButton.click(); + await TestUtils.waitForTimeout(200); // Small delay for UI update + + maxAttempts--; + } + + if (maxAttempts === 0) { + throw new Error( + `Failed to set tool policy to ${targetStates.join(" or ")} after 5 attempts`, + ); } } } diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index e6f8a3bee..d77ac69e1 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -4,7 +4,7 @@ import { InputBox, TextEditor, VSBrowser, - Workbench + Workbench, } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; @@ -86,76 +86,69 @@ export class GlobalActions { static async setNextEditEnabled(enabled: boolean) { const workbench = new Workbench(); - - await workbench.openCommandPrompt(); - process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = 'true'; - + await workbench.openCommandPrompt(); + process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = "true"; + // Initial wait and clear await TestUtils.waitForTimeout(1000); await GlobalActions.clearAllNotifications(); - + const statusBar = await workbench.getStatusBar(); - + // Robust element finding with text validation - const continueItem = await TestUtils.waitForSuccess( - async () => { - // Clear any new notifications - try { - await GlobalActions.clearAllNotifications(); - } catch (e) { - // Ignore + const continueItem = await TestUtils.waitForSuccess(async () => { + // Clear any new notifications + try { + await GlobalActions.clearAllNotifications(); + } catch (e) { + // Ignore + } + + const element = await statusBar.findElement( + By.xpath("//*[contains(text(), 'Continue')]"), + ); + + // Validate we can get text + const text = await element.getText(); + if (!text || text.trim() === "") { + // Try alternative methods + const textContent = await element.getAttribute("textContent"); + if (!textContent || textContent.trim() === "") { + throw new Error("Text not yet available"); } - - const element = await statusBar.findElement( - By.xpath("//*[contains(text(), 'Continue')]") - ); - - // Validate we can get text - const text = await element.getText(); - if (!text || text.trim() === '') { - // Try alternative methods - const textContent = await element.getAttribute('textContent'); - if (!textContent || textContent.trim() === '') { - throw new Error('Text not yet available'); - } - } - - return element; - }, - DEFAULT_TIMEOUT.MD - ); + } + + return element; + }, DEFAULT_TIMEOUT.MD); // Get text with retry - const text = await TestUtils.waitForSuccess( - async () => { - const itemText = await continueItem.getText(); - if (!itemText || itemText.trim() === '') { - // Fallback to textContent - const textContent = await continueItem.getAttribute('textContent'); - if (textContent && textContent.trim() !== '') { - return textContent; - } - throw new Error('Text content not yet available'); + const text = await TestUtils.waitForSuccess(async () => { + const itemText = await continueItem.getText(); + if (!itemText || itemText.trim() === "") { + // Fallback to textContent + const textContent = await continueItem.getAttribute("textContent"); + if (textContent && textContent.trim() !== "") { + return textContent; } - return itemText; - }, - DEFAULT_TIMEOUT.MD - ); - + throw new Error("Text content not yet available"); + } + return itemText; + }, DEFAULT_TIMEOUT.MD); + console.log("Final text:", text); - - const hasNE = text.includes('(NE)'); + + const hasNE = text.includes("(NE)"); console.log("hasNE:", hasNE); - + if (hasNE !== enabled) { - await workbench.executeCommand('Continue: Toggle Next Edit'); + await workbench.executeCommand("Continue: Toggle Next Edit"); // Clear any resulting notifications await TestUtils.waitForTimeout(500); await GlobalActions.clearAllNotifications(); } } - + static async disableNextEdit() { await this.setNextEditEnabled(false); } diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index 0760a607e..74128cd9d 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -7,7 +7,7 @@ import { WebDriver, WebElement, WebView, - until + until, } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c8cd7819a..d876c83d8 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -158,6 +158,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -192,6 +193,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8054468a9..ee1649b03 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.2", + "version": "1.3.3", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -183,7 +183,7 @@ { "command": "continue.focusEdit", "category": "Continue", - "title": "Edit Highlighted Code", + "title": "Add to Edit", "group": "Continue" }, { @@ -195,7 +195,7 @@ { "command": "continue.focusContinueInputWithoutClear", "category": "Continue", - "title": "Add Highlighted Code to Context", + "title": "Add to Chat", "group": "Continue" }, { @@ -547,31 +547,6 @@ "command": "continue.focusEdit", "group": "Continue", "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.writeCommentsForCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.writeDocstringForCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.fixCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.optimizeCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.fixGrammar", - "group": "Continue", - "when": "editorHasSelection && editorLangId == 'markdown' && !editorReadonly" } ], "explorer/context": [ diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 19be7545e..6f4275f67 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -3,7 +3,6 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; -import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion, isUnsupportedPlatform } from "../util/util"; import { GlobalContext } from "core/util/GlobalContext"; @@ -41,7 +40,6 @@ export async function activateExtension(context: vscode.ExtensionContext) { getContinueRcPath(); // Register commands and providers - registerQuickFixProvider(); setupInlineTips(context); const vscodeExtension = new VsCodeExtension(context); diff --git a/extensions/vscode/src/lang-server/codeActions.ts b/extensions/vscode/src/lang-server/codeActions.ts deleted file mode 100644 index f39d5b926..000000000 --- a/extensions/vscode/src/lang-server/codeActions.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { EXTENSION_NAME } from "core/control-plane/env"; -import * as vscode from "vscode"; - -class ContinueQuickFixProvider implements vscode.CodeActionProvider { - public static readonly providedCodeActionKinds = [ - vscode.CodeActionKind.QuickFix, - ]; - - provideCodeActions( - document: vscode.TextDocument, - range: vscode.Range | vscode.Selection, - context: vscode.CodeActionContext, - token: vscode.CancellationToken, - ): vscode.ProviderResult<(vscode.Command | vscode.CodeAction)[]> { - if (context.diagnostics.length === 0) { - return []; - } - - const diagnostic = context.diagnostics[0]; - - const quickFix = new vscode.CodeAction( - "Ask Continue", - vscode.CodeActionKind.QuickFix, - ); - - quickFix.isPreferred = false; - - const surroundingRange = new vscode.Range( - Math.max(0, range.start.line - 3), - 0, - Math.min(document.lineCount, range.end.line + 3), - 0, - ); - - quickFix.command = { - command: "continue.quickFix", - title: "Continue Quick Fix", - arguments: [surroundingRange, diagnostic.message], - }; - - return [quickFix]; - } -} - -export default function registerQuickFixProvider() { - const isDisabled = - !!vscode.workspace - .getConfiguration(EXTENSION_NAME) - .get("disableQuickFix") === true; - - if (isDisabled) { - return; - } - - // In your extension's activate function: - vscode.languages.registerCodeActionsProvider( - { language: "*" }, - new ContinueQuickFixProvider(), - { - providedCodeActionKinds: ContinueQuickFixProvider.providedCodeActionKinds, - }, - ); -} diff --git a/gui/package-lock.json b/gui/package-lock.json index 8e4bfb7d9..2b33dc8c7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -8,6 +8,7 @@ "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "file:../packages/config-yaml", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@panzoom/panzoom": "^4.6.0", @@ -123,6 +124,7 @@ "@continuedev/fetch": "file:../packages/fetch", "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -173,6 +175,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "shell-quote": "^1.8.3", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -207,6 +210,7 @@ "@types/pg": "^8.11.6", "@types/plist": "^3.0.5", "@types/request": "^2.48.12", + "@types/shell-quote": "^1.7.5", "@types/tar": "^6.1.13", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", @@ -266,6 +270,20 @@ "typescript": "^5.5.2" } }, + "../packages/terminal-security": { + "name": "@continuedev/terminal-security", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "shell-quote": "^1.8.1" + }, + "devDependencies": { + "@types/node": "^20.11.19", + "@types/shell-quote": "^1.7.5", + "typescript": "^5.5.2", + "vitest": "^1.6.0" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -672,6 +690,10 @@ "resolved": "../packages/config-yaml", "link": true }, + "node_modules/@continuedev/terminal-security": { + "resolved": "../packages/terminal-security", + "link": true + }, "node_modules/@emotion/is-prop-valid": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.3.1.tgz", diff --git a/gui/package.json b/gui/package.json index 6cb45030c..2b5e31648 100644 --- a/gui/package.json +++ b/gui/package.json @@ -17,6 +17,7 @@ }, "dependencies": { "@continuedev/config-yaml": "file:../packages/config-yaml", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@panzoom/panzoom": "^4.6.0", diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 621fbeead..6abdded6e 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -58,33 +58,31 @@ export default function AcceptRejectAllButtons({ className="flex flex-row items-center justify-evenly gap-3 px-3" data-testid="accept-reject-all-buttons" > - - + + + - - + + + ); } diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index e77bf5118..72a0522db 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -125,12 +125,12 @@ export function AssistantAndOrgListbox() { {session?.AUTH_TYPE !== AuthType.OnPrem && session?.account.id} - - Logout + + + ) : ( - refreshProfiles("Manual refresh from assistant list") - } + onClick={(e: React.MouseEvent) => { + e.stopPropagation(); + refreshProfiles("Manual refresh from assistant list"); + }} > ) ) : ( - <> + +
Errors
+ {JSON.stringify(errors, null, 2)} + + } + > - -
Errors
- {JSON.stringify(errors, null, 2)} -
- +
)} diff --git a/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx index 28831b15d..3868b5a3b 100644 --- a/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx +++ b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx @@ -139,7 +139,6 @@ export function GenerationScreen({ }; const showNameSpinner = isGenerating && !formData.name && !isManualMode; - const tooltipId = "rule-type-tooltip"; return (
@@ -181,14 +180,12 @@ export function GenerationScreen({ - - + + +