Changesets · Branches · Tags · Compare
| Changeset | cdcb5d4db5d55d086d6f24f58dadb2b6b08aa948d4d2828df08825eb237f0d46 |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-09-22 15:50 -07:00 |
| Committer | Dallin Romney <dallinromney@gmail.com> · 2025-09-22 15:50 -07:00 |
| Parents | cb8ecd666f0f, ba33beacce39 |
More than 300 files changed
| @@ -1,20 +0,0 @@ | ||
| 1 | -#!/bin/bash | |
| 2 | - | |
| 3 | -# Get file path from hook input | |
| 4 | -FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1) | |
| 5 | - | |
| 6 | -# Function to run lint and typecheck | |
| 7 | -run_checks() { | |
| 8 | - local dir=$1 | |
| 9 | - cd "$dir" | |
| 10 | - npm run lint >&2 && npm run tsc:check >&2 | |
| 11 | -} | |
| 12 | - | |
| 13 | -# Run checks based on file location | |
| 14 | -if [[ "$FILE_PATH" == *"/core/"* ]]; then | |
| 15 | - run_checks core | |
| 16 | -elif [[ "$FILE_PATH" == *"/gui/"* ]]; then | |
| 17 | - run_checks gui | |
| 18 | -elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then | |
| 19 | - run_checks extensions/vscode | |
| 20 | -fi | |
| No newline at the end of the file |
| @@ -1,15 +0,0 @@ | ||
| 1 | -{ | |
| 2 | - "hooks": { | |
| 3 | - "PostToolUse": [ | |
| 4 | - { | |
| 5 | - "matcher": "Write|Edit|MultiEdit", | |
| 6 | - "hooks": [ | |
| 7 | - { | |
| 8 | - "type": "command", | |
| 9 | - "command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh" | |
| 10 | - } | |
| 11 | - ] | |
| 12 | - } | |
| 13 | - ] | |
| 14 | - } | |
| 15 | -} |
| @@ -0,0 +1,5 @@ | ||
| 1 | +--- | |
| 2 | +globs: "**/*.{ts,tsx}" | |
| 3 | +--- | |
| 4 | + | |
| 5 | +Avoid using the `any` type wherever possible. Use unknown or find the correct type. The only acceptable place to use any is when typecasting for test mocks, and even then it's better to avoid and provide a proper mock. |
| @@ -0,0 +1,55 @@ | ||
| 1 | +name: "Check LLM Changes" | |
| 2 | +description: "Check if LLM-related files have changed and set environment variable to control API tests" | |
| 3 | +outputs: | |
| 4 | + llm_changed: | |
| 5 | + description: "Whether LLM-related files have changed" | |
| 6 | + value: ${{ steps.check-changes.outputs.llm_changed }} | |
| 7 | + ignore_api_tests: | |
| 8 | + description: "Whether to ignore API tests based on file changes and other conditions" | |
| 9 | + value: ${{ steps.check-changes.outputs.ignore_api_tests }} | |
| 10 | +inputs: | |
| 11 | + is_fork: | |
| 12 | + description: "Whether this is a fork PR" | |
| 13 | + required: false | |
| 14 | + default: "false" | |
| 15 | + is_dependabot: | |
| 16 | + description: "Whether this is a dependabot PR" | |
| 17 | + required: false | |
| 18 | + default: "false" | |
| 19 | + | |
| 20 | +runs: | |
| 21 | + using: "composite" | |
| 22 | + steps: | |
| 23 | + - name: Check if LLM-related files changed | |
| 24 | + id: check-changes | |
| 25 | + shell: bash | |
| 26 | + run: | | |
| 27 | + if [ "${{ github.event_name }}" = "push" ]; then | |
| 28 | + # For push events, compare against the previous commit | |
| 29 | + CHANGED_FILES=$(git diff --name-only HEAD~1...HEAD) | |
| 30 | + else | |
| 31 | + # For PR events, compare against the base branch | |
| 32 | + git fetch origin ${{ github.event.pull_request.base.ref }} | |
| 33 | + CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }}...HEAD) | |
| 34 | + fi | |
| 35 | + | |
| 36 | + echo "Changed files:" | |
| 37 | + echo "$CHANGED_FILES" | |
| 38 | + | |
| 39 | + # Check if any LLM-related files were changed | |
| 40 | + LLM_CHANGED=false | |
| 41 | + if echo "$CHANGED_FILES" | grep -E "(^core/llm/|^core/index\.ts|^core/package\.json|^core/jest\.config\.js|^packages/.*/(.*llm.*|.*openai.*|.*anthropic.*)|\.github/workflows/pr-checks\.yaml|\.github/actions/check-llm-changes/)" > /dev/null; then | |
| 42 | + LLM_CHANGED=true | |
| 43 | + fi | |
| 44 | + | |
| 45 | + echo "LLM files changed: $LLM_CHANGED" | |
| 46 | + echo "llm_changed=$LLM_CHANGED" >> $GITHUB_OUTPUT | |
| 47 | + | |
| 48 | + # Determine whether to ignore API tests | |
| 49 | + IGNORE_API_TESTS=false | |
| 50 | + if [ "${{ inputs.is_fork }}" = "true" ] || [ "${{ inputs.is_dependabot }}" = "true" ] || [ "$LLM_CHANGED" = "false" ]; then | |
| 51 | + IGNORE_API_TESTS=true | |
| 52 | + fi | |
| 53 | + | |
| 54 | + echo "Ignore API tests: $IGNORE_API_TESTS" | |
| 55 | + echo "ignore_api_tests=$IGNORE_API_TESTS" >> $GITHUB_OUTPUT |
| @@ -107,7 +107,7 @@ | ||
| 107 | 107 | cd binary |
| 108 | 108 | npm run build |
| 109 | 109 | |
| 110 | - - name: Start test IDE | |
| 110 | + - name: Run tests | |
| 111 | 111 | shell: bash |
| 112 | 112 | run: | |
| 113 | 113 | cd extensions/intellij |
| @@ -115,21 +115,7 @@ | ||
| 115 | 115 | Xvfb -ac :99 -screen 0 1920x1080x24 & |
| 116 | 116 | sleep 10 |
| 117 | 117 | mkdir -p build/reports |
| 118 | - ./gradlew runIdeForUiTests & | |
| 119 | - | |
| 120 | - - name: Wait for JB connection | |
| 121 | - uses: jtalk/url-health-check-action@v3 | |
| 122 | - with: | |
| 123 | - url: http://127.0.0.1:8082 | |
| 124 | - max-attempts: 15 | |
| 125 | - retry-delay: 30s | |
| 126 | - | |
| 127 | - - name: Run tests | |
| 128 | - shell: bash | |
| 129 | - run: | | |
| 130 | - cd extensions/intellij | |
| 131 | - export DISPLAY=:99.0 | |
| 132 | - ./gradlew test | |
| 118 | + ./gradlew test testIntegration | |
| 133 | 119 | |
| 134 | 120 | - name: Move video |
| 135 | 121 | if: ${{ failure() }} |
| @@ -1,25 +1,25 @@ | ||
| 1 | -name: 'Run VS Code E2E Test' | |
| 2 | -description: 'Run a single VS Code E2E test with all required setup' | |
| 1 | +name: "Run VS Code E2E Test" | |
| 2 | +description: "Run a single VS Code E2E test with all required setup" | |
| 3 | 3 | inputs: |
| 4 | 4 | test_file: |
| 5 | - description: 'E2E test file to run' | |
| 5 | + description: "E2E test file to run" | |
| 6 | 6 | required: true |
| 7 | 7 | command: |
| 8 | - description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)' | |
| 8 | + description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)" | |
| 9 | 9 | required: true |
| 10 | 10 | ssh_key: |
| 11 | - description: 'SSH private key for testing' | |
| 11 | + description: "SSH private key for testing" | |
| 12 | 12 | required: false |
| 13 | 13 | ssh_host: |
| 14 | - description: 'SSH host for testing' | |
| 14 | + description: "SSH host for testing" | |
| 15 | 15 | required: false |
| 16 | 16 | is_fork: |
| 17 | - description: 'Whether this is a fork (affects SSH tests)' | |
| 17 | + description: "Whether this is a fork (affects SSH tests)" | |
| 18 | 18 | required: false |
| 19 | - default: 'false' | |
| 19 | + default: "false" | |
| 20 | 20 | |
| 21 | 21 | runs: |
| 22 | - using: 'composite' | |
| 22 | + using: "composite" | |
| 23 | 23 | steps: |
| 24 | 24 | - uses: actions/setup-node@v4 |
| 25 | 25 | with: |
| @@ -58,6 +58,7 @@ | ||
| 58 | 58 | cd core |
| 59 | 59 | npm ci |
| 60 | 60 | cd ../extensions/vscode |
| 61 | + npm ci | |
| 61 | 62 | npm run e2e:ci:download |
| 62 | 63 | else |
| 63 | 64 | cd core |
| @@ -131,4 +132,4 @@ | ||
| 131 | 132 | uses: actions/upload-artifact@v4 |
| 132 | 133 | with: |
| 133 | 134 | name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} |
| 134 | - path: extensions/vscode/e2e.log | |
| No newline at the end of the file | ||
| 135 | + path: extensions/vscode/e2e.log |
| @@ -0,0 +1,170 @@ | ||
| 1 | +name: Auto Fix Failed Tests | |
| 2 | + | |
| 3 | +on: | |
| 4 | + workflow_run: | |
| 5 | + workflows: ["PR Checks", "CLI PR Checks"] | |
| 6 | + types: | |
| 7 | + - completed | |
| 8 | + | |
| 9 | +permissions: | |
| 10 | + contents: write | |
| 11 | + pull-requests: write | |
| 12 | + issues: write | |
| 13 | + actions: read | |
| 14 | + | |
| 15 | +jobs: | |
| 16 | + fix-failed-tests: | |
| 17 | + # Only run if the workflow failed | |
| 18 | + # DISABLED: Remove 'false && ' on the next line to enable auto-fixing | |
| 19 | + if: false && github.event.workflow_run.conclusion == 'failure' | |
| 20 | + runs-on: ubuntu-latest | |
| 21 | + | |
| 22 | + steps: | |
| 23 | + - name: Get workflow run details | |
| 24 | + id: workflow-details | |
| 25 | + uses: actions/github-script@v8 | |
| 26 | + with: | |
| 27 | + script: | | |
| 28 | + const workflowRun = context.payload.workflow_run; | |
| 29 | + const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({ | |
| 30 | + owner: context.repo.owner, | |
| 31 | + repo: context.repo.repo, | |
| 32 | + run_id: workflowRun.id | |
| 33 | + }); | |
| 34 | + | |
| 35 | + // Find all failed jobs since we're only monitoring specific test workflows | |
| 36 | + const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure'); | |
| 37 | + | |
| 38 | + if (failedJobs.length === 0) { | |
| 39 | + core.info('No failed jobs found'); | |
| 40 | + return null; | |
| 41 | + } | |
| 42 | + | |
| 43 | + core.setOutput('has_failed_tests', 'true'); | |
| 44 | + core.setOutput('workflow_name', workflowRun.name); | |
| 45 | + core.setOutput('workflow_run_id', workflowRun.id); | |
| 46 | + core.setOutput('head_branch', workflowRun.head_branch); | |
| 47 | + core.setOutput('head_sha', workflowRun.head_sha); | |
| 48 | + core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name))); | |
| 49 | + | |
| 50 | + return failedJobs; | |
| 51 | + | |
| 52 | + - name: Get job logs for failed tests | |
| 53 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 54 | + id: get-logs | |
| 55 | + uses: actions/github-script@v8 | |
| 56 | + with: | |
| 57 | + script: | | |
| 58 | + const workflowRunId = ${{ github.event.workflow_run.id }}; | |
| 59 | + const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({ | |
| 60 | + owner: context.repo.owner, | |
| 61 | + repo: context.repo.repo, | |
| 62 | + run_id: workflowRunId | |
| 63 | + }); | |
| 64 | + | |
| 65 | + let errorLogs = ''; | |
| 66 | + | |
| 67 | + for (const job of jobs.jobs) { | |
| 68 | + if (job.conclusion === 'failure') { | |
| 69 | + try { | |
| 70 | + const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({ | |
| 71 | + owner: context.repo.owner, | |
| 72 | + repo: context.repo.repo, | |
| 73 | + job_id: job.id | |
| 74 | + }); | |
| 75 | + | |
| 76 | + errorLogs += `\n\n=== Job: ${job.name} ===\n`; | |
| 77 | + errorLogs += logData; | |
| 78 | + } catch (error) { | |
| 79 | + core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`); | |
| 80 | + } | |
| 81 | + } | |
| 82 | + } | |
| 83 | + | |
| 84 | + // Store logs in environment file for next step | |
| 85 | + const fs = require('fs'); | |
| 86 | + fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs); | |
| 87 | + | |
| 88 | + core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false'); | |
| 89 | + | |
| 90 | + - name: Checkout repository | |
| 91 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 92 | + uses: actions/checkout@v5 | |
| 93 | + with: | |
| 94 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 95 | + fetch-depth: 0 | |
| 96 | + ref: ${{ steps.workflow-details.outputs.head_sha }} | |
| 97 | + | |
| 98 | + - name: Setup Node.js | |
| 99 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 100 | + uses: actions/setup-node@v5 | |
| 101 | + with: | |
| 102 | + node-version: "20" | |
| 103 | + | |
| 104 | + - name: Install Continue CLI globally | |
| 105 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 106 | + run: npm i -g @continuedev/cli | |
| 107 | + | |
| 108 | + - name: Start remote session to fix failed tests | |
| 109 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 110 | + id: remote-session | |
| 111 | + env: | |
| 112 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 113 | + run: | | |
| 114 | + # Create a detailed prompt for fixing the failed tests | |
| 115 | + cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF' | |
| 116 | + 🔧 **Auto Test Fix Request** | |
| 117 | + | |
| 118 | + The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}): | |
| 119 | + | |
| 120 | + **Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }} | |
| 121 | + **Branch:** ${{ steps.workflow-details.outputs.head_branch }} | |
| 122 | + **Commit:** ${{ steps.workflow-details.outputs.head_sha }} | |
| 123 | + | |
| 124 | + **Your Task:** | |
| 125 | + 1. Analyze the test failure logs and error messages | |
| 126 | + 2. Identify the root cause of the test failures | |
| 127 | + 3. Fix the failing tests by updating the test code or the underlying implementation | |
| 128 | + 4. Ensure all tests pass after your changes | |
| 129 | + 5. Commit your fixes with a descriptive message | |
| 130 | + | |
| 131 | + **Test Failure Context:** | |
| 132 | + Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes. | |
| 133 | + | |
| 134 | + Focus on: | |
| 135 | + - Understanding what the tests are trying to validate | |
| 136 | + - Identifying why they're failing (code changes, environment issues, test logic errors) | |
| 137 | + - Making minimal, targeted fixes that address the root cause | |
| 138 | + - Ensuring the fixes don't break other functionality | |
| 139 | + | |
| 140 | + Please start by examining the failing tests and their error messages, then proceed with the necessary fixes. | |
| 141 | + PROMPT_EOF | |
| 142 | + | |
| 143 | + echo "Starting Continue CLI remote session for test fixes..." | |
| 144 | + echo "Prompt content:" | |
| 145 | + cat /tmp/fix_tests_prompt.txt | |
| 146 | + | |
| 147 | + # Start remote session and capture JSON output | |
| 148 | + SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }}) | |
| 149 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 150 | + | |
| 151 | + # Extract URL from JSON output | |
| 152 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 153 | + | |
| 154 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 155 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 156 | + exit 1 | |
| 157 | + fi | |
| 158 | + | |
| 159 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 160 | + echo "✅ Started remote session: $SESSION_URL" | |
| 161 | + | |
| 162 | + - name: Log session details | |
| 163 | + if: steps.workflow-details.outputs.has_failed_tests == 'true' | |
| 164 | + run: | | |
| 165 | + echo "✅ Successfully started auto-fix session for failed tests" | |
| 166 | + echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}" | |
| 167 | + echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}" | |
| 168 | + echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}" | |
| 169 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 170 | + echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}" |
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} |
| 25 | 25 | |
| 26 | 26 | - name: Setup Node.js |
| 27 | - uses: actions/setup-node@v4 | |
| 27 | + uses: actions/setup-node@v5 | |
| 28 | 28 | with: |
| 29 | 29 | node-version: 20 |
| 30 | 30 | registry-url: "https://registry.npmjs.org" |
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | uses: actions/checkout@v5 |
| 26 | 26 | |
| 27 | 27 | - name: Setup Node.js |
| 28 | - uses: actions/setup-node@v4 | |
| 28 | + uses: actions/setup-node@v5 | |
| 29 | 29 | with: |
| 30 | 30 | node-version: 20 |
| 31 | 31 | cache: "npm" |
| @@ -59,6 +59,7 @@ | ||
| 59 | 59 | matrix: |
| 60 | 60 | os: [ubuntu-latest, windows-latest, macos-latest] |
| 61 | 61 | node-version: [18, 20, 22, 24] |
| 62 | + fail-fast: false | |
| 62 | 63 | runs-on: ${{ matrix.os }} |
| 63 | 64 | |
| 64 | 65 | steps: |
| @@ -66,7 +67,7 @@ | ||
| 66 | 67 | uses: actions/checkout@v5 |
| 67 | 68 | |
| 68 | 69 | - name: Setup Node.js ${{ matrix.node-version }} |
| 69 | - uses: actions/setup-node@v4 | |
| 70 | + uses: actions/setup-node@v5 | |
| 70 | 71 | with: |
| 71 | 72 | node-version: ${{ matrix.node-version }} |
| 72 | 73 |
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | |
| 42 | 42 | - name: Add PR title guidance comment |
| 43 | 43 | if: always() && steps.pr-title-check.outputs.valid == 'false' |
| 44 | - uses: actions/github-script@v7 | |
| 44 | + uses: actions/github-script@v8 | |
| 45 | 45 | with: |
| 46 | 46 | script: | |
| 47 | 47 | const { data: comments } = await github.rest.issues.listComments({ |
| @@ -104,7 +104,7 @@ | ||
| 104 | 104 | uses: actions/checkout@v5 |
| 105 | 105 | |
| 106 | 106 | - name: Setup Node.js |
| 107 | - uses: actions/setup-node@v4 | |
| 107 | + uses: actions/setup-node@v5 | |
| 108 | 108 | with: |
| 109 | 109 | node-version-file: ".nvmrc" |
| 110 | 110 | cache: "npm" |
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | timeout-minutes: 10 |
| 19 | 19 | steps: |
| 20 | 20 | - name: Run Detailed PR Review |
| 21 | - uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe | |
| 21 | + uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52 | |
| 22 | 22 | with: |
| 23 | 23 | continue-api-key: ${{ secrets.CONTINUE_API_KEY }} |
| 24 | 24 | continue-org: continuedev |
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | timeout-minutes: 10 |
| 19 | 19 | steps: |
| 20 | 20 | - name: Run Continue PR Review Action |
| 21 | - uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe | |
| 21 | + uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52 | |
| 22 | 22 | with: |
| 23 | 23 | continue-api-key: ${{ secrets.CONTINUE_API_KEY }} |
| 24 | 24 | continue-org: "continuedev" |
| @@ -152,7 +152,7 @@ | ||
| 152 | 152 | |
| 153 | 153 | # # Setup Node.js |
| 154 | 154 | - name: Use Node.js from .nvmrc |
| 155 | - uses: actions/setup-node@v4 | |
| 155 | + uses: actions/setup-node@v5 | |
| 156 | 156 | with: |
| 157 | 157 | node-version-file: ".nvmrc" |
| 158 | 158 | |
| @@ -370,7 +370,7 @@ | ||
| 370 | 370 | |
| 371 | 371 | # 2. Install npm dependencies |
| 372 | 372 | - name: Use Node.js from .nvmrc |
| 373 | - uses: actions/setup-node@v4 | |
| 373 | + uses: actions/setup-node@v5 | |
| 374 | 374 | with: |
| 375 | 375 | node-version-file: ".nvmrc" |
| 376 | 376 |
| @@ -44,7 +44,7 @@ | ||
| 44 | 44 | |
| 45 | 45 | - name: Determine and apply tier label |
| 46 | 46 | if: steps.check-author.outputs.should_label == 'true' |
| 47 | - uses: actions/github-script@v7 | |
| 47 | + uses: actions/github-script@v8 | |
| 48 | 48 | with: |
| 49 | 49 | script: | |
| 50 | 50 | const pr = context.payload.pull_request; |
| @@ -20,14 +20,30 @@ | ||
| 20 | 20 | - id: check |
| 21 | 21 | working-directory: . |
| 22 | 22 | run: | |
| 23 | - if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then | |
| 23 | + if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then | |
| 24 | 24 | echo "should_run=true" >> $GITHUB_OUTPUT |
| 25 | 25 | else |
| 26 | 26 | echo "should_run=false" >> $GITHUB_OUTPUT |
| 27 | 27 | fi |
| 28 | 28 | |
| 29 | + check-version: | |
| 30 | + runs-on: ubuntu-latest | |
| 31 | + steps: | |
| 32 | + - name: Checkout | |
| 33 | + uses: actions/checkout@v5 | |
| 34 | + with: | |
| 35 | + fetch-depth: 0 # This ensures all tags are fetched | |
| 36 | + | |
| 37 | + - name: Checkout tag | |
| 38 | + run: git checkout ${GITHUB_REF#refs/tags/} | |
| 39 | + | |
| 40 | + - name: Make sure version isn't odd | |
| 41 | + run: | | |
| 42 | + cd extensions/vscode | |
| 43 | + node scripts/versionCheck.js | |
| 44 | + | |
| 29 | 45 | build: |
| 30 | - needs: check_release_name | |
| 46 | + needs: [check_release_name, check-version] | |
| 31 | 47 | if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' |
| 32 | 48 | runs-on: ${{ matrix.os }} |
| 33 | 49 | strategy: |
| @@ -70,7 +86,7 @@ | ||
| 70 | 86 | with: |
| 71 | 87 | fetch-depth: 0 |
| 72 | 88 | |
| 73 | - - uses: actions/setup-node@v4 | |
| 89 | + - uses: actions/setup-node@v5 | |
| 74 | 90 | with: |
| 75 | 91 | node-version-file: ".nvmrc" |
| 76 | 92 | |
| @@ -88,22 +104,6 @@ | ||
| 88 | 104 | name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix |
| 89 | 105 | path: "extensions/vscode/*.vsix" |
| 90 | 106 | |
| 91 | - check-version: | |
| 92 | - runs-on: ubuntu-latest | |
| 93 | - steps: | |
| 94 | - - name: Checkout | |
| 95 | - uses: actions/checkout@v5 | |
| 96 | - with: | |
| 97 | - fetch-depth: 0 # This ensures all tags are fetched | |
| 98 | - | |
| 99 | - - name: Checkout tag | |
| 100 | - run: git checkout ${GITHUB_REF#refs/tags/} | |
| 101 | - | |
| 102 | - - name: Make sure version isn't odd | |
| 103 | - run: | | |
| 104 | - cd extensions/vscode | |
| 105 | - node scripts/versionCheck.js | |
| 106 | - | |
| 107 | 107 | release: |
| 108 | 108 | permissions: |
| 109 | 109 | contents: write |
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | runs-on: ubuntu-latest |
| 24 | 24 | steps: |
| 25 | 25 | - uses: actions/checkout@v5 |
| 26 | - - uses: actions/setup-node@v4 | |
| 26 | + - uses: actions/setup-node@v5 | |
| 27 | 27 | with: |
| 28 | 28 | node-version-file: ".nvmrc" |
| 29 | 29 | |
| @@ -44,6 +44,8 @@ | ||
| 44 | 44 | runs-on: ubuntu-latest |
| 45 | 45 | steps: |
| 46 | 46 | - uses: actions/checkout@v5 |
| 47 | + with: | |
| 48 | + fetch-depth: 0 # Needed for git diff to work | |
| 47 | 49 | - name: Setup packages |
| 48 | 50 | uses: ./.github/actions/setup-packages |
| 49 | 51 | - name: Setup core component |
| @@ -52,6 +54,13 @@ | ||
| 52 | 54 | component: core |
| 53 | 55 | include-root: true |
| 54 | 56 | |
| 57 | + - name: Check if LLM-related files changed | |
| 58 | + id: llm-changes | |
| 59 | + uses: ./.github/actions/check-llm-changes | |
| 60 | + with: | |
| 61 | + is_fork: ${{ github.event.pull_request.head.repo.fork == true }} | |
| 62 | + is_dependabot: ${{ github.actor == 'dependabot[bot]' }} | |
| 63 | + | |
| 55 | 64 | - name: Type check and lint |
| 56 | 65 | run: | |
| 57 | 66 | cd core |
| @@ -66,7 +75,7 @@ | ||
| 66 | 75 | npm test |
| 67 | 76 | npm run vitest |
| 68 | 77 | env: |
| 69 | - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} | |
| 78 | + IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }} | |
| 70 | 79 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} |
| 71 | 80 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} |
| 72 | 81 | GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} |
| @@ -75,6 +84,9 @@ | ||
| 75 | 84 | AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} |
| 76 | 85 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 77 | 86 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 87 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 88 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 89 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 78 | 90 | |
| 79 | 91 | gui-checks: |
| 80 | 92 | runs-on: ubuntu-latest |
| @@ -180,16 +192,25 @@ | ||
| 180 | 192 | package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }} |
| 181 | 193 | steps: |
| 182 | 194 | - uses: actions/checkout@v5 |
| 195 | + with: | |
| 196 | + fetch-depth: 0 # Needed for git diff to work | |
| 183 | 197 | - name: Setup packages |
| 184 | 198 | uses: ./.github/actions/setup-packages |
| 185 | 199 | |
| 200 | + - name: Check if LLM-related files changed | |
| 201 | + id: llm-changes | |
| 202 | + uses: ./.github/actions/check-llm-changes | |
| 203 | + with: | |
| 204 | + is_fork: ${{ github.event.pull_request.head.repo.fork == true }} | |
| 205 | + is_dependabot: ${{ github.actor == 'dependabot[bot]' }} | |
| 206 | + | |
| 186 | 207 | - name: Test and check ${{ matrix.package }} |
| 187 | 208 | run: | |
| 188 | 209 | cd packages/${{ matrix.package }} |
| 189 | 210 | npm ci |
| 190 | 211 | npm test |
| 191 | 212 | env: |
| 192 | - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} | |
| 213 | + IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }} | |
| 193 | 214 | OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} |
| 194 | 215 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} |
| 195 | 216 | GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} |
| @@ -199,6 +220,8 @@ | ||
| 199 | 220 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 200 | 221 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 201 | 222 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 223 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 224 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 202 | 225 | |
| 203 | 226 | vscode-get-test-file-matrix: |
| 204 | 227 | runs-on: ubuntu-latest |
| @@ -206,7 +229,7 @@ | ||
| 206 | 229 | test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} |
| 207 | 230 | steps: |
| 208 | 231 | - uses: actions/checkout@v5 |
| 209 | - - uses: actions/setup-node@v4 | |
| 232 | + - uses: actions/setup-node@v5 | |
| 210 | 233 | with: |
| 211 | 234 | node-version-file: ".nvmrc" |
| 212 | 235 | |
| @@ -324,7 +347,7 @@ | ||
| 324 | 347 | runs-on: ubuntu-latest |
| 325 | 348 | steps: |
| 326 | 349 | - uses: actions/checkout@v5 |
| 327 | - - uses: actions/setup-node@v4 | |
| 350 | + - uses: actions/setup-node@v5 | |
| 328 | 351 | with: |
| 329 | 352 | node-version: 20 |
| 330 | 353 |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | with: |
| 71 | 71 | fetch-depth: 0 |
| 72 | 72 | |
| 73 | - - uses: actions/setup-node@v4 | |
| 73 | + - uses: actions/setup-node@v5 | |
| 74 | 74 | with: |
| 75 | 75 | node-version-file: ".nvmrc" |
| 76 | 76 | |
| @@ -165,7 +165,7 @@ | ||
| 165 | 165 | |
| 166 | 166 | # 4. Create PR with version bump |
| 167 | 167 | - name: Setup Node.js |
| 168 | - uses: actions/setup-node@v4 | |
| 168 | + uses: actions/setup-node@v5 | |
| 169 | 169 | with: |
| 170 | 170 | node-version-file: ".nvmrc" |
| 171 | 171 |
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
| @@ -23,4 +23,7 @@ | ||
| 23 | 23 | AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} |
| 24 | 24 | AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} |
| 25 | 25 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 26 | - AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| No newline at the end of the file | ||
| 26 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 27 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 28 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 29 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
| @@ -32,3 +32,5 @@ | ||
| 32 | 32 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 33 | 33 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 34 | 34 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 35 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 36 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} |
| @@ -0,0 +1,302 @@ | ||
| 1 | +name: Respond to @continuedev Comments | |
| 2 | + | |
| 3 | +on: | |
| 4 | + issue_comment: | |
| 5 | + types: [created] | |
| 6 | + pull_request_review_comment: | |
| 7 | + types: [created] | |
| 8 | + | |
| 9 | +permissions: | |
| 10 | + contents: write | |
| 11 | + pull-requests: write | |
| 12 | + issues: write | |
| 13 | + | |
| 14 | +jobs: | |
| 15 | + respond-to-comment: | |
| 16 | + # Only run on pull request comments | |
| 17 | + if: github.event_name == 'issue_comment' && github.event.issue.pull_request | |
| 18 | + runs-on: ubuntu-latest | |
| 19 | + | |
| 20 | + steps: | |
| 21 | + - name: Check if comment contains @continuedev | |
| 22 | + id: check-mention | |
| 23 | + run: | | |
| 24 | + # Create a temporary file to safely handle comment body with special characters | |
| 25 | + cat > /tmp/comment.txt << 'COMMENT_EOF' | |
| 26 | + ${{ github.event.comment.body }} | |
| 27 | + COMMENT_EOF | |
| 28 | + | |
| 29 | + if grep -q "@continuedev" /tmp/comment.txt; then | |
| 30 | + echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 31 | + else | |
| 32 | + echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 33 | + fi | |
| 34 | + | |
| 35 | + - name: Add eyes reaction to comment | |
| 36 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 37 | + uses: actions/github-script@v8 | |
| 38 | + with: | |
| 39 | + script: | | |
| 40 | + await github.rest.reactions.createForIssueComment({ | |
| 41 | + owner: context.repo.owner, | |
| 42 | + repo: context.repo.repo, | |
| 43 | + comment_id: ${{ github.event.comment.id }}, | |
| 44 | + content: 'eyes' | |
| 45 | + }); | |
| 46 | + | |
| 47 | + - name: Checkout PR branch | |
| 48 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 49 | + uses: actions/checkout@v5 | |
| 50 | + with: | |
| 51 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 52 | + fetch-depth: 0 | |
| 53 | + | |
| 54 | + - name: Get PR information | |
| 55 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 56 | + id: pr-info | |
| 57 | + uses: actions/github-script@v8 | |
| 58 | + with: | |
| 59 | + script: | | |
| 60 | + const { data: pr } = await github.rest.pulls.get({ | |
| 61 | + owner: context.repo.owner, | |
| 62 | + repo: context.repo.repo, | |
| 63 | + pull_number: context.issue.number | |
| 64 | + }); | |
| 65 | + | |
| 66 | + core.setOutput('head_ref', pr.head.ref); | |
| 67 | + core.setOutput('head_sha', pr.head.sha); | |
| 68 | + return pr; | |
| 69 | + | |
| 70 | + - name: Checkout PR branch | |
| 71 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 72 | + run: | | |
| 73 | + git checkout ${{ steps.pr-info.outputs.head_ref }} | |
| 74 | + | |
| 75 | + - name: Setup Node.js | |
| 76 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 77 | + uses: actions/setup-node@v5 | |
| 78 | + with: | |
| 79 | + node-version: "20" | |
| 80 | + | |
| 81 | + - name: Install Continue CLI globally | |
| 82 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 83 | + run: npm i -g @continuedev/cli | |
| 84 | + | |
| 85 | + - name: Start remote session | |
| 86 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 87 | + id: remote-session | |
| 88 | + env: | |
| 89 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 90 | + run: | | |
| 91 | + # Create a temporary file for the prompt to handle special characters and newlines properly | |
| 92 | + cat > /tmp/prompt.txt << 'PROMPT_EOF' | |
| 93 | + Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: | |
| 94 | + | |
| 95 | + ${{ github.event.comment.body }} | |
| 96 | + | |
| 97 | + Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch. | |
| 98 | + PROMPT_EOF | |
| 99 | + | |
| 100 | + # Debug output | |
| 101 | + echo "PROMPT content:" | |
| 102 | + cat /tmp/prompt.txt | |
| 103 | + | |
| 104 | + # Start remote session and capture JSON output | |
| 105 | + echo "Starting cn with prompt..." | |
| 106 | + SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }}) | |
| 107 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 108 | + | |
| 109 | + # Extract URL from JSON output | |
| 110 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 111 | + | |
| 112 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 113 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 114 | + exit 1 | |
| 115 | + fi | |
| 116 | + | |
| 117 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 118 | + echo "✅ Started remote session: $SESSION_URL" | |
| 119 | + | |
| 120 | + - name: Comment with session URL | |
| 121 | + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 122 | + uses: actions/github-script@v8 | |
| 123 | + env: | |
| 124 | + ORIGINAL_COMMENT: ${{ github.event.comment.body }} | |
| 125 | + with: | |
| 126 | + script: | | |
| 127 | + const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; | |
| 128 | + const originalComment = process.env.ORIGINAL_COMMENT; | |
| 129 | + const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; | |
| 130 | + | |
| 131 | + await github.rest.issues.createComment({ | |
| 132 | + owner: context.repo.owner, | |
| 133 | + repo: context.repo.repo, | |
| 134 | + issue_number: context.issue.number, | |
| 135 | + body: commentBody | |
| 136 | + }); | |
| 137 | + | |
| 138 | + - name: Log session details | |
| 139 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 140 | + run: | | |
| 141 | + echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" | |
| 142 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 143 | + echo "Original comment:" | |
| 144 | + cat /tmp/comment.txt | |
| 145 | + | |
| 146 | + respond-to-review-comment: | |
| 147 | + # Only run on pull request review comments | |
| 148 | + if: github.event_name == 'pull_request_review_comment' | |
| 149 | + runs-on: ubuntu-latest | |
| 150 | + | |
| 151 | + steps: | |
| 152 | + - name: Check if comment contains @continuedev | |
| 153 | + id: check-mention | |
| 154 | + run: | | |
| 155 | + # Create a temporary file to safely handle comment body with special characters | |
| 156 | + cat > /tmp/review_comment.txt << 'COMMENT_EOF' | |
| 157 | + ${{ github.event.comment.body }} | |
| 158 | + COMMENT_EOF | |
| 159 | + | |
| 160 | + if grep -q "@continuedev" /tmp/review_comment.txt; then | |
| 161 | + echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 162 | + else | |
| 163 | + echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 164 | + fi | |
| 165 | + | |
| 166 | + - name: Add eyes reaction to comment | |
| 167 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 168 | + uses: actions/github-script@v8 | |
| 169 | + with: | |
| 170 | + script: | | |
| 171 | + await github.rest.reactions.createForPullRequestReviewComment({ | |
| 172 | + owner: context.repo.owner, | |
| 173 | + repo: context.repo.repo, | |
| 174 | + comment_id: ${{ github.event.comment.id }}, | |
| 175 | + content: 'eyes' | |
| 176 | + }); | |
| 177 | + | |
| 178 | + - name: Checkout PR branch | |
| 179 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 180 | + uses: actions/checkout@v5 | |
| 181 | + with: | |
| 182 | + token: ${{ secrets.GITHUB_TOKEN }} | |
| 183 | + fetch-depth: 0 | |
| 184 | + ref: ${{ github.event.pull_request.head.ref }} | |
| 185 | + | |
| 186 | + - name: Setup Node.js | |
| 187 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 188 | + uses: actions/setup-node@v5 | |
| 189 | + with: | |
| 190 | + node-version: "20" | |
| 191 | + | |
| 192 | + - name: Install Continue CLI globally | |
| 193 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 194 | + run: npm i -g @continuedev/cli | |
| 195 | + | |
| 196 | + - name: Get review context | |
| 197 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 198 | + id: review-context | |
| 199 | + uses: actions/github-script@v8 | |
| 200 | + with: | |
| 201 | + script: | | |
| 202 | + let reviewContext = ''; | |
| 203 | + | |
| 204 | + // Check if this comment is a reply to another review comment | |
| 205 | + if (context.payload.comment.in_reply_to_id) { | |
| 206 | + try { | |
| 207 | + const { data: originalComment } = await github.rest.pulls.getReviewComment({ | |
| 208 | + owner: context.repo.owner, | |
| 209 | + repo: context.repo.repo, | |
| 210 | + comment_id: context.payload.comment.in_reply_to_id | |
| 211 | + }); | |
| 212 | + | |
| 213 | + reviewContext = `**Original review comment by @${originalComment.user.login}:** | |
| 214 | + ${originalComment.body} | |
| 215 | + | |
| 216 | + **Reply by @${{ github.event.comment.user.login }}:** | |
| 217 | + ${{ github.event.comment.body }}`; | |
| 218 | + } catch (error) { | |
| 219 | + console.log('Could not fetch original comment, using current comment only'); | |
| 220 | + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** | |
| 221 | + ${{ github.event.comment.body }}`; | |
| 222 | + } | |
| 223 | + } else { | |
| 224 | + reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:** | |
| 225 | + ${{ github.event.comment.body }}`; | |
| 226 | + } | |
| 227 | + | |
| 228 | + core.setOutput('context', reviewContext); | |
| 229 | + | |
| 230 | + - name: Start remote session | |
| 231 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 232 | + id: remote-session | |
| 233 | + env: | |
| 234 | + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 235 | + run: | | |
| 236 | + # Debug: Echo the branch we're starting the session on | |
| 237 | + echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}" | |
| 238 | + | |
| 239 | + # Create a temporary file for the prompt to handle special characters and newlines properly | |
| 240 | + cat > /tmp/prompt.txt << 'PROMPT_EOF' | |
| 241 | + Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}: | |
| 242 | + | |
| 243 | + **File:** ${{ github.event.comment.path }} | |
| 244 | + **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} | |
| 245 | + | |
| 246 | + ${{ steps.review-context.outputs.context }} | |
| 247 | + | |
| 248 | + Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch. | |
| 249 | + PROMPT_EOF | |
| 250 | + | |
| 251 | + # Debug output | |
| 252 | + echo "PROMPT content:" | |
| 253 | + cat /tmp/prompt.txt | |
| 254 | + | |
| 255 | + # Start remote session and capture JSON output | |
| 256 | + echo "Starting cn with prompt..." | |
| 257 | + SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }}) | |
| 258 | + echo "Raw session output: $SESSION_OUTPUT" | |
| 259 | + | |
| 260 | + # Extract URL from JSON output | |
| 261 | + SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 262 | + | |
| 263 | + if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 264 | + echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 265 | + exit 1 | |
| 266 | + fi | |
| 267 | + | |
| 268 | + echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 269 | + echo "✅ Started remote session: $SESSION_URL" | |
| 270 | + | |
| 271 | + - name: Comment with session URL | |
| 272 | + if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 273 | + uses: actions/github-script@v8 | |
| 274 | + env: | |
| 275 | + ORIGINAL_COMMENT: ${{ github.event.comment.body }} | |
| 276 | + with: | |
| 277 | + script: | | |
| 278 | + const sessionUrl = '${{ steps.remote-session.outputs.session_url }}'; | |
| 279 | + const originalComment = process.env.ORIGINAL_COMMENT; | |
| 280 | + const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment; | |
| 281 | + | |
| 282 | + const commentParams = { | |
| 283 | + owner: context.repo.owner, | |
| 284 | + repo: context.repo.repo, | |
| 285 | + pull_number: ${{ github.event.pull_request.number }}, | |
| 286 | + body: commentBody, | |
| 287 | + commit_id: '${{ github.event.pull_request.head.sha }}', | |
| 288 | + path: '${{ github.event.comment.path }}', | |
| 289 | + in_reply_to: ${{ github.event.comment.id }} | |
| 290 | + }; | |
| 291 | + | |
| 292 | + await github.rest.pulls.createReviewComment(commentParams); | |
| 293 | + | |
| 294 | + - name: Log session details | |
| 295 | + if: steps.check-mention.outputs.contains_mention == 'true' | |
| 296 | + run: | | |
| 297 | + echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}" | |
| 298 | + echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 299 | + echo "File: ${{ github.event.comment.path }}" | |
| 300 | + echo "Line: ${{ github.event.comment.line }}" | |
| 301 | + echo "Original comment:" | |
| 302 | + cat /tmp/review_comment.txt |
| @@ -32,6 +32,10 @@ | ||
| 32 | 32 | required: false |
| 33 | 33 | VOYAGE_API_KEY: |
| 34 | 34 | required: false |
| 35 | + RELACE_API_KEY: | |
| 36 | + required: false | |
| 37 | + INCEPTION_API_KEY: | |
| 38 | + required: false | |
| 35 | 39 | |
| 36 | 40 | permissions: |
| 37 | 41 | contents: write |
| @@ -55,7 +59,7 @@ | ||
| 55 | 59 | uses: ./.github/actions/setup-packages |
| 56 | 60 | |
| 57 | 61 | - name: Use Node.js from .nvmrc |
| 58 | - uses: actions/setup-node@v4 | |
| 62 | + uses: actions/setup-node@v5 | |
| 59 | 63 | with: |
| 60 | 64 | node-version-file: ".nvmrc" |
| 61 | 65 | |
| @@ -77,6 +81,8 @@ | ||
| 77 | 81 | AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} |
| 78 | 82 | AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} |
| 79 | 83 | VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
| 84 | + RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }} | |
| 85 | + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} | |
| 80 | 86 | |
| 81 | 87 | - name: Release |
| 82 | 88 | env: |
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | path: deja-view |
| 32 | 32 | |
| 33 | 33 | - name: Setup Python |
| 34 | - uses: actions/setup-python@v5 | |
| 34 | + uses: actions/setup-python@v6 | |
| 35 | 35 | with: |
| 36 | 36 | python-version: "3.11" |
| 37 | 37 | |
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT |
| 191 | 191 | |
| 192 | 192 | - name: Comment with analysis |
| 193 | - uses: actions/github-script@v7 | |
| 193 | + uses: actions/github-script@v8 | |
| 194 | 194 | with: |
| 195 | 195 | script: | |
| 196 | 196 | let comment = ''; |
| @@ -307,7 +307,7 @@ | ||
| 307 | 307 | |
| 308 | 308 | - name: Add labels |
| 309 | 309 | if: github.event_name == 'issues' |
| 310 | - uses: actions/github-script@v7 | |
| 310 | + uses: actions/github-script@v8 | |
| 311 | 311 | with: |
| 312 | 312 | script: | |
| 313 | 313 | const labels = []; |
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} |
| 41 | 41 | |
| 42 | 42 | - name: Setup Node.js |
| 43 | - uses: actions/setup-node@v4 | |
| 43 | + uses: actions/setup-node@v5 | |
| 44 | 44 | with: |
| 45 | 45 | node-version: 20 |
| 46 | 46 | registry-url: "https://registry.npmjs.org" |
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | pull-requests: write |
| 11 | 11 | runs-on: ubuntu-latest |
| 12 | 12 | steps: |
| 13 | - - uses: actions/stale@v9 | |
| 13 | + - uses: actions/stale@v10 | |
| 14 | 14 | with: |
| 15 | 15 | close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" |
| 16 | 16 | stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." |
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | gh auth login --with-token <<< "${{ github.token }}" |
| 22 | 22 | |
| 23 | 23 | - name: Use Node.js from .nvmrc |
| 24 | - uses: actions/setup-node@v4 | |
| 24 | + uses: actions/setup-node@v5 | |
| 25 | 25 | with: |
| 26 | 26 | node-version-file: ".nvmrc" |
| 27 | 27 |
| @@ -23,5 +23,5 @@ | ||
| 23 | 23 | **/CODEOWNERS |
| 24 | 24 | core/vendor |
| 25 | 25 | coverage |
| 26 | -e2e | |
| 26 | +# e2e | |
| 27 | 27 | packages/continue-sdk |
| No newline at the end of the file |
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | ], |
| 19 | 19 | "pauseForSourceMap": false, |
| 20 | 20 | "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], |
| 21 | - "preLaunchTask": "vscode-extension:build-with-packages", | |
| 21 | + "preLaunchTask": "vscode-extension:build-without-watch", | |
| 22 | 22 | "env": { |
| 23 | 23 | // "CONTROL_PLANE_ENV": "local", |
| 24 | 24 | "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" |
| @@ -153,7 +153,7 @@ | ||
| 153 | 153 | "${workspaceFolder}/**", |
| 154 | 154 | "!**/node_modules/**" |
| 155 | 155 | ], |
| 156 | - "preLaunchTask": "watch-logs", | |
| 156 | + "preLaunchTask": "cli:build-and-watch-logs", | |
| 157 | 157 | "cwd": "${workspaceFolder}/extensions/cli" |
| 158 | 158 | }, |
| 159 | 159 | { |
| @@ -43,7 +43,8 @@ | ||
| 43 | 43 | "extensions/vscode/e2e/storage": true, |
| 44 | 44 | "extensions/vscode/e2e/vsix": true, |
| 45 | 45 | "extensions/.continue-debug": true, |
| 46 | - "extensions/cli/dist/**": true | |
| 46 | + "extensions/cli/dist/**": true, | |
| 47 | + "packages/config-yaml/dist/**": true | |
| 47 | 48 | // "sync/**": true |
| 48 | 49 | }, |
| 49 | 50 | "editor.formatOnSave": true, |
| @@ -174,6 +174,25 @@ | ||
| 174 | 174 | } |
| 175 | 175 | ] |
| 176 | 176 | }, |
| 177 | + { | |
| 178 | + "label": "gui:build", | |
| 179 | + "type": "shell", | |
| 180 | + "command": "npm", | |
| 181 | + "options": { | |
| 182 | + "cwd": "${workspaceFolder}/gui", | |
| 183 | + "env": { | |
| 184 | + "NODE_OPTIONS": "--max-old-space-size=4096" | |
| 185 | + } | |
| 186 | + }, | |
| 187 | + "args": ["run", "build"], | |
| 188 | + "problemMatcher": ["$tsc"], | |
| 189 | + "presentation": { | |
| 190 | + "group": "build-tasks", | |
| 191 | + "panel": "shared", | |
| 192 | + "reveal": "silent", | |
| 193 | + "close": true | |
| 194 | + } | |
| 195 | + }, | |
| 177 | 196 | { |
| 178 | 197 | "label": "binary:esbuild", |
| 179 | 198 | "type": "shell", |
| @@ -330,6 +349,26 @@ | ||
| 330 | 349 | "cwd": "${workspaceFolder}/extensions/cli" |
| 331 | 350 | } |
| 332 | 351 | }, |
| 352 | + { | |
| 353 | + "label": "cli:build-no-minify", | |
| 354 | + "type": "shell", | |
| 355 | + "command": "npm", | |
| 356 | + "args": ["run", "build:bundle", "--", "--no-minify"], | |
| 357 | + "group": "build", | |
| 358 | + "presentation": { | |
| 359 | + "echo": true, | |
| 360 | + "reveal": "silent", | |
| 361 | + "focus": false, | |
| 362 | + "panel": "shared", | |
| 363 | + "showReuseMessage": true, | |
| 364 | + "clear": false, | |
| 365 | + "close": true | |
| 366 | + }, | |
| 367 | + "problemMatcher": ["$tsc"], | |
| 368 | + "options": { | |
| 369 | + "cwd": "${workspaceFolder}/extensions/cli" | |
| 370 | + } | |
| 371 | + }, | |
| 333 | 372 | { |
| 334 | 373 | "label": "cli:test", |
| 335 | 374 | "type": "npm", |
| @@ -373,6 +412,21 @@ | ||
| 373 | 412 | "options": { |
| 374 | 413 | "cwd": "${workspaceFolder}/extensions/cli" |
| 375 | 414 | } |
| 415 | + }, | |
| 416 | + { | |
| 417 | + "label": "cli:build-and-watch-logs", | |
| 418 | + "dependsOn": ["cli:build-no-minify", "watch-logs"], | |
| 419 | + "dependsOrder": "sequence", | |
| 420 | + "type": "shell", | |
| 421 | + "command": "echo", | |
| 422 | + "args": ["Build and watch logs completed"], | |
| 423 | + "presentation": { | |
| 424 | + "group": "build-tasks", | |
| 425 | + "panel": "shared", | |
| 426 | + "reveal": "silent", | |
| 427 | + "close": true, | |
| 428 | + "focus": false | |
| 429 | + } | |
| 376 | 430 | } |
| 377 | 431 | ] |
| 378 | 432 | } |
| @@ -176,9 +176,9 @@ | ||
| 176 | 176 | ### Our Git Workflow |
| 177 | 177 | |
| 178 | 178 | We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the |
| 179 | -`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow | |
| 179 | +`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow | |
| 180 | 180 | in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When |
| 181 | -a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar | |
| 181 | +a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar | |
| 182 | 182 | workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code |
| 183 | 183 | extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow |
| 184 | 184 | is well explained by <http://releaseflow.org>. |
| @@ -35,25 +35,25 @@ | ||
| 35 | 35 | |
| 36 | 36 | ## Agent |
| 37 | 37 | |
| 38 | -[Agent](/features/agent/quick-start) to work on development tasks together with AI | |
| 38 | +[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI | |
| 39 | 39 | |
| 40 | 40 |  |
| 41 | 41 | |
| 42 | 42 | ## Chat |
| 43 | 43 | |
| 44 | -[Chat](/features/chat/quick-start) to ask general questions and clarify code sections | |
| 44 | +[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections | |
| 45 | 45 | |
| 46 | 46 |  |
| 47 | 47 | |
| 48 | 48 | ## Edit |
| 49 | 49 | |
| 50 | -[Edit](/features/edit/quick-start) to modify a code section without leaving your current file | |
| 50 | +[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file | |
| 51 | 51 | |
| 52 | 52 |  |
| 53 | 53 | |
| 54 | 54 | ## Autocomplete |
| 55 | 55 | |
| 56 | -[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type | |
| 56 | +[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type | |
| 57 | 57 | |
| 58 | 58 |  |
| 59 | 59 |
| @@ -73,7 +73,7 @@ | ||
| 73 | 73 | - name: Install Continue CLI |
| 74 | 74 | if: env.SKIP_REVIEW != 'true' |
| 75 | 75 | shell: bash |
| 76 | - run: npm install -g @continuedev/cli@1.4.25 | |
| 76 | + run: npm install -g @continuedev/cli@1.4.30 | |
| 77 | 77 | |
| 78 | 78 | - name: Build Inline Review Prompt |
| 79 | 79 | if: env.SKIP_REVIEW != 'true' |
| @@ -194,6 +194,21 @@ | ||
| 194 | 194 | exit 1 |
| 195 | 195 | fi |
| 196 | 196 | |
| 197 | + # Validate API key | |
| 198 | + if [ -z "$CONTINUE_API_KEY" ]; then | |
| 199 | + echo "Warning: CONTINUE_API_KEY environment variable is not set" | |
| 200 | + # Create fallback review and continue | |
| 201 | + cat > inline_review.json << 'EOF' | |
| 202 | + { | |
| 203 | + "review_summary": "AI review skipped: CONTINUE_API_KEY not configured.", | |
| 204 | + "comments": [] | |
| 205 | + } | |
| 206 | + EOF | |
| 207 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 208 | + else | |
| 209 | + echo "SKIP_CLI=false" >> $GITHUB_ENV | |
| 210 | + fi | |
| 211 | + | |
| 197 | 212 | # Log the prompt for debugging |
| 198 | 213 | echo "===== START REVIEW PROMPT =====" |
| 199 | 214 | head -n 50 inline_review_prompt.txt |
| @@ -201,23 +216,67 @@ | ||
| 201 | 216 | tail -n 20 inline_review_prompt.txt |
| 202 | 217 | echo "===== END REVIEW PROMPT =====" |
| 203 | 218 | |
| 204 | - # Run the CLI and capture JSON output | |
| 205 | - cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json | |
| 206 | - | |
| 207 | - # Log the output for debugging | |
| 208 | - echo "Initial Continue CLI output:" | |
| 209 | - cat inline_review_raw.json | |
| 219 | + # Test Continue CLI availability | |
| 220 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 221 | + echo "Testing Continue CLI..." | |
| 222 | + if ! cn --version; then | |
| 223 | + echo "Warning: Continue CLI not found or not working" | |
| 224 | + cat > inline_review.json << 'EOF' | |
| 225 | + { | |
| 226 | + "review_summary": "AI review skipped: Continue CLI installation failed.", | |
| 227 | + "comments": [] | |
| 228 | + } | |
| 229 | + EOF | |
| 230 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 231 | + else | |
| 232 | + echo "Continue CLI version: $(cn --version)" | |
| 233 | + fi | |
| 234 | + fi | |
| 210 | 235 | |
| 211 | - # Validate JSON output and use it directly | |
| 212 | - if ! jq empty inline_review_raw.json 2>/dev/null; then | |
| 213 | - echo "Error: Invalid JSON output from Continue CLI" | |
| 214 | - exit 1 | |
| 236 | + # Run the CLI and capture JSON output with error handling | |
| 237 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 238 | + echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}" | |
| 239 | + | |
| 240 | + # Write prompt to temp file for better handling | |
| 241 | + PROMPT_FILE="/tmp/continue-prompt-$.txt" | |
| 242 | + cp inline_review_prompt.txt "$PROMPT_FILE" | |
| 243 | + | |
| 244 | + # Use timeout to prevent hanging (240 seconds = 4 minutes) | |
| 245 | + 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 | |
| 246 | + echo "Warning: Continue CLI command failed" | |
| 247 | + echo "CLI error log:" | |
| 248 | + cat cli_error.log | |
| 249 | + | |
| 250 | + # Create fallback review | |
| 251 | + cat > inline_review.json << 'EOF' | |
| 252 | + { | |
| 253 | + "review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.", | |
| 254 | + "comments": [] | |
| 255 | + } | |
| 256 | + EOF | |
| 257 | + echo "Created fallback review due to CLI failure" | |
| 258 | + else | |
| 259 | + # Log the output for debugging | |
| 260 | + echo "Initial Continue CLI output:" | |
| 261 | + cat inline_review_raw.json | |
| 262 | + | |
| 263 | + # Validate JSON output and use it directly | |
| 264 | + if ! jq empty inline_review_raw.json 2>/dev/null; then | |
| 265 | + echo "Warning: Invalid JSON output from Continue CLI, using fallback" | |
| 266 | + cat > inline_review.json << 'EOF' | |
| 267 | + { | |
| 268 | + "review_summary": "AI review completed but failed to parse output correctly.", | |
| 269 | + "comments": [] | |
| 270 | + } | |
| 271 | + EOF | |
| 272 | + else | |
| 273 | + # Use the JSON output directly | |
| 274 | + cp inline_review_raw.json inline_review.json | |
| 275 | + echo "Review output:" | |
| 276 | + cat inline_review.json | |
| 277 | + fi | |
| 278 | + fi | |
| 215 | 279 | fi |
| 216 | - | |
| 217 | - # Use the JSON output directly | |
| 218 | - cp inline_review_raw.json inline_review.json | |
| 219 | - echo "Review output:" | |
| 220 | - cat inline_review.json | |
| 221 | 280 | |
| 222 | 281 | - name: Post Inline Review Comments |
| 223 | 282 | if: env.SKIP_REVIEW != 'true' |
| @@ -1,20 +1,20 @@ | ||
| 1 | -name: 'Continue PR Review' | |
| 2 | -description: 'Automated code review for pull requests using Continue CLI' | |
| 3 | -author: 'Continue Dev, Inc.' | |
| 1 | +name: "Continue PR Review" | |
| 2 | +description: "Automated code review for pull requests using Continue CLI" | |
| 3 | +author: "Continue Dev, Inc." | |
| 4 | 4 | |
| 5 | 5 | inputs: |
| 6 | 6 | continue-api-key: |
| 7 | - description: 'API key for Continue service' | |
| 7 | + description: "API key for Continue service" | |
| 8 | 8 | required: true |
| 9 | 9 | continue-org: |
| 10 | - description: 'Organization for Continue config' | |
| 10 | + description: "Organization for Continue config" | |
| 11 | 11 | required: true |
| 12 | 12 | continue-config: |
| 13 | 13 | description: 'Config path to use (e.g., "myorg/review-bot")' |
| 14 | 14 | required: true |
| 15 | 15 | |
| 16 | 16 | runs: |
| 17 | - using: 'composite' | |
| 17 | + using: "composite" | |
| 18 | 18 | steps: |
| 19 | 19 | - name: Checkout Repository |
| 20 | 20 | uses: actions/checkout@v4 |
| @@ -27,7 +27,7 @@ | ||
| 27 | 27 | run: | |
| 28 | 28 | # Check if this action should run based on event type and user permissions |
| 29 | 29 | SHOULD_RUN="false" |
| 30 | - | |
| 30 | + | |
| 31 | 31 | if [ "${{ github.event_name }}" = "pull_request" ]; then |
| 32 | 32 | # Check if PR is a draft |
| 33 | 33 | if [ "${{ github.event.pull_request.draft }}" = "true" ]; then |
| @@ -56,7 +56,7 @@ | ||
| 56 | 56 | else |
| 57 | 57 | echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}" |
| 58 | 58 | fi |
| 59 | - | |
| 59 | + | |
| 60 | 60 | echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV |
| 61 | 61 | |
| 62 | 62 | - name: Setup Node.js |
| @@ -68,7 +68,7 @@ | ||
| 68 | 68 | - name: Install Continue CLI |
| 69 | 69 | if: env.SHOULD_RUN == 'true' |
| 70 | 70 | shell: bash |
| 71 | - run: npm install -g @continuedev/cli@1.4.25 | |
| 71 | + run: npm install -g @continuedev/cli@1.4.30 | |
| 72 | 72 | |
| 73 | 73 | - name: Build PR Review Prompt |
| 74 | 74 | if: env.SHOULD_RUN == 'true' |
| @@ -157,19 +157,84 @@ | ||
| 157 | 157 | echo "==================================" |
| 158 | 158 | echo "" |
| 159 | 159 | |
| 160 | + # Validate API key | |
| 161 | + if [ -z "$CONTINUE_API_KEY" ]; then | |
| 162 | + echo "Warning: CONTINUE_API_KEY environment variable is not set" | |
| 163 | + # Create fallback review and continue | |
| 164 | + cat > code_review.md << 'EOF' | |
| 165 | + ## Code Review Summary | |
| 166 | + | |
| 167 | + ⚠️ AI review skipped: CONTINUE_API_KEY not configured. | |
| 168 | + | |
| 169 | + ### Configuration Required | |
| 170 | + - Please set the CONTINUE_API_KEY secret in repository settings | |
| 171 | + - Verify that the organization and config path are valid | |
| 172 | + EOF | |
| 173 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 174 | + else | |
| 175 | + echo "SKIP_CLI=false" >> $GITHUB_ENV | |
| 176 | + fi | |
| 177 | + | |
| 160 | 178 | # Validate inputs to prevent command injection |
| 161 | 179 | if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then |
| 162 | 180 | echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores." |
| 163 | 181 | exit 1 |
| 164 | 182 | fi |
| 165 | - | |
| 183 | + | |
| 166 | 184 | if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then |
| 167 | 185 | echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes." |
| 168 | 186 | exit 1 |
| 169 | 187 | fi |
| 170 | 188 | |
| 171 | - # Run the CLI with validated config | |
| 172 | - cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md | |
| 189 | + # Test Continue CLI availability | |
| 190 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 191 | + echo "Testing Continue CLI..." | |
| 192 | + if ! cn --version; then | |
| 193 | + echo "Warning: Continue CLI not found or not working" | |
| 194 | + cat > code_review.md << 'EOF' | |
| 195 | + ## Code Review Summary | |
| 196 | + | |
| 197 | + ⚠️ AI review skipped: Continue CLI installation failed. | |
| 198 | + | |
| 199 | + ### Troubleshooting | |
| 200 | + - Check that npm installation succeeded | |
| 201 | + - Verify @continuedev/cli package is available | |
| 202 | + EOF | |
| 203 | + echo "SKIP_CLI=true" >> $GITHUB_ENV | |
| 204 | + else | |
| 205 | + echo "Continue CLI version: $(cn --version)" | |
| 206 | + fi | |
| 207 | + fi | |
| 208 | + | |
| 209 | + # Run the CLI with validated config and error handling | |
| 210 | + if [ "$SKIP_CLI" != "true" ]; then | |
| 211 | + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" | |
| 212 | + | |
| 213 | + # Write prompt to temp file for better handling | |
| 214 | + PROMPT_FILE="/tmp/continue-prompt-$.txt" | |
| 215 | + cp review_prompt.txt "$PROMPT_FILE" | |
| 216 | + | |
| 217 | + # Use timeout to prevent hanging (240 seconds = 4 minutes) | |
| 218 | + if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then | |
| 219 | + echo "Error: Continue CLI command failed" | |
| 220 | + echo "CLI error log:" | |
| 221 | + cat cli_error.log | |
| 222 | + | |
| 223 | + # Create fallback review | |
| 224 | + cat > code_review.md << 'EOF' | |
| 225 | + ## Code Review Summary | |
| 226 | + | |
| 227 | + ⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. | |
| 228 | + | |
| 229 | + ### Troubleshooting | |
| 230 | + - Verify the CONTINUE_API_KEY secret is set correctly | |
| 231 | + - Check that the organization and config path are valid | |
| 232 | + - Ensure the Continue service is accessible | |
| 233 | + EOF | |
| 234 | + else | |
| 235 | + echo "Review generated successfully" | |
| 236 | + fi | |
| 237 | + fi | |
| 173 | 238 | |
| 174 | 239 | - name: Upload Review Results |
| 175 | 240 | if: env.SHOULD_RUN == 'true' && always() |
| @@ -229,5 +294,5 @@ | ||
| 229 | 294 | } |
| 230 | 295 | |
| 231 | 296 | branding: |
| 232 | - icon: 'code' | |
| 233 | - color: 'blue' | |
| No newline at the end of the file | ||
| 297 | + icon: "code" | |
| 298 | + color: "blue" |
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
| @@ -166,8 +166,13 @@ | ||
| 166 | 166 | export const CODE_STOP_BLOCK = "[/CODE]"; |
| 167 | 167 | export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; |
| 168 | 168 | export const PREFIXES_TO_SKIP = ["<COMPLETION>"]; |
| 169 | -export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"]; | |
| 170 | -export const LINES_TO_SKIP = ["</START EDITING HERE>"]; | |
| 169 | +export const LINES_TO_STOP_AT = [ | |
| 170 | + "# End of file.", | |
| 171 | + "<STOP EDITING HERE", | |
| 172 | + "<|/updated_code|>", | |
| 173 | + "```", | |
| 174 | +]; | |
| 175 | +export const LINES_TO_SKIP = ["</START EDITING HERE>", "<|updated_code|>"]; | |
| 171 | 176 | export const LINES_TO_REMOVE_BEFORE_START = [ |
| 172 | 177 | "<COMPLETION>", |
| 173 | 178 | "[CODE]", |
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | getSingletonHighlighter, |
| 20 | 20 | Highlighter, |
| 21 | 21 | } from "shiki"; |
| 22 | -import { DiffLine } from ".."; | |
| 22 | +import { DiffChar, DiffLine } from ".."; | |
| 23 | 23 | import { escapeForSVG, kebabOfThemeStr } from "../util/text"; |
| 24 | 24 | |
| 25 | 25 | interface CodeRendererOptions { |
| @@ -228,6 +228,7 @@ | ||
| 228 | 228 | options: ConversionOptions, |
| 229 | 229 | currLineOffsetFromTop: number, |
| 230 | 230 | newDiffLines: DiffLine[], |
| 231 | + newDiffChars: DiffChar[], | |
| 231 | 232 | ): Promise<Buffer> { |
| 232 | 233 | const strokeWidth = 1; |
| 233 | 234 | const highlightedCodeHtml = await this.highlightCode( |
| @@ -236,13 +237,14 @@ | ||
| 236 | 237 | currLineOffsetFromTop, |
| 237 | 238 | newDiffLines, |
| 238 | 239 | ); |
| 239 | - // console.log(highlightedCodeHtml); | |
| 240 | 240 | |
| 241 | 241 | const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut( |
| 242 | 242 | highlightedCodeHtml, |
| 243 | 243 | options, |
| 244 | + newDiffChars, | |
| 244 | 245 | ); |
| 245 | 246 | const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); |
| 247 | + const borderColor = "#6b6b6b"; | |
| 246 | 248 | |
| 247 | 249 | const lines = code.split("\n"); |
| 248 | 250 | const actualHeight = lines.length * options.lineHeight; |
| @@ -256,12 +258,11 @@ | ||
| 256 | 258 | } |
| 257 | 259 | </style> |
| 258 | 260 | <g> |
| 259 | - <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" /> | |
| 261 | + <rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" /> | |
| 260 | 262 | ${lineBackgrounds} |
| 261 | 263 | ${guts} |
| 262 | 264 | </g> |
| 263 | 265 | </svg>`; |
| 264 | - // console.log(svg); | |
| 265 | 266 | |
| 266 | 267 | return Buffer.from(svg, "utf8"); |
| 267 | 268 | } |
| @@ -269,11 +270,56 @@ | ||
| 269 | 270 | convertShikiHtmlToSvgGut( |
| 270 | 271 | shikiHtml: string, |
| 271 | 272 | options: ConversionOptions, |
| 273 | + diffChars: DiffChar[], | |
| 272 | 274 | ): { guts: string; lineBackgrounds: string } { |
| 273 | 275 | const dom = new JSDOM(shikiHtml); |
| 274 | 276 | const document = dom.window.document; |
| 275 | 277 | |
| 276 | 278 | const lines = Array.from(document.querySelectorAll(".line")); |
| 279 | + | |
| 280 | + const additionSegmentsByLine = new Map< | |
| 281 | + number, | |
| 282 | + Array<{ start: number; end: number }> | |
| 283 | + >(); | |
| 284 | + | |
| 285 | + diffChars.forEach((diff) => { | |
| 286 | + if ( | |
| 287 | + diff.type !== "new" || | |
| 288 | + diff.newLineIndex === undefined || | |
| 289 | + diff.newCharIndexInLine === undefined | |
| 290 | + ) { | |
| 291 | + return; | |
| 292 | + } | |
| 293 | + | |
| 294 | + if (diff.char.includes("\n")) { | |
| 295 | + return; | |
| 296 | + } | |
| 297 | + | |
| 298 | + const start = diff.newCharIndexInLine; | |
| 299 | + const end = start + diff.char.length; | |
| 300 | + const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? []; | |
| 301 | + existing.push({ start, end }); | |
| 302 | + additionSegmentsByLine.set(diff.newLineIndex, existing); | |
| 303 | + }); | |
| 304 | + | |
| 305 | + additionSegmentsByLine.forEach((segments, lineIndex) => { | |
| 306 | + segments.sort((a, b) => a.start - b.start); | |
| 307 | + const merged: Array<{ start: number; end: number }> = []; | |
| 308 | + segments.forEach((segment) => { | |
| 309 | + if (merged.length === 0) { | |
| 310 | + merged.push({ ...segment }); | |
| 311 | + return; | |
| 312 | + } | |
| 313 | + | |
| 314 | + const last = merged[merged.length - 1]; | |
| 315 | + if (segment.start <= last.end) { | |
| 316 | + last.end = Math.max(last.end, segment.end); | |
| 317 | + } else { | |
| 318 | + merged.push({ ...segment }); | |
| 319 | + } | |
| 320 | + }); | |
| 321 | + additionSegmentsByLine.set(lineIndex, merged); | |
| 322 | + }); | |
| 277 | 323 | const svgLines = lines.map((line, index) => { |
| 278 | 324 | const spans = Array.from(line.childNodes) |
| 279 | 325 | .map((node) => { |
| @@ -309,60 +355,37 @@ | ||
| 309 | 355 | return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`; |
| 310 | 356 | }); |
| 311 | 357 | |
| 358 | + const estimatedCharWidth = options.fontSize * 0.6; | |
| 359 | + const additionFill = "rgba(40, 167, 69, 0.25)"; | |
| 360 | + | |
| 312 | 361 | const lineBackgrounds = lines |
| 313 | 362 | .map((line, index) => { |
| 314 | 363 | const classes = line?.getAttribute("class") || ""; |
| 315 | - const bgColor = classes.includes("highlighted") | |
| 316 | - ? this.editorLineHighlight | |
| 317 | - : classes.includes("diff add") | |
| 318 | - ? "rgba(255, 255, 0, 0.2)" | |
| 319 | - : this.editorBackground; | |
| 320 | - | |
| 321 | 364 | const y = index * options.lineHeight; |
| 322 | - const isFirst = index === 0; | |
| 323 | - const isLast = index === lines.length - 1; | |
| 324 | - const isSingleLine = isFirst && isLast; | |
| 325 | - const radius = 10; | |
| 326 | - | |
| 327 | - // Handle single line case (both first and last) | |
| 328 | - if (isSingleLine) { | |
| 329 | - return `<path d="M ${radius} ${y} | |
| 330 | - L ${options.dimensions.width - radius} ${y} | |
| 331 | - Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius} | |
| 332 | - L ${options.dimensions.width} ${y + options.lineHeight - radius} | |
| 333 | - Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight} | |
| 334 | - L ${radius} ${y + options.lineHeight} | |
| 335 | - Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius} | |
| 336 | - L ${0} ${y + radius} | |
| 337 | - Q ${0} ${y} ${radius} ${y} | |
| 338 | - Z" | |
| 339 | - fill="${bgColor}" />`; | |
| 365 | + const segments = additionSegmentsByLine.get(index) ?? []; | |
| 366 | + const backgrounds: string[] = []; | |
| 367 | + | |
| 368 | + if (classes.includes("highlighted")) { | |
| 369 | + backgrounds.push( | |
| 370 | + `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`, | |
| 371 | + ); | |
| 340 | 372 | } |
| 341 | 373 | |
| 342 | - // SVG notes: | |
| 343 | - // By default SVGs have anti-aliasing on. | |
| 344 | - // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps. | |
| 345 | - // Turning it off with 'shape-rendering="crispEdges"' solves the issue. | |
| 346 | - return isFirst | |
| 347 | - ? `<path d="M ${0} ${y + options.lineHeight} | |
| 348 | - L ${0} ${y + radius} | |
| 349 | - Q ${0} ${y} ${radius} ${y} | |
| 350 | - L ${options.dimensions.width - radius} ${y} | |
| 351 | - Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius} | |
| 352 | - L ${options.dimensions.width} ${y + options.lineHeight} | |
| 353 | - Z" | |
| 354 | - fill="${bgColor}" />` | |
| 355 | - : isLast | |
| 356 | - ? `<path d="M ${0} ${y} | |
| 357 | - L ${0} ${y + options.lineHeight - radius} | |
| 358 | - Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight} | |
| 359 | - L ${options.dimensions.width - radius} ${y + options.lineHeight} | |
| 360 | - Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10} | |
| 361 | - L ${options.dimensions.width} ${y} | |
| 362 | - Z" | |
| 363 | - fill="${bgColor}" />` | |
| 364 | - : `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`; | |
| 374 | + segments.forEach(({ start, end }) => { | |
| 375 | + const widthInChars = Math.max(end - start, 0); | |
| 376 | + if (widthInChars <= 0) { | |
| 377 | + return; | |
| 378 | + } | |
| 379 | + const x = start * estimatedCharWidth; | |
| 380 | + const segmentWidth = widthInChars * estimatedCharWidth; | |
| 381 | + backgrounds.push( | |
| 382 | + `<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`, | |
| 383 | + ); | |
| 384 | + }); | |
| 385 | + | |
| 386 | + return backgrounds.join("\n"); | |
| 365 | 387 | }) |
| 388 | + .filter((bg) => bg.length > 0) | |
| 366 | 389 | .join("\n"); |
| 367 | 390 | |
| 368 | 391 | return { |
| @@ -394,6 +417,7 @@ | ||
| 394 | 417 | options: ConversionOptions, |
| 395 | 418 | currLineOffsetFromTop: number, |
| 396 | 419 | newDiffLines: DiffLine[], |
| 420 | + newDiffChars: DiffChar[], | |
| 397 | 421 | ): Promise<DataUri> { |
| 398 | 422 | switch (options.imageType) { |
| 399 | 423 | // case "png": |
| @@ -413,6 +437,7 @@ | ||
| 413 | 437 | options, |
| 414 | 438 | currLineOffsetFromTop, |
| 415 | 439 | newDiffLines, |
| 440 | + newDiffChars, | |
| 416 | 441 | ); |
| 417 | 442 | return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; |
| 418 | 443 | } |
| @@ -1,99 +1,17 @@ | ||
| 1 | -import fs from "fs"; | |
| 2 | -import { homedir } from "node:os"; | |
| 3 | -import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 1 | +import { fileURLToPath } from "node:url"; | |
| 4 | 2 | import path from "path"; |
| 5 | 3 | |
| 6 | -import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | 4 | import { SlashCommand } from "../../../index.js"; |
| 8 | -import { renderChatMessage } from "../../../util/messageContent.js"; | |
| 9 | -import { getContinueGlobalPath } from "../../../util/paths.js"; | |
| 10 | - | |
| 11 | -// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | -function getOffsetDatetime(date: Date): Date { | |
| 13 | - const offset = date.getTimezoneOffset(); | |
| 14 | - const offsetHours = Math.floor(offset / 60); | |
| 15 | - const offsetMinutes = offset % 60; | |
| 16 | - date.setHours(date.getHours() - offsetHours); | |
| 17 | - date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | - | |
| 19 | - return date; | |
| 20 | -} | |
| 21 | - | |
| 22 | -function asBasicISOString(date: Date): string { | |
| 23 | - const isoString = date.toISOString(); | |
| 24 | - | |
| 25 | - return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | -} | |
| 27 | - | |
| 28 | -function reformatCodeBlocks(msgText: string): string { | |
| 29 | - const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | - msgText = msgText.replace( | |
| 31 | - codeBlockFenceRegex, | |
| 32 | - (match, metadata, filename, extension) => { | |
| 33 | - const lang = languageForFilepath(filename); | |
| 34 | - return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | - }, | |
| 36 | - ); | |
| 37 | - // Appease the markdown linter | |
| 38 | - return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | -} | |
| 5 | +import { shareSession } from "../../../util/historyUtils.js"; | |
| 40 | 6 | |
| 41 | 7 | const ShareSlashCommand: SlashCommand = { |
| 42 | 8 | name: "share", |
| 43 | 9 | description: "Export the current chat session to markdown", |
| 44 | 10 | run: async function* ({ ide, history, params }) { |
| 45 | - const now = new Date(); | |
| 46 | - | |
| 47 | - let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; | |
| 48 | - | |
| 49 | - // As currently implemented, the /share command is by definition the last | |
| 50 | - // message in the chat history, this will omit it | |
| 51 | - for (const msg of history.slice(0, history.length - 1)) { | |
| 52 | - let msgText = msg.content; | |
| 53 | - msgText = renderChatMessage(msg); | |
| 54 | - | |
| 55 | - if (msg.role === "user" && msgText.search("```") > -1) { | |
| 56 | - msgText = reformatCodeBlocks(msgText); | |
| 57 | - } | |
| 58 | - | |
| 59 | - // format messages as blockquotes | |
| 60 | - msgText = msgText.replace(/^/gm, "> "); | |
| 61 | - | |
| 62 | - content += `\n\n#### ${ | |
| 63 | - msg.role === "user" ? "_User_" : "_Assistant_" | |
| 64 | - }\n\n${msgText}`; | |
| 65 | - } | |
| 66 | - | |
| 67 | - let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); | |
| 68 | - | |
| 69 | - if (outputDir.startsWith("~")) { | |
| 70 | - outputDir = outputDir.replace(/^~/, homedir); | |
| 71 | - } else if ( | |
| 72 | - outputDir.startsWith("./") || | |
| 73 | - outputDir.startsWith(".\\") || | |
| 74 | - outputDir === "." | |
| 75 | - ) { | |
| 76 | - const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 77 | - // Although the most common situation is to have one directory open in a | |
| 78 | - // workspace it's also possible to have just a file open without an | |
| 79 | - // associated directory or to use multi-root workspaces in which multiple | |
| 80 | - // folders are included. We default to using the first item in the list, if | |
| 81 | - // it exists. | |
| 82 | - const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 83 | - outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 84 | - } | |
| 85 | - | |
| 86 | - if (!fs.existsSync(outputDir)) { | |
| 87 | - fs.mkdirSync(outputDir, { recursive: true }); | |
| 88 | - } | |
| 89 | - | |
| 90 | - const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 91 | - const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 92 | - | |
| 93 | - const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 94 | - await ide.writeFile(fileUrl, content); | |
| 95 | - await ide.openFile(fileUrl); | |
| 96 | - | |
| 11 | + const fileUrl = await shareSession(ide, history, params?.outputDir); | |
| 12 | + const filePath = fileURLToPath(fileUrl); | |
| 13 | + // output path is the parent directory of the filePath | |
| 14 | + const outPath = path.dirname(filePath); | |
| 97 | 15 | yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; |
| 98 | 16 | }, |
| 99 | 17 | }; |
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { RuleWithSource, SlashCommandWithSource } from "../.."; | |
| 2 | + | |
| 3 | +export function convertRuleBlockToSlashCommand( | |
| 4 | + rule: RuleWithSource, | |
| 5 | +): SlashCommandWithSource { | |
| 6 | + return { | |
| 7 | + name: | |
| 8 | + rule.name || | |
| 9 | + (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), | |
| 10 | + description: rule.description ?? "", | |
| 11 | + prompt: rule.rule, | |
| 12 | + source: "invokable-rule", | |
| 13 | + promptFile: rule.ruleFile, | |
| 14 | + }; | |
| 15 | +} |
| @@ -0,0 +1,93 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { RuleWithSource } from "../.."; | |
| 3 | +import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand"; | |
| 4 | + | |
| 5 | +describe("convertRuleBlockToSlashCommand", () => { | |
| 6 | + it("should convert a rule with all properties to a slash command", () => { | |
| 7 | + const rule: RuleWithSource = { | |
| 8 | + name: "Code Review", | |
| 9 | + rule: "Review this code for best practices", | |
| 10 | + description: "Performs a code review", | |
| 11 | + source: "rules-block", | |
| 12 | + ruleFile: "/path/to/rules.yaml", | |
| 13 | + invokable: true, | |
| 14 | + }; | |
| 15 | + | |
| 16 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 17 | + | |
| 18 | + expect(result).toEqual({ | |
| 19 | + name: "Code Review", | |
| 20 | + description: "Performs a code review", | |
| 21 | + prompt: "Review this code for best practices", | |
| 22 | + source: "invokable-rule", | |
| 23 | + promptFile: "/path/to/rules.yaml", | |
| 24 | + }); | |
| 25 | + }); | |
| 26 | + | |
| 27 | + it("should handle a rule without name", () => { | |
| 28 | + const rule: RuleWithSource = { | |
| 29 | + rule: "Review this code", | |
| 30 | + source: "rules-block", | |
| 31 | + invokable: true, | |
| 32 | + }; | |
| 33 | + | |
| 34 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 35 | + | |
| 36 | + expect(result.name).toBe("Review this code"); | |
| 37 | + expect(result.prompt).toBe("Review this code"); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should truncate long rule text when used as name", () => { | |
| 41 | + const rule: RuleWithSource = { | |
| 42 | + rule: "This is a very long rule text that should be truncated", | |
| 43 | + source: "rules-block", | |
| 44 | + invokable: true, | |
| 45 | + }; | |
| 46 | + | |
| 47 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 48 | + | |
| 49 | + expect(result.name).toBe("This is a very long ..."); | |
| 50 | + expect(result.prompt).toBe( | |
| 51 | + "This is a very long rule text that should be truncated", | |
| 52 | + ); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("should handle a rule without description", () => { | |
| 56 | + const rule: RuleWithSource = { | |
| 57 | + name: "Test Rule", | |
| 58 | + rule: "Test rule content", | |
| 59 | + source: "rules-block", | |
| 60 | + invokable: true, | |
| 61 | + }; | |
| 62 | + | |
| 63 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 64 | + | |
| 65 | + expect(result.description).toBe(""); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + it("should use rule text as the prompt", () => { | |
| 69 | + const rule: RuleWithSource = { | |
| 70 | + name: "Explain Code", | |
| 71 | + rule: "Explain what this code does in simple terms", | |
| 72 | + source: "rules-block", | |
| 73 | + invokable: true, | |
| 74 | + }; | |
| 75 | + | |
| 76 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 77 | + | |
| 78 | + expect(result.prompt).toBe("Explain what this code does in simple terms"); | |
| 79 | + }); | |
| 80 | + | |
| 81 | + it("should always set source to 'invokable-rule'", () => { | |
| 82 | + const rule: RuleWithSource = { | |
| 83 | + name: "Test", | |
| 84 | + rule: "Test", | |
| 85 | + source: "default-chat", | |
| 86 | + invokable: true, | |
| 87 | + }; | |
| 88 | + | |
| 89 | + const result = convertRuleBlockToSlashCommand(rule); | |
| 90 | + | |
| 91 | + expect(result.source).toBe("invokable-rule"); | |
| 92 | + }); | |
| 93 | +}); |
| @@ -59,27 +59,17 @@ | ||
| 59 | 59 | |
| 60 | 60 | constructor( |
| 61 | 61 | private readonly ide: IDE, |
| 62 | - private ideSettingsPromise: Promise<IdeSettings>, | |
| 63 | 62 | private llmLogger: ILLMLogger, |
| 64 | - sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, | |
| 63 | + initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, | |
| 65 | 64 | ) { |
| 66 | - this.ide = ide; | |
| 67 | - this.ideSettingsPromise = ideSettingsPromise; | |
| 68 | - | |
| 69 | 65 | this.controlPlaneClient = new ControlPlaneClient( |
| 70 | - sessionInfoPromise, | |
| 71 | - ideSettingsPromise, | |
| 72 | - this.ide.getIdeInfo(), | |
| 66 | + initialSessionInfoPromise, | |
| 67 | + this.ide, | |
| 73 | 68 | ); |
| 74 | 69 | |
| 75 | 70 | // This profile manager will always be available |
| 76 | 71 | this.globalLocalProfileManager = new ProfileLifecycleManager( |
| 77 | - new LocalProfileLoader( | |
| 78 | - ide, | |
| 79 | - ideSettingsPromise, | |
| 80 | - this.controlPlaneClient, | |
| 81 | - this.llmLogger, | |
| 82 | - ), | |
| 72 | + new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger), | |
| 83 | 73 | this.ide, |
| 84 | 74 | ); |
| 85 | 75 | |
| @@ -97,6 +87,7 @@ | ||
| 97 | 87 | } |
| 98 | 88 | |
| 99 | 89 | private workspaceDirs: string[] | null = null; |
| 90 | + | |
| 100 | 91 | async getWorkspaceId() { |
| 101 | 92 | if (!this.workspaceDirs) { |
| 102 | 93 | this.workspaceDirs = await this.ide.getWorkspaceDirs(); |
| @@ -113,6 +104,13 @@ | ||
| 113 | 104 | const signal = this.cascadeAbortController.signal; |
| 114 | 105 | this.workspaceDirs = null; // forces workspace dirs reload |
| 115 | 106 | |
| 107 | + // Always update globalLocalProfileManager before recreating all the loaders | |
| 108 | + // during every cascadeInit so it holds the most recent controlPlaneClient. | |
| 109 | + this.globalLocalProfileManager = new ProfileLifecycleManager( | |
| 110 | + new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger), | |
| 111 | + this.ide, | |
| 112 | + ); | |
| 113 | + | |
| 116 | 114 | try { |
| 117 | 115 | const { orgs, errors } = await this.getOrgs(); |
| 118 | 116 | |
| @@ -202,6 +200,8 @@ | ||
| 202 | 200 | message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`, |
| 203 | 201 | }); |
| 204 | 202 | } |
| 203 | + } else { | |
| 204 | + PolicySingleton.getInstance().policy = null; | |
| 205 | 205 | } |
| 206 | 206 | // Load local org if not signed in or hub orgs fail |
| 207 | 207 | try { |
| @@ -246,7 +246,6 @@ | ||
| 246 | 246 | versionSlug: assistant.configResult.config?.version ?? "latest", |
| 247 | 247 | controlPlaneClient: this.controlPlaneClient, |
| 248 | 248 | ide: this.ide, |
| 249 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 250 | 249 | llmLogger: this.llmLogger, |
| 251 | 250 | rawYaml: assistant.rawYaml, |
| 252 | 251 | orgScopeId: orgScopeId, |
| @@ -367,7 +366,6 @@ | ||
| 367 | 366 | const profiles = [...assistantFiles, ...agentFiles].map((assistant) => { |
| 368 | 367 | return new LocalProfileLoader( |
| 369 | 368 | this.ide, |
| 370 | - this.ideSettingsPromise, | |
| 371 | 369 | this.controlPlaneClient, |
| 372 | 370 | this.llmLogger, |
| 373 | 371 | assistant, |
| @@ -392,7 +390,6 @@ | ||
| 392 | 390 | |
| 393 | 391 | // Ide settings change: refresh session and cascade refresh from the top |
| 394 | 392 | async updateIdeSettings(ideSettings: IdeSettings) { |
| 395 | - this.ideSettingsPromise = Promise.resolve(ideSettings); | |
| 396 | 393 | this.abortCascade(); |
| 397 | 394 | await this.cascadeInit("IDE settings update"); |
| 398 | 395 | } |
| @@ -430,8 +427,7 @@ | ||
| 430 | 427 | if (reload) { |
| 431 | 428 | this.controlPlaneClient = new ControlPlaneClient( |
| 432 | 429 | Promise.resolve(sessionInfo), |
| 433 | - this.ideSettingsPromise, | |
| 434 | - this.ide.getIdeInfo(), | |
| 430 | + this.ide, | |
| 435 | 431 | ); |
| 436 | 432 | this.abortCascade(); |
| 437 | 433 | await this.cascadeInit("Control plane session info update"); |
| @@ -1,32 +1,32 @@ | ||
| 1 | 1 | import { IDE } from ".."; |
| 2 | 2 | import { joinPathsToUri } from "../util/uri"; |
| 3 | 3 | |
| 4 | -const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file | |
| 5 | -# It is used to define custom AI assistants within Continue | |
| 6 | -# Each assistant file can be accessed by selecting it from the assistant dropdown | |
| 4 | +const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file | |
| 5 | +# It is used to define custom AI agents within Continue | |
| 6 | +# Each agent file can be accessed by selecting it from the agent dropdown | |
| 7 | 7 | |
| 8 | -# To learn more, see the full assistant reference: https://docs.continue.dev/reference | |
| 8 | +# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference | |
| 9 | 9 | |
| 10 | -name: Example Assistant | |
| 10 | +name: Example Agent | |
| 11 | 11 | version: 1.0.0 |
| 12 | 12 | schema: v1 |
| 13 | 13 | |
| 14 | -# Models define which AI models this assistant can use | |
| 14 | +# Models define which AI models this agent can use | |
| 15 | +# https://docs.continue.dev/customization/models | |
| 15 | 16 | models: |
| 16 | 17 | - name: my gpt-5 |
| 17 | 18 | provider: openai |
| 18 | 19 | model: gpt-5 |
| 19 | - apiKey: YOUR_API_KEY_HERE | |
| 20 | + apiKey: YOUR_OPENAI_API_KEY_HERE | |
| 21 | + - uses: ollama/qwen2.5-coder-7b | |
| 22 | + - uses: anthropic/claude-4-sonnet | |
| 23 | + with: | |
| 24 | + ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }} | |
| 20 | 25 | |
| 21 | -# Context providers define what information the assistant can access | |
| 22 | -context: | |
| 23 | - - provider: code | |
| 24 | - - provider: docs | |
| 25 | - - provider: diff | |
| 26 | - - provider: terminal | |
| 27 | - - provider: problems | |
| 28 | - - provider: folder | |
| 29 | - - provider: codebase | |
| 26 | +# MCP Servers the agent can use | |
| 27 | +# https://docs.continue.dev/customization/mcp-tools | |
| 28 | +mcpServers: | |
| 29 | + - uses: anthropic/memory-mcp | |
| 30 | 30 | `; |
| 31 | 31 | |
| 32 | 32 | export async function createNewAssistantFile( |
| @@ -42,7 +42,7 @@ | ||
| 42 | 42 | |
| 43 | 43 | const baseDirUri = joinPathsToUri( |
| 44 | 44 | workspaceDirs[0], |
| 45 | - assistantPath ?? ".continue/assistants", | |
| 45 | + assistantPath ?? ".continue/agents", | |
| 46 | 46 | ); |
| 47 | 47 | |
| 48 | 48 | // Find the first available filename |
| @@ -50,10 +50,7 @@ | ||
| 50 | 50 | let assistantFileUri: string; |
| 51 | 51 | do { |
| 52 | 52 | const suffix = counter === 0 ? "" : `-${counter}`; |
| 53 | - assistantFileUri = joinPathsToUri( | |
| 54 | - baseDirUri, | |
| 55 | - `new-assistant${suffix}.yaml`, | |
| 56 | - ); | |
| 53 | + assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`); | |
| 57 | 54 | counter++; |
| 58 | 55 | } while (await ide.fileExists(assistantFileUri)); |
| 59 | 56 |
| @@ -57,6 +57,7 @@ | ||
| 57 | 57 | } from "../util/paths"; |
| 58 | 58 | import { localPathToUri } from "../util/pathToUri"; |
| 59 | 59 | |
| 60 | +import { PolicySingleton } from "../control-plane/PolicySingleton"; | |
| 60 | 61 | import CustomContextProviderClass from "../context/providers/CustomContextProvider"; |
| 61 | 62 | import { getBaseToolDefinitions } from "../tools"; |
| 62 | 63 | import { resolveRelativePathInDir } from "../util/ideUtils"; |
| @@ -214,8 +215,8 @@ | ||
| 214 | 215 | // Prepare models |
| 215 | 216 | for (const model of models) { |
| 216 | 217 | model.requestOptions = { |
| 217 | - ...model.requestOptions, | |
| 218 | 218 | ...config.requestOptions, |
| 219 | + ...model.requestOptions, | |
| 219 | 220 | }; |
| 220 | 221 | if (roles !== undefined) { |
| 221 | 222 | model.roles = model.roles ?? roles; |
| @@ -544,16 +545,23 @@ | ||
| 544 | 545 | |
| 545 | 546 | // Trigger MCP server refreshes (Config is reloaded again once connected!) |
| 546 | 547 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 547 | - mcpManager.setConnections( | |
| 548 | - (config.experimental?.modelContextProtocolServers ?? []).map( | |
| 549 | - (server, index) => ({ | |
| 550 | - id: `continue-mcp-server-${index + 1}`, | |
| 551 | - name: `MCP Server`, | |
| 552 | - ...server, | |
| 553 | - }), | |
| 554 | - ), | |
| 555 | - false, | |
| 556 | - ); | |
| 548 | + | |
| 549 | + const orgPolicy = PolicySingleton.getInstance().policy; | |
| 550 | + if (orgPolicy?.policy?.allowMcpServers === false) { | |
| 551 | + await mcpManager.shutdown(); | |
| 552 | + } else { | |
| 553 | + mcpManager.setConnections( | |
| 554 | + (config.experimental?.modelContextProtocolServers ?? []).map( | |
| 555 | + (server, index) => ({ | |
| 556 | + id: `continue-mcp-server-${index + 1}`, | |
| 557 | + name: `MCP Server`, | |
| 558 | + ...server, | |
| 559 | + requestOptions: config.requestOptions, | |
| 560 | + }), | |
| 561 | + ), | |
| 562 | + false, | |
| 563 | + ); | |
| 564 | + } | |
| 557 | 565 | |
| 558 | 566 | // Handle experimental modelRole config values for apply and edit |
| 559 | 567 | const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; |
| 2 | 2 | |
| 3 | 3 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 4 | -import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; | |
| 4 | +import { ContinueConfig, IDE, ILLMLogger } from "../../index.js"; | |
| 5 | 5 | import { ProfileDescription } from "../ProfileLifecycleManager.js"; |
| 6 | 6 | |
| 7 | 7 | import { getPrimaryConfigFilePath } from "../../util/paths.js"; |
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | |
| 16 | 16 | constructor( |
| 17 | 17 | private ide: IDE, |
| 18 | - private ideSettingsPromise: Promise<IdeSettings>, | |
| 19 | 18 | private controlPlaneClient: ControlPlaneClient, |
| 20 | 19 | private llmLogger: ILLMLogger, |
| 21 | 20 | private overrideAssistantFile?: |
| @@ -57,7 +56,6 @@ | ||
| 57 | 56 | async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> { |
| 58 | 57 | const result = await doLoadConfig({ |
| 59 | 58 | ide: this.ide, |
| 60 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 61 | 59 | controlPlaneClient: this.controlPlaneClient, |
| 62 | 60 | llmLogger: this.llmLogger, |
| 63 | 61 | profileId: this.description.id, |
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 4 | 4 | import { getControlPlaneEnv } from "../../control-plane/env.js"; |
| 5 | -import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; | |
| 5 | +import { ContinueConfig, IDE, ILLMLogger } from "../../index.js"; | |
| 6 | 6 | import { ProfileDescription } from "../ProfileLifecycleManager.js"; |
| 7 | 7 | |
| 8 | 8 | import doLoadConfig from "./doLoadConfig.js"; |
| @@ -28,7 +28,6 @@ | ||
| 28 | 28 | private readonly versionSlug: string; |
| 29 | 29 | private readonly controlPlaneClient: ControlPlaneClient; |
| 30 | 30 | private readonly ide: IDE; |
| 31 | - private ideSettingsPromise: Promise<IdeSettings>; | |
| 32 | 31 | private llmLogger: ILLMLogger; |
| 33 | 32 | readonly description: ProfileDescription; |
| 34 | 33 | private readonly orgScopeId: string | null; |
| @@ -41,7 +40,6 @@ | ||
| 41 | 40 | versionSlug, |
| 42 | 41 | controlPlaneClient, |
| 43 | 42 | ide, |
| 44 | - ideSettingsPromise, | |
| 45 | 43 | llmLogger, |
| 46 | 44 | description, |
| 47 | 45 | orgScopeId, |
| @@ -53,7 +51,6 @@ | ||
| 53 | 51 | versionSlug: string; |
| 54 | 52 | controlPlaneClient: ControlPlaneClient; |
| 55 | 53 | ide: IDE; |
| 56 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 57 | 54 | llmLogger: ILLMLogger; |
| 58 | 55 | description: ProfileDescription; |
| 59 | 56 | orgScopeId: string | null; |
| @@ -65,7 +62,6 @@ | ||
| 65 | 62 | this.versionSlug = versionSlug; |
| 66 | 63 | this.controlPlaneClient = controlPlaneClient; |
| 67 | 64 | this.ide = ide; |
| 68 | - this.ideSettingsPromise = ideSettingsPromise; | |
| 69 | 65 | this.llmLogger = llmLogger; |
| 70 | 66 | this.description = description; |
| 71 | 67 | this.orgScopeId = orgScopeId; |
| @@ -79,7 +75,6 @@ | ||
| 79 | 75 | versionSlug, |
| 80 | 76 | controlPlaneClient, |
| 81 | 77 | ide, |
| 82 | - ideSettingsPromise, | |
| 83 | 78 | llmLogger, |
| 84 | 79 | rawYaml, |
| 85 | 80 | orgScopeId, |
| @@ -91,12 +86,11 @@ | ||
| 91 | 86 | versionSlug: string; |
| 92 | 87 | controlPlaneClient: ControlPlaneClient; |
| 93 | 88 | ide: IDE; |
| 94 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 95 | 89 | llmLogger: ILLMLogger; |
| 96 | 90 | rawYaml: string; |
| 97 | 91 | orgScopeId: string | null; |
| 98 | 92 | }): Promise<PlatformProfileLoader> { |
| 99 | - const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); | |
| 93 | + const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings()); | |
| 100 | 94 | |
| 101 | 95 | const description: ProfileDescription = { |
| 102 | 96 | id: `${ownerSlug}/${packageSlug}`, |
| @@ -121,7 +115,6 @@ | ||
| 121 | 115 | versionSlug, |
| 122 | 116 | controlPlaneClient, |
| 123 | 117 | ide, |
| 124 | - ideSettingsPromise, | |
| 125 | 118 | llmLogger, |
| 126 | 119 | description, |
| 127 | 120 | orgScopeId, |
| @@ -139,7 +132,6 @@ | ||
| 139 | 132 | |
| 140 | 133 | const results = await doLoadConfig({ |
| 141 | 134 | ide: this.ide, |
| 142 | - ideSettingsPromise: this.ideSettingsPromise, | |
| 143 | 135 | controlPlaneClient: this.controlPlaneClient, |
| 144 | 136 | llmLogger: this.llmLogger, |
| 145 | 137 | overrideConfigYaml: this.configResult.config, |
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | import { |
| 12 | 12 | ContinueConfig, |
| 13 | 13 | IDE, |
| 14 | - IdeSettings, | |
| 15 | 14 | ILLMLogger, |
| 16 | 15 | RuleWithSource, |
| 17 | 16 | SerializedContinueConfig, |
| @@ -70,7 +69,6 @@ | ||
| 70 | 69 | } |
| 71 | 70 | export default async function doLoadConfig(options: { |
| 72 | 71 | ide: IDE; |
| 73 | - ideSettingsPromise: Promise<IdeSettings>; | |
| 74 | 72 | controlPlaneClient: ControlPlaneClient; |
| 75 | 73 | llmLogger: ILLMLogger; |
| 76 | 74 | overrideConfigJson?: SerializedContinueConfig; |
| @@ -82,7 +80,6 @@ | ||
| 82 | 80 | }): Promise<ConfigResult<ContinueConfig>> { |
| 83 | 81 | const { |
| 84 | 82 | ide, |
| 85 | - ideSettingsPromise, | |
| 86 | 83 | controlPlaneClient, |
| 87 | 84 | llmLogger, |
| 88 | 85 | overrideConfigJson, |
| @@ -95,7 +92,7 @@ | ||
| 95 | 92 | |
| 96 | 93 | const ideInfo = await ide.getIdeInfo(); |
| 97 | 94 | const uniqueId = await ide.getUniqueId(); |
| 98 | - const ideSettings = await ideSettingsPromise; | |
| 95 | + const ideSettings = await ide.getIdeSettings(); | |
| 99 | 96 | const workOsAccessToken = await controlPlaneClient.getAccessToken(); |
| 100 | 97 | const isSignedIn = await controlPlaneClient.isSignedIn(); |
| 101 | 98 | |
| @@ -190,7 +187,6 @@ | ||
| 190 | 187 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 191 | 188 | const mcpServerStatuses = mcpManager.getStatuses(); |
| 192 | 189 | |
| 193 | - // Slightly hacky just need connection's client to make slash command for now | |
| 194 | 190 | const serializableStatuses = mcpServerStatuses.map((server) => { |
| 195 | 191 | const { client, ...rest } = server; |
| 196 | 192 | return rest; |
| @@ -332,12 +328,14 @@ | ||
| 332 | 328 | } |
| 333 | 329 | } |
| 334 | 330 | |
| 335 | - if ( | |
| 336 | - PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === | |
| 337 | - false | |
| 338 | - ) { | |
| 331 | + // Org policies | |
| 332 | + const policy = PolicySingleton.getInstance().policy?.policy; | |
| 333 | + if (policy?.allowAnonymousTelemetry === false) { | |
| 339 | 334 | newConfig.allowAnonymousTelemetry = false; |
| 340 | 335 | } |
| 336 | + if (policy?.allowCodebaseIndexing === false) { | |
| 337 | + newConfig.disableIndexing = true; | |
| 338 | + } | |
| 341 | 339 | |
| 342 | 340 | // Setup telemetry only after (and if) we know it is enabled |
| 343 | 341 | await Telemetry.setup( |
| @@ -372,7 +370,7 @@ | ||
| 372 | 370 | const useOnPremProxy = |
| 373 | 371 | controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; |
| 374 | 372 | |
| 375 | - const env = await getControlPlaneEnv(ideSettingsPromise); | |
| 373 | + const env = await getControlPlaneEnv(Promise.resolve(ideSettings)); | |
| 376 | 374 | let controlPlaneProxyUrl: string = useOnPremProxy |
| 377 | 375 | ? controlPlane?.proxyUrl |
| 378 | 376 | : env.DEFAULT_CONTROL_PLANE_PROXY_URL; |
| @@ -280,11 +280,6 @@ | ||
| 280 | 280 | replacement: string; |
| 281 | 281 | } |
| 282 | 282 | |
| 283 | - export interface ContinueError { | |
| 284 | - title: string; | |
| 285 | - message: string; | |
| 286 | - } | |
| 287 | - | |
| 288 | 283 | export interface CompletionOptions extends BaseCompletionOptions { |
| 289 | 284 | model: string; |
| 290 | 285 | } |
| @@ -692,6 +687,8 @@ | ||
| 692 | 687 | |
| 693 | 688 | openUrl(url: string): Promise<void>; |
| 694 | 689 | |
| 690 | + getExternalUri?(uri: string): Promise<string>; | |
| 691 | + | |
| 695 | 692 | runCommand(command: string): Promise<void>; |
| 696 | 693 | |
| 697 | 694 | saveFile(filepath: string): Promise<void>; |
| @@ -1061,6 +1058,7 @@ | ||
| 1061 | 1058 | filepath?: string; |
| 1062 | 1059 | fileContent?: string; |
| 1063 | 1060 | originalFileContent?: string; |
| 1061 | + autoFormattingDiff?: string; | |
| 1064 | 1062 | } |
| 1065 | 1063 | |
| 1066 | 1064 | export interface RangeInFileWithContents { |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | ConfigResult, |
| 5 | 5 | ConfigValidationError, |
| 6 | 6 | isAssistantUnrolledNonNullable, |
| 7 | + mergeConfigYamlRequestOptions, | |
| 7 | 8 | mergeUnrolledAssistants, |
| 8 | 9 | ModelRole, |
| 9 | 10 | PackageIdentifier, |
| @@ -24,7 +25,9 @@ | ||
| 24 | 25 | |
| 25 | 26 | import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; |
| 26 | 27 | import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; |
| 28 | +import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; | |
| 27 | 29 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 30 | +import { PolicySingleton } from "../../control-plane/PolicySingleton"; | |
| 28 | 31 | import { getBaseToolDefinitions } from "../../tools"; |
| 29 | 32 | import { getCleanUriPath } from "../../util/uri"; |
| 30 | 33 | import { loadConfigContextProviders } from "../loadContextProviders"; |
| @@ -32,10 +35,7 @@ | ||
| 32 | 35 | import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks"; |
| 33 | 36 | import { LocalPlatformClient } from "./LocalPlatformClient"; |
| 34 | 37 | import { llmsFromModelConfig } from "./models"; |
| 35 | -import { | |
| 36 | - convertYamlMcpToContinueMcp, | |
| 37 | - convertYamlRuleToContinueRule, | |
| 38 | -} from "./yamlToContinueConfig"; | |
| 38 | +import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig"; | |
| 39 | 39 | |
| 40 | 40 | async function loadConfigYaml(options: { |
| 41 | 41 | overrideConfigYaml: AssistantUnrolled | undefined; |
| @@ -153,16 +153,15 @@ | ||
| 153 | 153 | }; |
| 154 | 154 | } |
| 155 | 155 | |
| 156 | -async function configYamlToContinueConfig(options: { | |
| 156 | +export async function configYamlToContinueConfig(options: { | |
| 157 | 157 | config: AssistantUnrolled; |
| 158 | 158 | ide: IDE; |
| 159 | - ideSettings: IdeSettings; | |
| 160 | 159 | ideInfo: IdeInfo; |
| 161 | 160 | uniqueId: string; |
| 162 | 161 | llmLogger: ILLMLogger; |
| 163 | 162 | workOsAccessToken: string | undefined; |
| 164 | 163 | }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { |
| 165 | - let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options; | |
| 164 | + let { config, ide, ideInfo, uniqueId, llmLogger } = options; | |
| 166 | 165 | |
| 167 | 166 | const localErrors: ConfigValidationError[] = []; |
| 168 | 167 | |
| @@ -190,6 +189,7 @@ | ||
| 190 | 189 | summarize: null, |
| 191 | 190 | }, |
| 192 | 191 | rules: [], |
| 192 | + requestOptions: { ...config.requestOptions }, | |
| 193 | 193 | }; |
| 194 | 194 | |
| 195 | 195 | // Right now, if there are any missing packages in the config, then we will just throw an error |
| @@ -207,10 +207,30 @@ | ||
| 207 | 207 | } |
| 208 | 208 | |
| 209 | 209 | for (const rule of config.rules ?? []) { |
| 210 | - continueConfig.rules.push(convertYamlRuleToContinueRule(rule)); | |
| 210 | + const convertedRule = convertYamlRuleToContinueRule(rule); | |
| 211 | + continueConfig.rules.push(convertedRule); | |
| 212 | + | |
| 213 | + // Convert invokable rules to slash commands | |
| 214 | + if (convertedRule.invokable) { | |
| 215 | + try { | |
| 216 | + const slashCommand = convertRuleBlockToSlashCommand(convertedRule); | |
| 217 | + continueConfig.slashCommands?.push(slashCommand); | |
| 218 | + } catch (e) { | |
| 219 | + localErrors.push({ | |
| 220 | + message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`, | |
| 221 | + fatal: false, | |
| 222 | + }); | |
| 223 | + } | |
| 224 | + } | |
| 211 | 225 | } |
| 212 | 226 | |
| 213 | - continueConfig.data = config.data; | |
| 227 | + continueConfig.data = config.data?.map((d) => ({ | |
| 228 | + ...d, | |
| 229 | + requestOptions: mergeConfigYamlRequestOptions( | |
| 230 | + d.requestOptions, | |
| 231 | + continueConfig.requestOptions, | |
| 232 | + ), | |
| 233 | + })); | |
| 214 | 234 | continueConfig.docs = config.docs?.map((doc) => ({ |
| 215 | 235 | title: doc.name, |
| 216 | 236 | startUrl: doc.startUrl, |
| @@ -234,12 +254,6 @@ | ||
| 234 | 254 | }); |
| 235 | 255 | }); |
| 236 | 256 | |
| 237 | - continueConfig.experimental = { | |
| 238 | - modelContextProtocolServers: config.mcpServers?.map( | |
| 239 | - convertYamlMcpToContinueMcp, | |
| 240 | - ), | |
| 241 | - }; | |
| 242 | - | |
| 243 | 257 | // Prompt files - |
| 244 | 258 | try { |
| 245 | 259 | const promptFiles = await getAllPromptFiles(ide, undefined, true); |
| @@ -291,9 +305,7 @@ | ||
| 291 | 305 | try { |
| 292 | 306 | const llms = await llmsFromModelConfig({ |
| 293 | 307 | model, |
| 294 | - ide, | |
| 295 | 308 | uniqueId, |
| 296 | - ideSettings, | |
| 297 | 309 | llmLogger, |
| 298 | 310 | config: continueConfig, |
| 299 | 311 | }); |
| @@ -378,21 +390,31 @@ | ||
| 378 | 390 | |
| 379 | 391 | // Trigger MCP server refreshes (Config is reloaded again once connected!) |
| 380 | 392 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 381 | - mcpManager.setConnections( | |
| 382 | - (config.mcpServers ?? []).map((server) => ({ | |
| 383 | - id: server.name, | |
| 384 | - name: server.name, | |
| 385 | - sourceFile: server.sourceFile, | |
| 386 | - transport: { | |
| 387 | - type: "stdio", | |
| 388 | - args: [], | |
| 389 | - ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 390 | - }, | |
| 391 | - timeout: server.connectionTimeout, | |
| 392 | - })), | |
| 393 | - false, | |
| 394 | - { ide }, | |
| 395 | - ); | |
| 393 | + | |
| 394 | + const orgPolicy = PolicySingleton.getInstance().policy; | |
| 395 | + if (orgPolicy?.policy?.allowMcpServers === false) { | |
| 396 | + await mcpManager.shutdown(); | |
| 397 | + } else { | |
| 398 | + mcpManager.setConnections( | |
| 399 | + (config.mcpServers ?? []).map((server) => ({ | |
| 400 | + id: server.name, | |
| 401 | + name: server.name, | |
| 402 | + sourceFile: server.sourceFile, | |
| 403 | + transport: { | |
| 404 | + type: "stdio", | |
| 405 | + args: [], | |
| 406 | + requestOptions: mergeConfigYamlRequestOptions( | |
| 407 | + server.requestOptions, | |
| 408 | + config.requestOptions, | |
| 409 | + ), | |
| 410 | + ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 411 | + }, | |
| 412 | + timeout: server.connectionTimeout, | |
| 413 | + })), | |
| 414 | + false, | |
| 415 | + { ide }, | |
| 416 | + ); | |
| 417 | + } | |
| 396 | 418 | |
| 397 | 419 | return { config: continueConfig, errors: localErrors }; |
| 398 | 420 | } |
| @@ -443,7 +465,6 @@ | ||
| 443 | 465 | await configYamlToContinueConfig({ |
| 444 | 466 | config: configYamlResult.config, |
| 445 | 467 | ide, |
| 446 | - ideSettings, | |
| 447 | 468 | ideInfo, |
| 448 | 469 | uniqueId, |
| 449 | 470 | llmLogger, |
| @@ -1,12 +1,9 @@ | ||
| 1 | -import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | - | |
| 3 | 1 | import { |
| 4 | - ContinueConfig, | |
| 5 | - IDE, | |
| 6 | - IdeSettings, | |
| 7 | - ILLMLogger, | |
| 8 | - LLMOptions, | |
| 9 | -} from "../.."; | |
| 2 | + mergeConfigYamlRequestOptions, | |
| 3 | + ModelConfig, | |
| 4 | +} from "@continuedev/config-yaml"; | |
| 5 | + | |
| 6 | +import { ContinueConfig, ILLMLogger, LLMOptions } from "../.."; | |
| 10 | 7 | import { BaseLLM } from "../../llm"; |
| 11 | 8 | import { LLMClasses } from "../../llm/llms"; |
| 12 | 9 | |
| @@ -29,14 +26,12 @@ | ||
| 29 | 26 | async function modelConfigToBaseLLM({ |
| 30 | 27 | model, |
| 31 | 28 | uniqueId, |
| 32 | - ideSettings, | |
| 33 | 29 | llmLogger, |
| 34 | 30 | config, |
| 35 | 31 | isFromAutoDetect, |
| 36 | 32 | }: { |
| 37 | 33 | model: ModelConfig; |
| 38 | 34 | uniqueId: string; |
| 39 | - ideSettings: IdeSettings; | |
| 40 | 35 | llmLogger: ILLMLogger; |
| 41 | 36 | config: ContinueConfig; |
| 42 | 37 | isFromAutoDetect?: boolean; |
| @@ -49,6 +44,11 @@ | ||
| 49 | 44 | |
| 50 | 45 | const { capabilities, ...rest } = model; |
| 51 | 46 | |
| 47 | + const mergedRequestOptions = mergeConfigYamlRequestOptions( | |
| 48 | + rest.requestOptions, | |
| 49 | + config.requestOptions, | |
| 50 | + ); | |
| 51 | + | |
| 52 | 52 | let options: LLMOptions = { |
| 53 | 53 | ...rest, |
| 54 | 54 | contextLength: model.defaultCompletionOptions?.contextLength, |
| @@ -74,6 +74,7 @@ | ||
| 74 | 74 | }, |
| 75 | 75 | autocompleteOptions: model.autocompleteOptions, |
| 76 | 76 | isFromAutoDetect, |
| 77 | + requestOptions: mergedRequestOptions, | |
| 77 | 78 | }; |
| 78 | 79 | |
| 79 | 80 | // Model capabilities - need to be undefined if not found |
| @@ -154,17 +155,13 @@ | ||
| 154 | 155 | async function autodetectModels({ |
| 155 | 156 | llm, |
| 156 | 157 | model, |
| 157 | - ide, | |
| 158 | 158 | uniqueId, |
| 159 | - ideSettings, | |
| 160 | 159 | llmLogger, |
| 161 | 160 | config, |
| 162 | 161 | }: { |
| 163 | 162 | llm: BaseLLM; |
| 164 | 163 | model: ModelConfig; |
| 165 | - ide: IDE; | |
| 166 | 164 | uniqueId: string; |
| 167 | - ideSettings: IdeSettings; | |
| 168 | 165 | llmLogger: ILLMLogger; |
| 169 | 166 | config: ContinueConfig; |
| 170 | 167 | }): Promise<BaseLLM[]> { |
| @@ -183,7 +180,6 @@ | ||
| 183 | 180 | name: modelName, |
| 184 | 181 | }, |
| 185 | 182 | uniqueId, |
| 186 | - ideSettings, | |
| 187 | 183 | llmLogger, |
| 188 | 184 | config, |
| 189 | 185 | isFromAutoDetect: true, |
| @@ -199,23 +195,18 @@ | ||
| 199 | 195 | |
| 200 | 196 | export async function llmsFromModelConfig({ |
| 201 | 197 | model, |
| 202 | - ide, | |
| 203 | 198 | uniqueId, |
| 204 | - ideSettings, | |
| 205 | 199 | llmLogger, |
| 206 | 200 | config, |
| 207 | 201 | }: { |
| 208 | 202 | model: ModelConfig; |
| 209 | - ide: IDE; | |
| 210 | 203 | uniqueId: string; |
| 211 | - ideSettings: IdeSettings; | |
| 212 | 204 | llmLogger: ILLMLogger; |
| 213 | 205 | config: ContinueConfig; |
| 214 | 206 | }): Promise<BaseLLM[]> { |
| 215 | 207 | const baseLlm = await modelConfigToBaseLLM({ |
| 216 | 208 | model, |
| 217 | 209 | uniqueId, |
| 218 | - ideSettings, | |
| 219 | 210 | llmLogger, |
| 220 | 211 | config, |
| 221 | 212 | }); |
| @@ -227,9 +218,7 @@ | ||
| 227 | 218 | const models = await autodetectModels({ |
| 228 | 219 | llm: baseLlm, |
| 229 | 220 | model, |
| 230 | - ide, | |
| 231 | 221 | uniqueId, |
| 232 | - ideSettings, | |
| 233 | 222 | llmLogger, |
| 234 | 223 | config, |
| 235 | 224 | }); |
| @@ -0,0 +1,355 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | + | |
| 4 | +import { ContinueConfig, ILLMLogger } from "../.."; | |
| 5 | +import { llmsFromModelConfig } from "./models"; | |
| 6 | + | |
| 7 | +// Mock the LLM classes | |
| 8 | +vi.mock("../../llm/llms", () => ({ | |
| 9 | + LLMClasses: [ | |
| 10 | + class MockOpenAI { | |
| 11 | + static providerName = "openai"; | |
| 12 | + static defaultOptions = { | |
| 13 | + completionOptions: { | |
| 14 | + maxTokens: 2048, | |
| 15 | + }, | |
| 16 | + }; | |
| 17 | + | |
| 18 | + constructor(options: any) { | |
| 19 | + Object.assign(this, options); | |
| 20 | + } | |
| 21 | + | |
| 22 | + async listModels() { | |
| 23 | + return ["gpt-4", "gpt-3.5-turbo"]; | |
| 24 | + } | |
| 25 | + }, | |
| 26 | + class MockAnthropic { | |
| 27 | + static providerName = "anthropic"; | |
| 28 | + static defaultOptions = { | |
| 29 | + completionOptions: { | |
| 30 | + maxTokens: 4096, | |
| 31 | + }, | |
| 32 | + }; | |
| 33 | + | |
| 34 | + constructor(options: any) { | |
| 35 | + Object.assign(this, options); | |
| 36 | + } | |
| 37 | + | |
| 38 | + async listModels() { | |
| 39 | + return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"]; | |
| 40 | + } | |
| 41 | + }, | |
| 42 | + ], | |
| 43 | +})); | |
| 44 | + | |
| 45 | +describe("llmsFromModelConfig requestOptions merging", () => { | |
| 46 | + let mockLLMLogger: ILLMLogger; | |
| 47 | + let mockConfig: ContinueConfig; | |
| 48 | + | |
| 49 | + beforeEach(() => { | |
| 50 | + mockLLMLogger = { log: vi.fn() } as any; | |
| 51 | + mockConfig = { | |
| 52 | + requestOptions: { | |
| 53 | + timeout: 30000, | |
| 54 | + headers: { | |
| 55 | + "User-Agent": "Continue/1.0.0", | |
| 56 | + }, | |
| 57 | + proxy: "global-proxy", | |
| 58 | + }, | |
| 59 | + contextProviders: [], | |
| 60 | + mcpServerStatuses: [], | |
| 61 | + rules: [], | |
| 62 | + selectedModelByRole: { | |
| 63 | + apply: null, | |
| 64 | + autocomplete: null, | |
| 65 | + chat: null, | |
| 66 | + edit: null, | |
| 67 | + embed: null, | |
| 68 | + rerank: null, | |
| 69 | + summarize: null, | |
| 70 | + }, | |
| 71 | + modelsByRole: { | |
| 72 | + apply: [], | |
| 73 | + autocomplete: [], | |
| 74 | + chat: [], | |
| 75 | + edit: [], | |
| 76 | + embed: [], | |
| 77 | + rerank: [], | |
| 78 | + summarize: [], | |
| 79 | + }, | |
| 80 | + slashCommands: [], | |
| 81 | + tools: [], | |
| 82 | + allowAnonymousTelemetry: false, | |
| 83 | + } as ContinueConfig; | |
| 84 | + vi.clearAllMocks(); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("should merge model requestOptions with config requestOptions", async () => { | |
| 88 | + const model: ModelConfig = { | |
| 89 | + name: "test-openai", | |
| 90 | + provider: "openai", | |
| 91 | + model: "gpt-4", | |
| 92 | + requestOptions: { | |
| 93 | + timeout: 60000, | |
| 94 | + headers: { | |
| 95 | + Authorization: "Bearer token123", | |
| 96 | + }, | |
| 97 | + proxy: "model-proxy", | |
| 98 | + }, | |
| 99 | + }; | |
| 100 | + | |
| 101 | + const result = await llmsFromModelConfig({ | |
| 102 | + model, | |
| 103 | + uniqueId: "test-id", | |
| 104 | + llmLogger: mockLLMLogger, | |
| 105 | + config: mockConfig, | |
| 106 | + }); | |
| 107 | + | |
| 108 | + expect(result).toHaveLength(1); | |
| 109 | + const llm = result[0]; | |
| 110 | + | |
| 111 | + // The LLM should have merged requestOptions | |
| 112 | + expect(llm.requestOptions).toEqual({ | |
| 113 | + timeout: 60000, // model-specific takes precedence | |
| 114 | + headers: { | |
| 115 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 116 | + Authorization: "Bearer token123", // from model | |
| 117 | + }, | |
| 118 | + proxy: "model-proxy", // model-specific takes precedence | |
| 119 | + }); | |
| 120 | + }); | |
| 121 | + | |
| 122 | + it("should use config requestOptions when model has no requestOptions", async () => { | |
| 123 | + const model: ModelConfig = { | |
| 124 | + name: "test-openai", | |
| 125 | + provider: "openai", | |
| 126 | + model: "gpt-4", | |
| 127 | + // no requestOptions | |
| 128 | + }; | |
| 129 | + | |
| 130 | + const result = await llmsFromModelConfig({ | |
| 131 | + model, | |
| 132 | + uniqueId: "test-id", | |
| 133 | + llmLogger: mockLLMLogger, | |
| 134 | + config: mockConfig, | |
| 135 | + }); | |
| 136 | + | |
| 137 | + expect(result).toHaveLength(1); | |
| 138 | + const llm = result[0]; | |
| 139 | + | |
| 140 | + // The LLM should have config requestOptions | |
| 141 | + expect(llm.requestOptions).toEqual(mockConfig.requestOptions); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should use model requestOptions when config has no requestOptions", async () => { | |
| 145 | + const model: ModelConfig = { | |
| 146 | + name: "test-openai", | |
| 147 | + provider: "openai", | |
| 148 | + model: "gpt-4", | |
| 149 | + requestOptions: { | |
| 150 | + timeout: 45000, | |
| 151 | + headers: { | |
| 152 | + "API-Key": "secret", | |
| 153 | + }, | |
| 154 | + }, | |
| 155 | + }; | |
| 156 | + | |
| 157 | + const configWithoutOptions = { ...mockConfig }; | |
| 158 | + delete configWithoutOptions.requestOptions; | |
| 159 | + | |
| 160 | + const result = await llmsFromModelConfig({ | |
| 161 | + model, | |
| 162 | + uniqueId: "test-id", | |
| 163 | + llmLogger: mockLLMLogger, | |
| 164 | + config: configWithoutOptions, | |
| 165 | + }); | |
| 166 | + | |
| 167 | + expect(result).toHaveLength(1); | |
| 168 | + const llm = result[0]; | |
| 169 | + | |
| 170 | + // The LLM should have model requestOptions | |
| 171 | + expect(llm.requestOptions).toEqual(model.requestOptions); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + it("should handle empty headers correctly in merge", async () => { | |
| 175 | + const model: ModelConfig = { | |
| 176 | + name: "test-openai", | |
| 177 | + provider: "openai", | |
| 178 | + model: "gpt-4", | |
| 179 | + requestOptions: { | |
| 180 | + timeout: 60000, | |
| 181 | + headers: {}, | |
| 182 | + }, | |
| 183 | + }; | |
| 184 | + | |
| 185 | + const configWithEmptyHeaders = { | |
| 186 | + ...mockConfig, | |
| 187 | + requestOptions: { | |
| 188 | + ...mockConfig.requestOptions!, | |
| 189 | + headers: {}, | |
| 190 | + }, | |
| 191 | + }; | |
| 192 | + | |
| 193 | + const result = await llmsFromModelConfig({ | |
| 194 | + model, | |
| 195 | + uniqueId: "test-id", | |
| 196 | + llmLogger: mockLLMLogger, | |
| 197 | + config: configWithEmptyHeaders, | |
| 198 | + }); | |
| 199 | + | |
| 200 | + expect(result).toHaveLength(1); | |
| 201 | + const llm = result[0]; | |
| 202 | + | |
| 203 | + // When headers merge to empty object, they should be undefined | |
| 204 | + expect(llm.requestOptions).toEqual({ | |
| 205 | + timeout: 60000, | |
| 206 | + proxy: "global-proxy", | |
| 207 | + headers: undefined, | |
| 208 | + }); | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should handle autodetect models with merged requestOptions", async () => { | |
| 212 | + const model: ModelConfig = { | |
| 213 | + name: "autodetect-openai", | |
| 214 | + provider: "openai", | |
| 215 | + model: "AUTODETECT", | |
| 216 | + requestOptions: { | |
| 217 | + timeout: 120000, | |
| 218 | + headers: { | |
| 219 | + "X-Custom": "autodetect", | |
| 220 | + }, | |
| 221 | + }, | |
| 222 | + }; | |
| 223 | + | |
| 224 | + const result = await llmsFromModelConfig({ | |
| 225 | + model, | |
| 226 | + uniqueId: "test-id", | |
| 227 | + llmLogger: mockLLMLogger, | |
| 228 | + config: mockConfig, | |
| 229 | + }); | |
| 230 | + | |
| 231 | + // Should return multiple models from listModels() | |
| 232 | + expect(result.length).toBeGreaterThan(0); | |
| 233 | + | |
| 234 | + // Each detected model should have the merged requestOptions | |
| 235 | + result.forEach((llm) => { | |
| 236 | + expect(llm.requestOptions).toEqual({ | |
| 237 | + timeout: 120000, // model-specific takes precedence | |
| 238 | + headers: { | |
| 239 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 240 | + "X-Custom": "autodetect", // from model | |
| 241 | + }, | |
| 242 | + proxy: "global-proxy", // from global request options | |
| 243 | + }); | |
| 244 | + }); | |
| 245 | + }); | |
| 246 | + | |
| 247 | + it("should handle unknown provider gracefully", async () => { | |
| 248 | + const model: ModelConfig = { | |
| 249 | + name: "unknown-provider", | |
| 250 | + provider: "unknown", | |
| 251 | + model: "unknown-model", | |
| 252 | + requestOptions: { | |
| 253 | + timeout: 60000, | |
| 254 | + }, | |
| 255 | + }; | |
| 256 | + | |
| 257 | + const result = await llmsFromModelConfig({ | |
| 258 | + model, | |
| 259 | + uniqueId: "test-id", | |
| 260 | + llmLogger: mockLLMLogger, | |
| 261 | + config: mockConfig, | |
| 262 | + }); | |
| 263 | + | |
| 264 | + // Should return empty array for unknown provider | |
| 265 | + expect(result).toHaveLength(0); | |
| 266 | + }); | |
| 267 | + | |
| 268 | + it("should preserve other model properties while merging requestOptions", async () => { | |
| 269 | + const model: ModelConfig = { | |
| 270 | + name: "test-anthropic", | |
| 271 | + provider: "anthropic", | |
| 272 | + model: "claude-3-5-sonnet-20241022", | |
| 273 | + roles: ["chat", "summarize"], | |
| 274 | + capabilities: ["tool_use", "image_input"], | |
| 275 | + defaultCompletionOptions: { | |
| 276 | + temperature: 0.7, | |
| 277 | + maxTokens: 1000, | |
| 278 | + }, | |
| 279 | + requestOptions: { | |
| 280 | + timeout: 90000, | |
| 281 | + }, | |
| 282 | + }; | |
| 283 | + | |
| 284 | + const result = await llmsFromModelConfig({ | |
| 285 | + model, | |
| 286 | + uniqueId: "test-id", | |
| 287 | + llmLogger: mockLLMLogger, | |
| 288 | + config: mockConfig, | |
| 289 | + }); | |
| 290 | + | |
| 291 | + expect(result).toHaveLength(1); | |
| 292 | + const llm = result[0]; | |
| 293 | + | |
| 294 | + // Should preserve model properties | |
| 295 | + expect(llm.title).toBe("test-anthropic"); | |
| 296 | + expect(llm.completionOptions?.temperature).toBe(0.7); | |
| 297 | + expect(llm.completionOptions?.maxTokens).toBe(1000); | |
| 298 | + expect(llm.capabilities?.tools).toBe(true); | |
| 299 | + expect(llm.capabilities?.uploadImage).toBe(true); | |
| 300 | + | |
| 301 | + // Should have merged requestOptions | |
| 302 | + expect(llm.requestOptions).toEqual({ | |
| 303 | + timeout: 90000, | |
| 304 | + headers: { | |
| 305 | + "User-Agent": "Continue/1.0.0", | |
| 306 | + }, | |
| 307 | + proxy: "global-proxy", | |
| 308 | + }); | |
| 309 | + }); | |
| 310 | + | |
| 311 | + it("should handle complex header merging scenarios", async () => { | |
| 312 | + const model: ModelConfig = { | |
| 313 | + name: "complex-headers", | |
| 314 | + provider: "openai", | |
| 315 | + model: "gpt-4", | |
| 316 | + requestOptions: { | |
| 317 | + headers: { | |
| 318 | + Authorization: "Bearer model-token", | |
| 319 | + Accept: "application/json", // Should override config Accept | |
| 320 | + "X-Model-Specific": "true", | |
| 321 | + }, | |
| 322 | + }, | |
| 323 | + }; | |
| 324 | + | |
| 325 | + const configWithMoreHeaders = { | |
| 326 | + ...mockConfig, | |
| 327 | + requestOptions: { | |
| 328 | + ...mockConfig.requestOptions!, | |
| 329 | + headers: { | |
| 330 | + ...mockConfig.requestOptions!.headers, | |
| 331 | + Accept: "text/plain", // Should be overridden by model | |
| 332 | + "Cache-Control": "no-cache", | |
| 333 | + }, | |
| 334 | + }, | |
| 335 | + }; | |
| 336 | + | |
| 337 | + const result = await llmsFromModelConfig({ | |
| 338 | + model, | |
| 339 | + uniqueId: "test-id", | |
| 340 | + llmLogger: mockLLMLogger, | |
| 341 | + config: configWithMoreHeaders, | |
| 342 | + }); | |
| 343 | + | |
| 344 | + expect(result).toHaveLength(1); | |
| 345 | + const llm = result[0]; | |
| 346 | + | |
| 347 | + expect(llm.requestOptions?.headers).toEqual({ | |
| 348 | + "User-Agent": "Continue/1.0.0", // from global request options | |
| 349 | + "Cache-Control": "no-cache", // from global request options | |
| 350 | + Authorization: "Bearer model-token", // from model | |
| 351 | + Accept: "application/json", // from model (overrides config) | |
| 352 | + "X-Model-Specific": "true", // from model | |
| 353 | + }); | |
| 354 | + }); | |
| 355 | +}); |
| @@ -13,8 +13,10 @@ | ||
| 13 | 13 | rule: rule.rule, |
| 14 | 14 | globs: rule.globs, |
| 15 | 15 | name: rule.name, |
| 16 | + description: rule.description, | |
| 16 | 17 | ruleFile: rule.sourceFile, |
| 17 | 18 | alwaysApply: rule.alwaysApply, |
| 19 | + invokable: rule.invokable ?? false, | |
| 18 | 20 | }; |
| 19 | 21 | } |
| 20 | 22 | } |
| @@ -1,6 +1,4 @@ | ||
| 1 | 1 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; |
| 2 | -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; | |
| 3 | - | |
| 4 | 2 | import { |
| 5 | 3 | SSEClientTransport, |
| 6 | 4 | SseError, |
| @@ -8,7 +6,8 @@ | ||
| 8 | 6 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; |
| 9 | 7 | import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; |
| 10 | 8 | import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; |
| 11 | - | |
| 9 | +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; | |
| 10 | +import { Agent as HttpsAgent } from "https"; | |
| 12 | 11 | import { |
| 13 | 12 | IDE, |
| 14 | 13 | MCPConnectionStatus, |
| @@ -53,6 +52,7 @@ | ||
| 53 | 52 | public status: MCPConnectionStatus = "not-connected"; |
| 54 | 53 | public isProtectedResource = false; |
| 55 | 54 | public errors: string[] = []; |
| 55 | + public infos: string[] = []; | |
| 56 | 56 | public prompts: MCPPrompt[] = []; |
| 57 | 57 | public tools: MCPTool[] = []; |
| 58 | 58 | public resources: MCPResource[] = []; |
| @@ -94,6 +94,7 @@ | ||
| 94 | 94 | return { |
| 95 | 95 | ...this.options, |
| 96 | 96 | errors: this.errors, |
| 97 | + infos: this.infos, | |
| 97 | 98 | prompts: this.prompts, |
| 98 | 99 | resources: this.resources, |
| 99 | 100 | resourceTemplates: this.resourceTemplates, |
| @@ -123,6 +124,7 @@ | ||
| 123 | 124 | this.resources = []; |
| 124 | 125 | this.resourceTemplates = []; |
| 125 | 126 | this.errors = []; |
| 127 | + this.infos = []; | |
| 126 | 128 | this.stdioOutput = { stdout: "", stderr: "" }; |
| 127 | 129 | |
| 128 | 130 | this.abortController.abort(); |
| @@ -281,6 +283,16 @@ | ||
| 281 | 283 | if (msg.includes("spawn") && msg.includes("enoent")) { |
| 282 | 284 | const command = msg.split(" ")[1]; |
| 283 | 285 | errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`; |
| 286 | + if (["uv", "uvx"].includes(command)) { | |
| 287 | + this.infos.push( | |
| 288 | + 'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>', | |
| 289 | + ); | |
| 290 | + } | |
| 291 | + if (["node", "npx"].includes(command)) { | |
| 292 | + this.infos.push( | |
| 293 | + 'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>', | |
| 294 | + ); | |
| 295 | + } | |
| 284 | 296 | } else { |
| 285 | 297 | errorMessage += "Error: " + error.message; |
| 286 | 298 | } |
| @@ -393,6 +405,11 @@ | ||
| 393 | 405 | case "websocket": |
| 394 | 406 | return new WebSocketClientTransport(new URL(options.transport.url)); |
| 395 | 407 | case "sse": |
| 408 | + const sseAgent = | |
| 409 | + options.transport.requestOptions?.verifySsl === false | |
| 410 | + ? new HttpsAgent({ rejectUnauthorized: false }) | |
| 411 | + : undefined; | |
| 412 | + | |
| 396 | 413 | return new SSEClientTransport(new URL(options.transport.url), { |
| 397 | 414 | eventSourceInit: { |
| 398 | 415 | fetch: (input, init) => |
| @@ -404,17 +421,27 @@ | ||
| 404 | 421 | | Record<string, string> |
| 405 | 422 | | undefined), |
| 406 | 423 | }, |
| 424 | + ...(sseAgent && { agent: sseAgent }), | |
| 407 | 425 | }), |
| 408 | 426 | }, |
| 409 | - requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 427 | + requestInit: { | |
| 428 | + headers: options.transport.requestOptions?.headers, | |
| 429 | + ...(sseAgent && { agent: sseAgent }), | |
| 430 | + }, | |
| 410 | 431 | }); |
| 411 | 432 | case "streamable-http": |
| 412 | - return new StreamableHTTPClientTransport( | |
| 413 | - new URL(options.transport.url), | |
| 414 | - { | |
| 415 | - requestInit: { headers: options.transport.requestOptions?.headers }, | |
| 433 | + const { url, requestOptions } = options.transport; | |
| 434 | + const streamableAgent = | |
| 435 | + requestOptions?.verifySsl === false | |
| 436 | + ? new HttpsAgent({ rejectUnauthorized: false }) | |
| 437 | + : undefined; | |
| 438 | + | |
| 439 | + return new StreamableHTTPClientTransport(new URL(url), { | |
| 440 | + requestInit: { | |
| 441 | + headers: requestOptions?.headers, | |
| 442 | + ...(streamableAgent && { agent: streamableAgent }), | |
| 416 | 443 | }, |
| 417 | - ); | |
| 444 | + }); | |
| 418 | 445 | default: |
| 419 | 446 | throw new Error( |
| 420 | 447 | `Unsupported transport type: ${(options.transport as any).type}`, |
| @@ -142,6 +142,7 @@ | ||
| 142 | 142 | expect(status).toEqual({ |
| 143 | 143 | ...options, |
| 144 | 144 | errors: [], |
| 145 | + infos: [], | |
| 145 | 146 | isProtectedResource: false, |
| 146 | 147 | prompts: [], |
| 147 | 148 | resources: [], |
| @@ -48,6 +48,21 @@ | ||
| 48 | 48 | this.connections.delete(id); |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | + async shutdown() { | |
| 52 | + if (this.connections.size > 0) { | |
| 53 | + await Promise.allSettled( | |
| 54 | + Array.from(this.connections.entries()).map(([id, connection]) => { | |
| 55 | + try { | |
| 56 | + connection.abortController.abort(); | |
| 57 | + void connection.client.close(); | |
| 58 | + } finally { | |
| 59 | + this.connections.delete(id); | |
| 60 | + } | |
| 61 | + }), | |
| 62 | + ); | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 51 | 66 | setConnections( |
| 52 | 67 | servers: MCPOptions[], |
| 53 | 68 | forceRefresh: boolean, |
| @@ -12,65 +12,121 @@ | ||
| 12 | 12 | |
| 13 | 13 | import http from "http"; |
| 14 | 14 | import url from "url"; |
| 15 | +import crypto from "crypto"; | |
| 15 | 16 | import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; |
| 16 | 17 | |
| 17 | -let authenticatingMCPContext = null as { | |
| 18 | - authenticatingServer: MCPServerStatus; | |
| 19 | - ide: IDE; | |
| 20 | -} | null; | |
| 18 | +// Use a Map to support concurrent authentications for different servers | |
| 19 | +const authenticatingContexts = new Map< | |
| 20 | + string, | |
| 21 | + { | |
| 22 | + authenticatingServer: MCPServerStatus; | |
| 23 | + ide: IDE; | |
| 24 | + state?: string; | |
| 25 | + } | |
| 26 | +>(); | |
| 27 | + | |
| 28 | +// Map state parameters to server URLs for OAuth callback matching | |
| 29 | +const stateToServerUrl = new Map<string, string>(); | |
| 21 | 30 | |
| 22 | 31 | const PORT = 3000; |
| 23 | 32 | |
| 24 | -const server = http.createServer((req, res) => { | |
| 25 | - try { | |
| 26 | - if (!req.url) { | |
| 27 | - throw new Error("no url found"); | |
| 28 | - } | |
| 33 | +let serverInstance: http.Server | null = null; | |
| 29 | 34 | |
| 30 | - const parsedUrl = url.parse(req.url, true); | |
| 31 | - if (!parsedUrl.query["code"]) { | |
| 32 | - throw new Error("no query params found"); | |
| 33 | - } | |
| 35 | +const createServerForOAuth = () => | |
| 36 | + http.createServer((req, res) => { | |
| 37 | + try { | |
| 38 | + if (!req.url) { | |
| 39 | + throw new Error("no url found"); | |
| 40 | + } | |
| 41 | + | |
| 42 | + const parsedUrl = url.parse(req.url, true); | |
| 43 | + if (!parsedUrl.query["code"]) { | |
| 44 | + throw new Error("no query params found"); | |
| 45 | + } | |
| 34 | 46 | |
| 35 | - void handleMCPOauthCode(parsedUrl.query["code"] as string); | |
| 47 | + const code = parsedUrl.query["code"] as string; | |
| 48 | + const state = parsedUrl.query["state"] as string | undefined; | |
| 36 | 49 | |
| 37 | - const html = ` | |
| 50 | + void handleMCPOauthCode(code, state); | |
| 51 | + | |
| 52 | + const html = ` | |
| 38 | 53 | <!DOCTYPE html> |
| 39 | 54 | <html> |
| 40 | 55 | <head><title>Authentication Complete</title></head> |
| 41 | 56 | <body>Authentication Complete. You can close this page now.</body> |
| 42 | 57 | </html>`; |
| 43 | 58 | |
| 44 | - res.writeHead(200, { | |
| 45 | - "Content-Type": "text/html", | |
| 46 | - }); | |
| 47 | - res.end(html); | |
| 48 | - } catch (error) { | |
| 49 | - res.writeHead(400, { "Content-Type": "text/plain" }); | |
| 50 | - res.end(`Unexpected redirect error: ${(error as Error).message}`); | |
| 51 | - } | |
| 52 | -}); | |
| 59 | + res.writeHead(200, { | |
| 60 | + "Content-Type": "text/html", | |
| 61 | + }); | |
| 62 | + res.end(html); | |
| 63 | + } catch (error) { | |
| 64 | + res.writeHead(400, { "Content-Type": "text/plain" }); | |
| 65 | + res.end(`Unexpected redirect error: ${(error as Error).message}`); | |
| 66 | + } | |
| 67 | + }); | |
| 53 | 68 | |
| 54 | 69 | type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; |
| 55 | 70 | type MCPOauthStorageKey = keyof MCPOauthStorage; |
| 56 | 71 | |
| 57 | 72 | class MCPConnectionOauthProvider implements OAuthClientProvider { |
| 58 | 73 | private globalContext: GlobalContext; |
| 74 | + private _redirectUrl: string; | |
| 75 | + private _redirectUrlInitialized: Promise<void>; | |
| 59 | 76 | |
| 60 | 77 | constructor( |
| 61 | 78 | public oauthServerUrl: string, |
| 62 | 79 | private ide: IDE, |
| 63 | 80 | ) { |
| 64 | 81 | this.globalContext = new GlobalContext(); |
| 82 | + // Set default redirect URL immediately for synchronous access | |
| 83 | + this._redirectUrl = `http://localhost:${PORT}`; | |
| 84 | + // Initialize actual redirect URL asynchronously | |
| 85 | + this._redirectUrlInitialized = this._initializeRedirectUrl(); | |
| 86 | + } | |
| 87 | + | |
| 88 | + private async _initializeRedirectUrl(): Promise<void> { | |
| 89 | + try { | |
| 90 | + // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI | |
| 91 | + if (this.ide.getExternalUri) { | |
| 92 | + const localUri = `http://localhost:${PORT}`; | |
| 93 | + const externalUri = await this.ide.getExternalUri(localUri); | |
| 94 | + this._redirectUrl = externalUri; | |
| 95 | + } | |
| 96 | + // Otherwise keep the default localhost URL | |
| 97 | + } catch (error) { | |
| 98 | + console.error("Failed to initialize redirect URL:", error); | |
| 99 | + // Keep default URL on error | |
| 100 | + } | |
| 65 | 101 | } |
| 66 | 102 | |
| 67 | 103 | get redirectUrl() { |
| 68 | - return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server? | |
| 104 | + // Always return a valid URL, even if initialization is pending | |
| 105 | + return this._redirectUrl; | |
| 106 | + } | |
| 107 | + | |
| 108 | + getRedirectUrlWithState(state: string): string { | |
| 109 | + // Add state parameter to redirect URL | |
| 110 | + const urlObj = new URL(this._redirectUrl); | |
| 111 | + urlObj.searchParams.set("state", state); | |
| 112 | + return urlObj.toString(); | |
| 113 | + } | |
| 114 | + | |
| 115 | + async ensureRedirectUrl(): Promise<string> { | |
| 116 | + // Wait for initialization to complete before returning | |
| 117 | + await this._redirectUrlInitialized; | |
| 118 | + return this._redirectUrl; | |
| 69 | 119 | } |
| 70 | 120 | |
| 71 | 121 | get clientMetadata() { |
| 122 | + // Generate state parameter if needed | |
| 123 | + const state = authenticatingContexts.get(this.oauthServerUrl)?.state; | |
| 124 | + const redirectUri = state | |
| 125 | + ? this.getRedirectUrlWithState(state) | |
| 126 | + : this.redirectUrl; | |
| 127 | + | |
| 72 | 128 | return { |
| 73 | - redirect_uris: [this.redirectUrl], | |
| 129 | + redirect_uris: [redirectUri], | |
| 74 | 130 | token_endpoint_auth_method: "none", |
| 75 | 131 | grant_types: ["authorization_code", "refresh_token"], |
| 76 | 132 | response_types: ["code"], |
| @@ -151,14 +207,28 @@ | ||
| 151 | 207 | } |
| 152 | 208 | |
| 153 | 209 | async redirectToAuthorization(authorizationUrl: URL) { |
| 154 | - if (!server.listening) { | |
| 155 | - server.listen(PORT, () => { | |
| 156 | - console.debug( | |
| 157 | - `Server started for MCP Oauth process at http://localhost:${PORT}/`, | |
| 158 | - ); | |
| 159 | - }); | |
| 210 | + // Ensure redirect URL is initialized before proceeding | |
| 211 | + await this.ensureRedirectUrl(); | |
| 212 | + | |
| 213 | + // Only create and start local server if using localhost redirect | |
| 214 | + // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism | |
| 215 | + if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) { | |
| 216 | + if (!serverInstance) { | |
| 217 | + serverInstance = createServerForOAuth(); | |
| 218 | + } | |
| 219 | + if (!serverInstance.listening) { | |
| 220 | + await new Promise<void>((resolve, reject) => { | |
| 221 | + serverInstance!.listen(PORT, () => { | |
| 222 | + console.debug( | |
| 223 | + `Server started for MCP Oauth process at http://localhost:${PORT}/`, | |
| 224 | + ); | |
| 225 | + resolve(); | |
| 226 | + }); | |
| 227 | + serverInstance!.on("error", reject); | |
| 228 | + }); | |
| 229 | + } | |
| 160 | 230 | } |
| 161 | - void this.ide.openUrl(authorizationUrl.toString()); | |
| 231 | + await this.ide.openUrl(authorizationUrl.toString()); | |
| 162 | 232 | } |
| 163 | 233 | } |
| 164 | 234 | |
| @@ -175,49 +245,109 @@ | ||
| 175 | 245 | export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { |
| 176 | 246 | const mcpServerUrl = (mcpServer.transport as SSEOptions).url; |
| 177 | 247 | const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); |
| 178 | - authenticatingMCPContext = { | |
| 248 | + // Ensure redirect URL is ready before starting auth | |
| 249 | + await authProvider.ensureRedirectUrl(); | |
| 250 | + | |
| 251 | + // Generate a unique state parameter for this auth flow | |
| 252 | + const state = crypto.randomUUID(); | |
| 253 | + | |
| 254 | + // Store context for this specific server with state | |
| 255 | + authenticatingContexts.set(mcpServerUrl, { | |
| 179 | 256 | authenticatingServer: mcpServer, |
| 180 | 257 | ide, |
| 181 | - }; | |
| 182 | - return await auth(authProvider, { | |
| 183 | - serverUrl: mcpServerUrl, | |
| 258 | + state, | |
| 184 | 259 | }); |
| 260 | + | |
| 261 | + // Map state to server URL for callback matching | |
| 262 | + stateToServerUrl.set(state, mcpServerUrl); | |
| 263 | + | |
| 264 | + try { | |
| 265 | + return await auth(authProvider, { | |
| 266 | + serverUrl: mcpServerUrl, | |
| 267 | + }); | |
| 268 | + } catch (error) { | |
| 269 | + // Clean up on error | |
| 270 | + authenticatingContexts.delete(mcpServerUrl); | |
| 271 | + stateToServerUrl.delete(state); | |
| 272 | + throw error; | |
| 273 | + } | |
| 185 | 274 | } |
| 186 | 275 | |
| 187 | 276 | /** |
| 188 | 277 | * handle the authentication code received from the oauth redirect |
| 189 | 278 | */ |
| 190 | -async function handleMCPOauthCode(authorizationCode: string) { | |
| 191 | - if (!authenticatingMCPContext) { | |
| 192 | - return; | |
| 279 | +async function handleMCPOauthCode(authorizationCode: string, state?: string) { | |
| 280 | + let serverUrl: string | undefined; | |
| 281 | + let context: | |
| 282 | + | { authenticatingServer: MCPServerStatus; ide: IDE; state?: string } | |
| 283 | + | undefined; | |
| 284 | + | |
| 285 | + if (state) { | |
| 286 | + // Use state parameter to find the correct server | |
| 287 | + serverUrl = stateToServerUrl.get(state); | |
| 288 | + if (serverUrl) { | |
| 289 | + context = authenticatingContexts.get(serverUrl); | |
| 290 | + } | |
| 291 | + } else { | |
| 292 | + // Fallback: if no state or single context, use the first one | |
| 293 | + const contexts = Array.from(authenticatingContexts.entries()); | |
| 294 | + if (contexts.length === 1) { | |
| 295 | + [serverUrl, context] = contexts[0]; | |
| 296 | + } | |
| 193 | 297 | } |
| 194 | - const { ide, authenticatingServer } = authenticatingMCPContext; | |
| 195 | - const serverUrl = (authenticatingServer.transport as SSEOptions).url; | |
| 196 | 298 | |
| 197 | - if (!serverUrl) { | |
| 198 | - void ide.showToast("error", "No MCP server url found for authentication"); | |
| 299 | + if (!context || !serverUrl) { | |
| 300 | + console.error("No matching authenticating context found for state:", state); | |
| 199 | 301 | return; |
| 200 | 302 | } |
| 201 | - if (!authorizationCode) { | |
| 202 | - void ide.showToast( | |
| 203 | - "error", | |
| 204 | - `No MCP authorization code found for ${serverUrl}`, | |
| 205 | - ); | |
| 206 | - return; | |
| 207 | - } | |
| 208 | - server.close(() => console.debug("Server for MCP Oauth process was closed")); | |
| 209 | - const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); | |
| 210 | - const authStatus = await auth(authProvider, { | |
| 211 | - serverUrl, | |
| 212 | - authorizationCode, | |
| 213 | - }); | |
| 214 | - if (authStatus === "AUTHORIZED") { | |
| 215 | - const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports | |
| 216 | - await MCPManagerSingleton.getInstance().refreshConnection( | |
| 217 | - authenticatingServer.id, | |
| 218 | - ); | |
| 303 | + | |
| 304 | + const { ide, authenticatingServer } = context; | |
| 305 | + | |
| 306 | + try { | |
| 307 | + if (!serverUrl) { | |
| 308 | + throw new Error("No MCP server url found for authentication"); | |
| 309 | + } | |
| 310 | + if (!authorizationCode) { | |
| 311 | + throw new Error(`No MCP authorization code found for ${serverUrl}`); | |
| 312 | + } | |
| 313 | + | |
| 314 | + // Close the server before processing auth | |
| 315 | + if (serverInstance) { | |
| 316 | + await new Promise<void>((resolve) => { | |
| 317 | + serverInstance!.close(() => { | |
| 318 | + console.debug("Server for MCP Oauth process was closed"); | |
| 319 | + serverInstance = null; | |
| 320 | + resolve(); | |
| 321 | + }); | |
| 322 | + }); | |
| 323 | + } | |
| 324 | + | |
| 325 | + const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); | |
| 326 | + await authProvider.ensureRedirectUrl(); | |
| 327 | + const authStatus = await auth(authProvider, { | |
| 328 | + serverUrl, | |
| 329 | + authorizationCode, | |
| 330 | + }); | |
| 331 | + | |
| 332 | + if (authStatus === "AUTHORIZED") { | |
| 333 | + const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports | |
| 334 | + await MCPManagerSingleton.getInstance().refreshConnection( | |
| 335 | + authenticatingServer.id, | |
| 336 | + ); | |
| 337 | + } | |
| 338 | + } catch (error) { | |
| 339 | + const errorMessage = error instanceof Error ? error.message : String(error); | |
| 340 | + console.error("OAuth authorization failed:", errorMessage); | |
| 341 | + if (context?.ide) { | |
| 342 | + await context.ide.showToast("error", `OAuth failed: ${errorMessage}`); | |
| 343 | + } | |
| 344 | + } finally { | |
| 345 | + // Always clean up the context and state mapping | |
| 346 | + authenticatingContexts.delete(serverUrl); | |
| 347 | + if (state) { | |
| 348 | + stateToServerUrl.delete(state); | |
| 349 | + } | |
| 219 | 350 | } |
| 220 | - authenticatingMCPContext = null; | |
| 221 | 351 | } |
| 222 | 352 | |
| 223 | 353 | export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { |
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | mockIde = { |
| 34 | 34 | openUrl: vi.fn(), |
| 35 | 35 | showToast: vi.fn(), |
| 36 | + getExternalUri: vi.fn((uri) => Promise.resolve(uri)), | |
| 36 | 37 | }; |
| 37 | 38 | |
| 38 | 39 | mockMcpServer = { |
| @@ -178,4 +179,155 @@ | ||
| 178 | 179 | }); |
| 179 | 180 | }); |
| 180 | 181 | }); |
| 182 | + | |
| 183 | + describe("redirect URL handling", () => { | |
| 184 | + test("should use getExternalUri when available for VS Code", async () => { | |
| 185 | + const vscodeIde = { | |
| 186 | + ...mockIde, | |
| 187 | + getExternalUri: vi.fn((uri) => | |
| 188 | + Promise.resolve("https://vscode.dev/redirect"), | |
| 189 | + ), | |
| 190 | + }; | |
| 191 | + | |
| 192 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 193 | + const mockAuth = vi.mocked(auth); | |
| 194 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 195 | + | |
| 196 | + await performAuth(mockMcpServer, vscodeIde); | |
| 197 | + | |
| 198 | + expect(vscodeIde.getExternalUri).toHaveBeenCalledWith( | |
| 199 | + "http://localhost:3000", | |
| 200 | + ); | |
| 201 | + }); | |
| 202 | + | |
| 203 | + test("should fallback to localhost when getExternalUri is not available", async () => { | |
| 204 | + const ideWithoutExternalUri = { | |
| 205 | + openUrl: vi.fn(() => Promise.resolve()), | |
| 206 | + showToast: vi.fn(() => Promise.resolve()), | |
| 207 | + }; | |
| 208 | + | |
| 209 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 210 | + const mockAuth = vi.mocked(auth); | |
| 211 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 212 | + | |
| 213 | + await performAuth(mockMcpServer, ideWithoutExternalUri as any); | |
| 214 | + | |
| 215 | + // Should still work without getExternalUri | |
| 216 | + expect(mockAuth).toHaveBeenCalled(); | |
| 217 | + }); | |
| 218 | + | |
| 219 | + test("should handle getExternalUri errors gracefully", async () => { | |
| 220 | + const errorIde = { | |
| 221 | + ...mockIde, | |
| 222 | + getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))), | |
| 223 | + }; | |
| 224 | + | |
| 225 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 226 | + const mockAuth = vi.mocked(auth); | |
| 227 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 228 | + | |
| 229 | + // Should not throw, should fallback to localhost | |
| 230 | + await performAuth(mockMcpServer, errorIde); | |
| 231 | + | |
| 232 | + expect(mockAuth).toHaveBeenCalled(); | |
| 233 | + }); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + describe("concurrent authentication", () => { | |
| 237 | + test("should handle multiple concurrent auth flows", async () => { | |
| 238 | + const server1 = { | |
| 239 | + id: "server-1", | |
| 240 | + transport: { type: "sse" as const, url: "https://server1.com" }, | |
| 241 | + status: "connected" as const, | |
| 242 | + errors: [], | |
| 243 | + infos: [], | |
| 244 | + isProtectedResource: false, | |
| 245 | + prompts: [], | |
| 246 | + tools: [], | |
| 247 | + resources: [], | |
| 248 | + resourceTemplates: [], | |
| 249 | + name: "server-1", | |
| 250 | + }; | |
| 251 | + const server2 = { | |
| 252 | + id: "server-2", | |
| 253 | + transport: { type: "sse" as const, url: "https://server2.com" }, | |
| 254 | + status: "connected" as const, | |
| 255 | + errors: [], | |
| 256 | + infos: [], | |
| 257 | + isProtectedResource: false, | |
| 258 | + prompts: [], | |
| 259 | + tools: [], | |
| 260 | + resources: [], | |
| 261 | + resourceTemplates: [], | |
| 262 | + name: "server-2", | |
| 263 | + }; | |
| 264 | + | |
| 265 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 266 | + const mockAuth = vi.mocked(auth); | |
| 267 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 268 | + | |
| 269 | + // Start two auth flows concurrently | |
| 270 | + const [result1, result2] = await Promise.all([ | |
| 271 | + performAuth(server1, mockIde), | |
| 272 | + performAuth(server2, mockIde), | |
| 273 | + ]); | |
| 274 | + | |
| 275 | + expect(result1).toBe("AUTHORIZED"); | |
| 276 | + expect(result2).toBe("AUTHORIZED"); | |
| 277 | + expect(mockAuth).toHaveBeenCalledTimes(2); | |
| 278 | + }); | |
| 279 | + }); | |
| 280 | + | |
| 281 | + describe("error handling", () => { | |
| 282 | + test("should clean up context on auth failure", async () => { | |
| 283 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 284 | + const mockAuth = vi.mocked(auth); | |
| 285 | + | |
| 286 | + // First successful call to set up the context | |
| 287 | + mockAuth.mockResolvedValueOnce("AUTHORIZED"); | |
| 288 | + await performAuth(mockMcpServer, mockIde); | |
| 289 | + | |
| 290 | + // Reset mock for the failure test | |
| 291 | + mockAuth.mockRejectedValueOnce(new Error("Auth failed")); | |
| 292 | + | |
| 293 | + // Second call that should fail and clean up | |
| 294 | + await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow( | |
| 295 | + "Auth failed", | |
| 296 | + ); | |
| 297 | + | |
| 298 | + // Verify auth was called twice | |
| 299 | + expect(mockAuth).toHaveBeenCalledTimes(2); | |
| 300 | + | |
| 301 | + // The context cleanup happens internally in performAuth's catch block | |
| 302 | + // We can verify it indirectly by checking that a subsequent auth call works | |
| 303 | + mockAuth.mockResolvedValueOnce("AUTHORIZED"); | |
| 304 | + const result = await performAuth(mockMcpServer, mockIde); | |
| 305 | + expect(result).toBe("AUTHORIZED"); | |
| 306 | + }); | |
| 307 | + | |
| 308 | + test("should handle missing server URL", async () => { | |
| 309 | + const invalidServer = { | |
| 310 | + id: "invalid", | |
| 311 | + transport: { type: "sse" as const, url: "" }, | |
| 312 | + status: "connected" as const, | |
| 313 | + errors: [], | |
| 314 | + infos: [], | |
| 315 | + isProtectedResource: false, | |
| 316 | + prompts: [], | |
| 317 | + tools: [], | |
| 318 | + resources: [], | |
| 319 | + resourceTemplates: [], | |
| 320 | + name: "invalid", | |
| 321 | + }; | |
| 322 | + | |
| 323 | + const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js"); | |
| 324 | + const mockAuth = vi.mocked(auth); | |
| 325 | + mockAuth.mockResolvedValue("AUTHORIZED"); | |
| 326 | + | |
| 327 | + await performAuth(invalidServer, mockIde); | |
| 328 | + | |
| 329 | + // Should still attempt auth with empty URL | |
| 330 | + expect(mockAuth).toHaveBeenCalled(); | |
| 331 | + }); | |
| 332 | + }); | |
| 181 | 333 | }); |
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | displayTitle: "Code", |
| 17 | 17 | description: "Type to search", |
| 18 | 18 | type: "submenu", |
| 19 | - dependsOnIndexing: true, | |
| 19 | + dependsOnIndexing: ["chunk", "codeSnippets"], | |
| 20 | 20 | }; |
| 21 | 21 | |
| 22 | 22 | async getContextItems( |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | description: "Automatically find relevant files", |
| 14 | 14 | type: "normal", |
| 15 | 15 | renderInlineAs: "", |
| 16 | - dependsOnIndexing: true, | |
| 16 | + dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"], | |
| 17 | 17 | }; |
| 18 | 18 | |
| 19 | 19 | async getContextItems( |
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | displayTitle: "Folder", |
| 20 | 20 | description: "Type to search", |
| 21 | 21 | type: "submenu", |
| 22 | - dependsOnIndexing: true, | |
| 22 | + dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"], | |
| 23 | 23 | }; |
| 24 | 24 | |
| 25 | 25 | async getContextItems( |
| @@ -28,11 +28,9 @@ | ||
| 28 | 28 | ): Promise<ContextProviderExtras> { |
| 29 | 29 | setUpTestDir(); |
| 30 | 30 | const ide = new FileSystemIde(TEST_DIR); |
| 31 | - const ideSettingsPromise = ide.getIdeSettings(); | |
| 32 | 31 | const llmLogger = new LLMLogger(); |
| 33 | 32 | const configHandler = new ConfigHandler( |
| 34 | 33 | ide, |
| 35 | - ideSettingsPromise, | |
| 36 | 34 | llmLogger, |
| 37 | 35 | Promise.resolve(undefined), |
| 38 | 36 | ); |
| @@ -11,10 +11,19 @@ | ||
| 11 | 11 | import fetch, { RequestInit, Response } from "node-fetch"; |
| 12 | 12 | |
| 13 | 13 | import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; |
| 14 | -import { IdeInfo, IdeSettings, ModelDescription } from "../index.js"; | |
| 14 | +import { | |
| 15 | + IDE, | |
| 16 | + ModelDescription, | |
| 17 | + Session, | |
| 18 | + BaseSessionMetadata, | |
| 19 | +} from "../index.js"; | |
| 15 | 20 | import { Logger } from "../util/Logger.js"; |
| 16 | 21 | |
| 17 | -import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js"; | |
| 22 | +import { | |
| 23 | + ControlPlaneSessionInfo, | |
| 24 | + HubSessionInfo, | |
| 25 | + isOnPremSession, | |
| 26 | +} from "./AuthTypes.js"; | |
| 18 | 27 | import { getControlPlaneEnv } from "./env.js"; |
| 19 | 28 | |
| 20 | 29 | export interface PolicyResponse { |
| @@ -41,11 +50,15 @@ | ||
| 41 | 50 | export const TRIAL_PROXY_URL = |
| 42 | 51 | "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; |
| 43 | 52 | |
| 53 | +export interface RemoteSessionMetadata extends BaseSessionMetadata { | |
| 54 | + isRemote: true; | |
| 55 | + remoteId: string; | |
| 56 | +} | |
| 57 | + | |
| 44 | 58 | export class ControlPlaneClient { |
| 45 | 59 | constructor( |
| 46 | 60 | readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>, |
| 47 | - private readonly ideSettingsPromise: Promise<IdeSettings>, | |
| 48 | - private readonly ideInfoPromise: Promise<IdeInfo>, | |
| 61 | + private readonly ide: IDE, | |
| 49 | 62 | ) {} |
| 50 | 63 | |
| 51 | 64 | async resolveFQSNs( |
| @@ -90,9 +103,9 @@ | ||
| 90 | 103 | throw new Error("No access token"); |
| 91 | 104 | } |
| 92 | 105 | |
| 93 | - const env = await getControlPlaneEnv(this.ideSettingsPromise); | |
| 106 | + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); | |
| 94 | 107 | const url = new URL(path, env.CONTROL_PLANE_URL).toString(); |
| 95 | - const ideInfo = await this.ideInfoPromise; | |
| 108 | + const ideInfo = await this.ide.getIdeInfo(); | |
| 96 | 109 | |
| 97 | 110 | const resp = await fetch(url, { |
| 98 | 111 | ...init, |
| @@ -304,4 +317,127 @@ | ||
| 304 | 317 | return null; |
| 305 | 318 | } |
| 306 | 319 | } |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Check if remote sessions should be enabled based on feature flags | |
| 323 | + * Requires: PostHog feature flag AND @continue.dev email | |
| 324 | + */ | |
| 325 | + public async shouldEnableRemoteSessions(): Promise<boolean> { | |
| 326 | + // Check if user is signed in | |
| 327 | + if (!(await this.isSignedIn())) { | |
| 328 | + return false; | |
| 329 | + } | |
| 330 | + | |
| 331 | + // Check if user has @continue.dev email | |
| 332 | + try { | |
| 333 | + const sessionInfo = await this.sessionInfoPromise; | |
| 334 | + if (isOnPremSession(sessionInfo) || !sessionInfo) { | |
| 335 | + return false; | |
| 336 | + } | |
| 337 | + | |
| 338 | + const hubSession = sessionInfo as HubSessionInfo; | |
| 339 | + const email = hubSession.account?.id; | |
| 340 | + | |
| 341 | + return email ? email.includes("@continue.dev") : false; | |
| 342 | + } catch (e) { | |
| 343 | + Logger.error(e, { | |
| 344 | + context: "control_plane_check_remote_sessions_enabled", | |
| 345 | + }); | |
| 346 | + return false; | |
| 347 | + } | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Get current user's session info | |
| 352 | + */ | |
| 353 | + public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> { | |
| 354 | + return await this.sessionInfoPromise; | |
| 355 | + } | |
| 356 | + | |
| 357 | + /** | |
| 358 | + * Fetch remote agents/sessions from the control plane | |
| 359 | + * Currently restricted to @continue.dev emails for internal use | |
| 360 | + */ | |
| 361 | + public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> { | |
| 362 | + if (!(await this.isSignedIn())) { | |
| 363 | + return []; | |
| 364 | + } | |
| 365 | + | |
| 366 | + try { | |
| 367 | + // Note: This endpoint is currently restricted to internal @continue.dev users | |
| 368 | + // In the future, this may be expanded to support broader remote session access | |
| 369 | + const resp = await this.requestAndHandleError("agents/devboxes", { | |
| 370 | + method: "GET", | |
| 371 | + }); | |
| 372 | + | |
| 373 | + const agents = (await resp.json()) as any[]; | |
| 374 | + | |
| 375 | + return agents.map( | |
| 376 | + (agent: any): RemoteSessionMetadata => ({ | |
| 377 | + sessionId: `remote-${agent.id}`, | |
| 378 | + title: agent.name || "Remote Agent", | |
| 379 | + dateCreated: new Date(agent.create_time_ms).toISOString(), | |
| 380 | + workspaceDirectory: "", | |
| 381 | + isRemote: true, | |
| 382 | + remoteId: agent.id, | |
| 383 | + }), | |
| 384 | + ); | |
| 385 | + } catch (e) { | |
| 386 | + // Log error but don't throw - remote sessions are optional | |
| 387 | + Logger.error(e, { | |
| 388 | + context: "control_plane_list_remote_sessions", | |
| 389 | + }); | |
| 390 | + return []; | |
| 391 | + } | |
| 392 | + } | |
| 393 | + | |
| 394 | + public async loadRemoteSession(remoteId: string): Promise<Session> { | |
| 395 | + if (!(await this.isSignedIn())) { | |
| 396 | + throw new Error("Not signed in to load remote session"); | |
| 397 | + } | |
| 398 | + | |
| 399 | + try { | |
| 400 | + // First get the tunnel URL for the remote agent | |
| 401 | + const tunnelResp = await this.requestAndHandleError( | |
| 402 | + `agents/devboxes/${remoteId}/tunnel`, | |
| 403 | + { | |
| 404 | + method: "POST", | |
| 405 | + }, | |
| 406 | + ); | |
| 407 | + | |
| 408 | + const tunnelData = (await tunnelResp.json()) as { url?: string }; | |
| 409 | + const tunnelUrl = tunnelData.url; | |
| 410 | + | |
| 411 | + if (!tunnelUrl) { | |
| 412 | + throw new Error(`Failed to get tunnel URL for agent ${remoteId}`); | |
| 413 | + } | |
| 414 | + | |
| 415 | + // Now fetch the session state from the remote agent's /state endpoint | |
| 416 | + const stateResponse = await fetch(`${tunnelUrl}/state`); | |
| 417 | + if (!stateResponse.ok) { | |
| 418 | + throw new Error( | |
| 419 | + `Failed to fetch state from remote agent: ${stateResponse.statusText}`, | |
| 420 | + ); | |
| 421 | + } | |
| 422 | + | |
| 423 | + const remoteState = (await stateResponse.json()) as { session?: Session }; | |
| 424 | + | |
| 425 | + // The remote state contains a session property with the full session data | |
| 426 | + if (!remoteState.session) { | |
| 427 | + throw new Error( | |
| 428 | + "Remote agent returned invalid state - no session found", | |
| 429 | + ); | |
| 430 | + } | |
| 431 | + | |
| 432 | + return remoteState.session; | |
| 433 | + } catch (e) { | |
| 434 | + Logger.error(e, { | |
| 435 | + context: "control_plane_load_remote_session", | |
| 436 | + remoteId, | |
| 437 | + }); | |
| 438 | + throw new Error( | |
| 439 | + `Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`, | |
| 440 | + ); | |
| 441 | + } | |
| 442 | + } | |
| 307 | 443 | } |
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; |
| 18 | 18 | import DocsService from "./indexing/docs/DocsService"; |
| 19 | 19 | import { countTokens } from "./llm/countTokens"; |
| 20 | +import Lemonade from "./llm/llms/Lemonade"; | |
| 20 | 21 | import Ollama from "./llm/llms/Ollama"; |
| 21 | 22 | import { EditAggregator } from "./nextEdit/context/aggregateEdits"; |
| 22 | 23 | import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile"; |
| @@ -29,8 +30,9 @@ | ||
| 29 | 30 | import { Telemetry } from "./util/posthog"; |
| 30 | 31 | import { |
| 31 | 32 | isProcessBackgrounded, |
| 33 | + killTerminalProcess, | |
| 32 | 34 | markProcessAsBackgrounded, |
| 33 | -} from "./util/processTerminalBackgroundStates"; | |
| 35 | +} from "./util/processTerminalStates"; | |
| 34 | 36 | import { getSymbolsForManyFiles } from "./util/treeSitter"; |
| 35 | 37 | import { TTS } from "./util/tts"; |
| 36 | 38 | |
| @@ -76,6 +78,7 @@ | ||
| 76 | 78 | import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; |
| 77 | 79 | import { OnboardingModes } from "./protocol/core"; |
| 78 | 80 | import type { IMessenger, Message } from "./protocol/messenger"; |
| 81 | +import { shareSession } from "./util/historyUtils"; | |
| 79 | 82 | import { Logger } from "./util/Logger.js"; |
| 80 | 83 | import { getUriPathBasename } from "./util/uri"; |
| 81 | 84 | |
| @@ -138,7 +141,7 @@ | ||
| 138 | 141 | |
| 139 | 142 | const ideInfoPromise = messenger.request("getIdeInfo", undefined); |
| 140 | 143 | const ideSettingsPromise = messenger.request("getIdeSettings", undefined); |
| 141 | - const sessionInfoPromise = messenger.request( | |
| 144 | + const initialSessionInfoPromise = messenger.request( | |
| 142 | 145 | "getControlPlaneSessionInfo", |
| 143 | 146 | { |
| 144 | 147 | silent: true, |
| @@ -148,9 +151,8 @@ | ||
| 148 | 151 | |
| 149 | 152 | this.configHandler = new ConfigHandler( |
| 150 | 153 | this.ide, |
| 151 | - ideSettingsPromise, | |
| 152 | 154 | this.llmLogger, |
| 153 | - sessionInfoPromise, | |
| 155 | + initialSessionInfoPromise, | |
| 154 | 156 | ); |
| 155 | 157 | |
| 156 | 158 | this.docsService = DocsService.createSingleton( |
| @@ -175,6 +177,13 @@ | ||
| 175 | 177 | } |
| 176 | 178 | }; |
| 177 | 179 | |
| 180 | + this.codeBaseIndexer = new CodebaseIndexer( | |
| 181 | + this.configHandler, | |
| 182 | + this.ide, | |
| 183 | + this.messenger, | |
| 184 | + this.globalContext.get("indexingPaused"), | |
| 185 | + ); | |
| 186 | + | |
| 178 | 187 | this.configHandler.onConfigUpdate((result) => { |
| 179 | 188 | void (async () => { |
| 180 | 189 | const serializedResult = |
| @@ -187,6 +196,12 @@ | ||
| 187 | 196 | selectedOrgId: this.configHandler.currentOrg?.id ?? null, |
| 188 | 197 | }); |
| 189 | 198 | |
| 199 | + if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) { | |
| 200 | + await this.codeBaseIndexer.refreshCodebaseIndex( | |
| 201 | + await this.ide.getWorkspaceDirs(), | |
| 202 | + ); | |
| 203 | + } | |
| 204 | + | |
| 190 | 205 | // update additional submenu context providers registered via VSCode API |
| 191 | 206 | const additionalProviders = |
| 192 | 207 | this.configHandler.getAdditionalSubmenuContextProviders(); |
| @@ -198,13 +213,6 @@ | ||
| 198 | 213 | })(); |
| 199 | 214 | }); |
| 200 | 215 | |
| 201 | - this.codeBaseIndexer = new CodebaseIndexer( | |
| 202 | - this.configHandler, | |
| 203 | - this.ide, | |
| 204 | - this.messenger, | |
| 205 | - this.globalContext.get("indexingPaused"), | |
| 206 | - ); | |
| 207 | - | |
| 208 | 216 | // Dev Data Logger |
| 209 | 217 | const dataLogger = DataLogger.getInstance(); |
| 210 | 218 | dataLogger.core = this; |
| @@ -225,6 +233,17 @@ | ||
| 225 | 233 | return; |
| 226 | 234 | } |
| 227 | 235 | |
| 236 | + // Check for disableIndexing to prevent race condition | |
| 237 | + const { config } = await this.configHandler.loadConfig(); | |
| 238 | + if (!config || config.disableIndexing) { | |
| 239 | + void this.messenger.request("indexProgress", { | |
| 240 | + progress: 0, | |
| 241 | + desc: "Indexing is disabled", | |
| 242 | + status: "disabled", | |
| 243 | + }); | |
| 244 | + return; | |
| 245 | + } | |
| 246 | + | |
| 228 | 247 | void this.codeBaseIndexer.refreshCodebaseIndex(dirs); |
| 229 | 248 | }); |
| 230 | 249 | }); |
| @@ -307,8 +326,27 @@ | ||
| 307 | 326 | }); |
| 308 | 327 | |
| 309 | 328 | // History |
| 310 | - on("history/list", (msg) => { | |
| 311 | - return historyManager.list(msg.data); | |
| 329 | + on("history/list", async (msg) => { | |
| 330 | + const localSessions = historyManager.list(msg.data); | |
| 331 | + | |
| 332 | + // Check if remote sessions should be enabled based on feature flags | |
| 333 | + const shouldFetchRemote = | |
| 334 | + await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions(); | |
| 335 | + | |
| 336 | + // Get remote sessions from control plane if feature is enabled | |
| 337 | + const remoteSessions = shouldFetchRemote | |
| 338 | + ? await this.configHandler.controlPlaneClient.listRemoteSessions() | |
| 339 | + : []; | |
| 340 | + | |
| 341 | + // Combine and sort by date (most recent first) | |
| 342 | + const allSessions = [...localSessions, ...remoteSessions].sort( | |
| 343 | + (a, b) => | |
| 344 | + new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(), | |
| 345 | + ); | |
| 346 | + | |
| 347 | + // Apply limit if specified | |
| 348 | + const limit = msg.data?.limit ?? 100; | |
| 349 | + return allSessions.slice(0, limit); | |
| 312 | 350 | }); |
| 313 | 351 | |
| 314 | 352 | on("history/delete", (msg) => { |
| @@ -319,10 +357,23 @@ | ||
| 319 | 357 | return historyManager.load(msg.data.id); |
| 320 | 358 | }); |
| 321 | 359 | |
| 360 | + on("history/loadRemote", async (msg) => { | |
| 361 | + return this.configHandler.controlPlaneClient.loadRemoteSession( | |
| 362 | + msg.data.remoteId, | |
| 363 | + ); | |
| 364 | + }); | |
| 365 | + | |
| 322 | 366 | on("history/save", (msg) => { |
| 323 | 367 | historyManager.save(msg.data); |
| 324 | 368 | }); |
| 325 | 369 | |
| 370 | + on("history/share", async (msg) => { | |
| 371 | + const session = historyManager.load(msg.data.id); | |
| 372 | + const outputDir = msg.data.outputDir; | |
| 373 | + const history = session.history.map((msg) => msg.message); | |
| 374 | + await shareSession(this.ide, history, outputDir); | |
| 375 | + }); | |
| 376 | + | |
| 326 | 377 | on("history/clear", (msg) => { |
| 327 | 378 | historyManager.clearAll(); |
| 328 | 379 | }); |
| @@ -668,6 +719,8 @@ | ||
| 668 | 719 | return queue.dequeueProcessed() || null; |
| 669 | 720 | }); |
| 670 | 721 | |
| 722 | + // NOTE: This is not used unless prefetch is used. | |
| 723 | + // At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching. | |
| 671 | 724 | on("nextEdit/queue/processOne", async (msg) => { |
| 672 | 725 | console.log("nextEdit/queue/processOne"); |
| 673 | 726 | const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data; |
| @@ -720,20 +773,13 @@ | ||
| 720 | 773 | data.fileUri ?? "current-file-stream", |
| 721 | 774 | ); // not super important since currently cancelling apply will cancel all streams it's one file at a time |
| 722 | 775 | |
| 723 | - return streamDiffLines({ | |
| 724 | - highlighted: data.highlighted, | |
| 725 | - prefix: data.prefix, | |
| 726 | - suffix: data.suffix, | |
| 776 | + return streamDiffLines( | |
| 777 | + data, | |
| 727 | 778 | llm, |
| 728 | - // rules included for edit, NOT apply | |
| 729 | - rulesToInclude: data.includeRulesInSystemMessage | |
| 730 | - ? config.rules | |
| 731 | - : undefined, | |
| 732 | - input: data.input, | |
| 733 | - language: data.language, | |
| 734 | - overridePrompt: undefined, | |
| 735 | 779 | abortController, |
| 736 | - }); | |
| 780 | + undefined, | |
| 781 | + data.includeRulesInSystemMessage ? config.rules : undefined, | |
| 782 | + ); | |
| 737 | 783 | }); |
| 738 | 784 | |
| 739 | 785 | on("cancelApply", async (msg) => { |
| @@ -1007,6 +1053,37 @@ | ||
| 1007 | 1053 | this.handleToolCall(toolCall), |
| 1008 | 1054 | ); |
| 1009 | 1055 | |
| 1056 | + on( | |
| 1057 | + "tools/evaluatePolicy", | |
| 1058 | + async ({ data: { toolName, basePolicy, args } }) => { | |
| 1059 | + const { config } = await this.configHandler.loadConfig(); | |
| 1060 | + if (!config) { | |
| 1061 | + throw new Error("Config not loaded"); | |
| 1062 | + } | |
| 1063 | + | |
| 1064 | + const tool = config.tools.find((t) => t.function.name === toolName); | |
| 1065 | + if (!tool) { | |
| 1066 | + // Tool not found, return base policy | |
| 1067 | + return { policy: basePolicy }; | |
| 1068 | + } | |
| 1069 | + | |
| 1070 | + // Extract display value for specific tools | |
| 1071 | + let displayValue: string | undefined; | |
| 1072 | + if (toolName === "runTerminalCommand" && args.command) { | |
| 1073 | + displayValue = args.command as string; | |
| 1074 | + } | |
| 1075 | + | |
| 1076 | + // If tool has evaluateToolCallPolicy function, use it | |
| 1077 | + if (tool.evaluateToolCallPolicy) { | |
| 1078 | + const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); | |
| 1079 | + return { policy: evaluatedPolicy, displayValue }; | |
| 1080 | + } | |
| 1081 | + | |
| 1082 | + // Otherwise return base policy unchanged | |
| 1083 | + return { policy: basePolicy, displayValue }; | |
| 1084 | + }, | |
| 1085 | + ); | |
| 1086 | + | |
| 1010 | 1087 | on("isItemTooBig", async ({ data: { item } }) => { |
| 1011 | 1088 | return this.isItemTooBig(item); |
| 1012 | 1089 | }); |
| @@ -1024,6 +1101,10 @@ | ||
| 1024 | 1101 | }, |
| 1025 | 1102 | ); |
| 1026 | 1103 | |
| 1104 | + on("process/killTerminalProcess", async ({ data: { toolCallId } }) => { | |
| 1105 | + await killTerminalProcess(toolCallId); | |
| 1106 | + }); | |
| 1107 | + | |
| 1027 | 1108 | on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { |
| 1028 | 1109 | const isValid = setMdmLicenseKey(licenseKey); |
| 1029 | 1110 | return isValid; |
| @@ -1220,6 +1301,9 @@ | ||
| 1220 | 1301 | if (msg.data.title === "Ollama") { |
| 1221 | 1302 | const models = await new Ollama({ model: "" }).listModels(); |
| 1222 | 1303 | return models; |
| 1304 | + } else if (msg.data.title === "Lemonade") { | |
| 1305 | + const models = await new Lemonade({ model: "" }).listModels(); | |
| 1306 | + return models; | |
| 1223 | 1307 | } else { |
| 1224 | 1308 | return undefined; |
| 1225 | 1309 | } |
| @@ -1305,6 +1389,8 @@ | ||
| 1305 | 1389 | selectedCode, |
| 1306 | 1390 | reranker: config.selectedModelByRole.rerank, |
| 1307 | 1391 | fetch: (url, init) => |
| 1392 | + // Important note: context providers fetch uses global request options not LLM request options | |
| 1393 | + // Because LLM calls are handled separately | |
| 1308 | 1394 | fetchwithRequestOptions(url, init, config.requestOptions), |
| 1309 | 1395 | isInAgentMode: msg.data.isInAgentMode, |
| 1310 | 1396 | }); |
| @@ -1,1 +1,3 @@ | ||
| 1 | 1 | export const EDIT_MODE_STREAM_ID = "edit-mode"; |
| 2 | + | |
| 3 | +export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>"; |
| @@ -1,7 +1,14 @@ | ||
| 1 | -import { ChatMessage, ILLM, Prediction, PromptLog } from ".."; | |
| 1 | +import { | |
| 2 | + ChatMessage, | |
| 3 | + ILLM, | |
| 4 | + Prediction, | |
| 5 | + PromptLog, | |
| 6 | + type StreamDiffLinesType, | |
| 7 | +} from ".."; | |
| 2 | 8 | import { DEFAULT_MAX_TOKENS } from "../llm/constants"; |
| 3 | 9 | import { countTokens } from "../llm/countTokens"; |
| 4 | 10 | import { renderChatMessage } from "../util/messageContent"; |
| 11 | +import { APPLY_UNIQUE_TOKEN } from "./constants.js"; | |
| 5 | 12 | |
| 6 | 13 | const INFINITE_STREAM_SAFETY = 0.9; |
| 7 | 14 | |
| @@ -17,6 +24,7 @@ | ||
| 17 | 24 | export async function* recursiveStream( |
| 18 | 25 | llm: ILLM, |
| 19 | 26 | abortController: AbortController, |
| 27 | + type: StreamDiffLinesType, | |
| 20 | 28 | prompt: ChatMessage[] | string, |
| 21 | 29 | prediction: Prediction | undefined, |
| 22 | 30 | currentBuffer = "", |
| @@ -28,8 +36,11 @@ | ||
| 28 | 36 | let buffer = currentBuffer; |
| 29 | 37 | // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries |
| 30 | 38 | |
| 39 | + const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm); | |
| 31 | 40 | if (typeof prompt === "string") { |
| 32 | - const generator = llm.streamComplete(prompt, abortController.signal, { | |
| 41 | + const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt; | |
| 42 | + | |
| 43 | + const generator = llm.streamComplete(finalPrompt, abortController.signal, { | |
| 33 | 44 | raw: true, |
| 34 | 45 | prediction: undefined, |
| 35 | 46 | reasoning: false, |
| @@ -62,7 +73,11 @@ | ||
| 62 | 73 | } |
| 63 | 74 | } |
| 64 | 75 | } else { |
| 65 | - const generator = llm.streamChat(prompt, abortController.signal, { | |
| 76 | + const promptMessages = injectApplyToken | |
| 77 | + ? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN) | |
| 78 | + : prompt; | |
| 79 | + | |
| 80 | + const generator = llm.streamChat(promptMessages, abortController.signal, { | |
| 66 | 81 | raw: true, |
| 67 | 82 | prediction: undefined, |
| 68 | 83 | reasoning: false, |
| @@ -104,3 +119,36 @@ | ||
| 104 | 119 | } |
| 105 | 120 | } |
| 106 | 121 | } |
| 122 | + | |
| 123 | +function shouldInjectApplyToken(llm: ILLM): boolean { | |
| 124 | + const model = llm.model?.toLowerCase() ?? ""; | |
| 125 | + return ( | |
| 126 | + llm.underlyingProviderName === "inception" && model.includes("mercury") | |
| 127 | + ); | |
| 128 | +} | |
| 129 | + | |
| 130 | +function appendTokenToLastMessage( | |
| 131 | + messages: ChatMessage[], | |
| 132 | + token: string, | |
| 133 | +): ChatMessage[] { | |
| 134 | + if (messages.length === 0) { | |
| 135 | + return messages; | |
| 136 | + } | |
| 137 | + | |
| 138 | + const lastMessage = messages[messages.length - 1]; | |
| 139 | + if (typeof lastMessage.content !== "string") { | |
| 140 | + return messages; | |
| 141 | + } | |
| 142 | + | |
| 143 | + if (lastMessage.content.endsWith(token)) { | |
| 144 | + return messages; | |
| 145 | + } | |
| 146 | + | |
| 147 | + const updatedMessages = [...messages]; | |
| 148 | + updatedMessages[updatedMessages.length - 1] = { | |
| 149 | + ...lastMessage, | |
| 150 | + content: lastMessage.content + token, | |
| 151 | + }; | |
| 152 | + | |
| 153 | + return updatedMessages; | |
| 154 | +} |
| @@ -0,0 +1,252 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { executeFindAndReplace } from "./performReplace"; | |
| 4 | + | |
| 5 | +describe("executeFindAndReplace", () => { | |
| 6 | + describe("normal cases", () => { | |
| 7 | + it("should replace single occurrence by default", () => { | |
| 8 | + const content = "Hello world\nThis is a test file\nGoodbye"; | |
| 9 | + const result = executeFindAndReplace(content, "Hello", "Hi", false); | |
| 10 | + | |
| 11 | + expect(result).toBe("Hi world\nThis is a test file\nGoodbye"); | |
| 12 | + }); | |
| 13 | + | |
| 14 | + it("should replace single occurrence when replaceAll is false", () => { | |
| 15 | + const content = "Hello world\nHello again"; | |
| 16 | + const result = executeFindAndReplace( | |
| 17 | + content, | |
| 18 | + "Hello world", | |
| 19 | + "Hi world", | |
| 20 | + false, | |
| 21 | + ); | |
| 22 | + | |
| 23 | + expect(result).toBe("Hi world\nHello again"); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + it("should replace all occurrences when replaceAll is true", () => { | |
| 27 | + const content = "Hello world\nHello again\nHello there"; | |
| 28 | + const result = executeFindAndReplace(content, "Hello", "Hi", true); | |
| 29 | + | |
| 30 | + expect(result).toBe("Hi world\nHi again\nHi there"); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + it("should handle empty new string (deletion)", () => { | |
| 34 | + const content = "Hello world"; | |
| 35 | + const result = executeFindAndReplace(content, "Hello ", "", false); | |
| 36 | + | |
| 37 | + expect(result).toBe("world"); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should handle empty old string replacement (insertion at start)", () => { | |
| 41 | + const content = ""; | |
| 42 | + const result = executeFindAndReplace(content, "", "Hello world", false); | |
| 43 | + | |
| 44 | + expect(result).toBe("Hello world"); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should preserve whitespace and indentation", () => { | |
| 48 | + const content = | |
| 49 | + "function test() {\n const value = 'old';\n return value;\n}"; | |
| 50 | + const result = executeFindAndReplace( | |
| 51 | + content, | |
| 52 | + " const value = 'old';", | |
| 53 | + " const value = 'new';", | |
| 54 | + false, | |
| 55 | + ); | |
| 56 | + | |
| 57 | + expect(result).toBe( | |
| 58 | + "function test() {\n const value = 'new';\n return value;\n}", | |
| 59 | + ); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + it("should handle multiline strings", () => { | |
| 63 | + const content = "line1\nline2\nline3"; | |
| 64 | + const result = executeFindAndReplace( | |
| 65 | + content, | |
| 66 | + "line1\nline2", | |
| 67 | + "newline1\nnewline2", | |
| 68 | + false, | |
| 69 | + ); | |
| 70 | + | |
| 71 | + expect(result).toBe("newline1\nnewline2\nline3"); | |
| 72 | + }); | |
| 73 | + }); | |
| 74 | + | |
| 75 | + describe("special character handling", () => { | |
| 76 | + it("should handle regex special characters in old string", () => { | |
| 77 | + const content = "const regex = /[a-z]+/g;"; | |
| 78 | + const result = executeFindAndReplace( | |
| 79 | + content, | |
| 80 | + "/[a-z]+/g", | |
| 81 | + "/[A-Z]+/g", | |
| 82 | + false, | |
| 83 | + ); | |
| 84 | + | |
| 85 | + expect(result).toBe("const regex = /[A-Z]+/g;"); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + it("should handle dollar signs in strings", () => { | |
| 89 | + const content = 'const text = "Hello $world"'; | |
| 90 | + const result = executeFindAndReplace( | |
| 91 | + content, | |
| 92 | + '"Hello $world"', | |
| 93 | + '"Hi $universe"', | |
| 94 | + false, | |
| 95 | + ); | |
| 96 | + | |
| 97 | + expect(result).toBe('const text = "Hi $universe"'); | |
| 98 | + }); | |
| 99 | + | |
| 100 | + it("should handle backslashes", () => { | |
| 101 | + const content = 'const path = "C:\\Users\\test"'; | |
| 102 | + const result = executeFindAndReplace( | |
| 103 | + content, | |
| 104 | + "C:\\Users\\test", | |
| 105 | + "D:\\Users\\test", | |
| 106 | + false, | |
| 107 | + ); | |
| 108 | + | |
| 109 | + expect(result).toBe('const path = "D:\\Users\\test"'); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should handle parentheses", () => { | |
| 113 | + const content = "function test() { return 'old'; }"; | |
| 114 | + const result = executeFindAndReplace( | |
| 115 | + content, | |
| 116 | + "() { return 'old'; }", | |
| 117 | + "() { return 'new'; }", | |
| 118 | + false, | |
| 119 | + ); | |
| 120 | + | |
| 121 | + expect(result).toBe("function test() { return 'new'; }"); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + it("should handle square brackets", () => { | |
| 125 | + const content = "const arr = [1, 2, 3];"; | |
| 126 | + const result = executeFindAndReplace( | |
| 127 | + content, | |
| 128 | + "[1, 2, 3]", | |
| 129 | + "[4, 5, 6]", | |
| 130 | + false, | |
| 131 | + ); | |
| 132 | + | |
| 133 | + expect(result).toBe("const arr = [4, 5, 6];"); | |
| 134 | + }); | |
| 135 | + }); | |
| 136 | + | |
| 137 | + describe("replaceAll behavior", () => { | |
| 138 | + it("should replace all occurrences including partial matches", () => { | |
| 139 | + const content = "test testing tested test"; | |
| 140 | + const result = executeFindAndReplace(content, "test", "exam", true); | |
| 141 | + | |
| 142 | + expect(result).toBe("exam examing examed exam"); | |
| 143 | + }); | |
| 144 | + | |
| 145 | + it("should replace all occurrences with empty string", () => { | |
| 146 | + const content = "remove this remove that remove everything"; | |
| 147 | + const result = executeFindAndReplace(content, "remove ", "", true); | |
| 148 | + | |
| 149 | + expect(result).toBe("this that everything"); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("should handle overlapping patterns correctly", () => { | |
| 153 | + const content = "aaaa"; | |
| 154 | + const result = executeFindAndReplace(content, "aa", "b", true); | |
| 155 | + | |
| 156 | + expect(result).toBe("bb"); | |
| 157 | + }); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + describe("error cases", () => { | |
| 161 | + it("should throw error when string not found", () => { | |
| 162 | + const content = "Hello world"; | |
| 163 | + | |
| 164 | + expect(() => { | |
| 165 | + executeFindAndReplace(content, "xyz", "abc", false); | |
| 166 | + }).toThrowError( | |
| 167 | + expect.objectContaining({ | |
| 168 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 169 | + }), | |
| 170 | + ); | |
| 171 | + }); | |
| 172 | + | |
| 173 | + it("should throw error with edit context when string not found", () => { | |
| 174 | + const content = "Hello world"; | |
| 175 | + | |
| 176 | + expect(() => { | |
| 177 | + executeFindAndReplace(content, "xyz", "abc", false, 2); | |
| 178 | + }).toThrowError( | |
| 179 | + expect.objectContaining({ | |
| 180 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 181 | + }), | |
| 182 | + ); | |
| 183 | + }); | |
| 184 | + | |
| 185 | + it("should throw error when multiple occurrences exist and replaceAll is false", () => { | |
| 186 | + const content = "Hello world\nHello again\nHello there"; | |
| 187 | + | |
| 188 | + expect(() => { | |
| 189 | + executeFindAndReplace(content, "Hello", "Hi", false); | |
| 190 | + }).toThrowError( | |
| 191 | + expect.objectContaining({ | |
| 192 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 193 | + }), | |
| 194 | + ); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should throw error with edit context for multiple occurrences", () => { | |
| 198 | + const content = "test test test"; | |
| 199 | + | |
| 200 | + expect(() => { | |
| 201 | + executeFindAndReplace(content, "test", "exam", false, 1); | |
| 202 | + }).toThrowError( | |
| 203 | + expect.objectContaining({ | |
| 204 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 205 | + }), | |
| 206 | + ); | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + describe("edge cases", () => { | |
| 211 | + it("should handle single character replacement", () => { | |
| 212 | + const content = "a b c"; | |
| 213 | + const result = executeFindAndReplace(content, "b", "x", false); | |
| 214 | + | |
| 215 | + expect(result).toBe("a x c"); | |
| 216 | + }); | |
| 217 | + | |
| 218 | + it("should handle very long strings", () => { | |
| 219 | + const longString = "a".repeat(10000); | |
| 220 | + const content = `start${longString}end`; | |
| 221 | + const result = executeFindAndReplace(content, longString, "short", false); | |
| 222 | + | |
| 223 | + expect(result).toBe("startshortend"); | |
| 224 | + }); | |
| 225 | + | |
| 226 | + it("should handle strings at beginning of content", () => { | |
| 227 | + const content = "start middle end"; | |
| 228 | + const result = executeFindAndReplace(content, "start", "begin", false); | |
| 229 | + | |
| 230 | + expect(result).toBe("begin middle end"); | |
| 231 | + }); | |
| 232 | + | |
| 233 | + it("should handle strings at end of content", () => { | |
| 234 | + const content = "start middle end"; | |
| 235 | + const result = executeFindAndReplace(content, "end", "finish", false); | |
| 236 | + | |
| 237 | + expect(result).toBe("start middle finish"); | |
| 238 | + }); | |
| 239 | + | |
| 240 | + it("should handle entire content replacement", () => { | |
| 241 | + const content = "replace everything"; | |
| 242 | + const result = executeFindAndReplace( | |
| 243 | + content, | |
| 244 | + "replace everything", | |
| 245 | + "new content", | |
| 246 | + false, | |
| 247 | + ); | |
| 248 | + | |
| 249 | + expect(result).toBe("new content"); | |
| 250 | + }); | |
| 251 | + }); | |
| 252 | +}); |
| @@ -0,0 +1,53 @@ | ||
| 1 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 2 | + | |
| 3 | +export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = | |
| 4 | + "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * Validates a single edit operation | |
| 8 | + */ | |
| 9 | +export function validateSingleEdit( | |
| 10 | + oldString: string, | |
| 11 | + newString: string, | |
| 12 | + index?: number, | |
| 13 | +): void { | |
| 14 | + const context = index !== undefined ? `edit at index ${index}: ` : ""; | |
| 15 | + | |
| 16 | + if (!oldString && oldString !== "") { | |
| 17 | + throw new ContinueError( | |
| 18 | + ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 19 | + `${context}old_string is required`, | |
| 20 | + ); | |
| 21 | + } | |
| 22 | + if (newString === undefined) { | |
| 23 | + throw new ContinueError( | |
| 24 | + ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 25 | + `${context}new_string is required`, | |
| 26 | + ); | |
| 27 | + } | |
| 28 | + if (oldString === newString) { | |
| 29 | + throw new ContinueError( | |
| 30 | + ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 31 | + `${context}old_string and new_string must be different`, | |
| 32 | + ); | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +export function trimEmptyLines({ | |
| 37 | + lines, | |
| 38 | + fromEnd, | |
| 39 | +}: { | |
| 40 | + lines: string[]; | |
| 41 | + fromEnd: boolean; | |
| 42 | +}): string[] { | |
| 43 | + lines = fromEnd ? lines.slice().reverse() : lines.slice(); | |
| 44 | + const newLines: string[] = []; | |
| 45 | + let shouldContinueRemoving = true; | |
| 46 | + for (let index = 0; index < lines.length; index++) { | |
| 47 | + const line = lines[index]; | |
| 48 | + if (shouldContinueRemoving && line.trim() === "") continue; | |
| 49 | + shouldContinueRemoving = false; | |
| 50 | + newLines.push(line); | |
| 51 | + } | |
| 52 | + return fromEnd ? newLines.reverse() : newLines; | |
| 53 | +} |
| @@ -0,0 +1,151 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils"; | |
| 4 | + | |
| 5 | +describe("validateSingleEdit", () => { | |
| 6 | + describe("valid inputs", () => { | |
| 7 | + it("should not throw for valid non-empty strings", () => { | |
| 8 | + expect(() => { | |
| 9 | + validateSingleEdit("old", "new"); | |
| 10 | + }).not.toThrow(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + it("should allow empty old_string for file creation", () => { | |
| 14 | + expect(() => { | |
| 15 | + validateSingleEdit("", "new content"); | |
| 16 | + }).not.toThrow(); | |
| 17 | + }); | |
| 18 | + | |
| 19 | + it("should allow empty new_string for deletion", () => { | |
| 20 | + expect(() => { | |
| 21 | + validateSingleEdit("delete me", ""); | |
| 22 | + }).not.toThrow(); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + it("should allow multiline strings", () => { | |
| 26 | + expect(() => { | |
| 27 | + validateSingleEdit("line1\nline2", "newline1\nnewline2"); | |
| 28 | + }).not.toThrow(); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("should allow special characters", () => { | |
| 32 | + expect(() => { | |
| 33 | + validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g"); | |
| 34 | + }).not.toThrow(); | |
| 35 | + }); | |
| 36 | + }); | |
| 37 | + | |
| 38 | + describe("invalid inputs", () => { | |
| 39 | + it("should throw error when old_string is null", () => { | |
| 40 | + expect(() => { | |
| 41 | + validateSingleEdit(null as any, "new"); | |
| 42 | + }).toThrowError( | |
| 43 | + expect.objectContaining({ | |
| 44 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 45 | + }), | |
| 46 | + ); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + it("should throw error when old_string is undefined", () => { | |
| 50 | + expect(() => { | |
| 51 | + validateSingleEdit(undefined as any, "new"); | |
| 52 | + }).toThrowError( | |
| 53 | + expect.objectContaining({ | |
| 54 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 55 | + }), | |
| 56 | + ); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + it("should throw error when new_string is undefined", () => { | |
| 60 | + expect(() => { | |
| 61 | + validateSingleEdit("old", undefined as any); | |
| 62 | + }).toThrowError( | |
| 63 | + expect.objectContaining({ | |
| 64 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 65 | + }), | |
| 66 | + ); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("should throw error when old_string and new_string are identical", () => { | |
| 70 | + expect(() => { | |
| 71 | + validateSingleEdit("same", "same"); | |
| 72 | + }).toThrowError( | |
| 73 | + expect.objectContaining({ | |
| 74 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 75 | + }), | |
| 76 | + ); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + it("should throw error when both are empty strings", () => { | |
| 80 | + expect(() => { | |
| 81 | + validateSingleEdit("", ""); | |
| 82 | + }).toThrowError( | |
| 83 | + expect.objectContaining({ | |
| 84 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 85 | + }), | |
| 86 | + ); | |
| 87 | + }); | |
| 88 | + }); | |
| 89 | + | |
| 90 | + describe("error messages with context", () => { | |
| 91 | + it("should include edit number in error messages when index provided", () => { | |
| 92 | + expect(() => { | |
| 93 | + validateSingleEdit(null as any, "new", 2); | |
| 94 | + }).toThrowError( | |
| 95 | + expect.objectContaining({ | |
| 96 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 97 | + }), | |
| 98 | + ); | |
| 99 | + }); | |
| 100 | + | |
| 101 | + it("should include edit number for new_string errors", () => { | |
| 102 | + expect(() => { | |
| 103 | + validateSingleEdit("old", undefined as any, 0); | |
| 104 | + }).toThrowError( | |
| 105 | + expect.objectContaining({ | |
| 106 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 107 | + }), | |
| 108 | + ); | |
| 109 | + }); | |
| 110 | + | |
| 111 | + it("should include edit number for identical strings error", () => { | |
| 112 | + expect(() => { | |
| 113 | + validateSingleEdit("same", "same", 4); | |
| 114 | + }).toThrowError( | |
| 115 | + expect.objectContaining({ | |
| 116 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 117 | + }), | |
| 118 | + ); | |
| 119 | + }); | |
| 120 | + | |
| 121 | + it("should not include context when index not provided", () => { | |
| 122 | + expect(() => { | |
| 123 | + validateSingleEdit("same", "same"); | |
| 124 | + }).toThrowError( | |
| 125 | + expect.objectContaining({ | |
| 126 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 127 | + }), | |
| 128 | + ); | |
| 129 | + }); | |
| 130 | + }); | |
| 131 | +}); | |
| 132 | + | |
| 133 | +describe("trimEmptyLines", () => { | |
| 134 | + it("trims leading empty lines from start", () => { | |
| 135 | + const input = ["", "", "a", "", "b"]; | |
| 136 | + const result = trimEmptyLines({ lines: input, fromEnd: false }); | |
| 137 | + expect(result).toEqual(["a", "", "b"]); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("trims trailing empty lines from end", () => { | |
| 141 | + const input = ["a", "", "b", "", ""]; | |
| 142 | + const result = trimEmptyLines({ lines: input, fromEnd: true }); | |
| 143 | + expect(result).toEqual(["a", "", "b"]); | |
| 144 | + }); | |
| 145 | + | |
| 146 | + it("returns empty array when all lines are empty", () => { | |
| 147 | + const input = ["", "", ""]; | |
| 148 | + const result = trimEmptyLines({ lines: input, fromEnd: false }); | |
| 149 | + expect(result).toEqual([]); | |
| 150 | + }); | |
| 151 | +}); |
| @@ -1,618 +0,0 @@ | ||
| 1 | -import { findSearchMatch, SearchMatchResult } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -/** | |
| 4 | - * Helper function to perform a replacement using the match result | |
| 5 | - * This simulates what the actual replacement tool would do | |
| 6 | - */ | |
| 7 | -function performReplacement( | |
| 8 | - fileContent: string, | |
| 9 | - match: SearchMatchResult, | |
| 10 | - replacement: string, | |
| 11 | -): string { | |
| 12 | - return ( | |
| 13 | - fileContent.substring(0, match.startIndex) + | |
| 14 | - replacement + | |
| 15 | - fileContent.substring(match.endIndex) | |
| 16 | - ); | |
| 17 | -} | |
| 18 | - | |
| 19 | -/** | |
| 20 | - * Helper function to test a specific strategy by crafting inputs that | |
| 21 | - * will fail all previous strategies | |
| 22 | - */ | |
| 23 | -function testSpecificStrategy( | |
| 24 | - fileContent: string, | |
| 25 | - searchContent: string, | |
| 26 | - expectedStrategy: string, | |
| 27 | -): SearchMatchResult | null { | |
| 28 | - const result = findSearchMatch(fileContent, searchContent); | |
| 29 | - if (result && result.strategyName !== expectedStrategy) { | |
| 30 | - throw new Error( | |
| 31 | - `Expected strategy ${expectedStrategy} but got ${result.strategyName}`, | |
| 32 | - ); | |
| 33 | - } | |
| 34 | - return result; | |
| 35 | -} | |
| 36 | - | |
| 37 | -/** | |
| 38 | - * Helper function to verify that a match result correctly identifies | |
| 39 | - * the intended content and replacement works properly | |
| 40 | - */ | |
| 41 | -function verifyMatchAndReplacement( | |
| 42 | - fileContent: string, | |
| 43 | - searchContent: string, | |
| 44 | - expectedMatchedText: string, | |
| 45 | - replacementText: string, | |
| 46 | - expectedResult: string, | |
| 47 | -): void { | |
| 48 | - const match = findSearchMatch(fileContent, searchContent); | |
| 49 | - | |
| 50 | - if (!match) { | |
| 51 | - throw new Error("No match found"); | |
| 52 | - } | |
| 53 | - | |
| 54 | - // Verify the match captures the expected text | |
| 55 | - const actualMatchedText = fileContent.substring( | |
| 56 | - match.startIndex, | |
| 57 | - match.endIndex, | |
| 58 | - ); | |
| 59 | - expect(actualMatchedText).toBe(expectedMatchedText); | |
| 60 | - | |
| 61 | - // Verify replacement works correctly | |
| 62 | - const result = performReplacement(fileContent, match, replacementText); | |
| 63 | - expect(result).toBe(expectedResult); | |
| 64 | -} | |
| 65 | - | |
| 66 | -describe("Strategy-specific tests", () => { | |
| 67 | - describe("exactMatch strategy", () => { | |
| 68 | - it("should handle exact match at various positions", () => { | |
| 69 | - const testCases = [ | |
| 70 | - { | |
| 71 | - name: "at start", | |
| 72 | - fileContent: "abc def ghi", | |
| 73 | - searchContent: "abc", | |
| 74 | - expectedStart: 0, | |
| 75 | - expectedEnd: 3, | |
| 76 | - }, | |
| 77 | - { | |
| 78 | - name: "in middle", | |
| 79 | - fileContent: "abc def ghi", | |
| 80 | - searchContent: "def", | |
| 81 | - expectedStart: 4, | |
| 82 | - expectedEnd: 7, | |
| 83 | - }, | |
| 84 | - { | |
| 85 | - name: "at end", | |
| 86 | - fileContent: "abc def ghi", | |
| 87 | - searchContent: "ghi", | |
| 88 | - expectedStart: 8, | |
| 89 | - expectedEnd: 11, | |
| 90 | - }, | |
| 91 | - { | |
| 92 | - name: "entire content", | |
| 93 | - fileContent: "abc def ghi", | |
| 94 | - searchContent: "abc def ghi", | |
| 95 | - expectedStart: 0, | |
| 96 | - expectedEnd: 11, | |
| 97 | - }, | |
| 98 | - ]; | |
| 99 | - | |
| 100 | - testCases.forEach( | |
| 101 | - ({ name, fileContent, searchContent, expectedStart, expectedEnd }) => { | |
| 102 | - const result = testSpecificStrategy( | |
| 103 | - fileContent, | |
| 104 | - searchContent, | |
| 105 | - "exactMatch", | |
| 106 | - ); | |
| 107 | - expect(result).not.toBeNull(); | |
| 108 | - expect(result!.startIndex).toBe(expectedStart); | |
| 109 | - expect(result!.endIndex).toBe(expectedEnd); | |
| 110 | - | |
| 111 | - // Verify the matched content | |
| 112 | - const matchedContent = fileContent.substring( | |
| 113 | - result!.startIndex, | |
| 114 | - result!.endIndex, | |
| 115 | - ); | |
| 116 | - expect(matchedContent).toBe(searchContent); | |
| 117 | - }, | |
| 118 | - ); | |
| 119 | - }); | |
| 120 | - | |
| 121 | - it("should handle multiline exact matches", () => { | |
| 122 | - const fileContent = `line1 | |
| 123 | -line2 | |
| 124 | -line3 | |
| 125 | -line4`; | |
| 126 | - const searchContent = `line2 | |
| 127 | -line3`; | |
| 128 | - | |
| 129 | - const result = testSpecificStrategy( | |
| 130 | - fileContent, | |
| 131 | - searchContent, | |
| 132 | - "exactMatch", | |
| 133 | - ); | |
| 134 | - expect(result).not.toBeNull(); | |
| 135 | - expect(result!.startIndex).toBe(6); // After "line1\n" | |
| 136 | - expect(result!.endIndex).toBe(17); // End of "line3" | |
| 137 | - | |
| 138 | - const matchedContent = fileContent.substring( | |
| 139 | - result!.startIndex, | |
| 140 | - result!.endIndex, | |
| 141 | - ); | |
| 142 | - expect(matchedContent).toBe(searchContent); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - it("should handle content with special characters", () => { | |
| 146 | - const fileContent = `const regex = /[a-z]+/gi; | |
| 147 | -const str = "Hello, World!"; | |
| 148 | -const result = str.match(regex);`; | |
| 149 | - const searchContent = `const str = "Hello, World!";`; | |
| 150 | - | |
| 151 | - const result = testSpecificStrategy( | |
| 152 | - fileContent, | |
| 153 | - searchContent, | |
| 154 | - "exactMatch", | |
| 155 | - ); | |
| 156 | - expect(result).not.toBeNull(); | |
| 157 | - | |
| 158 | - const matchedContent = fileContent.substring( | |
| 159 | - result!.startIndex, | |
| 160 | - result!.endIndex, | |
| 161 | - ); | |
| 162 | - expect(matchedContent).toBe(searchContent); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should verify replacement works correctly for exact matches", () => { | |
| 166 | - verifyMatchAndReplacement( | |
| 167 | - "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 168 | - "const b = 2;", | |
| 169 | - "const b = 2;", | |
| 170 | - "const b = 42;", | |
| 171 | - "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 172 | - ); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - it("should handle Windows-style line endings", () => { | |
| 176 | - const fileContent = "line1\r\nline2\r\nline3"; | |
| 177 | - const searchContent = "line2"; | |
| 178 | - | |
| 179 | - const result = testSpecificStrategy( | |
| 180 | - fileContent, | |
| 181 | - searchContent, | |
| 182 | - "exactMatch", | |
| 183 | - ); | |
| 184 | - expect(result).not.toBeNull(); | |
| 185 | - expect(result!.startIndex).toBe(7); // After "line1\r\n" | |
| 186 | - expect(result!.endIndex).toBe(12); // End of "line2" | |
| 187 | - }); | |
| 188 | - | |
| 189 | - it("should handle mixed line endings", () => { | |
| 190 | - const fileContent = "line1\nline2\r\nline3\rline4"; | |
| 191 | - const searchContent = "line2\r\nline3"; | |
| 192 | - | |
| 193 | - const result = testSpecificStrategy( | |
| 194 | - fileContent, | |
| 195 | - searchContent, | |
| 196 | - "exactMatch", | |
| 197 | - ); | |
| 198 | - expect(result).not.toBeNull(); | |
| 199 | - | |
| 200 | - const matchedContent = fileContent.substring( | |
| 201 | - result!.startIndex, | |
| 202 | - result!.endIndex, | |
| 203 | - ); | |
| 204 | - expect(matchedContent).toBe(searchContent); | |
| 205 | - }); | |
| 206 | - }); | |
| 207 | - | |
| 208 | - describe("trimmedMatch strategy", () => { | |
| 209 | - it("should match when only whitespace differs at edges", () => { | |
| 210 | - const testCases = [ | |
| 211 | - { | |
| 212 | - name: "leading spaces", | |
| 213 | - fileContent: "abc\n def\nghi", | |
| 214 | - searchContent: " def", | |
| 215 | - trimmedSearch: "def", | |
| 216 | - }, | |
| 217 | - { | |
| 218 | - name: "trailing spaces", | |
| 219 | - fileContent: "abc\ndef \nghi", | |
| 220 | - searchContent: "def ", | |
| 221 | - trimmedSearch: "def", | |
| 222 | - }, | |
| 223 | - { | |
| 224 | - name: "both leading and trailing", | |
| 225 | - fileContent: "abc\n def \nghi", | |
| 226 | - searchContent: " def ", | |
| 227 | - trimmedSearch: "def", | |
| 228 | - }, | |
| 229 | - { | |
| 230 | - name: "tabs and spaces", | |
| 231 | - fileContent: "abc\n\t def \t\nghi", | |
| 232 | - searchContent: "\t def \t", | |
| 233 | - trimmedSearch: "def", | |
| 234 | - }, | |
| 235 | - ]; | |
| 236 | - | |
| 237 | - testCases.forEach( | |
| 238 | - ({ name, fileContent, searchContent, trimmedSearch }) => { | |
| 239 | - const result = findSearchMatch(fileContent, searchContent); | |
| 240 | - expect(result).not.toBeNull(); | |
| 241 | - | |
| 242 | - // For cases where exact match exists, it should be preferred | |
| 243 | - if (fileContent.indexOf(searchContent) !== -1) { | |
| 244 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 245 | - const matchedContent = fileContent.substring( | |
| 246 | - result!.startIndex, | |
| 247 | - result!.endIndex, | |
| 248 | - ); | |
| 249 | - expect(matchedContent).toBe(searchContent); | |
| 250 | - } else { | |
| 251 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 252 | - // The match should find the trimmed content with surrounding whitespace | |
| 253 | - const matchedContent = fileContent.substring( | |
| 254 | - result!.startIndex, | |
| 255 | - result!.endIndex, | |
| 256 | - ); | |
| 257 | - expect(matchedContent).toContain(trimmedSearch); | |
| 258 | - } | |
| 259 | - }, | |
| 260 | - ); | |
| 261 | - }); | |
| 262 | - | |
| 263 | - it("should handle multiline content with edge whitespace", () => { | |
| 264 | - const fileContent = `function test() { | |
| 265 | - const x = 1; | |
| 266 | - const y = 2; | |
| 267 | -}`; | |
| 268 | - const searchContent = ` const x = 1; | |
| 269 | - const y = 2; `; | |
| 270 | - | |
| 271 | - const result = findSearchMatch(fileContent, searchContent); | |
| 272 | - expect(result).not.toBeNull(); | |
| 273 | - // Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used | |
| 274 | - expect(result!.strategyName).toBe("trimmedMatch"); | |
| 275 | - }); | |
| 276 | - | |
| 277 | - it("should verify replacement with trimmed matches", () => { | |
| 278 | - const fileContent = "start\n targetContent \nend"; | |
| 279 | - const searchContent = " targetContent "; | |
| 280 | - const replacement = "newContent"; | |
| 281 | - | |
| 282 | - const match = findSearchMatch(fileContent, searchContent); | |
| 283 | - expect(match).not.toBeNull(); | |
| 284 | - expect(match!.strategyName).toBe("trimmedMatch"); | |
| 285 | - | |
| 286 | - const result = performReplacement(fileContent, match!, replacement); | |
| 287 | - expect(result).toBe("start\nnewContent\nend"); | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle edge case with only whitespace", () => { | |
| 291 | - const fileContent = " \n \n "; | |
| 292 | - const searchContent = " \n "; | |
| 293 | - | |
| 294 | - const result = findSearchMatch(fileContent, searchContent); | |
| 295 | - expect(result).not.toBeNull(); | |
| 296 | - // Should find exact match since the content matches exactly | |
| 297 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 298 | - }); | |
| 299 | - }); | |
| 300 | - | |
| 301 | - describe("whitespaceIgnoredMatch strategy", () => { | |
| 302 | - it("should match content with different indentation", () => { | |
| 303 | - const fileContent = `function test() { | |
| 304 | - const x = 1; | |
| 305 | - if (x > 0) { | |
| 306 | - return true; | |
| 307 | - } | |
| 308 | -}`; | |
| 309 | - const searchContent = `const x=1; | |
| 310 | -if(x>0){ | |
| 311 | -return true; | |
| 312 | -}`; | |
| 313 | - | |
| 314 | - const result = findSearchMatch(fileContent, searchContent); | |
| 315 | - expect(result).not.toBeNull(); | |
| 316 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 317 | - | |
| 318 | - // Verify the match covers the intended code block | |
| 319 | - const matchedContent = fileContent.substring( | |
| 320 | - result!.startIndex, | |
| 321 | - result!.endIndex, | |
| 322 | - ); | |
| 323 | - expect(matchedContent).toContain("const x = 1"); | |
| 324 | - expect(matchedContent).toContain("return true"); | |
| 325 | - }); | |
| 326 | - | |
| 327 | - it("should handle complex whitespace variations", () => { | |
| 328 | - const testCases = [ | |
| 329 | - { | |
| 330 | - name: "spaces vs tabs", | |
| 331 | - fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}", | |
| 332 | - searchContent: "if (condition) { return true; }", | |
| 333 | - }, | |
| 334 | - { | |
| 335 | - name: "multiple spaces collapsed", | |
| 336 | - fileContent: "const result = calculate( x , y );", | |
| 337 | - searchContent: "const result=calculate(x,y);", | |
| 338 | - }, | |
| 339 | - { | |
| 340 | - name: "newlines removed", | |
| 341 | - fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}", | |
| 342 | - searchContent: "function test(){return 1;}", | |
| 343 | - }, | |
| 344 | - ]; | |
| 345 | - | |
| 346 | - testCases.forEach(({ name, fileContent, searchContent }) => { | |
| 347 | - const result = findSearchMatch(fileContent, searchContent); | |
| 348 | - expect(result).not.toBeNull(); | |
| 349 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 350 | - | |
| 351 | - // Verify the entire content is matched | |
| 352 | - const matchedContent = fileContent.substring( | |
| 353 | - result!.startIndex, | |
| 354 | - result!.endIndex, | |
| 355 | - ); | |
| 356 | - expect(matchedContent.replace(/\s/g, "")).toBe( | |
| 357 | - searchContent.replace(/\s/g, ""), | |
| 358 | - ); | |
| 359 | - }); | |
| 360 | - }); | |
| 361 | - | |
| 362 | - it("should handle partial matches with whitespace differences", () => { | |
| 363 | - const fileContent = `class Example { | |
| 364 | - constructor(name) { | |
| 365 | - this.name = name; | |
| 366 | - this.items = []; | |
| 367 | - } | |
| 368 | - | |
| 369 | - addItem(item) { | |
| 370 | - this.items.push(item); | |
| 371 | - } | |
| 372 | -}`; | |
| 373 | - const searchContent = `constructor(name){this.name=name;this.items=[];}`; | |
| 374 | - | |
| 375 | - const result = findSearchMatch(fileContent, searchContent); | |
| 376 | - expect(result).not.toBeNull(); | |
| 377 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 378 | - | |
| 379 | - // The match should cover the constructor method | |
| 380 | - const matchedContent = fileContent.substring( | |
| 381 | - result!.startIndex, | |
| 382 | - result!.endIndex, | |
| 383 | - ); | |
| 384 | - expect(matchedContent).toContain("constructor"); | |
| 385 | - expect(matchedContent).toContain("this.items = []"); | |
| 386 | - }); | |
| 387 | - | |
| 388 | - it("should verify replacement with whitespace-ignored matches", () => { | |
| 389 | - const fileContent = `function calculate ( a , b ) { | |
| 390 | - return a + b ; | |
| 391 | -}`; | |
| 392 | - const searchContent = `function calculate(a,b){return a+b;}`; | |
| 393 | - const replacement = `function calculate(x, y) { | |
| 394 | - return x + y; | |
| 395 | -}`; | |
| 396 | - | |
| 397 | - const match = findSearchMatch(fileContent, searchContent); | |
| 398 | - expect(match).not.toBeNull(); | |
| 399 | - expect(match!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 400 | - | |
| 401 | - const result = performReplacement(fileContent, match!, replacement); | |
| 402 | - expect(result).toBe(replacement); | |
| 403 | - }); | |
| 404 | - | |
| 405 | - it("should handle edge cases with empty content after whitespace removal", () => { | |
| 406 | - const fileContent = " \n\t\r\n "; | |
| 407 | - const searchContent = " \n "; | |
| 408 | - | |
| 409 | - const result = findSearchMatch(fileContent, searchContent); | |
| 410 | - // Since search content doesn't exist in file but trims to empty, should return emptySearch | |
| 411 | - expect(result).not.toBeNull(); | |
| 412 | - expect(result!.strategyName).toBe("emptySearch"); | |
| 413 | - }); | |
| 414 | - | |
| 415 | - it("should match correctly when multiple potential matches exist", () => { | |
| 416 | - const fileContent = `const a=1; | |
| 417 | -const a = 1 ; | |
| 418 | -const a = 1;`; | |
| 419 | - const searchContent = "const a = 1;"; | |
| 420 | - | |
| 421 | - const result = findSearchMatch(fileContent, searchContent); | |
| 422 | - expect(result).not.toBeNull(); | |
| 423 | - // Should find the exact match first (third occurrence) | |
| 424 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 425 | - expect(result!.startIndex).toBe(33); // After first two lines | |
| 426 | - }); | |
| 427 | - }); | |
| 428 | - | |
| 429 | - describe("Empty search content", () => { | |
| 430 | - it("should always return position 0 for empty search", () => { | |
| 431 | - const testCases = [ | |
| 432 | - { fileContent: "some content" }, | |
| 433 | - { fileContent: "" }, | |
| 434 | - { fileContent: "line1\nline2\nline3" }, | |
| 435 | - { fileContent: " spaces " }, | |
| 436 | - ]; | |
| 437 | - | |
| 438 | - testCases.forEach(({ fileContent }) => { | |
| 439 | - const result = findSearchMatch(fileContent, ""); | |
| 440 | - expect(result).toEqual({ | |
| 441 | - startIndex: 0, | |
| 442 | - endIndex: 0, | |
| 443 | - strategyName: "emptySearch", | |
| 444 | - }); | |
| 445 | - }); | |
| 446 | - }); | |
| 447 | - | |
| 448 | - it("should treat whitespace-only search as empty", () => { | |
| 449 | - const searchVariants = [" ", "\n\n", "\t\t", " \n\t "]; | |
| 450 | - | |
| 451 | - searchVariants.forEach((searchContent) => { | |
| 452 | - const result = findSearchMatch("test content", searchContent); | |
| 453 | - expect(result).toEqual({ | |
| 454 | - startIndex: 0, | |
| 455 | - endIndex: 0, | |
| 456 | - strategyName: "emptySearch", | |
| 457 | - }); | |
| 458 | - }); | |
| 459 | - }); | |
| 460 | - }); | |
| 461 | - | |
| 462 | - describe("Strategy precedence", () => { | |
| 463 | - it("should always prefer exact match over other strategies", () => { | |
| 464 | - const fileContent = `exact match | |
| 465 | -exact match with spaces | |
| 466 | -exactmatch`; | |
| 467 | - | |
| 468 | - // This should find exact match even though fuzzy would also work | |
| 469 | - const result = findSearchMatch(fileContent, "exact match"); | |
| 470 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 471 | - expect(result!.startIndex).toBe(0); | |
| 472 | - }); | |
| 473 | - | |
| 474 | - it("should prefer trimmed match over whitespace-ignored", () => { | |
| 475 | - const fileContent = " content "; | |
| 476 | - const searchContent = " content "; | |
| 477 | - | |
| 478 | - // Should find exact match | |
| 479 | - const result = findSearchMatch(fileContent, searchContent); | |
| 480 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 481 | - }); | |
| 482 | - | |
| 483 | - it("should prefer whitespace-ignored over fuzzy", () => { | |
| 484 | - const fileContent = "const x = 1;"; | |
| 485 | - const searchContent = "const x=1;"; | |
| 486 | - | |
| 487 | - // Should use whitespace-ignored, not fuzzy | |
| 488 | - const result = findSearchMatch(fileContent, searchContent); | |
| 489 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 490 | - }); | |
| 491 | - }); | |
| 492 | - | |
| 493 | - describe("Replacement verification tests", () => { | |
| 494 | - it("should correctly replace content found by each strategy", () => { | |
| 495 | - const testCases = [ | |
| 496 | - { | |
| 497 | - name: "exact match replacement", | |
| 498 | - fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;", | |
| 499 | - searchContent: "const b = 2;", | |
| 500 | - replacement: "const b = 42;", | |
| 501 | - expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;", | |
| 502 | - expectedStrategy: "exactMatch", | |
| 503 | - }, | |
| 504 | - { | |
| 505 | - name: "trimmed match replacement", | |
| 506 | - fileContent: "start\n target \nend", | |
| 507 | - searchContent: " target ", | |
| 508 | - replacement: "replaced", | |
| 509 | - expectedResult: "start\nreplaced\nend", | |
| 510 | - expectedStrategy: "trimmedMatch", | |
| 511 | - }, | |
| 512 | - { | |
| 513 | - name: "whitespace-ignored replacement", | |
| 514 | - fileContent: "if ( x > 0 ) { return true; }", | |
| 515 | - searchContent: "if(x>0){return true;}", | |
| 516 | - replacement: "if (x > 0) { return false; }", | |
| 517 | - expectedResult: "if (x > 0) { return false; }", | |
| 518 | - expectedStrategy: "whitespaceIgnoredMatch", | |
| 519 | - }, | |
| 520 | - ]; | |
| 521 | - | |
| 522 | - testCases.forEach( | |
| 523 | - ({ | |
| 524 | - name, | |
| 525 | - fileContent, | |
| 526 | - searchContent, | |
| 527 | - replacement, | |
| 528 | - expectedResult, | |
| 529 | - expectedStrategy, | |
| 530 | - }) => { | |
| 531 | - const match = findSearchMatch(fileContent, searchContent); | |
| 532 | - expect(match).not.toBeNull(); | |
| 533 | - expect(match!.strategyName).toBe(expectedStrategy); | |
| 534 | - | |
| 535 | - const result = performReplacement(fileContent, match!, replacement); | |
| 536 | - expect(result).toBe(expectedResult); | |
| 537 | - }, | |
| 538 | - ); | |
| 539 | - }); | |
| 540 | - | |
| 541 | - it("should handle edge cases in replacement", () => { | |
| 542 | - // Empty replacement | |
| 543 | - verifyMatchAndReplacement( | |
| 544 | - "before target after", | |
| 545 | - "target", | |
| 546 | - "target", | |
| 547 | - "", | |
| 548 | - "before after", | |
| 549 | - ); | |
| 550 | - | |
| 551 | - // Replacement longer than original | |
| 552 | - verifyMatchAndReplacement( | |
| 553 | - "short", | |
| 554 | - "short", | |
| 555 | - "short", | |
| 556 | - "much longer replacement", | |
| 557 | - "much longer replacement", | |
| 558 | - ); | |
| 559 | - | |
| 560 | - // Multiline replacement | |
| 561 | - verifyMatchAndReplacement( | |
| 562 | - "single line", | |
| 563 | - "single", | |
| 564 | - "single", | |
| 565 | - "multi\nline\nreplacement", | |
| 566 | - "multi\nline\nreplacement line", | |
| 567 | - ); | |
| 568 | - }); | |
| 569 | - }); | |
| 570 | - | |
| 571 | - describe("Performance and edge cases", () => { | |
| 572 | - it("should handle very long content efficiently", () => { | |
| 573 | - const longContent = "x".repeat(10000) + "target" + "y".repeat(10000); | |
| 574 | - const result = findSearchMatch(longContent, "target"); | |
| 575 | - | |
| 576 | - expect(result).not.toBeNull(); | |
| 577 | - expect(result!.startIndex).toBe(10000); | |
| 578 | - expect(result!.endIndex).toBe(10006); | |
| 579 | - }); | |
| 580 | - | |
| 581 | - it("should handle unicode and special characters", () => { | |
| 582 | - const testCases = [ | |
| 583 | - { | |
| 584 | - fileContent: "const emoji = '🚀🌟🎉';", | |
| 585 | - searchContent: "🚀🌟🎉", | |
| 586 | - }, | |
| 587 | - { | |
| 588 | - fileContent: "const chinese = '你好世界';", | |
| 589 | - searchContent: "你好世界", | |
| 590 | - }, | |
| 591 | - { | |
| 592 | - fileContent: "const regex = /\\d+/g;", | |
| 593 | - searchContent: "/\\d+/g", | |
| 594 | - }, | |
| 595 | - ]; | |
| 596 | - | |
| 597 | - testCases.forEach(({ fileContent, searchContent }) => { | |
| 598 | - const result = findSearchMatch(fileContent, searchContent); | |
| 599 | - expect(result).not.toBeNull(); | |
| 600 | - | |
| 601 | - const matchedContent = fileContent.substring( | |
| 602 | - result!.startIndex, | |
| 603 | - result!.endIndex, | |
| 604 | - ); | |
| 605 | - expect(matchedContent).toContain(searchContent); | |
| 606 | - }); | |
| 607 | - }); | |
| 608 | - | |
| 609 | - it("should handle null bytes and control characters", () => { | |
| 610 | - const fileContent = "before\x00null\x01byte\x02after"; | |
| 611 | - const searchContent = "\x00null\x01byte\x02"; | |
| 612 | - | |
| 613 | - const result = findSearchMatch(fileContent, searchContent); | |
| 614 | - expect(result).not.toBeNull(); | |
| 615 | - expect(result!.strategyName).toBe("exactMatch"); | |
| 616 | - }); | |
| 617 | - }); | |
| 618 | -}); |
| @@ -1,587 +0,0 @@ | ||
| 1 | -import { findSearchMatch } from "./findSearchMatch"; | |
| 2 | - | |
| 3 | -describe("Exact matches", () => { | |
| 4 | - it("should find exact match at the beginning of file", () => { | |
| 5 | - const fileContent = `function hello() { | |
| 6 | - console.log("world"); | |
| 7 | -}`; | |
| 8 | - const searchContent = `function hello() { | |
| 9 | - console.log("world"); | |
| 10 | -}`; | |
| 11 | - | |
| 12 | - const result = findSearchMatch(fileContent, searchContent); | |
| 13 | - | |
| 14 | - expect(result).toEqual({ | |
| 15 | - startIndex: 0, | |
| 16 | - endIndex: fileContent.length, | |
| 17 | - strategyName: "exactMatch", | |
| 18 | - }); | |
| 19 | - }); | |
| 20 | - | |
| 21 | - it("should find exact match in the middle of file", () => { | |
| 22 | - const fileContent = `const a = 1; | |
| 23 | -function hello() { | |
| 24 | - console.log("world"); | |
| 25 | -} | |
| 26 | -const b = 2;`; | |
| 27 | - const searchContent = `function hello() { | |
| 28 | - console.log("world"); | |
| 29 | -}`; | |
| 30 | - | |
| 31 | - const result = findSearchMatch(fileContent, searchContent); | |
| 32 | - | |
| 33 | - expect(result).toEqual({ | |
| 34 | - startIndex: 13, // After "const a = 1;\n" | |
| 35 | - endIndex: 13 + searchContent.length, | |
| 36 | - strategyName: "exactMatch", | |
| 37 | - }); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - it("should find exact match at the end of file", () => { | |
| 41 | - const fileContent = `const a = 1; | |
| 42 | -function hello() { | |
| 43 | - console.log("world"); | |
| 44 | -}`; | |
| 45 | - const searchContent = `function hello() { | |
| 46 | - console.log("world"); | |
| 47 | -}`; | |
| 48 | - | |
| 49 | - const result = findSearchMatch(fileContent, searchContent); | |
| 50 | - | |
| 51 | - expect(result).toEqual({ | |
| 52 | - startIndex: 13, // After "const a = 1;\n" | |
| 53 | - endIndex: fileContent.length, | |
| 54 | - strategyName: "exactMatch", | |
| 55 | - }); | |
| 56 | - }); | |
| 57 | - | |
| 58 | - it("should find exact match with single line", () => { | |
| 59 | - const fileContent = `const a = 1; | |
| 60 | -const b = 2; | |
| 61 | -const c = 3;`; | |
| 62 | - const searchContent = `const b = 2;`; | |
| 63 | - | |
| 64 | - const result = findSearchMatch(fileContent, searchContent); | |
| 65 | - | |
| 66 | - expect(result).toEqual({ | |
| 67 | - startIndex: 13, // After "const a = 1;\n" | |
| 68 | - endIndex: 13 + searchContent.length, | |
| 69 | - strategyName: "exactMatch", | |
| 70 | - }); | |
| 71 | - }); | |
| 72 | - | |
| 73 | - it("should find exact match with whitespace preserved", () => { | |
| 74 | - const fileContent = `function test() { | |
| 75 | - const x = 1; | |
| 76 | - const y = 2; | |
| 77 | -}`; | |
| 78 | - const searchContent = ` const x = 1; | |
| 79 | - const y = 2;`; | |
| 80 | - | |
| 81 | - const result = findSearchMatch(fileContent, searchContent); | |
| 82 | - | |
| 83 | - // The actual indexOf result is 18, not 17 | |
| 84 | - expect(result).toEqual({ | |
| 85 | - startIndex: 18, | |
| 86 | - endIndex: 18 + searchContent.length, | |
| 87 | - strategyName: "exactMatch", | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | -}); | |
| 91 | - | |
| 92 | -describe("Trimmed matches", () => { | |
| 93 | - it("should find trimmed match when exact match fails due to leading newlines", () => { | |
| 94 | - const fileContent = `function hello() { | |
| 95 | - console.log("world"); | |
| 96 | -}`; | |
| 97 | - const searchContent = `\n\nfunction hello() { | |
| 98 | - console.log("world"); | |
| 99 | -}\n\n`; | |
| 100 | - | |
| 101 | - const result = findSearchMatch(fileContent, searchContent); | |
| 102 | - | |
| 103 | - expect(result).toEqual({ | |
| 104 | - startIndex: 0, | |
| 105 | - endIndex: fileContent.length, // Uses trimmed length | |
| 106 | - strategyName: "trimmedMatch", | |
| 107 | - }); | |
| 108 | - }); | |
| 109 | - | |
| 110 | - it("should find trimmed match when exact match fails due to trailing newlines", () => { | |
| 111 | - const fileContent = `const a = 1; | |
| 112 | -function hello() { | |
| 113 | - return "world"; | |
| 114 | -} | |
| 115 | -const b = 2;`; | |
| 116 | - const searchContent = `\nfunction hello() { | |
| 117 | - return "world"; | |
| 118 | -}\n`; | |
| 119 | - | |
| 120 | - const result = findSearchMatch(fileContent, searchContent); | |
| 121 | - | |
| 122 | - // The function finds the exact match first (at index 12), not the trimmed match | |
| 123 | - expect(result).toEqual({ | |
| 124 | - startIndex: 12, | |
| 125 | - endIndex: 12 + searchContent.length, | |
| 126 | - strategyName: "exactMatch", | |
| 127 | - }); | |
| 128 | - }); | |
| 129 | - | |
| 130 | - it("should find trimmed match for single line with extra whitespace", () => { | |
| 131 | - const fileContent = `const a = 1; | |
| 132 | -const b = 2; | |
| 133 | -const c = 3;`; | |
| 134 | - const searchContent = `\n const b = 2; \n`; | |
| 135 | - | |
| 136 | - const result = findSearchMatch(fileContent, searchContent); | |
| 137 | - | |
| 138 | - const trimmedSearchContent = searchContent.trim(); | |
| 139 | - const expectedStart = fileContent.indexOf(trimmedSearchContent); | |
| 140 | - | |
| 141 | - expect(result).toEqual({ | |
| 142 | - startIndex: expectedStart, | |
| 143 | - endIndex: expectedStart + trimmedSearchContent.length, | |
| 144 | - strategyName: "trimmedMatch", | |
| 145 | - }); | |
| 146 | - }); | |
| 147 | -}); | |
| 148 | - | |
| 149 | -describe("Empty search content", () => { | |
| 150 | - it("should match at beginning for empty search content", () => { | |
| 151 | - const fileContent = `function hello() { | |
| 152 | - console.log("world"); | |
| 153 | -}`; | |
| 154 | - const searchContent = ""; | |
| 155 | - | |
| 156 | - const result = findSearchMatch(fileContent, searchContent); | |
| 157 | - | |
| 158 | - expect(result).toEqual({ | |
| 159 | - startIndex: 0, | |
| 160 | - endIndex: 0, | |
| 161 | - strategyName: "emptySearch", | |
| 162 | - }); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should match at beginning for whitespace-only search content", () => { | |
| 166 | - const fileContent = `function hello() { | |
| 167 | - console.log("world"); | |
| 168 | -}`; | |
| 169 | - const searchContent = "\n\n \t \n"; | |
| 170 | - | |
| 171 | - const result = findSearchMatch(fileContent, searchContent); | |
| 172 | - | |
| 173 | - expect(result).toEqual({ | |
| 174 | - startIndex: 0, | |
| 175 | - endIndex: 0, | |
| 176 | - strategyName: "emptySearch", | |
| 177 | - }); | |
| 178 | - }); | |
| 179 | - | |
| 180 | - it("should match at beginning for empty file and empty search", () => { | |
| 181 | - const fileContent = ""; | |
| 182 | - const searchContent = ""; | |
| 183 | - | |
| 184 | - const result = findSearchMatch(fileContent, searchContent); | |
| 185 | - | |
| 186 | - expect(result).toEqual({ | |
| 187 | - startIndex: 0, | |
| 188 | - endIndex: 0, | |
| 189 | - strategyName: "emptySearch", | |
| 190 | - }); | |
| 191 | - }); | |
| 192 | -}); | |
| 193 | - | |
| 194 | -describe("Edge cases", () => { | |
| 195 | - it("should handle empty file with non-empty search", () => { | |
| 196 | - const fileContent = ""; | |
| 197 | - const searchContent = "function hello() {}"; | |
| 198 | - | |
| 199 | - const result = findSearchMatch(fileContent, searchContent); | |
| 200 | - | |
| 201 | - expect(result).toBeNull(); | |
| 202 | - }); | |
| 203 | - | |
| 204 | - it("should handle very large content", () => { | |
| 205 | - const repeatedLine = "const x = 1;\n"; | |
| 206 | - const fileContent = | |
| 207 | - repeatedLine.repeat(1000) + | |
| 208 | - "const target = 2;\n" + | |
| 209 | - repeatedLine.repeat(1000); | |
| 210 | - const searchContent = "const target = 2;"; | |
| 211 | - | |
| 212 | - const result = findSearchMatch(fileContent, searchContent); | |
| 213 | - | |
| 214 | - const expectedStart = repeatedLine.length * 1000; | |
| 215 | - expect(result).toEqual({ | |
| 216 | - startIndex: expectedStart, | |
| 217 | - endIndex: expectedStart + searchContent.length, | |
| 218 | - strategyName: "exactMatch", | |
| 219 | - }); | |
| 220 | - }); | |
| 221 | - | |
| 222 | - it("should handle special characters and symbols", () => { | |
| 223 | - const fileContent = `const regex = /[a-zA-Z]+/g; | |
| 224 | -const symbols = !@#$%^&*(); | |
| 225 | -const unicode = "🚀 Hello 世界";`; | |
| 226 | - const searchContent = `const symbols = !@#$%^&*();`; | |
| 227 | - | |
| 228 | - const result = findSearchMatch(fileContent, searchContent); | |
| 229 | - | |
| 230 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 231 | - expect(result).toEqual({ | |
| 232 | - startIndex: expectedStart, | |
| 233 | - endIndex: expectedStart + searchContent.length, | |
| 234 | - strategyName: "exactMatch", | |
| 235 | - }); | |
| 236 | - }); | |
| 237 | - | |
| 238 | - it("should prefer exact match over trimmed match", () => { | |
| 239 | - const fileContent = `function test() { | |
| 240 | - const x = 1; | |
| 241 | -} | |
| 242 | - | |
| 243 | -function test() { | |
| 244 | - const x = 1; | |
| 245 | -}`; | |
| 246 | - const searchContent = `function test() { | |
| 247 | - const x = 1; | |
| 248 | -}`; | |
| 249 | - | |
| 250 | - const result = findSearchMatch(fileContent, searchContent); | |
| 251 | - | |
| 252 | - // Should find the first exact match, not a trimmed version | |
| 253 | - expect(result).toEqual({ | |
| 254 | - startIndex: 0, | |
| 255 | - endIndex: searchContent.length, | |
| 256 | - strategyName: "exactMatch", | |
| 257 | - }); | |
| 258 | - }); | |
| 259 | - | |
| 260 | - it("should handle multiple occurrences and return first match", () => { | |
| 261 | - const fileContent = `const a = 1; | |
| 262 | -const b = 2; | |
| 263 | -const a = 1;`; | |
| 264 | - const searchContent = `const a = 1;`; | |
| 265 | - | |
| 266 | - const result = findSearchMatch(fileContent, searchContent); | |
| 267 | - | |
| 268 | - expect(result).toEqual({ | |
| 269 | - startIndex: 0, | |
| 270 | - endIndex: searchContent.length, | |
| 271 | - strategyName: "exactMatch", | |
| 272 | - }); | |
| 273 | - }); | |
| 274 | -}); | |
| 275 | - | |
| 276 | -describe("Whitespace-ignored matches", () => { | |
| 277 | - it("should match code with different indentation", () => { | |
| 278 | - const fileContent = `function example() { | |
| 279 | - const x = 1; | |
| 280 | - const y = 2; | |
| 281 | - return x + y; | |
| 282 | -}`; | |
| 283 | - const searchContent = `const x=1; | |
| 284 | -const y=2; | |
| 285 | -return x+y;`; | |
| 286 | - | |
| 287 | - const result = findSearchMatch(fileContent, searchContent); | |
| 288 | - | |
| 289 | - expect(result).not.toBeNull(); | |
| 290 | - expect(result!.startIndex).toBe(20); // After "function example() {\n" | |
| 291 | - expect(result!.endIndex).toBe(72); // End of " return x + y;" | |
| 292 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 293 | - | |
| 294 | - // Verify the matched content contains the original whitespace | |
| 295 | - const matchedContent = fileContent.substring( | |
| 296 | - result!.startIndex, | |
| 297 | - result!.endIndex, | |
| 298 | - ); | |
| 299 | - expect(matchedContent).toBe(` | |
| 300 | - const x = 1; | |
| 301 | - const y = 2; | |
| 302 | - return x + y;`); | |
| 303 | - }); | |
| 304 | - | |
| 305 | - it("should match single line with different spacing", () => { | |
| 306 | - const fileContent = `const a = 1; | |
| 307 | -const b = 2; | |
| 308 | -const c = 3;`; | |
| 309 | - const searchContent = `const b=2;`; | |
| 310 | - | |
| 311 | - const result = findSearchMatch(fileContent, searchContent); | |
| 312 | - | |
| 313 | - expect(result).not.toBeNull(); | |
| 314 | - expect(result!.startIndex).toBe(12); // After "const a = 1;" | |
| 315 | - expect(result!.endIndex).toBe(32); // End of "const b = 2;" | |
| 316 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 317 | - | |
| 318 | - // Verify the matched content preserves original spacing | |
| 319 | - const matchedContent = fileContent.substring( | |
| 320 | - result!.startIndex, | |
| 321 | - result!.endIndex, | |
| 322 | - ); | |
| 323 | - expect(matchedContent).toBe(` | |
| 324 | -const b = 2;`); | |
| 325 | - }); | |
| 326 | - | |
| 327 | - it("should match with tabs vs spaces", () => { | |
| 328 | - const fileContent = `function test() { | |
| 329 | -\tif (condition) { | |
| 330 | -\t\treturn true; | |
| 331 | -\t} | |
| 332 | -}`; | |
| 333 | - const searchContent = `if (condition) { | |
| 334 | - return true; | |
| 335 | -}`; | |
| 336 | - | |
| 337 | - const result = findSearchMatch(fileContent, searchContent); | |
| 338 | - | |
| 339 | - expect(result).not.toBeNull(); | |
| 340 | - expect(result!.startIndex).toBe(17); // After "function test() {" | |
| 341 | - expect(result!.endIndex).toBe(53); // End of "\t}" | |
| 342 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 343 | - | |
| 344 | - // Verify the matched content preserves original tabs | |
| 345 | - const matchedContent = fileContent.substring( | |
| 346 | - result!.startIndex, | |
| 347 | - result!.endIndex, | |
| 348 | - ); | |
| 349 | - expect(matchedContent).toBe(` | |
| 350 | -\tif (condition) { | |
| 351 | -\t\treturn true; | |
| 352 | -\t}`); | |
| 353 | - }); | |
| 354 | - | |
| 355 | - it("should match complex whitespace patterns", () => { | |
| 356 | - const fileContent = `const obj = { | |
| 357 | - key1 : 'value1', | |
| 358 | - key2 : 'value2', | |
| 359 | - key3 : 'value3' | |
| 360 | -};`; | |
| 361 | - const searchContent = `key1:'value1', | |
| 362 | -key2:'value2', | |
| 363 | -key3:'value3'`; | |
| 364 | - | |
| 365 | - const result = findSearchMatch(fileContent, searchContent); | |
| 366 | - | |
| 367 | - expect(result).not.toBeNull(); | |
| 368 | - expect(result!.startIndex).toBe(13); // After "const obj = {" | |
| 369 | - expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'" | |
| 370 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 371 | - | |
| 372 | - // Verify the matched content preserves original formatting | |
| 373 | - const matchedContent = fileContent.substring( | |
| 374 | - result!.startIndex, | |
| 375 | - result!.endIndex, | |
| 376 | - ); | |
| 377 | - expect(matchedContent).toBe(` | |
| 378 | - key1 : 'value1', | |
| 379 | - key2 : 'value2', | |
| 380 | - key3 : 'value3'`); | |
| 381 | - }); | |
| 382 | - | |
| 383 | - it("should handle newlines and mixed whitespace", () => { | |
| 384 | - const fileContent = `function calc() { | |
| 385 | - | |
| 386 | - | |
| 387 | - let result = 0; | |
| 388 | - | |
| 389 | - result += 5; | |
| 390 | - | |
| 391 | - | |
| 392 | - return result; | |
| 393 | -}`; | |
| 394 | - const searchContent = `let result=0;result+=5;return result;`; | |
| 395 | - | |
| 396 | - const result = findSearchMatch(fileContent, searchContent); | |
| 397 | - | |
| 398 | - expect(result).not.toBeNull(); | |
| 399 | - expect(result!.startIndex).toBe(17); // After "function calc() {\n\n" | |
| 400 | - expect(result!.endIndex).toBe(78); // End of " return result;" | |
| 401 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 402 | - | |
| 403 | - // Verify the matched content includes all original whitespace | |
| 404 | - const matchedContent = fileContent.substring( | |
| 405 | - result!.startIndex, | |
| 406 | - result!.endIndex, | |
| 407 | - ); | |
| 408 | - expect(matchedContent).toBe(` | |
| 409 | - | |
| 410 | - | |
| 411 | - let result = 0; | |
| 412 | - | |
| 413 | - result += 5; | |
| 414 | - | |
| 415 | - | |
| 416 | - return result;`); | |
| 417 | - }); | |
| 418 | - | |
| 419 | - it("should prefer exact match over whitespace-ignored match", () => { | |
| 420 | - const fileContent = `const x=1; | |
| 421 | -const x = 1;`; | |
| 422 | - const searchContent = `const x=1;`; | |
| 423 | - | |
| 424 | - const result = findSearchMatch(fileContent, searchContent); | |
| 425 | - | |
| 426 | - // Should find the exact match first (at index 0), not the whitespace-ignored match | |
| 427 | - expect(result).toEqual({ | |
| 428 | - startIndex: 0, | |
| 429 | - endIndex: 10, | |
| 430 | - strategyName: "exactMatch", | |
| 431 | - }); | |
| 432 | - }); | |
| 433 | - | |
| 434 | - it("should handle empty content after whitespace removal", () => { | |
| 435 | - const fileContent = `function test() { | |
| 436 | - return 1; | |
| 437 | -}`; | |
| 438 | - const searchContent = `\n\n \t \n`; | |
| 439 | - | |
| 440 | - const result = findSearchMatch(fileContent, searchContent); | |
| 441 | - | |
| 442 | - // Should match at beginning for empty/whitespace-only content | |
| 443 | - expect(result).toEqual({ | |
| 444 | - startIndex: 0, | |
| 445 | - endIndex: 0, | |
| 446 | - strategyName: "emptySearch", | |
| 447 | - }); | |
| 448 | - }); | |
| 449 | - | |
| 450 | - it("should handle complex code blocks with different formatting", () => { | |
| 451 | - const fileContent = `class Example { | |
| 452 | - constructor(name) { | |
| 453 | - this.name = name; | |
| 454 | - this.value = 0; | |
| 455 | - } | |
| 456 | - | |
| 457 | - getValue() { | |
| 458 | - return this.value; | |
| 459 | - } | |
| 460 | -}`; | |
| 461 | - const searchContent = `constructor(name){ | |
| 462 | -this.name=name; | |
| 463 | -this.value=0; | |
| 464 | -}`; | |
| 465 | - | |
| 466 | - const result = findSearchMatch(fileContent, searchContent); | |
| 467 | - | |
| 468 | - expect(result).not.toBeNull(); | |
| 469 | - expect(result!.startIndex).toBe(15); // After "class Example {" | |
| 470 | - expect(result!.endIndex).toBe(95); // End of " }" | |
| 471 | - expect(result!.strategyName).toBe("whitespaceIgnoredMatch"); | |
| 472 | - | |
| 473 | - // Verify the matched content preserves original formatting | |
| 474 | - const matchedContent = fileContent.substring( | |
| 475 | - result!.startIndex, | |
| 476 | - result!.endIndex, | |
| 477 | - ); | |
| 478 | - expect(matchedContent).toBe(` | |
| 479 | - constructor(name) { | |
| 480 | - this.name = name; | |
| 481 | - this.value = 0; | |
| 482 | - }`); | |
| 483 | - }); | |
| 484 | - | |
| 485 | - it("should return null when no close match exists", () => { | |
| 486 | - const fileContent = `function hello() { | |
| 487 | - console.log("world"); | |
| 488 | -}`; | |
| 489 | - const searchContent = `this has nothing to do with the other option`; | |
| 490 | - | |
| 491 | - const result = findSearchMatch(fileContent, searchContent); | |
| 492 | - | |
| 493 | - expect(result).toBeNull(); | |
| 494 | - }); | |
| 495 | - | |
| 496 | - it("should handle multiple potential matches and return first", () => { | |
| 497 | - const fileContent = `const a=1; | |
| 498 | -const a = 1; | |
| 499 | -const a = 1;`; | |
| 500 | - const searchContent = `const a=1;`; | |
| 501 | - | |
| 502 | - const result = findSearchMatch(fileContent, searchContent); | |
| 503 | - | |
| 504 | - // Should find the first exact match | |
| 505 | - expect(result).toEqual({ | |
| 506 | - startIndex: 0, | |
| 507 | - endIndex: 10, | |
| 508 | - strategyName: "exactMatch", | |
| 509 | - }); | |
| 510 | - }); | |
| 511 | -}); | |
| 512 | - | |
| 513 | -describe("Real-world scenarios", () => { | |
| 514 | - it("should match typical function replacement", () => { | |
| 515 | - const fileContent = `class Calculator { | |
| 516 | - constructor() { | |
| 517 | - this.result = 0; | |
| 518 | - } | |
| 519 | - | |
| 520 | - reset() { | |
| 521 | - this.result = 0; | |
| 522 | - return this; | |
| 523 | - } | |
| 524 | - | |
| 525 | - add(value) { | |
| 526 | - this.result += value; | |
| 527 | - return this; | |
| 528 | - } | |
| 529 | -}`; | |
| 530 | - const searchContent = ` reset() { | |
| 531 | - this.result = 0; | |
| 532 | - return this; | |
| 533 | - }`; | |
| 534 | - | |
| 535 | - const result = findSearchMatch(fileContent, searchContent); | |
| 536 | - | |
| 537 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 538 | - expect(result).toEqual({ | |
| 539 | - startIndex: expectedStart, | |
| 540 | - endIndex: expectedStart + searchContent.length, | |
| 541 | - strategyName: "exactMatch", | |
| 542 | - }); | |
| 543 | - }); | |
| 544 | - | |
| 545 | - it("should match import statement", () => { | |
| 546 | - const fileContent = `import React from 'react'; | |
| 547 | -import { useState, useEffect } from 'react'; | |
| 548 | -import './App.css'; | |
| 549 | - | |
| 550 | -function App() { | |
| 551 | - return <div>Hello World</div>; | |
| 552 | -}`; | |
| 553 | - const searchContent = `import { useState, useEffect } from 'react';`; | |
| 554 | - | |
| 555 | - const result = findSearchMatch(fileContent, searchContent); | |
| 556 | - | |
| 557 | - const expectedStart = fileContent.indexOf(searchContent); | |
| 558 | - expect(result).toEqual({ | |
| 559 | - startIndex: expectedStart, | |
| 560 | - endIndex: expectedStart + searchContent.length, | |
| 561 | - strategyName: "exactMatch", | |
| 562 | - }); | |
| 563 | - }); | |
| 564 | - | |
| 565 | - it("should match comment block", () => { | |
| 566 | - const fileContent = `/** | |
| 567 | - * This is a comment | |
| 568 | - * that spans multiple lines | |
| 569 | - */ | |
| 570 | -function test() { | |
| 571 | - // Single line comment | |
| 572 | - return true; | |
| 573 | -}`; | |
| 574 | - const searchContent = `/** | |
| 575 | - * This is a comment | |
| 576 | - * that spans multiple lines | |
| 577 | - */`; | |
| 578 | - | |
| 579 | - const result = findSearchMatch(fileContent, searchContent); | |
| 580 | - | |
| 581 | - expect(result).toEqual({ | |
| 582 | - startIndex: 0, | |
| 583 | - endIndex: searchContent.length, | |
| 584 | - strategyName: "exactMatch", | |
| 585 | - }); | |
| 586 | - }); | |
| 587 | -}); |
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | interface BasicMatchResult { |
| 5 | 5 | /** The starting character index of the match in the file content */ |
| 6 | 6 | startIndex: number; |
| 7 | - /** The ending character index of the match in the file content */ | |
| 7 | + /** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/ | |
| 8 | 8 | endIndex: number; |
| 9 | 9 | } |
| 10 | 10 | |
| @@ -43,48 +43,20 @@ | ||
| 43 | 43 | |
| 44 | 44 | /** |
| 45 | 45 | * Trimmed content matching strategy |
| 46 | - * Finds content where the search content (when trimmed) matches content in the file, | |
| 47 | - * and returns the span that includes the file content's whitespace | |
| 48 | 46 | */ |
| 49 | 47 | function trimmedMatch( |
| 50 | 48 | fileContent: string, |
| 51 | 49 | searchContent: string, |
| 52 | 50 | ): BasicMatchResult | null { |
| 53 | 51 | const trimmedSearchContent = searchContent.trim(); |
| 54 | - | |
| 55 | - // Don't apply if search content has no leading/trailing whitespace to trim | |
| 56 | - if (trimmedSearchContent === searchContent) { | |
| 57 | - return null; | |
| 58 | - } | |
| 59 | - | |
| 60 | - // Don't match if trimmed content is empty | |
| 61 | - if (trimmedSearchContent === "") { | |
| 62 | - return null; | |
| 63 | - } | |
| 64 | - | |
| 65 | - // Look for the trimmed content in the file | |
| 66 | - const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent); | |
| 67 | - if (trimmedContentIndex === -1) { | |
| 68 | - return null; | |
| 69 | - } | |
| 70 | - | |
| 71 | - // Find the boundaries that include surrounding whitespace (but not newlines) | |
| 72 | - // Look backwards for horizontal whitespace (spaces and tabs) | |
| 73 | - let startIndex = trimmedContentIndex; | |
| 74 | - while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) { | |
| 75 | - startIndex--; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Look forwards for horizontal whitespace (spaces and tabs) | |
| 79 | - let endIndex = trimmedContentIndex + trimmedSearchContent.length; | |
| 80 | - while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) { | |
| 81 | - endIndex++; | |
| 52 | + const trimmedIndex = fileContent.indexOf(trimmedSearchContent); | |
| 53 | + if (trimmedIndex !== -1) { | |
| 54 | + return { | |
| 55 | + startIndex: trimmedIndex, | |
| 56 | + endIndex: trimmedIndex + trimmedSearchContent.length, | |
| 57 | + }; | |
| 82 | 58 | } |
| 83 | - | |
| 84 | - return { | |
| 85 | - startIndex, | |
| 86 | - endIndex, | |
| 87 | - }; | |
| 59 | + return null; | |
| 88 | 60 | } |
| 89 | 61 | |
| 90 | 62 | /** |
| @@ -109,32 +81,38 @@ | ||
| 109 | 81 | } |
| 110 | 82 | |
| 111 | 83 | // Map the stripped position back to the original file content |
| 112 | - let originalStartIndex = 0; | |
| 84 | + let originalStartIndex = -1; | |
| 113 | 85 | let strippedCharCount = 0; |
| 114 | 86 | |
| 115 | - // Find the original position by counting non-whitespace characters | |
| 87 | + // Find the original start position by counting non-whitespace characters | |
| 116 | 88 | for (let i = 0; i < fileContent.length; i++) { |
| 117 | - if (strippedCharCount === strippedIndex) { | |
| 118 | - originalStartIndex = i; | |
| 119 | - break; | |
| 120 | - } | |
| 121 | 89 | if (!/\s/.test(fileContent[i])) { |
| 90 | + if (strippedCharCount === strippedIndex) { | |
| 91 | + originalStartIndex = i; | |
| 92 | + break; | |
| 93 | + } | |
| 122 | 94 | strippedCharCount++; |
| 123 | 95 | } |
| 124 | 96 | } |
| 125 | 97 | |
| 126 | - // Find the end position by counting the length of the search content | |
| 98 | + if (originalStartIndex === -1) { | |
| 99 | + return null; // Should not happen if strippedIndex was valid | |
| 100 | + } | |
| 101 | + | |
| 102 | + // Find the end position by counting through all characters (including whitespace) | |
| 103 | + // that correspond to the stripped search content length | |
| 127 | 104 | let originalEndIndex = originalStartIndex; |
| 128 | - let matchedChars = 0; | |
| 105 | + let matchedNonWhitespaceChars = 0; | |
| 129 | 106 | |
| 130 | - for ( | |
| 131 | - let i = originalStartIndex; | |
| 132 | - i < fileContent.length && matchedChars < strippedSearchContent.length; | |
| 133 | - i++ | |
| 134 | - ) { | |
| 107 | + for (let i = originalStartIndex; i < fileContent.length; i++) { | |
| 135 | 108 | if (!/\s/.test(fileContent[i])) { |
| 136 | - matchedChars++; | |
| 109 | + matchedNonWhitespaceChars++; | |
| 110 | + if (matchedNonWhitespaceChars === strippedSearchContent.length) { | |
| 111 | + originalEndIndex = i + 1; | |
| 112 | + break; | |
| 113 | + } | |
| 137 | 114 | } |
| 115 | + // Always update end index to include current position (whether whitespace or not) | |
| 138 | 116 | originalEndIndex = i + 1; |
| 139 | 117 | } |
| 140 | 118 | |
| @@ -144,6 +122,162 @@ | ||
| 144 | 122 | }; |
| 145 | 123 | } |
| 146 | 124 | |
| 125 | +/** | |
| 126 | + * Calculate the Jaro similarity between two strings | |
| 127 | + * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match | |
| 128 | + */ | |
| 129 | +function jaroSimilarity(s1: string, s2: string): number { | |
| 130 | + if (s1 === s2) return 1.0; | |
| 131 | + if (s1.length === 0 || s2.length === 0) return 0.0; | |
| 132 | + | |
| 133 | + const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1; | |
| 134 | + if (matchDistance < 0) return 0.0; | |
| 135 | + | |
| 136 | + const s1Matches = new Array(s1.length).fill(false); | |
| 137 | + const s2Matches = new Array(s2.length).fill(false); | |
| 138 | + | |
| 139 | + let matches = 0; | |
| 140 | + let transpositions = 0; | |
| 141 | + | |
| 142 | + // Find matches | |
| 143 | + for (let i = 0; i < s1.length; i++) { | |
| 144 | + const start = Math.max(0, i - matchDistance); | |
| 145 | + const end = Math.min(i + matchDistance + 1, s2.length); | |
| 146 | + | |
| 147 | + for (let j = start; j < end; j++) { | |
| 148 | + if (s2Matches[j] || s1[i] !== s2[j]) continue; | |
| 149 | + s1Matches[i] = true; | |
| 150 | + s2Matches[j] = true; | |
| 151 | + matches++; | |
| 152 | + break; | |
| 153 | + } | |
| 154 | + } | |
| 155 | + | |
| 156 | + if (matches === 0) return 0.0; | |
| 157 | + | |
| 158 | + // Count transpositions | |
| 159 | + let k = 0; | |
| 160 | + for (let i = 0; i < s1.length; i++) { | |
| 161 | + if (!s1Matches[i]) continue; | |
| 162 | + while (!s2Matches[k]) k++; | |
| 163 | + if (s1[i] !== s2[k]) transpositions++; | |
| 164 | + k++; | |
| 165 | + } | |
| 166 | + | |
| 167 | + return ( | |
| 168 | + (matches / s1.length + | |
| 169 | + matches / s2.length + | |
| 170 | + (matches - transpositions / 2) / matches) / | |
| 171 | + 3.0 | |
| 172 | + ); | |
| 173 | +} | |
| 174 | + | |
| 175 | +/** | |
| 176 | + * Calculate the Jaro-Winkler similarity between two strings | |
| 177 | + */ | |
| 178 | +function jaroWinklerSimilarity( | |
| 179 | + s1: string, | |
| 180 | + s2: string, | |
| 181 | + prefixScale = 0.1, | |
| 182 | +): number { | |
| 183 | + const jaroSim = jaroSimilarity(s1, s2); | |
| 184 | + | |
| 185 | + if (jaroSim < 0.7) return jaroSim; | |
| 186 | + | |
| 187 | + // Calculate common prefix length (up to 4 characters) | |
| 188 | + let prefixLength = 0; | |
| 189 | + const maxPrefix = Math.min(4, Math.min(s1.length, s2.length)); | |
| 190 | + | |
| 191 | + for (let i = 0; i < maxPrefix; i++) { | |
| 192 | + if (s1[i] === s2[i]) { | |
| 193 | + prefixLength++; | |
| 194 | + } else { | |
| 195 | + break; | |
| 196 | + } | |
| 197 | + } | |
| 198 | + | |
| 199 | + return jaroSim + prefixLength * prefixScale * (1 - jaroSim); | |
| 200 | +} | |
| 201 | + | |
| 202 | +/** | |
| 203 | + * Find the best fuzzy match for search content in file content using Jaro-Winkler | |
| 204 | + */ | |
| 205 | +function findFuzzyMatch( | |
| 206 | + fileContent: string, | |
| 207 | + searchContent: string, | |
| 208 | + threshold: number = 0.9, | |
| 209 | +): BasicMatchResult | null { | |
| 210 | + const searchLines = searchContent.split("\n"); | |
| 211 | + const fileLines = fileContent.split("\n"); | |
| 212 | + | |
| 213 | + let bestMatch: BasicMatchResult | null = null; | |
| 214 | + let bestSimilarity = 0; | |
| 215 | + | |
| 216 | + // Try matching the search content as a whole block | |
| 217 | + const searchBlock = searchContent.trim(); | |
| 218 | + if (searchBlock.length > 5) { | |
| 219 | + // Require minimum length for meaningful matches | |
| 220 | + // Use sliding window approach for multi-line search | |
| 221 | + for (let i = 0; i <= fileLines.length - searchLines.length; i++) { | |
| 222 | + const candidateLines = fileLines.slice(i, i + searchLines.length); | |
| 223 | + const candidateBlock = candidateLines.join("\n").trim(); | |
| 224 | + | |
| 225 | + if (candidateBlock.length < 5) continue; // Skip very short blocks | |
| 226 | + | |
| 227 | + const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock); | |
| 228 | + | |
| 229 | + if (similarity >= threshold && similarity > bestSimilarity) { | |
| 230 | + // Calculate character positions | |
| 231 | + const linesBeforeMatch = fileLines.slice(0, i); | |
| 232 | + const startIndex = | |
| 233 | + linesBeforeMatch.join("\n").length + | |
| 234 | + (linesBeforeMatch.length > 0 ? 1 : 0); | |
| 235 | + const endIndex = startIndex + candidateBlock.length; | |
| 236 | + | |
| 237 | + bestMatch = { | |
| 238 | + startIndex, | |
| 239 | + endIndex, | |
| 240 | + }; | |
| 241 | + bestSimilarity = similarity; | |
| 242 | + } | |
| 243 | + } | |
| 244 | + } | |
| 245 | + | |
| 246 | + // Also try line-by-line matching for better granularity | |
| 247 | + for ( | |
| 248 | + let searchLineIdx = 0; | |
| 249 | + searchLineIdx < searchLines.length; | |
| 250 | + searchLineIdx++ | |
| 251 | + ) { | |
| 252 | + const searchLine = searchLines[searchLineIdx].trim(); | |
| 253 | + if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines | |
| 254 | + | |
| 255 | + for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) { | |
| 256 | + const fileLine = fileLines[fileLineIdx].trim(); | |
| 257 | + if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines | |
| 258 | + | |
| 259 | + const similarity = jaroWinklerSimilarity(searchLine, fileLine); | |
| 260 | + | |
| 261 | + if (similarity >= threshold && similarity > bestSimilarity) { | |
| 262 | + // Calculate character positions for the line | |
| 263 | + const linesBeforeMatch = fileLines.slice(0, fileLineIdx); | |
| 264 | + const startIndex = | |
| 265 | + linesBeforeMatch.join("\n").length + | |
| 266 | + (linesBeforeMatch.length > 0 ? 1 : 0); | |
| 267 | + const endIndex = startIndex + fileLines[fileLineIdx].length; | |
| 268 | + | |
| 269 | + bestMatch = { | |
| 270 | + startIndex, | |
| 271 | + endIndex, | |
| 272 | + }; | |
| 273 | + bestSimilarity = similarity; | |
| 274 | + } | |
| 275 | + } | |
| 276 | + } | |
| 277 | + | |
| 278 | + return bestMatch; | |
| 279 | +} | |
| 280 | + | |
| 147 | 281 | /** |
| 148 | 282 | * Ordered list of matching strategies to try with their names |
| 149 | 283 | */ |
| @@ -151,6 +285,7 @@ | ||
| 151 | 285 | { strategy: exactMatch, name: "exactMatch" }, |
| 152 | 286 | { strategy: trimmedMatch, name: "trimmedMatch" }, |
| 153 | 287 | { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, |
| 288 | + // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, | |
| 154 | 289 | ]; |
| 155 | 290 | |
| 156 | 291 | /** |
| @@ -170,24 +305,10 @@ | ||
| 170 | 305 | fileContent: string, |
| 171 | 306 | searchContent: string, |
| 172 | 307 | ): SearchMatchResult | null { |
| 173 | - // Handle truly empty search content | |
| 174 | - if (searchContent === "") { | |
| 175 | - return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; | |
| 176 | - } | |
| 177 | - | |
| 178 | - // Handle whitespace-only search content that trims to empty | |
| 179 | 308 | const trimmedSearchContent = searchContent.trim(); |
| 309 | + | |
| 180 | 310 | if (trimmedSearchContent === "") { |
| 181 | - // Check if the whitespace-only search content has an exact match first | |
| 182 | - const exactIndex = fileContent.indexOf(searchContent); | |
| 183 | - if (exactIndex !== -1) { | |
| 184 | - return { | |
| 185 | - startIndex: exactIndex, | |
| 186 | - endIndex: exactIndex + searchContent.length, | |
| 187 | - strategyName: "exactMatch", | |
| 188 | - }; | |
| 189 | - } | |
| 190 | - // If no exact match for whitespace-only content, treat as empty search | |
| 311 | + // Empty search content matches the beginning of the file | |
| 191 | 312 | return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; |
| 192 | 313 | } |
| 193 | 314 | |
| @@ -201,3 +322,58 @@ | ||
| 201 | 322 | |
| 202 | 323 | return null; |
| 203 | 324 | } |
| 325 | + | |
| 326 | +/** | |
| 327 | + * Find all matches for search content in file content. | |
| 328 | + * Uses the same matching strategies as findSearchMatch, applied iteratively. | |
| 329 | + * | |
| 330 | + * @param fileContent - The complete content of the file to search in | |
| 331 | + * @param searchContent - The content to search for | |
| 332 | + * @returns Array of match results with character positions, empty array if no matches found | |
| 333 | + */ | |
| 334 | +export function findSearchMatches( | |
| 335 | + fileContent: string, | |
| 336 | + searchContent: string, | |
| 337 | +): SearchMatchResult[] { | |
| 338 | + const matches: SearchMatchResult[] = []; | |
| 339 | + | |
| 340 | + // Special case: empty search string always matches at position 0 | |
| 341 | + if (searchContent.trim() === "") { | |
| 342 | + return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }]; | |
| 343 | + } | |
| 344 | + | |
| 345 | + let remainingContent = fileContent; | |
| 346 | + let currentOffset = 0; | |
| 347 | + | |
| 348 | + while (remainingContent.length > 0) { | |
| 349 | + const match = findSearchMatch(remainingContent, searchContent); | |
| 350 | + | |
| 351 | + if (match === null) { | |
| 352 | + break; | |
| 353 | + } | |
| 354 | + | |
| 355 | + // Adjust match positions to account for the current offset | |
| 356 | + const adjustedMatch: SearchMatchResult = { | |
| 357 | + startIndex: match.startIndex + currentOffset, | |
| 358 | + endIndex: match.endIndex + currentOffset, | |
| 359 | + strategyName: match.strategyName, | |
| 360 | + }; | |
| 361 | + | |
| 362 | + // Prevent infinite loops by ensuring we're making progress | |
| 363 | + // If the new match starts at or before the last match's start position, break | |
| 364 | + if ( | |
| 365 | + matches.length > 0 && | |
| 366 | + adjustedMatch.startIndex <= matches[matches.length - 1].startIndex | |
| 367 | + ) { | |
| 368 | + break; | |
| 369 | + } | |
| 370 | + | |
| 371 | + matches.push(adjustedMatch); | |
| 372 | + | |
| 373 | + // Update offset and truncate content after the current match | |
| 374 | + currentOffset = adjustedMatch.endIndex; | |
| 375 | + remainingContent = fileContent.slice(currentOffset); | |
| 376 | + } | |
| 377 | + | |
| 378 | + return matches; | |
| 379 | +} |
| @@ -0,0 +1,571 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { findSearchMatch } from "./findSearchMatch"; | |
| 3 | + | |
| 4 | +describe("findSearchMatch", () => { | |
| 5 | + describe("Empty search content", () => { | |
| 6 | + it("should return position 0 for empty string", () => { | |
| 7 | + const result = findSearchMatch("some file content", ""); | |
| 8 | + expect(result).toEqual({ | |
| 9 | + startIndex: 0, | |
| 10 | + endIndex: 0, | |
| 11 | + strategyName: "emptySearch", | |
| 12 | + }); | |
| 13 | + }); | |
| 14 | + | |
| 15 | + it("should return position 0 for whitespace-only string", () => { | |
| 16 | + const result = findSearchMatch("some file content", " \n\t "); | |
| 17 | + expect(result).toEqual({ | |
| 18 | + startIndex: 0, | |
| 19 | + endIndex: 0, | |
| 20 | + strategyName: "emptySearch", | |
| 21 | + }); | |
| 22 | + }); | |
| 23 | + | |
| 24 | + it("should handle empty file content with empty search", () => { | |
| 25 | + const result = findSearchMatch("", ""); | |
| 26 | + expect(result).toEqual({ | |
| 27 | + startIndex: 0, | |
| 28 | + endIndex: 0, | |
| 29 | + strategyName: "emptySearch", | |
| 30 | + }); | |
| 31 | + }); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + describe("Exact match strategy", () => { | |
| 35 | + it("should find exact match at beginning of file", () => { | |
| 36 | + const fileContent = "hello world"; | |
| 37 | + const searchContent = "hello"; | |
| 38 | + const result = findSearchMatch(fileContent, searchContent); | |
| 39 | + | |
| 40 | + expect(result).toEqual({ | |
| 41 | + startIndex: 0, | |
| 42 | + endIndex: 5, | |
| 43 | + strategyName: "exactMatch", | |
| 44 | + }); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should find exact match in middle of file", () => { | |
| 48 | + const fileContent = "hello world test"; | |
| 49 | + const searchContent = "world"; | |
| 50 | + const result = findSearchMatch(fileContent, searchContent); | |
| 51 | + | |
| 52 | + expect(result).toEqual({ | |
| 53 | + startIndex: 6, | |
| 54 | + endIndex: 11, | |
| 55 | + strategyName: "exactMatch", | |
| 56 | + }); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + it("should find exact match at end of file", () => { | |
| 60 | + const fileContent = "hello world"; | |
| 61 | + const searchContent = "world"; | |
| 62 | + const result = findSearchMatch(fileContent, searchContent); | |
| 63 | + | |
| 64 | + expect(result).toEqual({ | |
| 65 | + startIndex: 6, | |
| 66 | + endIndex: 11, | |
| 67 | + strategyName: "exactMatch", | |
| 68 | + }); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("should find multi-line exact match", () => { | |
| 72 | + const fileContent = "line1\nline2\nline3"; | |
| 73 | + const searchContent = "line2\nline3"; | |
| 74 | + const result = findSearchMatch(fileContent, searchContent); | |
| 75 | + | |
| 76 | + expect(result).toEqual({ | |
| 77 | + startIndex: 6, | |
| 78 | + endIndex: 17, | |
| 79 | + strategyName: "exactMatch", | |
| 80 | + }); | |
| 81 | + }); | |
| 82 | + | |
| 83 | + it("should handle exact match with special characters", () => { | |
| 84 | + const fileContent = 'function test() { return "hello"; }'; | |
| 85 | + const searchContent = '{ return "hello"; }'; | |
| 86 | + const result = findSearchMatch(fileContent, searchContent); | |
| 87 | + | |
| 88 | + expect(result).toEqual({ | |
| 89 | + startIndex: 16, | |
| 90 | + endIndex: 35, | |
| 91 | + strategyName: "exactMatch", | |
| 92 | + }); | |
| 93 | + }); | |
| 94 | + | |
| 95 | + it("should find first occurrence when multiple matches exist", () => { | |
| 96 | + const fileContent = "test test test"; | |
| 97 | + const searchContent = "test"; | |
| 98 | + const result = findSearchMatch(fileContent, searchContent); | |
| 99 | + | |
| 100 | + expect(result).toEqual({ | |
| 101 | + startIndex: 0, | |
| 102 | + endIndex: 4, | |
| 103 | + strategyName: "exactMatch", | |
| 104 | + }); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + it("should handle case-sensitive matching", () => { | |
| 108 | + const fileContent = "Hello World"; | |
| 109 | + const searchContent = "hello"; | |
| 110 | + const result = findSearchMatch(fileContent, searchContent); | |
| 111 | + | |
| 112 | + // Should not match due to case sensitivity, will fall through to other strategies | |
| 113 | + expect(result).toBeNull(); | |
| 114 | + }); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + describe("Trimmed match strategy fallback", () => { | |
| 118 | + it("should find match when search content has leading/trailing whitespace", () => { | |
| 119 | + const fileContent = "hello world"; | |
| 120 | + const searchContent = " hello "; | |
| 121 | + const result = findSearchMatch(fileContent, searchContent); | |
| 122 | + | |
| 123 | + expect(result).toEqual({ | |
| 124 | + startIndex: 0, | |
| 125 | + endIndex: 5, | |
| 126 | + strategyName: "trimmedMatch", | |
| 127 | + }); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should find match when search content has tabs and newlines", () => { | |
| 131 | + const fileContent = "function test() {}"; | |
| 132 | + const searchContent = "\t\nfunction test()\n\t"; | |
| 133 | + const result = findSearchMatch(fileContent, searchContent); | |
| 134 | + | |
| 135 | + expect(result).toEqual({ | |
| 136 | + startIndex: 0, | |
| 137 | + endIndex: 15, | |
| 138 | + strategyName: "trimmedMatch", | |
| 139 | + }); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("should handle complex whitespace trimming", () => { | |
| 143 | + const fileContent = "const x = 5;"; | |
| 144 | + const searchContent = " \n\t const x = 5; \t\n "; | |
| 145 | + const result = findSearchMatch(fileContent, searchContent); | |
| 146 | + | |
| 147 | + expect(result).toEqual({ | |
| 148 | + startIndex: 0, | |
| 149 | + endIndex: 12, | |
| 150 | + strategyName: "trimmedMatch", | |
| 151 | + }); | |
| 152 | + }); | |
| 153 | + }); | |
| 154 | + | |
| 155 | + describe("Whitespace ignored strategy fallback", () => { | |
| 156 | + it("should match content with different whitespace formatting", () => { | |
| 157 | + const fileContent = "function test() {\n return true;\n}"; | |
| 158 | + const searchContent = "function test(){return true;}"; | |
| 159 | + const result = findSearchMatch(fileContent, searchContent); | |
| 160 | + | |
| 161 | + expect(result).toEqual({ | |
| 162 | + startIndex: 0, | |
| 163 | + endIndex: 34, | |
| 164 | + strategyName: "whitespaceIgnoredMatch", | |
| 165 | + }); | |
| 166 | + }); | |
| 167 | + | |
| 168 | + it("should handle mixed whitespace differences", () => { | |
| 169 | + const fileContent = "if (condition) {\n doSomething();\n}"; | |
| 170 | + const searchContent = "if(condition){doSomething();}"; | |
| 171 | + const result = findSearchMatch(fileContent, searchContent); | |
| 172 | + | |
| 173 | + expect(result).toEqual({ | |
| 174 | + startIndex: 0, | |
| 175 | + endIndex: 37, | |
| 176 | + strategyName: "whitespaceIgnoredMatch", | |
| 177 | + }); | |
| 178 | + }); | |
| 179 | + | |
| 180 | + it("should match with tabs vs spaces differences", () => { | |
| 181 | + const fileContent = "function test() {\n\treturn 42;\n}"; | |
| 182 | + const searchContent = "function test() {\n return 42;\n}"; | |
| 183 | + const result = findSearchMatch(fileContent, searchContent); | |
| 184 | + | |
| 185 | + expect(result).toEqual({ | |
| 186 | + startIndex: 0, | |
| 187 | + endIndex: 31, | |
| 188 | + strategyName: "whitespaceIgnoredMatch", | |
| 189 | + }); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + it("should handle partial matches within larger content", () => { | |
| 193 | + const fileContent = "before\nfunction test() {\n return true;\n}\nafter"; | |
| 194 | + const searchContent = "function test(){return true;}"; | |
| 195 | + const result = findSearchMatch(fileContent, searchContent); | |
| 196 | + | |
| 197 | + expect(result).toEqual({ | |
| 198 | + startIndex: 7, | |
| 199 | + endIndex: 41, | |
| 200 | + strategyName: "whitespaceIgnoredMatch", | |
| 201 | + }); | |
| 202 | + }); | |
| 203 | + | |
| 204 | + it("should recognize empty search", () => { | |
| 205 | + const fileContent = "some content"; | |
| 206 | + const searchContent = " \t\n "; | |
| 207 | + const result = findSearchMatch(fileContent, searchContent); | |
| 208 | + | |
| 209 | + expect(result).toEqual({ | |
| 210 | + startIndex: 0, | |
| 211 | + endIndex: 0, | |
| 212 | + strategyName: "emptySearch", | |
| 213 | + }); | |
| 214 | + }); | |
| 215 | + | |
| 216 | + it("should handle complex nested structures with whitespace differences", () => { | |
| 217 | + const fileContent = `{ | |
| 218 | + "key": "value", | |
| 219 | + "nested": { | |
| 220 | + "prop": 123 | |
| 221 | + } | |
| 222 | +}`; | |
| 223 | + const searchContent = '{"key":"value","nested":{"prop":123}}'; | |
| 224 | + const result = findSearchMatch(fileContent, searchContent); | |
| 225 | + | |
| 226 | + expect(result).toEqual({ | |
| 227 | + startIndex: 0, | |
| 228 | + endIndex: 55, | |
| 229 | + strategyName: "whitespaceIgnoredMatch", | |
| 230 | + }); | |
| 231 | + }); | |
| 232 | + | |
| 233 | + it("should match content in middle of file with complex indentation", () => { | |
| 234 | + const fileContent = `import React from 'react'; | |
| 235 | + | |
| 236 | +function MyComponent() { | |
| 237 | + const handleClick = () => { | |
| 238 | + console.log('clicked'); | |
| 239 | + }; | |
| 240 | + return <button onClick={handleClick}>Click me</button>; | |
| 241 | +} | |
| 242 | + | |
| 243 | +export default MyComponent;`; | |
| 244 | + const searchContent = `const handleClick=()=>{console.log('clicked');};`; | |
| 245 | + const result = findSearchMatch(fileContent, searchContent); | |
| 246 | + | |
| 247 | + expect(result).toEqual({ | |
| 248 | + startIndex: 55, | |
| 249 | + endIndex: 115, | |
| 250 | + strategyName: "whitespaceIgnoredMatch", | |
| 251 | + }); | |
| 252 | + }); | |
| 253 | + | |
| 254 | + it("should handle matches with mixed line endings and special characters", () => { | |
| 255 | + const fileContent = `<!DOCTYPE html>\r\n<html>\r\n <body>\r\n <div id="app">\r\n <p>Hello & goodbye</p>\r\n </div>\r\n </body>\r\n</html>`; | |
| 256 | + const searchContent = `<divid="app"><p>Hello&goodbye</p></div>`; | |
| 257 | + const result = findSearchMatch(fileContent, searchContent); | |
| 258 | + | |
| 259 | + expect(result).toEqual({ | |
| 260 | + startIndex: 39, | |
| 261 | + endIndex: 95, | |
| 262 | + strategyName: "whitespaceIgnoredMatch", | |
| 263 | + }); | |
| 264 | + }); | |
| 265 | + | |
| 266 | + it("should match content surrounded by different types of whitespace", () => { | |
| 267 | + const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`; | |
| 268 | + const searchContent = `address:{street:"MainSt",city:"NYC"}`; | |
| 269 | + const result = findSearchMatch(fileContent, searchContent); | |
| 270 | + | |
| 271 | + expect(result).toEqual({ | |
| 272 | + startIndex: 45, | |
| 273 | + endIndex: 96, | |
| 274 | + strategyName: "whitespaceIgnoredMatch", | |
| 275 | + }); | |
| 276 | + }); | |
| 277 | + | |
| 278 | + // IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both | |
| 279 | + it("should handle unicode characters with whitespace differences", () => { | |
| 280 | + const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`; | |
| 281 | + const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`; | |
| 282 | + const result = findSearchMatch(fileContent, searchContent); | |
| 283 | + | |
| 284 | + expect(result).toEqual({ | |
| 285 | + startIndex: 44, | |
| 286 | + endIndex: 89, | |
| 287 | + strategyName: "whitespaceIgnoredMatch", | |
| 288 | + }); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + it("should match across multiple nested blocks with varying indentation", () => { | |
| 292 | + const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`; | |
| 293 | + const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`; | |
| 294 | + const result = findSearchMatch(fileContent, searchContent); | |
| 295 | + | |
| 296 | + expect(result).toEqual({ | |
| 297 | + startIndex: 43, | |
| 298 | + endIndex: 132, | |
| 299 | + strategyName: "whitespaceIgnoredMatch", | |
| 300 | + }); | |
| 301 | + }); | |
| 302 | + | |
| 303 | + it("should handle regex-like patterns with escaped characters", () => { | |
| 304 | + const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`; | |
| 305 | + const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`; | |
| 306 | + const result = findSearchMatch(fileContent, searchContent); | |
| 307 | + | |
| 308 | + expect(result).toEqual({ | |
| 309 | + startIndex: 29, | |
| 310 | + endIndex: 110, | |
| 311 | + strategyName: "whitespaceIgnoredMatch", | |
| 312 | + }); | |
| 313 | + }); | |
| 314 | + | |
| 315 | + it("should match SQL-like content with varying whitespace", () => { | |
| 316 | + const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`; | |
| 317 | + const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`; | |
| 318 | + const result = findSearchMatch(fileContent, searchContent); | |
| 319 | + | |
| 320 | + expect(result).toEqual({ | |
| 321 | + startIndex: 0, | |
| 322 | + endIndex: 89, | |
| 323 | + strategyName: "whitespaceIgnoredMatch", | |
| 324 | + }); | |
| 325 | + }); | |
| 326 | + | |
| 327 | + it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => { | |
| 328 | + const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`; | |
| 329 | + const searchContent = `functionprocessdata(input){returninput.trim();}`; | |
| 330 | + const result = findSearchMatch(fileContent, searchContent); | |
| 331 | + | |
| 332 | + expect(result).toEqual({ | |
| 333 | + startIndex: 0, | |
| 334 | + endIndex: 56, | |
| 335 | + strategyName: "whitespaceIgnoredMatch", | |
| 336 | + }); | |
| 337 | + }); | |
| 338 | + | |
| 339 | + it("should match content with Windows-style CRLF line endings", () => { | |
| 340 | + const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`; | |
| 341 | + const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`; | |
| 342 | + const result = findSearchMatch(fileContent, searchContent); | |
| 343 | + | |
| 344 | + expect(result).toEqual({ | |
| 345 | + startIndex: 37, | |
| 346 | + endIndex: 105, | |
| 347 | + strategyName: "whitespaceIgnoredMatch", | |
| 348 | + }); | |
| 349 | + }); | |
| 350 | + | |
| 351 | + it("should handle deeply nested JSON with mixed formatting", () => { | |
| 352 | + const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`; | |
| 353 | + const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`; | |
| 354 | + const result = findSearchMatch(fileContent, searchContent); | |
| 355 | + | |
| 356 | + expect(result).toEqual({ | |
| 357 | + startIndex: 87, | |
| 358 | + endIndex: 243, | |
| 359 | + strategyName: "whitespaceIgnoredMatch", | |
| 360 | + }); | |
| 361 | + }); | |
| 362 | + | |
| 363 | + it("should match XML content with attribute spacing differences", () => { | |
| 364 | + const fileContent = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n <item id = \"1\" type= \"primary\" >\n <name>Test Item</name>\n <value unit=\"px\" >100</value>\n </item>\n</root>`; | |
| 365 | + const searchContent = `<itemid=\"1\"type=\"primary\"><name>TestItem</name><valueunit=\"px\">100</value></item>`; | |
| 366 | + const result = findSearchMatch(fileContent, searchContent); | |
| 367 | + | |
| 368 | + expect(result).toEqual({ | |
| 369 | + startIndex: 48, | |
| 370 | + endIndex: 155, | |
| 371 | + strategyName: "whitespaceIgnoredMatch", | |
| 372 | + }); | |
| 373 | + }); | |
| 374 | + | |
| 375 | + it("should handle mathematical expressions with varying spacing", () => { | |
| 376 | + const fileContent = `const result = (a + b) * c - d / e;\nconst complex = Math.sqrt( x ** 2 + y ** 2 );\nconst formula = ( ( a + b ) * ( c - d ) ) / ( e + f );`; | |
| 377 | + const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`; | |
| 378 | + const result = findSearchMatch(fileContent, searchContent); | |
| 379 | + | |
| 380 | + expect(result).toEqual({ | |
| 381 | + startIndex: 36, | |
| 382 | + endIndex: 142, | |
| 383 | + strategyName: "whitespaceIgnoredMatch", | |
| 384 | + }); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + it("should match across comments and code with whitespace variations", () => { | |
| 388 | + const fileContent = `/* Multi-line comment\n with varying indentation */\nfunction processData(input) {\n // Single line comment\n const cleaned = input.trim();\n /* Another comment */\n return cleaned.toLowerCase();\n}`; | |
| 389 | + const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`; | |
| 390 | + const result = findSearchMatch(fileContent, searchContent); | |
| 391 | + | |
| 392 | + expect(result).toEqual({ | |
| 393 | + startIndex: 0, | |
| 394 | + endIndex: 205, | |
| 395 | + strategyName: "whitespaceIgnoredMatch", | |
| 396 | + }); | |
| 397 | + }); | |
| 398 | + }); | |
| 399 | + | |
| 400 | + describe("No match scenarios", () => { | |
| 401 | + it("should return null when no strategy finds a match", () => { | |
| 402 | + const fileContent = "hello world"; | |
| 403 | + const searchContent = "goodbye"; | |
| 404 | + const result = findSearchMatch(fileContent, searchContent); | |
| 405 | + | |
| 406 | + expect(result).toBeNull(); | |
| 407 | + }); | |
| 408 | + | |
| 409 | + it("should return null for completely different content", () => { | |
| 410 | + const fileContent = "function test() { return true; }"; | |
| 411 | + const searchContent = "class MyClass { }"; | |
| 412 | + const result = findSearchMatch(fileContent, searchContent); | |
| 413 | + | |
| 414 | + expect(result).toBeNull(); | |
| 415 | + }); | |
| 416 | + | |
| 417 | + it("should return null when search content is longer than file content", () => { | |
| 418 | + const fileContent = "short"; | |
| 419 | + const searchContent = "this is much longer than the file content"; | |
| 420 | + const result = findSearchMatch(fileContent, searchContent); | |
| 421 | + | |
| 422 | + expect(result).toBeNull(); | |
| 423 | + }); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + describe("Edge cases", () => { | |
| 427 | + it("should handle empty file content with non-empty search", () => { | |
| 428 | + const fileContent = ""; | |
| 429 | + const searchContent = "something"; | |
| 430 | + const result = findSearchMatch(fileContent, searchContent); | |
| 431 | + | |
| 432 | + expect(result).toBeNull(); | |
| 433 | + }); | |
| 434 | + | |
| 435 | + it("should handle single character matches", () => { | |
| 436 | + const fileContent = "a"; | |
| 437 | + const searchContent = "a"; | |
| 438 | + const result = findSearchMatch(fileContent, searchContent); | |
| 439 | + | |
| 440 | + expect(result).toEqual({ | |
| 441 | + startIndex: 0, | |
| 442 | + endIndex: 1, | |
| 443 | + strategyName: "exactMatch", | |
| 444 | + }); | |
| 445 | + }); | |
| 446 | + | |
| 447 | + it("should handle unicode characters", () => { | |
| 448 | + const fileContent = "Hello 🌍 World"; | |
| 449 | + const searchContent = "🌍"; | |
| 450 | + const result = findSearchMatch(fileContent, searchContent); | |
| 451 | + | |
| 452 | + expect(result).toEqual({ | |
| 453 | + startIndex: 6, | |
| 454 | + endIndex: 8, // Unicode emoji takes 2 character positions | |
| 455 | + strategyName: "exactMatch", | |
| 456 | + }); | |
| 457 | + }); | |
| 458 | + | |
| 459 | + it("should handle newlines and carriage returns", () => { | |
| 460 | + const fileContent = "line1\r\nline2\nline3"; | |
| 461 | + const searchContent = "\r\nline2"; | |
| 462 | + const result = findSearchMatch(fileContent, searchContent); | |
| 463 | + | |
| 464 | + expect(result).toEqual({ | |
| 465 | + startIndex: 5, | |
| 466 | + endIndex: 12, | |
| 467 | + strategyName: "exactMatch", | |
| 468 | + }); | |
| 469 | + }); | |
| 470 | + | |
| 471 | + it("should handle very long content efficiently", () => { | |
| 472 | + const longContent = "a".repeat(10000) + "target" + "b".repeat(10000); | |
| 473 | + const searchContent = "target"; | |
| 474 | + const result = findSearchMatch(longContent, searchContent); | |
| 475 | + | |
| 476 | + expect(result).toEqual({ | |
| 477 | + startIndex: 10000, | |
| 478 | + endIndex: 10006, | |
| 479 | + strategyName: "exactMatch", | |
| 480 | + }); | |
| 481 | + }); | |
| 482 | + }); | |
| 483 | + | |
| 484 | + describe("Strategy precedence", () => { | |
| 485 | + it("should prefer exact match over trimmed match", () => { | |
| 486 | + const fileContent = "hello world hello"; | |
| 487 | + const searchContent = "hello"; // This exists exactly, so should use exactMatch | |
| 488 | + const result = findSearchMatch(fileContent, searchContent); | |
| 489 | + | |
| 490 | + expect(result).toEqual({ | |
| 491 | + startIndex: 0, | |
| 492 | + endIndex: 5, | |
| 493 | + strategyName: "exactMatch", | |
| 494 | + }); | |
| 495 | + }); | |
| 496 | + | |
| 497 | + it("should prefer trimmed match over whitespace ignored match", () => { | |
| 498 | + // Set up content where trimmed match would work but whitespace ignored would also work | |
| 499 | + const fileContent = "hello world"; | |
| 500 | + const searchContent = " hello "; // Has whitespace but trimmed version exists | |
| 501 | + const result = findSearchMatch(fileContent, searchContent); | |
| 502 | + | |
| 503 | + expect(result).toEqual({ | |
| 504 | + startIndex: 0, | |
| 505 | + endIndex: 5, | |
| 506 | + strategyName: "trimmedMatch", | |
| 507 | + }); | |
| 508 | + }); | |
| 509 | + | |
| 510 | + it("should fall back through strategies in correct order", () => { | |
| 511 | + const fileContent = "function test() {\n return true;\n}"; | |
| 512 | + const searchContent = " function test(){return true;} "; // Needs whitespace ignored | |
| 513 | + const result = findSearchMatch(fileContent, searchContent); | |
| 514 | + | |
| 515 | + expect(result).toEqual({ | |
| 516 | + startIndex: 0, | |
| 517 | + endIndex: 34, | |
| 518 | + strategyName: "whitespaceIgnoredMatch", | |
| 519 | + }); | |
| 520 | + }); | |
| 521 | + }); | |
| 522 | + | |
| 523 | + describe("Real-world code examples", () => { | |
| 524 | + it("should handle JavaScript function matching", () => { | |
| 525 | + const fileContent = `function calculateSum(a, b) { | |
| 526 | + const result = a + b; | |
| 527 | + return result; | |
| 528 | +}`; | |
| 529 | + const searchContent = `function calculateSum(a, b) { | |
| 530 | + const result = a + b; | |
| 531 | + return result; | |
| 532 | +}`; | |
| 533 | + const result = findSearchMatch(fileContent, searchContent); | |
| 534 | + | |
| 535 | + expect(result).toEqual({ | |
| 536 | + startIndex: 0, | |
| 537 | + endIndex: 72, | |
| 538 | + strategyName: "exactMatch", | |
| 539 | + }); | |
| 540 | + }); | |
| 541 | + | |
| 542 | + it("should handle HTML tag matching with different formatting", () => { | |
| 543 | + const fileContent = `<div class="container"> | |
| 544 | + <p>Hello World</p> | |
| 545 | +</div>`; | |
| 546 | + const searchContent = `<div class="container"><p>Hello World</p></div>`; | |
| 547 | + const result = findSearchMatch(fileContent, searchContent); | |
| 548 | + | |
| 549 | + expect(result).toEqual({ | |
| 550 | + startIndex: 0, | |
| 551 | + endIndex: 51, | |
| 552 | + strategyName: "whitespaceIgnoredMatch", | |
| 553 | + }); | |
| 554 | + }); | |
| 555 | + | |
| 556 | + it("should handle CSS rule matching", () => { | |
| 557 | + const fileContent = `.button { | |
| 558 | + background-color: blue; | |
| 559 | + color: white; | |
| 560 | +}`; | |
| 561 | + const searchContent = `.button{background-color:blue;color:white;}`; | |
| 562 | + const result = findSearchMatch(fileContent, searchContent); | |
| 563 | + | |
| 564 | + expect(result).toEqual({ | |
| 565 | + startIndex: 0, | |
| 566 | + endIndex: 53, | |
| 567 | + strategyName: "whitespaceIgnoredMatch", | |
| 568 | + }); | |
| 569 | + }); | |
| 570 | + }); | |
| 571 | +}); |
| @@ -0,0 +1,368 @@ | ||
| 1 | +import { findSearchMatches } from "./findSearchMatch"; | |
| 2 | + | |
| 3 | +describe("findSearchMatches", () => { | |
| 4 | + describe("exact match strategy", () => { | |
| 5 | + it("should find single occurrence", () => { | |
| 6 | + const content = "const foo = 'bar';"; | |
| 7 | + const search = "foo"; | |
| 8 | + const matches = findSearchMatches(content, search); | |
| 9 | + | |
| 10 | + expect(matches).toHaveLength(1); | |
| 11 | + expect(matches[0]).toEqual({ | |
| 12 | + startIndex: 6, | |
| 13 | + endIndex: 9, | |
| 14 | + strategyName: "exactMatch", | |
| 15 | + }); | |
| 16 | + }); | |
| 17 | + | |
| 18 | + it("should find multiple occurrences", () => { | |
| 19 | + const content = "const foo = 'foo';"; | |
| 20 | + const search = "foo"; | |
| 21 | + const matches = findSearchMatches(content, search); | |
| 22 | + | |
| 23 | + expect(matches).toHaveLength(2); | |
| 24 | + expect(matches[0]).toEqual({ | |
| 25 | + startIndex: 6, | |
| 26 | + endIndex: 9, | |
| 27 | + strategyName: "exactMatch", | |
| 28 | + }); | |
| 29 | + expect(matches[1]).toEqual({ | |
| 30 | + startIndex: 13, | |
| 31 | + endIndex: 16, | |
| 32 | + strategyName: "exactMatch", | |
| 33 | + }); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should find overlapping pattern occurrences correctly", () => { | |
| 37 | + const content = "aaaa"; | |
| 38 | + const search = "aa"; | |
| 39 | + const matches = findSearchMatches(content, search); | |
| 40 | + | |
| 41 | + expect(matches).toHaveLength(2); | |
| 42 | + expect(matches[0]).toEqual({ | |
| 43 | + startIndex: 0, | |
| 44 | + endIndex: 2, | |
| 45 | + strategyName: "exactMatch", | |
| 46 | + }); | |
| 47 | + expect(matches[1]).toEqual({ | |
| 48 | + startIndex: 2, | |
| 49 | + endIndex: 4, | |
| 50 | + strategyName: "exactMatch", | |
| 51 | + }); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("should return empty array when no matches found", () => { | |
| 55 | + const content = "const bar = 'baz';"; | |
| 56 | + const search = "foo"; | |
| 57 | + const matches = findSearchMatches(content, search); | |
| 58 | + | |
| 59 | + expect(matches).toEqual([]); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + it("should handle multi-line content", () => { | |
| 63 | + const content = `line 1 foo | |
| 64 | +line 2 bar | |
| 65 | +line 3 foo`; | |
| 66 | + const search = "foo"; | |
| 67 | + const matches = findSearchMatches(content, search); | |
| 68 | + | |
| 69 | + expect(matches).toHaveLength(2); | |
| 70 | + expect(matches[0]).toEqual({ | |
| 71 | + startIndex: 7, | |
| 72 | + endIndex: 10, | |
| 73 | + strategyName: "exactMatch", | |
| 74 | + }); | |
| 75 | + expect(matches[1]).toEqual({ | |
| 76 | + startIndex: 29, | |
| 77 | + endIndex: 32, | |
| 78 | + strategyName: "exactMatch", | |
| 79 | + }); | |
| 80 | + }); | |
| 81 | + }); | |
| 82 | + | |
| 83 | + describe("trimmed match strategy", () => { | |
| 84 | + it("should find trimmed occurrences when exact match fails", () => { | |
| 85 | + const content = "const foo = 'bar';"; | |
| 86 | + const search = " foo "; | |
| 87 | + const matches = findSearchMatches(content, search); | |
| 88 | + | |
| 89 | + expect(matches).toHaveLength(1); | |
| 90 | + expect(matches[0]).toEqual({ | |
| 91 | + startIndex: 6, | |
| 92 | + endIndex: 9, | |
| 93 | + strategyName: "trimmedMatch", | |
| 94 | + }); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should find multiple trimmed occurrences", () => { | |
| 98 | + const content = "const foo = 'foo';"; | |
| 99 | + const search = " foo "; | |
| 100 | + const matches = findSearchMatches(content, search); | |
| 101 | + | |
| 102 | + expect(matches).toHaveLength(2); | |
| 103 | + expect(matches[0]).toEqual({ | |
| 104 | + startIndex: 6, | |
| 105 | + endIndex: 9, | |
| 106 | + strategyName: "trimmedMatch", | |
| 107 | + }); | |
| 108 | + expect(matches[1]).toEqual({ | |
| 109 | + startIndex: 13, | |
| 110 | + endIndex: 16, | |
| 111 | + strategyName: "trimmedMatch", | |
| 112 | + }); | |
| 113 | + }); | |
| 114 | + }); | |
| 115 | + | |
| 116 | + describe("whitespace ignored match strategy", () => { | |
| 117 | + it("should find matches ignoring internal whitespace", () => { | |
| 118 | + const content = "const foo = bar;"; | |
| 119 | + const search = "const foo=bar"; | |
| 120 | + const matches = findSearchMatches(content, search); | |
| 121 | + | |
| 122 | + expect(matches).toHaveLength(1); | |
| 123 | + expect(matches[0]).toEqual({ | |
| 124 | + startIndex: 0, | |
| 125 | + endIndex: 15, | |
| 126 | + strategyName: "whitespaceIgnoredMatch", | |
| 127 | + }); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should find multiple matches ignoring whitespace", () => { | |
| 131 | + const content = `const foo = bar; | |
| 132 | +const baz = foo;`; | |
| 133 | + const search = "const foo"; | |
| 134 | + const matches = findSearchMatches(content, search); | |
| 135 | + | |
| 136 | + expect(matches).toHaveLength(1); | |
| 137 | + expect(matches[0]).toEqual({ | |
| 138 | + startIndex: 0, | |
| 139 | + endIndex: 9, | |
| 140 | + strategyName: "exactMatch", | |
| 141 | + }); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should handle complex whitespace patterns", () => { | |
| 145 | + const content = `function test() { | |
| 146 | + return true; | |
| 147 | +}`; | |
| 148 | + const search = "function test(){return true;}"; | |
| 149 | + const matches = findSearchMatches(content, search); | |
| 150 | + | |
| 151 | + expect(matches).toHaveLength(1); | |
| 152 | + expect(matches[0]).toEqual({ | |
| 153 | + startIndex: 0, | |
| 154 | + endIndex: 34, | |
| 155 | + strategyName: "whitespaceIgnoredMatch", | |
| 156 | + }); | |
| 157 | + }); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + describe("empty search content", () => { | |
| 161 | + it("should return single match at position 0 for empty string", () => { | |
| 162 | + const content = "const foo = 'bar';"; | |
| 163 | + const search = ""; | |
| 164 | + const matches = findSearchMatches(content, search); | |
| 165 | + | |
| 166 | + expect(matches).toHaveLength(1); | |
| 167 | + expect(matches[0]).toEqual({ | |
| 168 | + startIndex: 0, | |
| 169 | + endIndex: 0, | |
| 170 | + strategyName: "emptySearch", | |
| 171 | + }); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + it("should return single match at position 0 for whitespace-only string", () => { | |
| 175 | + const content = "const foo = 'bar';"; | |
| 176 | + const search = " \n\t "; | |
| 177 | + const matches = findSearchMatches(content, search); | |
| 178 | + | |
| 179 | + expect(matches).toHaveLength(1); | |
| 180 | + expect(matches[0]).toEqual({ | |
| 181 | + startIndex: 0, | |
| 182 | + endIndex: 0, | |
| 183 | + strategyName: "emptySearch", | |
| 184 | + }); | |
| 185 | + }); | |
| 186 | + }); | |
| 187 | + | |
| 188 | + describe("edge cases", () => { | |
| 189 | + it("should handle searching in empty content", () => { | |
| 190 | + const content = ""; | |
| 191 | + const search = "foo"; | |
| 192 | + const matches = findSearchMatches(content, search); | |
| 193 | + | |
| 194 | + expect(matches).toEqual([]); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should handle searching for content at the beginning", () => { | |
| 198 | + const content = "foo bar baz"; | |
| 199 | + const search = "foo"; | |
| 200 | + const matches = findSearchMatches(content, search); | |
| 201 | + | |
| 202 | + expect(matches).toHaveLength(1); | |
| 203 | + expect(matches[0]).toEqual({ | |
| 204 | + startIndex: 0, | |
| 205 | + endIndex: 3, | |
| 206 | + strategyName: "exactMatch", | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + it("should handle searching for content at the end", () => { | |
| 211 | + const content = "foo bar baz"; | |
| 212 | + const search = "baz"; | |
| 213 | + const matches = findSearchMatches(content, search); | |
| 214 | + | |
| 215 | + expect(matches).toHaveLength(1); | |
| 216 | + expect(matches[0]).toEqual({ | |
| 217 | + startIndex: 8, | |
| 218 | + endIndex: 11, | |
| 219 | + strategyName: "exactMatch", | |
| 220 | + }); | |
| 221 | + }); | |
| 222 | + | |
| 223 | + it("should handle searching for the entire content", () => { | |
| 224 | + const content = "foo bar baz"; | |
| 225 | + const search = "foo bar baz"; | |
| 226 | + const matches = findSearchMatches(content, search); | |
| 227 | + | |
| 228 | + expect(matches).toHaveLength(1); | |
| 229 | + expect(matches[0]).toEqual({ | |
| 230 | + startIndex: 0, | |
| 231 | + endIndex: 11, | |
| 232 | + strategyName: "exactMatch", | |
| 233 | + }); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + it("should handle special characters", () => { | |
| 237 | + const content = "const regex = /[a-z]+/g;"; | |
| 238 | + const search = "/[a-z]+/g"; | |
| 239 | + const matches = findSearchMatches(content, search); | |
| 240 | + | |
| 241 | + expect(matches).toHaveLength(1); | |
| 242 | + expect(matches[0]).toEqual({ | |
| 243 | + startIndex: 14, | |
| 244 | + endIndex: 23, | |
| 245 | + strategyName: "exactMatch", | |
| 246 | + }); | |
| 247 | + }); | |
| 248 | + | |
| 249 | + it("should handle Unicode characters", () => { | |
| 250 | + const content = "const emoji = '🚀 Hello 🌍';"; | |
| 251 | + const search = "🚀 Hello 🌍"; | |
| 252 | + const matches = findSearchMatches(content, search); | |
| 253 | + | |
| 254 | + expect(matches).toHaveLength(1); | |
| 255 | + expect(matches[0]).toEqual({ | |
| 256 | + startIndex: 15, | |
| 257 | + endIndex: 26, | |
| 258 | + strategyName: "exactMatch", | |
| 259 | + }); | |
| 260 | + }); | |
| 261 | + }); | |
| 262 | + | |
| 263 | + describe("performance considerations", () => { | |
| 264 | + it("should handle long content with multiple matches", () => { | |
| 265 | + const repeatedContent = "foo bar ".repeat(1000); | |
| 266 | + const search = "foo"; | |
| 267 | + const matches = findSearchMatches(repeatedContent, search); | |
| 268 | + | |
| 269 | + expect(matches).toHaveLength(1000); | |
| 270 | + expect(matches[0]).toEqual({ | |
| 271 | + startIndex: 0, | |
| 272 | + endIndex: 3, | |
| 273 | + strategyName: "exactMatch", | |
| 274 | + }); | |
| 275 | + expect(matches[999]).toEqual({ | |
| 276 | + startIndex: 7992, | |
| 277 | + endIndex: 7995, | |
| 278 | + strategyName: "exactMatch", | |
| 279 | + }); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("should prevent infinite loops on edge cases", () => { | |
| 283 | + const content = "aaaa"; | |
| 284 | + const search = ""; | |
| 285 | + const matches = findSearchMatches(content, search); | |
| 286 | + | |
| 287 | + // Should only return one match for empty search | |
| 288 | + expect(matches).toHaveLength(1); | |
| 289 | + expect(matches[0]).toEqual({ | |
| 290 | + startIndex: 0, | |
| 291 | + endIndex: 0, | |
| 292 | + strategyName: "emptySearch", | |
| 293 | + }); | |
| 294 | + }); | |
| 295 | + }); | |
| 296 | + | |
| 297 | + describe("strategy selection", () => { | |
| 298 | + it("should use exact match strategy when possible", () => { | |
| 299 | + const content = "const foo = bar;"; | |
| 300 | + const search = "foo"; | |
| 301 | + const matches = findSearchMatches(content, search); | |
| 302 | + | |
| 303 | + expect(matches).toHaveLength(1); | |
| 304 | + expect(matches[0].strategyName).toBe("exactMatch"); | |
| 305 | + }); | |
| 306 | + | |
| 307 | + it("should fallback to trimmed match when exact fails", () => { | |
| 308 | + const content = "const foo = bar;"; | |
| 309 | + const search = " foo "; | |
| 310 | + const matches = findSearchMatches(content, search); | |
| 311 | + | |
| 312 | + expect(matches).toHaveLength(1); | |
| 313 | + expect(matches[0].strategyName).toBe("trimmedMatch"); | |
| 314 | + }); | |
| 315 | + | |
| 316 | + it("should fallback to whitespace ignored when others fail", () => { | |
| 317 | + const content = "const foo = bar;"; | |
| 318 | + const search = "const foo=bar"; | |
| 319 | + const matches = findSearchMatches(content, search); | |
| 320 | + | |
| 321 | + expect(matches).toHaveLength(1); | |
| 322 | + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); | |
| 323 | + }); | |
| 324 | + }); | |
| 325 | + | |
| 326 | + describe("complex patterns", () => { | |
| 327 | + it("should handle multiple matches with different line endings", () => { | |
| 328 | + const content = "foo\r\nbar\r\nfoo\nfoo"; | |
| 329 | + const search = "foo"; | |
| 330 | + const matches = findSearchMatches(content, search); | |
| 331 | + | |
| 332 | + expect(matches).toHaveLength(3); | |
| 333 | + expect(matches[0].startIndex).toBe(0); | |
| 334 | + expect(matches[1].startIndex).toBe(10); | |
| 335 | + expect(matches[2].startIndex).toBe(14); | |
| 336 | + }); | |
| 337 | + | |
| 338 | + it("should handle matches across different strategies", () => { | |
| 339 | + const content = "const foo = 'bar';\n const foo='baz';"; | |
| 340 | + const search = "foo"; | |
| 341 | + const matches = findSearchMatches(content, search); | |
| 342 | + | |
| 343 | + // Both occurrences of "foo" should be found with exact match | |
| 344 | + expect(matches).toHaveLength(2); | |
| 345 | + expect(matches[0]).toEqual({ | |
| 346 | + startIndex: 6, | |
| 347 | + endIndex: 9, | |
| 348 | + strategyName: "exactMatch", | |
| 349 | + }); | |
| 350 | + expect(matches[1]).toEqual({ | |
| 351 | + startIndex: 29, | |
| 352 | + endIndex: 32, | |
| 353 | + strategyName: "exactMatch", | |
| 354 | + }); | |
| 355 | + }); | |
| 356 | + | |
| 357 | + it("should handle code with mixed indentation", () => { | |
| 358 | + const content = `\tfunction test() { | |
| 359 | + return true; | |
| 360 | +\t}`; | |
| 361 | + const search = "function test(){return true;}"; | |
| 362 | + const matches = findSearchMatches(content, search); | |
| 363 | + | |
| 364 | + expect(matches).toHaveLength(1); | |
| 365 | + expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch"); | |
| 366 | + }); | |
| 367 | + }); | |
| 368 | +}); |
| @@ -0,0 +1,341 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 3 | +import { ContinueErrorReason } from "../../util/errors"; | |
| 4 | +import { validateMultiEdit } from "./multiEditValidation"; | |
| 5 | +import { executeMultiFindAndReplace } from "./performReplace"; | |
| 6 | + | |
| 7 | +describe("multiEdit shared validation", () => { | |
| 8 | + describe("validateMultiEdit", () => { | |
| 9 | + it("should throw error if edits is not an array", () => { | |
| 10 | + expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError( | |
| 11 | + expect.objectContaining({ | |
| 12 | + reason: ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 13 | + }), | |
| 14 | + ); | |
| 15 | + }); | |
| 16 | + | |
| 17 | + it("should throw error if edits is missing", () => { | |
| 18 | + expect(() => validateMultiEdit({})).toThrowError( | |
| 19 | + expect.objectContaining({ | |
| 20 | + reason: ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 21 | + }), | |
| 22 | + ); | |
| 23 | + }); | |
| 24 | + | |
| 25 | + it("should throw error if edits array is empty", () => { | |
| 26 | + expect(() => validateMultiEdit({ edits: [] })).toThrowError( | |
| 27 | + expect.objectContaining({ | |
| 28 | + reason: ContinueErrorReason.MultiEditEditsArrayEmpty, | |
| 29 | + }), | |
| 30 | + ); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + it("should return valid edits", () => { | |
| 34 | + const edits: EditOperation[] = [ | |
| 35 | + { old_string: "hello", new_string: "world" }, | |
| 36 | + ]; | |
| 37 | + const result = validateMultiEdit({ edits }); | |
| 38 | + expect(result.edits).toEqual(edits); | |
| 39 | + }); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + describe("validateMultiEdit - individual edit validation", () => { | |
| 43 | + it("should throw error if edit has missing old_string", () => { | |
| 44 | + const args = { | |
| 45 | + edits: [ | |
| 46 | + { | |
| 47 | + old_string: undefined as any, | |
| 48 | + new_string: "Hi there", | |
| 49 | + }, | |
| 50 | + ], | |
| 51 | + }; | |
| 52 | + | |
| 53 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 54 | + expect.objectContaining({ | |
| 55 | + reason: ContinueErrorReason.FindAndReplaceMissingOldString, | |
| 56 | + }), | |
| 57 | + ); | |
| 58 | + }); | |
| 59 | + | |
| 60 | + it("should throw error if edit has missing new_string", () => { | |
| 61 | + const args = { | |
| 62 | + edits: [ | |
| 63 | + { | |
| 64 | + old_string: "Hello world", | |
| 65 | + new_string: undefined as any, | |
| 66 | + }, | |
| 67 | + ], | |
| 68 | + }; | |
| 69 | + | |
| 70 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 71 | + expect.objectContaining({ | |
| 72 | + reason: ContinueErrorReason.FindAndReplaceMissingNewString, | |
| 73 | + }), | |
| 74 | + ); | |
| 75 | + }); | |
| 76 | + | |
| 77 | + it("should throw error if old_string and new_string are the same", () => { | |
| 78 | + const args = { | |
| 79 | + edits: [ | |
| 80 | + { | |
| 81 | + old_string: "Hello world", | |
| 82 | + new_string: "Hello world", | |
| 83 | + }, | |
| 84 | + ], | |
| 85 | + }; | |
| 86 | + | |
| 87 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 88 | + expect.objectContaining({ | |
| 89 | + reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, | |
| 90 | + }), | |
| 91 | + ); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should throw error if non-first edit has empty old_string", () => { | |
| 95 | + const args = { | |
| 96 | + edits: [ | |
| 97 | + { | |
| 98 | + old_string: "Hello world", | |
| 99 | + new_string: "Hi there", | |
| 100 | + }, | |
| 101 | + { | |
| 102 | + old_string: "", | |
| 103 | + new_string: "Invalid insertion", | |
| 104 | + }, | |
| 105 | + ], | |
| 106 | + }; | |
| 107 | + | |
| 108 | + expect(() => validateMultiEdit(args)).toThrowError( | |
| 109 | + expect.objectContaining({ | |
| 110 | + reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, | |
| 111 | + }), | |
| 112 | + ); | |
| 113 | + }); | |
| 114 | + | |
| 115 | + it("should allow first edit to have empty old_string", () => { | |
| 116 | + const args = { | |
| 117 | + edits: [ | |
| 118 | + { | |
| 119 | + old_string: "", | |
| 120 | + new_string: "New content", | |
| 121 | + }, | |
| 122 | + ], | |
| 123 | + }; | |
| 124 | + | |
| 125 | + expect(() => validateMultiEdit(args)).not.toThrow(); | |
| 126 | + }); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + describe("executeMultiFindAndReplace", () => { | |
| 130 | + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; | |
| 131 | + | |
| 132 | + it("should handle single edit", () => { | |
| 133 | + const edits = [ | |
| 134 | + { | |
| 135 | + old_string: "Hello world", | |
| 136 | + new_string: "Hi there", | |
| 137 | + }, | |
| 138 | + ]; | |
| 139 | + | |
| 140 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 141 | + expect(result).toBe("Hi there\nThis is a test file\nGoodbye world"); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should handle multiple edits", () => { | |
| 145 | + const edits = [ | |
| 146 | + { | |
| 147 | + old_string: "Hello world", | |
| 148 | + new_string: "Hi there", | |
| 149 | + }, | |
| 150 | + { | |
| 151 | + old_string: "Goodbye world", | |
| 152 | + new_string: "See you later", | |
| 153 | + }, | |
| 154 | + ]; | |
| 155 | + | |
| 156 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 157 | + expect(result).toBe("Hi there\nThis is a test file\nSee you later"); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + it("should handle replace_all", () => { | |
| 161 | + const edits = [ | |
| 162 | + { | |
| 163 | + old_string: "world", | |
| 164 | + new_string: "universe", | |
| 165 | + replace_all: true, | |
| 166 | + }, | |
| 167 | + ]; | |
| 168 | + | |
| 169 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 170 | + expect(result).toBe( | |
| 171 | + "Hello universe\nThis is a test file\nGoodbye universe", | |
| 172 | + ); | |
| 173 | + }); | |
| 174 | + | |
| 175 | + it("should handle empty old_string as insertion at beginning", () => { | |
| 176 | + const edits = [ | |
| 177 | + { | |
| 178 | + old_string: "", | |
| 179 | + new_string: "New first line\n", | |
| 180 | + }, | |
| 181 | + ]; | |
| 182 | + | |
| 183 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 184 | + expect(result).toBe( | |
| 185 | + "New first line\nHello world\nThis is a test file\nGoodbye world", | |
| 186 | + ); | |
| 187 | + }); | |
| 188 | + | |
| 189 | + it("should handle empty string in empty file", () => { | |
| 190 | + const edits = [ | |
| 191 | + { | |
| 192 | + old_string: "", | |
| 193 | + new_string: "Content for empty file", | |
| 194 | + }, | |
| 195 | + ]; | |
| 196 | + | |
| 197 | + // Empty old_string matches at position 0 (beginning of file) | |
| 198 | + const result = executeMultiFindAndReplace("", edits); | |
| 199 | + expect(result).toBe("Content for empty file"); | |
| 200 | + }); | |
| 201 | + | |
| 202 | + it("should apply edits sequentially", () => { | |
| 203 | + const edits = [ | |
| 204 | + { | |
| 205 | + old_string: "Hello world", | |
| 206 | + new_string: "Hi universe", | |
| 207 | + }, | |
| 208 | + { | |
| 209 | + old_string: "Hi universe", | |
| 210 | + new_string: "Greetings cosmos", | |
| 211 | + }, | |
| 212 | + ]; | |
| 213 | + | |
| 214 | + const result = executeMultiFindAndReplace(originalContent, edits); | |
| 215 | + expect(result).toBe( | |
| 216 | + "Greetings cosmos\nThis is a test file\nGoodbye world", | |
| 217 | + ); | |
| 218 | + }); | |
| 219 | + | |
| 220 | + it("should throw error if old_string is not found", () => { | |
| 221 | + const edits = [ | |
| 222 | + { | |
| 223 | + old_string: "Not found", | |
| 224 | + new_string: "Hi there", | |
| 225 | + }, | |
| 226 | + ]; | |
| 227 | + | |
| 228 | + expect(() => | |
| 229 | + executeMultiFindAndReplace(originalContent, edits), | |
| 230 | + ).toThrowError( | |
| 231 | + expect.objectContaining({ | |
| 232 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 233 | + }), | |
| 234 | + ); | |
| 235 | + }); | |
| 236 | + | |
| 237 | + it("should throw error if old_string appears multiple times and replace_all is false", () => { | |
| 238 | + const edits = [ | |
| 239 | + { | |
| 240 | + old_string: "world", | |
| 241 | + new_string: "universe", | |
| 242 | + replace_all: false, | |
| 243 | + }, | |
| 244 | + ]; | |
| 245 | + | |
| 246 | + expect(() => | |
| 247 | + executeMultiFindAndReplace(originalContent, edits), | |
| 248 | + ).toThrowError( | |
| 249 | + expect.objectContaining({ | |
| 250 | + reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 251 | + }), | |
| 252 | + ); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + it("should throw if string not found in edit sequence", () => { | |
| 256 | + const content = "Hello world"; | |
| 257 | + const edits = [ | |
| 258 | + { old_string: "Hello", new_string: "Hi" }, | |
| 259 | + { old_string: "not found", new_string: "test" }, | |
| 260 | + ]; | |
| 261 | + | |
| 262 | + expect(() => executeMultiFindAndReplace(content, edits)).toThrowError( | |
| 263 | + expect.objectContaining({ | |
| 264 | + reason: ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 265 | + }), | |
| 266 | + ); | |
| 267 | + }); | |
| 268 | + | |
| 269 | + it("should handle whitespace differences using findSearchMatch", () => { | |
| 270 | + const content = "function test() {\n return true;\n}"; | |
| 271 | + const edits = [ | |
| 272 | + { | |
| 273 | + old_string: "function test(){return true;}", | |
| 274 | + new_string: "function test() { return false; }", | |
| 275 | + }, | |
| 276 | + ]; | |
| 277 | + | |
| 278 | + const result = executeMultiFindAndReplace(content, edits); | |
| 279 | + expect(result).toBe("function test() { return false; }"); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("should handle mixed replace_all settings", () => { | |
| 283 | + const content = "x y x z x"; | |
| 284 | + const edits = [ | |
| 285 | + { old_string: "x", new_string: "a", replace_all: true }, | |
| 286 | + { old_string: "y", new_string: "b" }, | |
| 287 | + ]; | |
| 288 | + | |
| 289 | + const result = executeMultiFindAndReplace(content, edits); | |
| 290 | + expect(result).toBe("a b a z a"); | |
| 291 | + }); | |
| 292 | + }); | |
| 293 | + | |
| 294 | + describe("preprocessing logic", () => { | |
| 295 | + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; | |
| 296 | + | |
| 297 | + it("should handle single edit preprocessing", () => { | |
| 298 | + const edits = [ | |
| 299 | + { | |
| 300 | + old_string: "Hello world", | |
| 301 | + new_string: "Hi there", | |
| 302 | + }, | |
| 303 | + ]; | |
| 304 | + | |
| 305 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 306 | + | |
| 307 | + expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world"); | |
| 308 | + }); | |
| 309 | + | |
| 310 | + it("should handle multiple edits preprocessing", () => { | |
| 311 | + const edits = [ | |
| 312 | + { | |
| 313 | + old_string: "Hello world", | |
| 314 | + new_string: "Hi there", | |
| 315 | + }, | |
| 316 | + { | |
| 317 | + old_string: "Goodbye world", | |
| 318 | + new_string: "See you later", | |
| 319 | + }, | |
| 320 | + ]; | |
| 321 | + | |
| 322 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 323 | + | |
| 324 | + expect(newContent).toBe("Hi there\nThis is a test file\nSee you later"); | |
| 325 | + }); | |
| 326 | + | |
| 327 | + it("should count edits correctly", () => { | |
| 328 | + const edits = [ | |
| 329 | + { old_string: "Hello", new_string: "Hi" }, | |
| 330 | + { old_string: "world", new_string: "universe", replace_all: true }, | |
| 331 | + ]; | |
| 332 | + | |
| 333 | + const newContent = executeMultiFindAndReplace(originalContent, edits); | |
| 334 | + | |
| 335 | + expect(newContent).toBe( | |
| 336 | + "Hi universe\nThis is a test file\nGoodbye universe", | |
| 337 | + ); | |
| 338 | + expect(edits.length).toBe(2); | |
| 339 | + }); | |
| 340 | + }); | |
| 341 | +}); |
| @@ -0,0 +1,50 @@ | ||
| 1 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 2 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { validateSingleEdit } from "./findAndReplaceUtils"; | |
| 4 | + | |
| 5 | +export interface MultiEditValidationResult { | |
| 6 | + edits: EditOperation[]; | |
| 7 | +} | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * Validates multi-edit arguments and all edits in a single pass | |
| 11 | + * @param args - The arguments object containing the edits array | |
| 12 | + * @returns Validated edits array | |
| 13 | + * @throws ContinueError if validation fails | |
| 14 | + */ | |
| 15 | +export function validateMultiEdit(args: any): MultiEditValidationResult { | |
| 16 | + const { edits } = args; | |
| 17 | + | |
| 18 | + // Validate that edits is a non-empty array | |
| 19 | + if (!edits || !Array.isArray(edits)) { | |
| 20 | + throw new ContinueError( | |
| 21 | + ContinueErrorReason.MultiEditEditsArrayRequired, | |
| 22 | + "edits array is required", | |
| 23 | + ); | |
| 24 | + } | |
| 25 | + | |
| 26 | + if (edits.length === 0) { | |
| 27 | + throw new ContinueError( | |
| 28 | + ContinueErrorReason.MultiEditEditsArrayEmpty, | |
| 29 | + "edits array must contain at least one edit", | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + | |
| 33 | + // Validate each individual edit | |
| 34 | + for (let i = 0; i < edits.length; i++) { | |
| 35 | + const edit = edits[i]; | |
| 36 | + | |
| 37 | + // Use existing single edit validation | |
| 38 | + validateSingleEdit(edit.old_string, edit.new_string, i); | |
| 39 | + | |
| 40 | + // Only the first edit can have empty old_string (for insertion at beginning) | |
| 41 | + if (i > 0 && edit.old_string === "") { | |
| 42 | + throw new ContinueError( | |
| 43 | + ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString, | |
| 44 | + `Edit at index ${i}: old_string cannot be empty. Only the first edit can have an empty old_string for insertion at the beginning of the file.`, | |
| 45 | + ); | |
| 46 | + } | |
| 47 | + } | |
| 48 | + | |
| 49 | + return { edits }; | |
| 50 | +} |
| @@ -1,390 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - parseAllSearchReplaceBlocks, | |
| 3 | - parseSearchReplaceBlock, | |
| 4 | -} from "./parseSearchReplaceBlock"; | |
| 5 | - | |
| 6 | -describe("parseSearchReplaceBlock", () => { | |
| 7 | - describe("Complete blocks", () => { | |
| 8 | - it("should parse a complete basic search/replace block", () => { | |
| 9 | - const content = `------- SEARCH | |
| 10 | -reset() { | |
| 11 | -this.result = 0; | |
| 12 | -return this; | |
| 13 | -} | |
| 14 | -======= | |
| 15 | -// Resets the calculator result to 0 and returns the instance for method chaining | |
| 16 | -reset() { | |
| 17 | -this.result = 0; | |
| 18 | -return this; | |
| 19 | -} | |
| 20 | -+++++++ REPLACE`; | |
| 21 | - | |
| 22 | - const result = parseSearchReplaceBlock(content); | |
| 23 | - | |
| 24 | - expect(result.isComplete).toBe(true); | |
| 25 | - expect(result.searchContent).toBe(`reset() { | |
| 26 | -this.result = 0; | |
| 27 | -return this; | |
| 28 | -}`); | |
| 29 | - expect(result.replaceContent) | |
| 30 | - .toBe(`// Resets the calculator result to 0 and returns the instance for method chaining | |
| 31 | -reset() { | |
| 32 | -this.result = 0; | |
| 33 | -return this; | |
| 34 | -}`); | |
| 35 | - expect(result.error).toBeUndefined(); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - it("should handle different marker lengths", () => { | |
| 39 | - const content = `------- SEARCH | |
| 40 | -old content | |
| 41 | -========= | |
| 42 | -new content | |
| 43 | -+++++++++++ REPLACE`; | |
| 44 | - | |
| 45 | - const result = parseSearchReplaceBlock(content); | |
| 46 | - | |
| 47 | - expect(result.isComplete).toBe(true); | |
| 48 | - expect(result.searchContent).toBe("old content"); | |
| 49 | - expect(result.replaceContent).toBe("new content"); | |
| 50 | - }); | |
| 51 | - | |
| 52 | - it("should handle empty search content", () => { | |
| 53 | - const content = `------- SEARCH | |
| 54 | -======= | |
| 55 | -new content | |
| 56 | -+++++++ REPLACE`; | |
| 57 | - | |
| 58 | - const result = parseSearchReplaceBlock(content); | |
| 59 | - | |
| 60 | - expect(result.isComplete).toBe(true); | |
| 61 | - expect(result.searchContent).toBe(""); | |
| 62 | - expect(result.replaceContent).toBe("new content"); | |
| 63 | - }); | |
| 64 | - | |
| 65 | - it("should handle empty replace content (deletion)", () => { | |
| 66 | - const content = `------- SEARCH | |
| 67 | -old content to delete | |
| 68 | -======= | |
| 69 | -+++++++ REPLACE`; | |
| 70 | - | |
| 71 | - const result = parseSearchReplaceBlock(content); | |
| 72 | - | |
| 73 | - expect(result.isComplete).toBe(true); | |
| 74 | - expect(result.searchContent).toBe("old content to delete"); | |
| 75 | - expect(result.replaceContent).toBe(""); | |
| 76 | - }); | |
| 77 | - | |
| 78 | - it("should handle both empty search and replace content", () => { | |
| 79 | - const content = `------- SEARCH | |
| 80 | -======= | |
| 81 | -+++++++ REPLACE`; | |
| 82 | - | |
| 83 | - const result = parseSearchReplaceBlock(content); | |
| 84 | - | |
| 85 | - expect(result.isComplete).toBe(true); | |
| 86 | - expect(result.searchContent).toBe(""); | |
| 87 | - expect(result.replaceContent).toBe(""); | |
| 88 | - }); | |
| 89 | - }); | |
| 90 | - | |
| 91 | - describe("Incomplete blocks", () => { | |
| 92 | - it("should handle incomplete search block", () => { | |
| 93 | - const content = `------- SEARCH | |
| 94 | -some content`; | |
| 95 | - | |
| 96 | - const result = parseSearchReplaceBlock(content); | |
| 97 | - | |
| 98 | - expect(result.isComplete).toBe(false); | |
| 99 | - expect(result.searchContent).toBe("some content"); | |
| 100 | - expect(result.replaceContent).toBe(""); | |
| 101 | - expect(result.error).toBeUndefined(); | |
| 102 | - }); | |
| 103 | - | |
| 104 | - it("should handle incomplete replace block", () => { | |
| 105 | - const content = `------- SEARCH | |
| 106 | -old content | |
| 107 | -======= | |
| 108 | -new content`; | |
| 109 | - | |
| 110 | - const result = parseSearchReplaceBlock(content); | |
| 111 | - | |
| 112 | - expect(result.isComplete).toBe(false); | |
| 113 | - expect(result.searchContent).toBe("old content"); | |
| 114 | - expect(result.replaceContent).toBe("new content"); | |
| 115 | - expect(result.error).toBeUndefined(); | |
| 116 | - }); | |
| 117 | - }); | |
| 118 | - | |
| 119 | - describe("Error cases", () => { | |
| 120 | - it("should error on search end without start", () => { | |
| 121 | - const content = `======= | |
| 122 | -some content | |
| 123 | -+++++++ REPLACE`; | |
| 124 | - | |
| 125 | - const result = parseSearchReplaceBlock(content); | |
| 126 | - | |
| 127 | - expect(result.isComplete).toBe(false); | |
| 128 | - expect(result.error).toBe( | |
| 129 | - "Found search block end marker without matching start marker", | |
| 130 | - ); | |
| 131 | - }); | |
| 132 | - | |
| 133 | - it("should error on replace end without replace start", () => { | |
| 134 | - const content = `+++++++ REPLACE`; | |
| 135 | - | |
| 136 | - const result = parseSearchReplaceBlock(content); | |
| 137 | - | |
| 138 | - expect(result.isComplete).toBe(false); | |
| 139 | - expect(result.error).toBe( | |
| 140 | - "Found replace block end marker without matching replace start marker", | |
| 141 | - ); | |
| 142 | - }); | |
| 143 | - }); | |
| 144 | - | |
| 145 | - describe("Regex pattern validation", () => { | |
| 146 | - it("should match various search start patterns", () => { | |
| 147 | - const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"]; | |
| 148 | - | |
| 149 | - patterns.forEach((pattern) => { | |
| 150 | - const content = `${pattern} | |
| 151 | -content | |
| 152 | -======= | |
| 153 | -replacement | |
| 154 | -+++++++ REPLACE`; | |
| 155 | - | |
| 156 | - const result = parseSearchReplaceBlock(content); | |
| 157 | - expect(result.isComplete).toBe(true); | |
| 158 | - }); | |
| 159 | - }); | |
| 160 | - | |
| 161 | - it("should match various search end patterns", () => { | |
| 162 | - const patterns = ["===", "=======", "=============="]; | |
| 163 | - | |
| 164 | - patterns.forEach((pattern) => { | |
| 165 | - const content = `------- SEARCH | |
| 166 | -content | |
| 167 | -${pattern} | |
| 168 | -replacement | |
| 169 | -+++++++ REPLACE`; | |
| 170 | - | |
| 171 | - const result = parseSearchReplaceBlock(content); | |
| 172 | - expect(result.isComplete).toBe(true); | |
| 173 | - }); | |
| 174 | - }); | |
| 175 | - | |
| 176 | - it("should match various replace end patterns", () => { | |
| 177 | - const patterns = [ | |
| 178 | - "+++ REPLACE", | |
| 179 | - "+++++++ REPLACE", | |
| 180 | - "+++++++++++ REPLACE", | |
| 181 | - ]; | |
| 182 | - | |
| 183 | - patterns.forEach((pattern) => { | |
| 184 | - const content = `------- SEARCH | |
| 185 | -content | |
| 186 | -======= | |
| 187 | -replacement | |
| 188 | -${pattern}`; | |
| 189 | - | |
| 190 | - const result = parseSearchReplaceBlock(content); | |
| 191 | - expect(result.isComplete).toBe(true); | |
| 192 | - }); | |
| 193 | - }); | |
| 194 | - | |
| 195 | - it("should not match invalid patterns", () => { | |
| 196 | - const invalidPatterns = [ | |
| 197 | - "-- SEARCH", // Too few dashes | |
| 198 | - "SEARCH", // No markers | |
| 199 | - "== SEARCH", // Wrong markers | |
| 200 | - "=== REPLACE", // Wrong end marker | |
| 201 | - "++++ SEARCH", // Wrong markers for search | |
| 202 | - ]; | |
| 203 | - | |
| 204 | - invalidPatterns.forEach((pattern) => { | |
| 205 | - const content = `${pattern} | |
| 206 | -content`; | |
| 207 | - | |
| 208 | - const result = parseSearchReplaceBlock(content); | |
| 209 | - expect(result.isComplete).toBe(false); | |
| 210 | - expect(result.searchContent).toBe(""); // Should not enter search mode | |
| 211 | - }); | |
| 212 | - }); | |
| 213 | - }); | |
| 214 | -}); | |
| 215 | - | |
| 216 | -describe("parseAllSearchReplaceBlocks", () => { | |
| 217 | - it("should parse multiple complete blocks", () => { | |
| 218 | - const content = `------- SEARCH | |
| 219 | -old code 1 | |
| 220 | -======= | |
| 221 | -new code 1 | |
| 222 | -+++++++ REPLACE | |
| 223 | - | |
| 224 | -------- SEARCH | |
| 225 | -old code 2 | |
| 226 | -======= | |
| 227 | -new code 2 | |
| 228 | -+++++++ REPLACE`; | |
| 229 | - | |
| 230 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 231 | - | |
| 232 | - expect(blocks).toHaveLength(2); | |
| 233 | - expect(blocks[0].searchContent).toBe("old code 1"); | |
| 234 | - expect(blocks[0].replaceContent).toBe("new code 1"); | |
| 235 | - expect(blocks[1].searchContent).toBe("old code 2"); | |
| 236 | - expect(blocks[1].replaceContent).toBe("new code 2"); | |
| 237 | - }); | |
| 238 | - | |
| 239 | - it("should handle blocks with different content", () => { | |
| 240 | - const content = `------- SEARCH | |
| 241 | -function old() { | |
| 242 | - return 1; | |
| 243 | -} | |
| 244 | -======= | |
| 245 | -function new() { | |
| 246 | - return 2; | |
| 247 | -} | |
| 248 | -+++++++ REPLACE | |
| 249 | - | |
| 250 | -------- SEARCH | |
| 251 | -const x = 'old'; | |
| 252 | -======= | |
| 253 | -const x = 'new'; | |
| 254 | -+++++++ REPLACE`; | |
| 255 | - | |
| 256 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 257 | - | |
| 258 | - expect(blocks).toHaveLength(2); | |
| 259 | - expect(blocks[0].searchContent).toBe(`function old() { | |
| 260 | - return 1; | |
| 261 | -}`); | |
| 262 | - expect(blocks[0].replaceContent).toBe(`function new() { | |
| 263 | - return 2; | |
| 264 | -}`); | |
| 265 | - expect(blocks[1].searchContent).toBe(`const x = 'old';`); | |
| 266 | - expect(blocks[1].replaceContent).toBe(`const x = 'new';`); | |
| 267 | - }); | |
| 268 | - | |
| 269 | - it("should handle deletion blocks (empty replace content)", () => { | |
| 270 | - const content = `------- SEARCH | |
| 271 | -code to keep | |
| 272 | -======= | |
| 273 | -modified code | |
| 274 | -+++++++ REPLACE | |
| 275 | - | |
| 276 | -------- SEARCH | |
| 277 | -code to delete | |
| 278 | -======= | |
| 279 | -+++++++ REPLACE`; | |
| 280 | - | |
| 281 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 282 | - | |
| 283 | - expect(blocks).toHaveLength(2); | |
| 284 | - expect(blocks[0].searchContent).toBe("code to keep"); | |
| 285 | - expect(blocks[0].replaceContent).toBe("modified code"); | |
| 286 | - expect(blocks[1].searchContent).toBe("code to delete"); | |
| 287 | - expect(blocks[1].replaceContent).toBe(""); // Deletion | |
| 288 | - }); | |
| 289 | - | |
| 290 | - it("should handle insertion blocks (empty search content)", () => { | |
| 291 | - const content = `------- SEARCH | |
| 292 | -existing code | |
| 293 | -======= | |
| 294 | -modified existing code | |
| 295 | -+++++++ REPLACE | |
| 296 | - | |
| 297 | -------- SEARCH | |
| 298 | -======= | |
| 299 | -new code to insert | |
| 300 | -+++++++ REPLACE`; | |
| 301 | - | |
| 302 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 303 | - | |
| 304 | - expect(blocks).toHaveLength(2); | |
| 305 | - expect(blocks[0].searchContent).toBe("existing code"); | |
| 306 | - expect(blocks[0].replaceContent).toBe("modified existing code"); | |
| 307 | - expect(blocks[1].searchContent).toBe(""); // Insertion | |
| 308 | - expect(blocks[1].replaceContent).toBe("new code to insert"); | |
| 309 | - }); | |
| 310 | - | |
| 311 | - it("should skip incomplete blocks", () => { | |
| 312 | - const content = `------- SEARCH | |
| 313 | -incomplete block | |
| 314 | - | |
| 315 | -------- SEARCH | |
| 316 | -complete block | |
| 317 | -======= | |
| 318 | -replacement | |
| 319 | -+++++++ REPLACE`; | |
| 320 | - | |
| 321 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 322 | - | |
| 323 | - expect(blocks).toHaveLength(1); | |
| 324 | - expect(blocks[0].searchContent).toBe("complete block"); | |
| 325 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 326 | - }); | |
| 327 | - | |
| 328 | - it("should handle single block", () => { | |
| 329 | - const content = `------- SEARCH | |
| 330 | -single block | |
| 331 | -======= | |
| 332 | -replacement | |
| 333 | -+++++++ REPLACE`; | |
| 334 | - | |
| 335 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 336 | - | |
| 337 | - expect(blocks).toHaveLength(1); | |
| 338 | - expect(blocks[0].searchContent).toBe("single block"); | |
| 339 | - expect(blocks[0].replaceContent).toBe("replacement"); | |
| 340 | - }); | |
| 341 | - | |
| 342 | - it("should return empty array when no complete blocks found", () => { | |
| 343 | - const content = `------- SEARCH | |
| 344 | -incomplete | |
| 345 | -======= | |
| 346 | -missing replace marker`; | |
| 347 | - | |
| 348 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 349 | - | |
| 350 | - expect(blocks).toHaveLength(0); | |
| 351 | - }); | |
| 352 | - | |
| 353 | - it("should handle blocks with extra content between them", () => { | |
| 354 | - const content = `Some other content here | |
| 355 | - | |
| 356 | -------- SEARCH | |
| 357 | -block 1 | |
| 358 | -======= | |
| 359 | -replacement 1 | |
| 360 | -+++++++ REPLACE | |
| 361 | - | |
| 362 | -More content in between | |
| 363 | - | |
| 364 | -------- SEARCH | |
| 365 | -block 2 | |
| 366 | -======= | |
| 367 | -replacement 2 | |
| 368 | -+++++++ REPLACE | |
| 369 | - | |
| 370 | -Trailing content`; | |
| 371 | - | |
| 372 | - const blocks = parseAllSearchReplaceBlocks(content); | |
| 373 | - | |
| 374 | - expect(blocks).toHaveLength(2); | |
| 375 | - expect(blocks[0].searchContent).toBe("block 1"); | |
| 376 | - expect(blocks[0].replaceContent).toBe("replacement 1"); | |
| 377 | - expect(blocks[1].searchContent).toBe("block 2"); | |
| 378 | - expect(blocks[1].replaceContent).toBe("replacement 2"); | |
| 379 | - }); | |
| 380 | - | |
| 381 | - it("should throw error for malformed blocks", () => { | |
| 382 | - const content = `------- SEARCH | |
| 383 | -content | |
| 384 | -+++++++ REPLACE`; // Missing ======= | |
| 385 | - | |
| 386 | - expect(() => parseAllSearchReplaceBlocks(content)).toThrow( | |
| 387 | - "Found replace block end marker without matching replace start marker", | |
| 388 | - ); | |
| 389 | - }); | |
| 390 | -}); |
| @@ -1,147 +0,0 @@ | ||
| 1 | -// Search and replace block markers using flexible regex patterns | |
| 2 | -const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; | |
| 3 | -const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; | |
| 4 | -const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; | |
| 5 | - | |
| 6 | -export interface SearchReplaceBlockResult { | |
| 7 | - /** Whether a complete search/replace block has been parsed */ | |
| 8 | - isComplete: boolean; | |
| 9 | - /** The content to search for in the file */ | |
| 10 | - searchContent?: string; | |
| 11 | - /** The content to replace the search content with */ | |
| 12 | - replaceContent?: string; | |
| 13 | - /** Error message if parsing failed */ | |
| 14 | - error?: string; | |
| 15 | -} | |
| 16 | - | |
| 17 | -/** | |
| 18 | - * Parses a search and replace block from content. | |
| 19 | - * | |
| 20 | - * Expected format: | |
| 21 | - * ------- SEARCH | |
| 22 | - * [content to find] | |
| 23 | - * ======= | |
| 24 | - * [content to replace with] | |
| 25 | - * +++++++ REPLACE | |
| 26 | - * | |
| 27 | - * @param content - The content to parse | |
| 28 | - * @returns ParseResult with completion status and extracted content | |
| 29 | - */ | |
| 30 | -export function parseSearchReplaceBlock( | |
| 31 | - content: string, | |
| 32 | -): SearchReplaceBlockResult { | |
| 33 | - const lines = content.split("\n"); | |
| 34 | - | |
| 35 | - let currentSearchContent = ""; | |
| 36 | - let currentReplaceContent = ""; | |
| 37 | - let inSearch = false; | |
| 38 | - let inReplace = false; | |
| 39 | - | |
| 40 | - for (const line of lines) { | |
| 41 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 42 | - inSearch = true; | |
| 43 | - inReplace = false; | |
| 44 | - currentSearchContent = ""; | |
| 45 | - currentReplaceContent = ""; | |
| 46 | - continue; | |
| 47 | - } | |
| 48 | - | |
| 49 | - if (SEARCH_BLOCK_END_REGEX.test(line)) { | |
| 50 | - if (!inSearch) { | |
| 51 | - return { | |
| 52 | - isComplete: false, | |
| 53 | - error: "Found search block end marker without matching start marker", | |
| 54 | - }; | |
| 55 | - } | |
| 56 | - inSearch = false; | |
| 57 | - inReplace = true; | |
| 58 | - continue; | |
| 59 | - } | |
| 60 | - | |
| 61 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 62 | - if (!inReplace) { | |
| 63 | - return { | |
| 64 | - isComplete: false, | |
| 65 | - error: | |
| 66 | - "Found replace block end marker without matching replace start marker", | |
| 67 | - }; | |
| 68 | - } | |
| 69 | - | |
| 70 | - // Complete block found | |
| 71 | - return { | |
| 72 | - isComplete: true, | |
| 73 | - searchContent: currentSearchContent.trim(), | |
| 74 | - replaceContent: currentReplaceContent.trim(), | |
| 75 | - }; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Accumulate content | |
| 79 | - if (inSearch) { | |
| 80 | - currentSearchContent += line + "\n"; | |
| 81 | - } else if (inReplace) { | |
| 82 | - currentReplaceContent += line + "\n"; | |
| 83 | - } | |
| 84 | - } | |
| 85 | - | |
| 86 | - // Block is not yet complete | |
| 87 | - return { | |
| 88 | - isComplete: false, | |
| 89 | - searchContent: currentSearchContent.trim(), | |
| 90 | - replaceContent: currentReplaceContent.trim(), | |
| 91 | - }; | |
| 92 | -} | |
| 93 | - | |
| 94 | -/** | |
| 95 | - * Parses all complete search and replace blocks from content. | |
| 96 | - * | |
| 97 | - * @param content - The content containing multiple search/replace blocks | |
| 98 | - * @returns Array of complete search/replace blocks found | |
| 99 | - * @throws Error if any malformed blocks are encountered | |
| 100 | - */ | |
| 101 | -export function parseAllSearchReplaceBlocks( | |
| 102 | - content: string, | |
| 103 | -): SearchReplaceBlockResult[] { | |
| 104 | - const blocks: SearchReplaceBlockResult[] = []; | |
| 105 | - const lines = content.split("\n"); | |
| 106 | - | |
| 107 | - let currentBlockLines: string[] = []; | |
| 108 | - let inBlock = false; | |
| 109 | - | |
| 110 | - for (const line of lines) { | |
| 111 | - if (SEARCH_BLOCK_START_REGEX.test(line)) { | |
| 112 | - // Start of new block | |
| 113 | - if (inBlock && currentBlockLines.length > 0) { | |
| 114 | - // Process previous incomplete block if any | |
| 115 | - const blockContent = currentBlockLines.join("\n"); | |
| 116 | - const result = parseSearchReplaceBlock(blockContent); | |
| 117 | - if (result.isComplete) { | |
| 118 | - blocks.push(result); | |
| 119 | - } else if (result.error) { | |
| 120 | - // Fail fast on any parsing error | |
| 121 | - throw new Error(result.error); | |
| 122 | - } | |
| 123 | - // If incomplete but no error, it's just a partial block - continue processing | |
| 124 | - } | |
| 125 | - currentBlockLines = [line]; | |
| 126 | - inBlock = true; | |
| 127 | - } else if (inBlock) { | |
| 128 | - currentBlockLines.push(line); | |
| 129 | - | |
| 130 | - // Check if this line completes the current block | |
| 131 | - if (REPLACE_BLOCK_END_REGEX.test(line)) { | |
| 132 | - const blockContent = currentBlockLines.join("\n"); | |
| 133 | - const result = parseSearchReplaceBlock(blockContent); | |
| 134 | - if (result.isComplete) { | |
| 135 | - blocks.push(result); | |
| 136 | - } else if (result.error) { | |
| 137 | - // Fail fast on any parsing error | |
| 138 | - throw new Error(result.error); | |
| 139 | - } | |
| 140 | - currentBlockLines = []; | |
| 141 | - inBlock = false; | |
| 142 | - } | |
| 143 | - } | |
| 144 | - } | |
| 145 | - | |
| 146 | - return blocks; | |
| 147 | -} |
| @@ -0,0 +1,70 @@ | ||
| 1 | +import { EditOperation } from "../../tools/definitions/multiEdit"; | |
| 2 | +import { ContinueError, ContinueErrorReason } from "../../util/errors"; | |
| 3 | +import { findSearchMatches } from "./findSearchMatch"; | |
| 4 | + | |
| 5 | +export function executeFindAndReplace( | |
| 6 | + fileContent: string, | |
| 7 | + oldString: string, | |
| 8 | + newString: string, | |
| 9 | + replaceAll: boolean, | |
| 10 | + editIndex = 0, | |
| 11 | +): string { | |
| 12 | + const matches = findSearchMatches(fileContent, oldString); | |
| 13 | + | |
| 14 | + if (matches.length === 0) { | |
| 15 | + throw new ContinueError( | |
| 16 | + ContinueErrorReason.FindAndReplaceOldStringNotFound, | |
| 17 | + `Edit at index ${editIndex}: string not found in file: "${oldString}"`, | |
| 18 | + ); | |
| 19 | + } | |
| 20 | + | |
| 21 | + if (replaceAll) { | |
| 22 | + // Apply replacements in reverse order to maintain correct positions | |
| 23 | + let result = fileContent; | |
| 24 | + for (let i = matches.length - 1; i >= 0; i--) { | |
| 25 | + const match = matches[i]; | |
| 26 | + result = | |
| 27 | + result.substring(0, match.startIndex) + | |
| 28 | + newString + | |
| 29 | + result.substring(match.endIndex); | |
| 30 | + } | |
| 31 | + return result; | |
| 32 | + } else { | |
| 33 | + // For single replacement, check for multiple matches first | |
| 34 | + if (matches.length > 1) { | |
| 35 | + throw new ContinueError( | |
| 36 | + ContinueErrorReason.FindAndReplaceMultipleOccurrences, | |
| 37 | + `Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, | |
| 38 | + ); | |
| 39 | + } | |
| 40 | + | |
| 41 | + // Apply single replacement | |
| 42 | + const match = matches[0]; | |
| 43 | + return ( | |
| 44 | + fileContent.substring(0, match.startIndex) + | |
| 45 | + newString + | |
| 46 | + fileContent.substring(match.endIndex) | |
| 47 | + ); | |
| 48 | + } | |
| 49 | +} | |
| 50 | + | |
| 51 | +export function executeMultiFindAndReplace( | |
| 52 | + fileContent: string, | |
| 53 | + edits: EditOperation[], | |
| 54 | +): string { | |
| 55 | + let result = fileContent; | |
| 56 | + | |
| 57 | + // Apply edits in sequence | |
| 58 | + for (let editIndex = 0; editIndex < edits.length; editIndex++) { | |
| 59 | + const edit = edits[editIndex]; | |
| 60 | + result = executeFindAndReplace( | |
| 61 | + result, | |
| 62 | + edit.old_string, | |
| 63 | + edit.new_string, | |
| 64 | + edit.replace_all ?? false, | |
| 65 | + editIndex, | |
| 66 | + ); | |
| 67 | + } | |
| 68 | + | |
| 69 | + return result; | |
| 70 | +} |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | ILLM, |
| 5 | 5 | Prediction, |
| 6 | 6 | RuleWithSource, |
| 7 | + StreamDiffLinesPayload, | |
| 7 | 8 | ToolResultChatMessage, |
| 8 | 9 | UserChatMessage, |
| 9 | 10 | } from "../"; |
| @@ -20,6 +21,7 @@ | ||
| 20 | 21 | import { streamLines } from "../diff/util"; |
| 21 | 22 | import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; |
| 22 | 23 | import { gptEditPrompt } from "../llm/templates/edit"; |
| 24 | +import { defaultApplyPrompt } from "../llm/templates/edit/gpt"; | |
| 23 | 25 | import { findLast } from "../util/findLast"; |
| 24 | 26 | import { Telemetry } from "../util/posthog"; |
| 25 | 27 | import { recursiveStream } from "./recursiveStream"; |
| @@ -42,6 +44,20 @@ | ||
| 42 | 44 | }); |
| 43 | 45 | } |
| 44 | 46 | |
| 47 | +function constructApplyPrompt( | |
| 48 | + originalCode: string, | |
| 49 | + newCode: string, | |
| 50 | + llm: ILLM, | |
| 51 | +) { | |
| 52 | + const template = llm.promptTemplates?.apply ?? defaultApplyPrompt; | |
| 53 | + const rendered = llm.renderPromptTemplate(template, [], { | |
| 54 | + original_code: originalCode, | |
| 55 | + new_code: newCode, | |
| 56 | + }); | |
| 57 | + | |
| 58 | + return rendered; | |
| 59 | +} | |
| 60 | + | |
| 45 | 61 | export async function* addIndentation( |
| 46 | 62 | diffLineGenerator: AsyncGenerator<DiffLine>, |
| 47 | 63 | indentation: string, |
| @@ -58,27 +74,15 @@ | ||
| 58 | 74 | return !(model.includes("gpt") || model.includes("claude")); |
| 59 | 75 | } |
| 60 | 76 | |
| 61 | -export async function* streamDiffLines({ | |
| 62 | - prefix, | |
| 63 | - highlighted, | |
| 64 | - suffix, | |
| 65 | - llm, | |
| 66 | - abortController, | |
| 67 | - input, | |
| 68 | - language, | |
| 69 | - overridePrompt, | |
| 70 | - rulesToInclude, | |
| 71 | -}: { | |
| 72 | - prefix: string; | |
| 73 | - highlighted: string; | |
| 74 | - suffix: string; | |
| 75 | - llm: ILLM; | |
| 76 | - abortController: AbortController; | |
| 77 | - input: string; | |
| 78 | - language: string | undefined; | |
| 79 | - overridePrompt: ChatMessage[] | undefined; | |
| 80 | - rulesToInclude: RuleWithSource[] | undefined; | |
| 81 | -}): AsyncGenerator<DiffLine> { | |
| 77 | +export async function* streamDiffLines( | |
| 78 | + options: StreamDiffLinesPayload, | |
| 79 | + llm: ILLM, | |
| 80 | + abortController: AbortController, | |
| 81 | + overridePrompt: ChatMessage[] | undefined, | |
| 82 | + rulesToInclude: RuleWithSource[] | undefined, | |
| 83 | +): AsyncGenerator<DiffLine> { | |
| 84 | + const { type, prefix, highlighted, suffix, input, language } = options; | |
| 85 | + | |
| 82 | 86 | void Telemetry.capture( |
| 83 | 87 | "inlineEdit", |
| 84 | 88 | { |
| @@ -104,27 +108,30 @@ | ||
| 104 | 108 | // For apply can be overridden with simply apply prompt |
| 105 | 109 | let prompt = |
| 106 | 110 | overridePrompt ?? |
| 107 | - constructEditPrompt(prefix, highlighted, suffix, llm, input, language); | |
| 111 | + (type === "apply" | |
| 112 | + ? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm) | |
| 113 | + : constructEditPrompt(prefix, highlighted, suffix, llm, input, language)); | |
| 108 | 114 | |
| 109 | 115 | // Rules can be included with edit prompt |
| 110 | 116 | // If any rules are present this will result in using chat instead of legacy completion |
| 111 | - const systemMessage = rulesToInclude | |
| 112 | - ? getSystemMessageWithRules({ | |
| 113 | - availableRules: rulesToInclude, | |
| 114 | - userMessage: | |
| 115 | - typeof prompt === "string" | |
| 116 | - ? ({ | |
| 117 | - role: "user", | |
| 118 | - content: prompt, | |
| 119 | - } as UserChatMessage) | |
| 120 | - : (findLast( | |
| 121 | - prompt, | |
| 122 | - (msg) => msg.role === "user" || msg.role === "tool", | |
| 123 | - ) as UserChatMessage | ToolResultChatMessage | undefined), | |
| 124 | - baseSystemMessage: undefined, | |
| 125 | - contextItems: [], | |
| 126 | - }).systemMessage | |
| 127 | - : undefined; | |
| 117 | + const systemMessage = | |
| 118 | + rulesToInclude || llm.baseChatSystemMessage | |
| 119 | + ? getSystemMessageWithRules({ | |
| 120 | + availableRules: rulesToInclude ?? [], | |
| 121 | + userMessage: | |
| 122 | + typeof prompt === "string" | |
| 123 | + ? ({ | |
| 124 | + role: "user", | |
| 125 | + content: prompt, | |
| 126 | + } as UserChatMessage) | |
| 127 | + : (findLast( | |
| 128 | + prompt, | |
| 129 | + (msg) => msg.role === "user" || msg.role === "tool", | |
| 130 | + ) as UserChatMessage | ToolResultChatMessage | undefined), | |
| 131 | + baseSystemMessage: llm.baseChatSystemMessage, | |
| 132 | + contextItems: [], | |
| 133 | + }).systemMessage | |
| 134 | + : undefined; | |
| 128 | 135 | |
| 129 | 136 | if (systemMessage) { |
| 130 | 137 | if (typeof prompt === "string") { |
| @@ -158,7 +165,13 @@ | ||
| 158 | 165 | content: highlighted, |
| 159 | 166 | }; |
| 160 | 167 | |
| 161 | - const completion = recursiveStream(llm, abortController, prompt, prediction); | |
| 168 | + const completion = recursiveStream( | |
| 169 | + llm, | |
| 170 | + abortController, | |
| 171 | + type, | |
| 172 | + prompt, | |
| 173 | + prediction, | |
| 174 | + ); | |
| 162 | 175 | |
| 163 | 176 | let lines = streamLines(completion); |
| 164 | 177 |
| @@ -173,6 +173,11 @@ | ||
| 173 | 173 | } |
| 174 | 174 | |
| 175 | 175 | export type ContextProviderType = "normal" | "query" | "submenu"; |
| 176 | +export type ContextIndexingType = | |
| 177 | + | "chunk" | |
| 178 | + | "embeddings" | |
| 179 | + | "fullTextSearch" | |
| 180 | + | "codeSnippets"; | |
| 176 | 181 | |
| 177 | 182 | export interface ContextProviderDescription { |
| 178 | 183 | title: ContextProviderName; |
| @@ -180,7 +185,7 @@ | ||
| 180 | 185 | description: string; |
| 181 | 186 | renderInlineAs?: string; |
| 182 | 187 | type: ContextProviderType; |
| 183 | - dependsOnIndexing?: boolean; | |
| 188 | + dependsOnIndexing?: ContextIndexingType[]; | |
| 184 | 189 | } |
| 185 | 190 | |
| 186 | 191 | export type FetchFunction = (url: string | URL, init?: any) => Promise<any>; |
| @@ -267,7 +272,7 @@ | ||
| 267 | 272 | history: ChatHistoryItem[]; |
| 268 | 273 | } |
| 269 | 274 | |
| 270 | -export interface SessionMetadata { | |
| 275 | +export interface BaseSessionMetadata { | |
| 271 | 276 | sessionId: string; |
| 272 | 277 | title: string; |
| 273 | 278 | dateCreated: string; |
| @@ -305,11 +310,6 @@ | ||
| 305 | 310 | replacement: string; |
| 306 | 311 | } |
| 307 | 312 | |
| 308 | -export interface ContinueError { | |
| 309 | - title: string; | |
| 310 | - message: string; | |
| 311 | -} | |
| 312 | - | |
| 313 | 313 | export interface CompletionOptions extends BaseCompletionOptions { |
| 314 | 314 | model: string; |
| 315 | 315 | } |
| @@ -819,6 +819,8 @@ | ||
| 819 | 819 | |
| 820 | 820 | openUrl(url: string): Promise<void>; |
| 821 | 821 | |
| 822 | + getExternalUri?(uri: string): Promise<string>; | |
| 823 | + | |
| 822 | 824 | runCommand(command: string, options?: TerminalOptions): Promise<void>; |
| 823 | 825 | |
| 824 | 826 | saveFile(fileUri: string): Promise<void>; |
| @@ -1070,11 +1072,6 @@ | ||
| 1070 | 1072 | codeBaseIndexer?: CodebaseIndexer; |
| 1071 | 1073 | } |
| 1072 | 1074 | |
| 1073 | -export type ToolPolicy = | |
| 1074 | - | "allowedWithPermission" | |
| 1075 | - | "allowedWithoutPermission" | |
| 1076 | - | "disabled"; | |
| 1077 | - | |
| 1078 | 1075 | export interface Tool { |
| 1079 | 1076 | type: "function"; |
| 1080 | 1077 | function: { |
| @@ -1099,6 +1096,11 @@ | ||
| 1099 | 1096 | exampleArgs?: Array<[string, string | number]>; |
| 1100 | 1097 | }; |
| 1101 | 1098 | defaultToolPolicy?: ToolPolicy; |
| 1099 | + toolCallIcon?: string; | |
| 1100 | + evaluateToolCallPolicy?: ( | |
| 1101 | + basePolicy: ToolPolicy, | |
| 1102 | + parsedArgs: Record<string, unknown>, | |
| 1103 | + ) => ToolPolicy; | |
| 1102 | 1104 | } |
| 1103 | 1105 | |
| 1104 | 1106 | interface ToolChoice { |
| @@ -1277,6 +1279,7 @@ | ||
| 1277 | 1279 | transport: TransportOptions; |
| 1278 | 1280 | faviconUrl?: string; |
| 1279 | 1281 | timeout?: number; |
| 1282 | + requestOptions?: RequestOptions; | |
| 1280 | 1283 | } |
| 1281 | 1284 | |
| 1282 | 1285 | export type MCPConnectionStatus = |
| @@ -1329,6 +1332,7 @@ | ||
| 1329 | 1332 | export interface MCPServerStatus extends MCPOptions { |
| 1330 | 1333 | status: MCPConnectionStatus; |
| 1331 | 1334 | errors: string[]; |
| 1335 | + infos: string[]; | |
| 1332 | 1336 | isProtectedResource: boolean; |
| 1333 | 1337 | |
| 1334 | 1338 | prompts: MCPPrompt[]; |
| @@ -1383,9 +1387,12 @@ | ||
| 1383 | 1387 | fileContent?: string; |
| 1384 | 1388 | originalFileContent?: string; |
| 1385 | 1389 | toolCallId?: string; |
| 1390 | + autoFormattingDiff?: string; | |
| 1386 | 1391 | } |
| 1387 | 1392 | |
| 1388 | -export interface StreamDiffLinesPayload { | |
| 1393 | +export type StreamDiffLinesType = "edit" | "apply"; | |
| 1394 | +interface StreamDiffLinesOptionsBase { | |
| 1395 | + type: StreamDiffLinesType; | |
| 1389 | 1396 | prefix: string; |
| 1390 | 1397 | highlighted: string; |
| 1391 | 1398 | suffix: string; |
| @@ -1396,6 +1403,19 @@ | ||
| 1396 | 1403 | fileUri?: string; |
| 1397 | 1404 | } |
| 1398 | 1405 | |
| 1406 | +interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase { | |
| 1407 | + type: "edit"; | |
| 1408 | +} | |
| 1409 | + | |
| 1410 | +interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase { | |
| 1411 | + type: "apply"; | |
| 1412 | + newCode: string; | |
| 1413 | +} | |
| 1414 | + | |
| 1415 | +type StreamDiffLinesPayload = | |
| 1416 | + | StreamDiffLinesOptionsApply | |
| 1417 | + | StreamDiffLinesOptionsEdit; | |
| 1418 | + | |
| 1399 | 1419 | export interface HighlightedCodePayload { |
| 1400 | 1420 | rangeInFileWithContents: RangeInFileWithContents; |
| 1401 | 1421 | prompt?: string; |
| @@ -1803,6 +1823,7 @@ | ||
| 1803 | 1823 | description?: string; |
| 1804 | 1824 | ruleFile?: string; |
| 1805 | 1825 | alwaysApply?: boolean; |
| 1826 | + invokable?: boolean; | |
| 1806 | 1827 | } |
| 1807 | 1828 | export interface CompleteOnboardingPayload { |
| 1808 | 1829 | mode: OnboardingModes; |
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import { ContinueConfig } from "../index.js"; |
| 22 | 22 | import { localPathToUri } from "../util/pathToUri.js"; |
| 23 | 23 | import { CodebaseIndexer } from "./CodebaseIndexer.js"; |
| 24 | +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; | |
| 24 | 25 | import { getComputeDeleteAddRemove } from "./refreshIndex.js"; |
| 25 | 26 | import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; |
| 26 | 27 | import { CodebaseIndex } from "./types.js"; |
| @@ -675,5 +676,154 @@ | ||
| 675 | 676 | ]); |
| 676 | 677 | }); |
| 677 | 678 | }); |
| 679 | + | |
| 680 | + describe("getIndexesToBuild", () => { | |
| 681 | + let indexer: CodebaseIndexer; | |
| 682 | + let mockConfig: any; | |
| 683 | + let mockEmbeddingsModel: any; | |
| 684 | + let mockIdeSettings: any; | |
| 685 | + | |
| 686 | + beforeEach(async () => { | |
| 687 | + indexer = new CodebaseIndexer( | |
| 688 | + testConfigHandler, | |
| 689 | + testIde, | |
| 690 | + mockMessenger as any, | |
| 691 | + false, | |
| 692 | + ); | |
| 693 | + | |
| 694 | + mockEmbeddingsModel = { | |
| 695 | + maxEmbeddingChunkSize: 1000, | |
| 696 | + model: "test-model", | |
| 697 | + provider: "test-provider", | |
| 698 | + }; | |
| 699 | + | |
| 700 | + mockIdeSettings = { | |
| 701 | + remoteConfigServerUrl: "http://test.com", | |
| 702 | + userToken: "test-token", | |
| 703 | + }; | |
| 704 | + | |
| 705 | + mockConfig = { | |
| 706 | + selectedModelByRole: { | |
| 707 | + embed: mockEmbeddingsModel, | |
| 708 | + }, | |
| 709 | + contextProviders: [], | |
| 710 | + }; | |
| 711 | + | |
| 712 | + jest | |
| 713 | + .spyOn(testIde, "getIdeSettings") | |
| 714 | + .mockResolvedValue(mockIdeSettings); | |
| 715 | + }); | |
| 716 | + | |
| 717 | + afterEach(() => { | |
| 718 | + jest.clearAllMocks(); | |
| 719 | + }); | |
| 720 | + | |
| 721 | + test("should create specific indexTypes for the requested context providers", async () => { | |
| 722 | + mockConfig.contextProviders = [ | |
| 723 | + { | |
| 724 | + description: { | |
| 725 | + dependsOnIndexing: ["chunk", "codeSnippets"], | |
| 726 | + }, | |
| 727 | + }, | |
| 728 | + ]; | |
| 729 | + | |
| 730 | + jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({ | |
| 731 | + config: mockConfig, | |
| 732 | + errors: [], | |
| 733 | + configLoadInterrupted: false, | |
| 734 | + }); | |
| 735 | + | |
| 736 | + const indexes = (await ( | |
| 737 | + indexer as any | |
| 738 | + ).getIndexesToBuild()) as CodebaseIndex[]; | |
| 739 | + | |
| 740 | + expect(indexes).toHaveLength(2); | |
| 741 | + expect(indexes[0].artifactId).toBe("chunks"); | |
| 742 | + expect(indexes[1].artifactId).toBe("codeSnippets"); | |
| 743 | + }); | |
| 744 | + | |
| 745 | + test("should handle duplicate contexts", async () => { | |
| 746 | + mockConfig.contextProviders = [ | |
| 747 | + { | |
| 748 | + description: { | |
| 749 | + dependsOnIndexing: ["codeSnippets"], | |
| 750 | + }, | |
| 751 | + }, | |
| 752 | + { | |
| 753 | + description: { | |
| 754 | + dependsOnIndexing: ["codeSnippets"], | |
| 755 | + }, | |
| 756 | + }, | |
| 757 | + ]; | |
| 758 | + | |
| 759 | + jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({ | |
| 760 | + config: mockConfig, | |
| 761 | + errors: [], | |
| 762 | + configLoadInterrupted: false, | |
| 763 | + }); | |
| 764 | + | |
| 765 | + const indexes = await (indexer as any).getIndexesToBuild(); | |
| 766 | + | |
| 767 | + expect(indexes).toHaveLength(1); | |
| 768 | + expect(indexes[0].artifactId).toBe("codeSnippets"); | |
| 769 | + }); | |
| 770 | + }); | |
| 771 | + }); | |
| 772 | + | |
| 773 | + describe("wasAnyOneIndexAdded", () => { | |
| 774 | + let testIndexer: TestCodebaseIndexer; | |
| 775 | + let mockGetIndexesToBuild: jest.MockedFunction<any>; | |
| 776 | + | |
| 777 | + beforeEach(() => { | |
| 778 | + testIndexer = new TestCodebaseIndexer( | |
| 779 | + testConfigHandler, | |
| 780 | + testIde, | |
| 781 | + mockMessenger as any, | |
| 782 | + false, | |
| 783 | + ); | |
| 784 | + | |
| 785 | + // Mock getIndexesToBuild to control what indexes should be built | |
| 786 | + mockGetIndexesToBuild = jest | |
| 787 | + .spyOn(testIndexer as any, "getIndexesToBuild") | |
| 788 | + .mockResolvedValue([]); | |
| 789 | + | |
| 790 | + jest | |
| 791 | + .spyOn(testIndexer, "refreshCodebaseIndex") | |
| 792 | + .mockImplementation(async () => {}); | |
| 793 | + }); | |
| 794 | + | |
| 795 | + afterEach(() => { | |
| 796 | + jest.clearAllMocks(); | |
| 797 | + }); | |
| 798 | + | |
| 799 | + test("should return true when indexes to build differ from built indexes", async () => { | |
| 800 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 801 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 802 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1]); | |
| 803 | + (testIndexer as any).builtIndexes = [mockIndex2]; | |
| 804 | + | |
| 805 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 806 | + expect(result).toBe(true); | |
| 807 | + }); | |
| 808 | + | |
| 809 | + test("should return true when there are more indexes to build than built indexes", async () => { | |
| 810 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 811 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 812 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1, mockIndex2]); | |
| 813 | + (testIndexer as any).builtIndexes = [mockIndex1]; | |
| 814 | + | |
| 815 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 816 | + expect(result).toBe(true); | |
| 817 | + }); | |
| 818 | + | |
| 819 | + test("should return false when there are fewer indexes to build than built indexes", async () => { | |
| 820 | + const mockIndex1 = new TestCodebaseIndex(); | |
| 821 | + const mockIndex2 = new FullTextSearchCodebaseIndex(); | |
| 822 | + mockGetIndexesToBuild.mockResolvedValue([mockIndex1]); | |
| 823 | + (testIndexer as any).builtIndexes = [mockIndex1, mockIndex2]; | |
| 824 | + | |
| 825 | + const result = await testIndexer.wasAnyOneIndexAdded(); | |
| 826 | + expect(result).toBe(false); | |
| 827 | + }); | |
| 678 | 828 | }); |
| 679 | 829 | }); |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | 4 | import { |
| 5 | + ContextIndexingType, | |
| 5 | 6 | ContinueConfig, |
| 6 | 7 | IDE, |
| 7 | 8 | IndexingProgressUpdate, |
| @@ -58,6 +59,7 @@ | ||
| 58 | 59 | private indexingCancellationController: AbortController; |
| 59 | 60 | private codebaseIndexingState: IndexingProgressUpdate; |
| 60 | 61 | private readonly pauseToken: PauseToken; |
| 62 | + private builtIndexes: CodebaseIndex[] = []; | |
| 61 | 63 | |
| 62 | 64 | private getUserFriendlyIndexName(artifactId: string): string { |
| 63 | 65 | if (artifactId === FullTextSearchCodebaseIndex.artifactId) |
| @@ -166,28 +168,46 @@ | ||
| 166 | 168 | return []; |
| 167 | 169 | } |
| 168 | 170 | |
| 169 | - const indexes: CodebaseIndex[] = [ | |
| 170 | - new ChunkCodebaseIndex( | |
| 171 | - this.ide.readFile.bind(this.ide), | |
| 172 | - continueServerClient, | |
| 173 | - embeddingsModel.maxEmbeddingChunkSize, | |
| 174 | - ), // Chunking must come first | |
| 175 | - ]; | |
| 176 | - | |
| 177 | - const lanceDbIndex = await LanceDbIndex.create( | |
| 178 | - embeddingsModel, | |
| 179 | - this.ide.readFile.bind(this.ide), | |
| 171 | + const indexTypesToBuild = new Set( // use set to remove duplicates | |
| 172 | + config.contextProviders | |
| 173 | + .map((provider) => provider.description.dependsOnIndexing) | |
| 174 | + .filter((indexType) => Array.isArray(indexType)) // remove undefined indexTypes | |
| 175 | + .flat(), | |
| 180 | 176 | ); |
| 181 | 177 | |
| 182 | - if (lanceDbIndex) { | |
| 183 | - indexes.push(lanceDbIndex); | |
| 184 | - } | |
| 178 | + const indexTypeToIndexerMapping: Record< | |
| 179 | + ContextIndexingType, | |
| 180 | + () => Promise<CodebaseIndex | null> | |
| 181 | + > = { | |
| 182 | + chunk: async () => | |
| 183 | + new ChunkCodebaseIndex( | |
| 184 | + this.ide.readFile.bind(this.ide), | |
| 185 | + continueServerClient, | |
| 186 | + embeddingsModel.maxEmbeddingChunkSize, | |
| 187 | + ), | |
| 188 | + codeSnippets: async () => new CodeSnippetsCodebaseIndex(this.ide), | |
| 189 | + fullTextSearch: async () => new FullTextSearchCodebaseIndex(), | |
| 190 | + embeddings: async () => { | |
| 191 | + const lanceDbIndex = await LanceDbIndex.create( | |
| 192 | + embeddingsModel, | |
| 193 | + this.ide.readFile.bind(this.ide), | |
| 194 | + ); | |
| 195 | + return lanceDbIndex; | |
| 196 | + }, | |
| 197 | + }; | |
| 185 | 198 | |
| 186 | - indexes.push( | |
| 187 | - new FullTextSearchCodebaseIndex(), | |
| 188 | - new CodeSnippetsCodebaseIndex(this.ide), | |
| 189 | - ); | |
| 199 | + const indexes: CodebaseIndex[] = []; | |
| 200 | + // not parallelizing to avoid race conditions in sqlite | |
| 201 | + for (const indexType of indexTypesToBuild) { | |
| 202 | + if (indexType && indexType in indexTypeToIndexerMapping) { | |
| 203 | + const index = await indexTypeToIndexerMapping[indexType](); | |
| 204 | + if (index) { | |
| 205 | + indexes.push(index); | |
| 206 | + } | |
| 207 | + } | |
| 208 | + } | |
| 190 | 209 | |
| 210 | + this.builtIndexes = indexes; | |
| 191 | 211 | return indexes; |
| 192 | 212 | } |
| 193 | 213 | |
| @@ -694,6 +714,15 @@ | ||
| 694 | 714 | } |
| 695 | 715 | } |
| 696 | 716 | |
| 717 | + public async wasAnyOneIndexAdded() { | |
| 718 | + const indexes = await this.getIndexesToBuild(); | |
| 719 | + return !indexes.every((index) => | |
| 720 | + this.builtIndexes.some( | |
| 721 | + (builtIndex) => builtIndex.artifactId === index.artifactId, | |
| 722 | + ), | |
| 723 | + ); | |
| 724 | + } | |
| 725 | + | |
| 697 | 726 | public async refreshCodebaseIndex(paths: string[]) { |
| 698 | 727 | if (!this.indexingCancellationController.signal.aborted) { |
| 699 | 728 | this.indexingCancellationController.abort(); |
| @@ -272,7 +272,7 @@ | ||
| 272 | 272 | id: doc.startUrl, |
| 273 | 273 | isReindexing: false, |
| 274 | 274 | title: doc.title, |
| 275 | - debugInfo: `max depth: ${doc.maxDepth}`, | |
| 275 | + debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`, | |
| 276 | 276 | icon: doc.faviconUrl, |
| 277 | 277 | url: doc.startUrl, |
| 278 | 278 | }; |
| @@ -468,7 +468,7 @@ | ||
| 468 | 468 | embeddingsProviderId: provider.embeddingId, |
| 469 | 469 | isReindexing: forceReindex && indexExists, |
| 470 | 470 | title: siteIndexingConfig.title, |
| 471 | - debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, | |
| 471 | + debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`, | |
| 472 | 472 | icon: siteIndexingConfig.faviconUrl, |
| 473 | 473 | url: siteIndexingConfig.startUrl, |
| 474 | 474 | }; |
| @@ -155,9 +155,27 @@ | ||
| 155 | 155 | test( |
| 156 | 156 | `Default crawler common site: ${url}`, |
| 157 | 157 | async () => { |
| 158 | - const { pages, crawler } = await runCrawl(url); | |
| 159 | - expect(pages.length).toBeGreaterThanOrEqual(1); | |
| 160 | - expect(crawler).toEqual("default"); | |
| 158 | + // Retry logic to handle flaky network requests to TRIAL_PROXY_URL | |
| 159 | + let lastError; | |
| 160 | + const maxRetries = 3; | |
| 161 | + | |
| 162 | + for (let attempt = 1; attempt <= maxRetries; attempt++) { | |
| 163 | + try { | |
| 164 | + const { pages, crawler } = await runCrawl(url); | |
| 165 | + expect(pages.length).toBeGreaterThanOrEqual(1); | |
| 166 | + expect(crawler).toEqual("default"); | |
| 167 | + return; // Test passed, exit retry loop | |
| 168 | + } catch (error) { | |
| 169 | + lastError = error; | |
| 170 | + if (attempt === maxRetries) { | |
| 171 | + throw error; // Final attempt failed, throw the error | |
| 172 | + } | |
| 173 | + // Wait before retrying (exponential backoff) | |
| 174 | + await new Promise((resolve) => | |
| 175 | + setTimeout(resolve, 1000 * attempt), | |
| 176 | + ); | |
| 177 | + } | |
| 178 | + } | |
| 161 | 179 | }, |
| 162 | 180 | TIMEOUT_MS, |
| 163 | 181 | ); |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import path from "path"; |
| 4 | 4 | import { fileURLToPath } from "url"; |
| 5 | +import { ContinueError, ContinueErrorReason } from "../util/errors"; | |
| 5 | 6 | |
| 6 | 7 | // Security-focused ignore patterns - these should always be excluded for security reasons |
| 7 | 8 | export const DEFAULT_SECURITY_IGNORE_FILETYPES = [ |
| @@ -203,6 +204,13 @@ | ||
| 203 | 204 | ...ADDITIONAL_INDEXING_IGNORE_DIRS, |
| 204 | 205 | ]; |
| 205 | 206 | |
| 207 | +export const DEFAULT_IGNORES = [ | |
| 208 | + ...DEFAULT_IGNORE_FILETYPES, | |
| 209 | + ...DEFAULT_IGNORE_DIRS, | |
| 210 | +]; | |
| 211 | + | |
| 212 | +export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`; | |
| 213 | + | |
| 206 | 214 | // Create ignore instances |
| 207 | 215 | export const defaultSecurityIgnoreFile = ignore().add( |
| 208 | 216 | DEFAULT_SECURITY_IGNORE_FILETYPES, |
| @@ -252,7 +260,8 @@ | ||
| 252 | 260 | |
| 253 | 261 | export function throwIfFileIsSecurityConcern(filepath: string) { |
| 254 | 262 | if (isSecurityConcern(filepath)) { |
| 255 | - throw new Error( | |
| 263 | + throw new ContinueError( | |
| 264 | + ContinueErrorReason.FileIsSecurityConcern, | |
| 256 | 265 | `Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`, |
| 257 | 266 | ); |
| 258 | 267 | } |
| @@ -1,4 +1,9 @@ | ||
| 1 | -import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; | |
| 1 | +import { | |
| 2 | + ChatMessage, | |
| 3 | + ModelCapability, | |
| 4 | + ModelDescription, | |
| 5 | + TemplateType, | |
| 6 | +} from "../index.js"; | |
| 2 | 7 | import { NEXT_EDIT_MODELS } from "./constants.js"; |
| 3 | 8 | |
| 4 | 9 | import { |
| @@ -40,6 +45,7 @@ | ||
| 40 | 45 | |
| 41 | 46 | const PROVIDER_HANDLES_TEMPLATING: string[] = [ |
| 42 | 47 | "lmstudio", |
| 48 | + "lemonade", | |
| 43 | 49 | "openai", |
| 44 | 50 | "nvidia", |
| 45 | 51 | "ollama", |
| @@ -62,6 +68,7 @@ | ||
| 62 | 68 | const PROVIDER_SUPPORTS_IMAGES: string[] = [ |
| 63 | 69 | "openai", |
| 64 | 70 | "ollama", |
| 71 | + "lemonade", | |
| 65 | 72 | "cohere", |
| 66 | 73 | "gemini", |
| 67 | 74 | "msty", |
| @@ -80,26 +87,24 @@ | ||
| 80 | 87 | "watsonx", |
| 81 | 88 | ]; |
| 82 | 89 | |
| 83 | -const MODEL_SUPPORTS_IMAGES: string[] = [ | |
| 84 | - "llava", | |
| 85 | - "gpt-4-turbo", | |
| 86 | - "gpt-4o", | |
| 87 | - "gpt-4o-mini", | |
| 88 | - "gpt-4-vision", | |
| 89 | - "claude-3", | |
| 90 | - "c4ai-aya-vision-8b", | |
| 91 | - "c4ai-aya-vision-32b", | |
| 92 | - "gemini-ultra", | |
| 93 | - "gemini-1.5-pro", | |
| 94 | - "gemini-1.5-flash", | |
| 95 | - "sonnet", | |
| 96 | - "opus", | |
| 97 | - "haiku", | |
| 98 | - "pixtral", | |
| 99 | - "llama3.2", | |
| 100 | - "llama-3.2", | |
| 101 | - "llama4", | |
| 102 | - "granite-vision", | |
| 90 | +const MODEL_SUPPORTS_IMAGES: RegExp[] = [ | |
| 91 | + /llava/, | |
| 92 | + /gpt-4-turbo/, | |
| 93 | + /gpt-4o/, | |
| 94 | + /gpt-4o-mini/, | |
| 95 | + /claude-3/, | |
| 96 | + /gemini-ultra/, | |
| 97 | + /gemini-1\.5-pro/, | |
| 98 | + /gemini-1\.5-flash/, | |
| 99 | + /sonnet/, | |
| 100 | + /opus/, | |
| 101 | + /haiku/, | |
| 102 | + /pixtral/, | |
| 103 | + /llama-?3\.2/, | |
| 104 | + /llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed | |
| 105 | + /\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't! | |
| 106 | + /\b(pali|med)gemma/, | |
| 107 | + /qwen(.*)vl/, | |
| 103 | 108 | ]; |
| 104 | 109 | |
| 105 | 110 | function modelSupportsImages( |
| @@ -115,10 +120,14 @@ | ||
| 115 | 120 | return false; |
| 116 | 121 | } |
| 117 | 122 | |
| 118 | - const lower = model.toLowerCase(); | |
| 123 | + const lowerModel = model.toLowerCase(); | |
| 124 | + const lowerTitle = title?.toLowerCase() ?? ""; | |
| 125 | + | |
| 119 | 126 | if ( |
| 127 | + lowerModel.includes("vision") || | |
| 128 | + lowerTitle.includes("vision") || | |
| 120 | 129 | MODEL_SUPPORTS_IMAGES.some( |
| 121 | - (modelName) => lower.includes(modelName) || title?.includes(modelName), | |
| 130 | + (modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle), | |
| 122 | 131 | ) |
| 123 | 132 | ) { |
| 124 | 133 | return true; |
| @@ -126,6 +135,26 @@ | ||
| 126 | 135 | |
| 127 | 136 | return false; |
| 128 | 137 | } |
| 138 | + | |
| 139 | +function modelSupportsReasoning( | |
| 140 | + model: ModelDescription | null | undefined, | |
| 141 | +): boolean { | |
| 142 | + if (!model) { | |
| 143 | + return false; | |
| 144 | + } | |
| 145 | + if ("anthropic" === model.underlyingProviderName) { | |
| 146 | + return true; | |
| 147 | + } | |
| 148 | + if (model.model.includes("deepseek-r")) { | |
| 149 | + return true; | |
| 150 | + } | |
| 151 | + if (model.completionOptions?.reasoning) { | |
| 152 | + // Reasoning support is forced at the config level. Model might not necessarily support it though! | |
| 153 | + return true; | |
| 154 | + } | |
| 155 | + return false; | |
| 156 | +} | |
| 157 | + | |
| 129 | 158 | const PARALLEL_PROVIDERS: string[] = [ |
| 130 | 159 | "anthropic", |
| 131 | 160 | "bedrock", |
| @@ -421,4 +450,5 @@ | ||
| 421 | 450 | llmCanGenerateInParallel, |
| 422 | 451 | modelSupportsImages, |
| 423 | 452 | modelSupportsNextEdit, |
| 453 | + modelSupportsReasoning, | |
| 424 | 454 | }; |
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | |
| 86 | 86 | function countImageTokens(content: MessagePart): number { |
| 87 | 87 | if (content.type === "imageUrl") { |
| 88 | - return 85; | |
| 88 | + return 1024; | |
| 89 | 89 | } |
| 90 | 90 | throw new Error("Non-image content type"); |
| 91 | 91 | } |
| @@ -95,10 +95,31 @@ | ||
| 95 | 95 | test("should return true when modelSupportsImages returns true", () => { |
| 96 | 96 | baseLLM.model = "gpt-4-vision"; |
| 97 | 97 | expect(baseLLM.supportsImages()).toBe(true); |
| 98 | + | |
| 99 | + baseLLM.model = "fancy-vision-model"; | |
| 100 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 101 | + | |
| 102 | + baseLLM.model = "gemma3:4b"; | |
| 103 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 104 | + | |
| 105 | + baseLLM.model = "google/gemma-3-270m"; | |
| 106 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 107 | + | |
| 108 | + baseLLM.model = "foo/paligemma-custom-100"; | |
| 109 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 110 | + | |
| 111 | + baseLLM.model = "foo/medgemma_4b_it_16Q"; | |
| 112 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 113 | + | |
| 114 | + baseLLM.model = "qwen2.5vl"; | |
| 115 | + expect(baseLLM.supportsImages()).toBe(true); | |
| 98 | 116 | }); |
| 99 | 117 | |
| 100 | 118 | test("should return false when modelSupportsImages returns false", () => { |
| 101 | 119 | expect(baseLLM.supportsImages()).toBe(false); |
| 120 | + | |
| 121 | + baseLLM.model = "gemma3n"; | |
| 122 | + expect(baseLLM.supportsImages()).toBe(false); | |
| 102 | 123 | }); |
| 103 | 124 | }); |
| 104 | 125 |
| @@ -30,6 +30,7 @@ | ||
| 30 | 30 | TemplateType, |
| 31 | 31 | Usage, |
| 32 | 32 | } from "../index.js"; |
| 33 | +import { isLemonadeInstalled } from "../util/lemonadeHelper.js"; | |
| 33 | 34 | import { Logger } from "../util/Logger.js"; |
| 34 | 35 | import mergeJson from "../util/merge.js"; |
| 35 | 36 | import { renderChatMessage } from "../util/messageContent.js"; |
| @@ -370,8 +371,17 @@ | ||
| 370 | 371 | }, |
| 371 | 372 | }); |
| 372 | 373 | |
| 373 | - if (error !== undefined) { | |
| 374 | - if (error === "cancel" || error.name === "AbortError") { | |
| 374 | + if (typeof error === "undefined") { | |
| 375 | + interaction?.logItem({ | |
| 376 | + kind: "success", | |
| 377 | + promptTokens, | |
| 378 | + generatedTokens, | |
| 379 | + thinkingTokens, | |
| 380 | + usage, | |
| 381 | + }); | |
| 382 | + return "success"; | |
| 383 | + } else { | |
| 384 | + if (error === "cancel" || error?.name?.includes("AbortError")) { | |
| 375 | 385 | interaction?.logItem({ |
| 376 | 386 | kind: "cancel", |
| 377 | 387 | promptTokens, |
| @@ -393,15 +403,6 @@ | ||
| 393 | 403 | }); |
| 394 | 404 | return "error"; |
| 395 | 405 | } |
| 396 | - } else { | |
| 397 | - interaction?.logItem({ | |
| 398 | - kind: "success", | |
| 399 | - promptTokens, | |
| 400 | - generatedTokens, | |
| 401 | - thinkingTokens, | |
| 402 | - usage, | |
| 403 | - }); | |
| 404 | - return "success"; | |
| 405 | 406 | } |
| 406 | 407 | } |
| 407 | 408 | |
| @@ -503,6 +504,24 @@ | ||
| 503 | 504 | : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running."; |
| 504 | 505 | throw new Error(message); |
| 505 | 506 | } |
| 507 | + if ( | |
| 508 | + e.code === "ECONNREFUSED" && | |
| 509 | + e.message.includes("http://localhost:8000") | |
| 510 | + ) { | |
| 511 | + const isInstalled = await isLemonadeInstalled(); | |
| 512 | + let message: string; | |
| 513 | + if (process.platform === "linux") { | |
| 514 | + // On Linux, isLemonadeInstalled checks if it's running (via health endpoint) | |
| 515 | + message = | |
| 516 | + "Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions."; | |
| 517 | + } else { | |
| 518 | + // On Windows, we can check if it's installed | |
| 519 | + message = isInstalled | |
| 520 | + ? "Unable to connect to local Lemonade instance. Lemonade server may not be running." | |
| 521 | + : "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running."; | |
| 522 | + } | |
| 523 | + throw new Error(message); | |
| 524 | + } | |
| 506 | 525 | } |
| 507 | 526 | throw e; |
| 508 | 527 | } |
| @@ -537,18 +556,14 @@ | ||
| 537 | 556 | } |
| 538 | 557 | |
| 539 | 558 | private _formatChatMessage(msg: ChatMessage): string { |
| 540 | - let contentToShow = ""; | |
| 541 | - if (msg.role === "tool") { | |
| 542 | - contentToShow = msg.content; | |
| 543 | - } else if (msg.role === "assistant" && msg.toolCalls?.length) { | |
| 544 | - contentToShow = msg.toolCalls | |
| 559 | + let contentToShow = renderChatMessage(msg); | |
| 560 | + if (msg.role === "assistant" && msg.toolCalls?.length) { | |
| 561 | + contentToShow += msg.toolCalls | |
| 545 | 562 | ?.map( |
| 546 | 563 | (toolCall) => |
| 547 | 564 | `${toolCall.function?.name}(${toolCall.function?.arguments})`, |
| 548 | 565 | ) |
| 549 | 566 | .join("\n"); |
| 550 | - } else if ("content" in msg) { | |
| 551 | - contentToShow = renderChatMessage(msg); | |
| 552 | 567 | } |
| 553 | 568 | |
| 554 | 569 | return `<${msg.role}>\n${contentToShow}\n\n`; |
| @@ -615,6 +630,7 @@ | ||
| 615 | 630 | kind: "chunk", |
| 616 | 631 | chunk: formattedContent, |
| 617 | 632 | }); |
| 633 | + | |
| 618 | 634 | completion += formattedContent; |
| 619 | 635 | yield content; |
| 620 | 636 | } |
| @@ -630,6 +646,7 @@ | ||
| 630 | 646 | kind: "chunk", |
| 631 | 647 | chunk, |
| 632 | 648 | }); |
| 649 | + | |
| 633 | 650 | completion += chunk; |
| 634 | 651 | yield chunk; |
| 635 | 652 | } |
| @@ -1039,6 +1056,10 @@ | ||
| 1039 | 1056 | const msg = fromChatResponse(response); |
| 1040 | 1057 | yield msg; |
| 1041 | 1058 | completion = this._formatChatMessage(msg); |
| 1059 | + interaction?.logItem({ | |
| 1060 | + kind: "message", | |
| 1061 | + message: msg, | |
| 1062 | + }); | |
| 1042 | 1063 | } else { |
| 1043 | 1064 | // Stream true |
| 1044 | 1065 | const stream = this.openaiAdapter.chatCompletionStream( |
| @@ -68,6 +68,17 @@ | ||
| 68 | 68 | return finalOptions; |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | + private buildTextPart(text: string, addCaching: boolean) { | |
| 72 | + const part: any = { | |
| 73 | + type: "text", | |
| 74 | + text, | |
| 75 | + }; | |
| 76 | + if (addCaching) { | |
| 77 | + part.cache_control = { type: "ephemeral" }; | |
| 78 | + } | |
| 79 | + return part; | |
| 80 | + } | |
| 81 | + | |
| 71 | 82 | private convertMessage(message: ChatMessage, addCaching: boolean): any { |
| 72 | 83 | if (message.role === "tool") { |
| 73 | 84 | return { |
| @@ -81,14 +92,30 @@ | ||
| 81 | 92 | ], |
| 82 | 93 | }; |
| 83 | 94 | } else if (message.role === "assistant" && message.toolCalls) { |
| 84 | - return { | |
| 85 | - role: "assistant", | |
| 86 | - content: message.toolCalls.map((toolCall) => ({ | |
| 95 | + const parts: any[] = []; | |
| 96 | + if (message.content) { | |
| 97 | + if (typeof message.content === "string") { | |
| 98 | + parts.push(this.buildTextPart(message.content, addCaching)); | |
| 99 | + } else if (message.content.length > 0) { | |
| 100 | + const textContent = message.content.filter((p) => p.type === "text"); | |
| 101 | + const textParts = textContent.map((part, idx) => { | |
| 102 | + const cache = idx === textContent.length - 1 && addCaching; | |
| 103 | + return this.buildTextPart(part.text, cache); | |
| 104 | + }); | |
| 105 | + parts.push(...textParts); | |
| 106 | + } | |
| 107 | + } | |
| 108 | + parts.push( | |
| 109 | + ...message.toolCalls.map((toolCall) => ({ | |
| 87 | 110 | type: "tool_use", |
| 88 | 111 | id: toolCall.id, |
| 89 | 112 | name: toolCall.function?.name, |
| 90 | 113 | input: safeParseToolCallArgs(toolCall), |
| 91 | 114 | })), |
| 115 | + ); | |
| 116 | + return { | |
| 117 | + role: "assistant", | |
| 118 | + content: parts, | |
| 92 | 119 | }; |
| 93 | 120 | } else if (message.role === "thinking" && !message.redactedThinking) { |
| 94 | 121 | return { |
| @@ -154,9 +181,7 @@ | ||
| 154 | 181 | |
| 155 | 182 | public convertMessages(msgs: ChatMessage[]): any[] { |
| 156 | 183 | // should be public for use within VertexAI |
| 157 | - const filteredmessages = msgs.filter( | |
| 158 | - (m) => m.role !== "system" && !!m.content, | |
| 159 | - ); | |
| 184 | + const filteredmessages = msgs.filter((m) => m.role !== "system"); | |
| 160 | 185 | const lastTwoUserMsgIndices = filteredmessages |
| 161 | 186 | .map((msg, index) => (msg.role === "user" ? index : -1)) |
| 162 | 187 | .filter((index) => index !== -1) |
| @@ -532,7 +532,7 @@ | ||
| 532 | 532 | ); |
| 533 | 533 | }); |
| 534 | 534 | |
| 535 | - it("should add cache points for prompt caching when needed", () => { | |
| 535 | + it("should add cache points when cacheBehavior.cacheConversation is enabled", () => { | |
| 536 | 536 | // Create a test instance with caching behavior enabled |
| 537 | 537 | const bedrockWithCaching = new TestBedrock({ |
| 538 | 538 | apiKey: "test-key", |
| @@ -576,5 +576,95 @@ | ||
| 576 | 576 | const userMessageText = converted[0].content?.[0].text; |
| 577 | 577 | expect(userMessageText).toMatch(/First message.+/); |
| 578 | 578 | }); |
| 579 | + | |
| 580 | + it("should add cache points when completionOptions.promptCaching is enabled", () => { | |
| 581 | + // Create a test instance with prompt caching enabled via completionOptions | |
| 582 | + const bedrockWithPromptCaching = new TestBedrock({ | |
| 583 | + apiKey: "test-key", | |
| 584 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 585 | + region: "us-east-1", | |
| 586 | + }); | |
| 587 | + | |
| 588 | + // Set completionOptions.promptCaching (without cacheBehavior) | |
| 589 | + bedrockWithPromptCaching.completionOptions = { | |
| 590 | + ...bedrockWithPromptCaching.completionOptions, | |
| 591 | + promptCaching: true, | |
| 592 | + }; | |
| 593 | + | |
| 594 | + const messages: ChatMessage[] = [ | |
| 595 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 596 | + { role: "assistant", content: "First response" }, | |
| 597 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 598 | + ]; | |
| 599 | + | |
| 600 | + const availableTools = new Set<string>(); | |
| 601 | + const converted = bedrockWithPromptCaching["_convertMessages"]( | |
| 602 | + messages, | |
| 603 | + availableTools, | |
| 604 | + ); | |
| 605 | + | |
| 606 | + // The last two user messages should have cache points | |
| 607 | + expect(converted.length).toBe(3); | |
| 608 | + expect(converted[0].role).toBe("user"); | |
| 609 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 610 | + true, | |
| 611 | + ); | |
| 612 | + expect(converted[1].role).toBe("assistant"); | |
| 613 | + expect(converted[2].role).toBe("user"); | |
| 614 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 615 | + true, | |
| 616 | + ); | |
| 617 | + | |
| 618 | + // Verify that text content includes a cache ID suffix | |
| 619 | + const userMessageText = converted[0].content?.[0].text; | |
| 620 | + expect(userMessageText).toMatch(/First message.+/); | |
| 621 | + }); | |
| 622 | + | |
| 623 | + it("should not add cache points when both caching options are disabled", () => { | |
| 624 | + // Create a test instance with no caching enabled | |
| 625 | + const bedrockNoCaching = new TestBedrock({ | |
| 626 | + apiKey: "test-key", | |
| 627 | + model: "anthropic.claude-3-sonnet-20240229-v1:0", | |
| 628 | + region: "us-east-1", | |
| 629 | + }); | |
| 630 | + | |
| 631 | + // Explicitly set no caching | |
| 632 | + bedrockNoCaching.cacheBehavior = { | |
| 633 | + cacheConversation: false, | |
| 634 | + cacheSystemMessage: false, | |
| 635 | + }; | |
| 636 | + bedrockNoCaching.completionOptions = { | |
| 637 | + ...bedrockNoCaching.completionOptions, | |
| 638 | + promptCaching: false, | |
| 639 | + }; | |
| 640 | + | |
| 641 | + const messages: ChatMessage[] = [ | |
| 642 | + { role: "user", content: "First message" } as UserChatMessage, | |
| 643 | + { role: "assistant", content: "First response" }, | |
| 644 | + { role: "user", content: "Second message" } as UserChatMessage, | |
| 645 | + ]; | |
| 646 | + | |
| 647 | + const availableTools = new Set<string>(); | |
| 648 | + const converted = bedrockNoCaching["_convertMessages"]( | |
| 649 | + messages, | |
| 650 | + availableTools, | |
| 651 | + ); | |
| 652 | + | |
| 653 | + // No cache points should be added | |
| 654 | + expect(converted.length).toBe(3); | |
| 655 | + expect(converted[0].role).toBe("user"); | |
| 656 | + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( | |
| 657 | + false, | |
| 658 | + ); | |
| 659 | + expect(converted[1].role).toBe("assistant"); | |
| 660 | + expect(converted[2].role).toBe("user"); | |
| 661 | + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( | |
| 662 | + false, | |
| 663 | + ); | |
| 664 | + | |
| 665 | + // Verify that text content doesn't include a cache ID suffix | |
| 666 | + const userMessageText = converted[0].content?.[0].text; | |
| 667 | + expect(userMessageText).toBe("First message"); | |
| 668 | + }); | |
| 579 | 669 | }); |
| 580 | 670 | }); |
| @@ -1,13 +1,19 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | BedrockRuntimeClient, |
| 3 | 3 | ContentBlock, |
| 4 | + ContentBlockDelta, | |
| 5 | + ContentBlockStart, | |
| 6 | + ContentBlockStartEvent, | |
| 4 | 7 | ConversationRole, |
| 5 | 8 | ConverseStreamCommand, |
| 6 | 9 | ConverseStreamCommandOutput, |
| 7 | 10 | ImageFormat, |
| 8 | 11 | InvokeModelCommand, |
| 9 | 12 | Message, |
| 13 | + ReasoningContentBlockDelta, | |
| 10 | 14 | ToolConfiguration, |
| 15 | + ToolUseBlock, | |
| 16 | + ToolUseBlockDelta, | |
| 11 | 17 | } from "@aws-sdk/client-bedrock-runtime"; |
| 12 | 18 | import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; |
| 13 | 19 | |
| @@ -25,15 +31,6 @@ | ||
| 25 | 31 | extractEmbeddings: (responseBody: any) => number[][]; |
| 26 | 32 | } |
| 27 | 33 | |
| 28 | -/** | |
| 29 | - * Interface for tool use state tracking | |
| 30 | - */ | |
| 31 | -interface ToolUseState { | |
| 32 | - toolUseId: string; | |
| 33 | - name: string; | |
| 34 | - input: string; | |
| 35 | -} | |
| 36 | - | |
| 37 | 34 | /** |
| 38 | 35 | * Interface for prompt caching metrics |
| 39 | 36 | */ |
| @@ -50,7 +47,6 @@ | ||
| 50 | 47 | profile: "bedrock", |
| 51 | 48 | }; |
| 52 | 49 | |
| 53 | - private _currentToolResponse: Partial<ToolUseState> | null = null; | |
| 54 | 50 | private _promptCachingMetrics: PromptCachingMetrics = { |
| 55 | 51 | cacheReadInputTokens: 0, |
| 56 | 52 | cacheWriteInputTokens: 0, |
| @@ -149,108 +145,99 @@ | ||
| 149 | 145 | console.log(`${JSON.stringify(chunk.metadata.usage)}`); |
| 150 | 146 | } |
| 151 | 147 | |
| 152 | - if (chunk.contentBlockDelta?.delta) { | |
| 153 | - const delta: any = chunk.contentBlockDelta.delta; | |
| 154 | - | |
| 148 | + const contentBlockDelta: ContentBlockDelta | undefined = | |
| 149 | + chunk.contentBlockDelta?.delta; | |
| 150 | + if (contentBlockDelta) { | |
| 155 | 151 | // Handle text content |
| 156 | - if (chunk.contentBlockDelta.delta.text) { | |
| 152 | + if (contentBlockDelta.text) { | |
| 157 | 153 | yield { |
| 158 | 154 | role: "assistant", |
| 159 | - content: chunk.contentBlockDelta.delta.text, | |
| 160 | - }; | |
| 161 | - continue; | |
| 162 | - } | |
| 163 | - | |
| 164 | - // Handle text content | |
| 165 | - if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { | |
| 166 | - yield { | |
| 167 | - role: "thinking", | |
| 168 | - content: (chunk.contentBlockDelta.delta as any).reasoningContent | |
| 169 | - .text, | |
| 155 | + content: contentBlockDelta.text, | |
| 170 | 156 | }; |
| 171 | 157 | continue; |
| 172 | 158 | } |
| 173 | - | |
| 174 | - // Handle signature for thinking | |
| 175 | - if (delta.reasoningContent?.signature) { | |
| 159 | + if (contentBlockDelta.reasoningContent?.text) { | |
| 176 | 160 | yield { |
| 177 | 161 | role: "thinking", |
| 178 | - content: "", | |
| 179 | - signature: delta.reasoningContent.signature, | |
| 162 | + content: contentBlockDelta.reasoningContent.text, | |
| 180 | 163 | }; |
| 181 | 164 | continue; |
| 182 | 165 | } |
| 183 | - | |
| 184 | - // Handle redacted thinking | |
| 185 | - if (delta.redactedReasoning?.data) { | |
| 166 | + if (contentBlockDelta.reasoningContent?.signature) { | |
| 186 | 167 | yield { |
| 187 | 168 | role: "thinking", |
| 188 | 169 | content: "", |
| 189 | - redactedThinking: delta.redactedReasoning.data, | |
| 170 | + signature: contentBlockDelta.reasoningContent.signature, | |
| 190 | 171 | }; |
| 191 | 172 | continue; |
| 192 | 173 | } |
| 193 | - | |
| 194 | - if ( | |
| 195 | - chunk.contentBlockDelta.delta.toolUse?.input && | |
| 196 | - this._currentToolResponse | |
| 197 | - ) { | |
| 198 | - // Append the new input to the existing string | |
| 199 | - if (this._currentToolResponse.input === undefined) { | |
| 200 | - this._currentToolResponse.input = ""; | |
| 201 | - } | |
| 202 | - this._currentToolResponse.input += | |
| 203 | - chunk.contentBlockDelta.delta.toolUse.input; | |
| 204 | - continue; | |
| 205 | - } | |
| 206 | 174 | } |
| 207 | 175 | |
| 208 | - if (chunk.contentBlockStart?.start) { | |
| 209 | - const start: any = chunk.contentBlockStart.start; | |
| 210 | - if (start.redactedReasoning) { | |
| 176 | + const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk | |
| 177 | + .contentBlockDelta?.delta as ReasoningContentBlockDelta; | |
| 178 | + if (reasoningDelta) { | |
| 179 | + if (reasoningDelta.redactedContent) { | |
| 211 | 180 | yield { |
| 212 | 181 | role: "thinking", |
| 213 | 182 | content: "", |
| 214 | - redactedThinking: start.redactedReasoning.data, | |
| 183 | + redactedThinking: reasoningDelta.text, | |
| 215 | 184 | }; |
| 216 | 185 | continue; |
| 217 | 186 | } |
| 187 | + } | |
| 218 | 188 | |
| 219 | - const toolUse = chunk.contentBlockStart.start.toolUse; | |
| 220 | - if (toolUse?.toolUseId && toolUse?.name) { | |
| 221 | - this._currentToolResponse = { | |
| 222 | - toolUseId: toolUse.toolUseId, | |
| 223 | - name: toolUse.name, | |
| 224 | - input: "", | |
| 225 | - }; | |
| 226 | - } | |
| 189 | + const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk | |
| 190 | + .contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta; | |
| 191 | + const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta | |
| 192 | + ?.delta?.toolUse as ToolUseBlock; | |
| 193 | + if (toolUseBlockDelta && toolUseBlock) { | |
| 194 | + yield { | |
| 195 | + role: "assistant", | |
| 196 | + content: "", | |
| 197 | + toolCalls: [ | |
| 198 | + { | |
| 199 | + id: toolUseBlock.toolUseId, | |
| 200 | + type: "function", | |
| 201 | + function: { | |
| 202 | + name: toolUseBlock.name, | |
| 203 | + arguments: toolUseBlockDelta.input, | |
| 204 | + }, | |
| 205 | + }, | |
| 206 | + ], | |
| 207 | + }; | |
| 227 | 208 | continue; |
| 228 | 209 | } |
| 229 | 210 | |
| 230 | - if (chunk.contentBlockStop) { | |
| 231 | - if (this._currentToolResponse) { | |
| 232 | - yield { | |
| 233 | - role: "assistant", | |
| 234 | - content: "", | |
| 235 | - toolCalls: [ | |
| 236 | - { | |
| 237 | - id: this._currentToolResponse.toolUseId, | |
| 238 | - type: "function", | |
| 239 | - function: { | |
| 240 | - name: this._currentToolResponse.name, | |
| 241 | - arguments: this._currentToolResponse.input, | |
| 211 | + const contentBlockStart: ContentBlockStartEvent | undefined = | |
| 212 | + chunk.contentBlockStart as ContentBlockStartEvent; | |
| 213 | + if (contentBlockStart) { | |
| 214 | + const start: ContentBlockStart | undefined = chunk.contentBlockStart | |
| 215 | + ?.start as ContentBlockStart; | |
| 216 | + if (start) { | |
| 217 | + const toolUseBlock: ToolUseBlock | undefined = | |
| 218 | + start.toolUse as ToolUseBlock; | |
| 219 | + if (toolUseBlock?.toolUseId && toolUseBlock?.name) { | |
| 220 | + yield { | |
| 221 | + role: "assistant", | |
| 222 | + content: "", | |
| 223 | + toolCalls: [ | |
| 224 | + { | |
| 225 | + id: toolUseBlock.toolUseId, | |
| 226 | + type: "function", | |
| 227 | + function: { | |
| 228 | + name: toolUseBlock.name, | |
| 229 | + arguments: "", | |
| 230 | + }, | |
| 242 | 231 | }, |
| 243 | - }, | |
| 244 | - ], | |
| 245 | - }; | |
| 246 | - this._currentToolResponse = null; | |
| 232 | + ], | |
| 233 | + }; | |
| 234 | + continue; | |
| 235 | + } | |
| 247 | 236 | } |
| 248 | - continue; | |
| 249 | 237 | } |
| 250 | 238 | } |
| 251 | 239 | } catch (error: unknown) { |
| 252 | 240 | // Clean up state and let the original error bubble up to the retry decorator |
| 253 | - this._currentToolResponse = null; | |
| 254 | 241 | throw error; |
| 255 | 242 | } |
| 256 | 243 | } |
| @@ -348,6 +335,9 @@ | ||
| 348 | 335 | budget_tokens: options.reasoningBudgetTokens, |
| 349 | 336 | } |
| 350 | 337 | : undefined, |
| 338 | + anthropic_beta: options.model.includes("claude") | |
| 339 | + ? ["fine-grained-tool-streaming-2025-05-14"] | |
| 340 | + : undefined, | |
| 351 | 341 | }, |
| 352 | 342 | }; |
| 353 | 343 | } |
| @@ -513,7 +503,10 @@ | ||
| 513 | 503 | // The second-to-last because it retrieves potentially already cached contents, |
| 514 | 504 | // The last one because we want it cached for later retrieval. |
| 515 | 505 | // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html |
| 516 | - if (this.cacheBehavior?.cacheConversation) { | |
| 506 | + if ( | |
| 507 | + this.cacheBehavior?.cacheConversation || | |
| 508 | + this.completionOptions.promptCaching | |
| 509 | + ) { | |
| 517 | 510 | this._addCachingToLastTwoUserMessages(converted); |
| 518 | 511 | } |
| 519 | 512 |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 3 | 3 | |
| 4 | 4 | import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; |
| 5 | +import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js"; | |
| 5 | 6 | import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; |
| 6 | 7 | import OpenAI from "./OpenAI.js"; |
| 7 | 8 | |
| @@ -96,40 +97,21 @@ | ||
| 96 | 97 | options: CompletionOptions, |
| 97 | 98 | ): AsyncGenerator<ChatMessage> { |
| 98 | 99 | if (this.isNextEdit(messages)) { |
| 99 | - messages = this.removeNextEditToken(messages); | |
| 100 | - | |
| 101 | - // Use edit/completions endpoint. | |
| 102 | - const endpoint = new URL("edit/completions", this.apiBase); | |
| 103 | - | |
| 104 | - const resp = await this.fetch(endpoint, { | |
| 105 | - method: "POST", | |
| 106 | - body: JSON.stringify({ | |
| 107 | - model: options.model, | |
| 108 | - messages: messages, | |
| 109 | - max_tokens: options.maxTokens, | |
| 110 | - temperature: options.temperature, | |
| 111 | - top_p: options.topP, | |
| 112 | - frequency_penalty: options.frequencyPenalty, | |
| 113 | - presence_penalty: options.presencePenalty, | |
| 114 | - stop: options.stop, | |
| 115 | - stream: true, | |
| 116 | - }), | |
| 117 | - headers: { | |
| 118 | - "Content-Type": "application/json", | |
| 119 | - Accept: "application/json", | |
| 120 | - Authorization: `Bearer ${this.apiKey}`, | |
| 121 | - }, | |
| 100 | + messages = this.removeToken(messages, UNIQUE_TOKEN); | |
| 101 | + yield* this.streamSpecialEndpoint( | |
| 102 | + "edit/completions", | |
| 103 | + messages, | |
| 122 | 104 | signal, |
| 123 | - }); | |
| 124 | - | |
| 125 | - for await (const chunk of streamSse(resp)) { | |
| 126 | - if (chunk.choices?.[0]?.delta?.content) { | |
| 127 | - yield { | |
| 128 | - role: "assistant", | |
| 129 | - content: chunk.choices[0].delta.content, | |
| 130 | - }; | |
| 131 | - } | |
| 132 | - } | |
| 105 | + options, | |
| 106 | + ); | |
| 107 | + } else if (this.isApply(messages)) { | |
| 108 | + messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN); | |
| 109 | + yield* this.streamSpecialEndpoint( | |
| 110 | + "apply/completions", | |
| 111 | + messages, | |
| 112 | + signal, | |
| 113 | + options, | |
| 114 | + ); | |
| 133 | 115 | } else { |
| 134 | 116 | // Use regular chat/completions endpoint - call parent OpenAI implementation. |
| 135 | 117 | yield* super._streamChat(messages, signal, options); |
| @@ -145,23 +127,68 @@ | ||
| 145 | 127 | ); |
| 146 | 128 | } |
| 147 | 129 | |
| 148 | - private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] { | |
| 130 | + private isApply(messages: ChatMessage[]): boolean { | |
| 131 | + return messages.some( | |
| 132 | + (message) => | |
| 133 | + typeof message.content === "string" && | |
| 134 | + message.content.endsWith(APPLY_UNIQUE_TOKEN), | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + | |
| 138 | + private removeToken(messages: ChatMessage[], token: string): ChatMessage[] { | |
| 149 | 139 | const lastMessage = messages[messages.length - 1]; |
| 150 | 140 | |
| 151 | 141 | if ( |
| 152 | 142 | typeof lastMessage?.content === "string" && |
| 153 | - lastMessage.content.endsWith(UNIQUE_TOKEN) | |
| 143 | + lastMessage.content.endsWith(token) | |
| 154 | 144 | ) { |
| 155 | 145 | const cleanedMessages = [...messages]; |
| 156 | 146 | cleanedMessages[cleanedMessages.length - 1] = { |
| 157 | 147 | ...lastMessage, |
| 158 | - content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), | |
| 148 | + content: lastMessage.content.slice(0, -token.length), | |
| 159 | 149 | }; |
| 160 | 150 | return cleanedMessages; |
| 161 | 151 | } |
| 162 | 152 | |
| 163 | 153 | return messages; |
| 164 | 154 | } |
| 155 | + | |
| 156 | + private async *streamSpecialEndpoint( | |
| 157 | + path: string, | |
| 158 | + messages: ChatMessage[], | |
| 159 | + signal: AbortSignal, | |
| 160 | + options: CompletionOptions, | |
| 161 | + ): AsyncGenerator<ChatMessage> { | |
| 162 | + const endpoint = new URL(path, this.apiBase); | |
| 163 | + | |
| 164 | + const resp = await this.fetch(endpoint, { | |
| 165 | + method: "POST", | |
| 166 | + body: JSON.stringify({ | |
| 167 | + model: options.model, | |
| 168 | + messages, | |
| 169 | + max_tokens: options.maxTokens, | |
| 170 | + temperature: options.temperature, | |
| 171 | + top_p: options.topP, | |
| 172 | + frequency_penalty: options.frequencyPenalty, | |
| 173 | + presence_penalty: options.presencePenalty, | |
| 174 | + stop: options.stop, | |
| 175 | + stream: true, | |
| 176 | + }), | |
| 177 | + headers: { | |
| 178 | + "Content-Type": "application/json", | |
| 179 | + Accept: "application/json", | |
| 180 | + Authorization: `Bearer ${this.apiKey}`, | |
| 181 | + }, | |
| 182 | + signal, | |
| 183 | + }); | |
| 184 | + | |
| 185 | + for await (const chunk of streamSse(resp)) { | |
| 186 | + const content = chunk.choices?.[0]?.delta?.content; | |
| 187 | + if (content) { | |
| 188 | + yield { role: "assistant", content }; | |
| 189 | + } | |
| 190 | + } | |
| 191 | + } | |
| 165 | 192 | } |
| 166 | 193 | |
| 167 | 194 | export default Inception; |
| @@ -0,0 +1,12 @@ | ||
| 1 | +import { LLMOptions } from "../../index.js"; | |
| 2 | + | |
| 3 | +import OpenAI from "./OpenAI.js"; | |
| 4 | + | |
| 5 | +class Lemonade extends OpenAI { | |
| 6 | + static providerName = "lemonade"; | |
| 7 | + static defaultOptions: Partial<LLMOptions> = { | |
| 8 | + apiBase: "http://localhost:8000/api/v1/", | |
| 9 | + }; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export default Lemonade; |
| @@ -87,6 +87,7 @@ | ||
| 87 | 87 | tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory |
| 88 | 88 | // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false |
| 89 | 89 | // And correspondingly, tool calls in OllamaChatMessage |
| 90 | + think?: boolean; // if true the model will be prompted to think about the response before generating it | |
| 90 | 91 | } |
| 91 | 92 | |
| 92 | 93 | type OllamaBaseResponse = { |
| @@ -146,11 +147,10 @@ | ||
| 146 | 147 | private static modelsBeingInstalledMutex = new Mutex(); |
| 147 | 148 | |
| 148 | 149 | private fimSupported: boolean = false; |
| 149 | - | |
| 150 | 150 | constructor(options: LLMOptions) { |
| 151 | 151 | super(options); |
| 152 | 152 | |
| 153 | - if (options.isFromAutoDetect) { | |
| 153 | + if (options.model === "AUTODETECT") { | |
| 154 | 154 | return; |
| 155 | 155 | } |
| 156 | 156 | const headers: Record<string, string> = { |
| @@ -269,6 +269,11 @@ | ||
| 269 | 269 | return this.modelMap[this.model] ?? this.model; |
| 270 | 270 | } |
| 271 | 271 | |
| 272 | + get contextLength() { | |
| 273 | + const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185 | |
| 274 | + return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH; | |
| 275 | + } | |
| 276 | + | |
| 272 | 277 | private _getModelFileParams( |
| 273 | 278 | options: CompletionOptions, |
| 274 | 279 | ): OllamaModelFileParams { |
| @@ -393,6 +398,7 @@ | ||
| 393 | 398 | model: this._getModel(), |
| 394 | 399 | messages: ollamaMessages, |
| 395 | 400 | options: this._getModelFileParams(options), |
| 401 | + think: options.reasoning, | |
| 396 | 402 | keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes |
| 397 | 403 | stream: options.stream, |
| 398 | 404 | // format: options.format, // Not currently in base completion options |
| @@ -174,7 +174,7 @@ | ||
| 174 | 174 | protected _getHeaders() { |
| 175 | 175 | return { |
| 176 | 176 | "Content-Type": "application/json", |
| 177 | - Authorization: `Bearer ${this.apiKey}`, | |
| 177 | + ...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }), | |
| 178 | 178 | "api-key": this.apiKey ?? "", // For Azure |
| 179 | 179 | }; |
| 180 | 180 | } |
| @@ -9,17 +9,16 @@ | ||
| 9 | 9 | }; |
| 10 | 10 | |
| 11 | 11 | private static MODEL_IDS: { [name: string]: string } = { |
| 12 | - "llama4-scout": "Llama-4-Scout-17B-16E-Instruct", | |
| 13 | 12 | "llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct", |
| 14 | 13 | "llama3.3-70b": "Meta-Llama-3.3-70B-Instruct", |
| 14 | + "llama3.3-swalllow-70b": "Llama-3.3-Swallow-70B-Instruct-v0.4", | |
| 15 | 15 | "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", |
| 16 | - "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", | |
| 17 | - "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct", | |
| 18 | - "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct", | |
| 19 | - "qwq-32b": "QwQ-32B", | |
| 20 | 16 | "deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B", |
| 21 | 17 | "deepseek-r1": "DeepSeek-R1", |
| 22 | 18 | "deepseek-v3": "DeepSeek-V3-0324", |
| 19 | + "deepseek-v3.1": "DeepSeek-V3-0324", | |
| 20 | + "gpt-oss-120b": "gpt-oss-120b", | |
| 21 | + "qwen3-32b": "Qwen3-32B", | |
| 23 | 22 | }; |
| 24 | 23 | |
| 25 | 24 | protected _convertModelName(model: string) { |
| @@ -7,16 +7,23 @@ | ||
| 7 | 7 | static providerName = "scaleway"; |
| 8 | 8 | static defaultOptions: Partial<LLMOptions> = { |
| 9 | 9 | apiBase: "https://api.scaleway.ai/v1/", |
| 10 | - model: "qwen2.5-coder-32b-instruct", | |
| 10 | + model: "qwen3-coder-30b-a3b-instruct", | |
| 11 | 11 | useLegacyCompletionsEndpoint: false, |
| 12 | 12 | }; |
| 13 | 13 | |
| 14 | 14 | private static MODEL_IDS: { [name: string]: string } = { |
| 15 | 15 | "llama3.1-8b": "llama-3.1-8b-instruct", |
| 16 | 16 | "llama3.3-70b": "llama-3.3-70b-instruct", |
| 17 | + "pixtral-12b": "pixtral-12b-2409", | |
| 17 | 18 | "mistral-small3.1": "mistral-small-3.1-24b-instruct-2503", |
| 19 | + "mistral-small3.2": "mistral-small-3.2-24b-instruct-2506", | |
| 20 | + "devstral-small": "devstral-small-2505", | |
| 18 | 21 | "deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b", |
| 19 | 22 | "qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct", |
| 23 | + "qwen3-coder-30b-a3b": "qwen3-coder-30b-a3b-instruct", | |
| 24 | + "qwen3-235b-a22b": "qwen3-235b-a22b-instruct-2507", | |
| 25 | + "gemma-3-27b": "gemma-3-27b-it", | |
| 26 | + "gpt-oss-120b": "gpt-oss-120b", | |
| 20 | 27 | }; |
| 21 | 28 | |
| 22 | 29 | protected _convertModelName(model: string) { |
| @@ -0,0 +1,18 @@ | ||
| 1 | +import { LLMOptions } from "../../index.js"; | |
| 2 | +import { osModelsEditPrompt } from "../templates/edit.js"; | |
| 3 | + | |
| 4 | +import OpenAI from "./OpenAI.js"; | |
| 5 | + | |
| 6 | +class TARS extends OpenAI { | |
| 7 | + static providerName = "tars"; | |
| 8 | + static defaultOptions: Partial<LLMOptions> = { | |
| 9 | + apiBase: "https://api.router.tetrate.ai/v1", | |
| 10 | + model: "gpt-5-mini", | |
| 11 | + promptTemplates: { | |
| 12 | + edit: osModelsEditPrompt, | |
| 13 | + }, | |
| 14 | + useLegacyCompletionsEndpoint: false, | |
| 15 | + }; | |
| 16 | +} | |
| 17 | + | |
| 18 | +export default TARS; |
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | import LlamaCpp from "./LlamaCpp"; |
| 34 | 34 | import Llamafile from "./Llamafile"; |
| 35 | 35 | import LlamaStack from "./LlamaStack"; |
| 36 | +import Lemonade from "./Lemonade"; | |
| 36 | 37 | import LMStudio from "./LMStudio"; |
| 37 | 38 | import Mistral from "./Mistral"; |
| 38 | 39 | import MockLLM from "./Mock"; |
| @@ -53,6 +54,7 @@ | ||
| 53 | 54 | import Scaleway from "./Scaleway"; |
| 54 | 55 | import SiliconFlow from "./SiliconFlow"; |
| 55 | 56 | import ContinueProxy from "./stubs/ContinueProxy"; |
| 57 | +import TARS from "./TARS"; | |
| 56 | 58 | import TestLLM from "./Test"; |
| 57 | 59 | import TextGenWebUI from "./TextGenWebUI"; |
| 58 | 60 | import Together from "./Together"; |
| @@ -81,6 +83,7 @@ | ||
| 81 | 83 | LlamaCpp, |
| 82 | 84 | OpenAI, |
| 83 | 85 | OVHcloud, |
| 86 | + Lemonade, | |
| 84 | 87 | LMStudio, |
| 85 | 88 | Mistral, |
| 86 | 89 | Bedrock, |
| @@ -116,6 +119,7 @@ | ||
| 116 | 119 | Inception, |
| 117 | 120 | Voyage, |
| 118 | 121 | LlamaStack, |
| 122 | + TARS, | |
| 119 | 123 | ]; |
| 120 | 124 | |
| 121 | 125 | export async function llmFromDescription( |
| @@ -95,7 +95,7 @@ | ||
| 95 | 95 | ...init, |
| 96 | 96 | signal: abortController.signal, |
| 97 | 97 | }, |
| 98 | - config.requestOptions, | |
| 98 | + model.requestOptions, | |
| 99 | 99 | ), |
| 100 | 100 | completionOptions, |
| 101 | 101 | abortController, |
| @@ -71,3 +71,10 @@ | ||
| 71 | 71 | |
| 72 | 72 | return paragraphs.join("\n\n"); |
| 73 | 73 | }; |
| 74 | + | |
| 75 | +export const defaultApplyPrompt: PromptTemplateFunction = ( | |
| 76 | + history, | |
| 77 | + otherData, | |
| 78 | +) => { | |
| 79 | + return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`; | |
| 80 | +}; |
| @@ -203,7 +203,9 @@ | ||
| 203 | 203 | if ( |
| 204 | 204 | model.toLowerCase().startsWith("meta-llama-3") || |
| 205 | 205 | model.toLowerCase().includes("llama-4") || |
| 206 | - model.toLowerCase().includes("deepseek") | |
| 206 | + model.toLowerCase().includes("deepseek") || | |
| 207 | + model.toLowerCase().includes("gpt") || | |
| 208 | + model.toLowerCase().includes("qwen") | |
| 207 | 209 | ) { |
| 208 | 210 | return true; |
| 209 | 211 | } |
| @@ -374,9 +376,8 @@ | ||
| 374 | 376 | [/o[134]/], |
| 375 | 377 | [/deepseek/, /r1|reasoner/], |
| 376 | 378 | [/gemini/, /2\.5/, /pro/], |
| 377 | - [/gpt/, /4/], | |
| 378 | 379 | [/gpt-5/], |
| 379 | - [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], | |
| 380 | + [/claude/, /sonnet/, /3\.7|3-7|-4/], | |
| 380 | 381 | [/claude/, /opus/, /-4/], |
| 381 | 382 | ]; |
| 382 | 383 | for (const combo of recs) { |
| @@ -13,6 +13,10 @@ | ||
| 13 | 13 | Static = "static", |
| 14 | 14 | } |
| 15 | 15 | |
| 16 | +/** | |
| 17 | + * This was an attempt to find next edit locations deterministically. | |
| 18 | + * I was intending to use this in tandem with the prefetching logic, but we are not using it anymore. | |
| 19 | + */ | |
| 16 | 20 | export async function getNextEditableRegion( |
| 17 | 21 | strategy: EditableRegionStrategy, |
| 18 | 22 | ctx: any, |
| @@ -7,6 +7,14 @@ | ||
| 7 | 7 | outcome: NextEditOutcome; // Result from the model |
| 8 | 8 | } |
| 9 | 9 | |
| 10 | +/** | |
| 11 | + * Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts | |
| 12 | + */ | |
| 13 | +/** | |
| 14 | + * This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain. | |
| 15 | + * I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background. | |
| 16 | + * Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea. | |
| 17 | + */ | |
| 10 | 18 | export class PrefetchQueue { |
| 11 | 19 | private static instance: PrefetchQueue | null = null; |
| 12 | 20 |
| @@ -19,14 +19,13 @@ | ||
| 19 | 19 | import { AutocompleteInput } from "../autocomplete/util/types.js"; |
| 20 | 20 | import { isSecurityConcern } from "../indexing/ignore.js"; |
| 21 | 21 | import { modelSupportsNextEdit } from "../llm/autodetect.js"; |
| 22 | -import { countTokens } from "../llm/countTokens.js"; | |
| 23 | 22 | import { localPathOrUriToPath } from "../util/pathToUri.js"; |
| 24 | 23 | import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; |
| 25 | 24 | import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; |
| 26 | 25 | import { NextEditLoggingService } from "./NextEditLoggingService.js"; |
| 27 | 26 | import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; |
| 28 | 27 | import { NextEditProviderFactory } from "./NextEditProviderFactory.js"; |
| 29 | -import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; | |
| 28 | +import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js"; | |
| 30 | 29 | import { |
| 31 | 30 | ModelSpecificContext, |
| 32 | 31 | NextEditOutcome, |
| @@ -45,6 +44,14 @@ | ||
| 45 | 44 | "operation was aborted", |
| 46 | 45 | ]; |
| 47 | 46 | |
| 47 | +/** | |
| 48 | + * This is the next edit analogue to autocomplete's CompletionProvider. | |
| 49 | + * You will see a lot of similar if not identical methods to CompletionProvider methods. | |
| 50 | + * All logic used to live inside this class, but that became untenable quickly. | |
| 51 | + * I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it. | |
| 52 | + * Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc. | |
| 53 | + * There being a singleton also gives a lot of guarantees about the state of the next edit state machine. | |
| 54 | + */ | |
| 48 | 55 | export class NextEditProvider { |
| 49 | 56 | private static instance: NextEditProvider | null = null; |
| 50 | 57 | |
| @@ -62,10 +69,9 @@ | ||
| 62 | 69 | private currentEditChainId: string | null = null; |
| 63 | 70 | private previousRequest: AutocompleteInput | null = null; |
| 64 | 71 | private previousCompletions: NextEditOutcome[] = []; |
| 65 | - // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; | |
| 66 | 72 | |
| 67 | 73 | // Model-specific provider instance. |
| 68 | - private modelProvider: BaseNextEditProvider | null = null; | |
| 74 | + private modelProvider: BaseNextEditModelProvider | null = null; | |
| 69 | 75 | |
| 70 | 76 | private constructor( |
| 71 | 77 | private readonly configHandler: ConfigHandler, |
| @@ -223,14 +229,14 @@ | ||
| 223 | 229 | |
| 224 | 230 | this.currentEditChainId = null; |
| 225 | 231 | this.previousCompletions = []; |
| 226 | - // TODO: this should be cleaned up in the prefetch queue. | |
| 227 | - // this.nextEditableRegionsInTheCurrentChain = []; | |
| 228 | 232 | |
| 229 | 233 | if (this.previousRequest) { |
| 230 | 234 | const fileContent = ( |
| 231 | 235 | await this.ide.readFile(this.previousRequest.filepath) |
| 232 | 236 | ).toString(); |
| 237 | + | |
| 233 | 238 | const ast = await getAst(this.previousRequest.filepath, fileContent); |
| 239 | + | |
| 234 | 240 | if (ast) { |
| 235 | 241 | DocumentHistoryTracker.getInstance().push( |
| 236 | 242 | localPathOrUriToPath(this.previousRequest.filepath), |
| @@ -253,6 +259,9 @@ | ||
| 253 | 259 | return this.previousCompletions.length === 1; |
| 254 | 260 | } |
| 255 | 261 | |
| 262 | + /** | |
| 263 | + * This is the main entry point to this class. | |
| 264 | + */ | |
| 256 | 265 | public async provideInlineCompletionItems( |
| 257 | 266 | input: AutocompleteInput, |
| 258 | 267 | token: AbortSignal | undefined, |
| @@ -370,6 +379,8 @@ | ||
| 370 | 379 | throw new Error("Model provider not initialized"); |
| 371 | 380 | } |
| 372 | 381 | |
| 382 | + // NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets. | |
| 383 | + // Use getAllSnippets if snippet gathering becomes noticably slow. | |
| 373 | 384 | const [snippetPayload, workspaceDirs] = await Promise.all([ |
| 374 | 385 | getAllSnippetsWithoutRace({ |
| 375 | 386 | helper, |
| @@ -445,6 +456,9 @@ | ||
| 445 | 456 | } |
| 446 | 457 | |
| 447 | 458 | // Send prompts to LLM (using only user prompt for fine-tuned models). |
| 459 | + // prompts[1] extracts the user prompt from the system-user prompt pair. | |
| 460 | + // NOTE: Stream is currently set to false, but this should ideally be a per-model flag. | |
| 461 | + // Mercury Coder currently does not support streaming. | |
| 448 | 462 | const msg: ChatMessage = await llm.chat([prompts[1]], token, { |
| 449 | 463 | stream: false, |
| 450 | 464 | }); |
| @@ -484,7 +498,7 @@ | ||
| 484 | 498 | } |
| 485 | 499 | |
| 486 | 500 | if (outcome) { |
| 487 | - // Handle NextEditProvider-specific state | |
| 501 | + // Handle NextEditProvider-specific state. | |
| 488 | 502 | this.previousCompletions.push(outcome); |
| 489 | 503 | |
| 490 | 504 | // Mark as displayed for JetBrains |
| @@ -494,97 +508,6 @@ | ||
| 494 | 508 | return outcome; |
| 495 | 509 | } |
| 496 | 510 | |
| 497 | - private _calculateOptimalEditableRegion( | |
| 498 | - helper: HelperVars, | |
| 499 | - heuristic: "fourChars" | "tokenizer" = "tokenizer", | |
| 500 | - ): { | |
| 501 | - editableRegionStartLine: number; | |
| 502 | - editableRegionEndLine: number; | |
| 503 | - } { | |
| 504 | - const cursorLine = helper.pos.line; | |
| 505 | - const fileLines = helper.fileLines; | |
| 506 | - const MAX_TOKENS = 512; | |
| 507 | - | |
| 508 | - // Initialize with cursor line. | |
| 509 | - let editableRegionStartLine = cursorLine; | |
| 510 | - let editableRegionEndLine = cursorLine; | |
| 511 | - | |
| 512 | - // Get initial content and token count. | |
| 513 | - let currentContent = fileLines[cursorLine]; | |
| 514 | - let totalTokens = | |
| 515 | - heuristic === "tokenizer" | |
| 516 | - ? countTokens(currentContent, helper.modelName) | |
| 517 | - : Math.ceil(currentContent.length / 4); | |
| 518 | - | |
| 519 | - // Expand outward alternating between adding lines above and below. | |
| 520 | - let addingAbove = true; | |
| 521 | - | |
| 522 | - while (totalTokens < MAX_TOKENS) { | |
| 523 | - let addedLine = false; | |
| 524 | - | |
| 525 | - if (addingAbove) { | |
| 526 | - // Try to add a line above. | |
| 527 | - if (editableRegionStartLine > 0) { | |
| 528 | - editableRegionStartLine--; | |
| 529 | - const lineContent = fileLines[editableRegionStartLine]; | |
| 530 | - const lineTokens = | |
| 531 | - heuristic === "tokenizer" | |
| 532 | - ? countTokens(lineContent, helper.modelName) | |
| 533 | - : Math.ceil(lineContent.length / 4); | |
| 534 | - | |
| 535 | - totalTokens += lineTokens; | |
| 536 | - addedLine = true; | |
| 537 | - } | |
| 538 | - } else { | |
| 539 | - // Try to add a line below. | |
| 540 | - if (editableRegionEndLine < fileLines.length - 1) { | |
| 541 | - editableRegionEndLine++; | |
| 542 | - const lineContent = fileLines[editableRegionEndLine]; | |
| 543 | - const lineTokens = | |
| 544 | - heuristic === "tokenizer" | |
| 545 | - ? countTokens(lineContent, helper.modelName) | |
| 546 | - : Math.ceil(lineContent.length / 4); | |
| 547 | - | |
| 548 | - totalTokens += lineTokens; | |
| 549 | - addedLine = true; | |
| 550 | - } | |
| 551 | - } | |
| 552 | - | |
| 553 | - // If we can't add in the current direction, try the other. | |
| 554 | - if (!addedLine) { | |
| 555 | - // If we're already at both file boundaries, we're done. | |
| 556 | - if ( | |
| 557 | - editableRegionStartLine === 0 && | |
| 558 | - editableRegionEndLine === fileLines.length - 1 | |
| 559 | - ) { | |
| 560 | - break; | |
| 561 | - } | |
| 562 | - | |
| 563 | - // If we couldn't add in one direction, force the next attempt in the other direction. | |
| 564 | - addingAbove = !addingAbove; | |
| 565 | - continue; | |
| 566 | - } | |
| 567 | - | |
| 568 | - // If we exceeded the token limit, revert the last addition. | |
| 569 | - if (totalTokens > MAX_TOKENS) { | |
| 570 | - if (addingAbove) { | |
| 571 | - editableRegionStartLine++; | |
| 572 | - } else { | |
| 573 | - editableRegionEndLine--; | |
| 574 | - } | |
| 575 | - break; | |
| 576 | - } | |
| 577 | - | |
| 578 | - // Alternate between adding above and below for balanced context. | |
| 579 | - addingAbove = !addingAbove; | |
| 580 | - } | |
| 581 | - | |
| 582 | - return { | |
| 583 | - editableRegionStartLine, | |
| 584 | - editableRegionEndLine, | |
| 585 | - }; | |
| 586 | - } | |
| 587 | - | |
| 588 | 511 | private async _markDisplayedIfJetBrains( |
| 589 | 512 | completionId: string, |
| 590 | 513 | outcome: NextEditOutcome, |
| @@ -595,6 +518,12 @@ | ||
| 595 | 518 | } |
| 596 | 519 | } |
| 597 | 520 | |
| 521 | + /** | |
| 522 | + * This is a wrapper around provideInlineCompletionItems. | |
| 523 | + * This is invoked when we call the model in the background using prefetch. | |
| 524 | + * It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch. | |
| 525 | + * You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`. | |
| 526 | + */ | |
| 598 | 527 | public async provideInlineCompletionItemsWithChain( |
| 599 | 528 | ctx: { |
| 600 | 529 | completionId: string; |
| @@ -1,259 +0,0 @@ | ||
| 1 | -import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | -import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; | |
| 3 | -import { HelperVars } from "../autocomplete/util/HelperVars.js"; | |
| 4 | -import { ConfigHandler } from "../config/ConfigHandler.js"; | |
| 5 | -import { IDE, ILLM } from "../index.js"; | |
| 6 | -import { NextEditProvider } from "./NextEditProvider.js"; | |
| 7 | - | |
| 8 | -// Mock the countTokens function | |
| 9 | -vi.mock("../llm/countTokens.js", () => ({ | |
| 10 | - countTokens: (text: string) => { | |
| 11 | - // Simple mock that counts 1 token per character for predictable tests | |
| 12 | - return text.length; | |
| 13 | - }, | |
| 14 | -})); | |
| 15 | - | |
| 16 | -// Create a helper function to set up the test context | |
| 17 | -function createMockHelper( | |
| 18 | - fileContents: string, | |
| 19 | - cursorLine: number, | |
| 20 | -): HelperVars { | |
| 21 | - const fileLines = fileContents.split("\n"); | |
| 22 | - | |
| 23 | - return { | |
| 24 | - fileLines, | |
| 25 | - fileContents, | |
| 26 | - pos: { line: cursorLine, character: 0 }, | |
| 27 | - modelName: "gpt-4", | |
| 28 | - lang: { name: "typescript" }, | |
| 29 | - filepath: "test/file.ts", | |
| 30 | - workspaceUris: ["test/workspace"], | |
| 31 | - options: {}, | |
| 32 | - input: { completionId: "test-completion-id" }, | |
| 33 | - } as unknown as HelperVars; | |
| 34 | -} | |
| 35 | - | |
| 36 | -// TODO: Add more tests for other methods. | |
| 37 | -describe("_calculateOptimalEditableRegion", () => { | |
| 38 | - let nextEditProvider: NextEditProvider; | |
| 39 | - let mockConfigHandler: ConfigHandler; | |
| 40 | - let mockIde: IDE; | |
| 41 | - let mockGetLlm: () => Promise<ILLM | undefined>; | |
| 42 | - let mockOnError: (e: any) => void; | |
| 43 | - let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction; | |
| 44 | - | |
| 45 | - beforeEach(() => { | |
| 46 | - // Create comprehensive mocks for all dependencies | |
| 47 | - mockConfigHandler = { | |
| 48 | - loadConfig: vi.fn().mockResolvedValue({ config: {} }), | |
| 49 | - } as unknown as ConfigHandler; | |
| 50 | - | |
| 51 | - mockIde = { | |
| 52 | - readFile: vi.fn().mockResolvedValue(""), | |
| 53 | - getWorkspaceDirs: vi.fn().mockResolvedValue([]), | |
| 54 | - getRepoName: vi.fn().mockResolvedValue("test-repo"), | |
| 55 | - getUniqueId: vi.fn().mockResolvedValue("test-id"), | |
| 56 | - getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }), | |
| 57 | - onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => { | |
| 58 | - // Return a disposable object that does nothing when disposed | |
| 59 | - return { | |
| 60 | - dispose: () => {}, | |
| 61 | - }; | |
| 62 | - }), | |
| 63 | - } as unknown as IDE; | |
| 64 | - | |
| 65 | - mockGetLlm = vi.fn().mockResolvedValue({ | |
| 66 | - model: "gpt-4", | |
| 67 | - providerName: "openai", | |
| 68 | - underlyingProviderName: "openai", | |
| 69 | - completionOptions: {}, | |
| 70 | - chat: vi.fn(), | |
| 71 | - }); | |
| 72 | - | |
| 73 | - mockOnError = vi.fn(); | |
| 74 | - mockGetDefinitionsFromLsp = vi.fn(); | |
| 75 | - | |
| 76 | - // Initialize NextEditProvider with mocked dependencies | |
| 77 | - nextEditProvider = NextEditProvider.initialize( | |
| 78 | - mockConfigHandler, | |
| 79 | - mockIde, | |
| 80 | - mockGetLlm, | |
| 81 | - mockOnError, | |
| 82 | - mockGetDefinitionsFromLsp, | |
| 83 | - "default", | |
| 84 | - ); | |
| 85 | - | |
| 86 | - // Expose the private method for testing | |
| 87 | - // This is a bit of a hack, but necessary for testing private methods | |
| 88 | - (nextEditProvider as any)._calculateOptimalEditableRegion = ( | |
| 89 | - NextEditProvider.prototype as any | |
| 90 | - )._calculateOptimalEditableRegion.bind(nextEditProvider); | |
| 91 | - }); | |
| 92 | - | |
| 93 | - // Test cases remain the same as before... | |
| 94 | - it("should include only the cursor line when it already exceeds token limit", () => { | |
| 95 | - // Create a mock helper with a very long cursor line (>500 characters) | |
| 96 | - const longLine = "X".repeat(600); | |
| 97 | - const helper = createMockHelper(longLine, 0); | |
| 98 | - | |
| 99 | - //@ts-ignore | |
| 100 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 101 | - helper, | |
| 102 | - "tokenizer", | |
| 103 | - ); | |
| 104 | - | |
| 105 | - expect(result.editableRegionStartLine).toBe(0); | |
| 106 | - expect(result.editableRegionEndLine).toBe(0); | |
| 107 | - }); | |
| 108 | - | |
| 109 | - it("should expand symmetrically when possible", () => { | |
| 110 | - // Create content with identical lines and cursor in the middle | |
| 111 | - const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each | |
| 112 | - const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5) | |
| 113 | - | |
| 114 | - //@ts-ignore | |
| 115 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 116 | - helper, | |
| 117 | - "tokenizer", | |
| 118 | - ); | |
| 119 | - | |
| 120 | - // Should expand 5 lines in each direction (total 11 lines) for symmetry | |
| 121 | - expect(result.editableRegionStartLine).toBe(0); | |
| 122 | - expect(result.editableRegionEndLine).toBe(10); | |
| 123 | - }); | |
| 124 | - | |
| 125 | - it("should expand asymmetrically when hitting a file boundary", () => { | |
| 126 | - // Create content with cursor near the top | |
| 127 | - const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each | |
| 128 | - const helper = createMockHelper(lines, 1); // Cursor near the top (line 1) | |
| 129 | - | |
| 130 | - //@ts-ignore | |
| 131 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 132 | - helper, | |
| 133 | - "tokenizer", | |
| 134 | - ); | |
| 135 | - | |
| 136 | - // Should include more lines below since it can't expand much above | |
| 137 | - expect(result.editableRegionStartLine).toBe(0); | |
| 138 | - // Should include many more lines below to reach token limit | |
| 139 | - expect(result.editableRegionEndLine).toBeGreaterThan(10); | |
| 140 | - }); | |
| 141 | - | |
| 142 | - it("should handle files with varying line lengths", () => { | |
| 143 | - // Create content with varying line lengths | |
| 144 | - const fileContents = [ | |
| 145 | - "Short line", // 10 chars | |
| 146 | - "A".repeat(100), // 100 chars | |
| 147 | - "Medium length line here", // 24 chars | |
| 148 | - "B".repeat(200), // 200 chars | |
| 149 | - "Another typical line of code", // 28 chars | |
| 150 | - ].join("\n"); | |
| 151 | - | |
| 152 | - const helper = createMockHelper(fileContents, 2); // Cursor on the medium line | |
| 153 | - | |
| 154 | - //@ts-ignore | |
| 155 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 156 | - helper, | |
| 157 | - "tokenizer", | |
| 158 | - ); | |
| 159 | - | |
| 160 | - // Should include all lines since total tokens < 500 | |
| 161 | - expect(result.editableRegionStartLine).toBe(0); | |
| 162 | - expect(result.editableRegionEndLine).toBe(4); | |
| 163 | - }); | |
| 164 | - | |
| 165 | - it("should respect the token limit and not include too many lines", () => { | |
| 166 | - // Create content with many small lines (10 chars each) | |
| 167 | - const lines = Array(600).fill("C".repeat(10)).join("\n"); | |
| 168 | - const helper = createMockHelper(lines, 300); // Cursor in the middle | |
| 169 | - | |
| 170 | - //@ts-ignore | |
| 171 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 172 | - helper, | |
| 173 | - "tokenizer", | |
| 174 | - ); | |
| 175 | - | |
| 176 | - // Each line is 10 chars = 10 tokens per line with our mock. | |
| 177 | - // So with 500 token limit, we should get 50 lines total. | |
| 178 | - // 25 above, 25 below, +1 current | |
| 179 | - const totalLines = | |
| 180 | - result.editableRegionEndLine - result.editableRegionStartLine + 1; | |
| 181 | - expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line) | |
| 182 | - }); | |
| 183 | - | |
| 184 | - it("should use character approximation when using fourChars heuristic", () => { | |
| 185 | - // In this test, we're setting up a situation where tiktoken and fourChars would give different results | |
| 186 | - // Creating 5 lines, each 100 characters | |
| 187 | - const lines = Array(10).fill("D".repeat(100)).join("\n"); | |
| 188 | - const helper = createMockHelper(lines, 2); // Cursor in the middle | |
| 189 | - | |
| 190 | - // Mock for tiktoken counting (1 char = 1 token) | |
| 191 | - //@ts-ignore | |
| 192 | - const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion( | |
| 193 | - helper, | |
| 194 | - "tokenizer", | |
| 195 | - ); | |
| 196 | - | |
| 197 | - // Mock for fourChars counting (1 token = 4 chars) | |
| 198 | - // This should include more lines since each line is counted as 25 tokens instead of 100 | |
| 199 | - //@ts-ignore | |
| 200 | - const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion( | |
| 201 | - helper, | |
| 202 | - "fourChars", | |
| 203 | - ); | |
| 204 | - | |
| 205 | - // The fourChars approach should include more lines since it estimates fewer tokens per line | |
| 206 | - expect( | |
| 207 | - fourCharsResult.editableRegionEndLine - | |
| 208 | - fourCharsResult.editableRegionStartLine, | |
| 209 | - ).toBeGreaterThan( | |
| 210 | - tokenizerResult.editableRegionEndLine - | |
| 211 | - tokenizerResult.editableRegionStartLine, | |
| 212 | - ); | |
| 213 | - }); | |
| 214 | - | |
| 215 | - it("should include the entire file if it's within token limit", () => { | |
| 216 | - // Create a small file | |
| 217 | - const smallFile = "Small file\nwith just\na few lines\nof text"; | |
| 218 | - const helper = createMockHelper(smallFile, 1); | |
| 219 | - | |
| 220 | - //@ts-ignore | |
| 221 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 222 | - helper, | |
| 223 | - "tokenizer", | |
| 224 | - ); | |
| 225 | - | |
| 226 | - // Should include all lines | |
| 227 | - expect(result.editableRegionStartLine).toBe(0); | |
| 228 | - expect(result.editableRegionEndLine).toBe(3); | |
| 229 | - }); | |
| 230 | - | |
| 231 | - it("should prioritize balanced context when token limit allows", () => { | |
| 232 | - // Create content with alternating long and short lines | |
| 233 | - const fileContents = [ | |
| 234 | - "Short", // 5 chars | |
| 235 | - "E".repeat(80), // 80 chars | |
| 236 | - "Also short", // 10 chars | |
| 237 | - "F".repeat(80), // 80 chars | |
| 238 | - "Another short one", // 17 chars | |
| 239 | - "G".repeat(80), // 80 chars | |
| 240 | - "Final short line", // 16 chars | |
| 241 | - ].join("\n"); | |
| 242 | - | |
| 243 | - const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3) | |
| 244 | - | |
| 245 | - //@ts-ignore | |
| 246 | - const result = nextEditProvider._calculateOptimalEditableRegion( | |
| 247 | - helper, | |
| 248 | - "tokenizer", | |
| 249 | - ); | |
| 250 | - | |
| 251 | - // Should try to include equal number of lines above and below cursor | |
| 252 | - const linesAbove = result.editableRegionStartLine; | |
| 253 | - const linesBelow = | |
| 254 | - helper.fileLines.length - 1 - result.editableRegionEndLine; | |
| 255 | - | |
| 256 | - // Difference between lines above and below should be minimal | |
| 257 | - expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1); | |
| 258 | - }); | |
| 259 | -}); |
| @@ -1,10 +1,10 @@ | ||
| 1 | 1 | import { NEXT_EDIT_MODELS } from "../llm/constants.js"; |
| 2 | -import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; | |
| 2 | +import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js"; | |
| 3 | 3 | import { InstinctProvider } from "./providers/InstinctNextEditProvider.js"; |
| 4 | 4 | import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js"; |
| 5 | 5 | |
| 6 | 6 | export class NextEditProviderFactory { |
| 7 | - static createProvider(modelName: string): BaseNextEditProvider { | |
| 7 | + static createProvider(modelName: string): BaseNextEditModelProvider { | |
| 8 | 8 | if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) { |
| 9 | 9 | return new MercuryCoderProvider(); |
| 10 | 10 | } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { |
| @@ -19,7 +19,12 @@ | ||
| 19 | 19 | } from "../types.js"; |
| 20 | 20 | import { isWhitespaceOnlyDeletion } from "../utils.js"; |
| 21 | 21 | |
| 22 | -export abstract class BaseNextEditProvider { | |
| 22 | +/** | |
| 23 | + * This class is used as an abstract base class for model-specific providers. | |
| 24 | + * This and its children are responsible for pre/post processing of prompts and outcomes. | |
| 25 | + * Different next edit models have very different requirements. | |
| 26 | + */ | |
| 27 | +export abstract class BaseNextEditModelProvider { | |
| 23 | 28 | protected readonly modelName: string; |
| 24 | 29 | |
| 25 | 30 | constructor(modelName: string) { |
| @@ -11,9 +11,9 @@ | ||
| 11 | 11 | PromptTemplateRenderer, |
| 12 | 12 | } from "../templating/NextEditPromptEngine.js"; |
| 13 | 13 | import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; |
| 14 | -import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; | |
| 14 | +import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js"; | |
| 15 | 15 | |
| 16 | -export class InstinctProvider extends BaseNextEditProvider { | |
| 16 | +export class InstinctProvider extends BaseNextEditModelProvider { | |
| 17 | 17 | private templateRenderer: PromptTemplateRenderer; |
| 18 | 18 | |
| 19 | 19 | constructor() { |
| @@ -11,9 +11,9 @@ | ||
| 11 | 11 | PromptTemplateRenderer, |
| 12 | 12 | } from "../templating/NextEditPromptEngine.js"; |
| 13 | 13 | import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; |
| 14 | -import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; | |
| 14 | +import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js"; | |
| 15 | 15 | |
| 16 | -export class MercuryCoderProvider extends BaseNextEditProvider { | |
| 16 | +export class MercuryCoderProvider extends BaseNextEditModelProvider { | |
| 17 | 17 | private templateRenderer: PromptTemplateRenderer; |
| 18 | 18 | |
| 19 | 19 | constructor() { |
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | "@types/pg": "^8.11.6", |
| 35 | 35 | "@types/plist": "^3.0.5", |
| 36 | 36 | "@types/request": "^2.48.12", |
| 37 | + "@types/shell-quote": "^1.7.5", | |
| 37 | 38 | "@types/tar": "^6.1.13", |
| 38 | 39 | "@types/uuid": "^9.0.7", |
| 39 | 40 | "@types/win-ca": "^3.5.4", |
| @@ -61,6 +62,7 @@ | ||
| 61 | 62 | "@continuedev/fetch": "file:../packages/fetch", |
| 62 | 63 | "@continuedev/llm-info": "file:../packages/llm-info", |
| 63 | 64 | "@continuedev/openai-adapters": "file:../packages/openai-adapters", |
| 65 | + "@continuedev/terminal-security": "file:../packages/terminal-security", | |
| 64 | 66 | "@modelcontextprotocol/sdk": "^1.12.0", |
| 65 | 67 | "@mozilla/readability": "^0.5.0", |
| 66 | 68 | "@octokit/rest": "^20.1.1", |
| @@ -111,6 +113,7 @@ | ||
| 111 | 113 | "quick-lru": "^7.0.0", |
| 112 | 114 | "replicate": "^0.26.0", |
| 113 | 115 | "request": "^2.88.2", |
| 116 | + "shell-quote": "^1.8.3", | |
| 114 | 117 | "socket.io-client": "^4.7.3", |
| 115 | 118 | "sqlite": "^5.1.1", |
| 116 | 119 | "sqlite3": "^5.1.7", |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | DevDataLogEvent, |
| 5 | 5 | ModelRole, |
| 6 | 6 | } from "@continuedev/config-yaml"; |
| 7 | +import { ToolPolicy } from "@continuedev/terminal-security"; | |
| 7 | 8 | |
| 8 | 9 | import { |
| 9 | 10 | AutocompleteInput, |
| @@ -34,7 +35,7 @@ | ||
| 34 | 35 | RangeInFileWithNextEditInfo, |
| 35 | 36 | SerializedContinueConfig, |
| 36 | 37 | Session, |
| 37 | - SessionMetadata, | |
| 38 | + BaseSessionMetadata, | |
| 38 | 39 | SiteIndexingConfig, |
| 39 | 40 | SlashCommandDescWithSource, |
| 40 | 41 | StreamDiffLinesPayload, |
| @@ -48,7 +49,10 @@ | ||
| 48 | 49 | ControlPlaneEnv, |
| 49 | 50 | ControlPlaneSessionInfo, |
| 50 | 51 | } from "../control-plane/AuthTypes"; |
| 51 | -import { FreeTrialStatus } from "../control-plane/client"; | |
| 52 | +import { | |
| 53 | + FreeTrialStatus, | |
| 54 | + RemoteSessionMetadata, | |
| 55 | +} from "../control-plane/client"; | |
| 52 | 56 | import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; |
| 53 | 57 | import { NextEditOutcome } from "../nextEdit/types"; |
| 54 | 58 | |
| @@ -70,10 +74,15 @@ | ||
| 70 | 74 | cancelApply: [undefined, void]; |
| 71 | 75 | |
| 72 | 76 | // History |
| 73 | - "history/list": [ListHistoryOptions, SessionMetadata[]]; | |
| 77 | + "history/list": [ | |
| 78 | + ListHistoryOptions, | |
| 79 | + (BaseSessionMetadata | RemoteSessionMetadata)[], | |
| 80 | + ]; | |
| 74 | 81 | "history/delete": [{ id: string }, void]; |
| 75 | 82 | "history/load": [{ id: string }, Session]; |
| 83 | + "history/loadRemote": [{ remoteId: string }, Session]; | |
| 76 | 84 | "history/save": [Session, void]; |
| 85 | + "history/share": [{ id: string; outputDir?: string }, void]; | |
| 77 | 86 | "history/clear": [undefined, void]; |
| 78 | 87 | "devdata/log": [DevDataLogEvent, void]; |
| 79 | 88 | "config/addOpenAiKey": [string, void]; |
| @@ -293,6 +302,10 @@ | ||
| 293 | 302 | { toolCall: ToolCall }, |
| 294 | 303 | { contextItems: ContextItem[]; errorMessage?: string }, |
| 295 | 304 | ]; |
| 305 | + "tools/evaluatePolicy": [ | |
| 306 | + { toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> }, | |
| 307 | + { policy: ToolPolicy; displayValue?: string }, | |
| 308 | + ]; | |
| 296 | 309 | "clipboardCache/add": [{ content: string }, void]; |
| 297 | 310 | "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; |
| 298 | 311 | "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; |
| @@ -308,5 +321,6 @@ | ||
| 308 | 321 | ]; |
| 309 | 322 | "process/markAsBackgrounded": [{ toolCallId: string }, void]; |
| 310 | 323 | "process/isBackgrounded": [{ toolCallId: string }, boolean]; |
| 324 | + "process/killTerminalProcess": [{ toolCallId: string }, void]; | |
| 311 | 325 | "mdm/setLicenseKey": [{ licenseKey: string }, boolean]; |
| 312 | 326 | }; |
| @@ -51,6 +51,7 @@ | ||
| 51 | 51 | getPinnedFiles: [undefined, string[]]; |
| 52 | 52 | showLines: [{ filepath: string; startLine: number; endLine: number }, void]; |
| 53 | 53 | readRangeInFile: [{ filepath: string; range: Range }, string]; |
| 54 | + readFileAsDataUrl: [{ filepath: string }, string]; | |
| 54 | 55 | getDiff: [{ includeUnstaged: boolean }, string[]]; |
| 55 | 56 | getTerminalContents: [undefined, string]; |
| 56 | 57 | getDebugLocals: [{ threadIndex: number }, string]; |
| @@ -48,6 +48,7 @@ | ||
| 48 | 48 | ]; |
| 49 | 49 | "edit/addCurrentSelection": [undefined, void]; |
| 50 | 50 | "edit/clearDecorations": [undefined, void]; |
| 51 | + "session/share": [{ sessionId: string }, void]; | |
| 51 | 52 | }; |
| 52 | 53 | |
| 53 | 54 | export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { |
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | "history/list", |
| 14 | 14 | "history/delete", |
| 15 | 15 | "history/load", |
| 16 | + "history/loadRemote", | |
| 16 | 17 | "history/save", |
| 17 | 18 | "history/clear", |
| 18 | 19 | "devdata/log", |
| @@ -78,6 +79,7 @@ | ||
| 78 | 79 | "didChangeSelectedProfile", |
| 79 | 80 | "didChangeSelectedOrg", |
| 80 | 81 | "tools/call", |
| 82 | + "tools/evaluatePolicy", | |
| 81 | 83 | "controlPlane/getEnvironment", |
| 82 | 84 | "controlPlane/getFreeTrialStatus", |
| 83 | 85 | "controlPlane/getModelsAddOnUpgradeUrl", |
| @@ -85,6 +87,7 @@ | ||
| 85 | 87 | "isItemTooBig", |
| 86 | 88 | "process/markAsBackgrounded", |
| 87 | 89 | "process/isBackgrounded", |
| 90 | + "process/killTerminalProcess", | |
| 88 | 91 | ]; |
| 89 | 92 | |
| 90 | 93 | // Message types to pass through from core to webview |
| @@ -12,13 +12,11 @@ | ||
| 12 | 12 | |
| 13 | 13 | export const testControlPlaneClient = new ControlPlaneClient( |
| 14 | 14 | Promise.resolve(undefined), |
| 15 | - ideSettingsPromise, | |
| 16 | - testIde.getIdeInfo(), | |
| 15 | + testIde, | |
| 17 | 16 | ); |
| 18 | 17 | |
| 19 | 18 | export const testConfigHandler = new ConfigHandler( |
| 20 | 19 | testIde, |
| 21 | - ideSettingsPromise, | |
| 22 | 20 | new LLMLogger(), |
| 23 | 21 | Promise.resolve(undefined), |
| 24 | 22 | ); |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | export enum BuiltInToolNames { |
| 2 | 2 | ReadFile = "read_file", |
| 3 | + ReadFileRange = "read_file_range", | |
| 3 | 4 | EditExistingFile = "edit_existing_file", |
| 4 | - SearchAndReplaceInFile = "search_and_replace_in_file", | |
| 5 | 5 | SingleFindAndReplace = "single_find_and_replace", |
| 6 | 6 | MultiEdit = "multi_edit", |
| 7 | 7 | ReadCurrentlyOpenFile = "read_currently_open_file", |
| @@ -26,7 +26,6 @@ | ||
| 26 | 26 | |
| 27 | 27 | export const CLIENT_TOOLS_IMPLS = [ |
| 28 | 28 | BuiltInToolNames.EditExistingFile, |
| 29 | - BuiltInToolNames.SearchAndReplaceInFile, | |
| 30 | 29 | BuiltInToolNames.SingleFindAndReplace, |
| 31 | 30 | BuiltInToolNames.MultiEdit, |
| 32 | 31 | ]; |
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; | |
| 1 | 2 | import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; |
| 2 | 3 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 3 | 4 | import { canParseUrl } from "../util/url"; |
| @@ -12,6 +13,8 @@ | ||
| 12 | 13 | import { lsToolImpl } from "./implementations/lsTool"; |
| 13 | 14 | import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; |
| 14 | 15 | import { readFileImpl } from "./implementations/readFile"; |
| 16 | + | |
| 17 | +import { readFileRangeImpl } from "./implementations/readFileRange"; | |
| 15 | 18 | import { requestRuleImpl } from "./implementations/requestRule"; |
| 16 | 19 | import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; |
| 17 | 20 | import { searchWebImpl } from "./implementations/searchWeb"; |
| @@ -85,10 +88,14 @@ | ||
| 85 | 88 | if (!client) { |
| 86 | 89 | throw new Error("MCP connection not found"); |
| 87 | 90 | } |
| 88 | - const response = await client.client.callTool({ | |
| 89 | - name: toolName, | |
| 90 | - arguments: args, | |
| 91 | - }); | |
| 91 | + const response = await client.client.callTool( | |
| 92 | + { | |
| 93 | + name: toolName, | |
| 94 | + arguments: args, | |
| 95 | + }, | |
| 96 | + CallToolResultSchema, | |
| 97 | + { timeout: client.options.timeout }, | |
| 98 | + ); | |
| 92 | 99 | |
| 93 | 100 | if (response.isError === true) { |
| 94 | 101 | throw new Error(JSON.stringify(response.content)); |
| @@ -145,6 +152,8 @@ | ||
| 145 | 152 | switch (functionName) { |
| 146 | 153 | case BuiltInToolNames.ReadFile: |
| 147 | 154 | return await readFileImpl(args, extras); |
| 155 | + case BuiltInToolNames.ReadFileRange: | |
| 156 | + return await readFileRangeImpl(args, extras); | |
| 148 | 157 | case BuiltInToolNames.CreateNewFile: |
| 149 | 158 | return await createNewFileImpl(args, extras); |
| 150 | 159 | case BuiltInToolNames.GrepSearch: |
| @@ -4,9 +4,9 @@ | ||
| 4 | 4 | export const createNewFileTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Create New File", |
| 7 | - wouldLikeTo: "create a new file at {{{ filepath }}}", | |
| 8 | - isCurrently: "creating a new file at {{{ filepath }}}", | |
| 9 | - hasAlready: "created a new file at {{{ filepath }}}", | |
| 7 | + wouldLikeTo: "create {{{ filepath }}}", | |
| 8 | + isCurrently: "creating {{{ filepath }}}", | |
| 9 | + hasAlready: "created {{{ filepath }}}", | |
| 10 | 10 | group: BUILT_IN_GROUP_NAME, |
| 11 | 11 | readonly: false, |
| 12 | 12 | isInstant: true, |
| @@ -84,4 +84,5 @@ | ||
| 84 | 84 | ["alwaysApply", "false"], |
| 85 | 85 | ], |
| 86 | 86 | }, |
| 87 | + toolCallIcon: "PencilIcon", | |
| 87 | 88 | }; |
| @@ -1,13 +1,15 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | -import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; | |
| 5 | 4 | |
| 6 | 5 | export interface EditToolArgs { |
| 7 | 6 | filepath: string; |
| 8 | 7 | changes: string; |
| 9 | 8 | } |
| 10 | 9 | |
| 10 | +export const NO_PARALLEL_TOOL_CALLING_INSTRUCTION = | |
| 11 | + "This tool CANNOT be called in parallel with other tools."; | |
| 12 | + | |
| 11 | 13 | const CHANGES_DESCRIPTION = |
| 12 | 14 | "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; |
| 13 | 15 | |
| @@ -22,7 +24,7 @@ | ||
| 22 | 24 | isInstant: false, |
| 23 | 25 | function: { |
| 24 | 26 | name: BuiltInToolNames.EditExistingFile, |
| 25 | - description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, | |
| 27 | + description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSTRUCTION}`, | |
| 26 | 28 | parameters: { |
| 27 | 29 | type: "object", |
| 28 | 30 | required: ["filepath", "changes"], |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | displayTitle: "Read URL", |
| 7 | 7 | wouldLikeTo: "fetch {{{ url }}}", |
| 8 | 8 | isCurrently: "fetching {{{ url }}}", |
| 9 | - hasAlready: "viewed {{{ url }}}", | |
| 9 | + hasAlready: "fetched {{{ url }}}", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, |
| 31 | 31 | exampleArgs: [["url", "https://example.com"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "GlobeAltIcon", | |
| 33 | 34 | }; |
| @@ -4,16 +4,16 @@ | ||
| 4 | 4 | export const globSearchTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Glob File Search", |
| 7 | - wouldLikeTo: 'find file matches for "{{{ pattern }}}"', | |
| 8 | - isCurrently: 'finding file matches for "{{{ pattern }}}"', | |
| 9 | - hasAlready: 'retrieved file matches for "{{{ pattern }}}"', | |
| 7 | + wouldLikeTo: 'search for files like "{{{ pattern }}}"', | |
| 8 | + isCurrently: 'searching for files like "{{{ pattern }}}"', | |
| 9 | + hasAlready: 'searched for files like "{{{ pattern }}}"', | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.FileGlobSearch, |
| 15 | 15 | description: |
| 16 | - "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns", | |
| 16 | + "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["pattern"], |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, |
| 31 | 31 | exampleArgs: [["pattern", "*.py"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "MagnifyingGlassIcon", | |
| 33 | 34 | }; |
| @@ -4,16 +4,16 @@ | ||
| 4 | 4 | export const grepSearchTool: Tool = { |
| 5 | 5 | type: "function", |
| 6 | 6 | displayTitle: "Grep Search", |
| 7 | - wouldLikeTo: 'search for "{{{ query }}}" in the repository', | |
| 8 | - isCurrently: 'getting search results for "{{{ query }}}"', | |
| 9 | - hasAlready: 'retrieved search results for "{{{ query }}}"', | |
| 7 | + wouldLikeTo: 'search for "{{{ query }}}"', | |
| 8 | + isCurrently: 'searching for "{{{ query }}}"', | |
| 9 | + hasAlready: 'searched for "{{{ query }}}"', | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.GrepSearch, |
| 15 | 15 | description: |
| 16 | - "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries", | |
| 16 | + "Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["query"], |
| @@ -31,4 +31,5 @@ | ||
| 31 | 31 | prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, |
| 32 | 32 | exampleArgs: [["query", ".*main_services.*"]], |
| 33 | 33 | }, |
| 34 | + toolCallIcon: "MagnifyingGlassIcon", | |
| 34 | 35 | }; |
| @@ -9,9 +9,10 @@ | ||
| 9 | 9 | export { multiEditTool } from "./multiEdit"; |
| 10 | 10 | export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile"; |
| 11 | 11 | export { readFileTool } from "./readFile"; |
| 12 | + | |
| 13 | +export { readFileRangeTool } from "./readFileRange"; | |
| 12 | 14 | export { requestRuleTool } from "./requestRule"; |
| 13 | 15 | export { runTerminalCommandTool } from "./runTerminalCommand"; |
| 14 | -export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile"; | |
| 15 | 16 | export { searchWebTool } from "./searchWeb"; |
| 16 | 17 | export { singleFindAndReplaceTool } from "./singleFindAndReplace"; |
| 17 | 18 | export { viewDiffTool } from "./viewDiff"; |
| @@ -5,9 +5,9 @@ | ||
| 5 | 5 | export const lsTool: Tool = { |
| 6 | 6 | type: "function", |
| 7 | 7 | displayTitle: "ls", |
| 8 | - wouldLikeTo: "list files and folders in {{{ dirPath }}}", | |
| 9 | - isCurrently: "listing files and folders in {{{ dirPath }}}", | |
| 10 | - hasAlready: "listed files and folders in {{{ dirPath }}}", | |
| 8 | + wouldLikeTo: "list files in {{{ dirPath }}}", | |
| 9 | + isCurrently: "listing files in {{{ dirPath }}}", | |
| 10 | + hasAlready: "listed files in {{{ dirPath }}}", | |
| 11 | 11 | readonly: true, |
| 12 | 12 | isInstant: true, |
| 13 | 13 | group: BUILT_IN_GROUP_NAME, |
| @@ -38,4 +38,5 @@ | ||
| 38 | 38 | ["recursive", "false"], |
| 39 | 39 | ], |
| 40 | 40 | }, |
| 41 | + toolCallIcon: "FolderIcon", | |
| 41 | 42 | }; |
| @@ -1,5 +1,7 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; | |
| 4 | +import { singleFindAndReplaceTool } from "./singleFindAndReplace"; | |
| 3 | 5 | |
| 4 | 6 | export interface EditOperation { |
| 5 | 7 | old_string: string; |
| @@ -23,59 +25,35 @@ | ||
| 23 | 25 | isInstant: false, |
| 24 | 26 | function: { |
| 25 | 27 | name: BuiltInToolNames.MultiEdit, |
| 26 | - description: `This is a tool for making multiple edits to a single file in one operation. It | |
| 27 | -is built on top of the single find and replace tool and allows you to perform multiple | |
| 28 | -find-and-replace operations efficiently. Prefer this tool over the single find and replace tool | |
| 29 | -when you need to make multiple edits to the same file. | |
| 30 | - | |
| 31 | -Before using this tool: | |
| 32 | - | |
| 33 | -1. Use the read_file tool to understand the file's contents and context | |
| 34 | -2. Verify the directory path is correct | |
| 35 | - | |
| 36 | -To make multiple file edits, provide the following: | |
| 37 | - | |
| 38 | -1. filepath: The path to the file to modify (relative to the root of the workspace) | |
| 28 | + description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently. | |
| 29 | +Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file. | |
| 30 | + | |
| 31 | +To make multiple edits to a file, provide the following: | |
| 32 | +1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct) | |
| 39 | 33 | 2. edits: An array of edit operations to perform, where each edit contains: |
| 40 | - - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) | |
| 34 | + - old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation) | |
| 41 | 35 | - new_string: The edited text to replace the old_string |
| 42 | 36 | - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false. |
| 43 | 37 | |
| 44 | 38 | IMPORTANT: |
| 45 | 39 | - All edits are applied in sequence, in the order they are provided |
| 46 | -- Each edit operates on the result of the previous edit | |
| 47 | -- All edits must be valid for the operation to succeed - if any edit fails, | |
| 48 | -none will be applied | |
| 49 | -- This tool is ideal when you need to make several changes to different parts | |
| 50 | -of the same file | |
| 40 | +- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations | |
| 41 | +- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied | |
| 42 | +- This tool is ideal when you need to make several changes to different parts of the same file | |
| 51 | 43 | |
| 52 | 44 | CRITICAL REQUIREMENTS: |
| 53 | - | |
| 54 | -1. All edits follow the same requirements as the single find and replace tool | |
| 55 | -2. The edits are atomic - either all succeed or none are applied | |
| 56 | -3. Plan your edits carefully to avoid conflicts between sequential operations | |
| 57 | - | |
| 58 | -WARNING: | |
| 59 | - | |
| 60 | -- The tool will fail if edits.old_string doesn't match the file contents | |
| 61 | -exactly (including whitespace) | |
| 62 | -- The tool will fail if edits.old_string and edits.new_string are the same | |
| 63 | -- Since edits are applied in sequence, ensure that earlier edits don't affect | |
| 64 | -the text that later edits are trying to find | |
| 65 | - | |
| 66 | -When making edits: | |
| 67 | - | |
| 45 | +1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. | |
| 46 | +2. ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION} | |
| 47 | +3. When making edits: | |
| 68 | 48 | - Ensure all edits result in idiomatic, correct code |
| 69 | 49 | - Do not leave the code in a broken state |
| 70 | -- Only use emojis if the user explicitly requests it. Avoid adding emojis to | |
| 71 | -files unless asked. | |
| 72 | -- Use replace_all for replacing and renaming strings across the file. This | |
| 73 | -parameter is useful if you want to rename a variable for instance. | |
| 74 | - | |
| 75 | -If you want to create a new file, use: | |
| 76 | -- A new file path | |
| 77 | -- First edit: empty old_string and the new file's contents as new_string | |
| 78 | -- Subsequent edits are not allowed - there is no need since you are creating`, | |
| 50 | +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked | |
| 51 | +- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance | |
| 52 | + | |
| 53 | +WARNINGS: | |
| 54 | +- If earlier edits affect the text that later edits are trying to find, files can become mangled | |
| 55 | +- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace) | |
| 56 | +- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`, | |
| 79 | 57 | parameters: { |
| 80 | 58 | type: "object", |
| 81 | 59 | required: ["filepath", "edits"], |
| @@ -95,16 +73,18 @@ | ||
| 95 | 73 | properties: { |
| 96 | 74 | old_string: { |
| 97 | 75 | type: "string", |
| 98 | - description: "The text to replace", | |
| 76 | + description: | |
| 77 | + "The text to replace (exact match including whitespace/indentation)", | |
| 99 | 78 | }, |
| 100 | 79 | new_string: { |
| 101 | 80 | type: "string", |
| 102 | - description: "The text to replace it with", | |
| 81 | + description: | |
| 82 | + "The text to replace it with. MUST be different than old_string.", | |
| 103 | 83 | }, |
| 104 | 84 | replace_all: { |
| 105 | 85 | type: "boolean", |
| 106 | 86 | description: |
| 107 | - "Replace all occurrences of old_string (default false)", | |
| 87 | + "Replace all occurrences of old_string (default false) in the file", | |
| 108 | 88 | }, |
| 109 | 89 | }, |
| 110 | 90 | }, |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | displayTitle: "Read Currently Open File", |
| 7 | 7 | wouldLikeTo: "read the current file", |
| 8 | 8 | isCurrently: "reading the current file", |
| 9 | - hasAlready: "viewed the current file", | |
| 9 | + hasAlready: "read the current file", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| @@ -24,4 +24,5 @@ | ||
| 24 | 24 | prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. |
| 25 | 25 | If the user is asking about a file and you don't see any code, use this to check the current file`, |
| 26 | 26 | }, |
| 27 | + toolCallIcon: "DocumentTextIcon", | |
| 27 | 28 | }; |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | displayTitle: "Read File", |
| 7 | 7 | wouldLikeTo: "read {{{ filepath }}}", |
| 8 | 8 | isCurrently: "reading {{{ filepath }}}", |
| 9 | - hasAlready: "viewed {{{ filepath }}}", | |
| 9 | + hasAlready: "read {{{ filepath }}}", | |
| 10 | 10 | readonly: true, |
| 11 | 11 | isInstant: true, |
| 12 | 12 | group: BUILT_IN_GROUP_NAME, |
| @@ -31,4 +31,5 @@ | ||
| 31 | 31 | exampleArgs: [["filepath", "path/to/the_file.txt"]], |
| 32 | 32 | }, |
| 33 | 33 | defaultToolPolicy: "allowedWithoutPermission", |
| 34 | + toolCallIcon: "DocumentIcon", | |
| 34 | 35 | }; |
| @@ -0,0 +1,52 @@ | ||
| 1 | +import { Tool } from "../.."; | |
| 2 | +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | + | |
| 4 | +export const readFileRangeTool: Tool = { | |
| 5 | + type: "function", | |
| 6 | + displayTitle: "Read File Range", | |
| 7 | + wouldLikeTo: | |
| 8 | + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 9 | + isCurrently: | |
| 10 | + "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 11 | + hasAlready: | |
| 12 | + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", | |
| 13 | + readonly: true, | |
| 14 | + isInstant: true, | |
| 15 | + group: BUILT_IN_GROUP_NAME, | |
| 16 | + function: { | |
| 17 | + name: BuiltInToolNames.ReadFileRange, | |
| 18 | + description: | |
| 19 | + "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.", | |
| 20 | + parameters: { | |
| 21 | + type: "object", | |
| 22 | + required: ["filepath", "startLine", "endLine"], | |
| 23 | + properties: { | |
| 24 | + filepath: { | |
| 25 | + type: "string", | |
| 26 | + description: | |
| 27 | + "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", | |
| 28 | + }, | |
| 29 | + startLine: { | |
| 30 | + type: "number", | |
| 31 | + description: | |
| 32 | + "The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line", | |
| 33 | + }, | |
| 34 | + endLine: { | |
| 35 | + type: "number", | |
| 36 | + description: | |
| 37 | + "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", | |
| 38 | + }, | |
| 39 | + }, | |
| 40 | + }, | |
| 41 | + }, | |
| 42 | + systemMessageDescription: { | |
| 43 | + 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:`, | |
| 44 | + exampleArgs: [ | |
| 45 | + ["filepath", "path/to/the_file.txt"], | |
| 46 | + ["startLine", 10], | |
| 47 | + ["endLine", 20], | |
| 48 | + ], | |
| 49 | + }, | |
| 50 | + defaultToolPolicy: "allowedWithoutPermission", | |
| 51 | + toolCallIcon: "DocumentIcon", | |
| 52 | +}; |
| @@ -1,6 +1,10 @@ | ||
| 1 | 1 | import os from "os"; |
| 2 | 2 | import { Tool } from "../.."; |
| 3 | 3 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 4 | +import { | |
| 5 | + evaluateTerminalCommandSecurity, | |
| 6 | + ToolPolicy, | |
| 7 | +} from "@continuedev/terminal-security"; | |
| 4 | 8 | |
| 5 | 9 | /** |
| 6 | 10 | * Get the preferred shell for the current platform |
| @@ -56,6 +60,15 @@ | ||
| 56 | 60 | }, |
| 57 | 61 | }, |
| 58 | 62 | defaultToolPolicy: "allowedWithPermission", |
| 63 | + evaluateToolCallPolicy: ( | |
| 64 | + basePolicy: ToolPolicy, | |
| 65 | + parsedArgs: Record<string, unknown>, | |
| 66 | + ): ToolPolicy => { | |
| 67 | + return evaluateTerminalCommandSecurity( | |
| 68 | + basePolicy, | |
| 69 | + parsedArgs.command as string, | |
| 70 | + ); | |
| 71 | + }, | |
| 59 | 72 | systemMessageDescription: { |
| 60 | 73 | prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool |
| 61 | 74 | ${RUN_COMMAND_NOTES} |
| @@ -1,112 +0,0 @@ | ||
| 1 | -import { Tool } from "../.."; | |
| 2 | -import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; | |
| 3 | - | |
| 4 | -export interface SearchAndReplaceInFileArgs { | |
| 5 | - filepath: string; | |
| 6 | - diffs: string[]; | |
| 7 | -} | |
| 8 | - | |
| 9 | -// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` | |
| 10 | -export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = | |
| 11 | - "Note this tool CANNOT be called in parallel."; | |
| 12 | - | |
| 13 | -const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH | |
| 14 | -[exact content to find] | |
| 15 | -======= | |
| 16 | -[new content to replace with] | |
| 17 | -+++++++ REPLACE`; | |
| 18 | - | |
| 19 | -const SEARCH_AND_REPLACE_RULES = `Critical rules: | |
| 20 | -1. SEARCH content must match the associated file section to find EXACTLY: | |
| 21 | - * Match character-for-character including whitespace, indentation, line endings | |
| 22 | - * Include all comments, docstrings, etc. | |
| 23 | -2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. | |
| 24 | - * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. | |
| 25 | - * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. | |
| 26 | - * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. | |
| 27 | -3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. | |
| 28 | -4. Keep SEARCH/REPLACE blocks concise: | |
| 29 | - * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. | |
| 30 | - * Include just the changing lines, and a few surrounding lines if needed for uniqueness. | |
| 31 | - * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. | |
| 32 | - * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. | |
| 33 | -5. Splitting up tool calls: | |
| 34 | - * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls | |
| 35 | - * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls | |
| 36 | - * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] | |
| 37 | -6. Special operations: | |
| 38 | - * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) | |
| 39 | - * To delete code: Use empty REPLACE section | |
| 40 | -7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`; | |
| 41 | - | |
| 42 | -const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: | |
| 43 | -\`\`\` | |
| 44 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 45 | -\`\`\` | |
| 46 | - | |
| 47 | -${SEARCH_AND_REPLACE_RULES} | |
| 48 | - | |
| 49 | -Usage: | |
| 50 | -\`\`\` | |
| 51 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 52 | - | |
| 53 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 54 | -\`\`\` | |
| 55 | - | |
| 56 | -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`; | |
| 57 | - | |
| 58 | -/** | |
| 59 | - * This tool is in an experimental state. | |
| 60 | - * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 | |
| 61 | - */ | |
| 62 | -export const searchAndReplaceInFileTool: Tool = { | |
| 63 | - type: "function", | |
| 64 | - displayTitle: "Edit File", | |
| 65 | - wouldLikeTo: "edit {{{ filepath }}}", | |
| 66 | - isCurrently: "editing {{{ filepath }}}", | |
| 67 | - hasAlready: "edited {{{ filepath }}}", | |
| 68 | - group: BUILT_IN_GROUP_NAME, | |
| 69 | - readonly: false, | |
| 70 | - isInstant: false, | |
| 71 | - function: { | |
| 72 | - name: BuiltInToolNames.SearchAndReplaceInFile, | |
| 73 | - description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, | |
| 74 | - parameters: { | |
| 75 | - type: "object", | |
| 76 | - required: ["filepath", "diffs"], | |
| 77 | - properties: { | |
| 78 | - filepath: { | |
| 79 | - type: "string", | |
| 80 | - description: `The path of the file to modify, relative to the root of the workspace.`, | |
| 81 | - }, | |
| 82 | - diffs: { | |
| 83 | - type: "array", | |
| 84 | - items: { | |
| 85 | - type: "string", | |
| 86 | - }, | |
| 87 | - description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION, | |
| 88 | - }, | |
| 89 | - }, | |
| 90 | - }, | |
| 91 | - }, | |
| 92 | - systemMessageDescription: { | |
| 93 | - prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. | |
| 94 | -Each block should follow this format: | |
| 95 | -${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} | |
| 96 | - | |
| 97 | -${SEARCH_AND_REPLACE_RULES} | |
| 98 | - | |
| 99 | - For example, you could respond with:`, | |
| 100 | - exampleArgs: [ | |
| 101 | - ["filepath", "path/to/file.ts"], | |
| 102 | - [ | |
| 103 | - "diffs", | |
| 104 | - `[ | |
| 105 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}", | |
| 106 | -"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}" | |
| 107 | -]`, | |
| 108 | - ], | |
| 109 | - ], | |
| 110 | - }, | |
| 111 | - defaultToolPolicy: "allowedWithPermission", | |
| 112 | -}; |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, |
| 31 | 31 | exampleArgs: [["query", "What is the current weather in San Francisco?"]], |
| 32 | 32 | }, |
| 33 | + toolCallIcon: "GlobeAltIcon", | |
| 33 | 34 | }; |
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { Tool } from "../.."; |
| 2 | 2 | import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; |
| 3 | +import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; | |
| 3 | 4 | |
| 4 | 5 | export interface SingleFindAndReplaceArgs { |
| 5 | 6 | filepath: string; |
| @@ -11,39 +12,26 @@ | ||
| 11 | 12 | export const singleFindAndReplaceTool: Tool = { |
| 12 | 13 | type: "function", |
| 13 | 14 | displayTitle: "Find and Replace", |
| 14 | - wouldLikeTo: "find and replace in {{{ filepath }}}", | |
| 15 | - isCurrently: "finding and replacing in {{{ filepath }}}", | |
| 16 | - hasAlready: "found and replaced in {{{ filepath }}}", | |
| 15 | + wouldLikeTo: "edit {{{ filepath }}}", | |
| 16 | + isCurrently: "editing {{{ filepath }}}", | |
| 17 | + hasAlready: "edited {{{ filepath }}}", | |
| 17 | 18 | group: BUILT_IN_GROUP_NAME, |
| 18 | 19 | readonly: false, |
| 19 | 20 | isInstant: false, |
| 20 | 21 | function: { |
| 21 | 22 | name: BuiltInToolNames.SingleFindAndReplace, |
| 22 | - description: `Performs exact string replacements in files. | |
| 23 | - | |
| 24 | -Usage: | |
| 25 | - | |
| 26 | -- You must use your \`read_file\` tool at least once in the conversation before | |
| 27 | -editing. This tool will error if you attempt an edit without reading the file. | |
| 28 | - | |
| 29 | -- When editing text from read_file tool output, ensure you preserve the exact | |
| 30 | -indentation (tabs/spaces) as it appears AFTER the line number prefix. The line | |
| 31 | -number prefix format is: spaces + line number + tab. Everything after that tab | |
| 32 | -is the actual file content to match. Never include any part of the line number | |
| 33 | -prefix in the old_string or new_string. | |
| 34 | - | |
| 35 | -- ALWAYS prefer editing existing files in the codebase. NEVER write new files | |
| 36 | -unless explicitly required. | |
| 37 | - | |
| 38 | -- Only use emojis if the user explicitly requests it. Avoid adding emojis to | |
| 39 | -files unless asked. | |
| 40 | - | |
| 41 | -- The edit will FAIL if \`old_string\` is not unique in the file. Either provide | |
| 42 | -a larger string with more surrounding context to make it unique or use | |
| 43 | -\`replace_all\` to change every instance of \`old_string\`. | |
| 44 | - | |
| 45 | -- Use \`replace_all\` for replacing and renaming strings across the file. This | |
| 46 | -parameter is useful if you want to rename a variable for instance.`, | |
| 23 | + description: `Performs exact string replacements in a file. | |
| 24 | + | |
| 25 | +IMPORTANT: | |
| 26 | +- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it. | |
| 27 | +- ${NO_PARALLEL_TOOL_CALLING_INSTRUCTION} | |
| 28 | +- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation. | |
| 29 | +- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. | |
| 30 | +- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance. | |
| 31 | + | |
| 32 | +WARNINGS: | |
| 33 | +- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. | |
| 34 | +- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`, | |
| 47 | 35 | parameters: { |
| 48 | 36 | type: "object", |
| 49 | 37 | required: ["filepath", "old_string", "new_string"], |
| @@ -55,12 +43,13 @@ | ||
| 55 | 43 | }, |
| 56 | 44 | old_string: { |
| 57 | 45 | type: "string", |
| 58 | - description: "The text to replace", | |
| 46 | + description: | |
| 47 | + "The text to replace - must be exact including whitespace/indentation", | |
| 59 | 48 | }, |
| 60 | 49 | new_string: { |
| 61 | 50 | type: "string", |
| 62 | 51 | description: |
| 63 | - "The text to replace it with (must be different from old_string)", | |
| 52 | + "The text to replace it with (MUST be different from old_string)", | |
| 64 | 53 | }, |
| 65 | 54 | replace_all: { |
| 66 | 55 | type: "boolean", |
| @@ -23,4 +23,5 @@ | ||
| 23 | 23 | prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, |
| 24 | 24 | }, |
| 25 | 25 | defaultToolPolicy: "allowedWithoutPermission", |
| 26 | + toolCallIcon: "CodeBracketIcon", | |
| 26 | 27 | }; |
| @@ -23,4 +23,5 @@ | ||
| 23 | 23 | prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, |
| 24 | 24 | }, |
| 25 | 25 | defaultToolPolicy: "allowedWithPermission", |
| 26 | + toolCallIcon: "MapIcon", | |
| 26 | 27 | }; |
| @@ -30,4 +30,5 @@ | ||
| 30 | 30 | exampleArgs: [["directory_path", "path/to/subdirectory"]], |
| 31 | 31 | }, |
| 32 | 32 | defaultToolPolicy: "allowedWithPermission", |
| 33 | + toolCallIcon: "FolderOpenIcon", | |
| 33 | 34 | }; |
| @@ -0,0 +1,204 @@ | ||
| 1 | +import { expect, test, vi } from "vitest"; | |
| 2 | +import { ToolExtras } from "../.."; | |
| 3 | +import { readFileRangeImpl } from "./readFileRange"; | |
| 4 | + | |
| 5 | +// Mock the dependencies | |
| 6 | +vi.mock("../../util/ideUtils", () => ({ | |
| 7 | + resolveRelativePathInDir: vi.fn(), | |
| 8 | +})); | |
| 9 | + | |
| 10 | +vi.mock("../../util/uri", () => ({ | |
| 11 | + getUriPathBasename: vi.fn(), | |
| 12 | +})); | |
| 13 | + | |
| 14 | +vi.mock("./readFileLimit", () => ({ | |
| 15 | + throwIfFileExceedsHalfOfContext: vi.fn(), | |
| 16 | +})); | |
| 17 | + | |
| 18 | +test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => { | |
| 19 | + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); | |
| 20 | + const { getUriPathBasename } = await import("../../util/uri"); | |
| 21 | + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); | |
| 22 | + | |
| 23 | + // Mock the utility functions | |
| 24 | + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); | |
| 25 | + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); | |
| 26 | + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); | |
| 27 | + | |
| 28 | + // Test case 1: Start line beyond end of file | |
| 29 | + const mockIdeOutOfBounds = { | |
| 30 | + readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string | |
| 31 | + }; | |
| 32 | + | |
| 33 | + const mockExtras1 = { | |
| 34 | + ide: mockIdeOutOfBounds, | |
| 35 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 36 | + } as unknown as ToolExtras; | |
| 37 | + | |
| 38 | + const result1 = await readFileRangeImpl( | |
| 39 | + { | |
| 40 | + filepath: "test.txt", | |
| 41 | + startLine: 100, // Beyond end of file | |
| 42 | + endLine: 105, | |
| 43 | + }, | |
| 44 | + mockExtras1, | |
| 45 | + ); | |
| 46 | + | |
| 47 | + expect(result1).toHaveLength(1); | |
| 48 | + expect(result1[0].content).toBe(""); | |
| 49 | + expect(result1[0].description).toBe("test.txt (lines 100-105)"); | |
| 50 | + | |
| 51 | + // Test case 2: End line beyond end of file | |
| 52 | + const mockIdePartialRange = { | |
| 53 | + readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content | |
| 54 | + }; | |
| 55 | + | |
| 56 | + const mockExtras2 = { | |
| 57 | + ide: mockIdePartialRange, | |
| 58 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 59 | + } as unknown as ToolExtras; | |
| 60 | + | |
| 61 | + const result2 = await readFileRangeImpl( | |
| 62 | + { | |
| 63 | + filepath: "test.txt", | |
| 64 | + startLine: 5, | |
| 65 | + endLine: 100, // Beyond end of file | |
| 66 | + }, | |
| 67 | + mockExtras2, | |
| 68 | + ); | |
| 69 | + | |
| 70 | + expect(result2).toHaveLength(1); | |
| 71 | + expect(result2[0].content).toBe("line5\nline6"); | |
| 72 | + expect(result2[0].description).toBe("test.txt (lines 5-100)"); | |
| 73 | + | |
| 74 | + // Verify that IDE methods were called with correct 0-based ranges | |
| 75 | + expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith( | |
| 76 | + "file:///test.txt", | |
| 77 | + { | |
| 78 | + start: { line: 99, character: 0 }, // 100 - 1 | |
| 79 | + end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1 | |
| 80 | + }, | |
| 81 | + ); | |
| 82 | + | |
| 83 | + expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith( | |
| 84 | + "file:///test.txt", | |
| 85 | + { | |
| 86 | + start: { line: 4, character: 0 }, // 5 - 1 | |
| 87 | + end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1 | |
| 88 | + }, | |
| 89 | + ); | |
| 90 | +}); | |
| 91 | + | |
| 92 | +test("readFileRangeImpl validates line number constraints", async () => { | |
| 93 | + const mockExtras = { | |
| 94 | + ide: { readRangeInFile: vi.fn(), readFile: vi.fn() }, | |
| 95 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 96 | + } as unknown as ToolExtras; | |
| 97 | + | |
| 98 | + // Test startLine < 1 (invalid) | |
| 99 | + await expect( | |
| 100 | + readFileRangeImpl( | |
| 101 | + { | |
| 102 | + filepath: "test.txt", | |
| 103 | + startLine: 0, | |
| 104 | + endLine: 5, | |
| 105 | + }, | |
| 106 | + mockExtras, | |
| 107 | + ), | |
| 108 | + ).rejects.toThrow("startLine must be 1 or greater"); | |
| 109 | + | |
| 110 | + // Test negative startLine (no longer supported) | |
| 111 | + await expect( | |
| 112 | + readFileRangeImpl( | |
| 113 | + { | |
| 114 | + filepath: "test.txt", | |
| 115 | + startLine: -1, | |
| 116 | + endLine: 5, | |
| 117 | + }, | |
| 118 | + mockExtras, | |
| 119 | + ), | |
| 120 | + ).rejects.toThrow("Negative line numbers are not supported"); | |
| 121 | + | |
| 122 | + // Test endLine < 1 (invalid) | |
| 123 | + await expect( | |
| 124 | + readFileRangeImpl( | |
| 125 | + { | |
| 126 | + filepath: "test.txt", | |
| 127 | + startLine: 1, | |
| 128 | + endLine: 0, | |
| 129 | + }, | |
| 130 | + mockExtras, | |
| 131 | + ), | |
| 132 | + ).rejects.toThrow("endLine must be 1 or greater"); | |
| 133 | + | |
| 134 | + // Test negative endLine (no longer supported) | |
| 135 | + await expect( | |
| 136 | + readFileRangeImpl( | |
| 137 | + { | |
| 138 | + filepath: "test.txt", | |
| 139 | + startLine: 1, | |
| 140 | + endLine: -1, | |
| 141 | + }, | |
| 142 | + mockExtras, | |
| 143 | + ), | |
| 144 | + ).rejects.toThrow("Negative line numbers are not supported"); | |
| 145 | + | |
| 146 | + // Test endLine < startLine | |
| 147 | + await expect( | |
| 148 | + readFileRangeImpl( | |
| 149 | + { | |
| 150 | + filepath: "test.txt", | |
| 151 | + startLine: 10, | |
| 152 | + endLine: 5, | |
| 153 | + }, | |
| 154 | + mockExtras, | |
| 155 | + ), | |
| 156 | + ).rejects.toThrow( | |
| 157 | + "endLine (5) must be greater than or equal to startLine (10)", | |
| 158 | + ); | |
| 159 | +}); | |
| 160 | + | |
| 161 | +test("readFileRangeImpl handles normal ranges correctly", async () => { | |
| 162 | + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); | |
| 163 | + const { getUriPathBasename } = await import("../../util/uri"); | |
| 164 | + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); | |
| 165 | + | |
| 166 | + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); | |
| 167 | + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); | |
| 168 | + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); | |
| 169 | + | |
| 170 | + const mockIde = { | |
| 171 | + readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"), | |
| 172 | + }; | |
| 173 | + | |
| 174 | + const mockExtras = { | |
| 175 | + ide: mockIde, | |
| 176 | + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, | |
| 177 | + } as unknown as ToolExtras; | |
| 178 | + | |
| 179 | + const result = await readFileRangeImpl( | |
| 180 | + { | |
| 181 | + filepath: "src/test.py", | |
| 182 | + startLine: 2, | |
| 183 | + endLine: 4, | |
| 184 | + }, | |
| 185 | + mockExtras, | |
| 186 | + ); | |
| 187 | + | |
| 188 | + expect(result).toHaveLength(1); | |
| 189 | + expect(result[0]).toEqual({ | |
| 190 | + name: "test.txt", | |
| 191 | + description: "src/test.py (lines 2-4)", | |
| 192 | + content: "line2\nline3\nline4", | |
| 193 | + uri: { | |
| 194 | + type: "file", | |
| 195 | + value: "file:///test.txt", | |
| 196 | + }, | |
| 197 | + }); | |
| 198 | + | |
| 199 | + // Verify correct 0-based conversion | |
| 200 | + expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", { | |
| 201 | + start: { line: 1, character: 0 }, // 2 - 1 | |
| 202 | + end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1 | |
| 203 | + }); | |
| 204 | +}); |
| @@ -0,0 +1,68 @@ | ||
| 1 | +import { resolveRelativePathInDir } from "../../util/ideUtils"; | |
| 2 | +import { getUriPathBasename } from "../../util/uri"; | |
| 3 | + | |
| 4 | +import { ToolImpl } from "."; | |
| 5 | +import { getNumberArg, getStringArg } from "../parseArgs"; | |
| 6 | +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; | |
| 7 | + | |
| 8 | +export const readFileRangeImpl: ToolImpl = async (args, extras) => { | |
| 9 | + const filepath = getStringArg(args, "filepath"); | |
| 10 | + const startLine = getNumberArg(args, "startLine"); | |
| 11 | + const endLine = getNumberArg(args, "endLine"); | |
| 12 | + | |
| 13 | + // Validate that line numbers are positive integers | |
| 14 | + if (startLine < 1) { | |
| 15 | + throw new Error( | |
| 16 | + "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", | |
| 17 | + ); | |
| 18 | + } | |
| 19 | + if (endLine < 1) { | |
| 20 | + throw new Error( | |
| 21 | + "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", | |
| 22 | + ); | |
| 23 | + } | |
| 24 | + if (endLine < startLine) { | |
| 25 | + throw new Error( | |
| 26 | + `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, | |
| 27 | + ); | |
| 28 | + } | |
| 29 | + | |
| 30 | + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); | |
| 31 | + if (!firstUriMatch) { | |
| 32 | + throw new Error( | |
| 33 | + `File "${filepath}" does not exist. You might want to check the path and try again.`, | |
| 34 | + ); | |
| 35 | + } | |
| 36 | + | |
| 37 | + // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) | |
| 38 | + const content = await extras.ide.readRangeInFile(firstUriMatch, { | |
| 39 | + start: { | |
| 40 | + line: startLine - 1, // Convert from 1-based to 0-based | |
| 41 | + character: 0, | |
| 42 | + }, | |
| 43 | + end: { | |
| 44 | + line: endLine - 1, // Convert from 1-based to 0-based | |
| 45 | + character: Number.MAX_SAFE_INTEGER, // Read to end of line | |
| 46 | + }, | |
| 47 | + }); | |
| 48 | + | |
| 49 | + await throwIfFileExceedsHalfOfContext( | |
| 50 | + filepath, | |
| 51 | + content, | |
| 52 | + extras.config.selectedModelByRole.chat, | |
| 53 | + ); | |
| 54 | + | |
| 55 | + const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; | |
| 56 | + | |
| 57 | + return [ | |
| 58 | + { | |
| 59 | + name: getUriPathBasename(firstUriMatch), | |
| 60 | + description: rangeDescription, | |
| 61 | + content, | |
| 62 | + uri: { | |
| 63 | + type: "file", | |
| 64 | + value: firstUriMatch, | |
| 65 | + }, | |
| 66 | + }, | |
| 67 | + ]; | |
| 68 | +}; |
| @@ -0,0 +1,60 @@ | ||
| 1 | +import { expect, test } from "vitest"; | |
| 2 | +import { getNumberArg } from "../parseArgs"; | |
| 3 | + | |
| 4 | +test("readFileRange should validate positive line number arguments", () => { | |
| 5 | + // Test positive startLine validation | |
| 6 | + expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow(); | |
| 7 | + expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow(); | |
| 8 | + expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow(); | |
| 9 | + | |
| 10 | + // Test positive endLine validation | |
| 11 | + expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow(); | |
| 12 | + expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow(); | |
| 13 | + expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow(); | |
| 14 | + | |
| 15 | + // Test missing arguments | |
| 16 | + expect(() => getNumberArg({}, "startLine")).toThrow( | |
| 17 | + "Argument `startLine` is required (type number)", | |
| 18 | + ); | |
| 19 | + expect(() => getNumberArg({}, "endLine")).toThrow( | |
| 20 | + "Argument `endLine` is required (type number)", | |
| 21 | + ); | |
| 22 | + | |
| 23 | + // Test invalid arguments | |
| 24 | + expect(() => | |
| 25 | + getNumberArg({ startLine: "not-a-number" }, "startLine"), | |
| 26 | + ).toThrow("Argument `startLine` must be a valid number"); | |
| 27 | + expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow( | |
| 28 | + "Argument `endLine` must be a valid number", | |
| 29 | + ); | |
| 30 | +}); | |
| 31 | + | |
| 32 | +test("readFileRange should handle line number conversion", () => { | |
| 33 | + // Test that our parsing function converts correctly | |
| 34 | + expect(getNumberArg({ line: 1 }, "line")).toBe(1); | |
| 35 | + expect(getNumberArg({ line: "5" }, "line")).toBe(5); | |
| 36 | + expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor | |
| 37 | + expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor | |
| 38 | +}); | |
| 39 | + | |
| 40 | +test("readFileRange parses negative numbers (validation happens in implementation)", () => { | |
| 41 | + // The parseArgs function should parse negative numbers correctly | |
| 42 | + // but the implementation will reject them with helpful error messages | |
| 43 | + expect(getNumberArg({ line: -1 }, "line")).toBe(-1); | |
| 44 | + expect(getNumberArg({ line: -10 }, "line")).toBe(-10); | |
| 45 | + expect(getNumberArg({ line: "-5" }, "line")).toBe(-5); | |
| 46 | +}); | |
| 47 | + | |
| 48 | +test("readFileRange handles out-of-bounds ranges gracefully", () => { | |
| 49 | + // IDE implementations handle out-of-bounds gracefully: | |
| 50 | + // - VS Code: Uses array.slice() which handles out-of-bounds gracefully | |
| 51 | + // - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds | |
| 52 | + // Both return empty content or available content without throwing errors | |
| 53 | + | |
| 54 | + expect(() => { | |
| 55 | + const startLine = getNumberArg({ startLine: 1000 }, "startLine"); | |
| 56 | + const endLine = getNumberArg({ endLine: 2000 }, "endLine"); | |
| 57 | + expect(startLine).toBe(1000); | |
| 58 | + expect(endLine).toBe(2000); | |
| 59 | + }).not.toThrow(); | |
| 60 | +}); |
| @@ -1,474 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import * as childProcess from "node:child_process"; | |
| 3 | -import * as fs from "node:fs"; | |
| 4 | -import * as os from "node:os"; | |
| 5 | -import * as path from "node:path"; | |
| 6 | -import { IDE, ToolExtras } from "../.."; | |
| 7 | -import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; | |
| 8 | -import { runTerminalCommandImpl } from "./runTerminalCommand"; | |
| 9 | - | |
| 10 | -// We're using real child processes, so ensure these aren't mocked | |
| 11 | -jest.unmock("node:child_process"); | |
| 12 | -jest.unmock("node:util"); | |
| 13 | - | |
| 14 | -describe("runTerminalCommandImpl", () => { | |
| 15 | - // Setup mocks and spies | |
| 16 | - const mockGetIdeInfo = jest.fn(); | |
| 17 | - const mockGetWorkspaceDirs = jest.fn(); | |
| 18 | - const mockOnPartialOutput = jest.fn(); | |
| 19 | - const mockRunCommand = jest.fn(); | |
| 20 | - | |
| 21 | - // Use a simple approach to ensure background processes are terminated | |
| 22 | - let testPid: number | null = null; | |
| 23 | - | |
| 24 | - // Create a temp directory for our tests | |
| 25 | - const tempDir = fs.mkdtempSync( | |
| 26 | - path.join(os.tmpdir(), "terminal-command-test-"), | |
| 27 | - ); | |
| 28 | - | |
| 29 | - beforeEach(() => { | |
| 30 | - jest.resetAllMocks(); | |
| 31 | - | |
| 32 | - // Setup backgrounded processes handling - don't mock, just make sure it's empty | |
| 33 | - // Get any processes that might be already tracked and clear them | |
| 34 | - const processMap = (processBackgroundStates as any) | |
| 35 | - .processTerminalBackgroundStates; | |
| 36 | - if (processMap && typeof processMap.clear === "function") { | |
| 37 | - processMap.clear(); | |
| 38 | - } | |
| 39 | - | |
| 40 | - // Setup IDE mocks | |
| 41 | - mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); | |
| 42 | - mockGetWorkspaceDirs.mockReturnValue( | |
| 43 | - Promise.resolve([`file://${tempDir}`]), | |
| 44 | - ); | |
| 45 | - }); | |
| 46 | - | |
| 47 | - afterEach(async () => { | |
| 48 | - // Clean up any lingering test processes | |
| 49 | - if (testPid !== null) { | |
| 50 | - try { | |
| 51 | - // Platform-independent way to kill a process | |
| 52 | - if (process.platform === "win32") { | |
| 53 | - await new Promise((resolve) => { | |
| 54 | - childProcess.exec(`taskkill /F /PID ${testPid}`, () => | |
| 55 | - resolve(null), | |
| 56 | - ); | |
| 57 | - }); | |
| 58 | - } else { | |
| 59 | - process.kill(testPid); | |
| 60 | - } | |
| 61 | - } catch (e) { | |
| 62 | - // Process might already be gone, ignore | |
| 63 | - } | |
| 64 | - testPid = null; | |
| 65 | - } | |
| 66 | - }); | |
| 67 | - | |
| 68 | - afterAll(() => { | |
| 69 | - // Clean up the temp directory after tests | |
| 70 | - fs.rmSync(tempDir, { recursive: true, force: true }); | |
| 71 | - }); | |
| 72 | - | |
| 73 | - // Helper function to create a ToolExtras object | |
| 74 | - const createMockExtras = ( | |
| 75 | - overrides: Partial<{ | |
| 76 | - onPartialOutput?: jest.Mock; | |
| 77 | - remoteName?: string; | |
| 78 | - }> = {}, | |
| 79 | - ): ToolExtras => { | |
| 80 | - // Update IDE info if remoteName is provided | |
| 81 | - if (overrides.remoteName) { | |
| 82 | - mockGetIdeInfo.mockReturnValue( | |
| 83 | - Promise.resolve({ remoteName: overrides.remoteName }), | |
| 84 | - ); | |
| 85 | - } | |
| 86 | - | |
| 87 | - // Create a minimally compliant IDE mock | |
| 88 | - const mockIde = { | |
| 89 | - getIdeInfo: mockGetIdeInfo, | |
| 90 | - getWorkspaceDirs: mockGetWorkspaceDirs, | |
| 91 | - runCommand: mockRunCommand, | |
| 92 | - // Add stubs for other required IDE methods | |
| 93 | - getIdeSettings: jest.fn(), | |
| 94 | - getDiff: jest.fn(), | |
| 95 | - getClipboardContent: jest.fn(), | |
| 96 | - isTelemetryEnabled: jest.fn(), | |
| 97 | - readFile: jest.fn(), | |
| 98 | - writeFile: jest.fn(), | |
| 99 | - renameFile: jest.fn(), | |
| 100 | - deleteFile: jest.fn(), | |
| 101 | - globFiles: jest.fn(), | |
| 102 | - ls: jest.fn(), | |
| 103 | - }; | |
| 104 | - | |
| 105 | - // Create a base ToolExtras object with required properties | |
| 106 | - const baseExtras = { | |
| 107 | - ide: mockIde as unknown as IDE, | |
| 108 | - llm: {} as any, | |
| 109 | - fetch: {} as any, | |
| 110 | - tool: {} as any, | |
| 111 | - toolCallId: "test-tool-call", | |
| 112 | - } as ToolExtras; | |
| 113 | - | |
| 114 | - // Apply overrides | |
| 115 | - if (overrides.onPartialOutput) { | |
| 116 | - baseExtras.onPartialOutput = overrides.onPartialOutput; | |
| 117 | - } | |
| 118 | - | |
| 119 | - return baseExtras; | |
| 120 | - }; | |
| 121 | - | |
| 122 | - it("should execute a command synchronously and capture output", async () => { | |
| 123 | - // Use Node.js for cross-platform output generation | |
| 124 | - const command = `node -e "console.log('real test output')"`; | |
| 125 | - const args = { command, waitForCompletion: true }; | |
| 126 | - const extras = createMockExtras(); | |
| 127 | - | |
| 128 | - const result = await runTerminalCommandImpl(args, extras); | |
| 129 | - | |
| 130 | - // Verify real command output | |
| 131 | - expect(result).toHaveLength(1); | |
| 132 | - expect(result[0].name).toBe("Terminal"); | |
| 133 | - expect(result[0].description).toBe("Terminal command output"); | |
| 134 | - expect(result[0].content).toContain("real test output"); | |
| 135 | - // Verify status field indicates successful completion | |
| 136 | - expect(result[0].status).toBe("Command completed"); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should stream output when onPartialOutput is provided", async () => { | |
| 140 | - // This test uses Node to create a command that outputs data incrementally | |
| 141 | - const command = `node -e " | |
| 142 | - console.log('first output'); | |
| 143 | - setTimeout(() => { | |
| 144 | - console.log('second output'); | |
| 145 | - console.error('error output'); | |
| 146 | - }, 50); | |
| 147 | - "`; | |
| 148 | - | |
| 149 | - const args = { command, waitForCompletion: true }; | |
| 150 | - const mockOutputFn = jest.fn(); | |
| 151 | - const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 152 | - | |
| 153 | - // Execute the command with streaming | |
| 154 | - const result = await runTerminalCommandImpl(args, extras); | |
| 155 | - | |
| 156 | - // Verify onPartialOutput was called with increasing content | |
| 157 | - expect(mockOutputFn).toHaveBeenCalled(); | |
| 158 | - | |
| 159 | - // Verify final result has all output | |
| 160 | - expect(result[0].content).toContain("first output"); | |
| 161 | - expect(result[0].content).toContain("second output"); | |
| 162 | - expect(result[0].content).toContain("error output"); | |
| 163 | - // Verify status field indicates successful completion | |
| 164 | - expect(result[0].status).toBe("Command completed"); | |
| 165 | - | |
| 166 | - // Verify that initial streaming updates have empty status for regular commands | |
| 167 | - const firstCall = mockOutputFn.mock.calls[0][0]; | |
| 168 | - if (firstCall && typeof firstCall === "object") { | |
| 169 | - const contextItems = (firstCall as any).contextItems; | |
| 170 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 171 | - // For commands with waitForCompletion=true, status should be empty while streaming | |
| 172 | - expect(contextItems[0].status).toBe(""); | |
| 173 | - } | |
| 174 | - } | |
| 175 | - }); | |
| 176 | - | |
| 177 | - it("should run commands in background when waitForCompletion is false", async () => { | |
| 178 | - // Create a self-identifying background process that writes its PID | |
| 179 | - // to a file we can access to kill it later | |
| 180 | - const pidFile = path.join(tempDir, "test-pid.txt"); | |
| 181 | - | |
| 182 | - // This script creates a long-running process and writes its PID to our file | |
| 183 | - // Using a fixed duration timeout so we can be sure to clean it up | |
| 184 | - const command = `node -e " | |
| 185 | - const fs = require('fs'); | |
| 186 | - console.log('starting background process with PID: ' + process.pid); | |
| 187 | - fs.writeFileSync('${pidFile}', process.pid.toString()); | |
| 188 | - setTimeout(() => { | |
| 189 | - console.log('background process completed'); | |
| 190 | - }, 500); | |
| 191 | - "`; | |
| 192 | - | |
| 193 | - const args = { command, waitForCompletion: false }; | |
| 194 | - const mockOutputFn = jest.fn(); | |
| 195 | - const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 196 | - | |
| 197 | - const result = await runTerminalCommandImpl(args, extras); | |
| 198 | - | |
| 199 | - // Result should indicate background running in either content or status | |
| 200 | - expect(result[0].content || result[0].status).toContain( | |
| 201 | - "running in the background", | |
| 202 | - ); | |
| 203 | - // Verify status field indicates background running | |
| 204 | - expect(result[0].status).toBe("Command is running in the background..."); | |
| 205 | - | |
| 206 | - // Initial notification should indicate background running | |
| 207 | - expect(mockOutputFn).toHaveBeenCalled(); | |
| 208 | - // Check the first call contains background running message | |
| 209 | - const firstCallData = mockOutputFn.mock.calls[0][0]; | |
| 210 | - if (firstCallData && typeof firstCallData === "object") { | |
| 211 | - const contextItems = (firstCallData as any).contextItems; | |
| 212 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 213 | - expect(contextItems[0].content).toContain(""); | |
| 214 | - expect(contextItems[0].status).toMatch( | |
| 215 | - /Command is running in the background.../, | |
| 216 | - ); | |
| 217 | - } | |
| 218 | - } | |
| 219 | - | |
| 220 | - // Wait a bit to make sure the PID file is written | |
| 221 | - await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 222 | - | |
| 223 | - // Read the PID file to get the process ID so we can kill it later | |
| 224 | - if (fs.existsSync(pidFile)) { | |
| 225 | - testPid = Number(fs.readFileSync(pidFile, "utf-8")); | |
| 226 | - } | |
| 227 | - | |
| 228 | - // Wait a bit longer for the process to complete and onPartialOutput to be called again | |
| 229 | - await new Promise((resolve) => setTimeout(resolve, 400)); | |
| 230 | - | |
| 231 | - // Check for background process completion message in mockOutputFn calls | |
| 232 | - // Note: This is optional and depends on timing, so we don't want to strictly enforce it | |
| 233 | - let foundCompletionMessage = false; | |
| 234 | - | |
| 235 | - for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { | |
| 236 | - const call = mockOutputFn.mock.calls[i][0]; | |
| 237 | - if (call && typeof call === "object") { | |
| 238 | - const contextItems = (call as any).contextItems; | |
| 239 | - if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 240 | - if ( | |
| 241 | - contextItems[0].status === "\nBackground command completed" || | |
| 242 | - (contextItems[0].status && | |
| 243 | - contextItems[0].status.includes("Background command")) | |
| 244 | - ) { | |
| 245 | - foundCompletionMessage = true; | |
| 246 | - break; | |
| 247 | - } | |
| 248 | - } | |
| 249 | - } | |
| 250 | - } | |
| 251 | - | |
| 252 | - // If we found any completion message in the output, great! | |
| 253 | - // But we won't fail the test if we didn't, since it may be timing-dependent | |
| 254 | - if (mockOutputFn.mock.calls.length > 1) { | |
| 255 | - expect(foundCompletionMessage || true).toBeTruthy(); | |
| 256 | - } | |
| 257 | - }); | |
| 258 | - | |
| 259 | - it("should handle remote environments", async () => { | |
| 260 | - // We'll keep mocking for remote environments as we can't test those directly | |
| 261 | - const args = { command: "echo 'test'", waitForCompletion: true }; | |
| 262 | - const extras = createMockExtras({ remoteName: "ssh" }); | |
| 263 | - | |
| 264 | - const result = await runTerminalCommandImpl(args, extras); | |
| 265 | - | |
| 266 | - // In remote environments, it should use the IDE's runCommand | |
| 267 | - expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); | |
| 268 | - // Match the actual output message | |
| 269 | - expect(result[0].content).toContain("Terminal output not available"); | |
| 270 | - expect(result[0].content).toContain("SSH environments"); | |
| 271 | - // Verify status field indicates command failed in remote environments | |
| 272 | - expect(result[0].status).toBe("Command failed"); | |
| 273 | - }); | |
| 274 | - | |
| 275 | - it("should handle errors when executing invalid commands", async () => { | |
| 276 | - // Use a command that should fail on any platform | |
| 277 | - const args = { | |
| 278 | - command: "non-existent-command-xyz", | |
| 279 | - waitForCompletion: true, | |
| 280 | - }; | |
| 281 | - const extras = createMockExtras(); | |
| 282 | - | |
| 283 | - const result = await runTerminalCommandImpl(args, extras); | |
| 284 | - | |
| 285 | - expect(result[0].name).toBe("Terminal"); | |
| 286 | - expect(result[0].description).toBe("Terminal command output"); | |
| 287 | - | |
| 288 | - // The exact error message varies by platform, but should contain error information | |
| 289 | - const errorContent = result[0].content; | |
| 290 | - expect( | |
| 291 | - errorContent.includes("Command failed") || | |
| 292 | - errorContent.includes("not found") || | |
| 293 | - errorContent.includes("recognized") || | |
| 294 | - /error/i.test(errorContent), | |
| 295 | - ).toBe(true); | |
| 296 | - | |
| 297 | - // Verify status field indicates command failure | |
| 298 | - expect(result[0].status).toContain("Command failed with:"); | |
| 299 | - }); | |
| 300 | - | |
| 301 | - it("should handle error situations gracefully", async () => { | |
| 302 | - // Use Node.js script that writes to stderr for cross-platform testing | |
| 303 | - const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; | |
| 304 | - const args = { command, waitForCompletion: true }; | |
| 305 | - const extras = createMockExtras(); | |
| 306 | - | |
| 307 | - const result = await runTerminalCommandImpl(args, extras); | |
| 308 | - | |
| 309 | - // Verify we still get a result with a name and description | |
| 310 | - expect(result).toHaveLength(1); | |
| 311 | - expect(result[0].name).toBe("Terminal"); | |
| 312 | - expect(result[0].description).toBe("Terminal command output"); | |
| 313 | - | |
| 314 | - // The command should have executed and returned content | |
| 315 | - expect(result[0].content).toBeDefined(); | |
| 316 | - | |
| 317 | - // We should see the error message we wrote to stderr | |
| 318 | - expect(result[0].content).toContain("This is an error message"); | |
| 319 | - | |
| 320 | - // Verify status field indicates command failure - the exact message format can vary | |
| 321 | - // between different node versions and platforms | |
| 322 | - expect(result[0].status).toContain("Command failed"); | |
| 323 | - }); | |
| 324 | - | |
| 325 | - it("should set appropriate status when a command completes successfully", async () => { | |
| 326 | - // Use a simple command that will succeed | |
| 327 | - const command = `node -e "console.log('success test')"`; | |
| 328 | - const args = { command, waitForCompletion: true }; | |
| 329 | - const extras = createMockExtras(); | |
| 330 | - | |
| 331 | - const result = await runTerminalCommandImpl(args, extras); | |
| 332 | - | |
| 333 | - expect(result).toHaveLength(1); | |
| 334 | - expect(result[0].name).toBe("Terminal"); | |
| 335 | - expect(result[0].content).toContain("success test"); | |
| 336 | - // Verify status field for successful command | |
| 337 | - expect(result[0].status).toBe("Command completed"); | |
| 338 | - }); | |
| 339 | - | |
| 340 | - it("should include status info for background commands in non-streaming mode", async () => { | |
| 341 | - // Use a simple background command | |
| 342 | - const command = `node -e "setTimeout(() => console.log('done'), 300)"`; | |
| 343 | - const args = { command, waitForCompletion: false }; | |
| 344 | - // No streaming in this test (no onPartialOutput) | |
| 345 | - const extras = createMockExtras(); | |
| 346 | - | |
| 347 | - const result = await runTerminalCommandImpl(args, extras); | |
| 348 | - | |
| 349 | - expect(result).toHaveLength(1); | |
| 350 | - expect(result[0].name).toBe("Terminal"); | |
| 351 | - // Verify both content and status fields for background commands | |
| 352 | - expect(result[0].content).toBe("Command is running in the background..."); | |
| 353 | - expect(result[0].status).toBe("Command is running in the background..."); | |
| 354 | - }); | |
| 355 | - | |
| 356 | - it("should handle missing workspace directory gracefully", async () => { | |
| 357 | - // Mock IDE to return empty workspace directories | |
| 358 | - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); | |
| 359 | - | |
| 360 | - // Create IDE mock with empty workspace | |
| 361 | - const mockIde = { | |
| 362 | - getIdeInfo: jest | |
| 363 | - .fn() | |
| 364 | - .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 365 | - getWorkspaceDirs: mockEmptyWorkspace, | |
| 366 | - runCommand: jest.fn(), | |
| 367 | - getIdeSettings: jest.fn(), | |
| 368 | - getDiff: jest.fn(), | |
| 369 | - getClipboardContent: jest.fn(), | |
| 370 | - isTelemetryEnabled: jest.fn(), | |
| 371 | - readFile: jest.fn(), | |
| 372 | - writeFile: jest.fn(), | |
| 373 | - renameFile: jest.fn(), | |
| 374 | - deleteFile: jest.fn(), | |
| 375 | - globFiles: jest.fn(), | |
| 376 | - ls: jest.fn(), | |
| 377 | - }; | |
| 378 | - | |
| 379 | - const extras = { | |
| 380 | - ide: mockIde as unknown as IDE, | |
| 381 | - llm: {} as any, | |
| 382 | - fetch: {} as any, | |
| 383 | - tool: {} as any, | |
| 384 | - toolCallId: "test-tool-call", | |
| 385 | - } as ToolExtras; | |
| 386 | - | |
| 387 | - const command = `node -e "console.log('no workspace test')"`; | |
| 388 | - const args = { command, waitForCompletion: true }; | |
| 389 | - | |
| 390 | - const result = await runTerminalCommandImpl(args, extras); | |
| 391 | - | |
| 392 | - // Should still work - falling back to HOME or cwd | |
| 393 | - expect(result).toHaveLength(1); | |
| 394 | - expect(result[0].name).toBe("Terminal"); | |
| 395 | - expect(result[0].description).toBe("Terminal command output"); | |
| 396 | - expect(result[0].content).toContain("no workspace test"); | |
| 397 | - expect(result[0].status).toBe("Command completed"); | |
| 398 | - | |
| 399 | - // Verify workspace dirs was called but returned empty | |
| 400 | - expect(mockEmptyWorkspace).toHaveBeenCalled(); | |
| 401 | - }); | |
| 402 | - | |
| 403 | - it("should handle case where cwd fallbacks all fail", async () => { | |
| 404 | - // Mock IDE to return empty workspace directories | |
| 405 | - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); | |
| 406 | - | |
| 407 | - // Save original environment variables and process.cwd | |
| 408 | - const originalHome = process.env.HOME; | |
| 409 | - const originalUserProfile = process.env.USERPROFILE; | |
| 410 | - const originalCwd = process.cwd; | |
| 411 | - | |
| 412 | - try { | |
| 413 | - // Mock all fallbacks to fail | |
| 414 | - delete process.env.HOME; | |
| 415 | - delete process.env.USERPROFILE; | |
| 416 | - process.cwd = jest.fn().mockImplementation(() => { | |
| 417 | - throw new Error("Current directory unavailable"); | |
| 418 | - }) as jest.MockedFunction<() => string>; | |
| 419 | - | |
| 420 | - // Create IDE mock with empty workspace | |
| 421 | - const mockIde = { | |
| 422 | - getIdeInfo: jest | |
| 423 | - .fn() | |
| 424 | - .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 425 | - getWorkspaceDirs: mockEmptyWorkspace, | |
| 426 | - runCommand: jest.fn(), | |
| 427 | - getIdeSettings: jest.fn(), | |
| 428 | - getDiff: jest.fn(), | |
| 429 | - getClipboardContent: jest.fn(), | |
| 430 | - isTelemetryEnabled: jest.fn(), | |
| 431 | - readFile: jest.fn(), | |
| 432 | - writeFile: jest.fn(), | |
| 433 | - renameFile: jest.fn(), | |
| 434 | - deleteFile: jest.fn(), | |
| 435 | - globFiles: jest.fn(), | |
| 436 | - ls: jest.fn(), | |
| 437 | - }; | |
| 438 | - | |
| 439 | - const extras = { | |
| 440 | - ide: mockIde as unknown as IDE, | |
| 441 | - llm: {} as any, | |
| 442 | - fetch: {} as any, | |
| 443 | - tool: {} as any, | |
| 444 | - toolCallId: "test-tool-call", | |
| 445 | - } as ToolExtras; | |
| 446 | - | |
| 447 | - const command = `node -e "console.log('fallback test')"`; | |
| 448 | - const args = { command, waitForCompletion: true }; | |
| 449 | - | |
| 450 | - // This should now handle the case gracefully by falling back to temp directory | |
| 451 | - const result = await runTerminalCommandImpl(args, extras); | |
| 452 | - | |
| 453 | - // Should work using the temp directory as fallback | |
| 454 | - expect(result).toHaveLength(1); | |
| 455 | - expect(result[0].name).toBe("Terminal"); | |
| 456 | - expect(result[0].content).toContain("fallback test"); | |
| 457 | - expect(result[0].status).toBe("Command completed"); | |
| 458 | - | |
| 459 | - console.log( | |
| 460 | - "Successfully handled cwd fallback to temp directory:", | |
| 461 | - result[0].status, | |
| 462 | - ); | |
| 463 | - } finally { | |
| 464 | - // Always restore original values | |
| 465 | - if (originalHome !== undefined) { | |
| 466 | - process.env.HOME = originalHome; | |
| 467 | - } | |
| 468 | - if (originalUserProfile !== undefined) { | |
| 469 | - process.env.USERPROFILE = originalUserProfile; | |
| 470 | - } | |
| 471 | - process.cwd = originalCwd; | |
| 472 | - } | |
| 473 | - }); | |
| 474 | -}); |
| @@ -36,8 +36,11 @@ | ||
| 36 | 36 | import { ToolImpl } from "."; |
| 37 | 37 | import { |
| 38 | 38 | isProcessBackgrounded, |
| 39 | + markProcessAsRunning, | |
| 39 | 40 | removeBackgroundedProcess, |
| 40 | -} from "../../util/processTerminalBackgroundStates"; | |
| 41 | + removeRunningProcess, | |
| 42 | + updateProcessOutput, | |
| 43 | +} from "../../util/processTerminalStates"; | |
| 41 | 44 | import { getBooleanArg, getStringArg } from "../parseArgs"; |
| 42 | 45 | |
| 43 | 46 | const asyncExec = util.promisify(childProcess.exec); |
| @@ -120,6 +123,16 @@ | ||
| 120 | 123 | env: getColorEnv(), // Add enhanced environment for colors |
| 121 | 124 | }); |
| 122 | 125 | |
| 126 | + // Track this process for foreground cancellation | |
| 127 | + if (toolCallId && waitForCompletion) { | |
| 128 | + markProcessAsRunning( | |
| 129 | + toolCallId, | |
| 130 | + childProc, | |
| 131 | + extras.onPartialOutput, | |
| 132 | + terminalOutput, | |
| 133 | + ); | |
| 134 | + } | |
| 135 | + | |
| 123 | 136 | childProc.stdout?.on("data", (data) => { |
| 124 | 137 | // Skip if this process has been backgrounded |
| 125 | 138 | if (isProcessBackgrounded(toolCallId)) return; |
| @@ -127,6 +140,11 @@ | ||
| 127 | 140 | const newOutput = getDecodedOutput(data); |
| 128 | 141 | terminalOutput += newOutput; |
| 129 | 142 | |
| 143 | + // Update the tracked output for potential cancellation notifications | |
| 144 | + if (toolCallId && waitForCompletion) { | |
| 145 | + updateProcessOutput(toolCallId, terminalOutput); | |
| 146 | + } | |
| 147 | + | |
| 130 | 148 | // Send partial output to UI |
| 131 | 149 | if (extras.onPartialOutput) { |
| 132 | 150 | const status = waitForCompletion |
| @@ -153,6 +171,11 @@ | ||
| 153 | 171 | const newOutput = getDecodedOutput(data); |
| 154 | 172 | terminalOutput += newOutput; |
| 155 | 173 | |
| 174 | + // Update the tracked output for potential cancellation notifications | |
| 175 | + if (toolCallId && waitForCompletion) { | |
| 176 | + updateProcessOutput(toolCallId, terminalOutput); | |
| 177 | + } | |
| 178 | + | |
| 156 | 179 | // Send partial output to UI, status is not required |
| 157 | 180 | if (extras.onPartialOutput) { |
| 158 | 181 | extras.onPartialOutput({ |
| @@ -182,15 +205,19 @@ | ||
| 182 | 205 | } |
| 183 | 206 | |
| 184 | 207 | childProc.on("close", (code) => { |
| 185 | - // If this process has been backgrounded, clean it up from the map and return | |
| 186 | - if (isProcessBackgrounded(toolCallId)) { | |
| 187 | - removeBackgroundedProcess(toolCallId); | |
| 188 | - return; | |
| 208 | + // Clean up process tracking | |
| 209 | + if (toolCallId) { | |
| 210 | + if (isProcessBackgrounded(toolCallId)) { | |
| 211 | + removeBackgroundedProcess(toolCallId); | |
| 212 | + return; | |
| 213 | + } | |
| 214 | + // Remove from foreground tracking if it was tracked | |
| 215 | + removeRunningProcess(toolCallId); | |
| 189 | 216 | } |
| 190 | 217 | |
| 191 | 218 | if (waitForCompletion) { |
| 192 | 219 | // Normal completion, resolve now |
| 193 | - if (code === 0) { | |
| 220 | + if (!code || code === 0) { | |
| 194 | 221 | const status = "Command completed"; |
| 195 | 222 | resolve([ |
| 196 | 223 | { |
| @@ -234,10 +261,14 @@ | ||
| 234 | 261 | }); |
| 235 | 262 | |
| 236 | 263 | childProc.on("error", (error) => { |
| 237 | - // If this process has been backgrounded, clean it up from the map and return | |
| 238 | - if (isProcessBackgrounded(toolCallId)) { | |
| 239 | - removeBackgroundedProcess(toolCallId); | |
| 240 | - return; | |
| 264 | + // Clean up process tracking | |
| 265 | + if (toolCallId) { | |
| 266 | + if (isProcessBackgrounded(toolCallId)) { | |
| 267 | + removeBackgroundedProcess(toolCallId); | |
| 268 | + return; | |
| 269 | + } | |
| 270 | + // Remove from foreground tracking if it was tracked | |
| 271 | + removeRunningProcess(toolCallId); | |
| 241 | 272 | } |
| 242 | 273 | |
| 243 | 274 | reject(error); |
| @@ -281,6 +312,11 @@ | ||
| 281 | 312 | }, |
| 282 | 313 | ); |
| 283 | 314 | |
| 315 | + // Track this process for foreground cancellation | |
| 316 | + if (toolCallId) { | |
| 317 | + markProcessAsRunning(toolCallId, childProc, undefined, ""); | |
| 318 | + } | |
| 319 | + | |
| 284 | 320 | let stdout = ""; |
| 285 | 321 | let stderr = ""; |
| 286 | 322 | |
| @@ -293,6 +329,11 @@ | ||
| 293 | 329 | }); |
| 294 | 330 | |
| 295 | 331 | childProc.on("close", (code) => { |
| 332 | + // Clean up process tracking | |
| 333 | + if (toolCallId) { | |
| 334 | + removeRunningProcess(toolCallId); | |
| 335 | + } | |
| 336 | + | |
| 296 | 337 | if (code === 0) { |
| 297 | 338 | resolve({ stdout, stderr }); |
| 298 | 339 | } else { |
| @@ -305,6 +346,10 @@ | ||
| 305 | 346 | }); |
| 306 | 347 | |
| 307 | 348 | childProc.on("error", (error) => { |
| 349 | + // Clean up process tracking | |
| 350 | + if (toolCallId) { | |
| 351 | + removeRunningProcess(toolCallId); | |
| 352 | + } | |
| 308 | 353 | reject(error); |
| 309 | 354 | }); |
| 310 | 355 | }, |
| @@ -0,0 +1,601 @@ | ||
| 1 | +import { | |
| 2 | + describe, | |
| 3 | + it, | |
| 4 | + expect, | |
| 5 | + beforeEach, | |
| 6 | + afterEach, | |
| 7 | + afterAll, | |
| 8 | + vi, | |
| 9 | +} from "vitest"; | |
| 10 | +import * as childProcess from "node:child_process"; | |
| 11 | +import * as fs from "node:fs"; | |
| 12 | +import * as os from "node:os"; | |
| 13 | +import * as path from "node:path"; | |
| 14 | +import { IDE, ToolExtras } from "../.."; | |
| 15 | +import * as processTerminalStates from "../../util/processTerminalStates"; | |
| 16 | +import { runTerminalCommandImpl } from "./runTerminalCommand"; | |
| 17 | +import { runTerminalCommandTool } from "../definitions/runTerminalCommand"; | |
| 18 | + | |
| 19 | +// We're using real child processes, so ensure these aren't mocked | |
| 20 | +vi.unmock("node:child_process"); | |
| 21 | +vi.unmock("node:util"); | |
| 22 | + | |
| 23 | +describe("runTerminalCommandImpl", () => { | |
| 24 | + // Setup mocks and spies | |
| 25 | + const mockGetIdeInfo = vi.fn(); | |
| 26 | + const mockGetWorkspaceDirs = vi.fn(); | |
| 27 | + const mockOnPartialOutput = vi.fn(); | |
| 28 | + const mockRunCommand = vi.fn(); | |
| 29 | + | |
| 30 | + // Use a simple approach to ensure background processes are terminated | |
| 31 | + let testPid: number | null = null; | |
| 32 | + | |
| 33 | + // Create a temp directory for our tests | |
| 34 | + const tempDir = fs.mkdtempSync( | |
| 35 | + path.join(os.tmpdir(), "terminal-command-test-"), | |
| 36 | + ); | |
| 37 | + | |
| 38 | + beforeEach(() => { | |
| 39 | + vi.resetAllMocks(); | |
| 40 | + | |
| 41 | + // Setup backgrounded processes handling - don't mock, just make sure it's empty | |
| 42 | + // Clear any processes that might be already tracked | |
| 43 | + processTerminalStates.clearAllBackgroundProcesses(); | |
| 44 | + | |
| 45 | + // Setup IDE mocks | |
| 46 | + mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); | |
| 47 | + mockGetWorkspaceDirs.mockReturnValue( | |
| 48 | + Promise.resolve([`file://${tempDir}`]), | |
| 49 | + ); | |
| 50 | + }); | |
| 51 | + | |
| 52 | + afterEach(async () => { | |
| 53 | + // Clean up any lingering test processes | |
| 54 | + if (testPid !== null) { | |
| 55 | + try { | |
| 56 | + // Platform-independent way to kill a process | |
| 57 | + if (process.platform === "win32") { | |
| 58 | + await new Promise((resolve) => { | |
| 59 | + childProcess.exec(`taskkill /F /PID ${testPid}`, () => | |
| 60 | + resolve(null), | |
| 61 | + ); | |
| 62 | + }); | |
| 63 | + } else { | |
| 64 | + process.kill(testPid); | |
| 65 | + } | |
| 66 | + } catch (e) { | |
| 67 | + // Process might already be gone, ignore | |
| 68 | + } | |
| 69 | + testPid = null; | |
| 70 | + } | |
| 71 | + }); | |
| 72 | + | |
| 73 | + afterAll(() => { | |
| 74 | + // Clean up the temp directory after tests | |
| 75 | + fs.rmSync(tempDir, { recursive: true, force: true }); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + // Helper function to create a ToolExtras object | |
| 79 | + const createMockExtras = ( | |
| 80 | + overrides: Partial<{ | |
| 81 | + onPartialOutput?: any; | |
| 82 | + remoteName?: string; | |
| 83 | + }> = {}, | |
| 84 | + ): ToolExtras => { | |
| 85 | + // Update IDE info if remoteName is provided | |
| 86 | + if (overrides.remoteName) { | |
| 87 | + mockGetIdeInfo.mockReturnValue( | |
| 88 | + Promise.resolve({ remoteName: overrides.remoteName }), | |
| 89 | + ); | |
| 90 | + } | |
| 91 | + | |
| 92 | + // Create a minimally compliant IDE mock | |
| 93 | + const mockIde = { | |
| 94 | + getIdeInfo: mockGetIdeInfo, | |
| 95 | + getWorkspaceDirs: mockGetWorkspaceDirs, | |
| 96 | + runCommand: mockRunCommand, | |
| 97 | + // Add stubs for other required IDE methods | |
| 98 | + getIdeSettings: vi.fn(), | |
| 99 | + getDiff: vi.fn(), | |
| 100 | + getClipboardContent: vi.fn(), | |
| 101 | + isTelemetryEnabled: vi.fn(), | |
| 102 | + readFile: vi.fn(), | |
| 103 | + writeFile: vi.fn(), | |
| 104 | + renameFile: vi.fn(), | |
| 105 | + deleteFile: vi.fn(), | |
| 106 | + globFiles: vi.fn(), | |
| 107 | + ls: vi.fn(), | |
| 108 | + }; | |
| 109 | + | |
| 110 | + // Create a base ToolExtras object with required properties | |
| 111 | + const baseExtras = { | |
| 112 | + ide: mockIde as unknown as IDE, | |
| 113 | + llm: {} as any, | |
| 114 | + fetch: {} as any, | |
| 115 | + tool: {} as any, | |
| 116 | + toolCallId: "test-tool-call", | |
| 117 | + } as ToolExtras; | |
| 118 | + | |
| 119 | + // Apply overrides | |
| 120 | + if (overrides.onPartialOutput) { | |
| 121 | + baseExtras.onPartialOutput = overrides.onPartialOutput; | |
| 122 | + } | |
| 123 | + | |
| 124 | + return baseExtras; | |
| 125 | + }; | |
| 126 | + | |
| 127 | + it("should execute a command synchronously and capture output", async () => { | |
| 128 | + // Use Node.js for cross-platform output generation | |
| 129 | + const command = `node -e "console.log('real test output')"`; | |
| 130 | + const args = { command, waitForCompletion: true }; | |
| 131 | + const extras = createMockExtras(); | |
| 132 | + | |
| 133 | + const result = await runTerminalCommandImpl(args, extras); | |
| 134 | + | |
| 135 | + // Verify real command output | |
| 136 | + expect(result).toHaveLength(1); | |
| 137 | + expect(result[0].name).toBe("Terminal"); | |
| 138 | + expect(result[0].description).toBe("Terminal command output"); | |
| 139 | + expect(result[0].content).toContain("real test output"); | |
| 140 | + // Verify status field indicates successful completion | |
| 141 | + expect(result[0].status).toBe("Command completed"); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + it("should stream output when onPartialOutput is provided", async () => { | |
| 145 | + // This test uses Node to create a command that outputs data incrementally | |
| 146 | + const command = `node -e " | |
| 147 | + console.log('first output'); | |
| 148 | + setTimeout(() => { | |
| 149 | + console.log('second output'); | |
| 150 | + console.error('error output'); | |
| 151 | + }, 50); | |
| 152 | + "`; | |
| 153 | + | |
| 154 | + const args = { command, waitForCompletion: true }; | |
| 155 | + const mockOutputFn = vi.fn(); | |
| 156 | + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 157 | + | |
| 158 | + // Execute the command with streaming | |
| 159 | + const result = await runTerminalCommandImpl(args, extras); | |
| 160 | + | |
| 161 | + // Verify onPartialOutput was called with increasing content | |
| 162 | + expect(mockOutputFn).toHaveBeenCalled(); | |
| 163 | + | |
| 164 | + // Verify final result has all output | |
| 165 | + expect(result[0].content).toContain("first output"); | |
| 166 | + expect(result[0].content).toContain("second output"); | |
| 167 | + expect(result[0].content).toContain("error output"); | |
| 168 | + // Verify status field indicates successful completion | |
| 169 | + expect(result[0].status).toBe("Command completed"); | |
| 170 | + | |
| 171 | + // Verify that initial streaming updates have empty status for regular commands | |
| 172 | + const firstCall = mockOutputFn.mock.calls[0][0]; | |
| 173 | + if (firstCall && typeof firstCall === "object") { | |
| 174 | + const contextItems = (firstCall as any).contextItems; | |
| 175 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 176 | + // For commands with waitForCompletion=true, status should be empty while streaming | |
| 177 | + expect(contextItems[0].status).toBe(""); | |
| 178 | + } | |
| 179 | + } | |
| 180 | + }); | |
| 181 | + | |
| 182 | + it("should run commands in background when waitForCompletion is false", async () => { | |
| 183 | + // Create a self-identifying background process that writes its PID | |
| 184 | + // to a file we can access to kill it later | |
| 185 | + const pidFile = path.join(tempDir, "test-pid.txt"); | |
| 186 | + | |
| 187 | + // This script creates a long-running process and writes its PID to our file | |
| 188 | + // Using a fixed duration timeout so we can be sure to clean it up | |
| 189 | + const command = `node -e " | |
| 190 | + const fs = require('fs'); | |
| 191 | + console.log('starting background process with PID: ' + process.pid); | |
| 192 | + fs.writeFileSync('${pidFile}', process.pid.toString()); | |
| 193 | + setTimeout(() => { | |
| 194 | + console.log('background process completed'); | |
| 195 | + }, 500); | |
| 196 | + "`; | |
| 197 | + | |
| 198 | + const args = { command, waitForCompletion: false }; | |
| 199 | + const mockOutputFn = vi.fn(); | |
| 200 | + const extras = createMockExtras({ onPartialOutput: mockOutputFn }); | |
| 201 | + | |
| 202 | + const result = await runTerminalCommandImpl(args, extras); | |
| 203 | + | |
| 204 | + // Result should indicate background running in either content or status | |
| 205 | + expect(result[0].content || result[0].status).toContain( | |
| 206 | + "running in the background", | |
| 207 | + ); | |
| 208 | + // Verify status field indicates background running | |
| 209 | + expect(result[0].status).toBe("Command is running in the background..."); | |
| 210 | + | |
| 211 | + // Initial notification should indicate background running | |
| 212 | + expect(mockOutputFn).toHaveBeenCalled(); | |
| 213 | + // Check the first call contains background running message | |
| 214 | + const firstCallData = mockOutputFn.mock.calls[0][0]; | |
| 215 | + if (firstCallData && typeof firstCallData === "object") { | |
| 216 | + const contextItems = (firstCallData as any).contextItems; | |
| 217 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 218 | + expect(contextItems[0].content).toContain(""); | |
| 219 | + expect(contextItems[0].status).toMatch( | |
| 220 | + /Command is running in the background.../, | |
| 221 | + ); | |
| 222 | + } | |
| 223 | + } | |
| 224 | + | |
| 225 | + // Wait a bit to make sure the PID file is written | |
| 226 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 227 | + | |
| 228 | + // Read the PID file to get the process ID so we can kill it later | |
| 229 | + if (fs.existsSync(pidFile)) { | |
| 230 | + testPid = Number(fs.readFileSync(pidFile, "utf-8")); | |
| 231 | + } | |
| 232 | + | |
| 233 | + // Wait a bit longer for the process to complete and onPartialOutput to be called again | |
| 234 | + await new Promise((resolve) => setTimeout(resolve, 400)); | |
| 235 | + | |
| 236 | + // Check for background process completion message in mockOutputFn calls | |
| 237 | + // Note: This is optional and depends on timing, so we don't want to strictly enforce it | |
| 238 | + let foundCompletionMessage = false; | |
| 239 | + | |
| 240 | + for (let i = 0; i < mockOutputFn.mock.calls.length; i++) { | |
| 241 | + const call = mockOutputFn.mock.calls[i][0]; | |
| 242 | + if (call && typeof call === "object") { | |
| 243 | + const contextItems = (call as any).contextItems; | |
| 244 | + if (contextItems && Array.isArray(contextItems) && contextItems[0]) { | |
| 245 | + if ( | |
| 246 | + contextItems[0].status === "\nBackground command completed" || | |
| 247 | + (contextItems[0].status && | |
| 248 | + contextItems[0].status.includes("Background command")) | |
| 249 | + ) { | |
| 250 | + foundCompletionMessage = true; | |
| 251 | + break; | |
| 252 | + } | |
| 253 | + } | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + // If we found any completion message in the output, great! | |
| 258 | + // But we won't fail the test if we didn't, since it may be timing-dependent | |
| 259 | + if (mockOutputFn.mock.calls.length > 1) { | |
| 260 | + expect(foundCompletionMessage || true).toBeTruthy(); | |
| 261 | + } | |
| 262 | + }); | |
| 263 | + | |
| 264 | + it("should handle remote environments", async () => { | |
| 265 | + // We'll keep mocking for remote environments as we can't test those directly | |
| 266 | + const args = { command: "echo 'test'", waitForCompletion: true }; | |
| 267 | + const extras = createMockExtras({ remoteName: "ssh" }); | |
| 268 | + | |
| 269 | + const result = await runTerminalCommandImpl(args, extras); | |
| 270 | + | |
| 271 | + // In remote environments, it should use the IDE's runCommand | |
| 272 | + expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'"); | |
| 273 | + // Match the actual output message | |
| 274 | + expect(result[0].content).toContain("Terminal output not available"); | |
| 275 | + expect(result[0].content).toContain("SSH environments"); | |
| 276 | + // Verify status field indicates command failed in remote environments | |
| 277 | + expect(result[0].status).toBe("Command failed"); | |
| 278 | + }); | |
| 279 | + | |
| 280 | + it("should handle errors when executing invalid commands", async () => { | |
| 281 | + // Use a command that should fail on any platform | |
| 282 | + const args = { | |
| 283 | + command: "non-existent-command-xyz", | |
| 284 | + waitForCompletion: true, | |
| 285 | + }; | |
| 286 | + const extras = createMockExtras(); | |
| 287 | + | |
| 288 | + const result = await runTerminalCommandImpl(args, extras); | |
| 289 | + | |
| 290 | + expect(result[0].name).toBe("Terminal"); | |
| 291 | + expect(result[0].description).toBe("Terminal command output"); | |
| 292 | + | |
| 293 | + // The exact error message varies by platform, but should contain error information | |
| 294 | + const errorContent = result[0].content; | |
| 295 | + expect( | |
| 296 | + errorContent.includes("Command failed") || | |
| 297 | + errorContent.includes("not found") || | |
| 298 | + errorContent.includes("recognized") || | |
| 299 | + /error/i.test(errorContent), | |
| 300 | + ).toBe(true); | |
| 301 | + | |
| 302 | + // Verify status field indicates command failure | |
| 303 | + expect(result[0].status).toContain("Command failed with:"); | |
| 304 | + }); | |
| 305 | + | |
| 306 | + it("should handle error situations gracefully", async () => { | |
| 307 | + // Use Node.js script that writes to stderr for cross-platform testing | |
| 308 | + const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`; | |
| 309 | + const args = { command, waitForCompletion: true }; | |
| 310 | + const extras = createMockExtras(); | |
| 311 | + | |
| 312 | + const result = await runTerminalCommandImpl(args, extras); | |
| 313 | + | |
| 314 | + // Verify we still get a result with a name and description | |
| 315 | + expect(result).toHaveLength(1); | |
| 316 | + expect(result[0].name).toBe("Terminal"); | |
| 317 | + expect(result[0].description).toBe("Terminal command output"); | |
| 318 | + | |
| 319 | + // The command should have executed and returned content | |
| 320 | + expect(result[0].content).toBeDefined(); | |
| 321 | + | |
| 322 | + // We should see the error message we wrote to stderr | |
| 323 | + expect(result[0].content).toContain("This is an error message"); | |
| 324 | + | |
| 325 | + // Verify status field indicates command failure - the exact message format can vary | |
| 326 | + // between different node versions and platforms | |
| 327 | + expect(result[0].status).toContain("Command failed"); | |
| 328 | + }); | |
| 329 | + | |
| 330 | + it("should set appropriate status when a command completes successfully", async () => { | |
| 331 | + // Use a simple command that will succeed | |
| 332 | + const command = `node -e "console.log('success test')"`; | |
| 333 | + const args = { command, waitForCompletion: true }; | |
| 334 | + const extras = createMockExtras(); | |
| 335 | + | |
| 336 | + const result = await runTerminalCommandImpl(args, extras); | |
| 337 | + | |
| 338 | + expect(result).toHaveLength(1); | |
| 339 | + expect(result[0].name).toBe("Terminal"); | |
| 340 | + expect(result[0].content).toContain("success test"); | |
| 341 | + // Verify status field for successful command | |
| 342 | + expect(result[0].status).toBe("Command completed"); | |
| 343 | + }); | |
| 344 | + | |
| 345 | + it("should include status info for background commands in non-streaming mode", async () => { | |
| 346 | + // Use a simple background command | |
| 347 | + const command = `node -e "setTimeout(() => console.log('done'), 300)"`; | |
| 348 | + const args = { command, waitForCompletion: false }; | |
| 349 | + // No streaming in this test (no onPartialOutput) | |
| 350 | + const extras = createMockExtras(); | |
| 351 | + | |
| 352 | + const result = await runTerminalCommandImpl(args, extras); | |
| 353 | + | |
| 354 | + expect(result).toHaveLength(1); | |
| 355 | + expect(result[0].name).toBe("Terminal"); | |
| 356 | + // Verify both content and status fields for background commands | |
| 357 | + expect(result[0].content).toBe("Command is running in the background..."); | |
| 358 | + expect(result[0].status).toBe("Command is running in the background..."); | |
| 359 | + }); | |
| 360 | + | |
| 361 | + it("should handle missing workspace directory gracefully", async () => { | |
| 362 | + // Mock IDE to return empty workspace directories | |
| 363 | + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); | |
| 364 | + | |
| 365 | + // Create IDE mock with empty workspace | |
| 366 | + const mockIde = { | |
| 367 | + getIdeInfo: vi | |
| 368 | + .fn() | |
| 369 | + .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 370 | + getWorkspaceDirs: mockEmptyWorkspace, | |
| 371 | + runCommand: vi.fn(), | |
| 372 | + getIdeSettings: vi.fn(), | |
| 373 | + getDiff: vi.fn(), | |
| 374 | + getClipboardContent: vi.fn(), | |
| 375 | + isTelemetryEnabled: vi.fn(), | |
| 376 | + readFile: vi.fn(), | |
| 377 | + writeFile: vi.fn(), | |
| 378 | + renameFile: vi.fn(), | |
| 379 | + deleteFile: vi.fn(), | |
| 380 | + globFiles: vi.fn(), | |
| 381 | + ls: vi.fn(), | |
| 382 | + }; | |
| 383 | + | |
| 384 | + const extras = { | |
| 385 | + ide: mockIde as unknown as IDE, | |
| 386 | + llm: {} as any, | |
| 387 | + fetch: {} as any, | |
| 388 | + tool: {} as any, | |
| 389 | + toolCallId: "test-tool-call", | |
| 390 | + } as ToolExtras; | |
| 391 | + | |
| 392 | + const command = `node -e "console.log('no workspace test')"`; | |
| 393 | + const args = { command, waitForCompletion: true }; | |
| 394 | + | |
| 395 | + const result = await runTerminalCommandImpl(args, extras); | |
| 396 | + | |
| 397 | + // Should still work - falling back to HOME or cwd | |
| 398 | + expect(result).toHaveLength(1); | |
| 399 | + expect(result[0].name).toBe("Terminal"); | |
| 400 | + expect(result[0].description).toBe("Terminal command output"); | |
| 401 | + expect(result[0].content).toContain("no workspace test"); | |
| 402 | + expect(result[0].status).toBe("Command completed"); | |
| 403 | + | |
| 404 | + // Verify workspace dirs was called but returned empty | |
| 405 | + expect(mockEmptyWorkspace).toHaveBeenCalled(); | |
| 406 | + }); | |
| 407 | + | |
| 408 | + it("should handle case where cwd fallbacks all fail", async () => { | |
| 409 | + // Mock IDE to return empty workspace directories | |
| 410 | + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); | |
| 411 | + | |
| 412 | + // Save original environment variables and process.cwd | |
| 413 | + const originalHome = process.env.HOME; | |
| 414 | + const originalUserProfile = process.env.USERPROFILE; | |
| 415 | + const originalCwd = process.cwd; | |
| 416 | + | |
| 417 | + try { | |
| 418 | + // Mock all fallbacks to fail | |
| 419 | + delete process.env.HOME; | |
| 420 | + delete process.env.USERPROFILE; | |
| 421 | + process.cwd = vi.fn().mockImplementation(() => { | |
| 422 | + throw new Error("Current directory unavailable"); | |
| 423 | + }) as any; | |
| 424 | + | |
| 425 | + // Create IDE mock with empty workspace | |
| 426 | + const mockIde = { | |
| 427 | + getIdeInfo: vi | |
| 428 | + .fn() | |
| 429 | + .mockReturnValue(Promise.resolve({ remoteName: "local" })), | |
| 430 | + getWorkspaceDirs: mockEmptyWorkspace, | |
| 431 | + runCommand: vi.fn(), | |
| 432 | + getIdeSettings: vi.fn(), | |
| 433 | + getDiff: vi.fn(), | |
| 434 | + getClipboardContent: vi.fn(), | |
| 435 | + isTelemetryEnabled: vi.fn(), | |
| 436 | + readFile: vi.fn(), | |
| 437 | + writeFile: vi.fn(), | |
| 438 | + renameFile: vi.fn(), | |
| 439 | + deleteFile: vi.fn(), | |
| 440 | + globFiles: vi.fn(), | |
| 441 | + ls: vi.fn(), | |
| 442 | + }; | |
| 443 | + | |
| 444 | + const extras = { | |
| 445 | + ide: mockIde as unknown as IDE, | |
| 446 | + llm: {} as any, | |
| 447 | + fetch: {} as any, | |
| 448 | + tool: {} as any, | |
| 449 | + toolCallId: "test-tool-call", | |
| 450 | + } as ToolExtras; | |
| 451 | + | |
| 452 | + const command = `node -e "console.log('fallback test')"`; | |
| 453 | + const args = { command, waitForCompletion: true }; | |
| 454 | + | |
| 455 | + // This should now handle the case gracefully by falling back to temp directory | |
| 456 | + const result = await runTerminalCommandImpl(args, extras); | |
| 457 | + | |
| 458 | + // Should work using the temp directory as fallback | |
| 459 | + expect(result).toHaveLength(1); | |
| 460 | + expect(result[0].name).toBe("Terminal"); | |
| 461 | + expect(result[0].content).toContain("fallback test"); | |
| 462 | + expect(result[0].status).toBe("Command completed"); | |
| 463 | + | |
| 464 | + console.log( | |
| 465 | + "Successfully handled cwd fallback to temp directory:", | |
| 466 | + result[0].status, | |
| 467 | + ); | |
| 468 | + } finally { | |
| 469 | + // Always restore original values | |
| 470 | + if (originalHome !== undefined) { | |
| 471 | + process.env.HOME = originalHome; | |
| 472 | + } | |
| 473 | + if (originalUserProfile !== undefined) { | |
| 474 | + process.env.USERPROFILE = originalUserProfile; | |
| 475 | + } | |
| 476 | + process.cwd = originalCwd; | |
| 477 | + } | |
| 478 | + }); | |
| 479 | +}); | |
| 480 | + | |
| 481 | +describe("runTerminalCommandTool.evaluateToolCallPolicy", () => { | |
| 482 | + it("should return base policy for safe commands like echo", () => { | |
| 483 | + const basePolicy = "allowedWithoutPermission"; | |
| 484 | + const args = { command: "echo hello world" }; | |
| 485 | + | |
| 486 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 487 | + basePolicy, | |
| 488 | + args, | |
| 489 | + ); | |
| 490 | + | |
| 491 | + expect(result).toBe("allowedWithoutPermission"); | |
| 492 | + }); | |
| 493 | + | |
| 494 | + it("should respect disabled policy even for non-echo commands", () => { | |
| 495 | + const basePolicy = "disabled"; | |
| 496 | + const args = { command: "ls -la" }; | |
| 497 | + | |
| 498 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 499 | + basePolicy, | |
| 500 | + args, | |
| 501 | + ); | |
| 502 | + | |
| 503 | + expect(result).toBe("disabled"); | |
| 504 | + }); | |
| 505 | + | |
| 506 | + it("should respect disabled policy even for safe commands", () => { | |
| 507 | + const basePolicy = "disabled"; | |
| 508 | + const args = { command: "echo test" }; | |
| 509 | + | |
| 510 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 511 | + basePolicy, | |
| 512 | + args, | |
| 513 | + ); | |
| 514 | + | |
| 515 | + expect(result).toBe("disabled"); | |
| 516 | + }); | |
| 517 | + | |
| 518 | + it("should return base policy for non-echo commands", () => { | |
| 519 | + const basePolicy = "allowedWithoutPermission"; | |
| 520 | + const args = { command: "ls -la" }; | |
| 521 | + | |
| 522 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 523 | + basePolicy, | |
| 524 | + args, | |
| 525 | + ); | |
| 526 | + | |
| 527 | + expect(result).toBe("allowedWithoutPermission"); | |
| 528 | + }); | |
| 529 | + | |
| 530 | + it("should return base policy for git commands", () => { | |
| 531 | + const basePolicy = "allowedWithPermission"; | |
| 532 | + const args = { command: "git status" }; | |
| 533 | + | |
| 534 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 535 | + basePolicy, | |
| 536 | + args, | |
| 537 | + ); | |
| 538 | + | |
| 539 | + expect(result).toBe("allowedWithPermission"); | |
| 540 | + }); | |
| 541 | + | |
| 542 | + it("should handle undefined command gracefully", () => { | |
| 543 | + const basePolicy = "allowedWithoutPermission"; | |
| 544 | + const args = { command: undefined }; | |
| 545 | + | |
| 546 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 547 | + basePolicy, | |
| 548 | + args, | |
| 549 | + ); | |
| 550 | + | |
| 551 | + expect(result).toBe("allowedWithoutPermission"); | |
| 552 | + }); | |
| 553 | + | |
| 554 | + it("should handle null command gracefully", () => { | |
| 555 | + const basePolicy = "allowedWithoutPermission"; | |
| 556 | + const args = { command: null }; | |
| 557 | + | |
| 558 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 559 | + basePolicy, | |
| 560 | + args, | |
| 561 | + ); | |
| 562 | + | |
| 563 | + expect(result).toBe("allowedWithoutPermission"); | |
| 564 | + }); | |
| 565 | + | |
| 566 | + it("should handle empty command string", () => { | |
| 567 | + const basePolicy = "allowedWithoutPermission"; | |
| 568 | + const args = { command: "" }; | |
| 569 | + | |
| 570 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 571 | + basePolicy, | |
| 572 | + args, | |
| 573 | + ); | |
| 574 | + | |
| 575 | + expect(result).toBe("allowedWithoutPermission"); | |
| 576 | + }); | |
| 577 | + | |
| 578 | + it("should disable dangerous commands like rm -rf /", () => { | |
| 579 | + const basePolicy = "allowedWithoutPermission"; | |
| 580 | + const args = { command: "rm -rf /" }; | |
| 581 | + | |
| 582 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 583 | + basePolicy, | |
| 584 | + args, | |
| 585 | + ); | |
| 586 | + | |
| 587 | + expect(result).toBe("disabled"); | |
| 588 | + }); | |
| 589 | + | |
| 590 | + it("should require permission for high-risk network commands", () => { | |
| 591 | + const basePolicy = "allowedWithoutPermission"; | |
| 592 | + const args = { command: "curl http://example.com" }; | |
| 593 | + | |
| 594 | + const result = runTerminalCommandTool.evaluateToolCallPolicy!( | |
| 595 | + basePolicy, | |
| 596 | + args, | |
| 597 | + ); | |
| 598 | + | |
| 599 | + expect(result).toBe("allowedWithPermission"); | |
| 600 | + }); | |
| 601 | +}); |
| @@ -9,6 +9,17 @@ | ||
| 9 | 9 | // TODO includeUnstaged should be an option |
| 10 | 10 | |
| 11 | 11 | const combinedDiff = diffs.join("\n"); |
| 12 | + | |
| 13 | + if (!combinedDiff.trim()) { | |
| 14 | + return [ | |
| 15 | + { | |
| 16 | + name: "Diff", | |
| 17 | + description: "current Git diff", | |
| 18 | + content: "The current diff is empty", | |
| 19 | + }, | |
| 20 | + ]; | |
| 21 | + } | |
| 22 | + | |
| 12 | 23 | const diffLines = combinedDiff.split("\n"); |
| 13 | 24 | |
| 14 | 25 | let truncated = false; |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { ConfigDependentToolParams, Tool } from ".."; |
| 2 | +import { isRecommendedAgentModel } from "../llm/toolSupport"; | |
| 2 | 3 | import * as toolDefinitions from "./definitions"; |
| 3 | 4 | |
| 4 | 5 | // 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. |
| @@ -12,7 +13,6 @@ | ||
| 12 | 13 | toolDefinitions.lsTool, |
| 13 | 14 | toolDefinitions.createRuleBlock, |
| 14 | 15 | toolDefinitions.fetchUrlContentTool, |
| 15 | - toolDefinitions.singleFindAndReplaceTool, | |
| 16 | 16 | ]; |
| 17 | 17 | |
| 18 | 18 | export const getConfigDependentToolDefinitions = ( |
| @@ -33,15 +33,15 @@ | ||
| 33 | 33 | toolDefinitions.viewRepoMapTool, |
| 34 | 34 | toolDefinitions.viewSubdirectoryTool, |
| 35 | 35 | toolDefinitions.codebaseTool, |
| 36 | + toolDefinitions.readFileRangeTool, | |
| 36 | 37 | ); |
| 37 | 38 | } |
| 38 | 39 | |
| 39 | - // OLD SEARCH AND REPLACE IS CURRENTLY NOT USED | |
| 40 | - // toolDefinitions.searchAndReplaceInFileTool | |
| 41 | - if (modelName?.includes("claude") || modelName?.includes("gpt-5")) { | |
| 40 | + if (modelName && isRecommendedAgentModel(modelName)) { | |
| 42 | 41 | tools.push(toolDefinitions.multiEditTool); |
| 43 | 42 | } else { |
| 44 | 43 | tools.push(toolDefinitions.editFileTool); |
| 44 | + tools.push(toolDefinitions.singleFindAndReplaceTool); | |
| 45 | 45 | } |
| 46 | 46 | |
| 47 | 47 | // missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269 |
| @@ -1,7 +1,12 @@ | ||
| 1 | 1 | import { MCPServerStatus, MCPTool } from ".."; |
| 2 | - | |
| 3 | 2 | export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) { |
| 4 | - const serverPrefix = server.name.split(" ").join("_").toLowerCase(); | |
| 3 | + // Replace any sequence of non-alphanumeric characters with a single underscore | |
| 4 | + const serverPrefix = server.name | |
| 5 | + .toLowerCase() | |
| 6 | + .replace(/[^a-z0-9]+/g, "_") | |
| 7 | + .replace(/^_+|_+$/g, "") // Remove leading/trailing underscores | |
| 8 | + .replace(/_+/g, "_"); // Replace multiple sequential underscores with single underscore | |
| 9 | + | |
| 5 | 10 | if (tool.name.startsWith(serverPrefix)) { |
| 6 | 11 | return tool.name; |
| 7 | 12 | } |
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | const createMcpServer = (name: string): MCPServerStatus => ({ |
| 6 | 6 | name, |
| 7 | 7 | errors: [], |
| 8 | + infos: [], | |
| 8 | 9 | prompts: [], |
| 9 | 10 | tools: [], |
| 10 | 11 | resources: [], |
| @@ -56,3 +57,54 @@ | ||
| 56 | 57 | const result = getMCPToolName(server, tool); |
| 57 | 58 | expect(result).toBe("gitlab_create_merge_request"); |
| 58 | 59 | }); |
| 60 | + | |
| 61 | +test("getMCPToolName - handles server names with special characters (parentheses)", () => { | |
| 62 | + const server = createMcpServer("Linear MCP (SSE)"); | |
| 63 | + const tool = createMCPTool("create_issue"); | |
| 64 | + | |
| 65 | + const result = getMCPToolName(server, tool); | |
| 66 | + // Should only contain alphanumeric characters and underscores | |
| 67 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 68 | + expect(result).toBe("linear_mcp_sse_create_issue"); | |
| 69 | +}); | |
| 70 | + | |
| 71 | +test("getMCPToolName - handles server names with dots and other special characters", () => { | |
| 72 | + const server = createMcpServer("My.Server@Test!"); | |
| 73 | + const tool = createMCPTool("test_action"); | |
| 74 | + | |
| 75 | + const result = getMCPToolName(server, tool); | |
| 76 | + // Should only contain alphanumeric characters and underscores | |
| 77 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 78 | + expect(result).toBe("my_server_test_test_action"); | |
| 79 | +}); | |
| 80 | + | |
| 81 | +test("getMCPToolName - handles server names with multiple consecutive special characters", () => { | |
| 82 | + const server = createMcpServer("Server@@##Name"); | |
| 83 | + const tool = createMCPTool("action"); | |
| 84 | + | |
| 85 | + const result = getMCPToolName(server, tool); | |
| 86 | + // Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores) | |
| 87 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 88 | + expect(result).toBe("server_name_action"); | |
| 89 | +}); | |
| 90 | + | |
| 91 | +test("getMCPToolName - handles server names with hyphens", () => { | |
| 92 | + const server = createMcpServer("My-Server-Name"); | |
| 93 | + const tool = createMCPTool("test_action"); | |
| 94 | + | |
| 95 | + const result = getMCPToolName(server, tool); | |
| 96 | + // Should only contain alphanumeric characters and underscores | |
| 97 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 98 | + expect(result).toBe("my_server_name_test_action"); | |
| 99 | +}); | |
| 100 | + | |
| 101 | +test("getMCPToolName - handles multiple consecutive underscores in server name", () => { | |
| 102 | + const server = createMcpServer("Linear__MCP"); | |
| 103 | + const tool = createMCPTool("create_issue"); | |
| 104 | + | |
| 105 | + const result = getMCPToolName(server, tool); | |
| 106 | + // Should only contain alphanumeric characters and single underscores | |
| 107 | + expect(result).toMatch(/^[a-zA-Z0-9_]+$/); | |
| 108 | + expect(result).not.toMatch(/__/); | |
| 109 | + expect(result).toBe("linear_mcp_create_issue"); | |
| 110 | +}); |
| @@ -40,6 +40,24 @@ | ||
| 40 | 40 | return getStringArg(args, argName, allowEmpty); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | +export function getNumberArg(args: any, argName: string): number { | |
| 44 | + if (!args || !(argName in args)) { | |
| 45 | + throw new Error(`Argument \`${argName}\` is required (type number)`); | |
| 46 | + } | |
| 47 | + const value = args[argName]; | |
| 48 | + if (typeof value === "string") { | |
| 49 | + const parsed = parseInt(value, 10); | |
| 50 | + if (isNaN(parsed)) { | |
| 51 | + throw new Error(`Argument \`${argName}\` must be a valid number`); | |
| 52 | + } | |
| 53 | + return parsed; | |
| 54 | + } | |
| 55 | + if (typeof value !== "number" || isNaN(value)) { | |
| 56 | + throw new Error(`Argument \`${argName}\` must be a valid number`); | |
| 57 | + } | |
| 58 | + return Math.floor(value); // Ensure integer for line numbers (supports negative numbers) | |
| 59 | +} | |
| 60 | + | |
| 43 | 61 | export function getBooleanArg(args: any, argName: string, required = false) { |
| 44 | 62 | if (!args || !(argName in args)) { |
| 45 | 63 | if (required) { |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { ToolCallDelta } from ".."; |
| 3 | 3 | import { |
| 4 | 4 | getBooleanArg, |
| 5 | + getNumberArg, | |
| 5 | 6 | getOptionalStringArg, |
| 6 | 7 | getStringArg, |
| 7 | 8 | safeParseToolCallArgs, |
| @@ -246,3 +247,86 @@ | ||
| 246 | 247 | ); |
| 247 | 248 | }); |
| 248 | 249 | }); |
| 250 | + | |
| 251 | +describe("getNumberArg", () => { | |
| 252 | + it("should return number argument when valid", () => { | |
| 253 | + const args = { count: 42 }; | |
| 254 | + const result = getNumberArg(args, "count"); | |
| 255 | + expect(result).toBe(42); | |
| 256 | + }); | |
| 257 | + | |
| 258 | + it("should parse string numbers", () => { | |
| 259 | + const args = { count: "42" }; | |
| 260 | + const result = getNumberArg(args, "count"); | |
| 261 | + expect(result).toBe(42); | |
| 262 | + }); | |
| 263 | + | |
| 264 | + it("should floor decimal numbers", () => { | |
| 265 | + const args = { count: 42.7 }; | |
| 266 | + const result = getNumberArg(args, "count"); | |
| 267 | + expect(result).toBe(42); | |
| 268 | + }); | |
| 269 | + | |
| 270 | + it("should parse and floor string decimal numbers", () => { | |
| 271 | + const args = { count: "42.7" }; | |
| 272 | + const result = getNumberArg(args, "count"); | |
| 273 | + expect(result).toBe(42); | |
| 274 | + }); | |
| 275 | + | |
| 276 | + it("should throw error when argument is missing", () => { | |
| 277 | + const args = { otherArg: 42 }; | |
| 278 | + expect(() => getNumberArg(args, "count")).toThrowError( | |
| 279 | + "Argument `count` is required (type number)", | |
| 280 | + ); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + it("should throw error when argument is not a number", () => { | |
| 284 | + const argsString = { count: "not-a-number" }; | |
| 285 | + const argsBoolean = { count: true }; | |
| 286 | + const argsObject = { count: {} }; | |
| 287 | + | |
| 288 | + expect(() => getNumberArg(argsString, "count")).toThrowError( | |
| 289 | + "Argument `count` must be a valid number", | |
| 290 | + ); | |
| 291 | + expect(() => getNumberArg(argsBoolean, "count")).toThrowError( | |
| 292 | + "Argument `count` must be a valid number", | |
| 293 | + ); | |
| 294 | + expect(() => getNumberArg(argsObject, "count")).toThrowError( | |
| 295 | + "Argument `count` must be a valid number", | |
| 296 | + ); | |
| 297 | + }); | |
| 298 | + | |
| 299 | + it("should throw error when argument is NaN", () => { | |
| 300 | + const args = { count: NaN }; | |
| 301 | + expect(() => getNumberArg(args, "count")).toThrowError( | |
| 302 | + "Argument `count` must be a valid number", | |
| 303 | + ); | |
| 304 | + }); | |
| 305 | + | |
| 306 | + it("should handle negative numbers", () => { | |
| 307 | + const args = { count: -5 }; | |
| 308 | + const result = getNumberArg(args, "count"); | |
| 309 | + expect(result).toBe(-5); | |
| 310 | + }); | |
| 311 | + | |
| 312 | + it("should handle negative string numbers", () => { | |
| 313 | + const args = { count: "-10" }; | |
| 314 | + const result = getNumberArg(args, "count"); | |
| 315 | + expect(result).toBe(-10); | |
| 316 | + }); | |
| 317 | + | |
| 318 | + it("should handle zero", () => { | |
| 319 | + const args = { count: 0 }; | |
| 320 | + const result = getNumberArg(args, "count"); | |
| 321 | + expect(result).toBe(0); | |
| 322 | + }); | |
| 323 | + | |
| 324 | + it("should handle null or undefined args", () => { | |
| 325 | + expect(() => getNumberArg(null, "count")).toThrowError( | |
| 326 | + "Argument `count` is required (type number)", | |
| 327 | + ); | |
| 328 | + expect(() => getNumberArg(undefined, "count")).toThrowError( | |
| 329 | + "Argument `count` is required (type number)", | |
| 330 | + ); | |
| 331 | + }); | |
| 332 | +}); |
| @@ -44,9 +44,8 @@ | ||
| 44 | 44 | isSupportedLanceDbCpuTargetForLinux: boolean; |
| 45 | 45 | sharedConfig: SharedConfigSchema; |
| 46 | 46 | failedDocs: SiteIndexingConfig[]; |
| 47 | - shownDeprecatedProviderWarnings: { | |
| 48 | - [providerTitle: string]: boolean; | |
| 49 | - }; | |
| 47 | + shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean }; | |
| 48 | + autoUpdateCli: boolean; | |
| 50 | 49 | mcpOauthStorage: { |
| 51 | 50 | [serverUrl: string]: { |
| 52 | 51 | clientInformation?: OAuthClientInformationFull; |
| @@ -66,16 +65,7 @@ | ||
| 66 | 65 | ) { |
| 67 | 66 | const filepath = getGlobalContextFilePath(); |
| 68 | 67 | if (!fs.existsSync(filepath)) { |
| 69 | - fs.writeFileSync( | |
| 70 | - filepath, | |
| 71 | - JSON.stringify( | |
| 72 | - { | |
| 73 | - [key]: value, | |
| 74 | - }, | |
| 75 | - null, | |
| 76 | - 2, | |
| 77 | - ), | |
| 78 | - ); | |
| 68 | + fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2)); | |
| 79 | 69 | } else { |
| 80 | 70 | const data = fs.readFileSync(filepath, "utf-8"); |
| 81 | 71 | |
| @@ -113,10 +103,7 @@ | ||
| 113 | 103 | } |
| 114 | 104 | |
| 115 | 105 | // Recreate the file with salvaged values plus the new value |
| 116 | - const newData = { | |
| 117 | - ...salvaged, | |
| 118 | - [key]: value, | |
| 119 | - }; | |
| 106 | + const newData = { ...salvaged, [key]: value }; | |
| 120 | 107 | |
| 121 | 108 | fs.writeFileSync(filepath, JSON.stringify(newData, null, 2)); |
| 122 | 109 | return; |
| @@ -174,10 +161,7 @@ | ||
| 174 | 161 | newValues: Partial<SharedConfigSchema>, |
| 175 | 162 | ): SharedConfigSchema { |
| 176 | 163 | const currentSharedConfig = this.getSharedConfig(); |
| 177 | - const updatedSharedConfig = { | |
| 178 | - ...currentSharedConfig, | |
| 179 | - ...newValues, | |
| 180 | - }; | |
| 164 | + const updatedSharedConfig = { ...currentSharedConfig, ...newValues }; | |
| 181 | 165 | this.update("sharedConfig", updatedSharedConfig); |
| 182 | 166 | return updatedSharedConfig; |
| 183 | 167 | } |
| @@ -189,10 +173,7 @@ | ||
| 189 | 173 | ): GlobalContextModelSelections { |
| 190 | 174 | const currentSelections = this.get("selectedModelsByProfileId") ?? {}; |
| 191 | 175 | const forProfile = currentSelections[profileId] ?? {}; |
| 192 | - const newSelections = { | |
| 193 | - ...forProfile, | |
| 194 | - [role]: title, | |
| 195 | - }; | |
| 176 | + const newSelections = { ...forProfile, [role]: title }; | |
| 196 | 177 | |
| 197 | 178 | this.update("selectedModelsByProfileId", { |
| 198 | 179 | ...currentSelections, |
| @@ -103,7 +103,6 @@ | ||
| 103 | 103 | |
| 104 | 104 | return undefined; |
| 105 | 105 | } catch (error) { |
| 106 | - console.debug("Error generating chat title:", error); | |
| 107 | 106 | return undefined; |
| 108 | 107 | } |
| 109 | 108 | } |
| @@ -10,3 +10,44 @@ | ||
| 10 | 10 | } |
| 11 | 11 | return err; |
| 12 | 12 | } |
| 13 | + | |
| 14 | +export class ContinueError extends Error { | |
| 15 | + reason: ContinueErrorReason; | |
| 16 | + | |
| 17 | + constructor(reason: ContinueErrorReason, message?: string) { | |
| 18 | + super(message); | |
| 19 | + this.reason = reason; | |
| 20 | + this.name = "ContinueError"; | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +export enum ContinueErrorReason { | |
| 25 | + // Find and Replace validation errors | |
| 26 | + FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings", | |
| 27 | + FindAndReplaceMissingOldString = "find_and_replace_missing_old_string", | |
| 28 | + FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string", | |
| 29 | + FindAndReplaceMissingNewString = "find_and_replace_missing_new_string", | |
| 30 | + FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found", | |
| 31 | + FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences", | |
| 32 | + FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath", | |
| 33 | + | |
| 34 | + // Multi-edit | |
| 35 | + MultiEditEditsArrayRequired = "multi_edit_edits_array_required", | |
| 36 | + MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty", | |
| 37 | + MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation", | |
| 38 | + MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first", | |
| 39 | + | |
| 40 | + // General Edit | |
| 41 | + EditToolFileNotRead = "edit_tool_file_not_yet_read", | |
| 42 | + | |
| 43 | + // General File | |
| 44 | + FileAlreadyExists = "file_already_exists", | |
| 45 | + FileNotFound = "file_not_found", | |
| 46 | + FileWriteError = "file_write_error", | |
| 47 | + FileIsSecurityConcern = "file_is_security_concern", | |
| 48 | + ParentDirectoryNotFound = "parent_directory_not_found", | |
| 49 | + | |
| 50 | + // Other | |
| 51 | + Unspecified = "unspecified", | |
| 52 | + Unknown = "unknown", | |
| 53 | +} |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | |
| 3 | -import { Session, SessionMetadata } from "../index.js"; | |
| 3 | +import { Session, BaseSessionMetadata } from "../index.js"; | |
| 4 | 4 | import { ListHistoryOptions } from "../protocol/core.js"; |
| 5 | 5 | |
| 6 | 6 | import { NEW_SESSION_TITLE } from "./constants.js"; |
| @@ -22,14 +22,14 @@ | ||
| 22 | 22 | } |
| 23 | 23 | |
| 24 | 24 | export class HistoryManager { |
| 25 | - list(options: ListHistoryOptions): SessionMetadata[] { | |
| 25 | + list(options: ListHistoryOptions): BaseSessionMetadata[] { | |
| 26 | 26 | const filepath = getSessionsListPath(); |
| 27 | 27 | if (!fs.existsSync(filepath)) { |
| 28 | 28 | return []; |
| 29 | 29 | } |
| 30 | 30 | const content = fs.readFileSync(filepath, "utf8"); |
| 31 | 31 | |
| 32 | - let sessions = safeParseArray<SessionMetadata>(content) ?? []; | |
| 32 | + let sessions = safeParseArray<BaseSessionMetadata>(content) ?? []; | |
| 33 | 33 | sessions = sessions |
| 34 | 34 | .filter((session: any) => { |
| 35 | 35 | // Filter out old format |
| @@ -59,7 +59,7 @@ | ||
| 59 | 59 | const sessionsListFile = getSessionsListPath(); |
| 60 | 60 | const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); |
| 61 | 61 | let sessionsList = |
| 62 | - safeParseArray<SessionMetadata>( | |
| 62 | + safeParseArray<BaseSessionMetadata>( | |
| 63 | 63 | sessionsListRaw, |
| 64 | 64 | "Error parsing sessions.json", |
| 65 | 65 | ) ?? []; |
| @@ -118,7 +118,7 @@ | ||
| 118 | 118 | try { |
| 119 | 119 | const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8"); |
| 120 | 120 | |
| 121 | - let sessionsList: SessionMetadata[]; | |
| 121 | + let sessionsList: BaseSessionMetadata[]; | |
| 122 | 122 | try { |
| 123 | 123 | sessionsList = JSON.parse(rawSessionsList); |
| 124 | 124 | } catch (e) { |
| @@ -141,7 +141,7 @@ | ||
| 141 | 141 | } |
| 142 | 142 | |
| 143 | 143 | if (!found) { |
| 144 | - const sessionMetadata: SessionMetadata = { | |
| 144 | + const sessionMetadata: BaseSessionMetadata = { | |
| 145 | 145 | sessionId: session.sessionId, |
| 146 | 146 | title: session.title, |
| 147 | 147 | dateCreated: String(Date.now()), |
| @@ -0,0 +1,105 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import { homedir } from "node:os"; | |
| 3 | +import { fileURLToPath, pathToFileURL } from "node:url"; | |
| 4 | +import path from "path"; | |
| 5 | + | |
| 6 | +import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js"; | |
| 7 | +import { ChatMessage, IDE } from "../index.js"; | |
| 8 | +import { renderChatMessage } from "../util/messageContent.js"; | |
| 9 | +import { getContinueGlobalPath } from "../util/paths.js"; | |
| 10 | + | |
| 11 | +// If useful elsewhere, helper funcs should move to core/util/index.ts or similar | |
| 12 | +function getOffsetDatetime(date: Date): Date { | |
| 13 | + const offset = date.getTimezoneOffset(); | |
| 14 | + const offsetHours = Math.floor(offset / 60); | |
| 15 | + const offsetMinutes = offset % 60; | |
| 16 | + date.setHours(date.getHours() - offsetHours); | |
| 17 | + date.setMinutes(date.getMinutes() - offsetMinutes); | |
| 18 | + | |
| 19 | + return date; | |
| 20 | +} | |
| 21 | + | |
| 22 | +function asBasicISOString(date: Date): string { | |
| 23 | + const isoString = date.toISOString(); | |
| 24 | + | |
| 25 | + return isoString.replace(/[-:]|(\.\d+Z)/g, ""); | |
| 26 | +} | |
| 27 | + | |
| 28 | +function reformatCodeBlocks(msgText: string): string { | |
| 29 | + const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; | |
| 30 | + msgText = msgText.replace( | |
| 31 | + codeBlockFenceRegex, | |
| 32 | + (match, metadata, filename, extension) => { | |
| 33 | + const lang = languageForFilepath(filename); | |
| 34 | + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; | |
| 35 | + }, | |
| 36 | + ); | |
| 37 | + // Appease the markdown linter | |
| 38 | + return msgText.replace(/```\n```/g, "```\n\n```"); | |
| 39 | +} | |
| 40 | + | |
| 41 | +export function toMarkDown(history: ChatMessage[], time?: Date): string { | |
| 42 | + if (!time) { | |
| 43 | + time = new Date(); | |
| 44 | + } | |
| 45 | + let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`; | |
| 46 | + | |
| 47 | + for (const msg of history) { | |
| 48 | + let msgText = renderChatMessage(msg); | |
| 49 | + if (!msgText) { | |
| 50 | + continue; // Skip messages without content | |
| 51 | + } | |
| 52 | + | |
| 53 | + if (msg.role === "user" && msgText.search("```") > -1) { | |
| 54 | + msgText = reformatCodeBlocks(msgText); | |
| 55 | + } | |
| 56 | + | |
| 57 | + // format messages as blockquotes | |
| 58 | + msgText = msgText.replace(/^/gm, "> "); | |
| 59 | + | |
| 60 | + content += `\n\n#### ${ | |
| 61 | + msg.role === "user" ? "_User_" : "_Assistant_" | |
| 62 | + }\n\n${msgText}`; | |
| 63 | + } | |
| 64 | + return content; | |
| 65 | +} | |
| 66 | + | |
| 67 | +export async function shareSession( | |
| 68 | + ide: IDE, | |
| 69 | + history: ChatMessage[], | |
| 70 | + outputDir?: string, | |
| 71 | +) { | |
| 72 | + const now = new Date(); | |
| 73 | + const content = toMarkDown(history, now); | |
| 74 | + | |
| 75 | + outputDir = outputDir ?? getContinueGlobalPath(); | |
| 76 | + | |
| 77 | + if (outputDir.startsWith("~")) { | |
| 78 | + outputDir = outputDir.replace(/^~/, homedir); | |
| 79 | + } else if ( | |
| 80 | + outputDir.startsWith("./") || | |
| 81 | + outputDir.startsWith(".\\") || | |
| 82 | + outputDir === "." | |
| 83 | + ) { | |
| 84 | + const workspaceDirs = await ide.getWorkspaceDirs(); | |
| 85 | + // Although the most common situation is to have one directory open in a | |
| 86 | + // workspace it's also possible to have just a file open without an | |
| 87 | + // associated directory or to use multi-root workspaces in which multiple | |
| 88 | + // folders are included. We default to using the first item in the list, if | |
| 89 | + // it exists. | |
| 90 | + const workspaceDirectory = workspaceDirs?.[0] || ""; | |
| 91 | + outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); | |
| 92 | + } | |
| 93 | + | |
| 94 | + if (!fs.existsSync(outputDir)) { | |
| 95 | + fs.mkdirSync(outputDir, { recursive: true }); | |
| 96 | + } | |
| 97 | + | |
| 98 | + const dtString = asBasicISOString(getOffsetDatetime(now)); | |
| 99 | + const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? | |
| 100 | + | |
| 101 | + const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ | |
| 102 | + await ide.writeFile(fileUrl, content); | |
| 103 | + await ide.openFile(fileUrl); | |
| 104 | + return fileUrl; | |
| 105 | +} |
| @@ -0,0 +1,59 @@ | ||
| 1 | +import { exec } from "node:child_process"; | |
| 2 | +import { IDE } from ".."; | |
| 3 | + | |
| 4 | +export async function isLemonadeInstalled(): Promise<boolean> { | |
| 5 | + // On Windows, check if lemonade-server command exists | |
| 6 | + if (process.platform === "win32") { | |
| 7 | + return new Promise((resolve, _reject) => { | |
| 8 | + exec("where.exe lemonade-server", (error, _stdout, _stderr) => { | |
| 9 | + resolve(!error); | |
| 10 | + }); | |
| 11 | + }); | |
| 12 | + } | |
| 13 | + | |
| 14 | + // On Linux, check if the health endpoint is accessible | |
| 15 | + try { | |
| 16 | + const response = await fetch("http://localhost:8000/api/v1/health", { | |
| 17 | + method: "GET", | |
| 18 | + signal: AbortSignal.timeout(3000), // 3 second timeout | |
| 19 | + }); | |
| 20 | + | |
| 21 | + if (response.ok) { | |
| 22 | + const data = await response.json(); | |
| 23 | + return data.status === "ok"; | |
| 24 | + } | |
| 25 | + return false; | |
| 26 | + } catch { | |
| 27 | + return false; | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +export async function startLocalLemonade(ide: IDE): Promise<any> { | |
| 32 | + let startCommand: string | undefined; | |
| 33 | + | |
| 34 | + switch (process.platform) { | |
| 35 | + case "linux": // Linux | |
| 36 | + // On Linux, direct users to start Lemonade manually | |
| 37 | + return ide.showToast( | |
| 38 | + "info", | |
| 39 | + "Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.", | |
| 40 | + ); | |
| 41 | + | |
| 42 | + case "win32": // Windows | |
| 43 | + startCommand = "lemonade-server serve\n"; | |
| 44 | + break; | |
| 45 | + | |
| 46 | + default: | |
| 47 | + return ide.showToast( | |
| 48 | + "error", | |
| 49 | + "Cannot start Lemonade: platform not supported!", | |
| 50 | + ); | |
| 51 | + } | |
| 52 | + | |
| 53 | + if (startCommand) { | |
| 54 | + return ide.runCommand(startCommand, { | |
| 55 | + reuseTerminal: true, | |
| 56 | + terminalName: "Start Lemonade", | |
| 57 | + }); | |
| 58 | + } | |
| 59 | +} |
| @@ -35,6 +35,21 @@ | ||
| 35 | 35 | return contextItems.map((item) => item.content).join("\n\n"); |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | +export function renderContextItemsWithStatus(contextItems: any[]): string { | |
| 39 | + return contextItems | |
| 40 | + .map((item) => { | |
| 41 | + let result = item.content; | |
| 42 | + | |
| 43 | + // If this item has a status, append it directly after the content | |
| 44 | + if (item.status) { | |
| 45 | + result += `\n[Status: ${item.status}]`; | |
| 46 | + } | |
| 47 | + | |
| 48 | + return result; | |
| 49 | + }) | |
| 50 | + .join("\n\n"); | |
| 51 | +} | |
| 52 | + | |
| 38 | 53 | export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { |
| 39 | 54 | switch (message.role) { |
| 40 | 55 | case "user": |
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | transform: true, |
| 22 | 22 | showWhateverWeHaveAtXMs: 300, |
| 23 | 23 | // Experimental options: true = enabled, false = disabled, number = enabled w priority |
| 24 | - experimental_includeClipboard: true, | |
| 24 | + experimental_includeClipboard: false, | |
| 25 | 25 | experimental_includeRecentlyVisitedRanges: true, |
| 26 | 26 | experimental_includeRecentlyEditedRanges: true, |
| 27 | 27 | experimental_includeDiff: true, |
| @@ -1,73 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - markProcessAsBackgrounded, | |
| 3 | - isProcessBackgrounded, | |
| 4 | - removeBackgroundedProcess, | |
| 5 | -} from "./processTerminalBackgroundStates"; | |
| 6 | - | |
| 7 | -describe("processTerminalBackgroundStates", () => { | |
| 8 | - beforeEach(() => { | |
| 9 | - // Clear any backgrounded processes before each test | |
| 10 | - const backgroundedProcesses = Array.from( | |
| 11 | - Object.getOwnPropertySymbols(global), | |
| 12 | - ).find( | |
| 13 | - (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)", | |
| 14 | - ); | |
| 15 | - | |
| 16 | - if (backgroundedProcesses) { | |
| 17 | - // Reset the map by reimporting the module | |
| 18 | - jest.resetModules(); | |
| 19 | - } | |
| 20 | - }); | |
| 21 | - | |
| 22 | - test("should mark a process as backgrounded", () => { | |
| 23 | - const toolCallId = "test-123"; | |
| 24 | - markProcessAsBackgrounded(toolCallId); | |
| 25 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 26 | - }); | |
| 27 | - | |
| 28 | - test("should correctly identify non-backgrounded processes", () => { | |
| 29 | - const toolCallId = "test-123"; | |
| 30 | - const anotherToolCallId = "test-456"; | |
| 31 | - | |
| 32 | - markProcessAsBackgrounded(toolCallId); | |
| 33 | - | |
| 34 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 35 | - expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - test("should remove a process from backgrounded state", () => { | |
| 39 | - const toolCallId = "test-123"; | |
| 40 | - | |
| 41 | - markProcessAsBackgrounded(toolCallId); | |
| 42 | - expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 43 | - | |
| 44 | - removeBackgroundedProcess(toolCallId); | |
| 45 | - expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 46 | - }); | |
| 47 | - | |
| 48 | - test("should handle removing non-existent processes", () => { | |
| 49 | - const toolCallId = "test-123"; | |
| 50 | - | |
| 51 | - // Should not throw an error | |
| 52 | - removeBackgroundedProcess(toolCallId); | |
| 53 | - expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 54 | - }); | |
| 55 | - | |
| 56 | - test("should handle multiple processes", () => { | |
| 57 | - const toolCallId1 = "test-123"; | |
| 58 | - const toolCallId2 = "test-456"; | |
| 59 | - const toolCallId3 = "test-789"; | |
| 60 | - | |
| 61 | - markProcessAsBackgrounded(toolCallId1); | |
| 62 | - markProcessAsBackgrounded(toolCallId2); | |
| 63 | - | |
| 64 | - expect(isProcessBackgrounded(toolCallId1)).toBe(true); | |
| 65 | - expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 66 | - expect(isProcessBackgrounded(toolCallId3)).toBe(false); | |
| 67 | - | |
| 68 | - removeBackgroundedProcess(toolCallId1); | |
| 69 | - | |
| 70 | - expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 71 | - expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 72 | - }); | |
| 73 | -}); |
| @@ -1,17 +0,0 @@ | ||
| 1 | -// Track which processes have been backgrounded | |
| 2 | -const processTerminalBackgroundStates = new Map<string, boolean>(); | |
| 3 | - | |
| 4 | -// Function to mark a process as backgrounded | |
| 5 | -export function markProcessAsBackgrounded(toolCallId: string): void { | |
| 6 | - processTerminalBackgroundStates.set(toolCallId, true); | |
| 7 | -} | |
| 8 | - | |
| 9 | -// Function to check if a process is backgrounded | |
| 10 | -export function isProcessBackgrounded(toolCallId: string): boolean { | |
| 11 | - return processTerminalBackgroundStates.has(toolCallId); | |
| 12 | -} | |
| 13 | - | |
| 14 | -// Function to remove a process from the backgrounded processes map | |
| 15 | -export function removeBackgroundedProcess(toolCallId: string): void { | |
| 16 | - processTerminalBackgroundStates.delete(toolCallId); | |
| 17 | -} |
| @@ -0,0 +1,367 @@ | ||
| 1 | +import { ChildProcess } from "child_process"; | |
| 2 | +import { | |
| 3 | + clearAllBackgroundProcesses, | |
| 4 | + getAllBackgroundedProcessIds, | |
| 5 | + getAllRunningProcessIds, | |
| 6 | + getRunningProcess, | |
| 7 | + isProcessBackgrounded, | |
| 8 | + isProcessRunning, | |
| 9 | + killAllRunningTerminalProcesses, | |
| 10 | + killMultipleTerminalProcesses, | |
| 11 | + killTerminalProcess, | |
| 12 | + markProcessAsBackgrounded, | |
| 13 | + markProcessAsRunning, | |
| 14 | + removeBackgroundedProcess, | |
| 15 | + removeRunningProcess, | |
| 16 | + updateProcessOutput, | |
| 17 | +} from "./processTerminalStates"; | |
| 18 | + | |
| 19 | +// Mock ChildProcess | |
| 20 | +const createMockProcess = ( | |
| 21 | + pid: number = 123, | |
| 22 | + killed: boolean = false, | |
| 23 | +): jest.Mocked<ChildProcess> => { | |
| 24 | + const mockProcess = { | |
| 25 | + pid, | |
| 26 | + killed, | |
| 27 | + kill: jest.fn(), | |
| 28 | + } as unknown as jest.Mocked<ChildProcess>; | |
| 29 | + | |
| 30 | + // Make kill() update the killed property | |
| 31 | + mockProcess.kill.mockImplementation(() => { | |
| 32 | + (mockProcess as any).killed = true; | |
| 33 | + return true; | |
| 34 | + }); | |
| 35 | + | |
| 36 | + return mockProcess; | |
| 37 | +}; | |
| 38 | + | |
| 39 | +describe("processTerminalStates", () => { | |
| 40 | + beforeEach(() => { | |
| 41 | + // Clear all running processes | |
| 42 | + const runningIds = getAllRunningProcessIds(); | |
| 43 | + runningIds.forEach((id) => removeRunningProcess(id)); | |
| 44 | + | |
| 45 | + // Clear all backgrounded processes | |
| 46 | + const backgroundedIds = getAllBackgroundedProcessIds(); | |
| 47 | + backgroundedIds.forEach((id) => removeBackgroundedProcess(id)); | |
| 48 | + | |
| 49 | + // Clear all timers | |
| 50 | + jest.clearAllTimers(); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + test("should mark a process as backgrounded", () => { | |
| 54 | + const toolCallId = "test-123"; | |
| 55 | + markProcessAsBackgrounded(toolCallId); | |
| 56 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + test("should correctly identify non-backgrounded processes", () => { | |
| 60 | + const toolCallId = "test-123"; | |
| 61 | + const anotherToolCallId = "test-456"; | |
| 62 | + | |
| 63 | + markProcessAsBackgrounded(toolCallId); | |
| 64 | + | |
| 65 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 66 | + expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + test("should remove a process from backgrounded state", () => { | |
| 70 | + const toolCallId = "test-123"; | |
| 71 | + | |
| 72 | + markProcessAsBackgrounded(toolCallId); | |
| 73 | + expect(isProcessBackgrounded(toolCallId)).toBe(true); | |
| 74 | + | |
| 75 | + removeBackgroundedProcess(toolCallId); | |
| 76 | + expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + test("should handle removing non-existent processes", () => { | |
| 80 | + const toolCallId = "test-123"; | |
| 81 | + | |
| 82 | + // Should not throw an error | |
| 83 | + removeBackgroundedProcess(toolCallId); | |
| 84 | + expect(isProcessBackgrounded(toolCallId)).toBe(false); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + test("should handle multiple processes", () => { | |
| 88 | + const toolCallId1 = "test-123"; | |
| 89 | + const toolCallId2 = "test-456"; | |
| 90 | + const toolCallId3 = "test-789"; | |
| 91 | + | |
| 92 | + markProcessAsBackgrounded(toolCallId1); | |
| 93 | + markProcessAsBackgrounded(toolCallId2); | |
| 94 | + | |
| 95 | + expect(isProcessBackgrounded(toolCallId1)).toBe(true); | |
| 96 | + expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 97 | + expect(isProcessBackgrounded(toolCallId3)).toBe(false); | |
| 98 | + | |
| 99 | + removeBackgroundedProcess(toolCallId1); | |
| 100 | + | |
| 101 | + expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 102 | + expect(isProcessBackgrounded(toolCallId2)).toBe(true); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + describe("foreground process functions", () => { | |
| 106 | + test("should mark a process as running", () => { | |
| 107 | + const toolCallId = "test-123"; | |
| 108 | + const mockProcess = createMockProcess(); | |
| 109 | + const mockCallback = jest.fn(); | |
| 110 | + const initialOutput = "initial output"; | |
| 111 | + | |
| 112 | + markProcessAsRunning( | |
| 113 | + toolCallId, | |
| 114 | + mockProcess, | |
| 115 | + mockCallback, | |
| 116 | + initialOutput, | |
| 117 | + ); | |
| 118 | + | |
| 119 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 120 | + expect(getRunningProcess(toolCallId)).toBe(mockProcess); | |
| 121 | + }); | |
| 122 | + | |
| 123 | + test("should handle process without callback or initial output", () => { | |
| 124 | + const toolCallId = "test-123"; | |
| 125 | + const mockProcess = createMockProcess(); | |
| 126 | + | |
| 127 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 128 | + | |
| 129 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 130 | + expect(getRunningProcess(toolCallId)).toBe(mockProcess); | |
| 131 | + }); | |
| 132 | + | |
| 133 | + test("should correctly identify non-running processes", () => { | |
| 134 | + const toolCallId = "test-123"; | |
| 135 | + const anotherToolCallId = "test-456"; | |
| 136 | + const mockProcess = createMockProcess(); | |
| 137 | + | |
| 138 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 139 | + | |
| 140 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 141 | + expect(isProcessRunning(anotherToolCallId)).toBe(false); | |
| 142 | + }); | |
| 143 | + | |
| 144 | + test("should update process output", () => { | |
| 145 | + const toolCallId = "test-123"; | |
| 146 | + const mockProcess = createMockProcess(); | |
| 147 | + const initialOutput = "initial"; | |
| 148 | + const updatedOutput = "updated output"; | |
| 149 | + | |
| 150 | + markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput); | |
| 151 | + updateProcessOutput(toolCallId, updatedOutput); | |
| 152 | + | |
| 153 | + // We can't directly test the output value, but we can ensure the function doesn't throw | |
| 154 | + expect(() => | |
| 155 | + updateProcessOutput(toolCallId, updatedOutput), | |
| 156 | + ).not.toThrow(); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + test("should handle updating output for non-existent process", () => { | |
| 160 | + const toolCallId = "non-existent"; | |
| 161 | + | |
| 162 | + expect(() => | |
| 163 | + updateProcessOutput(toolCallId, "some output"), | |
| 164 | + ).not.toThrow(); | |
| 165 | + }); | |
| 166 | + | |
| 167 | + test("should remove a process from running state", () => { | |
| 168 | + const toolCallId = "test-123"; | |
| 169 | + const mockProcess = createMockProcess(); | |
| 170 | + | |
| 171 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 172 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 173 | + | |
| 174 | + removeRunningProcess(toolCallId); | |
| 175 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 176 | + expect(getRunningProcess(toolCallId)).toBeUndefined(); | |
| 177 | + }); | |
| 178 | + | |
| 179 | + test("should handle removing non-existent running processes", () => { | |
| 180 | + const toolCallId = "test-123"; | |
| 181 | + | |
| 182 | + expect(() => removeRunningProcess(toolCallId)).not.toThrow(); | |
| 183 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 184 | + }); | |
| 185 | + | |
| 186 | + test("should return undefined for non-existent running process", () => { | |
| 187 | + const toolCallId = "non-existent"; | |
| 188 | + | |
| 189 | + expect(getRunningProcess(toolCallId)).toBeUndefined(); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("terminal command cancellation", () => { | |
| 194 | + beforeEach(() => { | |
| 195 | + jest.useFakeTimers(); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + afterEach(() => { | |
| 199 | + jest.useRealTimers(); | |
| 200 | + }); | |
| 201 | + | |
| 202 | + test("should cancel a running terminal command", async () => { | |
| 203 | + const toolCallId = "test-123"; | |
| 204 | + const mockProcess = createMockProcess(); | |
| 205 | + | |
| 206 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 207 | + expect(isProcessRunning(toolCallId)).toBe(true); | |
| 208 | + | |
| 209 | + await killTerminalProcess(toolCallId); | |
| 210 | + | |
| 211 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 212 | + expect(isProcessRunning(toolCallId)).toBe(false); | |
| 213 | + }); | |
| 214 | + | |
| 215 | + test("should handle cancelling non-existent process", async () => { | |
| 216 | + const toolCallId = "non-existent"; | |
| 217 | + | |
| 218 | + await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow(); | |
| 219 | + }); | |
| 220 | + | |
| 221 | + test("should handle cancelling already killed process", async () => { | |
| 222 | + const toolCallId = "test-123"; | |
| 223 | + const mockProcess = createMockProcess(123, true); // Already killed | |
| 224 | + | |
| 225 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 226 | + | |
| 227 | + await killTerminalProcess(toolCallId); | |
| 228 | + | |
| 229 | + expect(mockProcess.kill).not.toHaveBeenCalled(); | |
| 230 | + }); | |
| 231 | + | |
| 232 | + test("should send SIGKILL after timeout if process not killed", async () => { | |
| 233 | + const toolCallId = "test-123"; | |
| 234 | + const mockProcess = createMockProcess(); | |
| 235 | + | |
| 236 | + // Mock kill to not actually set killed=true for SIGTERM | |
| 237 | + mockProcess.kill.mockImplementation((signal) => { | |
| 238 | + if (signal === "SIGKILL") { | |
| 239 | + (mockProcess as any).killed = true; | |
| 240 | + } | |
| 241 | + return true; | |
| 242 | + }); | |
| 243 | + | |
| 244 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 245 | + | |
| 246 | + const cancelPromise = killTerminalProcess(toolCallId); | |
| 247 | + | |
| 248 | + // Fast-forward time to trigger the timeout | |
| 249 | + jest.advanceTimersByTime(5000); | |
| 250 | + | |
| 251 | + await cancelPromise; | |
| 252 | + | |
| 253 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 254 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL"); | |
| 255 | + }); | |
| 256 | + | |
| 257 | + test("should not send SIGKILL if process was already killed", async () => { | |
| 258 | + const toolCallId = "test-123"; | |
| 259 | + const mockProcess = createMockProcess(); | |
| 260 | + | |
| 261 | + markProcessAsRunning(toolCallId, mockProcess); | |
| 262 | + | |
| 263 | + const cancelPromise = killTerminalProcess(toolCallId); | |
| 264 | + | |
| 265 | + // Fast-forward time to trigger the timeout | |
| 266 | + jest.advanceTimersByTime(5000); | |
| 267 | + | |
| 268 | + await cancelPromise; | |
| 269 | + | |
| 270 | + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 271 | + expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + describe("utility functions", () => { | |
| 276 | + test("should get all running process IDs", () => { | |
| 277 | + const toolCallId1 = "test-123"; | |
| 278 | + const toolCallId2 = "test-456"; | |
| 279 | + const mockProcess1 = createMockProcess(123); | |
| 280 | + const mockProcess2 = createMockProcess(456); | |
| 281 | + | |
| 282 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 283 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 284 | + | |
| 285 | + const runningIds = getAllRunningProcessIds(); | |
| 286 | + expect(runningIds).toContain(toolCallId1); | |
| 287 | + expect(runningIds).toContain(toolCallId2); | |
| 288 | + expect(runningIds).toHaveLength(2); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + test("should get all backgrounded process IDs", () => { | |
| 292 | + const toolCallId1 = "test-123"; | |
| 293 | + const toolCallId2 = "test-456"; | |
| 294 | + | |
| 295 | + markProcessAsBackgrounded(toolCallId1); | |
| 296 | + markProcessAsBackgrounded(toolCallId2); | |
| 297 | + | |
| 298 | + const backgroundedIds = getAllBackgroundedProcessIds(); | |
| 299 | + expect(backgroundedIds).toContain(toolCallId1); | |
| 300 | + expect(backgroundedIds).toContain(toolCallId2); | |
| 301 | + expect(backgroundedIds).toHaveLength(2); | |
| 302 | + }); | |
| 303 | + | |
| 304 | + test("should return empty arrays when no processes", () => { | |
| 305 | + expect(getAllRunningProcessIds()).toEqual([]); | |
| 306 | + expect(getAllBackgroundedProcessIds()).toEqual([]); | |
| 307 | + }); | |
| 308 | + | |
| 309 | + test("should cancel multiple terminal commands", async () => { | |
| 310 | + const toolCallId1 = "test-123"; | |
| 311 | + const toolCallId2 = "test-456"; | |
| 312 | + const mockProcess1 = createMockProcess(123); | |
| 313 | + const mockProcess2 = createMockProcess(456); | |
| 314 | + | |
| 315 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 316 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 317 | + | |
| 318 | + await killMultipleTerminalProcesses([toolCallId1, toolCallId2]); | |
| 319 | + | |
| 320 | + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 321 | + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 322 | + expect(isProcessRunning(toolCallId1)).toBe(false); | |
| 323 | + expect(isProcessRunning(toolCallId2)).toBe(false); | |
| 324 | + }); | |
| 325 | + | |
| 326 | + test("should cancel all running terminal commands", async () => { | |
| 327 | + const toolCallId1 = "test-123"; | |
| 328 | + const toolCallId2 = "test-456"; | |
| 329 | + const mockProcess1 = createMockProcess(123); | |
| 330 | + const mockProcess2 = createMockProcess(456); | |
| 331 | + | |
| 332 | + markProcessAsRunning(toolCallId1, mockProcess1); | |
| 333 | + markProcessAsRunning(toolCallId2, mockProcess2); | |
| 334 | + | |
| 335 | + const cancelledIds = await killAllRunningTerminalProcesses(); | |
| 336 | + | |
| 337 | + expect(cancelledIds).toContain(toolCallId1); | |
| 338 | + expect(cancelledIds).toContain(toolCallId2); | |
| 339 | + expect(cancelledIds).toHaveLength(2); | |
| 340 | + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 341 | + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); | |
| 342 | + expect(isProcessRunning(toolCallId1)).toBe(false); | |
| 343 | + expect(isProcessRunning(toolCallId2)).toBe(false); | |
| 344 | + }); | |
| 345 | + | |
| 346 | + test("should return empty array when no running commands to cancel", async () => { | |
| 347 | + const cancelledIds = await killAllRunningTerminalProcesses(); | |
| 348 | + expect(cancelledIds).toEqual([]); | |
| 349 | + }); | |
| 350 | + | |
| 351 | + test("should clear all background processes", () => { | |
| 352 | + const toolCallId1 = "test-123"; | |
| 353 | + const toolCallId2 = "test-456"; | |
| 354 | + | |
| 355 | + markProcessAsBackgrounded(toolCallId1); | |
| 356 | + markProcessAsBackgrounded(toolCallId2); | |
| 357 | + | |
| 358 | + expect(getAllBackgroundedProcessIds()).toHaveLength(2); | |
| 359 | + | |
| 360 | + clearAllBackgroundProcesses(); | |
| 361 | + | |
| 362 | + expect(getAllBackgroundedProcessIds()).toEqual([]); | |
| 363 | + expect(isProcessBackgrounded(toolCallId1)).toBe(false); | |
| 364 | + expect(isProcessBackgrounded(toolCallId2)).toBe(false); | |
| 365 | + }); | |
| 366 | + }); | |
| 367 | +}); |
| @@ -0,0 +1,119 @@ | ||
| 1 | +import { ChildProcess } from "child_process"; | |
| 2 | + | |
| 3 | +// Track which processes have been backgrounded | |
| 4 | +const processTerminalBackgroundStates = new Map<string, boolean>(); | |
| 5 | + | |
| 6 | +// Track which foreground processes are currently running | |
| 7 | +interface RunningProcessInfo { | |
| 8 | + process: ChildProcess; | |
| 9 | + onPartialOutput?: (params: { | |
| 10 | + toolCallId: string; | |
| 11 | + contextItems: any[]; | |
| 12 | + }) => void; | |
| 13 | + currentOutput: string; | |
| 14 | +} | |
| 15 | + | |
| 16 | +const processTerminalForegroundStates = new Map<string, RunningProcessInfo>(); | |
| 17 | + | |
| 18 | +// Background process functions (existing) | |
| 19 | +export function markProcessAsBackgrounded(toolCallId: string): void { | |
| 20 | + processTerminalBackgroundStates.set(toolCallId, true); | |
| 21 | +} | |
| 22 | + | |
| 23 | +export function isProcessBackgrounded(toolCallId: string): boolean { | |
| 24 | + return processTerminalBackgroundStates.has(toolCallId); | |
| 25 | +} | |
| 26 | + | |
| 27 | +export function removeBackgroundedProcess(toolCallId: string): void { | |
| 28 | + processTerminalBackgroundStates.delete(toolCallId); | |
| 29 | +} | |
| 30 | + | |
| 31 | +// Foreground process functions (new) | |
| 32 | +export function markProcessAsRunning( | |
| 33 | + toolCallId: string, | |
| 34 | + process: ChildProcess, | |
| 35 | + onPartialOutput?: (params: { | |
| 36 | + toolCallId: string; | |
| 37 | + contextItems: any[]; | |
| 38 | + }) => void, | |
| 39 | + currentOutput: string = "", | |
| 40 | +): void { | |
| 41 | + processTerminalForegroundStates.set(toolCallId, { | |
| 42 | + process, | |
| 43 | + onPartialOutput, | |
| 44 | + currentOutput, | |
| 45 | + }); | |
| 46 | +} | |
| 47 | + | |
| 48 | +export function isProcessRunning(toolCallId: string): boolean { | |
| 49 | + return processTerminalForegroundStates.has(toolCallId); | |
| 50 | +} | |
| 51 | + | |
| 52 | +export function getRunningProcess( | |
| 53 | + toolCallId: string, | |
| 54 | +): ChildProcess | undefined { | |
| 55 | + const info = processTerminalForegroundStates.get(toolCallId); | |
| 56 | + return info?.process; | |
| 57 | +} | |
| 58 | + | |
| 59 | +export function updateProcessOutput(toolCallId: string, output: string): void { | |
| 60 | + const info = processTerminalForegroundStates.get(toolCallId); | |
| 61 | + if (info) { | |
| 62 | + info.currentOutput = output; | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +export function removeRunningProcess(toolCallId: string): void { | |
| 67 | + processTerminalForegroundStates.delete(toolCallId); | |
| 68 | +} | |
| 69 | + | |
| 70 | +export async function killTerminalProcess(toolCallId: string): Promise<void> { | |
| 71 | + const processInfo = processTerminalForegroundStates.get(toolCallId); | |
| 72 | + if (processInfo && !processInfo.process.killed) { | |
| 73 | + const { process } = processInfo; | |
| 74 | + | |
| 75 | + process.kill("SIGTERM"); | |
| 76 | + | |
| 77 | + // Force kill after 5 seconds if still running | |
| 78 | + setTimeout(() => { | |
| 79 | + if (!process.killed) { | |
| 80 | + process.kill("SIGKILL"); | |
| 81 | + } | |
| 82 | + }, 5000); | |
| 83 | + | |
| 84 | + processTerminalForegroundStates.delete(toolCallId); | |
| 85 | + } | |
| 86 | +} | |
| 87 | + | |
| 88 | +// Function to cancel multiple terminal commands at once | |
| 89 | +export async function killMultipleTerminalProcesses( | |
| 90 | + toolCallIds: string[], | |
| 91 | +): Promise<void> { | |
| 92 | + const cancelPromises = toolCallIds.map((toolCallId) => | |
| 93 | + killTerminalProcess(toolCallId), | |
| 94 | + ); | |
| 95 | + await Promise.all(cancelPromises); | |
| 96 | +} | |
| 97 | + | |
| 98 | +// Function to cancel ALL currently running terminal commands | |
| 99 | +export async function killAllRunningTerminalProcesses(): Promise<string[]> { | |
| 100 | + const runningIds = getAllRunningProcessIds(); | |
| 101 | + if (runningIds.length > 0) { | |
| 102 | + await killMultipleTerminalProcesses(runningIds); | |
| 103 | + } | |
| 104 | + return runningIds; // Return the IDs that were cancelled | |
| 105 | +} | |
| 106 | + | |
| 107 | +// Utility functions | |
| 108 | +export function getAllRunningProcessIds(): string[] { | |
| 109 | + return Array.from(processTerminalForegroundStates.keys()); | |
| 110 | +} | |
| 111 | + | |
| 112 | +export function getAllBackgroundedProcessIds(): string[] { | |
| 113 | + return Array.from(processTerminalBackgroundStates.keys()); | |
| 114 | +} | |
| 115 | + | |
| 116 | +// Utility function for testing - clears all background process states | |
| 117 | +export function clearAllBackgroundProcesses(): void { | |
| 118 | + processTerminalBackgroundStates.clear(); | |
| 119 | +} |
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | title: "Chat" |
| 3 | 3 | sidebarTitle: "How To Use AI Chat" |
| 4 | 4 | icon: "circle-question" |
| 5 | -description: "Learn how to use Continue's AI chat assistant to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models" | |
| 5 | +description: "Learn how to use Continue's AI chat agent to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models" | |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | 8 | <Frame> |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Customization Overview" |
| 3 | -description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding assistant" | |
| 3 | +description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding agent" | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | Continue can be deeply customized to fit your specific development workflow and preferences. This guide covers the main ways you can customize Continue to enhance your coding experience. |
| @@ -21,15 +21,15 @@ | ||
| 21 | 21 | |
| 22 | 22 | Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools) |
| 23 | 23 | |
| 24 | -Whatever you choose, you'll probably start by editing your Assistant. | |
| 24 | +Whatever you choose, you'll probably start by editing your Agent. | |
| 25 | 25 | |
| 26 | -## Edit Your Assistant | |
| 26 | +## Edit Your Agent | |
| 27 | 27 | |
| 28 | -You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. | |
| 28 | +You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. | |
| 29 | 29 | |
| 30 | - | |
| 30 | + | |
| 31 | 31 | |
| 32 | -## Manage Your Assistant | |
| 32 | +## Manage Your Agent | |
| 33 | 33 | |
| 34 | -- See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant | |
| 35 | -- See the [Config Deep Dive](/reference) for more details on configuring local assistants. | |
| 34 | +- See [Editing Hub Agents](/hub/agents/edit-an-agent) for more details on managing your hub agent | |
| 35 | +- See the [Config Deep Dive](/reference) for more details on configuring local agents. |
| @@ -1,18 +1,18 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Rules" |
| 3 | -description: "Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses." | |
| 3 | +description: "Rules allow you to provide specific instructions that guide how the AI agent behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Think of these as the guardrails for your AI coding assistants: | |
| 6 | +Think of these as the guardrails for your AI coding agents: | |
| 7 | 7 | |
| 8 | 8 | - **Enforce company-specific coding standards** and security practices |
| 9 | 9 | - **Implement quality checks** that match your engineering culture |
| 10 | 10 | - **Create paved paths** for developers to follow organizational best practices |
| 11 | 11 | |
| 12 | -By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints. | |
| 12 | +By implementing rules, you transform the AI from a generic coding agent into a knowledgeable team member that understands your project's unique requirements and constraints. | |
| 13 | 13 | |
| 14 | 14 | ## How Rules Work |
| 15 | 15 | |
| 16 | -Your assistant detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. | |
| 16 | +Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. | |
| 17 | 17 | |
| 18 | 18 | Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. |
| No newline at the end of the file |
| @@ -1,26 +1,26 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "How to Configure Continue Assistants" | |
| 3 | -description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files | |
| 2 | +title: "How to Configure Continue Agents" | |
| 3 | +description: Learn how to access and manage Continue agent configurations through Hub or local YAML files | |
| 4 | 4 | keywords: [config, settings, customize] |
| 5 | -sidebarTitle: "Assistant Configuration" | |
| 5 | +sidebarTitle: "Agent Configuration" | |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | -You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. | |
| 8 | +You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon. | |
| 9 | 9 | |
| 10 | - | |
| 10 | + | |
| 11 | 11 | |
| 12 | -## How to Manage Hub Assistants | |
| 12 | +## How to Manage Hub Agents | |
| 13 | 13 | |
| 14 | -Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md) | |
| 14 | +Hub Agents can be managed in [the Hub](https://hub.continue.dev). See [Editing an Agent](../../hub/agents/edit-an-agent.md) | |
| 15 | 15 | |
| 16 | -## How to Configure Local Assistants with YAML | |
| 16 | +## How to Configure Local Agents with YAML | |
| 17 | 17 | |
| 18 | 18 | Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: |
| 19 | 19 | |
| 20 | 20 | - `~/.continue/config.yaml` (MacOS / Linux) |
| 21 | 21 | - `%USERPROFILE%\.continue\config.yaml` (Windows) |
| 22 | 22 | |
| 23 | -To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`. | |
| 23 | +To open this `config.yaml`, you need to open the agents dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Agent" option, select the cog icon. It will open the local `config.yaml`. | |
| 24 | 24 | |
| 25 | 25 |  |
| 26 | 26 |
| @@ -335,6 +335,8 @@ | ||
| 335 | 335 | - provider: http |
| 336 | 336 | params: |
| 337 | 337 | url: "https://api.example.com/v1/users" |
| 338 | + headers: | |
| 339 | + - Authorization: "Bearer <token>" | |
| 338 | 340 | ``` |
| 339 | 341 | </Tab> |
| 340 | 342 | <Tab title="JSON (Deprecated)"> |
| @@ -409,7 +411,8 @@ | ||
| 409 | 411 | ## Deprecated Context Providers |
| 410 | 412 | |
| 411 | 413 | <Note> |
| 412 | - To provide conext beyond the built-in context providers, we now recommend using [MCP Servers](/customization/mcp-tools) | |
| 414 | + To provide conext beyond the built-in context providers, we now recommend | |
| 415 | + using [MCP Servers](/customization/mcp-tools) | |
| 413 | 416 | </Note> |
| 414 | 417 | |
| 415 | 418 | View the [deprecated context providers](/reference/deprecated-context-providers) for documentation on: |
| @@ -427,4 +430,4 @@ | ||
| 427 | 430 | - `@Issue` - GitHub issues |
| 428 | 431 | - `@Url` - URL content |
| 429 | 432 | - `@Search` - Codebase search |
| 430 | -- `@Web` - Web search results | |
| No newline at the end of the file | ||
| 433 | +- `@Web` - Web search results |
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | Currently custom tools can be configured using the Model Context |
| 20 | 20 | Protocol standard to unify prompts, context, and tool use. |
| 21 | 21 | |
| 22 | -MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can | |
| 22 | +MCP Servers can be added to hub Agents using `mcpServers` blocks. You can | |
| 23 | 23 | explore available MCP server blocks |
| 24 | 24 | [here](https://hub.continue.dev/explore/mcp). |
| 25 | 25 | |
| @@ -27,7 +27,7 @@ | ||
| 27 | 27 | |
| 28 | 28 | ## Quick Start: How to Set Up Your First MCP Server |
| 29 | 29 | |
| 30 | -Below is a quick example of setting up a new MCP server for use in your assistant: | |
| 30 | +Below is a quick example of setting up a new MCP server for use in your agent: | |
| 31 | 31 | |
| 32 | 32 | 1. Create a folder called `.continue/mcpServers` at the top level of your workspace |
| 33 | 33 | 2. Add a file called `playwright-mcp.yaml` to this folder. |
| @@ -231,12 +231,13 @@ | ||
| 231 | 231 | | Model | Tool Use | Image Input | Context Window | |
| 232 | 232 | | :------------- | -------- | ----------- | -------------- | |
| 233 | 233 | | Qwen 3 Coder | Yes | No | 32k | |
| 234 | +| Qwen 2.5 VL | No | Yes | 128k | | |
| 234 | 235 | | Devstral Small | Yes | No | 32k | |
| 235 | 236 | | Llama 3.1 | Yes | No | 128k | |
| 236 | 237 | | Llama 3 | Yes | No | 8k | |
| 237 | 238 | | Mistral | Yes | No | 32k | |
| 238 | 239 | | Codestral | Yes | No | 32k | |
| 239 | -| Gemma 3 4B | Yes | No | 8k | | |
| 240 | +| Gemma 3 4B | Yes | Yes | 128k | | |
| 240 | 241 | |
| 241 | 242 | ### Notes |
| 242 | 243 |
| @@ -42,7 +42,7 @@ | ||
| 42 | 42 | |
| 43 | 43 | ## How to Create Rules Blocks |
| 44 | 44 | |
| 45 | -Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules. | |
| 45 | +Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. | |
| 46 | 46 | |
| 47 | 47 |  |
| 48 | 48 | |
| @@ -53,7 +53,7 @@ | ||
| 53 | 53 | |
| 54 | 54 | </Info> |
| 55 | 55 | |
| 56 | -Rules can also be added to an Assistant on the Continue Hub. | |
| 56 | +Rules can also be added to an Agent on the Continue Hub. | |
| 57 | 57 | |
| 58 | 58 | Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. |
| 59 | 59 |
| @@ -39,7 +39,7 @@ | ||
| 39 | 39 | |
| 40 | 40 | ## Creating `rules` blocks |
| 41 | 41 | |
| 42 | -Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules. | |
| 42 | +Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. | |
| 43 | 43 | |
| 44 | 44 |  |
| 45 | 45 | |
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. |
| 50 | 50 | </Info> |
| 51 | 51 | |
| 52 | -Rules can also be added to an Assistant on the Continue Hub. | |
| 52 | +Rules can also be added to an Agent on the Continue Hub. | |
| 53 | 53 | |
| 54 | 54 | Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. |
| 55 | 55 | |
| @@ -133,7 +133,7 @@ | ||
| 133 | 133 | Always give concise responses |
| 134 | 134 | ``` |
| 135 | 135 | |
| 136 | -This is also done when selecting "Add Rule" in the Assistant settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`. | |
| 136 | +This is also done when selecting "Add Rule" in the Agent settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`. | |
| 137 | 137 | |
| 138 | 138 | ### Examples |
| 139 | 139 |
| @@ -21,9 +21,9 @@ | ||
| 21 | 21 | |
| 22 | 22 | ## Ways to Create Slash Commands in Continue |
| 23 | 23 | |
| 24 | -### Assistant Prompt Blocks | |
| 24 | +### Agent Prompt Blocks | |
| 25 | 25 | |
| 26 | -The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works). | |
| 26 | +The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your agent, which show up as slash commands in [Chat](../../features/chat/how-it-works). | |
| 27 | 27 | |
| 28 | 28 | ### Prompt Files |
| 29 | 29 |
Binary content is not shown. View the file.
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
Binary content is not shown. View the file.
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "SambaNova" |
| 3 | -description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance" | |
| 3 | +description: "Configure SambaCloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance" | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. |
| @@ -9,9 +9,9 @@ | ||
| 9 | 9 | <Tab title="YAML"> |
| 10 | 10 | ```yaml title="config.yaml" |
| 11 | 11 | models: |
| 12 | - - name: SambaNova Llama 4 Scout | |
| 12 | + - name: GPT OSS 120B | |
| 13 | 13 | provider: sambanova |
| 14 | - model: Llama-4-Scout-17B-16E-Instruct | |
| 14 | + model: gpt-oss-120b | |
| 15 | 15 | apiKey: <YOUR_SAMBANOVA_API_KEY> |
| 16 | 16 | ``` |
| 17 | 17 | </Tab> |
| @@ -20,9 +20,9 @@ | ||
| 20 | 20 | { |
| 21 | 21 | "models": [ |
| 22 | 22 | { |
| 23 | - "title": "SambaNova Llama 4 Scout", | |
| 23 | + "title": "GPT OSS 120B", | |
| 24 | 24 | "provider": "sambanova", |
| 25 | - "model": "Llama-4-Scout-17B-16E-Instruct", | |
| 25 | + "model": "gpt-oss-120b", | |
| 26 | 26 | "apiKey": "<YOUR_SAMBANOVA_API_KEY>" |
| 27 | 27 | } |
| 28 | 28 | ] |
| @@ -0,0 +1,81 @@ | ||
| 1 | +--- | |
| 2 | +title: "Lemonade Server" | |
| 3 | +description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Info> | |
| 7 | + Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration | |
| 8 | +</Info> | |
| 9 | + | |
| 10 | +## Overview | |
| 11 | + | |
| 12 | +Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms. | |
| 13 | + | |
| 14 | +## Installation | |
| 15 | + | |
| 16 | +Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/). | |
| 17 | + | |
| 18 | +## Configuration | |
| 19 | + | |
| 20 | +Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration. | |
| 21 | + | |
| 22 | +### Option 1: Using the Continue UI (Recommended) | |
| 23 | + | |
| 24 | +1. Click on the model selector dropdown in Continue | |
| 25 | +2. Select "Add Model" | |
| 26 | +3. Choose "Lemonade Server" from the provider list | |
| 27 | +4. Continue will automatically configure the connection | |
| 28 | + | |
| 29 | +### Option 2: Manual Configuration | |
| 30 | + | |
| 31 | +If you need custom settings, you can manually configure Lemonade: | |
| 32 | + | |
| 33 | +<Tabs> | |
| 34 | + <Tab title="YAML"> | |
| 35 | + ```yaml title="config.yaml" | |
| 36 | + models: | |
| 37 | + - name: Lemonade | |
| 38 | + provider: lemonade | |
| 39 | + model: <MODEL_NAME> | |
| 40 | + apiBase: http://localhost:8000/api/v1/ | |
| 41 | + ``` | |
| 42 | + </Tab> | |
| 43 | + <Tab title="JSON (Deprecated)"> | |
| 44 | + ```json title="config.json" | |
| 45 | + { | |
| 46 | + "models": [ | |
| 47 | + { | |
| 48 | + "title": "Lemonade", | |
| 49 | + "provider": "lemonade", | |
| 50 | + "model": "<MODEL_NAME>", | |
| 51 | + "apiBase": "http://localhost:8000/api/v1/" | |
| 52 | + } | |
| 53 | + ] | |
| 54 | + } | |
| 55 | + ``` | |
| 56 | + </Tab> | |
| 57 | +</Tabs> | |
| 58 | + | |
| 59 | +## Getting Started | |
| 60 | + | |
| 61 | +1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/) | |
| 62 | +2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default) | |
| 63 | +3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue | |
| 64 | +4. **Load a model**: Choose your preferred model through the interface | |
| 65 | + | |
| 66 | +## Hardware Support | |
| 67 | + | |
| 68 | +Lemonade Server automatically detects and optimizes for available hardware: | |
| 69 | +- **NPU**: Neural Processing Unit acceleration for efficient inference | |
| 70 | +- **GPU**: Full GPU acceleration support | |
| 71 | +- **CPU**: Optimized CPU fallback when accelerators are unavailable | |
| 72 | + | |
| 73 | +## Key Features | |
| 74 | + | |
| 75 | +- OpenAI-compatible API for seamless integration | |
| 76 | +- Support for popular model formats | |
| 77 | +- Automatic hardware detection and optimization | |
| 78 | +- Integration with Continue, Open WebUI, Gaia, and AnythingLLM | |
| 79 | +- Active open-source community | |
| 80 | + | |
| 81 | +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts) | |
| No newline at the end of the file |
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | | [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models | |
| 34 | 34 | | [DeepInfra](/customize/model-providers/more/deepinfra) | Hosting for various open source models | |
| 35 | 35 | | [OpenRouter](/customize/model-providers/top-level/openrouter) | Gateway to multiple model providers | |
| 36 | +| [Tetrate Agent Router Service](/customize/model-providers/top-level/tetrate_agent_router_service) | Gateway with intelligent routing across multiple model providers | | |
| 36 | 37 | | [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation | |
| 37 | 38 | | [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting | |
| 38 | 39 | | [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services | |
| @@ -30,7 +30,7 @@ | ||
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | 32 | "title": "<MODEL_NAME>", |
| 33 | - "provider": "openai", | |
| 33 | + "provider": "openai", | |
| 34 | 34 | "model": "<MODEL_ID>", |
| 35 | 35 | "apiKey": "<YOUR_OPENAI_API_KEY>" |
| 36 | 36 | } |
| @@ -56,6 +56,7 @@ | ||
| 56 | 56 | - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) |
| 57 | 57 | - [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) |
| 58 | 58 | - [BerriAI/litellm](https://github.com/BerriAI/litellm) |
| 59 | +- [Tetrate Agent Router Service](https://router.tetrate.ai) | |
| 59 | 60 | |
| 60 | 61 | If you are using an OpenAI API compatible providers, you can change the `apiBase` like this: |
| 61 | 62 | |
| @@ -75,7 +76,7 @@ | ||
| 75 | 76 | { |
| 76 | 77 | "models": [ |
| 77 | 78 | { |
| 78 | - "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>", | |
| 79 | + "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>", | |
| 79 | 80 | "provider": "openai", |
| 80 | 81 | "model": "<MODEL_NAME>", |
| 81 | 82 | "apiKey": "<YOUR_CUSTOM_API_KEY>", |
| @@ -110,7 +111,7 @@ | ||
| 110 | 111 | "title": "<OPENAI_API_COMPATIBLE_PROVIDER_MODEL>", |
| 111 | 112 | "provider": "openai", |
| 112 | 113 | "model": "<MODEL_NAME>", |
| 113 | - "apiBase": "http://localhost:8000/v1", | |
| 114 | + "apiBase": "http://localhost:8000/v1", | |
| 114 | 115 | "useLegacyCompletionsEndpoint": true |
| 115 | 116 | } |
| 116 | 117 | ] |
| @@ -0,0 +1,252 @@ | ||
| 1 | +--- | |
| 2 | +title: "Tetrate Agent Router Service" | |
| 3 | +sidebarTitle: "Tetrate Agent Router Service" | |
| 4 | +slug: ../tetrate-agent-router-service | |
| 5 | +--- | |
| 6 | +The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities. | |
| 7 | + | |
| 8 | +This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization. | |
| 9 | + | |
| 10 | +<Tip> | |
| 11 | +Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast. | |
| 12 | +</Tip> | |
| 13 | + | |
| 14 | +## Setup | |
| 15 | + | |
| 16 | +<Steps> | |
| 17 | +<Step title="Sign in or sign up"> | |
| 18 | +Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key | |
| 19 | +<img src="../assets/tetrate-sign-in.png" alt="Tetrate sign in page" style={{width: '250px', maxWidth: '100%'}} /> | |
| 20 | +</Step> | |
| 21 | + | |
| 22 | +<Step title="Get your API key"> | |
| 23 | +Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key | |
| 24 | +<img src="../assets/tetrate-get-api-key.png" alt="Tetrate get API key" style={{width: '250px', maxWidth: '100%'}} /> | |
| 25 | +</Step> | |
| 26 | + | |
| 27 | +<Step title="Configure Continue"> | |
| 28 | +- Choose a configuration method below. | |
| 29 | +- If you use the Continue VS Code extension, install version `>=1.2.3`. | |
| 30 | +</Step> | |
| 31 | + | |
| 32 | +</Steps> | |
| 33 | + | |
| 34 | + | |
| 35 | +### Quickstart with Continue Hub | |
| 36 | + | |
| 37 | +Fastest way: use preconfigured models from Tetrate on Continue Hub | |
| 38 | + | |
| 39 | +<Steps> | |
| 40 | +<Step title="Browse models"> | |
| 41 | +Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4)) | |
| 42 | +</Step> | |
| 43 | + | |
| 44 | +<Step title="Use or remix"> | |
| 45 | +Click "Use Model", or "Remix" to change the model ID if needed | |
| 46 | +</Step> | |
| 47 | + | |
| 48 | +<Step title="Add your API key"> | |
| 49 | +Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables) | |
| 50 | +<Tip> | |
| 51 | +Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects. | |
| 52 | +</Tip> | |
| 53 | +</Step> | |
| 54 | +</Steps> | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | +<Info> | |
| 59 | +If a model is missing, remix a similar one and set the `model` field to the target ID. | |
| 60 | +</Info> | |
| 61 | + | |
| 62 | +### Configuration Methods | |
| 63 | + | |
| 64 | +<CardGroup cols={1}> | |
| 65 | + <Card title="In Local Agent Configuration" icon="folder" vertical> | |
| 66 | + Use a Tetrate model block from the Hub or define it directly in your local agent configuration. | |
| 67 | + </Card> | |
| 68 | + <Card title="Continue Hub" icon="cloud" vertical> | |
| 69 | + Use a Tetrate model block from the Hub or define your own on the Hub. | |
| 70 | + </Card> | |
| 71 | + <Card title="Using Local Model Blocks" icon="file-lines" vertical> | |
| 72 | + Create a local model block for reuse across agents without publishing it to the Hub. | |
| 73 | + </Card> | |
| 74 | +</CardGroup> | |
| 75 | + | |
| 76 | + | |
| 77 | +### Configuration Examples | |
| 78 | +<Info> | |
| 79 | +**Click a tab** to see an example. | |
| 80 | +</Info> | |
| 81 | +<Tabs> | |
| 82 | +<Tab title="In Local Agent Configuration"> | |
| 83 | + | |
| 84 | +**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks. | |
| 85 | + | |
| 86 | +Use a Tetrate model block from the Hub in your local agent configuration: | |
| 87 | + | |
| 88 | +```yaml title="~/.continue/config.yaml" | |
| 89 | +name: Local Agent | |
| 90 | +version: 1.0.0 | |
| 91 | +schema: v1 | |
| 92 | +models: | |
| 93 | + - uses: tetrate/claude-sonnet-4 | |
| 94 | + with: | |
| 95 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 96 | +context: | |
| 97 | + - provider: code | |
| 98 | + - provider: docs | |
| 99 | + - provider: diff | |
| 100 | + - provider: terminal | |
| 101 | + - provider: problems | |
| 102 | + - provider: folder | |
| 103 | + - provider: codebase | |
| 104 | +``` | |
| 105 | + | |
| 106 | +Or define the model directly: | |
| 107 | + | |
| 108 | +```yaml title="~/.continue/config.yaml" | |
| 109 | +name: Local Agent | |
| 110 | +version: 1.0.0 | |
| 111 | +schema: v1 | |
| 112 | +models: | |
| 113 | + - name: Claude Sonnet 4 | |
| 114 | + provider: tars | |
| 115 | + model: claude-4-sonnet-20250514 | |
| 116 | + apiKey: ${{ secrets.TETRATE_API_KEY }} | |
| 117 | + roles: | |
| 118 | + - chat | |
| 119 | + - edit | |
| 120 | + - apply | |
| 121 | + capabilities: | |
| 122 | + - tool_use | |
| 123 | +context: | |
| 124 | + - provider: code | |
| 125 | + - provider: docs | |
| 126 | + - provider: diff | |
| 127 | + - provider: terminal | |
| 128 | + - provider: problems | |
| 129 | + - provider: folder | |
| 130 | + - provider: codebase | |
| 131 | +``` | |
| 132 | +</Tab> | |
| 133 | +<Tab title="Continue Hub"> | |
| 134 | +**When to use**: Share configurations across teams or contribute to the community. | |
| 135 | + | |
| 136 | +**The Model Block:** | |
| 137 | + | |
| 138 | +```yaml title="tetrate/claude-sonnet-4" | |
| 139 | +name: Claude Sonnet 4 | |
| 140 | +version: 1.0.14 | |
| 141 | +schema: v1 | |
| 142 | +models: | |
| 143 | + - name: Claude Sonnet 4 - Tetrate | |
| 144 | + provider: tars | |
| 145 | + model: claude-4-sonnet-20250514 | |
| 146 | + apiKey: ${{ inputs.TETRATE_API_KEY }} | |
| 147 | + roles: | |
| 148 | + - chat | |
| 149 | + - edit | |
| 150 | + - apply | |
| 151 | + capabilities: | |
| 152 | + - tool_use | |
| 153 | +``` | |
| 154 | +View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4). | |
| 155 | + | |
| 156 | +**Reference it in your Agent configuration:** | |
| 157 | + | |
| 158 | +```yaml title="my-agent" | |
| 159 | +name: My Agent | |
| 160 | +version: 1.0.0 | |
| 161 | +schema: v1 | |
| 162 | +models: | |
| 163 | + - uses: tetrate/claude-sonnet-4 | |
| 164 | + with: | |
| 165 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 166 | +context: | |
| 167 | + - uses: continuedev/diff-context | |
| 168 | + - uses: continuedev/terminal-context | |
| 169 | + - uses: continuedev/file-context | |
| 170 | +``` | |
| 171 | +<Tip> | |
| 172 | +To customize, see the [model block creation guide](/hub/blocks/create-a-block). | |
| 173 | +</Tip> | |
| 174 | + | |
| 175 | +</Tab> | |
| 176 | + | |
| 177 | +<Tab title="Using Local Model Blocks"> | |
| 178 | +**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub). | |
| 179 | + | |
| 180 | +**The Local Model Block:** | |
| 181 | +<Info> | |
| 182 | +Name the file `my-claude-4-model.yaml` so you can reference it in the Agent. | |
| 183 | +</Info> | |
| 184 | + | |
| 185 | +```yaml title="~/.continue/models/my-claude-4-model.yaml" | |
| 186 | +name: Claude Sonnet 4 | |
| 187 | +version: 1.0.1 | |
| 188 | +schema: v1 | |
| 189 | +models: | |
| 190 | + - name: Claude Sonnet 4 | |
| 191 | + provider: tars | |
| 192 | + model: claude-4-sonnet-20250514 | |
| 193 | + apiKey: ${{ inputs.TETRATE_API_KEY }} | |
| 194 | + roles: | |
| 195 | + - chat | |
| 196 | + - edit | |
| 197 | + - apply | |
| 198 | + capabilities: | |
| 199 | + - tool_use | |
| 200 | +``` | |
| 201 | +Reference it as `my-claude-4-model` in your Agent configuration: | |
| 202 | + | |
| 203 | +```yaml title="~/.continue/agents/simple-agent.yaml" | |
| 204 | +name: Simple Agent | |
| 205 | +version: 1.0.0 | |
| 206 | +schema: v1 | |
| 207 | +models: | |
| 208 | + - uses: my-claude-4-model | |
| 209 | + with: | |
| 210 | + TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }} | |
| 211 | +context: | |
| 212 | + - uses: continuedev/diff-context | |
| 213 | + - uses: continuedev/terminal-context | |
| 214 | + - uses: continuedev/file-context | |
| 215 | +``` | |
| 216 | + | |
| 217 | +<Tip> | |
| 218 | +Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks). | |
| 219 | +</Tip> | |
| 220 | + | |
| 221 | +</Tab> | |
| 222 | +</Tabs> | |
| 223 | + | |
| 224 | +--- | |
| 225 | + | |
| 226 | +## Troubleshooting Common Issues | |
| 227 | + | |
| 228 | +<CardGroup cols={2}> | |
| 229 | + <Card title="Invalid API key" icon="key" vertical> | |
| 230 | + Verify your API key is active and has no extra spaces. | |
| 231 | + </Card> | |
| 232 | + <Card title="Model not found" icon="ban" href="https://router.tetrate.ai/models" vertical> | |
| 233 | + Confirm the model ID matches the Tetrate catalog. | |
| 234 | + </Card> | |
| 235 | + <Card title="Slow responses" icon="code" vertical> | |
| 236 | + Check your network or try a less-loaded model. Contact Tetrate support if issues persist. | |
| 237 | + </Card> | |
| 238 | + <Card title="Configuration not loading" icon="file-lines" vertical> | |
| 239 | + Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published. | |
| 240 | + </Card> | |
| 241 | +</CardGroup> | |
| 242 | + | |
| 243 | +--- | |
| 244 | + | |
| 245 | +## Join the Community | |
| 246 | +Connect with Tetrate and other builders for help and discussion. | |
| 247 | + | |
| 248 | +<CardGroup cols={1}> | |
| 249 | + <Card title="Join the Tetrate Community" icon="slack" href="https://join.slack.com/t/tetrate-agent-router/shared_invite/zt-399tv7hjm-6YMXztGywTOQrMIolvEBNg"> | |
| 250 | +Get answers, insights, and best practices for secure, scalable infrastructure | |
| 251 | + </Card> | |
| 252 | +</CardGroup> |
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | title: "Model roles" |
| 3 | 3 | sidebarTitle: Overview |
| 4 | 4 | icon: "circle-info" |
| 5 | -description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding assistant's capabilities" | |
| 5 | +description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding agent's capabilities" | |
| 6 | 6 | --- |
| 7 | 7 | |
| 8 | 8 | <CardGroup> |
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | |
| 24 | 24 | ## Selecting model roles |
| 25 | 25 | |
| 26 | -You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. | |
| 26 | +You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. | |
| 27 | 27 | |
| 28 | 28 |  |
| 29 | 29 |
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | ## Selecting model roles |
| 18 | 18 | |
| 19 | -You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. | |
| 19 | +You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. | |
| 20 | 20 | |
| 21 | 21 | <Frame> |
| 22 | 22 | <img src="/images/settings-model-roles-5e5f8a6bd9137b70cf94178a7e45847c.png" /> |
| @@ -117,6 +117,7 @@ | ||
| 117 | 117 | "customize/model-providers/top-level/ollama", |
| 118 | 118 | "customize/model-providers/top-level/openrouter", |
| 119 | 119 | "customize/model-providers/top-level/openai", |
| 120 | + "customize/model-providers/top-level/tetrate_agent_router_service", | |
| 120 | 121 | "customize/model-providers/top-level/vertexai" |
| 121 | 122 | ] |
| 122 | 123 | }, |
| @@ -179,13 +180,13 @@ | ||
| 179 | 180 | "pages": [ |
| 180 | 181 | "hub/introduction", |
| 181 | 182 | { |
| 182 | - "group": "Assistants", | |
| 183 | + "group": "agents", | |
| 183 | 184 | "icon": "robot", |
| 184 | 185 | "pages": [ |
| 185 | - "hub/assistants/intro", | |
| 186 | - "hub/assistants/use-an-assistant", | |
| 187 | - "hub/assistants/create-an-assistant", | |
| 188 | - "hub/assistants/edit-an-assistant" | |
| 186 | + "hub/agents/intro", | |
| 187 | + "hub/agents/use-an-agent", | |
| 188 | + "hub/agents/create-an-agent", | |
| 189 | + "hub/agents/edit-an-agent" | |
| 189 | 190 | ] |
| 190 | 191 | }, |
| 191 | 192 | { |
| @@ -228,11 +229,15 @@ | ||
| 228 | 229 | "group": "Guides", |
| 229 | 230 | "pages": [ |
| 230 | 231 | "guides/overview", |
| 231 | - "guides/understanding-assistants", | |
| 232 | + "guides/understanding-agents", | |
| 232 | 233 | "guides/codebase-documentation-awareness", |
| 233 | 234 | "guides/cli", |
| 235 | + "guides/continuous-ai", | |
| 236 | + "guides/posthog-github-continuous-ai", | |
| 237 | + "guides/continuous-ai-readiness-assessment", | |
| 234 | 238 | "guides/plan-mode-guide", |
| 235 | 239 | "guides/ollama-guide", |
| 240 | + "guides/instinct", | |
| 236 | 241 | "guides/running-continue-without-internet", |
| 237 | 242 | "guides/custom-code-rag", |
| 238 | 243 | "guides/how-to-self-host-a-model" |
| @@ -346,18 +351,10 @@ | ||
| 346 | 351 | "source": "/hub/secrets", |
| 347 | 352 | "destination": "/hub/secrets/secret-types" |
| 348 | 353 | }, |
| 349 | - { | |
| 350 | - "source": "/hub/assistants", | |
| 351 | - "destination": "/hub/assistants/intro" | |
| 352 | - }, | |
| 353 | 354 | { |
| 354 | 355 | "source": "/hub/blocks", |
| 355 | 356 | "destination": "/hub/blocks/intro" |
| 356 | 357 | }, |
| 357 | - { | |
| 358 | - "source": "/hub/agents/intro", | |
| 359 | - "destination": "/hub/assistants/intro" | |
| 360 | - }, | |
| 361 | 358 | { |
| 362 | 359 | "source": "/customize", |
| 363 | 360 | "destination": "/customization/overview" |
| @@ -1104,7 +1101,7 @@ | ||
| 1104 | 1101 | }, |
| 1105 | 1102 | { |
| 1106 | 1103 | "source": "/troubleshooting#changes-to-assistants-not-showing-in-vs-code", |
| 1107 | - "destination": "/faqs#changes-to-assistants-not-showing-in-vs-code" | |
| 1104 | + "destination": "/faqs#changes-to-agents-not-showing-in-vs-code" | |
| 1108 | 1105 | }, |
| 1109 | 1106 | { |
| 1110 | 1107 | "source": "/troubleshooting#i-installed-continue-but-dont-see-the-sidebar-window", |
| @@ -1173,6 +1170,26 @@ | ||
| 1173 | 1170 | { |
| 1174 | 1171 | "source": "/features/edit/next-edit", |
| 1175 | 1172 | "destination": "/features/autocomplete/next-edit" |
| 1173 | + }, | |
| 1174 | + { | |
| 1175 | + "source": "/hub/assistants/intro", | |
| 1176 | + "destination": "/hub/agents/intro" | |
| 1177 | + }, | |
| 1178 | + { | |
| 1179 | + "source": "/hub/assistants/use-an-assistant", | |
| 1180 | + "destination": "/hub/agents/use-an-agent" | |
| 1181 | + }, | |
| 1182 | + { | |
| 1183 | + "source": "/hub/assistants/create-an-assistant", | |
| 1184 | + "destination": "/hub/agents/create-an-agent" | |
| 1185 | + }, | |
| 1186 | + { | |
| 1187 | + "source": "/hub/assistants/edit-an-assistant", | |
| 1188 | + "destination": "/hub/agents/edit-an-agent" | |
| 1189 | + }, | |
| 1190 | + { | |
| 1191 | + "source": "/guides/understanding-assistants", | |
| 1192 | + "destination": "/guides/understanding-agents" | |
| 1176 | 1193 | } |
| 1177 | 1194 | ] |
| 1178 | 1195 | } |
| @@ -48,15 +48,15 @@ | ||
| 48 | 48 | |
| 49 | 49 | Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server). |
| 50 | 50 | |
| 51 | -## Changes to assistants not showing in VS Code | |
| 51 | +## Changes to agents not showing in VS Code | |
| 52 | 52 | |
| 53 | -If you've made changes to assistants (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window: | |
| 53 | +If you've made changes to agents (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window: | |
| 54 | 54 | |
| 55 | 55 | 1. Open the command palette (`cmd/ctrl` + `shift` + `P`) |
| 56 | 56 | 2. Type "Reload Window" |
| 57 | 57 | 3. Select the reload option |
| 58 | 58 | |
| 59 | -This will restart VS Code and reload all extensions, which should make your assistant changes visible. | |
| 59 | +This will restart VS Code and reload all extensions, which should make your agent changes visible. | |
| 60 | 60 | |
| 61 | 61 | ## I installed Continue, but don't see the sidebar window |
| 62 | 62 | |
| @@ -256,7 +256,7 @@ | ||
| 256 | 256 | |
| 257 | 257 | 3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses |
| 258 | 258 | |
| 259 | -## Local Assistant | |
| 259 | +## Local Agent | |
| 260 | 260 | |
| 261 | 261 | ### Managing Local Secrets and Environment Variables |
| 262 | 262 | |
| @@ -318,7 +318,7 @@ | ||
| 318 | 318 | |
| 319 | 319 | ### Using Model Addons Locally |
| 320 | 320 | |
| 321 | -You can leverage model addons from the Continue Hub in your local assistant configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration. | |
| 321 | +You can leverage model addons from the Continue Hub in your local agent configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration. | |
| 322 | 322 | |
| 323 | 323 | #### Requirements |
| 324 | 324 | |
| @@ -330,7 +330,7 @@ | ||
| 330 | 330 | In your local `config.yaml`, reference model addons using the format `provider/model-name`: |
| 331 | 331 | |
| 332 | 332 | ```yaml |
| 333 | -name: My Local Assistant | |
| 333 | +name: My Local Agent | |
| 334 | 334 | version: 0.0.1 |
| 335 | 335 | schema: v1 |
| 336 | 336 | models: |
| @@ -344,7 +344,7 @@ | ||
| 344 | 344 | You can combine hub model addons with local models: |
| 345 | 345 | |
| 346 | 346 | ```yaml |
| 347 | -name: My Local Assistant | |
| 347 | +name: My Local Agent | |
| 348 | 348 | version: 0.0.1 |
| 349 | 349 | schema: v1 |
| 350 | 350 | models: |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | ## How to Add Rules Blocks |
| 8 | 8 | |
| 9 | -Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. | |
| 9 | +Adding Rules can be done in your agent locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. | |
| 10 | 10 | |
| 11 | 11 | ## How to Customize System Messages |
| 12 | 12 | |
| @@ -18,14 +18,14 @@ | ||
| 18 | 18 | provider: openai |
| 19 | 19 | model: gpt-4o |
| 20 | 20 | chatOptions: |
| 21 | - baseSystemMessage: "You are a helpful coding assistant." | |
| 22 | - baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically." | |
| 23 | - basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps." | |
| 21 | + baseSystemMessage: "You are a helpful coding agent." | |
| 22 | + baseAgentSystemMessage: "You are a systematic coding agent. Break down problems methodically." | |
| 23 | + basePlanSystemMessage: "You are a planning agent. Create clear, actionable steps." | |
| 24 | 24 | ``` |
| 25 | 25 | |
| 26 | 26 | ## How to Add MCP Tools |
| 27 | 27 | |
| 28 | -You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. | |
| 28 | +You can add MCP servers to your agent to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. | |
| 29 | 29 | |
| 30 | 30 | ## How to Configure Tool Policies |
| 31 | 31 |
| @@ -3,6 +3,6 @@ | ||
| 3 | 3 | description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.” |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings. | |
| 6 | +Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings. | |
| 7 | 7 | |
| 8 | 8 | For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete). |
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | <Warning> |
| 7 | - Next Edit is currently an experimental feature. It requires [Mercury Coder | |
| 7 | + Next Edit is currently an experimental feature. It requires | |
| 8 | + [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder | |
| 8 | 9 | model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in |
| 9 | 10 | your Continue autocomplete settings and is not yet available for JetBrains |
| 10 | 11 | use. |
| @@ -71,18 +72,18 @@ | ||
| 71 | 72 | |
| 72 | 73 | Next Edit requires: |
| 73 | 74 | |
| 74 | -- Compatible AI models (Mercury Coder) | |
| 75 | +- Compatible AI models (Mercury Coder or Instinct) | |
| 75 | 76 | - Continue development team access |
| 76 | 77 | - VS Code (JetBrains support coming soon) |
| 77 | 78 | - **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) |
| 78 | 79 | |
| 79 | 80 | <Note> |
| 80 | - To use Next Edit, you must have the Mercury Coder model configured in your | |
| 81 | - Continue autocomplete model settings. This model is specifically designed for | |
| 82 | - next edit predictions. Once it's been loaded, you must reload VS Code to | |
| 83 | - activate it. | |
| 81 | + To use Next Edit, you must have the Instinct or Mercury Coder model configured | |
| 82 | + in your Continue autocomplete model settings. This model is specifically | |
| 83 | + designed for next edit predictions. Once it's been loaded, you must reload VS | |
| 84 | + Code to activate it. | |
| 84 | 85 | <img |
| 85 | - src="/images/features/autocomplete/images/mercury-coder-next-edit.png" | |
| 86 | + src="/images/features/autocomplete/images/instinct-autocomplete.png" | |
| 86 | 87 | alt="Next Edit Model Setup" |
| 87 | 88 | /> |
| 88 | 89 | </Note> |
| @@ -117,6 +118,7 @@ | ||
| 117 | 118 | Next Edit requires AI models specifically trained for code prediction: |
| 118 | 119 | |
| 119 | 120 | - **Mercury Coder**: Primary model optimized for next edit prediction |
| 121 | +- **Instinct**: The leading open Next Edit model, trained by Continue | |
| 120 | 122 | |
| 121 | 123 | ### Automatic Detection |
| 122 | 124 |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | ## How to Set Active Edit/Apply Model |
| 8 | 8 | |
| 9 | -You can configure particular models from your Assistant to be used for Edit and Apply requests. | |
| 9 | +You can configure particular models from your Agent to be used for Edit and Apply requests. | |
| 10 | 10 | |
| 11 | 11 | 1. Click the 3 dots above the main input |
| 12 | 12 | 2. Click the cube icon to expand the "Models" section |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | -title: "Understanding Assistants" | |
| 2 | +title: "Understanding Agents" | |
| 3 | 3 | description: "Continue offers two ways to configure your AI assistants" |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants) | |
| 6 | +This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-assistants) |
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | </Step> |
| 25 | 25 | |
| 26 | 26 | <Step title="Sign In"> |
| 27 | -[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant | |
| 27 | +[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent | |
| 28 | 28 | </Step> |
| 29 | 29 | </Steps> |
| 30 | 30 | |
| @@ -54,7 +54,7 @@ | ||
| 54 | 54 | </Step> |
| 55 | 55 | |
| 56 | 56 | <Step title="Sign In"> |
| 57 | -[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant | |
| 57 | +[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent | |
| 58 | 58 | </Step> |
| 59 | 59 | </Steps> |
| 60 | 60 | |
| @@ -68,6 +68,6 @@ | ||
| 68 | 68 | |
| 69 | 69 | ## Signing in |
| 70 | 70 | |
| 71 | -Click "Get started" to sign in to the hub and start using assistants. | |
| 71 | +Click "Get started" to sign in to the hub and start using agents. | |
| 72 | 72 | |
| 73 | 73 |  |
| @@ -57,6 +57,6 @@ | ||
| 57 | 57 | </Tab> |
| 58 | 58 | </Tabs> |
| 59 | 59 | |
| 60 | -## AI Coding Assistants | |
| 60 | +## AI Coding Agents | |
| 61 | 61 | |
| 62 | -Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants). | |
| 62 | +Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Agents** for easy setup and synchronization, or **Local Agents** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants). |
| @@ -247,12 +247,12 @@ | ||
| 247 | 247 | |
| 248 | 248 | <Accordion title="Chat & Agent Best Practices"> |
| 249 | 249 | Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub |
| 250 | - v. local assistants](/guides/understanding-assistants), and [custom slash | |
| 250 | + v. local agents](/guides/understanding-agents), and [custom slash | |
| 251 | 251 | commands](/customize/deep-dives/slash-commands). |
| 252 | 252 | </Accordion> |
| 253 | 253 | |
| 254 | 254 | <Accordion title="Enterprise & Teams"> |
| 255 | - Explore [Hub Assistants](/hub/assistants/intro), [organization | |
| 255 | + Explore [Hub Agents](/hub/agents/intro), [organization | |
| 256 | 256 | management](/hub/governance/creating-an-org), and [sharing |
| 257 | 257 | configurations](/hub/sharing). |
| 258 | 258 | </Accordion> |
| @@ -87,6 +87,12 @@ | ||
| 87 | 87 | cn --exclude Fetch |
| 88 | 88 | ``` |
| 89 | 89 | |
| 90 | +## API Key Authentication | |
| 91 | + | |
| 92 | +For automation in CI or other headless environments, you can use an API key to authenticate with Continue. First, obtain your personal API key [here](https://hub.continue.dev/settings/api-keys). Then, set it as the `CONTINUE_API_KEY` environment variable. You can now use `cn -p` (headless mode) without needing to log in. | |
| 93 | + | |
| 94 | +If you wish to run an automation on behalf of your organization you can obtain an organization-scoped API key by going to [your organization's settings](https://hub.continue.dev/settings/organizations) -> API Keys. | |
| 95 | + | |
| 90 | 96 | ## Troubleshooting |
| 91 | 97 | |
| 92 | 98 | Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`. |
| @@ -1,11 +1,10 @@ | ||
| 1 | 1 | --- |
| 2 | -title: How to make your agent aware of codebases and documentation | |
| 2 | +title: How to Make Your Agent Aware of Codebases and Documentation | |
| 3 | 3 | description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance |
| 4 | 4 | keywords: [agent, codebase, documentation, MCP, context, RAG, tools] |
| 5 | +sidebarTitle: Codebase and Documentation Awareness | |
| 5 | 6 | --- |
| 6 | 7 | |
| 7 | -# How to make your agent aware of codebases and documentation | |
| 8 | - | |
| 9 | 8 | AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate. |
| 10 | 9 | |
| 11 | 10 | ## Make your agent aware of your open codebase |
| @@ -28,18 +27,21 @@ | ||
| 28 | 27 | # Project Architecture |
| 29 | 28 | |
| 30 | 29 | This is a React application with: |
| 30 | + | |
| 31 | 31 | - Components in `/src/components` |
| 32 | 32 | - API routes in `/src/api` |
| 33 | 33 | - State management using Redux in `/src/store` |
| 34 | 34 | |
| 35 | 35 | ## Coding Standards |
| 36 | + | |
| 36 | 37 | - Use TypeScript for all new files |
| 37 | 38 | - Follow the existing naming conventions |
| 38 | 39 | - Write tests for all new features |
| 39 | 40 | ``` |
| 40 | 41 | |
| 41 | 42 | <Tip> |
| 42 | - Place rules files at different levels of your project hierarchy to scope when they trigger | |
| 43 | + Place rules files at different levels of your project hierarchy to scope when | |
| 44 | + they trigger | |
| 43 | 45 | </Tip> |
| 44 | 46 | |
| 45 | 47 | Learn more about [rules configuration](/customize/deep-dives/rules). |
| @@ -60,6 +62,7 @@ | ||
| 60 | 62 | # External Dependencies |
| 61 | 63 | |
| 62 | 64 | Our authentication system is based on: |
| 65 | + | |
| 63 | 66 | - [Auth.js documentation](https://authjs.dev/) |
| 64 | 67 | - [Example implementation](https://github.com/nextauthjs/next-auth-example) |
| 65 | 68 | |
| @@ -76,6 +79,7 @@ | ||
| 76 | 79 | # Repository Access |
| 77 | 80 | |
| 78 | 81 | You can use the `gh` CLI to: |
| 82 | + | |
| 79 | 83 | - Search for issues: `gh issue list --repo owner/repo` |
| 80 | 84 | - View pull requests: `gh pr list --repo owner/repo` |
| 81 | 85 | - Clone repositories: `gh repo clone owner/repo` |
| @@ -84,9 +88,9 @@ | ||
| 84 | 88 | #### DeepWiki MCP |
| 85 | 89 | |
| 86 | 90 | [DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository. |
| 87 | -``` | |
| 88 | 91 | |
| 89 | 92 | Once configured, your agent can explore repositories like: |
| 93 | + | |
| 90 | 94 | - "Explore the React repository structure" |
| 91 | 95 | - "Find how authentication is implemented in NextAuth.js" |
| 92 | 96 | |
| @@ -116,6 +120,7 @@ | ||
| 116 | 120 | # Documentation Resources |
| 117 | 121 | |
| 118 | 122 | For framework-specific questions, refer to: |
| 123 | + | |
| 119 | 124 | - React: https://react.dev/reference/react |
| 120 | 125 | - Next.js: https://nextjs.org/docs |
| 121 | 126 | - Tailwind CSS: https://tailwindcss.com/docs |
| @@ -128,6 +133,7 @@ | ||
| 128 | 133 | [Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation: |
| 129 | 134 | |
| 130 | 135 | Your agent can then answer questions like: |
| 136 | + | |
| 131 | 137 | - "How do I use React hooks?" |
| 132 | 138 | - "What's the syntax for Tailwind CSS animations?" |
| 133 | 139 | |
| @@ -143,6 +149,7 @@ | ||
| 143 | 149 | # Internal Documentation |
| 144 | 150 | |
| 145 | 151 | Our team documentation is available at: |
| 152 | + | |
| 146 | 153 | - API Documentation: https://internal.docs/api |
| 147 | 154 | - Architecture Guide: https://internal.docs/architecture |
| 148 | 155 | - Deployment Process: https://internal.docs/deployment |
| @@ -180,4 +187,4 @@ | ||
| 180 | 187 | |
| 181 | 188 | - Learn more about [MCP servers](/reference/continue-mcp) |
| 182 | 189 | - Explore [rules configuration](/customize/deep-dives/rules) |
| 183 | -- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains | |
| No newline at the end of the file | ||
| 190 | +- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains |
| @@ -0,0 +1,309 @@ | ||
| 1 | +--- | |
| 2 | +title: Assessing Your Team's Readiness for Continuous AI | |
| 3 | +description: Complete framework to evaluate team readiness for Continuous AI adoption with maturity levels, assessment criteria, and implementation roadmap. | |
| 4 | +sidebarTitle: Continuous AI Readiness Assessment | |
| 5 | +--- | |
| 6 | + | |
| 7 | +<Info> | |
| 8 | + **TL;DR:** Use this assessment framework to determine if your team is ready to | |
| 9 | + move from individual AI tool usage to automated Continuous AI workflows. | |
| 10 | + Covers technical infrastructure, processes, culture, and organizational | |
| 11 | + support. | |
| 12 | +</Info> | |
| 13 | + | |
| 14 | +## Assessing Continuous AI Readiness | |
| 15 | + | |
| 16 | +Continuous AI can dramatically improve development velocity and code quality, but successful implementation requires careful evaluation across four key dimensions. | |
| 17 | + | |
| 18 | +<Warning> | |
| 19 | + Rushing into Continuous AI without proper foundations leads to frustration and | |
| 20 | + failed initiatives. Use this framework to identify gaps before scaling. | |
| 21 | +</Warning> | |
| 22 | + | |
| 23 | +### 1. Identify Your Current Maturity Level | |
| 24 | + | |
| 25 | +Determine where your team falls on the Continuous AI maturity spectrum: | |
| 26 | + | |
| 27 | +<CardGroup cols={1}> | |
| 28 | + <Card title="Level 1: Manual AI Assistance" icon="user"> | |
| 29 | + Developers use AI tools inconsistently with highly variable results. | |
| 30 | + | |
| 31 | + **Characteristics:** | |
| 32 | + - High rejection rates of AI-generated code (>50%) | |
| 33 | + - No shared standards or prompting rules | |
| 34 | + - AI tools lack context about your codebase | |
| 35 | + - Ad-hoc usage without team coordination | |
| 36 | + | |
| 37 | + </Card> | |
| 38 | + | |
| 39 | +<Card title="Level 2: Workflow Automation" icon="gear"> | |
| 40 | + AI is systematically integrated into team workflows and CI/CD pipelines. | |
| 41 | + | |
| 42 | +**Characteristics:** | |
| 43 | + | |
| 44 | +- Consistent adoption across 80%+ of team members | |
| 45 | +- AI integrated into code reviews and deployment processes | |
| 46 | +- Documented standards for prompts and tool usage | |
| 47 | +- Basic metrics tracking AI impact | |
| 48 | + | |
| 49 | +</Card> | |
| 50 | + | |
| 51 | + <Card title="Level 3: Zero-Intervention Workflows" icon="robot"> | |
| 52 | + Certain development processes run autonomously with minimal human oversight. | |
| 53 | + | |
| 54 | + **Characteristics:** | |
| 55 | + - Human intervention rates below 15% | |
| 56 | + - Robust monitoring and automated rollback systems | |
| 57 | + - Measurable ROI from automation initiatives | |
| 58 | + - Advanced context awareness and learning loops | |
| 59 | + | |
| 60 | + </Card> | |
| 61 | +</CardGroup> | |
| 62 | + | |
| 63 | +### 2. Evaluate Readiness Across Four Key Dimensions | |
| 64 | + | |
| 65 | +Assess your team's strengths and potential risks across these critical areas: | |
| 66 | + | |
| 67 | +<AccordionGroup> | |
| 68 | + <Accordion title="Technical Infrastructure Assessment"> | |
| 69 | + **Key Questions:** | |
| 70 | + - Do our development tools integrate reliably? | |
| 71 | + - Can we measure AI effectiveness and impact? | |
| 72 | + - Are security policies compatible with AI workflows? | |
| 73 | + | |
| 74 | + **🟢 Green Flags:** | |
| 75 | + - Stable tool integrations with >99.5% uptime | |
| 76 | + - Comprehensive monitoring and observability | |
| 77 | + - Security policies that support AI tool usage | |
| 78 | + - Automated testing and deployment pipelines | |
| 79 | + | |
| 80 | + **🔴 Red Flags:** | |
| 81 | + - Frequent integration breakdowns | |
| 82 | + - No performance tracking or metrics | |
| 83 | + - Restrictive security policies blocking AI tools | |
| 84 | + - Manual deployment processes | |
| 85 | + | |
| 86 | + </Accordion> | |
| 87 | + | |
| 88 | +<Accordion title="Process Maturity Assessment"> | |
| 89 | + **Key Questions:** | |
| 90 | + - Are our development workflows consistent and documented? | |
| 91 | + - Do we have quality gates and review processes? | |
| 92 | + - Can we reproduce builds and deployments reliably? | |
| 93 | + | |
| 94 | + **🟢 Green Flags:** | |
| 95 | + - Clear coding standards and style guides | |
| 96 | + - Automated CI/CD with quality gates | |
| 97 | + - Documented, repeatable processes | |
| 98 | + - Consistent code review practices | |
| 99 | + | |
| 100 | + **🔴 Red Flags:** | |
| 101 | + - Inconsistent code reviews | |
| 102 | + - Ad-hoc deployment processes | |
| 103 | + - "Works on my machine" culture | |
| 104 | + - Undocumented tribal knowledge | |
| 105 | + | |
| 106 | +</Accordion> | |
| 107 | + | |
| 108 | +<Accordion title="Team Culture & Skills Assessment"> | |
| 109 | + **Key Questions:** | |
| 110 | + - Are developers open to adopting new AI-powered workflows? | |
| 111 | + - How does the team handle experimentation and failure? | |
| 112 | + - Do team members collaborate effectively on new initiatives? | |
| 113 | + | |
| 114 | + **🟢 Green Flags:** | |
| 115 | + - High curiosity and willingness to experiment | |
| 116 | + - Collaborative problem-solving culture | |
| 117 | + - Constructive feedback and learning mindset | |
| 118 | + - Active knowledge sharing practices | |
| 119 | + | |
| 120 | +**🔴 Red Flags:** | |
| 121 | + | |
| 122 | +- Strong resistance to workflow changes | |
| 123 | +- Blame culture around mistakes | |
| 124 | +- Perfectionism blocking experimentation | |
| 125 | +- Siloed work with minimal collaboration | |
| 126 | + | |
| 127 | +</Accordion> | |
| 128 | + | |
| 129 | + <Accordion title="Organizational Support Assessment"> | |
| 130 | + **Key Questions:** | |
| 131 | + - Does leadership provide budget and resources for AI initiatives? | |
| 132 | + - Is there tolerance for experimentation and learning? | |
| 133 | + - Are expectations realistic for ROI timelines? | |
| 134 | + | |
| 135 | + **🟢 Green Flags:** | |
| 136 | + - Executive buy-in and strategic alignment | |
| 137 | + - Dedicated budget for training and tools | |
| 138 | + - 3-6 month ROI expectations | |
| 139 | + - Support for calculated risk-taking | |
| 140 | + | |
| 141 | + **🔴 Red Flags:** | |
| 142 | + - Pressure for immediate ROI (weeks) | |
| 143 | + - No allocated budget for AI initiatives | |
| 144 | + - High risk aversion culture | |
| 145 | + - Lack of leadership engagement | |
| 146 | + | |
| 147 | + </Accordion> | |
| 148 | +</AccordionGroup> | |
| 149 | + | |
| 150 | +### 3. Critical Warning Signs | |
| 151 | + | |
| 152 | +<Warning> | |
| 153 | + **Stop and address these issues before scaling Continuous AI:** | |
| 154 | +</Warning> | |
| 155 | + | |
| 156 | +<CardGroup cols={2}> | |
| 157 | + <Card title="Technical Red Flags" icon="triangle-exclamation"> | |
| 158 | + - Builds breaking regularly (>5% failure rate) | |
| 159 | + - Unstable deployments or rollback frequency >10% | |
| 160 | + - No monitoring or observability systems | |
| 161 | + - Critical security policy conflicts | |
| 162 | + | |
| 163 | + </Card> | |
| 164 | + | |
| 165 | +<Card title="Team & Culture Red Flags" icon="users-slash"> | |
| 166 | + - More than 30% of team opposed to AI tools | |
| 167 | + - No established feedback or learning culture | |
| 168 | + - History of failed automation initiatives | |
| 169 | + - Resistance to changing existing workflows | |
| 170 | + | |
| 171 | +</Card> | |
| 172 | + | |
| 173 | +<Card title="Process Red Flags" icon="exclamation-triangle"> | |
| 174 | + - Inconsistent development workflows | |
| 175 | + - No quality gates or review processes | |
| 176 | + - Manual deployment and testing processes | |
| 177 | + - Lack of documentation and standards | |
| 178 | + | |
| 179 | +</Card> | |
| 180 | + | |
| 181 | + <Card title="Organizational Red Flags" icon="building"> | |
| 182 | + - Leadership expecting ROI in weeks vs months | |
| 183 | + - No allocated budget for AI initiatives | |
| 184 | + - High pressure, low experimentation tolerance | |
| 185 | + - Lack of strategic alignment on AI adoption | |
| 186 | + | |
| 187 | + </Card> | |
| 188 | +</CardGroup> | |
| 189 | + | |
| 190 | +### 4. Implementation Roadmap | |
| 191 | + | |
| 192 | +Based on your assessment results, follow this step-by-step approach: | |
| 193 | + | |
| 194 | +<Steps> | |
| 195 | + <Step title="Establish Baseline Metrics"> | |
| 196 | + Document current performance across key areas: | |
| 197 | + | |
| 198 | + - Development velocity (story | |
| 199 | + points, cycle time) | |
| 200 | + - Code quality metrics (bug rates, technical debt) | |
| 201 | + - Review times and approval rates | |
| 202 | + - Developer satisfaction and productivity | |
| 203 | + scores | |
| 204 | + | |
| 205 | + </Step> | |
| 206 | + | |
| 207 | +<Step title="Select Initial Automation Target"> | |
| 208 | + Choose one high-impact, low-risk workflow to automate first: | |
| 209 | + | |
| 210 | + - **Code Review:** Automated analysis and suggestions | |
| 211 | + - **Documentation:** Auto-generated API docs and README updates | |
| 212 | + - **Testing:** Automated test generation and maintenance | |
| 213 | + - **Refactoring:** Systematic code improvement suggestions | |
| 214 | + | |
| 215 | + </Step> | |
| 216 | + | |
| 217 | +<Step title="Standardize Team AI Usage"> | |
| 218 | + Create and document consistent practices: | |
| 219 | + - AI tool selection and configuration guidelines | |
| 220 | + | |
| 221 | + - Prompting standards and best practices | |
| 222 | + | |
| 223 | + - Quality gates and review processes | |
| 224 | + | |
| 225 | + - Security and compliance requirements | |
| 226 | + | |
| 227 | + </Step> | |
| 228 | + | |
| 229 | +<Step title="Pilot and Measure Impact"> | |
| 230 | + Run controlled experiments with success criteria: | |
| 231 | + - Start with 2-3 team members for 2-4 weeks | |
| 232 | + - Track metrics against baseline performance | |
| 233 | + - Gather qualitative feedback on developer experience | |
| 234 | + - Document lessons learned and optimization opportunities | |
| 235 | + | |
| 236 | +</Step> | |
| 237 | + | |
| 238 | + <Step title="Scale Deliberately"> | |
| 239 | + Expand successful pilots across the organization: | |
| 240 | + - Roll out to additional team members gradually | |
| 241 | + - Implement monitoring and alerting systems | |
| 242 | + - Establish feedback loops for continuous improvement | |
| 243 | + - Plan next automation targets based on results | |
| 244 | + | |
| 245 | + </Step> | |
| 246 | +</Steps> | |
| 247 | + | |
| 248 | +<CardGroup cols={2}> | |
| 249 | + <Card | |
| 250 | + title="Building Async Agents with Continue CLI" | |
| 251 | + icon="blog" | |
| 252 | + href="https://blog.continue.dev/building-async-agents-with-continue-cli/" | |
| 253 | + > | |
| 254 | + Comprehensive explanation of maturity levels and organizational readiness | |
| 255 | + factors | |
| 256 | + </Card> | |
| 257 | + | |
| 258 | + <Card | |
| 259 | + title="Developer's Guide" | |
| 260 | + icon="book" | |
| 261 | + href="https://docs.continue.dev/guides/continuous-ai" | |
| 262 | + > | |
| 263 | + Technical implementation details and best practices for Continuous AI | |
| 264 | + workflows | |
| 265 | + </Card> | |
| 266 | +</CardGroup> | |
| 267 | + | |
| 268 | +## Quick Assessment Checklist | |
| 269 | + | |
| 270 | +<Tip> | |
| 271 | + **Ready to get started?** Use this quick checklist to gauge your immediate | |
| 272 | + readiness: | |
| 273 | +</Tip> | |
| 274 | + | |
| 275 | +**Technical Foundation (Score: \_\_\_/4)** | |
| 276 | + | |
| 277 | +- Stable CI/CD pipelines with \<5% failure rate | |
| 278 | +- Monitoring and observability systems in place | |
| 279 | +- Security policies support AI tool integration | |
| 280 | +- Development environment standardization | |
| 281 | + | |
| 282 | +**Process Maturity (Score: \_\_\_/4)** | |
| 283 | + | |
| 284 | +- Documented coding standards and review processes | |
| 285 | +- Consistent deployment and rollback procedures | |
| 286 | +- Quality gates and automated testing | |
| 287 | +- Regular retrospectives and process improvement | |
| 288 | + | |
| 289 | +**Team Culture (Score: \_\_\_/4)** | |
| 290 | + | |
| 291 | +- \<30% resistance to AI tool adoption | |
| 292 | +- Active experimentation and learning culture | |
| 293 | +- Collaborative problem-solving approach | |
| 294 | +- Constructive feedback and knowledge sharing | |
| 295 | + | |
| 296 | +**Organizational Support (Score: \_\_\_/4)** | |
| 297 | + | |
| 298 | +- Leadership buy-in and strategic alignment | |
| 299 | +- Dedicated budget for AI initiatives and training | |
| 300 | +- 3-6 month ROI expectations (not weeks) | |
| 301 | +- Support for calculated risk-taking | |
| 302 | + | |
| 303 | +--- | |
| 304 | + | |
| 305 | +**Overall Readiness Score: \_\_\_/16** | |
| 306 | + | |
| 307 | +- **12-16:** Ready to begin Continuous AI implementation | |
| 308 | +- **8-11:** Address gaps in 1-2 areas before scaling | |
| 309 | +- **\<8:** Focus on foundational improvements first |
| @@ -0,0 +1,207 @@ | ||
| 1 | +--- | |
| 2 | +title: "Continuous AI: A Developer's Guide" | |
| 3 | +description: "Learn how to integrate intelligent automation into development workflows, making AI assistance as natural as syntax highlighting. Implement systematic AI workflows that compound productivity gains over time." | |
| 4 | +--- | |
| 5 | + | |
| 6 | +Continuous AI is the integration of intelligent automation directly into development workflows, making AI assistance as natural and reliable as syntax highlighting or code completion. Its purpose is to amplify developer intent at every stage of the coding process. | |
| 7 | + | |
| 8 | +Think of it this way: DevOps automated the mechanical aspects of software delivery—building, testing, deploying. Continuous AI automates the intelligence aspects—understanding context, making suggestions, adapting to patterns, and learning from developer feedback. | |
| 9 | + | |
| 10 | +## Why Continuous AI Matters Now | |
| 11 | + | |
| 12 | +The same market forces that made DevOps inevitable are now driving Continuous AI adoption: | |
| 13 | + | |
| 14 | +<CardGroup> | |
| 15 | + <Card title="Developer Behavior is Shifting" icon="chart-line"> | |
| 16 | + Engineering teams are rapidly adopting AI tools, with many seeing | |
| 17 | + significant productivity improvements in their workflows. | |
| 18 | + </Card> | |
| 19 | + | |
| 20 | +<Card title="Economic Pressure" icon="dollar-sign"> | |
| 21 | + AI-assisted coding is contributing measurable increases in developer output, | |
| 22 | + creating competitive advantages for early adopters. | |
| 23 | +</Card> | |
| 24 | + | |
| 25 | + <Card title="Tooling Maturity" icon="wrench"> | |
| 26 | + Unlike DevOps, Continuous AI can be implemented incrementally on existing | |
| 27 | + development stacks without major infrastructure changes. | |
| 28 | + </Card> | |
| 29 | +</CardGroup> | |
| 30 | + | |
| 31 | +The teams that implement systematic AI workflows first create advantages that compound over time. | |
| 32 | + | |
| 33 | +## The Continuous AI Maturity Model | |
| 34 | + | |
| 35 | +Teams typically progress through three stages when adopting Continuous AI: | |
| 36 | + | |
| 37 | +<Accordion title="Level 1: Manual AI Assistance"> | |
| 38 | +You prompt the AI when you remember, and it completes the task. This is great for quick productivity boosts but remains highly manual and inconsistent. | |
| 39 | + | |
| 40 | +**Example**: Using AI to draft a function or suggest a test case only when you think to ask for it. | |
| 41 | + | |
| 42 | +**Continue Implementation**: Using [Chat](/features/chat/quick-start) or [Edit](/features/edit/quick-start) mode for one-off coding tasks. | |
| 43 | + | |
| 44 | +</Accordion> | |
| 45 | + | |
| 46 | +<Accordion title="Level 2: Workflow Automation"> | |
| 47 | +AI handles routine tasks with human oversight. This is where teams start seeing compounding gains. | |
| 48 | + | |
| 49 | +**Examples**: | |
| 50 | + | |
| 51 | +- AI adds missing documentation during PR review | |
| 52 | +- Automatic code formatting and style corrections | |
| 53 | +- Generated unit tests for new functions | |
| 54 | +- Updated issue tracking when branches are merged | |
| 55 | + | |
| 56 | +**Continue Implementation**: Using [Continue CLI](/guides/cli) with custom rules and integrations into CI/CD pipelines. | |
| 57 | + | |
| 58 | +</Accordion> | |
| 59 | + | |
| 60 | +<Accordion title="Level 3: Zero-Intervention Workflows"> | |
| 61 | +AI autonomously completes processes end-to-end without human input, but only for very specific, low-risk workflows. | |
| 62 | + | |
| 63 | +**Examples**: | |
| 64 | + | |
| 65 | +- AI merges safe dependency updates after automated tests pass | |
| 66 | +- Automatic documentation updates when code changes | |
| 67 | +- Self-healing test suites that fix themselves based on failure patterns | |
| 68 | + | |
| 69 | +**Continue Implementation**: Fully automated [agents](/features/agent/quick-start) with strict permissions and safety guardrails. | |
| 70 | + | |
| 71 | +</Accordion> | |
| 72 | + | |
| 73 | +## Building Your Continuous AI Workflow | |
| 74 | + | |
| 75 | +### Start with Level 1 → Level 2: Pick One Workflow | |
| 76 | + | |
| 77 | +Don't try to automate everything at once. Choose a specific daily friction point: | |
| 78 | + | |
| 79 | +```bash | |
| 80 | +# Example: Automated code review comments | |
| 81 | +git diff | cn -p "review this diff and suggest improvements following our team standards" | |
| 82 | + | |
| 83 | +# Example: Generate missing tests | |
| 84 | +cn -p "create unit tests for the functions in src/auth.js" | |
| 85 | + | |
| 86 | +# Example: Update documentation | |
| 87 | +cn -p "update the README with the new API endpoints from the recent changes" | |
| 88 | +``` | |
| 89 | + | |
| 90 | +### Configure Team-Wide Intelligence | |
| 91 | + | |
| 92 | +The most effective Continuous AI is tuned to your codebase, standards, and practices: | |
| 93 | + | |
| 94 | +```yaml config.yaml | |
| 95 | +rules: | |
| 96 | + - name: code-review | |
| 97 | + description: "Review code following team standards" | |
| 98 | + rule: "Review following our TypeScript style guide and security practices" | |
| 99 | + context: | |
| 100 | + - "docs/style-guide.md" | |
| 101 | + - "security-checklist.md" | |
| 102 | +``` | |
| 103 | + | |
| 104 | +### Implement Progressive Permissions | |
| 105 | + | |
| 106 | +Use Continue CLI's permission system to gradually expand AI capabilities: | |
| 107 | + | |
| 108 | +```yaml ~/.continue/permissions.yaml | |
| 109 | +permissions: | |
| 110 | + - allow: "Bash(git*)" # Git commands are safe | |
| 111 | + - ask: "Write(**/*.ts)" # Ask before modifying TypeScript files | |
| 112 | + - deny: "Bash(rm*)" # Never allow deletions | |
| 113 | +``` | |
| 114 | + | |
| 115 | +### Measure What Matters: Intervention Rate | |
| 116 | + | |
| 117 | +Track how often you need to correct AI output. Lower intervention rates mean higher trust and compounding productivity gains. | |
| 118 | + | |
| 119 | +## Real-World Implementation Patterns | |
| 120 | + | |
| 121 | +<AccordionGroup> | |
| 122 | + <Accordion title="Pattern 1: The Async Triage Bot"> | |
| 123 | + Imagine setting up an AI agent that checks new GitHub issues every morning and leaves the first helpful response. This lightens the load for maintainers and ensures community members feel heard quickly. | |
| 124 | + </Accordion> | |
| 125 | + | |
| 126 | + <Accordion title="Pattern 2: The PR Review Agent"> | |
| 127 | + AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the agent highlights common problems and speeds up the feedback loop. | |
| 128 | + | |
| 129 | + </Accordion> | |
| 130 | + <Accordion title="Pattern 3: The Documentation Guardian"> | |
| 131 | + Whenever code changes, AI can scan for mismatches in documentation and suggest updates. This keeps docs current without relying on developers to remember every detail. | |
| 132 | + </Accordion> | |
| 133 | +</AccordionGroup> | |
| 134 | +## Best Practices for Sustainable Continuous AI | |
| 135 | + | |
| 136 | +<CardGroup> | |
| 137 | + <Card title="Human-AI Collaboration" icon="handshake"> | |
| 138 | + AI should amplify human intelligence, not replace it. Always validate AI | |
| 139 | + suggestions rather than blindly accepting them. | |
| 140 | + </Card> | |
| 141 | + | |
| 142 | +<Card title="Start Small, Scale Thoughtfully" icon="seedling"> | |
| 143 | + Begin with low-risk, high-value automations. Gradually expand as you build | |
| 144 | + trust and understanding. | |
| 145 | +</Card> | |
| 146 | + | |
| 147 | +<Card title="Customize for Your Context" icon="cog"> | |
| 148 | + Generic AI suggestions are often wrong or irrelevant. Configure AI to | |
| 149 | + understand your specific patterns and requirements. | |
| 150 | +</Card> | |
| 151 | + | |
| 152 | + <Card title="Build Safety Guardrails" icon="shield"> | |
| 153 | + Use permission systems, code review processes, and testing to ensure AI | |
| 154 | + actions are safe and reversible. | |
| 155 | + </Card> | |
| 156 | +</CardGroup> | |
| 157 | + | |
| 158 | +## Common Pitfalls to Avoid | |
| 159 | + | |
| 160 | +<Warning> | |
| 161 | + **Over-automation**: Don't automate processes you don't fully understand | |
| 162 | +</Warning> | |
| 163 | + | |
| 164 | +<Warning> | |
| 165 | + **Ignoring Context**: AI works best when it understands your codebase and team | |
| 166 | + practices | |
| 167 | +</Warning> | |
| 168 | + | |
| 169 | +<Warning> | |
| 170 | + **Skipping Safety**: Always implement proper permissions and review processes | |
| 171 | +</Warning> | |
| 172 | + | |
| 173 | +<Warning> | |
| 174 | + **Vanity Metrics**: Focus on intervention rate and actual time saved, not "AI | |
| 175 | + suggestions generated" | |
| 176 | +</Warning> | |
| 177 | + | |
| 178 | +## Getting Started Today | |
| 179 | + | |
| 180 | +<Steps> | |
| 181 | + <Step title="Install Continue CLI"> | |
| 182 | + ```bash npm i -g @continuedev/cli ``` | |
| 183 | + </Step> | |
| 184 | + | |
| 185 | +<Step title="Pick One Workflow">Choose a daily friction point to automate</Step> | |
| 186 | + | |
| 187 | +<Step title="Set Permissions">Configure safe boundaries for AI actions</Step> | |
| 188 | + | |
| 189 | +<Step title="Measure Impact">Track intervention rates and time saved</Step> | |
| 190 | + | |
| 191 | + <Step title="Iterate and Expand">Gradually add more automated workflows</Step> | |
| 192 | +</Steps> | |
| 193 | + | |
| 194 | +## The Competitive Advantage | |
| 195 | + | |
| 196 | +Teams implementing Continuous AI are coding faster and building institutional intelligence that scales with their organization. While others manually perform routine tasks, your AI handles the repetitive work so your team can focus on innovation and complex problem-solving. | |
| 197 | + | |
| 198 | +## What's Next? | |
| 199 | + | |
| 200 | +As AI capabilities continue to improve and tooling matures, we're moving toward a world where intelligent assistance is as fundamental to development as version control or IDEs. The teams that start building these capabilities now will have refined systems, cultural readiness, and institutional knowledge when Continuous AI becomes the industry standard. | |
| 201 | + | |
| 202 | +Ready to amplify your development workflow with Continuous AI? Start with one simple automation and build from there. | |
| 203 | + | |
| 204 | +<Card title="Want to dive deeper?" icon="rocket"> | |
| 205 | + Check out our guides on [Continue CLI](/guides/cli) and [Understanding | |
| 206 | + Agents](/guides/understanding-agents). | |
| 207 | +</Card> |
| @@ -0,0 +1,39 @@ | ||
| 1 | +--- | |
| 2 | +title: "Using Instinct with Ollama in Continue" | |
| 3 | +description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +<Warning> | |
| 7 | + Instinct is a 7 billion parameter model. You should expect slow responses if | |
| 8 | + running on a laptop. To learn how to inference Instinct on a GPU, see our | |
| 9 | + [HuggingFace model card](https://huggingface.co/continuedev/instinct). | |
| 10 | +</Warning> | |
| 11 | + | |
| 12 | +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). | |
| 13 | + | |
| 14 | +<Frame> | |
| 15 | + <img src="/images/instinct.gif" /> | |
| 16 | +</Frame> | |
| 17 | + | |
| 18 | +### 1. Install Ollama | |
| 19 | + | |
| 20 | +If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx). | |
| 21 | + | |
| 22 | +### 2. Download Instinct | |
| 23 | + | |
| 24 | +```bash | |
| 25 | +ollama run nate/instinct | |
| 26 | +``` | |
| 27 | + | |
| 28 | +### 3. Update your `config.yaml` | |
| 29 | + | |
| 30 | +Open your `config.yaml` and add Instinct to the models section: | |
| 31 | + | |
| 32 | +```yaml | |
| 33 | +# ... rest of config.yaml ... | |
| 34 | + | |
| 35 | +models: | |
| 36 | + - uses: continuedev/instinct | |
| 37 | +``` | |
| 38 | + | |
| 39 | +Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct. |
| @@ -34,15 +34,15 @@ | ||
| 34 | 34 | After installation, start the Ollama service: |
| 35 | 35 | |
| 36 | 36 | ```bash |
| 37 | +# Check Ollama version - verify it's installed | |
| 38 | +ollama --version | |
| 39 | + | |
| 37 | 40 | # Start Ollama (runs in background) |
| 38 | 41 | ollama serve |
| 39 | 42 | |
| 40 | 43 | # Verify it's running |
| 41 | 44 | curl http://localhost:11434 |
| 42 | 45 | # Should return "Ollama is running" |
| 43 | - | |
| 44 | -# Check Ollama version | |
| 45 | -ollama --version | |
| 46 | 46 | ``` |
| 47 | 47 | |
| 48 | 48 | ### Step 3: Download Models |
| @@ -86,8 +86,8 @@ | ||
| 86 | 86 | |
| 87 | 87 | The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration: |
| 88 | 88 | |
| 89 | -```yaml title="~/.continue/assistants/My Local Assistant.yaml" | |
| 90 | -name: My Local Assistant | |
| 89 | +```yaml title="~/.continue/agents/My Local Agent.yaml" | |
| 90 | +name: My Local Agent | |
| 91 | 91 | version: 0.0.1 |
| 92 | 92 | schema: v1 |
| 93 | 93 | models: |
| @@ -190,9 +190,12 @@ | ||
| 190 | 190 | |
| 191 | 191 | #### If Agent Mode Shows "Not Supported" |
| 192 | 192 | |
| 193 | + | |
| 194 | + | |
| 193 | 195 | 1. First, add `capabilities: [tool_use]` to your model config |
| 194 | 196 | 2. If you still get errors, the model may not actually support tools despite documentation |
| 195 | 197 | 3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral) |
| 198 | +4. Alternatively, you can turn on [System Message tools](/features/agent/model-setup#how-system-message-tools-work) | |
| 196 | 199 | |
| 197 | 200 | See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details. |
| 198 | 201 | |
| @@ -309,11 +312,11 @@ | ||
| 309 | 312 | #### Using Hub Blocks in Local Config |
| 310 | 313 | |
| 311 | 314 | **Problem**: Unclear how to use hub models locally |
| 312 | -**Solution**: Create a local assistant file: | |
| 315 | +**Solution**: Create a local agent file: | |
| 313 | 316 | |
| 314 | 317 | ```yaml |
| 315 | -# ~/.continue/assistants/Local.yaml | |
| 316 | -name: Local Assistant | |
| 318 | +# ~/.continue/agents/Local.yaml | |
| 319 | +name: Local Agent | |
| 317 | 320 | version: 0.0.1 |
| 318 | 321 | schema: v1 |
| 319 | 322 | models: |
| @@ -9,6 +9,13 @@ | ||
| 9 | 9 | - [How to Self-Host a Model](/guides/how-to-self-host-a-model) - Self-hosting AI models |
| 10 | 10 | - [Running Continue Without Internet](/guides/running-continue-without-internet) - Offline development setup |
| 11 | 11 | |
| 12 | +## Continuous AI | |
| 13 | + | |
| 14 | +- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows | |
| 15 | +- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue | |
| 16 | +- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption | |
| 17 | +- [PostHog Session Analysis with Continue CLI](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation | |
| 18 | + | |
| 12 | 19 | ## What Advanced Tutorials Are Available |
| 13 | 20 | |
| 14 | 21 | - [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make your agent aware of codebases and documentation |
| @@ -0,0 +1,496 @@ | ||
| 1 | +--- | |
| 2 | +title: "Building a Continuous AI Workflow with PostHog and GitHub" | |
| 3 | +description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically." | |
| 4 | +sidebarTitle: "PostHog Session Analysis with Continue CLI" | |
| 5 | +--- | |
| 6 | + | |
| 7 | +<Card title="What You'll Build" icon="robot"> | |
| 8 | + A fully automated workflow that uses Continue CLI to fetch PostHog session | |
| 9 | + data, analyze user experience issues with AI, and automatically create GitHub | |
| 10 | + issues with specific technical recommendations | |
| 11 | +</Card> | |
| 12 | + | |
| 13 | +## Prerequisites | |
| 14 | + | |
| 15 | +Before starting, ensure you have: | |
| 16 | + | |
| 17 | +- GitHub repository where you want to create issues | |
| 18 | +- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)** | |
| 19 | +- Node.js 18+ installed locally | |
| 20 | +- Continue CLI account with **active credits** (required for API usage) | |
| 21 | + | |
| 22 | +<Steps> | |
| 23 | + <Step title="Install Continue CLI"> | |
| 24 | + ```bash | |
| 25 | + npm i -g @continuedev/cli | |
| 26 | + ``` | |
| 27 | + </Step> | |
| 28 | + | |
| 29 | + <Step title="Set up Continue CLI Account & API Key"> | |
| 30 | + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) | |
| 31 | + 2. Sign up or log in to your Continue account | |
| 32 | + 3. Navigate to your organization settings | |
| 33 | + 4. Click **"API Keys"** and then **"+ New API Key"** | |
| 34 | + 5. Copy the API key immediately (you won't see it again!) | |
| 35 | + 6. Login to the CLI: `cn login` | |
| 36 | + </Step> | |
| 37 | + | |
| 38 | + <Step title="Add Required Secrets to Continue CLI"> | |
| 39 | + Continue CLI will securely store your API keys as secrets that can be referenced in prompts. | |
| 40 | + </Step> | |
| 41 | +</Steps> | |
| 42 | + | |
| 43 | +<Tip> | |
| 44 | + Continue CLI handles all the complex API interactions - you just need to | |
| 45 | + provide the right prompts! | |
| 46 | +</Tip> | |
| 47 | + | |
| 48 | +## Step 1: Set Up Your Credentials | |
| 49 | + | |
| 50 | +First, you'll need to gather your API credentials and add them as secrets in Continue CLI. | |
| 51 | + | |
| 52 | +### Get Your PostHog API Credentials | |
| 53 | + | |
| 54 | +You need a **Personal API Key** (not a Project API key) to access session recordings: | |
| 55 | + | |
| 56 | +1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog | |
| 57 | +2. Click **+ Create a personal API Key** | |
| 58 | +3. Name it "Continue CLI Session Analysis" | |
| 59 | +4. Select these scopes: | |
| 60 | + - `session_recording:read` - **Required** for accessing session data | |
| 61 | + - `insight:read` - Optional, for additional analytics | |
| 62 | +5. Copy the key immediately (you won't see it again!) | |
| 63 | + | |
| 64 | +<Tip> | |
| 65 | + **Find Your Project Details**: Your Project ID is in your PostHog URL: | |
| 66 | + `https://app.posthog.com/project/YOUR_PROJECT_ID` | |
| 67 | +</Tip> | |
| 68 | + | |
| 69 | +### Get Your GitHub Personal Access Token | |
| 70 | + | |
| 71 | +1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new) | |
| 72 | +2. Click **"Generate new token (classic)"** | |
| 73 | +3. Name it "Continue CLI PostHog Analysis" | |
| 74 | +4. Select these scopes: | |
| 75 | + - `repo` (or just `public_repo` if your repository is public) | |
| 76 | + - `issues:write` - **Required** for creating issues | |
| 77 | +5. Copy the token immediately | |
| 78 | + | |
| 79 | +### Add Secrets to Continue CLI | |
| 80 | + | |
| 81 | +Use Continue CLI's built-in environment setup helper: | |
| 82 | + | |
| 83 | +```bash | |
| 84 | +cn -p "Help me set up my environment for PostHog session analysis. Please: | |
| 85 | +1. Check if I have the required secrets configured in Continue CLI: | |
| 86 | + - POSTHOG_API_KEY | |
| 87 | + - POSTHOG_PROJECT_ID | |
| 88 | + - POSTHOG_HOST | |
| 89 | + - GITHUB_PAT | |
| 90 | +2. If any are missing, guide me through: | |
| 91 | + - How to get PostHog Personal API Key from PostHog settings | |
| 92 | + - How to find my PostHog Project ID from the URL | |
| 93 | + - How to create a GitHub Personal Access Token with issues:write permission | |
| 94 | + - How to add these as secrets in Continue CLI | |
| 95 | +3. Help me identify my GitHub repository owner and name by: | |
| 96 | + - Checking git remote origin URL | |
| 97 | + - Or asking me to provide them | |
| 98 | +4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work. | |
| 99 | +Please walk me through this setup process step by step." | |
| 100 | +``` | |
| 101 | + | |
| 102 | +<Info> | |
| 103 | + Continue CLI will guide you through adding secrets and testing your API | |
| 104 | + connections. Follow the prompts to add: - `POSTHOG_API_KEY`: Your PostHog | |
| 105 | + Personal API Key - `POSTHOG_PROJECT_ID`: Your PostHog Project ID - | |
| 106 | + `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) - | |
| 107 | + `GITHUB_PAT`: Your GitHub Personal Access Token | |
| 108 | +</Info> | |
| 109 | + | |
| 110 | +## Step 2: Analyze PostHog Sessions with Continue CLI | |
| 111 | + | |
| 112 | +Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically. | |
| 113 | + | |
| 114 | +### Run the Analysis | |
| 115 | + | |
| 116 | +Use this prompt with Continue CLI to fetch and analyze your PostHog sessions: | |
| 117 | + | |
| 118 | +```bash | |
| 119 | +cn -p "I need you to help me analyze PostHog session recordings to identify UX issues. Please: | |
| 120 | + | |
| 121 | +1. First, fetch session recordings from PostHog using these details: | |
| 122 | + - Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets | |
| 123 | + - API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20 | |
| 124 | + - Include Authorization header: 'Bearer {POSTHOG_API_KEY}' | |
| 125 | + | |
| 126 | +2. Filter the sessions to find problematic ones with either: | |
| 127 | + - console_error_count > 0 (JavaScript errors) | |
| 128 | + - recording_duration > 300 (sessions longer than 5 minutes) | |
| 129 | + | |
| 130 | +3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems. | |
| 131 | + | |
| 132 | +4. Format each issue like this: | |
| 133 | +### 1. **Issue Title Here** | |
| 134 | +**Problem**: One sentence describing the user problem | |
| 135 | +**Technical Causes**: Brief technical explanation | |
| 136 | +**Affected Pages**: List the URLs | |
| 137 | +**Recommended Fix**: | |
| 138 | +- Specific action item 1 | |
| 139 | +- Specific action item 2 | |
| 140 | +**Priority**: **HIGH** or **MEDIUM** or **LOW** | |
| 141 | +**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions') | |
| 142 | + | |
| 143 | +Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data." | |
| 144 | +``` | |
| 145 | + | |
| 146 | +<Info> | |
| 147 | + **What Continue CLI Does:** - Makes authenticated API calls to PostHog using | |
| 148 | + your stored secrets - Fetches and filters session recordings automatically - | |
| 149 | + Analyzes patterns in the data using AI - Generates structured issue | |
| 150 | + descriptions ready for GitHub | |
| 151 | +</Info> | |
| 152 | + | |
| 153 | +<Tip> | |
| 154 | + Save the analysis output to a file by adding `> analysis-results.txt` to the | |
| 155 | + command if you want to review it later. | |
| 156 | +</Tip> | |
| 157 | + | |
| 158 | +## Step 3: Create GitHub Issues Automatically | |
| 159 | + | |
| 160 | +Now use Continue CLI to create GitHub issues from your analysis results: | |
| 161 | + | |
| 162 | +```bash | |
| 163 | +cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API. | |
| 164 | + | |
| 165 | +Use these details from my secrets: | |
| 166 | +- GITHUB_PAT: My GitHub Personal Access Token | |
| 167 | +- Repository: Extract from git remote or ask me to specify | |
| 168 | + | |
| 169 | +For each issue in my analysis: | |
| 170 | +1. Parse the issue title, body content, and priority level | |
| 171 | +2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues | |
| 172 | +3. Use these headers: | |
| 173 | + - Authorization: token {GITHUB_PAT} | |
| 174 | + - Accept: application/vnd.github.v3+json | |
| 175 | + - Content-Type: application/json | |
| 176 | +4. Set labels based on priority: | |
| 177 | + - HIGH: [\"bug\", \"high-priority\", \"user-experience\", \"automated\"] | |
| 178 | + - MEDIUM: [\"enhancement\", \"medium-priority\", \"user-experience\", \"automated\"] | |
| 179 | + - LOW: [\"low-priority\", \"user-experience\", \"automated\"] | |
| 180 | +5. Format the issue title as: \"🔍 UX Issue: {original title}\" | |
| 181 | + | |
| 182 | +Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs. | |
| 183 | +" | |
| 184 | +``` | |
| 185 | + | |
| 186 | +<Warning> | |
| 187 | +**Repository Labels Required**: Make sure your GitHub repository has these labels: | |
| 188 | +- `bug`, `enhancement` | |
| 189 | +- `high-priority`, `medium-priority`, `low-priority` | |
| 190 | +- `user-experience`, `automated` | |
| 191 | + | |
| 192 | +Create missing labels in your repo at: **Settings → Labels → New label** | |
| 193 | + | |
| 194 | +</Warning> | |
| 195 | + | |
| 196 | +<Info> | |
| 197 | + **What Continue CLI Does:** - Parses your analysis results automatically - | |
| 198 | + Makes authenticated GitHub API calls using your stored token - Creates | |
| 199 | + properly formatted issues with appropriate labels - Checks for duplicate | |
| 200 | + issues to avoid spam - Provides confirmation with issue URLs | |
| 201 | +</Info> | |
| 202 | + | |
| 203 | +## Step 4: Set Up Automated GitHub Actions Workflow | |
| 204 | + | |
| 205 | +Create a GitHub Actions workflow that runs your Continue CLI analysis automatically on a schedule. | |
| 206 | + | |
| 207 | +### Add GitHub Secrets | |
| 208 | + | |
| 209 | +First, add these secrets to your GitHub repository: | |
| 210 | + | |
| 211 | +1. Go to **Repository Settings → Secrets and variables → Actions** | |
| 212 | +2. Click **"New repository secret"** and add: | |
| 213 | + - `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev | |
| 214 | + - `POSTHOG_API_KEY`: Your PostHog Personal API Key | |
| 215 | + - `POSTHOG_PROJECT_ID`: Your PostHog Project ID | |
| 216 | + - `POSTHOG_HOST`: `https://us.posthog.com` (or your custom PostHog host) | |
| 217 | + - `GITHUB_PAT`: Your GitHub Personal Access Token | |
| 218 | + | |
| 219 | +### Create GitHub Actions Workflow | |
| 220 | + | |
| 221 | +Create `.github/workflows/posthog-analysis.yml` in your repository: | |
| 222 | + | |
| 223 | +```yaml | |
| 224 | +name: PostHog Session Analysis with Continue CLI | |
| 225 | + | |
| 226 | +on: | |
| 227 | + schedule: | |
| 228 | + - cron: "0 6 * * *" # Run at 6 AM UTC daily | |
| 229 | + workflow_dispatch: # Allow manual triggering | |
| 230 | + | |
| 231 | +jobs: | |
| 232 | + analyze: | |
| 233 | + runs-on: ubuntu-latest | |
| 234 | + | |
| 235 | + permissions: | |
| 236 | + contents: read | |
| 237 | + issues: write | |
| 238 | + | |
| 239 | + steps: | |
| 240 | + - uses: actions/checkout@v4 | |
| 241 | + | |
| 242 | + - name: Set up Node.js | |
| 243 | + uses: actions/setup-node@v4 | |
| 244 | + with: | |
| 245 | + node-version: "18" | |
| 246 | + | |
| 247 | + - name: Install Continue CLI | |
| 248 | + run: | | |
| 249 | + npm install -g @continuedev/cli | |
| 250 | + echo "✅ Continue CLI installed" | |
| 251 | + cn --version | |
| 252 | + | |
| 253 | + - name: Set up environment variables | |
| 254 | + run: | | |
| 255 | + echo "POSTHOG_API_KEY=${{ secrets.POSTHOG_API_KEY }}" >> $GITHUB_ENV | |
| 256 | + echo "POSTHOG_PROJECT_ID=${{ secrets.POSTHOG_PROJECT_ID }}" >> $GITHUB_ENV | |
| 257 | + echo "POSTHOG_HOST=${{ secrets.POSTHOG_HOST || 'https://us.posthog.com' }}" >> $GITHUB_ENV | |
| 258 | + echo "GITHUB_PAT=${{ secrets.GITHUB_PAT }}" >> $GITHUB_ENV | |
| 259 | + echo "GITHUB_OWNER=${{ github.repository_owner }}" >> $GITHUB_ENV | |
| 260 | + echo "GITHUB_REPO=$(echo ${{ github.repository }} | cut -d'/' -f2)" >> $GITHUB_ENV | |
| 261 | + | |
| 262 | + - name: Authenticate with Continue CLI | |
| 263 | + run: | | |
| 264 | + # Set Continue API key | |
| 265 | + export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}" | |
| 266 | + # Login to Continue CLI | |
| 267 | + if ! cn auth login --api-key "$CONTINUE_API_KEY"; then | |
| 268 | + echo "❌ Failed to authenticate with Continue CLI" | |
| 269 | + exit 1 | |
| 270 | + fi | |
| 271 | + echo "✅ Continue CLI authenticated" | |
| 272 | + | |
| 273 | + - name: Run PostHog Session Analysis | |
| 274 | + run: | | |
| 275 | + echo "🎬 Starting PostHog session analysis..." | |
| 276 | + # Create the analysis prompt | |
| 277 | + cat > analysis_prompt.txt << 'EOF' | |
| 278 | + I need you to help me analyze PostHog session recordings to identify UX issues. Please: | |
| 279 | + | |
| 280 | + 1. First, fetch session recordings from PostHog using these details: | |
| 281 | + - Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from environment variables | |
| 282 | + - API endpoint: $POSTHOG_HOST/api/projects/$POSTHOG_PROJECT_ID/session_recordings/?limit=20 | |
| 283 | + - Include Authorization header: "Bearer $POSTHOG_API_KEY" | |
| 284 | + | |
| 285 | + 2. Filter the sessions to find problematic ones with either: | |
| 286 | + - console_error_count > 0 (JavaScript errors) | |
| 287 | + - recording_duration > 300 (sessions longer than 5 minutes) | |
| 288 | + | |
| 289 | + 3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems. | |
| 290 | + | |
| 291 | + 4. Format each issue like this: | |
| 292 | + ### 1. **Issue Title Here** | |
| 293 | + **Problem**: One sentence describing the user problem | |
| 294 | + **Technical Causes**: Brief technical explanation | |
| 295 | + **Affected Pages**: List the URLs | |
| 296 | + **Recommended Fix**: | |
| 297 | + - Specific action item 1 | |
| 298 | + - Specific action item 2 | |
| 299 | + **Priority**: **HIGH** or **MEDIUM** or **LOW** | |
| 300 | + **Impact**: Quantify the impact (e.g., 'Affects 80% of sessions') | |
| 301 | + | |
| 302 | + Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data. | |
| 303 | + | |
| 304 | + Environment context: | |
| 305 | + - POSTHOG_API_KEY: $POSTHOG_API_KEY | |
| 306 | + - POSTHOG_PROJECT_ID: $POSTHOG_PROJECT_ID | |
| 307 | + - POSTHOG_HOST: $POSTHOG_HOST | |
| 308 | + - GitHub Repo: $GITHUB_OWNER/$GITHUB_REPO | |
| 309 | + EOF | |
| 310 | + | |
| 311 | + # Run the analysis | |
| 312 | + cn < analysis_prompt.txt > analysis-results.txt 2>&1 | |
| 313 | + | |
| 314 | + # Check if analysis completed | |
| 315 | + if [ ! -s analysis-results.txt ]; then | |
| 316 | + echo "❌ Analysis failed or produced no output" | |
| 317 | + exit 1 | |
| 318 | + fi | |
| 319 | + | |
| 320 | + echo "✅ Analysis completed" | |
| 321 | + echo "📄 Analysis results preview:" | |
| 322 | + head -20 analysis-results.txt | |
| 323 | + | |
| 324 | + - name: Create GitHub Issues from Analysis | |
| 325 | + run: | | |
| 326 | + echo "📝 Creating GitHub issues from analysis..." | |
| 327 | + # Create the issue creation prompt | |
| 328 | + cat > issue_prompt.txt << 'EOF' | |
| 329 | + I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API. | |
| 330 | + | |
| 331 | + Use these details from environment variables: | |
| 332 | + - GITHUB_PAT: My GitHub Personal Access Token | |
| 333 | + - Repository: $GITHUB_OWNER/$GITHUB_REPO | |
| 334 | + | |
| 335 | + For each issue in my analysis: | |
| 336 | + 1. Parse the issue title, body content, and priority level | |
| 337 | + 2. Create a GitHub issue via API POST to: https://api.github.com/repos/$GITHUB_OWNER/$GITHUB_REPO/issues | |
| 338 | + 3. Use these headers: | |
| 339 | + - Authorization: token $GITHUB_PAT | |
| 340 | + - Accept: application/vnd.github.v3+json | |
| 341 | + - Content-Type: application/json | |
| 342 | + 4. Set labels based on priority: | |
| 343 | + - HIGH: ["bug", "high-priority", "user-experience", "automated"] | |
| 344 | + - MEDIUM: ["enhancement", "medium-priority", "user-experience", "automated"] | |
| 345 | + - LOW: ["low-priority", "user-experience", "automated"] | |
| 346 | + 5. Format the issue title as: "🔍 UX Issue: {original title}" | |
| 347 | + | |
| 348 | + Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs. | |
| 349 | + | |
| 350 | + Here's my analysis to process: | |
| 351 | + EOF | |
| 352 | + | |
| 353 | + # Append the analysis results to the prompt | |
| 354 | + cat analysis-results.txt >> issue_prompt.txt | |
| 355 | + | |
| 356 | + # Run the issue creation | |
| 357 | + cn < issue_prompt.txt > issue-creation-results.txt 2>&1 | |
| 358 | + | |
| 359 | + echo "✅ Issue creation completed" | |
| 360 | + echo "📄 Issue creation results:" | |
| 361 | + cat issue-creation-results.txt | |
| 362 | + | |
| 363 | + - name: Upload Analysis Artifacts | |
| 364 | + uses: actions/upload-artifact@v4 | |
| 365 | + if: always() | |
| 366 | + with: | |
| 367 | + name: analysis-results-${{ github.run_number }} | |
| 368 | + path: | | |
| 369 | + analysis-results.txt | |
| 370 | + issue-creation-results.txt | |
| 371 | + retention-days: 30 | |
| 372 | + | |
| 373 | + - name: Summary | |
| 374 | + run: | | |
| 375 | + echo "✅ PostHog analysis workflow completed!" | |
| 376 | + echo "📊 Check the artifacts for detailed analysis results" | |
| 377 | + echo "🐛 Check your repository issues for newly created UX issues" | |
| 378 | +``` | |
| 379 | + | |
| 380 | +## Step 5: Testing Your Workflow | |
| 381 | + | |
| 382 | +### Test Locally First | |
| 383 | + | |
| 384 | +Before setting up automation, test the workflow locally: | |
| 385 | + | |
| 386 | +**Test 1: Session Analysis** | |
| 387 | + | |
| 388 | +```bash | |
| 389 | +cn -p "[Paste the PostHog analysis prompt from Step 2]" | |
| 390 | +``` | |
| 391 | + | |
| 392 | +Expected: Analysis output with 3 formatted GitHub issues | |
| 393 | + | |
| 394 | +**Test 2: Issue Creation** | |
| 395 | + | |
| 396 | +```bash | |
| 397 | +cn -p "[Paste the GitHub issue creation prompt from Step 3 with your analysis results]" | |
| 398 | +``` | |
| 399 | + | |
| 400 | +Expected: Confirmation of GitHub issues created with URLs | |
| 401 | + | |
| 402 | +### Test the GitHub Actions Workflow | |
| 403 | + | |
| 404 | +1. **Manual Trigger**: Go to **Actions** tab in your repository and manually trigger the workflow | |
| 405 | +2. **Check Artifacts**: Download the analysis results from the workflow run | |
| 406 | +3. **Verify Issues**: Check that GitHub issues were created in your repository | |
| 407 | + | |
| 408 | +<Check> | |
| 409 | + **Success Indicators:** - PostHog API returns session data (not empty) - | |
| 410 | + Continue CLI generates analysis with identified issues - GitHub issues are | |
| 411 | + created with proper labels and formatting - Workflow completes without errors | |
| 412 | +</Check> | |
| 413 | + | |
| 414 | +## Troubleshooting | |
| 415 | + | |
| 416 | +If you encounter issues, use this helpful prompt to diagnose problems: | |
| 417 | + | |
| 418 | +```bash | |
| 419 | +cn -p "Help me set up my environment for PostHog session analysis. Please: | |
| 420 | + | |
| 421 | +1. Check if I have the required secrets configured in Continue CLI: | |
| 422 | + - POSTHOG_API_KEY | |
| 423 | + - POSTHOG_PROJECT_ID | |
| 424 | + - POSTHOG_HOST | |
| 425 | + - GITHUB_PAT | |
| 426 | + | |
| 427 | +2. If any are missing, guide me through: | |
| 428 | + - How to get PostHog Personal API Key from PostHog settings | |
| 429 | + - How to find my PostHog Project ID from the URL | |
| 430 | + - How to create a GitHub Personal Access Token with issues:write permission | |
| 431 | + - How to add these as secrets in Continue CLI | |
| 432 | + | |
| 433 | +3. Help me identify my GitHub repository owner and name by: | |
| 434 | + - Checking git remote origin URL | |
| 435 | + - Or asking me to provide them | |
| 436 | + | |
| 437 | +4. Test the API connections by making a simple API call to both PostHog and GitHub to verify the credentials work. | |
| 438 | + | |
| 439 | +Please walk me through this setup process step by step." | |
| 440 | +``` | |
| 441 | + | |
| 442 | +## What You've Built | |
| 443 | + | |
| 444 | +After completing this guide, you have a complete **Continuous AI system** that: | |
| 445 | + | |
| 446 | +✅ **Monitors user experience** - Automatically fetches and analyzes PostHog session data | |
| 447 | +✅ **Identifies problems intelligently** - Uses AI to spot patterns and technical issues | |
| 448 | +✅ **Creates actionable tasks** - Generates GitHub issues with specific recommendations | |
| 449 | +✅ **Runs autonomously** - Operates daily without manual intervention using GitHub Actions | |
| 450 | +✅ **Scales with your team** - Handles growing amounts of session data automatically | |
| 451 | + | |
| 452 | +<Card title="Continuous AI" icon="rocket"> | |
| 453 | + Your system now operates at **[Level 2 Continuous | |
| 454 | + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - | |
| 455 | + AI handles routine analysis tasks with human oversight through GitHub issue | |
| 456 | + review and prioritization. | |
| 457 | +</Card> | |
| 458 | + | |
| 459 | +## Security Best Practices | |
| 460 | + | |
| 461 | +<Warning> | |
| 462 | + **Protect Your API Keys:** - Store all credentials as GitHub Secrets, never in | |
| 463 | + code - Use Continue CLI's secure secret storage - Limit token scopes to | |
| 464 | + minimum required permissions - Rotate API keys regularly (every 90 days | |
| 465 | + recommended) - Monitor token usage for unusual activity | |
| 466 | +</Warning> | |
| 467 | + | |
| 468 | +## Advanced Prompts | |
| 469 | + | |
| 470 | +Consider enhancing your workflow with these advanced Continue CLI prompts: | |
| 471 | + | |
| 472 | +<CardGroup cols={2}> | |
| 473 | + <Card title="Performance Analysis" icon="chart-line"> | |
| 474 | + "Analyze PostHog performance metrics alongside session recordings to | |
| 475 | + identify slow page loads affecting user experience" | |
| 476 | + </Card> | |
| 477 | + <Card title="Error Correlation" icon="bug"> | |
| 478 | + "Cross-reference JavaScript console errors with user actions to identify the | |
| 479 | + root cause of UX issues" | |
| 480 | + </Card> | |
| 481 | + <Card title="Feature Flag Analysis" icon="flag"> | |
| 482 | + "Analyze how PostHog feature flags impact user behavior in session | |
| 483 | + recordings" | |
| 484 | + </Card> | |
| 485 | + <Card title="Custom Slack Alerts" icon="slack"> | |
| 486 | + "Create Slack alerts when critical UX issues are detected in PostHog | |
| 487 | + sessions" | |
| 488 | + </Card> | |
| 489 | +</CardGroup> | |
| 490 | + | |
| 491 | +## Next Steps | |
| 492 | + | |
| 493 | +1. **Monitor your first issues** - Review the GitHub issues created and implement fixes | |
| 494 | +2. **Measure impact** - Track how resolved issues improve PostHog metrics | |
| 495 | +3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality | |
| 496 | +4. **Scale the system** - Add more data sources or create specialized analysis workflows |
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | description: "Learn how to set up Continue for air-gapped or offline environments using local models, including steps to disable telemetry and configure local model providers" |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). | |
| 7 | -2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry). | |
| 8 | -3. Also in `config.json`, set the default model to a local model. You can available options [here](/customization/models#openai). | |
| 9 | -4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect. | |
| 6 | +1. Download the latest .vsix file from the [GitHub Releases page](https://github.com/continuedev/continue/releases) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). | |
| 7 | +2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](https://docs.continue.dev/reference/telemetry). | |
| 8 | +3. In your `config.yaml` file (or through the Continue UI), set the default model to a local model. You can find available local model options [here](https://docs.continue.dev/reference/model-providers/ollama). | |
| 9 | +4. Restart VS Code to ensure that the changes to `config.yaml` take effect. |
| @@ -0,0 +1,202 @@ | ||
| 1 | +--- | |
| 2 | +title: "How to Understand Agents: Hub vs Local Configuration" | |
| 3 | +description: "Learn how to choose between cloud-managed Hub agents and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow. | |
| 7 | + | |
| 8 | +## What Are the Two Paths to AI Assistance? | |
| 9 | + | |
| 10 | +Continue provides two distinct ways to configure your AI agent: | |
| 11 | + | |
| 12 | +Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly. | |
| 13 | + | |
| 14 | +### How to Access Your Agent Configuration | |
| 15 | + | |
| 16 | +Before we dive into the specifics, let's understand how to access your configuration: | |
| 17 | + | |
| 18 | +1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) | |
| 19 | +2. Click the Agent selector above the main chat input | |
| 20 | +3. Hover over an agent and click: | |
| 21 | + - `new window` icon for Hub agents | |
| 22 | + - `gear` icon for Local agents | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | +## What Are Hub Agents: The Managed Experience | |
| 27 | + | |
| 28 | +Hub Agents represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured agents that sync seamlessly across all your development environments. | |
| 29 | + | |
| 30 | +### Why Should You Choose Hub Agents? | |
| 31 | + | |
| 32 | +**The Power of Simplicity** | |
| 33 | + | |
| 34 | +- **Instant Setup**: Browse the [agent marketplace](https://hub.continue.dev) and add any agent to your account with a single click | |
| 35 | +- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required | |
| 36 | +- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances | |
| 37 | +- **Team Collaboration**: Share custom agents with your team, ensuring everyone uses the same optimized configurations | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | +### How to Get Started with Hub Agents | |
| 42 | + | |
| 43 | +The journey from zero to AI-powered coding takes just four steps: | |
| 44 | + | |
| 45 | +1. **Select Your Agent**: Click the agent selector in your IDE's Continue panel | |
| 46 | +2. **Explore or Create**: Browse community agents or craft your own specialized helper | |
| 47 | +3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed | |
| 48 | +4. **Sync and Code**: Click "Reload config" to pull your latest settings | |
| 49 | + | |
| 50 | +Pro tip: Hub Agents are perfect for teams. Create a custom agent with your team's coding standards, preferred models, and context sources, then share it with a simple link. | |
| 51 | + | |
| 52 | +### How to Manage Hub Agents | |
| 53 | + | |
| 54 | +All Hub Agent management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Agent](/hub/agents/edit-an-agent). | |
| 55 | + | |
| 56 | +## What Are Local Agents: The Power User's Choice | |
| 57 | + | |
| 58 | +Local Agents put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI agent's behavior, with all configuration stored directly on your machine. | |
| 59 | + | |
| 60 | +### Why Should You Choose Local Agents? | |
| 61 | + | |
| 62 | +**Complete Control and Privacy** | |
| 63 | + | |
| 64 | +- **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies | |
| 65 | +- **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments | |
| 66 | +- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models) | |
| 67 | +- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting | |
| 68 | + | |
| 69 | +### How to Set Up Local Agents | |
| 70 | + | |
| 71 | +Local configuration lives in a single YAML file in your home directory: | |
| 72 | + | |
| 73 | +**File Locations:** | |
| 74 | + | |
| 75 | +- macOS/Linux: `~/.continue/config.yaml` | |
| 76 | +- Windows: `%USERPROFILE%\.continue\config.yaml` | |
| 77 | + | |
| 78 | +**Quick Access Method:** | |
| 79 | + | |
| 80 | +1. Open the agents dropdown in your IDE | |
| 81 | +2. Click the gear icon next to "Local Agent" | |
| 82 | +3. The `config.yaml` file opens in your editor | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | +### The Local Agent Experience | |
| 87 | + | |
| 88 | +When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required. | |
| 89 | + | |
| 90 | +The first time you use Continue, it generates a `config.yaml` with sensible defaults. From there, you can customize everything from model selection to context providers, slash commands, and more. | |
| 91 | + | |
| 92 | +For the complete configuration reference, see our [config.yaml documentation](/reference). | |
| 93 | + | |
| 94 | +## How to Make the Right Choice | |
| 95 | + | |
| 96 | +The decision between Hub and Local agents often comes down to your specific needs and constraints. Here's a framework to help you decide: | |
| 97 | + | |
| 98 | +### Choose Hub Agents When You: | |
| 99 | + | |
| 100 | +**Value Convenience Over Control** | |
| 101 | + | |
| 102 | +- Want to start coding with AI assistance in under 60 seconds | |
| 103 | +- Prefer visual interfaces over editing configuration files | |
| 104 | +- Need to switch between multiple machines frequently | |
| 105 | +- Work in a team that needs standardized AI assistance | |
| 106 | + | |
| 107 | +**Need Advanced Collaboration** | |
| 108 | + | |
| 109 | +- Want to share custom agents with teammates | |
| 110 | +- Need centralized API key management | |
| 111 | +- Require quick updates across your entire organization | |
| 112 | + | |
| 113 | +**Are Getting Started** | |
| 114 | + | |
| 115 | +- New to AI-powered development | |
| 116 | +- Want to experiment with different models and configurations | |
| 117 | +- Prefer guided setup experiences | |
| 118 | + | |
| 119 | +### Choose Local Agents When You: | |
| 120 | + | |
| 121 | +**Require Maximum Control** | |
| 122 | + | |
| 123 | +- Need to version control your exact configuration | |
| 124 | +- Want to customize every aspect of the AI behavior | |
| 125 | +- Require reproducible development environments | |
| 126 | + | |
| 127 | +**Have Privacy Requirements** | |
| 128 | + | |
| 129 | +- Work with sensitive code that requires air-gapped environments | |
| 130 | +- Need to ensure all configuration data stays local | |
| 131 | +- Have strict compliance requirements about data storage | |
| 132 | + | |
| 133 | +**Are a Power User** | |
| 134 | + | |
| 135 | +- Comfortable editing YAML/JSON files | |
| 136 | +- Want access to experimental features | |
| 137 | +- Need to integrate with local tools and scripts | |
| 138 | + | |
| 139 | +## How to Use the Hybrid Approach | |
| 140 | + | |
| 141 | +Here's a secret: you don't have to choose just one. Many developers use both approaches: | |
| 142 | + | |
| 143 | +- **Hub Agents** for general development and experimentation | |
| 144 | +- **Local Agents** for production work or client projects with specific requirements | |
| 145 | + | |
| 146 | +You can switch between them seamlessly using the agent selector in your IDE. | |
| 147 | + | |
| 148 | +## Common Patterns and Best Practices | |
| 149 | + | |
| 150 | +### For Hub Agent Users | |
| 151 | + | |
| 152 | +1. **Start with Community Agents**: Before creating your own, explore what others have built | |
| 153 | +2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature | |
| 154 | +3. **Create Specialized Agents**: Make different agents for different contexts (frontend, backend, DevOps) | |
| 155 | +4. **Share Liberally**: If you create something useful, share it with the community | |
| 156 | + | |
| 157 | +### For Local Agent Users | |
| 158 | + | |
| 159 | +1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history | |
| 160 | +2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values | |
| 161 | +3. **Document Your Setup**: Add comments to your config explaining non-obvious choices | |
| 162 | +4. **Keep a Backup**: Before major changes, save a working copy of your configuration | |
| 163 | + | |
| 164 | +## Troubleshooting and Tips | |
| 165 | + | |
| 166 | +### Hub Agent Issues | |
| 167 | + | |
| 168 | +**Changes Not Reflecting?** | |
| 169 | + | |
| 170 | +- Click "Reload config" in your IDE | |
| 171 | +- Check your internet connection | |
| 172 | +- Ensure you're signed in to the correct account | |
| 173 | + | |
| 174 | +**Agent Not Available?** | |
| 175 | + | |
| 176 | +- Verify it's added to your account on the hub | |
| 177 | +- Check if it requires specific API keys | |
| 178 | + | |
| 179 | +### Local Agent Issues | |
| 180 | + | |
| 181 | +**Config Not Loading?** | |
| 182 | + | |
| 183 | +- Verify file location matches your OS | |
| 184 | +- Check YAML syntax (Continue will show errors) | |
| 185 | +- Ensure file permissions allow reading | |
| 186 | + | |
| 187 | +**Autocomplete Not Working?** | |
| 188 | + | |
| 189 | +- Update to the latest Continue version | |
| 190 | +- Check that you're editing the correct file | |
| 191 | + | |
| 192 | +## Next Steps | |
| 193 | + | |
| 194 | +Now that you understand both configuration approaches, you're ready to dive deeper: | |
| 195 | + | |
| 196 | +- **For Hub Users**: [Create Your First Agent](/hub/agents/create-an-agent) | |
| 197 | +- **For Local Users**: [Explore the Config Reference](/reference) | |
| 198 | +- **For Everyone**: [Discover Available Models](/customize/model-providers/overview) | |
| 199 | + | |
| 200 | +Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow. | |
| 201 | + | |
| 202 | +Happy coding with Continue! 🚀 |
| @@ -1,202 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Understand Assistants: Hub vs Local Configuration" | |
| 3 | -description: "Learn how to choose between cloud-managed Hub assistants and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach" | |
| 4 | ---- | |
| 5 | - | |
| 6 | -Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow. | |
| 7 | - | |
| 8 | -## What Are the Two Paths to AI Assistance? | |
| 9 | - | |
| 10 | -Continue provides two distinct ways to configure your AI assistant: | |
| 11 | - | |
| 12 | -Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly. | |
| 13 | - | |
| 14 | -### How to Access Your Assistant Configuration | |
| 15 | - | |
| 16 | -Before we dive into the specifics, let's understand how to access your configuration: | |
| 17 | - | |
| 18 | -1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) | |
| 19 | -2. Click the Assistant selector above the main chat input | |
| 20 | -3. Hover over an assistant and click: | |
| 21 | - - `new window` icon for Hub assistants | |
| 22 | - - `gear` icon for Local assistants | |
| 23 | - | |
| 24 | - | |
| 25 | - | |
| 26 | -## What Are Hub Assistants: The Managed Experience | |
| 27 | - | |
| 28 | -Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments. | |
| 29 | - | |
| 30 | -### Why Should You Choose Hub Assistants? | |
| 31 | - | |
| 32 | -**The Power of Simplicity** | |
| 33 | - | |
| 34 | -- **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click | |
| 35 | -- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required | |
| 36 | -- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances | |
| 37 | -- **Team Collaboration**: Share custom assistants with your team, ensuring everyone uses the same optimized configurations | |
| 38 | - | |
| 39 | - | |
| 40 | - | |
| 41 | -### How to Get Started with Hub Assistants | |
| 42 | - | |
| 43 | -The journey from zero to AI-powered coding takes just four steps: | |
| 44 | - | |
| 45 | -1. **Select Your Assistant**: Click the assistant selector in your IDE's Continue panel | |
| 46 | -2. **Explore or Create**: Browse community assistants or craft your own specialized helper | |
| 47 | -3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed | |
| 48 | -4. **Sync and Code**: Click "Reload config" to pull your latest settings | |
| 49 | - | |
| 50 | -Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link. | |
| 51 | - | |
| 52 | -### How to Manage Hub Assistants | |
| 53 | - | |
| 54 | -All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant). | |
| 55 | - | |
| 56 | -## What Are Local Assistants: The Power User's Choice | |
| 57 | - | |
| 58 | -Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine. | |
| 59 | - | |
| 60 | -### Why Should You Choose Local Assistants? | |
| 61 | - | |
| 62 | -**Complete Control and Privacy** | |
| 63 | - | |
| 64 | -- **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies | |
| 65 | -- **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments | |
| 66 | -- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models) | |
| 67 | -- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting | |
| 68 | - | |
| 69 | -### How to Set Up Local Assistants | |
| 70 | - | |
| 71 | -Local configuration lives in a single YAML file in your home directory: | |
| 72 | - | |
| 73 | -**File Locations:** | |
| 74 | - | |
| 75 | -- macOS/Linux: `~/.continue/config.yaml` | |
| 76 | -- Windows: `%USERPROFILE%\.continue\config.yaml` | |
| 77 | - | |
| 78 | -**Quick Access Method:** | |
| 79 | - | |
| 80 | -1. Open the assistants dropdown in your IDE | |
| 81 | -2. Click the gear icon next to "Local Assistant" | |
| 82 | -3. The `config.yaml` file opens in your editor | |
| 83 | - | |
| 84 | - | |
| 85 | - | |
| 86 | -### The Local Assistant Experience | |
| 87 | - | |
| 88 | -When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required. | |
| 89 | - | |
| 90 | -The first time you use Continue, it generates a `config.yaml` with sensible defaults. From there, you can customize everything from model selection to context providers, slash commands, and more. | |
| 91 | - | |
| 92 | -For the complete configuration reference, see our [config.yaml documentation](/reference). | |
| 93 | - | |
| 94 | -## How to Make the Right Choice | |
| 95 | - | |
| 96 | -The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide: | |
| 97 | - | |
| 98 | -### Choose Hub Assistants When You: | |
| 99 | - | |
| 100 | -**Value Convenience Over Control** | |
| 101 | - | |
| 102 | -- Want to start coding with AI assistance in under 60 seconds | |
| 103 | -- Prefer visual interfaces over editing configuration files | |
| 104 | -- Need to switch between multiple machines frequently | |
| 105 | -- Work in a team that needs standardized AI assistance | |
| 106 | - | |
| 107 | -**Need Advanced Collaboration** | |
| 108 | - | |
| 109 | -- Want to share custom assistants with teammates | |
| 110 | -- Need centralized API key management | |
| 111 | -- Require quick updates across your entire organization | |
| 112 | - | |
| 113 | -**Are Getting Started** | |
| 114 | - | |
| 115 | -- New to AI-powered development | |
| 116 | -- Want to experiment with different models and configurations | |
| 117 | -- Prefer guided setup experiences | |
| 118 | - | |
| 119 | -### Choose Local Assistants When You: | |
| 120 | - | |
| 121 | -**Require Maximum Control** | |
| 122 | - | |
| 123 | -- Need to version control your exact configuration | |
| 124 | -- Want to customize every aspect of the AI behavior | |
| 125 | -- Require reproducible development environments | |
| 126 | - | |
| 127 | -**Have Privacy Requirements** | |
| 128 | - | |
| 129 | -- Work with sensitive code that requires air-gapped environments | |
| 130 | -- Need to ensure all configuration data stays local | |
| 131 | -- Have strict compliance requirements about data storage | |
| 132 | - | |
| 133 | -**Are a Power User** | |
| 134 | - | |
| 135 | -- Comfortable editing YAML/JSON files | |
| 136 | -- Want access to experimental features | |
| 137 | -- Need to integrate with local tools and scripts | |
| 138 | - | |
| 139 | -## How to Use the Hybrid Approach | |
| 140 | - | |
| 141 | -Here's a secret: you don't have to choose just one. Many developers use both approaches: | |
| 142 | - | |
| 143 | -- **Hub Assistants** for general development and experimentation | |
| 144 | -- **Local Assistants** for production work or client projects with specific requirements | |
| 145 | - | |
| 146 | -You can switch between them seamlessly using the assistant selector in your IDE. | |
| 147 | - | |
| 148 | -## Common Patterns and Best Practices | |
| 149 | - | |
| 150 | -### For Hub Assistant Users | |
| 151 | - | |
| 152 | -1. **Start with Community Assistants**: Before creating your own, explore what others have built | |
| 153 | -2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature | |
| 154 | -3. **Create Specialized Assistants**: Make different assistants for different contexts (frontend, backend, DevOps) | |
| 155 | -4. **Share Liberally**: If you create something useful, share it with the community | |
| 156 | - | |
| 157 | -### For Local Assistant Users | |
| 158 | - | |
| 159 | -1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history | |
| 160 | -2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values | |
| 161 | -3. **Document Your Setup**: Add comments to your config explaining non-obvious choices | |
| 162 | -4. **Keep a Backup**: Before major changes, save a working copy of your configuration | |
| 163 | - | |
| 164 | -## Troubleshooting and Tips | |
| 165 | - | |
| 166 | -### Hub Assistant Issues | |
| 167 | - | |
| 168 | -**Changes Not Reflecting?** | |
| 169 | - | |
| 170 | -- Click "Reload config" in your IDE | |
| 171 | -- Check your internet connection | |
| 172 | -- Ensure you're signed in to the correct account | |
| 173 | - | |
| 174 | -**Assistant Not Available?** | |
| 175 | - | |
| 176 | -- Verify it's added to your account on the hub | |
| 177 | -- Check if it requires specific API keys | |
| 178 | - | |
| 179 | -### Local Assistant Issues | |
| 180 | - | |
| 181 | -**Config Not Loading?** | |
| 182 | - | |
| 183 | -- Verify file location matches your OS | |
| 184 | -- Check YAML syntax (Continue will show errors) | |
| 185 | -- Ensure file permissions allow reading | |
| 186 | - | |
| 187 | -**Autocomplete Not Working?** | |
| 188 | - | |
| 189 | -- Update to the latest Continue version | |
| 190 | -- Check that you're editing the correct file | |
| 191 | - | |
| 192 | -## Next Steps | |
| 193 | - | |
| 194 | -Now that you understand both configuration approaches, you're ready to dive deeper: | |
| 195 | - | |
| 196 | -- **For Hub Users**: [Create Your First Assistant](/hub/assistants/create-an-assistant) | |
| 197 | -- **For Local Users**: [Explore the Config Reference](/reference) | |
| 198 | -- **For Everyone**: [Discover Available Models](/customize/model-providers/overview) | |
| 199 | - | |
| 200 | -Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow. | |
| 201 | - | |
| 202 | -Happy coding with Continue! 🚀 |
| @@ -0,0 +1,34 @@ | ||
| 1 | +--- | |
| 2 | +title: "How to Create an AI Agent" | |
| 3 | +description: "Learn how to create custom AI coding agents in Continue Hub by remixing existing agents or building new ones from scratch with reusable blocks and YAML configuration." | |
| 4 | +sidebarTitle: "Create an AI Agent" | |
| 5 | +--- | |
| 6 | + | |
| 7 | +## How to Create an AI Agent from Scratch | |
| 8 | + | |
| 9 | +To create an agent from scratch, select “New agent” in the top bar. | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | +Choose a name, slug, description, and icon for your agent. | |
| 14 | + | |
| 15 | +The easiest way to create an agent is to click "Create agent" with the default configuration and then add / remove blocks using the sidebar. | |
| 16 | + | |
| 17 | +Alternatively, you can edit the agent YAML directly before clicking "Create agent". Refer to examples of agents on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details. | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | +## How to Remix an Agent | |
| 22 | + | |
| 23 | +You can also create an agent by remixing an existing one. This is useful if you want to start with a pre-configured agent and make modifications. | |
| 24 | + | |
| 25 | +By clicking the “remix” button, you’ll be taken to the “Create a remix” page. | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | +Once here, you’ll be able to | |
| 30 | + | |
| 31 | +1. add or remove blocks in YAML configuration | |
| 32 | +2. change the name, description, icon, etc. | |
| 33 | + | |
| 34 | +Clicking “Create agent” will make this agent available for use. |
| @@ -0,0 +1,20 @@ | ||
| 1 | +--- | |
| 2 | +title: "How to Edit an Agent" | |
| 3 | +description: "New versions of an agent can be created and published using the sidebar." | |
| 4 | +--- | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | +First, select an agent from the dropdown at the top. | |
| 9 | + | |
| 10 | +While editing an agent, you can explore the hub and click "Add Block" from a block page to add it to your agent. | |
| 11 | + | |
| 12 | +For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed. | |
| 13 | + | |
| 14 | +To delete a block, click the trash icon. | |
| 15 | + | |
| 16 | +If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block). | |
| 17 | + | |
| 18 | +When you are done editing, click "Publish" to publish a new version of the agent. | |
| 19 | + | |
| 20 | +Click "Open VS Code" or "Open JetBrains" to open your IDE for using the agent. |
| @@ -0,0 +1,8 @@ | ||
| 1 | +--- | |
| 2 | +title: "Introduction to Agents" | |
| 3 | +description: "Custom AI code agents are configurations of building blocks that enable a coding experience tailored to your specific use cases." | |
| 4 | +--- | |
| 5 | + | |
| 6 | +`config.yaml` is a format for defining custom AI code agents. An agent has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an agent. | |
| 7 | + | |
| 8 | +The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom agent experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your agents will automatically be synced with the IDE extensions. |
| @@ -0,0 +1,19 @@ | ||
| 1 | +--- | |
| 2 | +title: "How to Use an Agent" | |
| 3 | +description: "Learn how to add, configure, and use an AI agent in Continue, including setting required inputs and selecting it in your IDE extension." | |
| 4 | +--- | |
| 5 | + | |
| 6 | +## Steps to Use an AI Agent in Continue | |
| 7 | + | |
| 8 | +Once you've found the agent you want to use on Continue Hub: | |
| 9 | + | |
| 10 | +1. Click “Add Agent” on its page | |
| 11 | +2. Add any required inputs (e.g. secrets like API keys) | |
| 12 | +3. Select “Save changes” in agent sidebar on the right hand side | |
| 13 | + | |
| 14 | +After saving, open your IDE extension and: | |
| 15 | + | |
| 16 | +- Select the agent from the **agent dropdown** in the Continue extension. | |
| 17 | +- Begin using it for chat, code generation, or other configured capabilities. | |
| 18 | + | |
| 19 | + |
| @@ -1,34 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Create an AI Assistant" | |
| 3 | -description: "Learn how to create custom AI coding assistants in Continue Hub by remixing existing assistants or building new ones from scratch with reusable blocks and YAML configuration." | |
| 4 | -sidebarTitle: "Create an AI Assistant" | |
| 5 | ---- | |
| 6 | - | |
| 7 | -## How to Create an AI Assistant from Scratch | |
| 8 | - | |
| 9 | -To create an assistant from scratch, select “New assistant” in the top bar. | |
| 10 | - | |
| 11 | - | |
| 12 | - | |
| 13 | -Choose a name, slug, description, and icon for your assistant. | |
| 14 | - | |
| 15 | -The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar. | |
| 16 | - | |
| 17 | -Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details. | |
| 18 | - | |
| 19 | - | |
| 20 | - | |
| 21 | -## How to Remix an Assistant | |
| 22 | - | |
| 23 | -You can also create an assistant by remixing an existing one. This is useful if you want to start with a pre-configured assistant and make modifications. | |
| 24 | - | |
| 25 | -By clicking the “remix” button, you’ll be taken to the “Create a remix” page. | |
| 26 | - | |
| 27 | - | |
| 28 | - | |
| 29 | -Once here, you’ll be able to | |
| 30 | - | |
| 31 | -1. add or remove blocks in YAML configuration | |
| 32 | -2. change the name, description, icon, etc. | |
| 33 | - | |
| 34 | -Clicking “Create assistant” will make this assistant available for use. |
| @@ -1,20 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Edit an Assistant" | |
| 3 | -description: "New versions of an assistant can be created and published using the sidebar." | |
| 4 | ---- | |
| 5 | - | |
| 6 | - | |
| 7 | - | |
| 8 | -First, select an assistant from the dropdown at the top. | |
| 9 | - | |
| 10 | -While editing an assistant, you can explore the hub and click "Add Block" from a block page to add it to your assistant. | |
| 11 | - | |
| 12 | -For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed. | |
| 13 | - | |
| 14 | -To delete a block, click the trash icon. | |
| 15 | - | |
| 16 | -If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block). | |
| 17 | - | |
| 18 | -When you are done editing, click "Publish" to publish a new version of the assistant. | |
| 19 | - | |
| 20 | -Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant. |
| @@ -1,8 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "Introduction to Assistants" | |
| 3 | -description: "Custom AI code assistants are configurations of building blocks that enable a coding experience tailored to your specific use cases." | |
| 4 | ---- | |
| 5 | - | |
| 6 | -`config.yaml` is a format for defining custom AI code assistants. An assistant has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an assistant. | |
| 7 | - | |
| 8 | -The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom assistant experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your assistants will automatically be synced with the IDE extensions. |
| @@ -1,19 +0,0 @@ | ||
| 1 | ---- | |
| 2 | -title: "How to Use an Assistant" | |
| 3 | -description: "Learn how to add, configure, and use an AI assistant in Continue, including setting required inputs and selecting it in your IDE extension." | |
| 4 | ---- | |
| 5 | - | |
| 6 | -## Steps to Use an AI Assistant in Continue | |
| 7 | - | |
| 8 | -Once you've found the assistant you want to use on Continue Hub: | |
| 9 | - | |
| 10 | -1. Click “Add Assistant” on its page | |
| 11 | -2. Add any required inputs (e.g. secrets like API keys) | |
| 12 | -3. Select “Save changes” in assistant sidebar on the right hand side | |
| 13 | - | |
| 14 | -After saving, open your IDE extension and: | |
| 15 | - | |
| 16 | -- Select the assistant from the **assistant dropdown** in the Continue extension. | |
| 17 | -- Begin using it for chat, code generation, or other configured capabilities. | |
| 18 | - | |
| 19 | - |
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | ## Rules |
| 22 | 22 | |
| 23 | -Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. | |
| 23 | +Rules blocks are instructions that your custom AI code agent will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. | |
| 24 | 24 | |
| 25 | 25 | Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. |
| 26 | 26 |
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | |
| 13 | 13 |  |
| 14 | 14 | |
| 15 | -Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an assistant. | |
| 15 | +Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an agent. | |
| 16 | 16 | |
| 17 | 17 | ## How to Create a Block from Scratch |
| 18 | 18 | |
| @@ -26,4 +26,4 @@ | ||
| 26 | 26 | |
| 27 | 27 | ### Block Inputs |
| 28 | 28 | |
| 29 | -Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. | |
| 29 | +Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their agent. |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Introduction" |
| 3 | -description: "Blocks are the components you use to build a custom AI code assistant. These include Models, MCP Servers, Rules, and Prompts." | |
| 3 | +description: "Blocks are the components you use to build a custom AI code agent. These include Models, MCP Servers, Rules, and Prompts." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. | |
| 6 | +Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code agent. |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "How to Use a Block" |
| 3 | -description: "Learn how to use blocks in Continue Hub to enhance your AI code assistant." | |
| 3 | +description: "Learn how to use blocks in Continue Hub to enhance your AI code agent." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | -Blocks are used to build custom AI code assistants in Continue Hub. Learn more: | |
| 6 | +Blocks are used to build custom AI code agents in Continue Hub. Learn more: | |
| 7 | 7 | |
| 8 | -- [Create an assistant](/hub/assistants/create-an-assistant) | |
| 9 | -- [Edit an assistant](/hub/assistants/edit-an-assistant) | |
| 8 | +- [Create an agent](/hub/agents/create-an-agent) | |
| 9 | +- [Edit an agent](/hub/agents/edit-an-agent) | |
| 10 | 10 | |
| 11 | 11 | Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input: |
| 12 | 12 |
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 |  |
| 7 | 7 | |
| 8 | 8 | 1. Choose a name, which will be used as the display name for your organization throughout the hub |
| 9 | -2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs | |
| 9 | +2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and agent slugs | |
| 10 | 10 | 3. Select an icon for your organization using the image uploader |
| 11 | 11 | 4. Finally, add a Biography, which will be displayed on your org Home Page |
| 12 | 12 |
| @@ -1,16 +1,16 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Secret Types" |
| 3 | -description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across assistants and within organizations." | |
| 3 | +description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across agents and within organizations." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | ## User secrets |
| 7 | 7 | |
| 8 | -User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`. | |
| 8 | +User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the agent `config.yaml`. | |
| 9 | 9 | |
| 10 | 10 | This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](/hub/governance/pricing#solo), [Teams](/hub/governance/pricing#teams), and [Enterprise](/hub/governance/pricing#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub. |
| 11 | 11 | |
| 12 | 12 | ## Org secrets |
| 13 | 13 | |
| 14 | -Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys). | |
| 14 | +Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with agents in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys). | |
| 15 | 15 | |
| 16 | 16 | This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](/hub/governance/pricing#teams) and [Enterprise](/hub/governance/pricing#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page. |
| @@ -15,17 +15,17 @@ | ||
| 15 | 15 | |
| 16 | 16 | [Visit the Hub →](https://hub.continue.dev) |
| 17 | 17 | |
| 18 | -## Browse Assistants | |
| 18 | +## Browse Agents | |
| 19 | 19 | |
| 20 | 20 | Explore assistants created by the community for specific use cases and workflows. |
| 21 | 21 | |
| 22 | -[Browse Assistants →](https://hub.continue.dev) | |
| 22 | +[Browse Agents →](https://hub.continue.dev) | |
| 23 | 23 | |
| 24 | -## Using Assistants | |
| 24 | +## Using Agents | |
| 25 | 25 | |
| 26 | 26 | Learn how to discover, install, and use community-created assistants in your projects. |
| 27 | 27 | |
| 28 | -[Learn About Assistants →](/hub/assistants/intro) | |
| 28 | +[Learn About Agents →](/hub/assistants/intro) | |
| 29 | 29 | |
| 30 | 30 | --- |
| 31 | 31 |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "Source Control" |
| 3 | -description: "When managing your custom assistants within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ." | |
| 3 | +description: "When managing your custom agents within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | ## Quickstart |
| @@ -34,11 +34,11 @@ | ||
| 34 | 34 | |
| 35 | 35 | ### 4. Commit and push |
| 36 | 36 | |
| 37 | -Add the [YAML for your assistants and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the assistant/block. | |
| 37 | +Add the [YAML for your agents and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the agent/block. | |
| 38 | 38 | |
| 39 | -- `assistants/public` for public assistants | |
| 40 | -- `assistants/private` for private (visible only within your organization) assistants | |
| 39 | +- `assistants/public` for public agents | |
| 40 | +- `assistants/private` for private (visible only within your organization) agents | |
| 41 | 41 | - `blocks/public` for public blocks |
| 42 | 42 | - `blocks/private` for private blocks |
| 43 | 43 | |
| 44 | -Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s). | |
| 44 | +Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the agents within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s). |
Binary content is not shown. View the file.
Binary content is not shown. View the file.
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
| @@ -1,43 +1,43 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | title: "config.yaml Reference" |
| 3 | -description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding assistants. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration." | |
| 3 | +description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding agents. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration." | |
| 4 | 4 | --- |
| 5 | 5 | |
| 6 | 6 | ## Introduction |
| 7 | 7 | |
| 8 | -Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally | |
| 8 | +Continue hub agents are defined using the `config.yaml` specification. Agents can be loaded from [the Hub](https://hub.continue.dev/explore/agents) or locally | |
| 9 | 9 | |
| 10 | -- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension | |
| 10 | +- [Continue Hub](https://hub.continue.dev/explore/agents) - YAML is stored on the hub and automatically synced to the extension | |
| 11 | 11 | |
| 12 | 12 | - Locally |
| 13 | - - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml` | |
| 14 | - - in your workspace in a `/.continue/assistants` folder, with the same naming convention | |
| 13 | + - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/agents`. The name of the file will be used as the display name of the agent, e.g. `My Agent.yaml` | |
| 14 | + - in your workspace in a `/.continue/agents` folder, with the same naming convention | |
| 15 | 15 | |
| 16 | 16 | <Info> |
| 17 | 17 | Config YAML replaces `config.json`, which is deprecated. View the **[Migration |
| 18 | 18 | Guide](/reference/yaml-migration)**. |
| 19 | 19 | </Info> |
| 20 | 20 | |
| 21 | -An assistant is made up of: | |
| 21 | +An agent is made up of: | |
| 22 | 22 | |
| 23 | -1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant | |
| 24 | -2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. | |
| 23 | +1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the agent | |
| 24 | +2. **Block lists**, which are composable arrays of coding agent building blocks available to the agent, such as models, docs, and context providers. | |
| 25 | 25 | |
| 26 | -A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. | |
| 26 | +A block is a single standalone building block of a coding agents, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as agents (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. | |
| 27 | 27 | |
| 28 | -Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). | |
| 28 | +Examples of blocks and agents can be found on the [Continue Hub](https://hub.continue.dev). | |
| 29 | 29 | |
| 30 | -Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. | |
| 30 | +Agents can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. | |
| 31 | 31 | |
| 32 | 32 | ### Using Blocks |
| 33 | 33 | |
| 34 | -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). | |
| 34 | +Hub blocks and agents are identified with a slug in the format `owner-slug/block-or-agent-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). | |
| 35 | 35 | |
| 36 | -Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. | |
| 36 | +Blocks can be imported into an agent by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. | |
| 37 | 37 | |
| 38 | -For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. | |
| 38 | +For example, the following agent imports an Anthropic model and defines an Ollama DeepSeek one. | |
| 39 | 39 | |
| 40 | -Assistant models section | |
| 40 | +Agent models section | |
| 41 | 41 | |
| 42 | 42 | ```yaml |
| 43 | 43 | name: Team Agent |
| @@ -52,13 +52,13 @@ | ||
| 52 | 52 | |
| 53 | 53 | ### Local Blocks |
| 54 | 54 | |
| 55 | -It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally). | |
| 55 | +It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all agents when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally). | |
| 56 | 56 | |
| 57 | 57 | Place your YAML files in the following folders: |
| 58 | 58 | |
| 59 | -Assistants: | |
| 59 | +Agents: | |
| 60 | 60 | |
| 61 | -- `.continue/assistants` - for assistants | |
| 61 | +- `.continue/agents` - for agents | |
| 62 | 62 | |
| 63 | 63 | Blocks: |
| 64 | 64 | |
| @@ -100,7 +100,7 @@ | ||
| 100 | 100 | Which can then be imported like this: |
| 101 | 101 | |
| 102 | 102 | ```yaml title="config.yaml" |
| 103 | -name: myprofile/custom-assistant | |
| 103 | +name: myprofile/custom-agent | |
| 104 | 104 | version: 1.0.0 |
| 105 | 105 | schema: v1 |
| 106 | 106 | |
| @@ -118,7 +118,7 @@ | ||
| 118 | 118 | Block properties can be also be directly overriden using `override`. For example: |
| 119 | 119 | |
| 120 | 120 | ```yaml title="config.yaml" |
| 121 | -name: myprofile/custom-assistant | |
| 121 | +name: myprofile/custom-agent | |
| 122 | 122 | version: 1.0.0 |
| 123 | 123 | schema: v1 |
| 124 | 124 | |
| @@ -219,7 +219,7 @@ | ||
| 219 | 219 | - `topP`: The cumulative probability for nucleus sampling. |
| 220 | 220 | - `topK`: Maximum number of tokens considered at each step. |
| 221 | 221 | - `stop`: An array of stop tokens that will terminate the completion. |
| 222 | - - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models. | |
| 222 | + - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models. | |
| 223 | 223 | - `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. |
| 224 | 224 | |
| 225 | 225 | - `requestOptions`: HTTP request options specific to the model. |
| @@ -251,6 +251,7 @@ | ||
| 251 | 251 | - `modelTimeout`: Model timeout for autocomplete requests in milliseconds. |
| 252 | 252 | - `maxSuffixPercentage`: Maximum percentage of prompt allocated for suffix. |
| 253 | 253 | - `prefixPercentage`: Percentage of input allocated for prefix. |
| 254 | + - `transform`: If `false`, disables trimming of multiline completions. Defaults to `true`. Useful for models that generate better multiline completions without transformations. | |
| 254 | 255 | - `template`: Custom template for autocomplete using Mustache syntax. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. |
| 255 | 256 | - `onlyMyCode`: Only includes code within the repository for context. |
| 256 | 257 | - `useCache`: If `true`, enables caching for completions. |
| @@ -402,6 +403,7 @@ | ||
| 402 | 403 | - `env`: An optional map of environment variables for the server process. |
| 403 | 404 | - `cwd`: An optional working directory to run the command in. Can be absolute or relative path. |
| 404 | 405 | - `connectionTimeout`: An optional connection timeout number to the server in milliseconds. |
| 406 | +- `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models). | |
| 405 | 407 | |
| 406 | 408 | **Example:** |
| 407 | 409 |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | ### Customization |
| 46 | 46 | |
| 47 | 47 | ``` |
| 48 | -How do I add custom rules to my assistant in Continue? | |
| 48 | +How do I add custom rules to my agent in Continue? | |
| 49 | 49 | ``` |
| 50 | 50 | |
| 51 | 51 | ## Troubleshooting |
| @@ -408,4 +408,4 @@ | ||
| 408 | 408 | </Tab> |
| 409 | 409 | </Tabs> |
| 410 | 410 | |
| 411 | -This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings). | |
| No newline at the end of the file | ||
| 411 | +This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon). | |
| No newline at the end of the file |
| @@ -191,7 +191,7 @@ | ||
| 191 | 191 | - `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). |
| 192 | 192 | - `numGpu`: For Ollama, this parameter overrides the number of gpu layers that will be used to load the model into VRAM. |
| 193 | 193 | - `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. |
| 194 | -- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ models. | |
| 194 | +- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models. | |
| 195 | 195 | - `reasoningBudgetTokens`: Sets budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. |
| 196 | 196 | |
| 197 | 197 | Example |
| @@ -485,8 +485,6 @@ | ||
| 485 | 485 | - `applyCodeBlock`: Model title for applying code blocks. |
| 486 | 486 | - `repoMapFileSelection`: Model title for repo map selections. |
| 487 | 487 | |
| 488 | - | |
| 489 | - | |
| 490 | 488 | - `modelContextProtocolServers`: See [Model Context Protocol](/customize/deep-dives/mcp) |
| 491 | 489 | |
| 492 | 490 | Example |
| @@ -540,5 +538,3 @@ | ||
| 540 | 538 | - `codeWrap` |
| 541 | 539 | - `displayRawMarkdown` |
| 542 | 540 | - `showChatScrollbar` |
| 543 | - | |
| 544 | - |
| @@ -50,8 +50,8 @@ | ||
| 50 | 50 | "[Kimi K2 (1T)](https://hub.continue.dev/openrouter/kimi-k2)", |
| 51 | 51 | "[gpt-oss (120B)](https://hub.continue.dev/openrouter/gpt-oss-120b)", |
| 52 | 52 | "[gpt-oss (20B)](https://hub.continue.dev/ollama/gpt-oss-20b)", |
| 53 | - "GLM 4.5 (355B)", | |
| 54 | - "GLM 4.5 Air (106B)", | |
| 53 | + "[GLM 4.5 (355B)](https://hub.continue.dev/openrouter/glm-4-5)", | |
| 54 | + "[GLM 4.5 Air (106B)](https://hub.continue.dev/openrouter/glm-4-5-air)", | |
| 55 | 55 | ], |
| 56 | 56 | closed: [ |
| 57 | 57 | "[Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus)", |
| @@ -83,7 +83,7 @@ | ||
| 83 | 83 | ], |
| 84 | 84 | closed: [ |
| 85 | 85 | "[Codestral](https://hub.continue.dev/mistral/codestral)", |
| 86 | - "[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)", | |
| 86 | + "[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)", | |
| 87 | 87 | ], |
| 88 | 88 | notes: "Closed models are slightly better than open models", |
| 89 | 89 | }, |
| @@ -117,11 +117,11 @@ | ||
| 117 | 117 | notes: "Open models are beginning to emerge for this model role", |
| 118 | 118 | }, |
| 119 | 119 | next_edit: { |
| 120 | - open: ["N/A"], | |
| 120 | + open: ["[Instinct](https://hub.continue.dev/continuedev/instinct)"], | |
| 121 | 121 | closed: [ |
| 122 | - "[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)", | |
| 122 | + "[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)", | |
| 123 | 123 | ], |
| 124 | - notes: "Closed models are significantly better than open models", | |
| 124 | + notes: "Closed models are better than open models", | |
| 125 | 125 | }, |
| 126 | 126 | }; |
| 127 | 127 |
| @@ -1,215 +0,0 @@ | ||
| 1 | -name: Respond to @continuedev Comments | |
| 2 | - | |
| 3 | -on: | |
| 4 | - issue_comment: | |
| 5 | - types: [created] | |
| 6 | - pull_request_review_comment: | |
| 7 | - types: [created] | |
| 8 | - | |
| 9 | -permissions: | |
| 10 | - contents: write | |
| 11 | - pull-requests: write | |
| 12 | - issues: write | |
| 13 | - | |
| 14 | -jobs: | |
| 15 | - respond-to-comment: | |
| 16 | - # Only run on pull request comments | |
| 17 | - if: github.event_name == 'issue_comment' && github.event.issue.pull_request | |
| 18 | - runs-on: ubuntu-latest | |
| 19 | - | |
| 20 | - steps: | |
| 21 | - - name: Check if comment contains @continuedev | |
| 22 | - id: check-mention | |
| 23 | - run: | | |
| 24 | - if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then | |
| 25 | - echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 26 | - else | |
| 27 | - echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 28 | - fi | |
| 29 | - | |
| 30 | - - name: Checkout PR branch | |
| 31 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 32 | - uses: actions/checkout@v4 | |
| 33 | - with: | |
| 34 | - token: ${{ secrets.GITHUB_TOKEN }} | |
| 35 | - fetch-depth: 0 | |
| 36 | - | |
| 37 | - - name: Get PR information | |
| 38 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 39 | - id: pr-info | |
| 40 | - uses: actions/github-script@v7 | |
| 41 | - with: | |
| 42 | - script: | | |
| 43 | - const { data: pr } = await github.rest.pulls.get({ | |
| 44 | - owner: context.repo.owner, | |
| 45 | - repo: context.repo.repo, | |
| 46 | - pull_number: context.issue.number | |
| 47 | - }); | |
| 48 | - | |
| 49 | - core.setOutput('head_ref', pr.head.ref); | |
| 50 | - core.setOutput('head_sha', pr.head.sha); | |
| 51 | - return pr; | |
| 52 | - | |
| 53 | - - name: Checkout PR branch | |
| 54 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 55 | - run: | | |
| 56 | - git checkout ${{ steps.pr-info.outputs.head_ref }} | |
| 57 | - | |
| 58 | - - name: Setup Node.js | |
| 59 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 60 | - uses: actions/setup-node@v4 | |
| 61 | - with: | |
| 62 | - node-version: "20" | |
| 63 | - | |
| 64 | - - name: Install Continue CLI globally | |
| 65 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 66 | - run: npm i -g @continuedev/cli | |
| 67 | - | |
| 68 | - - name: Start remote session | |
| 69 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 70 | - id: remote-session | |
| 71 | - env: | |
| 72 | - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 73 | - run: | | |
| 74 | - # Create the prompt for remote session | |
| 75 | - PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: | |
| 76 | - | |
| 77 | - ${{ github.event.comment.body }} | |
| 78 | - | |
| 79 | - Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch." | |
| 80 | - | |
| 81 | - # Start remote session and capture JSON output | |
| 82 | - SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }}) | |
| 83 | - echo "Raw session output: $SESSION_OUTPUT" | |
| 84 | - | |
| 85 | - # Extract URL from JSON output | |
| 86 | - SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 87 | - | |
| 88 | - if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 89 | - echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 90 | - exit 1 | |
| 91 | - fi | |
| 92 | - | |
| 93 | - echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 94 | - echo "✅ Started remote session: $SESSION_URL" | |
| 95 | - | |
| 96 | - - name: Comment with session URL | |
| 97 | - if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 98 | - uses: actions/github-script@v7 | |
| 99 | - with: | |
| 100 | - script: | | |
| 101 | - const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: | |
| 102 | - > ${{ github.event.comment.body }}`; | |
| 103 | - | |
| 104 | - await github.rest.issues.createComment({ | |
| 105 | - owner: context.repo.owner, | |
| 106 | - repo: context.repo.repo, | |
| 107 | - issue_number: context.issue.number, | |
| 108 | - body: commentBody | |
| 109 | - }); | |
| 110 | - | |
| 111 | - - name: Log session details | |
| 112 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 113 | - run: | | |
| 114 | - echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}" | |
| 115 | - echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 116 | - echo "Original comment: ${{ github.event.comment.body }}" | |
| 117 | - | |
| 118 | - respond-to-review-comment: | |
| 119 | - # Only run on pull request review comments | |
| 120 | - if: github.event_name == 'pull_request_review_comment' | |
| 121 | - runs-on: ubuntu-latest | |
| 122 | - | |
| 123 | - steps: | |
| 124 | - - name: Check if comment contains @continuedev | |
| 125 | - id: check-mention | |
| 126 | - run: | | |
| 127 | - if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then | |
| 128 | - echo "contains_mention=true" >> $GITHUB_OUTPUT | |
| 129 | - else | |
| 130 | - echo "contains_mention=false" >> $GITHUB_OUTPUT | |
| 131 | - fi | |
| 132 | - | |
| 133 | - - name: Checkout PR branch | |
| 134 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 135 | - uses: actions/checkout@v4 | |
| 136 | - with: | |
| 137 | - token: ${{ secrets.GITHUB_TOKEN }} | |
| 138 | - fetch-depth: 0 | |
| 139 | - ref: ${{ github.event.pull_request.head.ref }} | |
| 140 | - | |
| 141 | - - name: Setup Node.js | |
| 142 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 143 | - uses: actions/setup-node@v4 | |
| 144 | - with: | |
| 145 | - node-version: "20" | |
| 146 | - | |
| 147 | - - name: Install Continue CLI globally | |
| 148 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 149 | - run: npm i -g @continuedev/cli | |
| 150 | - | |
| 151 | - - name: Start remote session | |
| 152 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 153 | - id: remote-session | |
| 154 | - env: | |
| 155 | - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} | |
| 156 | - run: | | |
| 157 | - # Create a temporary file for the prompt to handle special characters and newlines properly | |
| 158 | - cat > /tmp/prompt.txt << 'PROMPT_EOF' | |
| 159 | - Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}: | |
| 160 | - | |
| 161 | - **File:** ${{ github.event.comment.path }} | |
| 162 | - **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }} | |
| 163 | - **Comment:** ${{ github.event.comment.body }} | |
| 164 | - | |
| 165 | - Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch. | |
| 166 | - PROMPT_EOF | |
| 167 | - | |
| 168 | - # Debug output | |
| 169 | - echo "PROMPT content:" | |
| 170 | - cat /tmp/prompt.txt | |
| 171 | - | |
| 172 | - # Start remote session and capture JSON output | |
| 173 | - echo "Starting cn with prompt..." | |
| 174 | - SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }}) | |
| 175 | - echo "Raw session output: $SESSION_OUTPUT" | |
| 176 | - | |
| 177 | - # Extract URL from JSON output | |
| 178 | - SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty') | |
| 179 | - | |
| 180 | - if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then | |
| 181 | - echo "Failed to extract session URL from output: $SESSION_OUTPUT" | |
| 182 | - exit 1 | |
| 183 | - fi | |
| 184 | - | |
| 185 | - echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT | |
| 186 | - echo "✅ Started remote session: $SESSION_URL" | |
| 187 | - | |
| 188 | - - name: Comment with session URL | |
| 189 | - if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url | |
| 190 | - uses: actions/github-script@v7 | |
| 191 | - with: | |
| 192 | - script: | | |
| 193 | - const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request: | |
| 194 | - > ${{ github.event.comment.body }}`; | |
| 195 | - | |
| 196 | - const commentParams = { | |
| 197 | - owner: context.repo.owner, | |
| 198 | - repo: context.repo.repo, | |
| 199 | - pull_number: ${{ github.event.pull_request.number }}, | |
| 200 | - body: commentBody, | |
| 201 | - commit_id: '${{ github.event.pull_request.head.sha }}', | |
| 202 | - path: '${{ github.event.comment.path }}', | |
| 203 | - in_reply_to: ${{ github.event.comment.id }} | |
| 204 | - }; | |
| 205 | - | |
| 206 | - await github.rest.pulls.createReviewComment(commentParams); | |
| 207 | - | |
| 208 | - - name: Log session details | |
| 209 | - if: steps.check-mention.outputs.contains_mention == 'true' | |
| 210 | - run: | | |
| 211 | - echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}" | |
| 212 | - echo "Session URL: ${{ steps.remote-session.outputs.session_url }}" | |
| 213 | - echo "File: ${{ github.event.comment.path }}" | |
| 214 | - echo "Line: ${{ github.event.comment.line }}" | |
| 215 | - echo "Original comment: ${{ github.event.comment.body }}" |
| @@ -1,10 +1,14 @@ | ||
| 1 | 1 | #!/usr/bin/env node |
| 2 | 2 | |
| 3 | 3 | import * as esbuild from "esbuild"; |
| 4 | -import { chmodSync, writeFileSync } from "fs"; | |
| 4 | +import { chmodSync, copyFileSync, writeFileSync } from "fs"; | |
| 5 | 5 | import { dirname, resolve } from "path"; |
| 6 | 6 | import { fileURLToPath } from "url"; |
| 7 | 7 | |
| 8 | +// Parse command line arguments | |
| 9 | +const args = process.argv.slice(2); | |
| 10 | +const noMinify = args.includes("--no-minify"); | |
| 11 | + | |
| 8 | 12 | const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 9 | 13 | |
| 10 | 14 | // List of packages to mark as external (ONLY native modules that cannot be bundled) |
| @@ -13,6 +17,7 @@ | ||
| 13 | 17 | const external = [ |
| 14 | 18 | "@sentry/profiling-node", // Contains native profiler bindings (optional) |
| 15 | 19 | "fsevents", // macOS native file watcher (optional dependency) |
| 20 | + "./xhr-sync-worker.js", // JSDOM worker file that needs to be copied separately | |
| 16 | 21 | ]; |
| 17 | 22 | |
| 18 | 23 | console.log("Building CLI with esbuild..."); |
| @@ -38,7 +43,7 @@ | ||
| 38 | 43 | outfile: "dist/index.js", |
| 39 | 44 | external, |
| 40 | 45 | sourcemap: true, |
| 41 | - minify: true, // Minify for smaller bundle size | |
| 46 | + minify: !noMinify, // Use --no-minify flag to control minification | |
| 42 | 47 | metafile: true, |
| 43 | 48 | plugins: [optionalDevtoolsPlugin], |
| 44 | 49 | |
| @@ -68,6 +73,10 @@ | ||
| 68 | 73 | __dirname, |
| 69 | 74 | "../../packages/llm-info/dist/index.js", |
| 70 | 75 | ), |
| 76 | + "@continuedev/terminal-security": resolve( | |
| 77 | + __dirname, | |
| 78 | + "../../packages/terminal-security/dist/index.js", | |
| 79 | + ), | |
| 71 | 80 | }, |
| 72 | 81 | |
| 73 | 82 | // Add banner to create require for CommonJS packages |
| @@ -80,8 +89,24 @@ | ||
| 80 | 89 | // Write metafile for analysis |
| 81 | 90 | writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2)); |
| 82 | 91 | |
| 83 | - // Create wrapper script with shebang | |
| 84 | - writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');"); | |
| 92 | + // Create wrapper script with shebang that explicitly runs the CLI | |
| 93 | + // Note: We must call runCli(); a plain dynamic import will not execute the CLI. | |
| 94 | + writeFileSync( | |
| 95 | + "dist/cn.js", | |
| 96 | + "#!/usr/bin/env node\nimport { runCli } from './index.js';\nawait runCli();\n", | |
| 97 | + ); | |
| 98 | + // Copy worker files needed by JSDOM | |
| 99 | + const workerSource = resolve( | |
| 100 | + __dirname, | |
| 101 | + "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js", | |
| 102 | + ); | |
| 103 | + const workerDest = resolve(__dirname, "dist/xhr-sync-worker.js"); | |
| 104 | + try { | |
| 105 | + copyFileSync(workerSource, workerDest); | |
| 106 | + console.log("✓ Copied xhr-sync-worker.js"); | |
| 107 | + } catch (error) { | |
| 108 | + console.warn("Warning: Could not copy xhr-sync-worker.js:", error.message); | |
| 109 | + } | |
| 85 | 110 | |
| 86 | 111 | // Make the wrapper script executable |
| 87 | 112 | chmodSync("dist/cn.js", 0o755); |
| @@ -0,0 +1,55 @@ | ||
| 1 | +# Storage Sync Flow for `cn serve` | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +The `--id <storageId>` flag enables the `cn serve` command to periodically persist session state to an external Continue-managed storage bucket. On startup, the CLI exchanges the provided `storageId` for two pre-signed S3 URLs - one for `session.json` and one for `diff.txt` - and then pushes fresh copies of those files every 30 seconds. | |
| 6 | + | |
| 7 | +This document captures the responsibilities for both the CLI and backend components so we can iterate on the feature together. | |
| 8 | + | |
| 9 | +## CLI Responsibilities | |
| 10 | + | |
| 11 | +- **Flag plumbing**: When `cn serve` is invoked with `--id <storageId>`, the CLI treats that value as an opaque identifier. | |
| 12 | +- **API key auth**: The CLI attaches the user-level Continue API key (same mechanism we already use for other authenticated requests) to backend calls. | |
| 13 | +- **Presign handshake**: | |
| 14 | + 1. On startup, issue `POST https://api.continue.dev/agents/storage/presigned-url` with JSON payload `{ "storageId": "<storageId>" }`. | |
| 15 | + 2. Expect a response payload containing two pre-signed `PUT` URLs and their target object keys: | |
| 16 | + ```json | |
| 17 | + { | |
| 18 | + "session": { | |
| 19 | + "key": "sessions/<sessionId>/session.json", | |
| 20 | + "putUrl": "https://<s3-host>/..." | |
| 21 | + }, | |
| 22 | + "diff": { | |
| 23 | + "key": "sessions/<sessionId>/diff.txt", | |
| 24 | + "putUrl": "https://<s3-host>/..." | |
| 25 | + } | |
| 26 | + } | |
| 27 | + ``` | |
| 28 | + 3. If the call fails, log and continue without remote storage (no retries yet). | |
| 29 | +- **Periodic uploads**: | |
| 30 | + - Every 30 seconds (configurable later), serialize the in-memory session to `session.json` and fetch the `/diff` payload to produce `diff.txt`. | |
| 31 | + - Upload both artifacts using their respective `PUT` URLs. For now we overwrite the same objects each cycle. | |
| 32 | + - Errors should be logged but non-fatal; the server keeps running. | |
| 33 | + - If the repo check fails (no git repo or missing `main`), `diff.txt` uploads an empty string and we log the condition once for debugging. | |
| 34 | + | |
| 35 | +## Backend Responsibilities | |
| 36 | + | |
| 37 | +- **Endpoint surface**: `POST /agents/storage/presigned-url` accepts a JSON body `{ "storageId": string }`. | |
| 38 | +- **Authentication**: Leverage the caller's Continue API key (the request arrives with the standard `Authorization: Bearer <apiKey>` header). Apply normal auth/tenant validation so users can only request URLs tied to their account/org. | |
| 39 | +- **URL issuance**: | |
| 40 | + - Resolve `storageId` into the desired S3 prefix (e.g., `sessions/<org>/<storageId>/`). | |
| 41 | + - Generate two short-lived pre-signed `PUT` URLs: one for `session.json`, one for `diff.txt`. | |
| 42 | + - Return both URLs and their keys in the response payload described above. | |
| 43 | +- **Expiration**: The initial implementation can hand out URLs with a generous TTL (e.g., 60 minutes). Later we will add CLI-side refresh logic before expiry. | |
| 44 | + | |
| 45 | +## Open Questions & Future Enhancements | |
| 46 | + | |
| 47 | +- **URL refresh**: When the presigned URLs expire we currently have no refresh cycle. We'd need either a renewal endpoint or to re-call the existing endpoint on failure. | |
| 48 | +- **Upload cadence**: The 30-second interval is hard-coded for now. Consider making it configurable in both CLI and backend policies. | |
| 49 | +- **Error telemetry**: Decide if repeated upload failures should trip analytics or circuit breakers. | |
| 50 | +- **Diff source**: `diff.txt` currently mirrors the `/diff` endpoint response. Confirm backend expectations for format and size limits. | |
| 51 | +- **Security**: We might want to sign responses or enforce stricter scope on `storageId` mapping (e.g., require both org + storageId and validate ownership). | |
| 52 | + | |
| 53 | +--- | |
| 54 | + | |
| 55 | +This document should evolve alongside implementation details; update it whenever the API contract or client behavior changes. |
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | "test:e2e": "vitest run --config vitest.e2e.config.ts", |
| 16 | 16 | "test:smoke": "node smoke-test.mjs", |
| 17 | 17 | "build:tsc": "tsc -p tsconfig.build.json", |
| 18 | - "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", | |
| 18 | + "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", | |
| 19 | 19 | "build:validate": "node validate-aliases.mjs", |
| 20 | 20 | "build:bundle": "node build.mjs", |
| 21 | 21 | "build": "npm run build:validate && npm run build:bundle", |
| @@ -37,19 +37,22 @@ | ||
| 37 | 37 | "license": "Apache-2.0", |
| 38 | 38 | "repository": { |
| 39 | 39 | "type": "git", |
| 40 | - "url": "https://github.com/continuedev/cli.git" | |
| 40 | + "url": "https://github.com/continuedev/continue.git" | |
| 41 | 41 | }, |
| 42 | 42 | "bugs": { |
| 43 | 43 | "url": "https://github.com/continuedev/continue/issues" |
| 44 | 44 | }, |
| 45 | 45 | "homepage": "https://continue.dev", |
| 46 | 46 | "dependencies": { |
| 47 | - "@sentry/profiling-node": "^9.43.0" | |
| 47 | + "@sentry/profiling-node": "^9.43.0", | |
| 48 | + "fdir": "^6.4.2", | |
| 49 | + "fzf": "^0.5.2" | |
| 48 | 50 | }, |
| 49 | 51 | "devDependencies": { |
| 50 | 52 | "@continuedev/config-yaml": "file:../../packages/config-yaml", |
| 51 | 53 | "@continuedev/openai-adapters": "file:../../packages/openai-adapters", |
| 52 | 54 | "@continuedev/sdk": "^0.0.13", |
| 55 | + "@continuedev/terminal-security": "file:../../packages/terminal-security", | |
| 53 | 56 | "@modelcontextprotocol/sdk": "^1.17.2", |
| 54 | 57 | "@opentelemetry/api": "^1.9.0", |
| 55 | 58 | "@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0", |
| @@ -59,79 +62,87 @@ | ||
| 59 | 62 | "@opentelemetry/resources": "^2.0.1", |
| 60 | 63 | "@opentelemetry/sdk-node": "^0.203.0", |
| 61 | 64 | "@opentelemetry/semantic-conventions": "^1.36.0", |
| 62 | - "@sentry/node": "^9.43.0", | |
| 63 | - "@types/express": "^5.0.3", | |
| 64 | - "@types/react": "^19.1.8", | |
| 65 | - "@types/turndown": "^5.0.5", | |
| 66 | - "@workos-inc/node": "^7.45.0", | |
| 67 | - "chalk": "^5.4.1", | |
| 68 | - "commander": "^14.0.0", | |
| 69 | - "core": "file:../../core", | |
| 70 | - "date-fns": "^4.1.0", | |
| 71 | - "diff": "^7.0.0", | |
| 72 | - "dotenv": "^16.5.0", | |
| 73 | - "express": "^5.1.0", | |
| 74 | - "glob": "^11.0.3", | |
| 75 | - "gpt-tokenizer": "^3.0.1", | |
| 76 | - "gradient-string": "^3.0.0", | |
| 77 | - "ignore": "^7.0.5", | |
| 78 | - "ignore-walk": "^7.0.0", | |
| 79 | - "ink": "^6.1.0", | |
| 80 | - "jszip": "^3.10.1", | |
| 81 | - "lowlight": "^3.3.0", | |
| 82 | - "minimatch": "^10.0.3", | |
| 83 | - "node-fetch": "^3.3.2", | |
| 84 | - "node-machine-id": "^1.1.12", | |
| 85 | - "open": "^10.1.0", | |
| 86 | - "posthog-node": "^5.6.0", | |
| 87 | - "react": "^19.1.0", | |
| 88 | - "readline-sync": "^1.4.10", | |
| 89 | - "shell-quote": "^1.8.3", | |
| 90 | - "swr": "^2.3.4", | |
| 91 | - "turndown": "^7.2.0", | |
| 92 | - "typescript": "^5.8.3", | |
| 93 | - "uuid": "^9.0.1", | |
| 94 | - "winston": "^3.17.0", | |
| 95 | - "yaml": "^2.8.0", | |
| 96 | 65 | "@semantic-release/changelog": "^6.0.3", |
| 97 | 66 | "@semantic-release/git": "^10.0.1", |
| 98 | 67 | "@semantic-release/github": "^11.0.3", |
| 99 | 68 | "@semantic-release/npm": "^12.0.2", |
| 69 | + "@sentry/node": "^9.43.0", | |
| 100 | 70 | "@testing-library/react": "^16.3.0", |
| 101 | 71 | "@types/date-fns": "^2.5.3", |
| 102 | 72 | "@types/diff": "^7.0.2", |
| 73 | + "@types/express": "^5.0.3", | |
| 103 | 74 | "@types/glob": "^8.1.0", |
| 104 | 75 | "@types/ignore-walk": "^4.0.3", |
| 105 | 76 | "@types/ink-testing-library": "^1.0.4", |
| 106 | 77 | "@types/jszip": "^3.4.0", |
| 107 | 78 | "@types/nock": "^10.0.3", |
| 108 | - "@types/readline-sync": "^1.4.8", | |
| 79 | + "@types/react": "^19.1.8", | |
| 109 | 80 | "@types/shell-quote": "^1.7.5", |
| 110 | 81 | "@types/supertest": "^6.0.3", |
| 82 | + "@types/turndown": "^5.0.5", | |
| 111 | 83 | "@types/uuid": "^10.0.0", |
| 112 | 84 | "@typescript-eslint/eslint-plugin": "^8.39.0", |
| 113 | 85 | "@typescript-eslint/parser": "^8.39.0", |
| 114 | 86 | "@vitest/ui": "^3.2.4", |
| 87 | + "@workos-inc/node": "^7.45.0", | |
| 88 | + "chalk": "^5.4.1", | |
| 89 | + "commander": "^14.0.0", | |
| 115 | 90 | "conventional-changelog-conventionalcommits": "^9.1.0", |
| 91 | + "core": "file:../../core", | |
| 116 | 92 | "cross-env": "^7.0.3", |
| 93 | + "date-fns": "^4.1.0", | |
| 94 | + "diff": "^7.0.0", | |
| 95 | + "dotenv": "^16.5.0", | |
| 117 | 96 | "esbuild": "^0.25.9", |
| 118 | 97 | "eslint": "^9.32.0", |
| 119 | 98 | "eslint-import-resolver-typescript": "^4.4.4", |
| 120 | 99 | "eslint-plugin-import": "^2.32.0", |
| 121 | 100 | "eslint-plugin-unused-imports": "^4.1.4", |
| 122 | 101 | "execa": "^9.6.0", |
| 102 | + "clipboardy": "^4.0.0", | |
| 103 | + "express": "^5.1.0", | |
| 104 | + "glob": "^11.0.3", | |
| 105 | + "gpt-tokenizer": "^3.0.1", | |
| 106 | + "gradient-string": "^3.0.0", | |
| 123 | 107 | "happy-dom": "^18.0.1", |
| 108 | + "ignore": "^7.0.5", | |
| 109 | + "ignore-walk": "^7.0.0", | |
| 110 | + "ink": "^6.1.0", | |
| 124 | 111 | "ink-testing-library": "^4.0.0", |
| 125 | 112 | "jsdom": "^26.1.0", |
| 113 | + "jszip": "^3.10.1", | |
| 114 | + "lowlight": "^3.3.0", | |
| 115 | + "minimatch": "^10.0.3", | |
| 126 | 116 | "nock": "^14.0.5", |
| 117 | + "node-fetch": "^3.3.2", | |
| 118 | + "node-machine-id": "^1.1.12", | |
| 119 | + "open": "^10.1.0", | |
| 120 | + "posthog-node": "^5.6.0", | |
| 127 | 121 | "prettier": "^3.6.2", |
| 122 | + "prettier-plugin-tailwindcss": "^0.6.14", | |
| 123 | + "react": "^19.1.0", | |
| 128 | 124 | "semantic-release": "^24.2.7", |
| 125 | + "shell-quote": "^1.8.3", | |
| 129 | 126 | "supertest": "^7.1.3", |
| 127 | + "swr": "^2.3.4", | |
| 130 | 128 | "ts-node": "^10.9.2", |
| 131 | 129 | "tsx": "^4.20.3", |
| 132 | - "vitest": "^3.2.4" | |
| 130 | + "turndown": "^7.2.0", | |
| 131 | + "typescript": "^5.8.3", | |
| 132 | + "uuid": "^9.0.1", | |
| 133 | + "vitest": "^3.2.4", | |
| 134 | + "winston": "^3.17.0", | |
| 135 | + "yaml": "^2.8.0" | |
| 133 | 136 | }, |
| 134 | 137 | "engine": { |
| 135 | 138 | "node": ">=18" |
| 139 | + }, | |
| 140 | + "optionalDependencies": { | |
| 141 | + "@img/sharp-darwin-arm64": "^0.33.5", | |
| 142 | + "@img/sharp-darwin-x64": "^0.33.5", | |
| 143 | + "@img/sharp-linux-arm": "^0.33.5", | |
| 144 | + "@img/sharp-linux-arm64": "^0.33.5", | |
| 145 | + "@img/sharp-linux-x64": "^0.33.5", | |
| 146 | + "@img/sharp-win32-x64": "^0.33.5" | |
| 136 | 147 | } |
| 137 | 148 | } |
| @@ -0,0 +1,32 @@ | ||
| 1 | +# Ctrl+C Exit Behavior | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +Ctrl+C operates on two levels: | |
| 6 | + | |
| 7 | +1. **Menus/Selectors**: Immediate cancellation and return to previous state | |
| 8 | +2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second | |
| 9 | + | |
| 10 | +## Two-Stage Exit (Main Application) | |
| 11 | + | |
| 12 | +### First Ctrl+C | |
| 13 | + | |
| 14 | +- Shows temporary status message "ctrl+c to exit" in bottom-left status bar | |
| 15 | +- Message automatically disappears after 1 second | |
| 16 | +- Clears any text in the input field (if focused) | |
| 17 | +- Does **not** exit the application | |
| 18 | + | |
| 19 | +### Second Ctrl+C (within 1 second) | |
| 20 | + | |
| 21 | +- Exits the application immediately | |
| 22 | +- Performs graceful shutdown | |
| 23 | + | |
| 24 | +### Second Ctrl+C (after 1 second) | |
| 25 | + | |
| 26 | +- Treated as a new "first Ctrl+C" | |
| 27 | +- Shows exit message again | |
| 28 | +- User must press Ctrl+C twice within 1 second window to actually exit | |
| 29 | + | |
| 30 | +## Menu/Selector Cancellation | |
| 31 | + | |
| 32 | +Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors. |
| @@ -51,7 +51,7 @@ | ||
| 51 | 51 | |
| 52 | 52 | ## Core Metrics |
| 53 | 53 | |
| 54 | -### ✅ `continue.cli.session.count` | |
| 54 | +### ✅ `continue_cli_session_count` | |
| 55 | 55 | |
| 56 | 56 | **Type:** Counter |
| 57 | 57 | **Unit:** `count` |
| @@ -65,7 +65,7 @@ | ||
| 65 | 65 | |
| 66 | 66 | --- |
| 67 | 67 | |
| 68 | -### ✅ `continue.cli.lines_of_code.count` | |
| 68 | +### ✅ `continue_cli_lines_of_code_count` | |
| 69 | 69 | |
| 70 | 70 | **Type:** Counter |
| 71 | 71 | **Unit:** `count` |
| @@ -80,7 +80,7 @@ | ||
| 80 | 80 | |
| 81 | 81 | --- |
| 82 | 82 | |
| 83 | -### ✅ `continue.cli.pull_request.count` | |
| 83 | +### ✅ `continue_cli_pull_request_count` | |
| 84 | 84 | |
| 85 | 85 | **Type:** Counter |
| 86 | 86 | **Unit:** `count` |
| @@ -94,7 +94,7 @@ | ||
| 94 | 94 | |
| 95 | 95 | --- |
| 96 | 96 | |
| 97 | -### ✅ `continue.cli.commit.count` | |
| 97 | +### ✅ `continue_cli_commit_count` | |
| 98 | 98 | |
| 99 | 99 | **Type:** Counter |
| 100 | 100 | **Unit:** `count` |
| @@ -108,7 +108,7 @@ | ||
| 108 | 108 | |
| 109 | 109 | --- |
| 110 | 110 | |
| 111 | -### ✅ `continue.cli.cost.usage` | |
| 111 | +### ✅ `continue_cli_cost_usage` | |
| 112 | 112 | |
| 113 | 113 | **Type:** Counter |
| 114 | 114 | **Unit:** `USD` |
| @@ -123,7 +123,7 @@ | ||
| 123 | 123 | |
| 124 | 124 | --- |
| 125 | 125 | |
| 126 | -### ✅ `continue.cli.token.usage` | |
| 126 | +### ✅ `continue_cli_token_usage` | |
| 127 | 127 | |
| 128 | 128 | **Type:** Counter |
| 129 | 129 | **Unit:** `tokens` |
| @@ -139,7 +139,7 @@ | ||
| 139 | 139 | |
| 140 | 140 | --- |
| 141 | 141 | |
| 142 | -### ❌ `continue.cli.code_edit_tool.decision` | |
| 142 | +### ❌ `continue_cli_code_edit_tool_decision` | |
| 143 | 143 | |
| 144 | 144 | **Type:** Counter |
| 145 | 145 | **Unit:** `count` |
| @@ -156,7 +156,7 @@ | ||
| 156 | 156 | |
| 157 | 157 | --- |
| 158 | 158 | |
| 159 | -### ✅ `continue.cli.active_time.total` | |
| 159 | +### ✅ `continue_cli_active_time_total` | |
| 160 | 160 | |
| 161 | 161 | **Type:** Counter |
| 162 | 162 | **Unit:** `s` |
| @@ -172,7 +172,7 @@ | ||
| 172 | 172 | |
| 173 | 173 | ### ✅ User Prompt Event |
| 174 | 174 | |
| 175 | -**Event Name:** `continue.cli.user_prompt` | |
| 175 | +**Event Name:** `continue_cli_user_prompt` | |
| 176 | 176 | |
| 177 | 177 | **Attributes:** |
| 178 | 178 | |
| @@ -188,7 +188,7 @@ | ||
| 188 | 188 | |
| 189 | 189 | ### ✅ Tool Result Event |
| 190 | 190 | |
| 191 | -**Event Name:** `continue.cli.tool_result` | |
| 191 | +**Event Name:** `continue_cli_tool_result` | |
| 192 | 192 | |
| 193 | 193 | **Attributes:** |
| 194 | 194 | |
| @@ -209,7 +209,7 @@ | ||
| 209 | 209 | |
| 210 | 210 | ### ✅ API Request Event |
| 211 | 211 | |
| 212 | -**Event Name:** `continue.cli.api_request` | |
| 212 | +**Event Name:** `continue_cli_api_request` | |
| 213 | 213 | |
| 214 | 214 | **Attributes:** |
| 215 | 215 | |
| @@ -232,7 +232,7 @@ | ||
| 232 | 232 | |
| 233 | 233 | ### Authentication Metrics |
| 234 | 234 | |
| 235 | -#### ✅ `continue.cli.auth.attempts` | |
| 235 | +#### ✅ `continue_cli_auth_attempts` | |
| 236 | 236 | |
| 237 | 237 | **Type:** Counter |
| 238 | 238 | **Unit:** `{attempt}` |
| @@ -248,7 +248,7 @@ | ||
| 248 | 248 | |
| 249 | 249 | ### MCP Integration Metrics |
| 250 | 250 | |
| 251 | -#### ❌ `continue.cli.mcp.connections` | |
| 251 | +#### ❌ `continue_cli_mcp_connections` | |
| 252 | 252 | |
| 253 | 253 | **Type:** Gauge |
| 254 | 254 | **Unit:** `{connection}` |
| @@ -264,7 +264,7 @@ | ||
| 264 | 264 | |
| 265 | 265 | ### Performance Metrics |
| 266 | 266 | |
| 267 | -#### ❌ `continue.cli.startup.time` | |
| 267 | +#### ❌ `continue_cli_startup_time` | |
| 268 | 268 | |
| 269 | 269 | **Type:** Histogram |
| 270 | 270 | **Unit:** `ms` |
| @@ -278,7 +278,7 @@ | ||
| 278 | 278 | |
| 279 | 279 | **Implementation:** Track in `src/index.ts` and `src/commands/chat.ts` |
| 280 | 280 | |
| 281 | -#### ✅ `continue.cli.response_time` | |
| 281 | +#### ✅ `continue_cli_response_time` | |
| 282 | 282 | |
| 283 | 283 | **Type:** Histogram |
| 284 | 284 | **Unit:** `ms` |
| @@ -297,7 +297,7 @@ | ||
| 297 | 297 | |
| 298 | 298 | ### Migration from Claude Code Dashboards |
| 299 | 299 | |
| 300 | -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.*`. | |
| 300 | +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_*`. | |
| 301 | 301 | |
| 302 | 302 | ### Privacy Considerations |
| 303 | 303 | |
| @@ -337,6 +337,6 @@ | ||
| 337 | 337 | |
| 338 | 338 | **Missing implementations:** |
| 339 | 339 | |
| 340 | -- `continue.cli.code_edit_tool.decision` - requires user confirmation UI | |
| 341 | -- `continue.cli.mcp.connections` - needs MCP service monitoring | |
| 342 | -- `continue.cli.startup.time` - needs startup time tracking | |
| 340 | +- `continue_cli_code_edit_tool_decision` - requires user confirmation UI | |
| 341 | +- `continue_cli_mcp_connections` - needs MCP service monitoring | |
| 342 | +- `continue_cli_startup_time` - needs startup time tracking |
| @@ -0,0 +1,138 @@ | ||
| 1 | +shell Mode (CLI TUI) | |
| 2 | + | |
| 3 | +Overview | |
| 4 | + | |
| 5 | +- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). | |
| 6 | +- It is intended for quick terminal command execution without leaving the TUI. | |
| 7 | + | |
| 8 | +Activation | |
| 9 | + | |
| 10 | +- shell mode is activated when the current input (trimmed) starts with ! | |
| 11 | + - Example: "!git status" or " !ls -la" both activate shell mode. | |
| 12 | +- Visual indicator: | |
| 13 | + - Input border color changes to yellow. | |
| 14 | + - The input prompt indicator changes to a yellow "$". | |
| 15 | + - The input placeholder includes "! for shell mode". | |
| 16 | + | |
| 17 | +Deactivation / Exiting shell Mode | |
| 18 | + | |
| 19 | +- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. | |
| 20 | +- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. | |
| 21 | +- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. | |
| 22 | + | |
| 23 | +Interaction with other input helpers | |
| 24 | + | |
| 25 | +- When in shell mode (input starts with !): | |
| 26 | + - "@" file search suggestions are disabled. | |
| 27 | + - "/" slash command UI is disabled. | |
| 28 | +- When in slash command mode (input starts with /): | |
| 29 | + - "@" file search suggestions are disabled. | |
| 30 | + | |
| 31 | +Submission behavior | |
| 32 | + | |
| 33 | +- On submit (Enter) with a shell-mode input: | |
| 34 | + - The leading ! is removed and the remainder is treated as the shell command to run. | |
| 35 | + - 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. | |
| 36 | + - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. | |
| 37 | + | |
| 38 | +Execution semantics | |
| 39 | + | |
| 40 | +- The command is executed in the same way as terminal tool commands, minus permissions | |
| 41 | + | |
| 42 | +Output handling | |
| 43 | + | |
| 44 | +- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. | |
| 45 | +- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. | |
| 46 | +- Output is truncated to the first 5000 lines if exceeded. | |
| 47 | +- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: | |
| 48 | + "[Command timed out after 30 seconds of no output]". | |
| 49 | + | |
| 50 | +Keyboard behaviors (summary) | |
| 51 | + | |
| 52 | +- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately. | |
| 53 | +- Shift+Enter: new line. | |
| 54 | +- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. | |
| 55 | +- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. | |
| 56 | + | |
| 57 | +Scope / Modes | |
| 58 | + | |
| 59 | +- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. | |
| 60 | + | |
| 61 | +Error handling | |
| 62 | + | |
| 63 | +- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). | |
| 64 | + | |
| 65 | +Examples | |
| 66 | + | |
| 67 | +- "!git status" → shows a shell tool call immediately, then populates with the git status output. | |
| 68 | +- "!echo hello" → shows a shell tool call immediately, then output "hello". | |
| 69 | +- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message. | |
| 70 | + Shell Mode (CLI TUI) | |
| 71 | + | |
| 72 | +Overview | |
| 73 | + | |
| 74 | +- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). | |
| 75 | +- It is intended for quick terminal command execution without leaving the TUI. | |
| 76 | + | |
| 77 | +Activation | |
| 78 | + | |
| 79 | +- Shell mode is activated when the current input (trimmed) starts with ! | |
| 80 | + - Example: "!git status" or " !ls -la" both activate Shell mode. | |
| 81 | +- Visual indicator: | |
| 82 | + - Input border color changes to yellow. | |
| 83 | + - The input prompt indicator changes to a yellow "$". | |
| 84 | + - The input placeholder includes "! for shell mode". | |
| 85 | + | |
| 86 | +Deactivation / Exiting Shell Mode | |
| 87 | + | |
| 88 | +- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. | |
| 89 | +- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. | |
| 90 | +- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. | |
| 91 | + | |
| 92 | +Interaction with other input helpers | |
| 93 | + | |
| 94 | +- When in shell mode (input starts with !): | |
| 95 | + - "@" file search suggestions are disabled. | |
| 96 | + - "/" slash command UI is disabled. | |
| 97 | +- When in slash command mode (input starts with /): | |
| 98 | + - "@" file search suggestions are disabled. | |
| 99 | + | |
| 100 | +Submission behavior | |
| 101 | + | |
| 102 | +- On submit (Enter) with a shell-mode input: | |
| 103 | + - The leading ! is removed and the remainder is treated as the shell command to run. | |
| 104 | + - 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. | |
| 105 | + - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. | |
| 106 | + | |
| 107 | +Execution semantics | |
| 108 | + | |
| 109 | +- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same. | |
| 110 | + | |
| 111 | +Output handling | |
| 112 | + | |
| 113 | +- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. | |
| 114 | +- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. | |
| 115 | +- Output is truncated to the first 5000 lines if exceeded. | |
| 116 | +- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: | |
| 117 | + "[Command timed out after 30 seconds of no output]". | |
| 118 | + | |
| 119 | +Keyboard behaviors (summary) | |
| 120 | + | |
| 121 | +- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately. | |
| 122 | +- Shift+Enter: new line. | |
| 123 | +- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. | |
| 124 | +- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. | |
| 125 | + | |
| 126 | +Scope / Modes | |
| 127 | + | |
| 128 | +- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. | |
| 129 | + | |
| 130 | +Error handling | |
| 131 | + | |
| 132 | +- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). | |
| 133 | + | |
| 134 | +Examples | |
| 135 | + | |
| 136 | +- "!git status" → shows a Shell tool call immediately, then populates with the git status output. | |
| 137 | +- "!echo hello" → shows a Shell tool call immediately, then output "hello". | |
| 138 | +- "!some-unknown-cmd" → shows a Shell tool call immediately, then sets status to error with an error message. |
| @@ -0,0 +1,15 @@ | ||
| 1 | +# Continue CLI Terminal UI spec | |
| 2 | + | |
| 3 | +This spec is incomplete. | |
| 4 | + | |
| 5 | +## Stack | |
| 6 | + | |
| 7 | +The Continue CLI uses Ink as a react TUI library. | |
| 8 | + | |
| 9 | +## cwd/git display | |
| 10 | + | |
| 11 | +The lower left corner of the TUI should display | |
| 12 | + | |
| 13 | +- the current git branch if in a git repo | |
| 14 | +- also the current owner/repo if enough columns are available to display and it's a gh repo | |
| 15 | +- if not in git, the cwd |
| @@ -13,5 +13,4 @@ | ||
| 13 | 13 | ) => [any, any] |
| 14 | 14 | >(); |
| 15 | 15 | export const getModel = vi.fn<(config: any, modelName: string) => any>(); |
| 16 | -export const createLlmApi = | |
| 17 | - vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>(); | |
| 16 | +export const createLlmApi = vi.fn<(model: any, authConfig: any) => any>(); |
| @@ -0,0 +1,74 @@ | ||
| 1 | +import { EventEmitter } from "events"; | |
| 2 | +import { vi } from "vitest"; | |
| 3 | + | |
| 4 | +/** | |
| 5 | + * Mocked base service class for testing | |
| 6 | + */ | |
| 7 | +export class BaseService<TState> extends EventEmitter { | |
| 8 | + protected serviceName: string; | |
| 9 | + protected currentState: TState; | |
| 10 | + private isInitialized: boolean = false; | |
| 11 | + | |
| 12 | + constructor(serviceName: string, initialState: TState) { | |
| 13 | + super(); | |
| 14 | + this.serviceName = serviceName; | |
| 15 | + this.currentState = initialState; | |
| 16 | + } | |
| 17 | + | |
| 18 | + // Mock the abstract method | |
| 19 | + doInitialize = vi.fn<any>(); | |
| 20 | + | |
| 21 | + async initialize(...args: any[]): Promise<TState> { | |
| 22 | + this.emit("initializing"); | |
| 23 | + try { | |
| 24 | + const state = await this.doInitialize(...args); | |
| 25 | + this.currentState = state; | |
| 26 | + this.isInitialized = true; | |
| 27 | + this.emit("initialized", state); | |
| 28 | + return state; | |
| 29 | + } catch (error) { | |
| 30 | + this.emit("error", error); | |
| 31 | + throw error; | |
| 32 | + } | |
| 33 | + } | |
| 34 | + | |
| 35 | + getState(): TState { | |
| 36 | + return { ...this.currentState }; | |
| 37 | + } | |
| 38 | + | |
| 39 | + protected setState(newState: Partial<TState>): void { | |
| 40 | + const previousState = this.currentState; | |
| 41 | + this.currentState = { ...this.currentState, ...newState }; | |
| 42 | + this.emit("stateChanged", this.currentState, previousState); | |
| 43 | + } | |
| 44 | + | |
| 45 | + isReady(): boolean { | |
| 46 | + return this.isInitialized; | |
| 47 | + } | |
| 48 | + | |
| 49 | + async reload(...args: any[]): Promise<TState> { | |
| 50 | + this.isInitialized = false; | |
| 51 | + return this.initialize(...args); | |
| 52 | + } | |
| 53 | + | |
| 54 | + async cleanup(): Promise<void> { | |
| 55 | + this.removeAllListeners(); | |
| 56 | + this.isInitialized = false; | |
| 57 | + } | |
| 58 | +} | |
| 59 | + | |
| 60 | +/** | |
| 61 | + * Interface for services with dependencies | |
| 62 | + */ | |
| 63 | +export interface ServiceWithDependencies { | |
| 64 | + getDependencies(): string[]; | |
| 65 | +} | |
| 66 | + | |
| 67 | +/** | |
| 68 | + * Helper to check if a service has dependencies | |
| 69 | + */ | |
| 70 | +export function hasDependencies( | |
| 71 | + service: any, | |
| 72 | +): service is ServiceWithDependencies { | |
| 73 | + return !!service && typeof service.getDependencies === "function"; | |
| 74 | +} |
| @@ -0,0 +1,12 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | + | |
| 3 | +describe("Process SIGINT handling functions", () => { | |
| 4 | + it("exports the necessary functions for exit message handling", async () => { | |
| 5 | + const indexModule = await import("../index.js"); | |
| 6 | + | |
| 7 | + // Verify the functions exist | |
| 8 | + expect(typeof indexModule.shouldShowExitMessage).toBe("function"); | |
| 9 | + expect(typeof indexModule.setExitMessageCallback).toBe("function"); | |
| 10 | + expect(typeof indexModule.setTUIUnmount).toBe("function"); | |
| 11 | + }); | |
| 12 | +}); |
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | organizationSlug?: string; // Organization slug to use for this session |
| 4 | 4 | prompt?: string; // Optional prompt argument |
| 5 | 5 | resume?: boolean; // Resume from last session |
| 6 | + fork?: string; // Fork from an existing session ID | |
| 6 | 7 | readonly?: boolean; // Start in plan mode (backward compatibility) |
| 7 | 8 | rules?: string[]; // Array of rule specifications |
| 8 | 9 | mcps?: string[]; // Array of MCP server slugs from the hub |
| @@ -71,6 +72,12 @@ | ||
| 71 | 72 | result.readonly = true; |
| 72 | 73 | } |
| 73 | 74 | |
| 75 | + // Parse fork flag | |
| 76 | + const forkValue = extractSingleFlag(args, "--fork"); | |
| 77 | + if (forkValue) { | |
| 78 | + result.fork = forkValue; | |
| 79 | + } | |
| 80 | + | |
| 74 | 81 | // Parse single-value flags |
| 75 | 82 | const formatValue = extractSingleFlag(args, "--format"); |
| 76 | 83 | if (formatValue === "json") { |
| @@ -124,6 +131,7 @@ | ||
| 124 | 131 | "--model", |
| 125 | 132 | "--prompt", |
| 126 | 133 | "--format", |
| 134 | + "--fork", | |
| 127 | 135 | ]; |
| 128 | 136 | const nonFlagArgs = args.filter((arg, index) => { |
| 129 | 137 | if (arg.startsWith("--") || arg === "-p") return false; |
| @@ -0,0 +1,5 @@ | ||
| 1 | +import * as path from "path"; | |
| 2 | + | |
| 3 | +import { env } from "../env.js"; | |
| 4 | + | |
| 5 | +export const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json"); |
| @@ -0,0 +1,233 @@ | ||
| 1 | +import * as fs from "fs"; | |
| 2 | + | |
| 3 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 4 | + | |
| 5 | +import { | |
| 6 | + autoSelectOrganizationAndConfig, | |
| 7 | + createUpdatedAuthConfig, | |
| 8 | +} from "./orgSelection.js"; | |
| 9 | +import type { AuthenticatedConfig } from "./workos.js"; | |
| 10 | + | |
| 11 | +// Mock dependencies | |
| 12 | +vi.mock("fs"); | |
| 13 | +vi.mock("../config.js"); | |
| 14 | +vi.mock("../env.js"); | |
| 15 | +vi.mock("./workos.js"); | |
| 16 | + | |
| 17 | +const mockApiClient = { | |
| 18 | + listOrganizations: vi.fn(), | |
| 19 | + listAssistants: vi.fn(), | |
| 20 | +} as any; // Mock API client for testing | |
| 21 | + | |
| 22 | +describe("orgSelection", () => { | |
| 23 | + const mockConfig: AuthenticatedConfig = { | |
| 24 | + userId: "user123", | |
| 25 | + userEmail: "user@example.com", | |
| 26 | + accessToken: "token123", | |
| 27 | + refreshToken: "refresh123", | |
| 28 | + expiresAt: Date.now() + 3600000, | |
| 29 | + organizationId: undefined, | |
| 30 | + configUri: undefined, | |
| 31 | + modelName: undefined, | |
| 32 | + }; | |
| 33 | + | |
| 34 | + beforeEach(async () => { | |
| 35 | + vi.clearAllMocks(); | |
| 36 | + | |
| 37 | + // Mock modules using vi.mocked | |
| 38 | + const configMod = await import("../config.js"); | |
| 39 | + const envMod = await import("../env.js"); | |
| 40 | + const workosMod = await import("./workos.js"); | |
| 41 | + | |
| 42 | + vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient); | |
| 43 | + vi.mocked(envMod.env).continueHome = "/mock/home"; | |
| 44 | + vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {}); | |
| 45 | + | |
| 46 | + // Default: no local config | |
| 47 | + vi.mocked(fs.existsSync).mockReturnValue(false); | |
| 48 | + }); | |
| 49 | + | |
| 50 | + describe("createUpdatedAuthConfig", () => { | |
| 51 | + it("should update organization ID", () => { | |
| 52 | + const result = createUpdatedAuthConfig(mockConfig, "org123"); | |
| 53 | + expect(result.organizationId).toBe("org123"); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + it("should update organization ID and config URI", () => { | |
| 57 | + const result = createUpdatedAuthConfig( | |
| 58 | + mockConfig, | |
| 59 | + "org123", | |
| 60 | + "slug://owner/assistant", | |
| 61 | + ); | |
| 62 | + expect(result.organizationId).toBe("org123"); | |
| 63 | + expect(result!.configUri).toBe("slug://owner/assistant"); | |
| 64 | + }); | |
| 65 | + | |
| 66 | + it("should set personal organization", () => { | |
| 67 | + const result = createUpdatedAuthConfig(mockConfig, null); | |
| 68 | + expect(result.organizationId).toBe(null); | |
| 69 | + }); | |
| 70 | + }); | |
| 71 | + | |
| 72 | + describe("autoSelectOrganizationAndConfig scenarios", () => { | |
| 73 | + it("Priority 1: Org with assistants → select first assistant", async () => { | |
| 74 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 75 | + organizations: [ | |
| 76 | + { id: "org1", name: "Org 1" }, | |
| 77 | + { id: "org2", name: "Org 2" }, | |
| 78 | + ], | |
| 79 | + }); | |
| 80 | + | |
| 81 | + // Mock API calls in order: org1 assistants, org2 assistants | |
| 82 | + mockApiClient.listAssistants.mockImplementation( | |
| 83 | + ({ organizationId }: { organizationId?: string }) => { | |
| 84 | + if (organizationId === "org1") return Promise.resolve([]); | |
| 85 | + if (organizationId === "org2") | |
| 86 | + return Promise.resolve([ | |
| 87 | + { ownerSlug: "owner", packageSlug: "assistant1" }, | |
| 88 | + ]); | |
| 89 | + return Promise.resolve([]); | |
| 90 | + }, | |
| 91 | + ); | |
| 92 | + | |
| 93 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 94 | + | |
| 95 | + expect(result!.organizationId).toBe("org2"); | |
| 96 | + expect(result!.configUri).toBe("slug://owner/assistant1"); | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("Priority 2: No org assistants → personal assistants exist", async () => { | |
| 100 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 101 | + organizations: [{ id: "org1", name: "Org 1" }], | |
| 102 | + }); | |
| 103 | + | |
| 104 | + mockApiClient.listAssistants.mockImplementation( | |
| 105 | + ({ organizationId }: { organizationId?: string }) => { | |
| 106 | + if (organizationId === "org1") return Promise.resolve([]); | |
| 107 | + if (organizationId === undefined) | |
| 108 | + return Promise.resolve([ | |
| 109 | + { ownerSlug: "personal", packageSlug: "my-assistant" }, | |
| 110 | + ]); | |
| 111 | + return Promise.resolve([]); | |
| 112 | + }, | |
| 113 | + ); | |
| 114 | + | |
| 115 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 116 | + | |
| 117 | + expect(result!.organizationId).toBe(null); // personal org | |
| 118 | + expect(result!.configUri).toBe("slug://personal/my-assistant"); | |
| 119 | + expect(mockApiClient.listAssistants).toHaveBeenCalledWith({ | |
| 120 | + organizationId: undefined, | |
| 121 | + }); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + it("Priority 3: No assistants anywhere → local config.yaml exists", async () => { | |
| 125 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 126 | + organizations: [{ id: "org1", name: "Org 1" }], | |
| 127 | + }); | |
| 128 | + | |
| 129 | + mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere | |
| 130 | + vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists | |
| 131 | + | |
| 132 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 133 | + | |
| 134 | + expect(result!.organizationId).toBe(null); | |
| 135 | + expect(result!.configUri).toContain("config.yaml"); | |
| 136 | + }); | |
| 137 | + | |
| 138 | + it("Priority 4: No assistants, no config.yaml → fallback", async () => { | |
| 139 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 140 | + organizations: [{ id: "org1", name: "Org 1" }], | |
| 141 | + }); | |
| 142 | + | |
| 143 | + mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere | |
| 144 | + vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml | |
| 145 | + | |
| 146 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 147 | + | |
| 148 | + expect(result!.organizationId).toBe(null); | |
| 149 | + expect(result!.configUri).toBeUndefined(); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("Multiple orgs with assistants → pick first one", async () => { | |
| 153 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 154 | + organizations: [ | |
| 155 | + { id: "org1", name: "Org 1" }, | |
| 156 | + { id: "org2", name: "Org 2" }, | |
| 157 | + ], | |
| 158 | + }); | |
| 159 | + | |
| 160 | + mockApiClient.listAssistants.mockImplementation( | |
| 161 | + ({ organizationId }: { organizationId?: string }) => { | |
| 162 | + if (organizationId === "org1") | |
| 163 | + return Promise.resolve([ | |
| 164 | + { ownerSlug: "owner1", packageSlug: "assistant1" }, | |
| 165 | + ]); | |
| 166 | + if (organizationId === "org2") | |
| 167 | + return Promise.resolve([ | |
| 168 | + { ownerSlug: "owner2", packageSlug: "assistant2" }, | |
| 169 | + ]); | |
| 170 | + return Promise.resolve([]); | |
| 171 | + }, | |
| 172 | + ); | |
| 173 | + | |
| 174 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 175 | + | |
| 176 | + expect(result!.organizationId).toBe("org1"); // First org wins | |
| 177 | + expect(result!.configUri).toBe("slug://owner1/assistant1"); | |
| 178 | + }); | |
| 179 | + | |
| 180 | + it("Personal assistants API fails → fallback to config.yaml", async () => { | |
| 181 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 182 | + organizations: [{ id: "org1", name: "Org 1" }], | |
| 183 | + }); | |
| 184 | + | |
| 185 | + mockApiClient.listAssistants | |
| 186 | + .mockResolvedValueOnce([]) // org1: no assistants | |
| 187 | + .mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error | |
| 188 | + | |
| 189 | + vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists | |
| 190 | + | |
| 191 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 192 | + | |
| 193 | + expect(result!.organizationId).toBe(null); | |
| 194 | + expect(result!.configUri).toContain("config.yaml"); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("Empty organizations list → check personal assistants", async () => { | |
| 198 | + mockApiClient.listOrganizations.mockResolvedValue({ | |
| 199 | + organizations: [], // No orgs | |
| 200 | + }); | |
| 201 | + | |
| 202 | + mockApiClient.listAssistants.mockResolvedValue([ | |
| 203 | + { ownerSlug: "personal", packageSlug: "my-assistant" }, | |
| 204 | + ]); | |
| 205 | + | |
| 206 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 207 | + | |
| 208 | + expect(result!.organizationId).toBe(null); | |
| 209 | + expect(result!.configUri).toBe("slug://personal/my-assistant"); | |
| 210 | + }); | |
| 211 | + | |
| 212 | + it("API error → fallback with error message", async () => { | |
| 213 | + mockApiClient.listOrganizations.mockRejectedValue( | |
| 214 | + new Error("Network error"), | |
| 215 | + ); | |
| 216 | + | |
| 217 | + const consoleSpy = vi | |
| 218 | + .spyOn(console, "error") | |
| 219 | + .mockImplementation(() => {}); | |
| 220 | + | |
| 221 | + const result = await autoSelectOrganizationAndConfig(mockConfig); | |
| 222 | + | |
| 223 | + expect(result!.organizationId).toBe(null); | |
| 224 | + expect(result!.configUri).toBeUndefined(); | |
| 225 | + expect(consoleSpy).toHaveBeenCalledWith( | |
| 226 | + expect.stringContaining("Error fetching organizations:"), | |
| 227 | + "Network error", | |
| 228 | + ); | |
| 229 | + | |
| 230 | + consoleSpy.mockRestore(); | |
| 231 | + }); | |
| 232 | + }); | |
| 233 | +}); |
| @@ -0,0 +1,155 @@ | ||
| 1 | +import * as fs from "fs"; | |
| 2 | +import * as path from "path"; | |
| 3 | + | |
| 4 | +import chalk from "chalk"; | |
| 5 | + | |
| 6 | +import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js"; | |
| 7 | +import { saveAuthConfig } from "../auth/workos.js"; | |
| 8 | +import { getApiClient } from "../config.js"; | |
| 9 | +import { env } from "../env.js"; | |
| 10 | + | |
| 11 | +/** | |
| 12 | + * Creates an updated AuthenticatedConfig with a new organization ID and optional config URI | |
| 13 | + */ | |
| 14 | +export function createUpdatedAuthConfig( | |
| 15 | + config: AuthenticatedConfig, | |
| 16 | + organizationId: string | null | undefined, | |
| 17 | + configUri?: string | null, | |
| 18 | +): AuthenticatedConfig { | |
| 19 | + return { | |
| 20 | + userId: config.userId, | |
| 21 | + userEmail: config.userEmail, | |
| 22 | + accessToken: config.accessToken, | |
| 23 | + refreshToken: config.refreshToken, | |
| 24 | + expiresAt: config.expiresAt, | |
| 25 | + organizationId, | |
| 26 | + configUri: configUri ?? config.configUri, | |
| 27 | + modelName: config.modelName, | |
| 28 | + }; | |
| 29 | +} | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * Check if an organization has available assistants | |
| 33 | + */ | |
| 34 | +async function hasOrgAssistants( | |
| 35 | + apiClient: ReturnType<typeof getApiClient>, | |
| 36 | + organizationId: string, | |
| 37 | +): Promise<boolean> { | |
| 38 | + try { | |
| 39 | + const assistants = await apiClient.listAssistants({ organizationId }); | |
| 40 | + return assistants.length > 0; | |
| 41 | + } catch { | |
| 42 | + // If we can't check, assume no assistants | |
| 43 | + return false; | |
| 44 | + } | |
| 45 | +} | |
| 46 | + | |
| 47 | +/** | |
| 48 | + * Get the first available assistant from an organization | |
| 49 | + */ | |
| 50 | +async function getFirstAssistant( | |
| 51 | + apiClient: ReturnType<typeof getApiClient>, | |
| 52 | + organizationId: string, | |
| 53 | +): Promise<string | null> { | |
| 54 | + try { | |
| 55 | + const assistants = await apiClient.listAssistants({ organizationId }); | |
| 56 | + if (assistants.length > 0) { | |
| 57 | + const first = assistants[0]; | |
| 58 | + return `${first.ownerSlug}/${first.packageSlug}`; | |
| 59 | + } | |
| 60 | + return null; | |
| 61 | + } catch { | |
| 62 | + return null; | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +/** | |
| 67 | + * Check if personal local config.yaml exists | |
| 68 | + */ | |
| 69 | +function hasPersonalLocalConfig(): boolean { | |
| 70 | + const defaultConfigPath = path.join(env.continueHome, "config.yaml"); | |
| 71 | + return fs.existsSync(defaultConfigPath); | |
| 72 | +} | |
| 73 | + | |
| 74 | +/** | |
| 75 | + * Automatically select organization and configuration for authenticated config | |
| 76 | + * Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback | |
| 77 | + */ | |
| 78 | +export async function autoSelectOrganizationAndConfig( | |
| 79 | + authenticatedConfig: AuthenticatedConfig, | |
| 80 | +): Promise<AuthConfig> { | |
| 81 | + const apiClient = getApiClient(authenticatedConfig.accessToken); | |
| 82 | + | |
| 83 | + try { | |
| 84 | + const resp = await apiClient.listOrganizations(); | |
| 85 | + const organizations = resp.organizations; | |
| 86 | + | |
| 87 | + // Priority 1: Find any organization that has assistants - use first assistant | |
| 88 | + for (const org of organizations) { | |
| 89 | + const hasAssistants = await hasOrgAssistants(apiClient, org.id); | |
| 90 | + if (hasAssistants) { | |
| 91 | + // Get the first assistant from this org | |
| 92 | + const firstAssistantSlug = await getFirstAssistant(apiClient, org.id); | |
| 93 | + const configUri = firstAssistantSlug | |
| 94 | + ? `slug://${firstAssistantSlug}` | |
| 95 | + : undefined; | |
| 96 | + | |
| 97 | + const updatedConfig = createUpdatedAuthConfig( | |
| 98 | + authenticatedConfig, | |
| 99 | + org.id, | |
| 100 | + configUri, | |
| 101 | + ); | |
| 102 | + saveAuthConfig(updatedConfig); | |
| 103 | + return updatedConfig; | |
| 104 | + } | |
| 105 | + } | |
| 106 | + | |
| 107 | + // Priority 2: Check if personal organization has assistants | |
| 108 | + try { | |
| 109 | + const personalAssistants = await apiClient.listAssistants({ | |
| 110 | + organizationId: undefined, | |
| 111 | + }); | |
| 112 | + if (personalAssistants.length > 0) { | |
| 113 | + const firstAssistant = personalAssistants[0]; | |
| 114 | + const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`; | |
| 115 | + const configUri = `slug://${firstAssistantSlug}`; | |
| 116 | + | |
| 117 | + const updatedConfig = createUpdatedAuthConfig( | |
| 118 | + authenticatedConfig, | |
| 119 | + null, | |
| 120 | + configUri, | |
| 121 | + ); | |
| 122 | + saveAuthConfig(updatedConfig); | |
| 123 | + console.log(chalk.green("✓ Automatically selected personal assistant")); | |
| 124 | + return updatedConfig; | |
| 125 | + } | |
| 126 | + } catch { | |
| 127 | + // If personal assistants can't be fetched, continue to next priority | |
| 128 | + } | |
| 129 | + | |
| 130 | + // Priority 3: If no assistants anywhere, use local config.yaml | |
| 131 | + if (hasPersonalLocalConfig()) { | |
| 132 | + const updatedConfig = createUpdatedAuthConfig( | |
| 133 | + authenticatedConfig, | |
| 134 | + null, | |
| 135 | + `file://${path.join(env.continueHome, "config.yaml")}`, | |
| 136 | + ); | |
| 137 | + saveAuthConfig(updatedConfig); | |
| 138 | + console.log(chalk.green("✓ Using local config.yaml")); | |
| 139 | + return updatedConfig; | |
| 140 | + } | |
| 141 | + | |
| 142 | + // no org assistants or config.yaml | |
| 143 | + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); | |
| 144 | + saveAuthConfig(updatedConfig); | |
| 145 | + return updatedConfig; | |
| 146 | + } catch (error: any) { | |
| 147 | + console.error( | |
| 148 | + chalk.red("Error fetching organizations:"), | |
| 149 | + error.response?.data?.message || error.message || error, | |
| 150 | + ); | |
| 151 | + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); | |
| 152 | + saveAuthConfig(updatedConfig); | |
| 153 | + return updatedConfig; | |
| 154 | + } | |
| 155 | +} |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { getApiClient } from "../config.js"; |
| 4 | 4 | import { safeStderr } from "../init.js"; |
| 5 | +import { gracefulExit } from "../util/exit.js"; | |
| 5 | 6 | |
| 6 | 7 | import type { |
| 7 | 8 | AuthConfig, |
| @@ -15,7 +16,7 @@ | ||
| 15 | 16 | */ |
| 16 | 17 | export function createUpdatedAuthConfig( |
| 17 | 18 | config: AuthenticatedConfig, |
| 18 | - organizationId: string | null, | |
| 19 | + organizationId: string | null | undefined, | |
| 19 | 20 | ): AuthenticatedConfig { |
| 20 | 21 | return { |
| 21 | 22 | userId: config.userId, |
| @@ -76,7 +77,7 @@ | ||
| 76 | 77 | "The --org flag is only supported in headless mode (with -p/--print flag)\n", |
| 77 | 78 | ), |
| 78 | 79 | ); |
| 79 | - process.exit(1); | |
| 80 | + await gracefulExit(1); | |
| 80 | 81 | } |
| 81 | 82 | |
| 82 | 83 | const apiClient = getApiClient(authConfig.accessToken); |
| @@ -107,7 +108,7 @@ | ||
| 107 | 108 | "The --org flag is only supported in headless mode (with -p/--print flag)\n", |
| 108 | 109 | ), |
| 109 | 110 | ); |
| 110 | - process.exit(1); | |
| 111 | + await gracefulExit(1); | |
| 111 | 112 | } |
| 112 | 113 | |
| 113 | 114 | const apiClient = getApiClient(authenticatedConfig.accessToken); |
| @@ -123,43 +124,3 @@ | ||
| 123 | 124 | saveAuthConfig(updatedConfig); |
| 124 | 125 | return updatedConfig; |
| 125 | 126 | } |
| 126 | - | |
| 127 | -/** | |
| 128 | - * Automatically select organization for authenticated config | |
| 129 | - */ | |
| 130 | -export async function autoSelectOrganization( | |
| 131 | - authenticatedConfig: AuthenticatedConfig, | |
| 132 | -): Promise<AuthConfig> { | |
| 133 | - const apiClient = getApiClient(authenticatedConfig.accessToken); | |
| 134 | - | |
| 135 | - try { | |
| 136 | - const resp = await apiClient.listOrganizations(); | |
| 137 | - const organizations = resp.organizations; | |
| 138 | - | |
| 139 | - if (organizations.length === 0) { | |
| 140 | - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); | |
| 141 | - saveAuthConfig(updatedConfig); | |
| 142 | - return updatedConfig; | |
| 143 | - } | |
| 144 | - | |
| 145 | - // Automatically select the first organization if available | |
| 146 | - const selectedOrg = organizations[0]; | |
| 147 | - const selectedOrgId = selectedOrg.id; | |
| 148 | - | |
| 149 | - const updatedConfig = createUpdatedAuthConfig( | |
| 150 | - authenticatedConfig, | |
| 151 | - selectedOrgId, | |
| 152 | - ); | |
| 153 | - saveAuthConfig(updatedConfig); | |
| 154 | - return updatedConfig; | |
| 155 | - } catch (error: any) { | |
| 156 | - console.error( | |
| 157 | - chalk.red("Error fetching organizations:"), | |
| 158 | - error.response?.data?.message || error.message || error, | |
| 159 | - ); | |
| 160 | - console.info(chalk.yellow("Continuing without organization selection.")); | |
| 161 | - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); | |
| 162 | - saveAuthConfig(updatedConfig); | |
| 163 | - return updatedConfig; | |
| 164 | - } | |
| 165 | -} |
| @@ -0,0 +1,58 @@ | ||
| 1 | +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js"; | |
| 4 | + | |
| 5 | +describe("ensureOrganization with API key org scope", () => { | |
| 6 | + const originalEnv = { ...process.env }; | |
| 7 | + const originalFetch = global.fetch; | |
| 8 | + | |
| 9 | + beforeEach(() => { | |
| 10 | + vi.restoreAllMocks(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + afterEach(() => { | |
| 14 | + process.env = { ...originalEnv }; | |
| 15 | + global.fetch = originalFetch as any; | |
| 16 | + }); | |
| 17 | + | |
| 18 | + it("resolves organizationId via auth/scope for API key auth", async () => { | |
| 19 | + const mockFetch = vi.fn().mockResolvedValue({ | |
| 20 | + ok: true, | |
| 21 | + json: async () => ({ organizationId: "org_123" }), | |
| 22 | + }); | |
| 23 | + (global as any).fetch = mockFetch; | |
| 24 | + | |
| 25 | + const envAuthConfig = { | |
| 26 | + accessToken: "sk_test_api_key", | |
| 27 | + organizationId: null as string | null, | |
| 28 | + } as const; | |
| 29 | + | |
| 30 | + const result = await ensureOrganization(envAuthConfig, true); | |
| 31 | + expect(result).not.toBeNull(); | |
| 32 | + if (result && isEnvironmentAuthConfig(result)) { | |
| 33 | + expect(result.organizationId).toBe("org_123"); | |
| 34 | + } else { | |
| 35 | + throw new Error("Expected environment auth config result"); | |
| 36 | + } | |
| 37 | + expect(mockFetch).toHaveBeenCalledOnce(); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("keeps organizationId null if endpoint not available", async () => { | |
| 41 | + const mockFetch = vi.fn().mockResolvedValue({ ok: false }); | |
| 42 | + (global as any).fetch = mockFetch; | |
| 43 | + | |
| 44 | + const envAuthConfig = { | |
| 45 | + accessToken: "sk_test_api_key", | |
| 46 | + organizationId: null as string | null, | |
| 47 | + } as const; | |
| 48 | + | |
| 49 | + const result = await ensureOrganization(envAuthConfig, true); | |
| 50 | + expect(result).not.toBeNull(); | |
| 51 | + if (result && isEnvironmentAuthConfig(result)) { | |
| 52 | + expect(result.organizationId).toBeNull(); | |
| 53 | + } else { | |
| 54 | + throw new Error("Expected environment auth config result"); | |
| 55 | + } | |
| 56 | + expect(mockFetch).toHaveBeenCalledOnce(); | |
| 57 | + }); | |
| 58 | +}); |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | +import * as os from "os"; | |
| 2 | 3 | import * as path from "path"; |
| 3 | 4 | |
| 4 | 5 | import chalk from "chalk"; |
| @@ -12,8 +13,12 @@ | ||
| 12 | 13 | globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; |
| 13 | 14 | } |
| 14 | 15 | |
| 15 | -// Config file path | |
| 16 | -const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json"); | |
| 16 | +// Config file path - define as a function to avoid initialization order issues | |
| 17 | +function getAuthConfigPath() { | |
| 18 | + const continueHome = | |
| 19 | + process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); | |
| 20 | + return path.join(continueHome, "auth.json"); | |
| 21 | +} | |
| 17 | 22 | |
| 18 | 23 | // Represents an authenticated user's configuration |
| 19 | 24 | export interface AuthenticatedConfig { |
| @@ -22,7 +27,7 @@ | ||
| 22 | 27 | accessToken: string; |
| 23 | 28 | refreshToken: string; |
| 24 | 29 | expiresAt: number; |
| 25 | - organizationId: string | null; // null means personal organization | |
| 30 | + organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection | |
| 26 | 31 | configUri?: string; // Optional config URI (file:// or slug://owner/slug) |
| 27 | 32 | modelName?: string; // Name of the selected model |
| 28 | 33 | } |
| @@ -74,7 +79,9 @@ | ||
| 74 | 79 | /** |
| 75 | 80 | * Gets the organization ID from any auth config type |
| 76 | 81 | */ |
| 77 | -export function getOrganizationId(config: AuthConfig): string | null { | |
| 82 | +export function getOrganizationId( | |
| 83 | + config: AuthConfig, | |
| 84 | +): string | null | undefined { | |
| 78 | 85 | if (config === null) return null; |
| 79 | 86 | return config.organizationId; |
| 80 | 87 | } |
| @@ -96,10 +103,9 @@ | ||
| 96 | 103 | } |
| 97 | 104 | |
| 98 | 105 | // URI utility functions have been moved to ./uriUtils.ts |
| 106 | +import { autoSelectOrganizationAndConfig } from "./orgSelection.js"; | |
| 99 | 107 | import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js"; |
| 100 | 108 | import { |
| 101 | - autoSelectOrganization, | |
| 102 | - createUpdatedAuthConfig, | |
| 103 | 109 | handleCliOrgForAuthenticatedConfig, |
| 104 | 110 | handleCliOrgForEnvironmentAuth, |
| 105 | 111 | } from "./workos.helpers.js"; |
| @@ -130,8 +136,9 @@ | ||
| 130 | 136 | } |
| 131 | 137 | |
| 132 | 138 | try { |
| 133 | - if (fs.existsSync(AUTH_CONFIG_PATH)) { | |
| 134 | - const data = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, "utf8")); | |
| 139 | + const authConfigPath = getAuthConfigPath(); | |
| 140 | + if (fs.existsSync(authConfigPath)) { | |
| 141 | + const data = JSON.parse(fs.readFileSync(authConfigPath, "utf8")); | |
| 135 | 142 | |
| 136 | 143 | // Validate that we have all required fields for authenticated config |
| 137 | 144 | if ( |
| @@ -173,13 +180,14 @@ | ||
| 173 | 180 | } |
| 174 | 181 | |
| 175 | 182 | try { |
| 183 | + const authConfigPath = getAuthConfigPath(); | |
| 176 | 184 | // Make sure the directory exists |
| 177 | - const dir = path.dirname(AUTH_CONFIG_PATH); | |
| 185 | + const dir = path.dirname(authConfigPath); | |
| 178 | 186 | if (!fs.existsSync(dir)) { |
| 179 | 187 | fs.mkdirSync(dir, { recursive: true }); |
| 180 | 188 | } |
| 181 | 189 | |
| 182 | - fs.writeFileSync(AUTH_CONFIG_PATH, JSON.stringify(config, null, 2)); | |
| 190 | + fs.writeFileSync(authConfigPath, JSON.stringify(config, null, 2)); | |
| 183 | 191 | } catch (error) { |
| 184 | 192 | console.error(`Error saving auth config: ${error}`); |
| 185 | 193 | } |
| @@ -360,7 +368,7 @@ | ||
| 360 | 368 | accessToken: access_token, |
| 361 | 369 | refreshToken: refresh_token, |
| 362 | 370 | expiresAt: tokenExpiresAt, |
| 363 | - organizationId: null, | |
| 371 | + organizationId: undefined, // undefined triggers auto-selection, null means personal org selected | |
| 364 | 372 | }; |
| 365 | 373 | |
| 366 | 374 | // Save the config |
| @@ -540,8 +548,10 @@ | ||
| 540 | 548 | ); |
| 541 | 549 | } |
| 542 | 550 | } else if (isEnvironmentAuthConfig(authConfig)) { |
| 543 | - // No CLI organization slug (or "personal" was specified) - return as-is | |
| 544 | - return authConfig; | |
| 551 | + // No CLI organization slug (or "personal" was specified) | |
| 552 | + // If using API key auth, attempt to resolve its organization scope once | |
| 553 | + const resolved = await resolveOrgScopeForApiKey(authConfig); | |
| 554 | + return resolved; | |
| 545 | 555 | } |
| 546 | 556 | |
| 547 | 557 | // If not authenticated, return as-is |
| @@ -561,20 +571,71 @@ | ||
| 561 | 571 | ); |
| 562 | 572 | } |
| 563 | 573 | |
| 564 | - // If already have organization ID (including null for personal), return as-is | |
| 565 | - if (authenticatedConfig.organizationId !== undefined) { | |
| 566 | - return authenticatedConfig; | |
| 574 | + // Only auto-select if user hasn't made any previous selections | |
| 575 | + // - organizationId === undefined means first-time setup | |
| 576 | + // - configUri being set means they've chosen a specific assistant/config | |
| 577 | + if ( | |
| 578 | + authenticatedConfig.organizationId === undefined && | |
| 579 | + !authenticatedConfig.configUri | |
| 580 | + ) { | |
| 581 | + return autoSelectOrganizationAndConfig(authenticatedConfig); | |
| 567 | 582 | } |
| 568 | 583 | |
| 569 | - // In headless mode, default to personal organization if none saved | |
| 570 | - if (isHeadless) { | |
| 571 | - const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); | |
| 572 | - saveAuthConfig(updatedConfig); | |
| 573 | - return updatedConfig; | |
| 584 | + // User already has made a selection (org or config) - respect their choice | |
| 585 | + return authenticatedConfig; | |
| 586 | +} | |
| 587 | + | |
| 588 | +/** | |
| 589 | + * Attempts to resolve the organization scope for API key auth (environment-based auth). | |
| 590 | + * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key. | |
| 591 | + * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config. | |
| 592 | + */ | |
| 593 | +async function resolveOrgScopeForApiKey( | |
| 594 | + envConfig: EnvironmentAuthConfig, | |
| 595 | +): Promise<EnvironmentAuthConfig> { | |
| 596 | + // If already set (including explicit null), return as-is | |
| 597 | + if (envConfig.organizationId !== null) { | |
| 598 | + return envConfig; | |
| 599 | + } | |
| 600 | + | |
| 601 | + const accessToken = envConfig.accessToken; | |
| 602 | + if (!accessToken) return envConfig; | |
| 603 | + | |
| 604 | + try { | |
| 605 | + // Prefer a dedicated endpoint for scope discovery. This should return JSON like: | |
| 606 | + // { organizationId: string | null } (aka orgScopeId) | |
| 607 | + const url = new URL("auth/scope", env.apiBase); | |
| 608 | + const resp = await fetch(url, { | |
| 609 | + method: "GET", | |
| 610 | + headers: { | |
| 611 | + Authorization: `Bearer ${accessToken}`, | |
| 612 | + "Content-Type": "application/json", | |
| 613 | + }, | |
| 614 | + }); | |
| 615 | + | |
| 616 | + if (!resp.ok) { | |
| 617 | + // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors | |
| 618 | + return envConfig; | |
| 619 | + } | |
| 620 | + | |
| 621 | + const data: any = await resp.json().catch(() => ({})); | |
| 622 | + const orgId = | |
| 623 | + data?.organizationId ?? | |
| 624 | + data?.orgScopeId ?? | |
| 625 | + data?.organization?.id ?? | |
| 626 | + null; | |
| 627 | + | |
| 628 | + if (orgId && typeof orgId === "string") { | |
| 629 | + return { | |
| 630 | + ...envConfig, | |
| 631 | + organizationId: orgId, | |
| 632 | + }; | |
| 633 | + } | |
| 634 | + } catch { | |
| 635 | + // Network or parsing issues: leave config unchanged | |
| 574 | 636 | } |
| 575 | 637 | |
| 576 | - // Need to select organization | |
| 577 | - return autoSelectOrganization(authenticatedConfig); | |
| 638 | + return envConfig; | |
| 578 | 639 | } |
| 579 | 640 | |
| 580 | 641 | /** |
| @@ -624,10 +685,9 @@ | ||
| 624 | 685 | * Logs the user out by clearing saved credentials |
| 625 | 686 | */ |
| 626 | 687 | export function logout(): void { |
| 627 | - const onboardingFlagPath = path.join( | |
| 628 | - env.continueHome, | |
| 629 | - ".onboarding_complete", | |
| 630 | - ); | |
| 688 | + const continueHome = | |
| 689 | + process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); | |
| 690 | + const onboardingFlagPath = path.join(continueHome, ".onboarding_complete"); | |
| 631 | 691 | |
| 632 | 692 | // Remove onboarding completion flag so user will go through onboarding again |
| 633 | 693 | if (fs.existsSync(onboardingFlagPath)) { |
| @@ -643,8 +703,9 @@ | ||
| 643 | 703 | return; |
| 644 | 704 | } |
| 645 | 705 | |
| 646 | - if (fs.existsSync(AUTH_CONFIG_PATH)) { | |
| 647 | - fs.unlinkSync(AUTH_CONFIG_PATH); | |
| 706 | + const authConfigPath = getAuthConfigPath(); | |
| 707 | + if (fs.existsSync(authConfigPath)) { | |
| 708 | + fs.unlinkSync(authConfigPath); | |
| 648 | 709 | console.info(chalk.green("Successfully logged out")); |
| 649 | 710 | } else { |
| 650 | 711 | console.info(chalk.yellow("No active session found")); |
| @@ -1,20 +1,16 @@ | ||
| 1 | 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 2 | 3 | import chalk from "chalk"; |
| 3 | -import type { ChatHistoryItem, Session } from "core/index.js"; | |
| 4 | +import { ChatHistoryItem, Session } from "core"; | |
| 4 | 5 | import { ChatDescriber } from "core/util/chatDescriber.js"; |
| 5 | -import * as readlineSync from "readline-sync"; | |
| 6 | 6 | |
| 7 | -import { | |
| 8 | - compactChatHistory, | |
| 9 | - findCompactionIndex, | |
| 10 | - getHistoryForLLM, | |
| 11 | -} from "../compaction.js"; | |
| 7 | +import { compactChatHistory, findCompactionIndex } from "../compaction.js"; | |
| 12 | 8 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 13 | -import { safeStdout } from "../init.js"; | |
| 9 | +import { safeStderr, safeStdout } from "../init.js"; | |
| 14 | 10 | import { configureLogger } from "../logger.js"; |
| 15 | 11 | import * as logging from "../logging.js"; |
| 16 | 12 | import { sentryService } from "../sentry.js"; |
| 17 | -import { initializeServices } from "../services/index.js"; | |
| 13 | +import { initializeServices, services } from "../services/index.js"; | |
| 18 | 14 | import { serviceContainer } from "../services/ServiceContainer.js"; |
| 19 | 15 | import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; |
| 20 | 16 | import { |
| @@ -26,8 +22,10 @@ | ||
| 26 | 22 | import { posthogService } from "../telemetry/posthogService.js"; |
| 27 | 23 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 28 | 24 | import { startTUIChat } from "../ui/index.js"; |
| 25 | +import { gracefulExit } from "../util/exit.js"; | |
| 29 | 26 | import { formatAnthropicError, formatError } from "../util/formatError.js"; |
| 30 | 27 | import { logger } from "../util/logger.js"; |
| 28 | +import { question } from "../util/prompt.js"; | |
| 31 | 29 | import { |
| 32 | 30 | calculateContextUsagePercentage, |
| 33 | 31 | countChatHistoryTokens, |
| @@ -80,6 +78,7 @@ | ||
| 80 | 78 | export interface ChatOptions extends ExtendedCommandOptions { |
| 81 | 79 | headless?: boolean; |
| 82 | 80 | resume?: boolean; |
| 81 | + fork?: string; // Fork from an existing session ID | |
| 83 | 82 | format?: "json"; // Output format for headless mode |
| 84 | 83 | silent?: boolean; // Strip <think></think> tags and excess whitespace |
| 85 | 84 | } |
| @@ -89,6 +88,20 @@ | ||
| 89 | 88 | ): Promise<ChatHistoryItem[]> { |
| 90 | 89 | let session: Session | null = null; |
| 91 | 90 | |
| 91 | + // Fork from an existing session if --fork flag is used | |
| 92 | + if (options.fork) { | |
| 93 | + const { loadSessionById, startNewSession } = await import("../session.js"); | |
| 94 | + const sessionToFork = loadSessionById(options.fork); | |
| 95 | + if (sessionToFork) { | |
| 96 | + logger.info(chalk.yellow("Forking from existing session...")); | |
| 97 | + const newSession = startNewSession(sessionToFork.history); | |
| 98 | + return newSession.history; | |
| 99 | + } else { | |
| 100 | + logger.error(chalk.red(`Session with ID "${options.fork}" not found.`)); | |
| 101 | + await gracefulExit(1); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 92 | 105 | // Load previous session if --resume flag is used |
| 93 | 106 | if (options.resume) { |
| 94 | 107 | session = loadSession(); |
| @@ -107,7 +120,7 @@ | ||
| 107 | 120 | async function handleManualCompaction( |
| 108 | 121 | chatHistory: ChatHistoryItem[], |
| 109 | 122 | model: ModelConfig, |
| 110 | - llmApi: any, | |
| 123 | + llmApi: BaseLlmApi, | |
| 111 | 124 | isHeadless: boolean, |
| 112 | 125 | ): Promise<{ compactionIndex?: number | null } | void> { |
| 113 | 126 | if (!isHeadless) { |
| @@ -115,21 +128,21 @@ | ||
| 115 | 128 | } |
| 116 | 129 | |
| 117 | 130 | try { |
| 118 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 119 | - | |
| 120 | - // Replace chat history with compacted version | |
| 121 | - chatHistory.length = 0; | |
| 122 | - chatHistory.push(...result.compactedHistory); | |
| 123 | - | |
| 124 | - // Save the compacted session | |
| 125 | - updateSessionHistory(chatHistory); | |
| 131 | + const current = services.chatHistory.getHistory(); | |
| 132 | + const result = await compactChatHistory(current, model, llmApi); | |
| 133 | + | |
| 134 | + // Update service-driven history (persistence handled by service) | |
| 135 | + services.chatHistory.compact( | |
| 136 | + result.compactedHistory, | |
| 137 | + result.compactionIndex, | |
| 138 | + ); | |
| 126 | 139 | |
| 127 | 140 | if (isHeadless) { |
| 128 | 141 | safeStdout( |
| 129 | 142 | JSON.stringify({ |
| 130 | 143 | status: "success", |
| 131 | 144 | message: "Chat history compacted", |
| 132 | - historyLength: chatHistory.length, | |
| 145 | + historyLength: services.chatHistory.getHistory().length, | |
| 133 | 146 | }) + "\n", |
| 134 | 147 | ); |
| 135 | 148 | } else { |
| @@ -148,11 +161,66 @@ | ||
| 148 | 161 | } |
| 149 | 162 | } |
| 150 | 163 | |
| 164 | +// Helper function to get streaming response based on compaction state | |
| 165 | +async function getStreamingResponse( | |
| 166 | + compactionIndex: number | null | undefined, | |
| 167 | + model: ModelConfig, | |
| 168 | + llmApi: BaseLlmApi, | |
| 169 | +): Promise<string> { | |
| 170 | + const abortController = new AbortController(); | |
| 171 | + | |
| 172 | + if (compactionIndex !== null && compactionIndex !== undefined) { | |
| 173 | + // Use service to compute history for LLM | |
| 174 | + const historyForLLM = | |
| 175 | + services.chatHistory.getHistoryForLLM(compactionIndex); | |
| 176 | + | |
| 177 | + return await streamChatResponse( | |
| 178 | + historyForLLM, | |
| 179 | + model, | |
| 180 | + llmApi, | |
| 181 | + abortController, | |
| 182 | + ); | |
| 183 | + } else { | |
| 184 | + // No compaction - get full history from service | |
| 185 | + return await streamChatResponse( | |
| 186 | + services.chatHistory.getHistory(), | |
| 187 | + model, | |
| 188 | + llmApi, | |
| 189 | + abortController, | |
| 190 | + ); | |
| 191 | + } | |
| 192 | +} | |
| 193 | + | |
| 194 | +// Helper function to process and output response in headless mode | |
| 195 | +function processAndOutputResponse( | |
| 196 | + finalResponse: string, | |
| 197 | + isHeadless: boolean, | |
| 198 | + silent?: boolean, | |
| 199 | + format?: "json", | |
| 200 | +): void { | |
| 201 | + if (isHeadless && finalResponse && finalResponse.trim()) { | |
| 202 | + let processedResponse = finalResponse; | |
| 203 | + | |
| 204 | + // Strip think tags if --silent flag is enabled | |
| 205 | + if (silent) { | |
| 206 | + processedResponse = stripThinkTags(processedResponse); | |
| 207 | + } | |
| 208 | + | |
| 209 | + // Process output based on format | |
| 210 | + const outputResponse = | |
| 211 | + format === "json" | |
| 212 | + ? processJsonOutput(processedResponse) | |
| 213 | + : processedResponse; | |
| 214 | + | |
| 215 | + safeStdout(outputResponse + "\n"); | |
| 216 | + } | |
| 217 | +} | |
| 218 | + | |
| 151 | 219 | // Helper function to handle auto-compaction for headless mode |
| 152 | 220 | async function handleAutoCompaction( |
| 153 | 221 | chatHistory: ChatHistoryItem[], |
| 154 | 222 | model: ModelConfig, |
| 155 | - llmApi: any, | |
| 223 | + llmApi: BaseLlmApi, | |
| 156 | 224 | isHeadless: boolean, |
| 157 | 225 | format?: "json", |
| 158 | 226 | ): Promise<number | null> { |
| @@ -176,7 +244,7 @@ | ||
| 176 | 244 | message: "Auto-compacting triggered", |
| 177 | 245 | contextUsage: |
| 178 | 246 | calculateContextUsagePercentage( |
| 179 | - countChatHistoryTokens(chatHistory), | |
| 247 | + countChatHistoryTokens(services.chatHistory.getHistory()), | |
| 180 | 248 | model, |
| 181 | 249 | ) + "%", |
| 182 | 250 | }) + "\n", |
| @@ -186,11 +254,11 @@ | ||
| 186 | 254 | if (!isHeadless) { |
| 187 | 255 | console.info(chalk.green(message)); |
| 188 | 256 | } else if (format === "json") { |
| 257 | + // Omit history length here; service updates occur after compaction completes | |
| 189 | 258 | safeStdout( |
| 190 | 259 | JSON.stringify({ |
| 191 | 260 | status: "success", |
| 192 | 261 | message: "Auto-compacted successfully", |
| 193 | - historyLength: chatHistory.length, | |
| 194 | 262 | }) + "\n", |
| 195 | 263 | ); |
| 196 | 264 | } |
| @@ -210,15 +278,19 @@ | ||
| 210 | 278 | }, |
| 211 | 279 | }; |
| 212 | 280 | |
| 213 | - const result = await coreAutoCompaction(chatHistory, model, llmApi, { | |
| 214 | - isHeadless, | |
| 215 | - format, | |
| 216 | - callbacks, | |
| 217 | - }); | |
| 281 | + const result = await coreAutoCompaction( | |
| 282 | + services.chatHistory.getHistory(), | |
| 283 | + model, | |
| 284 | + llmApi, | |
| 285 | + { | |
| 286 | + isHeadless, | |
| 287 | + format, | |
| 288 | + callbacks, | |
| 289 | + }, | |
| 290 | + ); | |
| 218 | 291 | |
| 219 | - // Update the original array reference for headless mode | |
| 220 | - chatHistory.length = 0; | |
| 221 | - chatHistory.push(...result.chatHistory); | |
| 292 | + // Update service-driven history | |
| 293 | + services.chatHistory.setHistory(result.chatHistory); | |
| 222 | 294 | |
| 223 | 295 | return result.compactionIndex; |
| 224 | 296 | } |
| @@ -228,7 +300,7 @@ | ||
| 228 | 300 | */ |
| 229 | 301 | async function handleTitleGeneration( |
| 230 | 302 | assistantResponse: string, |
| 231 | - llmApi: any, | |
| 303 | + llmApi: BaseLlmApi, | |
| 232 | 304 | model: ModelConfig, |
| 233 | 305 | ): Promise<void> { |
| 234 | 306 | try { |
| @@ -254,7 +326,7 @@ | ||
| 254 | 326 | userInput: string; |
| 255 | 327 | chatHistory: ChatHistoryItem[]; |
| 256 | 328 | model: ModelConfig; |
| 257 | - llmApi: any; | |
| 329 | + llmApi: BaseLlmApi; | |
| 258 | 330 | isHeadless: boolean; |
| 259 | 331 | format?: "json"; |
| 260 | 332 | silent?: boolean; |
| @@ -286,7 +358,7 @@ | ||
| 286 | 358 | telemetryService.logUserPrompt(userInput.length, userInput); |
| 287 | 359 | |
| 288 | 360 | // Check if auto-compacting is needed BEFORE adding user message |
| 289 | - if (shouldAutoCompact(chatHistory, model)) { | |
| 361 | + if (shouldAutoCompact(services.chatHistory.getHistory(), model)) { | |
| 290 | 362 | const newIndex = await handleAutoCompaction( |
| 291 | 363 | chatHistory, |
| 292 | 364 | model, |
| @@ -296,17 +368,12 @@ | ||
| 296 | 368 | ); |
| 297 | 369 | if (newIndex !== null) { |
| 298 | 370 | compactionIndex = newIndex; |
| 299 | - // Replace chatHistory with compacted version | |
| 300 | - chatHistory.length = 0; | |
| 301 | - chatHistory.push(...chatHistory); | |
| 371 | + // Service already updated in handleAutoCompaction via setHistory | |
| 302 | 372 | } |
| 303 | 373 | } |
| 304 | 374 | |
| 305 | 375 | // Add user message to history AFTER potential compaction |
| 306 | - chatHistory.push({ | |
| 307 | - message: { role: "user", content: userInput }, | |
| 308 | - contextItems: [], | |
| 309 | - }); | |
| 376 | + services.chatHistory.addUserMessage(userInput); | |
| 310 | 377 | |
| 311 | 378 | // Get AI response with potential tool usage |
| 312 | 379 | if (!isHeadless) { |
| @@ -314,79 +381,56 @@ | ||
| 314 | 381 | } |
| 315 | 382 | |
| 316 | 383 | try { |
| 317 | - const abortController = new AbortController(); | |
| 318 | - | |
| 319 | - // Handle compaction properly - streamChatResponse modifies the array in place | |
| 320 | - let finalResponse; | |
| 321 | - if (compactionIndex !== null && compactionIndex !== undefined) { | |
| 322 | - // When using compaction, we need to send a subset but capture the full history | |
| 323 | - const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex); | |
| 324 | - const originalLength = historyForLLM.length; | |
| 325 | - | |
| 326 | - finalResponse = await streamChatResponse( | |
| 327 | - historyForLLM, | |
| 328 | - model, | |
| 329 | - llmApi, | |
| 330 | - abortController, | |
| 331 | - ); | |
| 332 | - | |
| 333 | - // Append any new messages (assistant/tool) that were added by streamChatResponse | |
| 334 | - const newMessages = historyForLLM.slice(originalLength); | |
| 335 | - chatHistory.push(...newMessages); | |
| 336 | - } else { | |
| 337 | - // No compaction - just pass the full history directly | |
| 338 | - finalResponse = await streamChatResponse( | |
| 339 | - chatHistory, | |
| 340 | - model, | |
| 341 | - llmApi, | |
| 342 | - abortController, | |
| 343 | - ); | |
| 344 | - // No need to sync back - streamChatResponse modifies chatHistory in place | |
| 345 | - } | |
| 384 | + // Get AI response with potential tool usage | |
| 385 | + const finalResponse = await getStreamingResponse( | |
| 386 | + compactionIndex, | |
| 387 | + model, | |
| 388 | + llmApi, | |
| 389 | + ); | |
| 346 | 390 | |
| 347 | 391 | // Generate session title after first assistant response |
| 348 | 392 | if (firstAssistantResponse && finalResponse && finalResponse.trim()) { |
| 349 | 393 | await handleTitleGeneration(finalResponse, llmApi, model); |
| 350 | 394 | } |
| 351 | 395 | |
| 352 | - // In headless mode, only print the final response using safe stdout | |
| 353 | - if (isHeadless && finalResponse && finalResponse.trim()) { | |
| 354 | - let processedResponse = finalResponse; | |
| 355 | - | |
| 356 | - // Strip think tags if --silent flag is enabled | |
| 357 | - if (silent) { | |
| 358 | - processedResponse = stripThinkTags(processedResponse); | |
| 359 | - } | |
| 360 | - | |
| 361 | - // Process output based on format | |
| 362 | - const outputResponse = | |
| 363 | - format === "json" | |
| 364 | - ? processJsonOutput(processedResponse) | |
| 365 | - : processedResponse; | |
| 366 | - | |
| 367 | - safeStdout(outputResponse + "\n"); | |
| 368 | - } | |
| 396 | + // Process and output response in headless mode | |
| 397 | + processAndOutputResponse(finalResponse, isHeadless, silent, format); | |
| 369 | 398 | |
| 370 | 399 | // Save session after each successful response |
| 371 | - updateSessionHistory(chatHistory); | |
| 400 | + updateSessionHistory(services.chatHistory.getHistory()); | |
| 372 | 401 | } catch (e: any) { |
| 373 | 402 | const error = e instanceof Error ? e : new Error(String(e)); |
| 374 | 403 | |
| 375 | - if (model.provider === "anthropic") { | |
| 376 | - logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); | |
| 377 | - } else { | |
| 378 | - logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); | |
| 404 | + // In headless mode, don't output JSON here - let error bubble up to main handler | |
| 405 | + if (!isHeadless) { | |
| 406 | + // Non-headless mode: use colored console output | |
| 407 | + if (model.provider === "anthropic") { | |
| 408 | + logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); | |
| 409 | + } else { | |
| 410 | + logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); | |
| 411 | + } | |
| 412 | + | |
| 413 | + logger.info( | |
| 414 | + chalk.dim( | |
| 415 | + `Chat history:\n${JSON.stringify( | |
| 416 | + services.chatHistory.getHistory(), | |
| 417 | + null, | |
| 418 | + 2, | |
| 419 | + )}`, | |
| 420 | + ), | |
| 421 | + ); | |
| 379 | 422 | } |
| 380 | 423 | |
| 381 | 424 | sentryService.captureException(error, { |
| 382 | 425 | context: "chat_response", |
| 383 | 426 | isHeadless, |
| 384 | - chatHistoryLength: chatHistory.length, | |
| 427 | + chatHistoryLength: services.chatHistory.getHistory().length, | |
| 385 | 428 | }); |
| 386 | - if (!isHeadless) { | |
| 387 | - logger.info( | |
| 388 | - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`), | |
| 389 | - ); | |
| 429 | + | |
| 430 | + // In headless mode, re-throw the error to bubble up to main error handler | |
| 431 | + // This preserves downstream logic like telemetry cleanup | |
| 432 | + if (isHeadless) { | |
| 433 | + throw error; | |
| 390 | 434 | } |
| 391 | 435 | } |
| 392 | 436 | } |
| @@ -414,12 +458,15 @@ | ||
| 414 | 458 | throw new Error("No models were found."); |
| 415 | 459 | } |
| 416 | 460 | |
| 417 | - // Initialize chat history | |
| 418 | - const chatHistory = await initializeChatHistory(options); | |
| 461 | + if (!llmApi) { | |
| 462 | + throw new Error("No LLM API instance found."); | |
| 463 | + } | |
| 419 | 464 | |
| 420 | - // Track compaction index if resuming with compacted history | |
| 465 | + // Initialize service-driven history (resume if requested) | |
| 466 | + const chatHistory = await initializeChatHistory(options); | |
| 421 | 467 | let compactionIndex: number | null = null; |
| 422 | - if (options.resume) { | |
| 468 | + if (options.resume || options.fork) { | |
| 469 | + services.chatHistory.setHistory(chatHistory); | |
| 423 | 470 | compactionIndex = findCompactionIndex(chatHistory); |
| 424 | 471 | } |
| 425 | 472 | |
| @@ -443,7 +490,7 @@ | ||
| 443 | 490 | const userInput = |
| 444 | 491 | isFirstMessage && initialUserInput |
| 445 | 492 | ? initialUserInput |
| 446 | - : readlineSync.question(`\n${chalk.bold.green("You:")} `); | |
| 493 | + : await question(`\n${chalk.bold.green("You:")} `); | |
| 447 | 494 | |
| 448 | 495 | isFirstMessage = false; |
| 449 | 496 | |
| @@ -487,21 +534,17 @@ | ||
| 487 | 534 | const { permissionOverrides } = processCommandFlags(options); |
| 488 | 535 | |
| 489 | 536 | // Initialize services with onboarding handled internally |
| 490 | - const initResult = await initializeServices({ | |
| 537 | + await initializeServices({ | |
| 491 | 538 | options, |
| 492 | 539 | headless: false, |
| 493 | 540 | toolPermissionOverrides: permissionOverrides, |
| 494 | 541 | }); |
| 495 | 542 | |
| 496 | - // If onboarding was completed, show success message | |
| 497 | - if (initResult.wasOnboarded) { | |
| 498 | - console.log(chalk.green("✓ Setup complete! Starting chat...")); | |
| 499 | - } | |
| 500 | - | |
| 501 | 543 | // Start TUI with skipOnboarding since we already handled it |
| 502 | 544 | const tuiOptions: any = { |
| 503 | 545 | initialPrompt: prompt, |
| 504 | 546 | resume: options.resume, |
| 547 | + fork: options.fork, | |
| 505 | 548 | config: options.config, |
| 506 | 549 | org: options.org, |
| 507 | 550 | rule: options.rule, |
| @@ -528,15 +571,30 @@ | ||
| 528 | 571 | await runHeadlessMode(prompt, options); |
| 529 | 572 | } catch (error: any) { |
| 530 | 573 | const err = error instanceof Error ? error : new Error(String(error)); |
| 531 | - // Use headless-aware error logging to ensure fatal errors are shown in headless mode | |
| 532 | - logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); | |
| 574 | + | |
| 575 | + // In headless mode, output error as JSON to stdout | |
| 576 | + if (options.headless) { | |
| 577 | + const errorOutput = { | |
| 578 | + status: "error", | |
| 579 | + message: err.message || String(err), | |
| 580 | + }; | |
| 581 | + safeStderr(JSON.stringify(errorOutput) + "\n"); | |
| 582 | + } else { | |
| 583 | + // Use headless-aware error logging for non-headless mode | |
| 584 | + logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); | |
| 585 | + } | |
| 586 | + | |
| 533 | 587 | sentryService.captureException(err, { |
| 534 | 588 | context: "chat_command_fatal", |
| 535 | 589 | headless: options.headless, |
| 536 | 590 | }); |
| 537 | - process.exit(1); | |
| 591 | + | |
| 592 | + // Stop active time tracking BEFORE graceful exit | |
| 593 | + telemetryService.stopActiveTime(); | |
| 594 | + | |
| 595 | + await gracefulExit(1); | |
| 538 | 596 | } finally { |
| 539 | - // Stop active time tracking | |
| 597 | + // Stop active time tracking for normal completion | |
| 540 | 598 | telemetryService.stopActiveTime(); |
| 541 | 599 | } |
| 542 | 600 | } |
| @@ -71,15 +71,17 @@ | ||
| 71 | 71 | }); |
| 72 | 72 | }); |
| 73 | 73 | |
| 74 | - it("should only show exit command in remote mode", () => { | |
| 74 | + it("should only show remote mode commands in remote mode", () => { | |
| 75 | 75 | const commands = getAllSlashCommands(mockAssistant, { |
| 76 | 76 | isRemoteMode: true, |
| 77 | 77 | }); |
| 78 | 78 | const commandNames = commands.map((cmd) => cmd.name); |
| 79 | 79 | |
| 80 | - // In remote mode, only exit command should be available | |
| 80 | + // In remote mode, only remote commands should be available | |
| 81 | 81 | expect(commandNames).toContain("exit"); |
| 82 | - expect(commandNames).toHaveLength(1); | |
| 82 | + expect(commandNames).toContain("diff"); | |
| 83 | + expect(commandNames).toContain("apply"); | |
| 84 | + expect(commandNames).toHaveLength(3); | |
| 83 | 85 | }); |
| 84 | 86 | }); |
| 85 | 87 | }); |
| @@ -40,6 +40,11 @@ | ||
| 40 | 40 | description: "Sign out of your current session", |
| 41 | 41 | category: "system", |
| 42 | 42 | }, |
| 43 | + { | |
| 44 | + name: "update", | |
| 45 | + description: "Update the Continue CLI", | |
| 46 | + category: "system", | |
| 47 | + }, | |
| 43 | 48 | { |
| 44 | 49 | name: "whoami", |
| 45 | 50 | description: "Check who you're currently logged in as", |
| @@ -65,7 +70,11 @@ | ||
| 65 | 70 | description: "Manage MCP server connections", |
| 66 | 71 | category: "system", |
| 67 | 72 | }, |
| 68 | - | |
| 73 | + { | |
| 74 | + name: "init", | |
| 75 | + description: "Create an AGENTS.md file", | |
| 76 | + category: "system", | |
| 77 | + }, | |
| 69 | 78 | { |
| 70 | 79 | name: "compact", |
| 71 | 80 | description: "Summarize chat history into a compact form", |
| @@ -76,6 +85,16 @@ | ||
| 76 | 85 | description: "Resume a previous chat session", |
| 77 | 86 | category: "system", |
| 78 | 87 | }, |
| 88 | + { | |
| 89 | + name: "fork", | |
| 90 | + description: "Start a forked chat session from the current history", | |
| 91 | + category: "system", | |
| 92 | + }, | |
| 93 | + { | |
| 94 | + name: "title", | |
| 95 | + description: "Set the title for the current session", | |
| 96 | + category: "system", | |
| 97 | + }, | |
| 79 | 98 | { |
| 80 | 99 | name: "exit", |
| 81 | 100 | description: "Exit the chat", |
| @@ -90,6 +109,16 @@ | ||
| 90 | 109 | description: "Exit the remote environment", |
| 91 | 110 | category: "system", |
| 92 | 111 | }, |
| 112 | + { | |
| 113 | + name: "diff", | |
| 114 | + description: "Show the current diff from the remote environment", | |
| 115 | + category: "system", | |
| 116 | + }, | |
| 117 | + { | |
| 118 | + name: "apply", | |
| 119 | + description: "Apply the current diff to the local working tree", | |
| 120 | + category: "system", | |
| 121 | + }, | |
| 93 | 122 | ]; |
| 94 | 123 | |
| 95 | 124 | /** |
| @@ -0,0 +1,45 @@ | ||
| 1 | +import { type AssistantConfig } from "@continuedev/sdk"; | |
| 2 | + | |
| 3 | +import { SlashCommandResult } from "../ui/hooks/useChat.types.js"; | |
| 4 | + | |
| 5 | +function createInitPrompt(): string { | |
| 6 | + return `Please analyze this repository and create a comprehensive AGENTS.md file. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup. | |
| 7 | + | |
| 8 | +Create an AGENTS.md file with the following structure: | |
| 9 | + | |
| 10 | +# Repository Overview | |
| 11 | + | |
| 12 | +## Project Description | |
| 13 | +- What this project does | |
| 14 | +- Main purpose and goals | |
| 15 | +- Key technologies used | |
| 16 | + | |
| 17 | +## Architecture Overview | |
| 18 | +- High-level architecture | |
| 19 | +- Main components and their relationships | |
| 20 | +- Data flow and system interactions | |
| 21 | + | |
| 22 | +## Directory Structure | |
| 23 | +- Important directories and their purposes | |
| 24 | +- Key files and configuration | |
| 25 | +- Entry points and main modules | |
| 26 | + | |
| 27 | +## Development Workflow | |
| 28 | +- How to build/run the project | |
| 29 | +- Testing approach | |
| 30 | +- Development environment setup | |
| 31 | +- Lint and format commands | |
| 32 | + | |
| 33 | +Please create the AGENTS.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the file concise but informational.`; | |
| 34 | +} | |
| 35 | + | |
| 36 | +export async function handleInit( | |
| 37 | + _args: string[], | |
| 38 | + _assistant: AssistantConfig, | |
| 39 | +): Promise<SlashCommandResult> { | |
| 40 | + const prompt = createInitPrompt(); | |
| 41 | + | |
| 42 | + return { | |
| 43 | + newInput: prompt, | |
| 44 | + }; | |
| 45 | +} |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import chalk from "chalk"; |
| 2 | 2 | |
| 3 | 3 | import { login as workosLogin } from "../auth/workos.js"; |
| 4 | +import { gracefulExit } from "../util/exit.js"; | |
| 4 | 5 | |
| 5 | 6 | export async function login() { |
| 6 | 7 | console.info(chalk.yellow("Logging in to Continue...")); |
| @@ -10,6 +11,6 @@ | ||
| 10 | 11 | console.info(chalk.green("Successfully logged in!")); |
| 11 | 12 | } catch (error: any) { |
| 12 | 13 | console.error(chalk.red(`Login failed: ${error.message}`)); |
| 13 | - process.exit(1); | |
| 14 | + await gracefulExit(1); | |
| 14 | 15 | } |
| 15 | 16 | } |
| @@ -20,16 +20,26 @@ | ||
| 20 | 20 | render: vi.fn(() => ({ unmount: vi.fn() })), |
| 21 | 21 | })); |
| 22 | 22 | |
| 23 | -// Mock react | |
| 24 | -vi.mock("react", () => ({ | |
| 25 | - createElement: vi.fn(), | |
| 26 | -})); | |
| 23 | +// Mock react with createContext | |
| 24 | +vi.mock("react", async (importOriginal) => { | |
| 25 | + const actual: any = await importOriginal(); | |
| 26 | + return { | |
| 27 | + ...actual, | |
| 28 | + createElement: vi.fn(), | |
| 29 | + createContext: vi.fn(() => ({ Provider: vi.fn(), Consumer: vi.fn() })), | |
| 30 | + }; | |
| 31 | +}); | |
| 27 | 32 | |
| 28 | 33 | // Mock the chat command |
| 29 | 34 | vi.mock("./chat.js", () => ({ |
| 30 | 35 | chat: vi.fn(), |
| 31 | 36 | })); |
| 32 | 37 | |
| 38 | +// Mock the remote command | |
| 39 | +vi.mock("./remote.js", () => ({ | |
| 40 | + remote: vi.fn(), | |
| 41 | +})); | |
| 42 | + | |
| 33 | 43 | describe("listSessionsCommand", () => { |
| 34 | 44 | const mockListSessions = vi.mocked(sessionModule.listSessions); |
| 35 | 45 | |
| @@ -49,6 +59,7 @@ | ||
| 49 | 59 | dateCreated: "2023-01-01T10:00:00.000Z", |
| 50 | 60 | workspaceDirectory: "/workspace", |
| 51 | 61 | firstUserMessage: "Hello world", |
| 62 | + isRemote: false, | |
| 52 | 63 | }, |
| 53 | 64 | { |
| 54 | 65 | sessionId: "session-2", |
| @@ -56,10 +67,12 @@ | ||
| 56 | 67 | dateCreated: "2023-01-01T09:00:00.000Z", |
| 57 | 68 | workspaceDirectory: "/workspace", |
| 58 | 69 | firstUserMessage: "Test message", |
| 70 | + isRemote: true, | |
| 71 | + remoteId: "agent-123", | |
| 59 | 72 | }, |
| 60 | 73 | ]; |
| 61 | 74 | |
| 62 | - mockListSessions.mockReturnValue(mockSessions); | |
| 75 | + mockListSessions.mockResolvedValue(mockSessions); | |
| 63 | 76 | |
| 64 | 77 | const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {}); |
| 65 | 78 | |
| @@ -75,6 +88,8 @@ | ||
| 75 | 88 | workspaceDirectory: "/workspace", |
| 76 | 89 | title: "Session 1", |
| 77 | 90 | firstUserMessage: "Hello world", |
| 91 | + isRemote: false, | |
| 92 | + remoteId: undefined, | |
| 78 | 93 | }, |
| 79 | 94 | { |
| 80 | 95 | id: "session-2", |
| @@ -82,6 +97,8 @@ | ||
| 82 | 97 | workspaceDirectory: "/workspace", |
| 83 | 98 | title: "Session 2", |
| 84 | 99 | firstUserMessage: "Test message", |
| 100 | + isRemote: true, | |
| 101 | + remoteId: "agent-123", | |
| 85 | 102 | }, |
| 86 | 103 | ], |
| 87 | 104 | }, |
| @@ -93,20 +110,23 @@ | ||
| 93 | 110 | consoleSpy.mockRestore(); |
| 94 | 111 | }); |
| 95 | 112 | |
| 96 | - it("should use limit of 10 for JSON and 20 for TUI", async () => { | |
| 97 | - mockListSessions.mockReturnValue([]); | |
| 113 | + it("should call listSessions without limit restrictions", async () => { | |
| 114 | + mockListSessions.mockResolvedValue([]); | |
| 98 | 115 | |
| 99 | - // JSON mode should fetch 10 | |
| 116 | + // JSON mode - should call listSessions (implementation decides limit) | |
| 100 | 117 | await listSessionsCommand({ format: "json" }); |
| 101 | - expect(mockListSessions).toHaveBeenCalledWith(10); | |
| 118 | + expect(mockListSessions).toHaveBeenCalled(); | |
| 102 | 119 | |
| 103 | - // TUI mode should fetch 20 (so UI can choose how many to display) | |
| 120 | + // TUI mode - should call listSessions (implementation decides limit) | |
| 104 | 121 | await listSessionsCommand({}); |
| 105 | - expect(mockListSessions).toHaveBeenCalledWith(20); | |
| 122 | + expect(mockListSessions).toHaveBeenCalled(); | |
| 123 | + | |
| 124 | + // Verify it was called twice total | |
| 125 | + expect(mockListSessions).toHaveBeenCalledTimes(2); | |
| 106 | 126 | }); |
| 107 | 127 | |
| 108 | 128 | it("should handle empty sessions gracefully in JSON mode", async () => { |
| 109 | - mockListSessions.mockReturnValue([]); | |
| 129 | + mockListSessions.mockResolvedValue([]); | |
| 110 | 130 | |
| 111 | 131 | const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {}); |
| 112 | 132 | |
| @@ -120,7 +140,7 @@ | ||
| 120 | 140 | }); |
| 121 | 141 | |
| 122 | 142 | it("should handle empty sessions gracefully in TUI mode", async () => { |
| 123 | - mockListSessions.mockReturnValue([]); | |
| 143 | + mockListSessions.mockResolvedValue([]); | |
| 124 | 144 | |
| 125 | 145 | const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {}); |
| 126 | 146 |
| @@ -1,11 +1,14 @@ | ||
| 1 | 1 | import { render } from "ink"; |
| 2 | 2 | import React from "react"; |
| 3 | 3 | |
| 4 | -import { loadSessionById, listSessions } from "../session.js"; | |
| 4 | +import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; | |
| 5 | +import { env } from "../env.js"; | |
| 6 | +import { listSessions, loadSessionById } from "../session.js"; | |
| 5 | 7 | import { SessionSelector } from "../ui/SessionSelector.js"; |
| 6 | 8 | import { logger } from "../util/logger.js"; |
| 7 | 9 | |
| 8 | 10 | import { chat } from "./chat.js"; |
| 11 | +import { remote } from "./remote.js"; | |
| 9 | 12 | |
| 10 | 13 | interface ListSessionsOptions { |
| 11 | 14 | format?: "json"; |
| @@ -23,18 +26,35 @@ | ||
| 23 | 26 | ); |
| 24 | 27 | } |
| 25 | 28 | |
| 29 | +export async function getTunnelForAgent(agentId: string): Promise<string> { | |
| 30 | + const authConfig = loadAuthConfig(); | |
| 31 | + const accessToken = getAccessToken(authConfig); | |
| 32 | + | |
| 33 | + const resp = await fetch(`${env.apiBase}agents/devboxes/${agentId}/tunnel`, { | |
| 34 | + method: "POST", | |
| 35 | + headers: { | |
| 36 | + "Content-Type": "application/json", | |
| 37 | + Authorization: `Bearer ${accessToken}`, | |
| 38 | + }, | |
| 39 | + }); | |
| 40 | + if (!resp.ok) { | |
| 41 | + throw new Error( | |
| 42 | + `Failed to get tunnel for agent ${agentId}: ${await resp.text()}`, | |
| 43 | + ); | |
| 44 | + } | |
| 45 | + const data = await resp.json(); | |
| 46 | + return data.url; | |
| 47 | +} | |
| 48 | + | |
| 26 | 49 | /** |
| 27 | 50 | * List recent chat sessions and allow selection |
| 28 | 51 | */ |
| 29 | 52 | export async function listSessionsCommand( |
| 30 | 53 | options: ListSessionsOptions = {}, |
| 31 | 54 | ): Promise<void> { |
| 32 | - // Fetch more sessions than we might display so the UI can choose based on screen height | |
| 33 | - // But still limit for JSON output to keep it reasonable | |
| 34 | - const sessions = listSessions(options.format === "json" ? 10 : 20); | |
| 35 | - | |
| 36 | - // Handle JSON format output | |
| 55 | + // Handle JSON format output first | |
| 37 | 56 | if (options.format === "json") { |
| 57 | + const sessions = await listSessions(); | |
| 38 | 58 | console.log( |
| 39 | 59 | JSON.stringify( |
| 40 | 60 | { |
| @@ -44,6 +64,8 @@ | ||
| 44 | 64 | workspaceDirectory: session.workspaceDirectory, |
| 45 | 65 | title: session.title, |
| 46 | 66 | firstUserMessage: session.firstUserMessage, |
| 67 | + isRemote: session.isRemote, | |
| 68 | + remoteId: session.remoteId, | |
| 47 | 69 | })), |
| 48 | 70 | }, |
| 49 | 71 | null, |
| @@ -53,6 +75,9 @@ | ||
| 53 | 75 | return; |
| 54 | 76 | } |
| 55 | 77 | |
| 78 | + // For TUI mode, fetch more sessions than we might display so the UI can choose based on screen height | |
| 79 | + const sessions = await listSessions(); | |
| 80 | + | |
| 56 | 81 | // Handle empty sessions case |
| 57 | 82 | if (sessions.length === 0) { |
| 58 | 83 | console.log( |
| @@ -67,25 +92,37 @@ | ||
| 67 | 92 | try { |
| 68 | 93 | app.unmount(); |
| 69 | 94 | |
| 70 | - // Verify the session exists before trying to load it | |
| 71 | - const sessionHistory = loadSessionById(sessionId); | |
| 72 | - if (!sessionHistory) { | |
| 73 | - console.error(`Session ${sessionId} could not be loaded.`); | |
| 74 | - resolve(); | |
| 75 | - return; | |
| 95 | + // Find the selected session to check if it's remote | |
| 96 | + const selectedSession = sessions.find((s) => s.sessionId === sessionId); | |
| 97 | + | |
| 98 | + if (selectedSession?.isRemote && selectedSession.remoteId) { | |
| 99 | + // Handle remote session - use the remote command with the agent URL | |
| 100 | + logger.info(`Opening remote session: ${selectedSession.remoteId}`); | |
| 101 | + | |
| 102 | + const tunnelUrl = await getTunnelForAgent(selectedSession.remoteId); | |
| 103 | + | |
| 104 | + await remote(undefined, { url: tunnelUrl }); | |
| 105 | + } else { | |
| 106 | + // Handle local session | |
| 107 | + const sessionHistory = loadSessionById(sessionId); | |
| 108 | + if (!sessionHistory) { | |
| 109 | + logger.error(`Session ${sessionId} could not be loaded.`); | |
| 110 | + resolve(); | |
| 111 | + return; | |
| 112 | + } | |
| 113 | + | |
| 114 | + logger.info(`Loading session: ${sessionId}`); | |
| 115 | + | |
| 116 | + // Set the session ID so that when chat() runs, it will load this session | |
| 117 | + setSessionId(sessionId); | |
| 118 | + | |
| 119 | + // Start chat with resume flag to load the selected session | |
| 120 | + await chat(undefined, { | |
| 121 | + resume: true, | |
| 122 | + headless: false, | |
| 123 | + }); | |
| 76 | 124 | } |
| 77 | 125 | |
| 78 | - logger.info(`Loading session: ${sessionId}`); | |
| 79 | - | |
| 80 | - // Set the session ID so that when chat() runs, it will load this session | |
| 81 | - setSessionId(sessionId); | |
| 82 | - | |
| 83 | - // Start chat with resume flag to load the selected session | |
| 84 | - await chat(undefined, { | |
| 85 | - resume: true, | |
| 86 | - headless: false, | |
| 87 | - }); | |
| 88 | - | |
| 89 | 126 | resolve(); |
| 90 | 127 | } catch (error) { |
| 91 | 128 | logger.error("Error loading session:", error); |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 4 | 4 | import { startRemoteTUIChat } from "../ui/index.js"; |
| 5 | +import { gracefulExit } from "../util/exit.js"; | |
| 5 | 6 | import { logger } from "../util/logger.js"; |
| 6 | 7 | |
| 7 | 8 | export async function remoteTest( |
| @@ -25,6 +26,6 @@ | ||
| 25 | 26 | logger.error( |
| 26 | 27 | chalk.red(`Failed to connect to remote environment: ${error.message}`), |
| 27 | 28 | ); |
| 28 | - process.exit(1); | |
| 29 | + await gracefulExit(1); | |
| 29 | 30 | } |
| 30 | 31 | } |
| @@ -236,6 +236,71 @@ | ||
| 236 | 236 | prompt: "test prompt", |
| 237 | 237 | idempotencyKey: testIdempotencyKey, |
| 238 | 238 | branchName: testBranch, |
| 239 | + agent: undefined, | |
| 240 | + config: undefined, | |
| 241 | + }); | |
| 242 | + }); | |
| 243 | + | |
| 244 | + it("should include config in request body when config option is provided", async () => { | |
| 245 | + const testConfig = "test-config-path"; | |
| 246 | + | |
| 247 | + await remote("test prompt", { config: testConfig }); | |
| 248 | + | |
| 249 | + expect(mockFetch).toHaveBeenCalledWith( | |
| 250 | + new URL("agents/devboxes", mockEnv.env.apiBase), | |
| 251 | + expect.objectContaining({ | |
| 252 | + method: "POST", | |
| 253 | + headers: { | |
| 254 | + "Content-Type": "application/json", | |
| 255 | + Authorization: "Bearer test-token", | |
| 256 | + }, | |
| 257 | + body: expect.stringContaining(`"config":"${testConfig}"`), | |
| 258 | + }), | |
| 259 | + ); | |
| 260 | + | |
| 261 | + expect(mockFetch).toHaveBeenCalledWith( | |
| 262 | + new URL("agents/devboxes", mockEnv.env.apiBase), | |
| 263 | + expect.objectContaining({ | |
| 264 | + body: expect.stringContaining(`"agent":"${testConfig}"`), | |
| 265 | + }), | |
| 266 | + ); | |
| 267 | + }); | |
| 268 | + | |
| 269 | + it("should handle proper request body structure with config field", async () => { | |
| 270 | + const testConfig = "my-agent-config"; | |
| 271 | + const testIdempotencyKey = "test-with-config"; | |
| 272 | + | |
| 273 | + await remote("test prompt", { | |
| 274 | + config: testConfig, | |
| 275 | + idempotencyKey: testIdempotencyKey, | |
| 276 | + }); | |
| 277 | + | |
| 278 | + const fetchCall = mockFetch.mock.calls[0]; | |
| 279 | + const requestBody = JSON.parse(fetchCall[1].body); | |
| 280 | + | |
| 281 | + expect(requestBody).toEqual({ | |
| 282 | + repoUrl: "https://github.com/user/test-repo.git", | |
| 283 | + name: expect.stringMatching(/^devbox-\d+$/), | |
| 284 | + prompt: "test prompt", | |
| 285 | + idempotencyKey: testIdempotencyKey, | |
| 286 | + agent: testConfig, | |
| 287 | + config: testConfig, | |
| 288 | + }); | |
| 289 | + }); | |
| 290 | + | |
| 291 | + it("should not include config in request body when config option is not provided", async () => { | |
| 292 | + await remote("test prompt", {}); | |
| 293 | + | |
| 294 | + const fetchCall = mockFetch.mock.calls[0]; | |
| 295 | + const requestBody = JSON.parse(fetchCall[1].body); | |
| 296 | + | |
| 297 | + expect(requestBody).toEqual({ | |
| 298 | + repoUrl: "https://github.com/user/test-repo.git", | |
| 299 | + name: expect.stringMatching(/^devbox-\d+$/), | |
| 300 | + prompt: "test prompt", | |
| 301 | + idempotencyKey: undefined, | |
| 302 | + agent: undefined, | |
| 303 | + config: undefined, | |
| 239 | 304 | }); |
| 240 | 305 | }); |
| 241 | 306 |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | import { env } from "../env.js"; |
| 5 | 5 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 6 | 6 | import { startRemoteTUIChat } from "../ui/index.js"; |
| 7 | +import { gracefulExit } from "../util/exit.js"; | |
| 7 | 8 | import { getRepoUrl } from "../util/git.js"; |
| 8 | 9 | import { logger } from "../util/logger.js"; |
| 9 | 10 | import { readStdinSync } from "../util/stdin.js"; |
| @@ -16,6 +17,7 @@ | ||
| 16 | 17 | start?: boolean; |
| 17 | 18 | branch?: string; |
| 18 | 19 | repo?: string; |
| 20 | + config?: string; | |
| 19 | 21 | } = {}, |
| 20 | 22 | ) { |
| 21 | 23 | // Check if prompt should come from stdin instead of parameter |
| @@ -74,7 +76,7 @@ | ||
| 74 | 76 | console.error( |
| 75 | 77 | chalk.red("Not authenticated. Please run 'cn login' first."), |
| 76 | 78 | ); |
| 77 | - process.exit(1); | |
| 79 | + await gracefulExit(1); | |
| 78 | 80 | } |
| 79 | 81 | |
| 80 | 82 | const accessToken = getAccessToken(authConfig); |
| @@ -84,6 +86,8 @@ | ||
| 84 | 86 | name: `devbox-${Date.now()}`, |
| 85 | 87 | prompt: actualPrompt, |
| 86 | 88 | idempotencyKey: options.idempotencyKey, |
| 89 | + agent: options.config, | |
| 90 | + config: options.config, | |
| 87 | 91 | }; |
| 88 | 92 | |
| 89 | 93 | // Add branchName to request body if branch option is provided |
| @@ -154,6 +158,6 @@ | ||
| 154 | 158 | logger.error( |
| 155 | 159 | chalk.red(`Failed to create remote environment: ${error.message}`), |
| 156 | 160 | ); |
| 157 | - process.exit(1); | |
| 161 | + await gracefulExit(1); | |
| 158 | 162 | } |
| 159 | 163 | } |
| @@ -1,7 +1,9 @@ | ||
| 1 | -import type { Session, ToolCallState, ToolStatus } from "core/index.js"; | |
| 1 | +import type { Session, ToolStatus } from "core/index.js"; | |
| 2 | 2 | |
| 3 | +import { services } from "../services/index.js"; | |
| 3 | 4 | import { streamChatResponse } from "../stream/streamChatResponse.js"; |
| 4 | 5 | import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; |
| 6 | +import { logger } from "../util/logger.js"; | |
| 5 | 7 | |
| 6 | 8 | // Modified version of streamChatResponse that supports interruption |
| 7 | 9 | export async function streamChatResponseWithInterruption( |
| @@ -38,47 +40,11 @@ | ||
| 38 | 40 | // This callback is just for notification/UI updates |
| 39 | 41 | // The tool call state is already created and added by handleToolCalls |
| 40 | 42 | }, |
| 41 | - onToolResult: (result: string, toolName: string, status: ToolStatus) => { | |
| 42 | - // Update only the tool call state status | |
| 43 | - // The actual result is already added as a separate message by handleToolCalls | |
| 44 | - for (let i = state.session.history.length - 1; i >= 0; i--) { | |
| 45 | - const item = state.session.history[i]; | |
| 46 | - if (item.toolCallStates) { | |
| 47 | - const toolState = item.toolCallStates.find( | |
| 48 | - (ts: ToolCallState) => | |
| 49 | - ts.toolCall.function.name === toolName && | |
| 50 | - (ts.status === "calling" || ts.status === "generated"), | |
| 51 | - ); | |
| 52 | - if (toolState) { | |
| 53 | - // Only update the status, not the output | |
| 54 | - toolState.status = status; | |
| 55 | - break; | |
| 56 | - } | |
| 57 | - } | |
| 58 | - } | |
| 43 | + onToolResult: (_result: string, _toolName: string, _status: ToolStatus) => { | |
| 44 | + // No-op when using ChatHistoryService; it updates tool states/results | |
| 59 | 45 | }, |
| 60 | - onToolError: (error: string, toolName?: string) => { | |
| 61 | - // Only update the tool call state to errored status when tool name is provided | |
| 62 | - // The error message is already added as a separate tool result message | |
| 63 | - // by handleToolCalls/preprocessStreamedToolCalls/executeStreamedToolCalls | |
| 64 | - if (toolName) { | |
| 65 | - // Find and update the corresponding tool call state | |
| 66 | - for (let i = state.session.history.length - 1; i >= 0; i--) { | |
| 67 | - const item = state.session.history[i]; | |
| 68 | - if (item.toolCallStates) { | |
| 69 | - const toolState = item.toolCallStates.find( | |
| 70 | - (ts: ToolCallState) => | |
| 71 | - ts.toolCall.function.name === toolName && | |
| 72 | - (ts.status === "calling" || ts.status === "generated"), | |
| 73 | - ); | |
| 74 | - if (toolState) { | |
| 75 | - // Only update the status, not the output | |
| 76 | - toolState.status = "errored"; | |
| 77 | - break; | |
| 78 | - } | |
| 79 | - } | |
| 80 | - } | |
| 81 | - } | |
| 46 | + onToolError: (_error: string, _toolName?: string) => { | |
| 47 | + // No-op; errors are added to history via handleToolCalls flow | |
| 82 | 48 | }, |
| 83 | 49 | onToolPermissionRequest: ( |
| 84 | 50 | toolName: string, |
| @@ -95,25 +61,33 @@ | ||
| 95 | 61 | toolCallPreview, |
| 96 | 62 | }; |
| 97 | 63 | |
| 98 | - // Add a system message indicating permission is needed | |
| 99 | - state.session.history.push({ | |
| 100 | - message: { | |
| 101 | - role: "system", | |
| 102 | - content: `WARNING: Tool ${toolName} requires permission`, | |
| 103 | - }, | |
| 104 | - contextItems: [], | |
| 105 | - }); | |
| 64 | + // Add a system message indicating permission is needed via service | |
| 65 | + try { | |
| 66 | + services.chatHistory.addSystemMessage( | |
| 67 | + `WARNING: Tool ${toolName} requires permission`, | |
| 68 | + ); | |
| 69 | + } catch (err) { | |
| 70 | + // Do not mutate session history; ChatHistoryService is the source of truth | |
| 71 | + logger.error( | |
| 72 | + "Failed to add system message via ChatHistoryService", | |
| 73 | + err, | |
| 74 | + { context: "onToolPermissionRequest", toolName, requestId }, | |
| 75 | + ); | |
| 76 | + } | |
| 106 | 77 | |
| 107 | 78 | // Don't wait here - the streamChatResponse will handle waiting |
| 108 | 79 | }, |
| 109 | 80 | onSystemMessage: (message: string) => { |
| 110 | - state.session.history.push({ | |
| 111 | - message: { | |
| 112 | - role: "system", | |
| 113 | - content: message, | |
| 114 | - }, | |
| 115 | - contextItems: [], | |
| 116 | - }); | |
| 81 | + try { | |
| 82 | + services.chatHistory.addSystemMessage(message); | |
| 83 | + } catch (err) { | |
| 84 | + // Do not mutate session history; ChatHistoryService is the source of truth | |
| 85 | + logger.error( | |
| 86 | + "Failed to add system message via ChatHistoryService", | |
| 87 | + err, | |
| 88 | + { context: "onSystemMessage" }, | |
| 89 | + ); | |
| 90 | + } | |
| 117 | 91 | }, |
| 118 | 92 | }; |
| 119 | 93 |
| @@ -25,6 +25,7 @@ | ||
| 25 | 25 | ensureOrganization: vi.fn(), |
| 26 | 26 | getOrganizationId: vi.fn(), |
| 27 | 27 | isAuthenticated: vi.fn(() => false), |
| 28 | + isAuthenticatedConfig: vi.fn(() => false), | |
| 28 | 29 | })); |
| 29 | 30 | |
| 30 | 31 | vi.mock("../onboarding.js", () => ({ |
| @@ -1,27 +1,27 @@ | ||
| 1 | -import { exec } from "child_process"; | |
| 2 | -import { promisify } from "util"; | |
| 3 | - | |
| 4 | 1 | import chalk from "chalk"; |
| 5 | 2 | import type { ChatHistoryItem } from "core/index.js"; |
| 6 | 3 | import express, { Request, Response } from "express"; |
| 7 | 4 | |
| 8 | -import { getAssistantSlug } from "../auth/workos.js"; | |
| 5 | +import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; | |
| 9 | 6 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 10 | 7 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 11 | 8 | import { |
| 12 | 9 | getService, |
| 13 | 10 | initializeServices, |
| 14 | 11 | SERVICE_NAMES, |
| 12 | + services, | |
| 15 | 13 | } from "../services/index.js"; |
| 16 | 14 | import { |
| 17 | 15 | AuthServiceState, |
| 18 | 16 | ConfigServiceState, |
| 19 | 17 | ModelServiceState, |
| 20 | 18 | } from "../services/types.js"; |
| 21 | -import { createSession, updateSessionHistory } from "../session.js"; | |
| 19 | +import { createSession, getSessionPersistenceSnapshot } from "../session.js"; | |
| 22 | 20 | import { constructSystemMessage } from "../systemMessage.js"; |
| 23 | 21 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 22 | +import { gracefulExit } from "../util/exit.js"; | |
| 24 | 23 | import { formatError } from "../util/formatError.js"; |
| 24 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 25 | 25 | import { logger } from "../util/logger.js"; |
| 26 | 26 | import { readStdinSync } from "../util/stdin.js"; |
| 27 | 27 | |
| @@ -31,13 +31,14 @@ | ||
| 31 | 31 | type ServerState, |
| 32 | 32 | } from "./serve.helpers.js"; |
| 33 | 33 | |
| 34 | -const execAsync = promisify(exec); | |
| 35 | - | |
| 36 | 34 | interface ServeOptions extends ExtendedCommandOptions { |
| 37 | 35 | timeout?: string; |
| 38 | 36 | port?: string; |
| 37 | + /** Storage identifier for remote sync */ | |
| 38 | + id?: string; | |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | +// eslint-disable-next-line max-statements | |
| 41 | 42 | export async function serve(prompt?: string, options: ServeOptions = {}) { |
| 42 | 43 | // Check if prompt should come from stdin instead of parameter |
| 43 | 44 | let actualPrompt = prompt; |
| @@ -83,6 +84,7 @@ | ||
| 83 | 84 | if (authState.organizationId) { |
| 84 | 85 | telemetryService.updateOrganization(authState.organizationId); |
| 85 | 86 | } |
| 87 | + const accessToken = getAccessToken(authState.authConfig); | |
| 86 | 88 | |
| 87 | 89 | // Log configuration information |
| 88 | 90 | const organizationId = authState.organizationId || "personal"; |
| @@ -122,6 +124,13 @@ | ||
| 122 | 124 | |
| 123 | 125 | const session = createSession(initialHistory); |
| 124 | 126 | |
| 127 | + // Align ChatHistoryService with server session and enable remote mode | |
| 128 | + try { | |
| 129 | + await services.chatHistory.initialize(session, false); | |
| 130 | + } catch { | |
| 131 | + // Fallback: continue even if service init fails; stream will still work with arrays | |
| 132 | + } | |
| 133 | + | |
| 125 | 134 | // Initialize server state |
| 126 | 135 | const state: ServerState = { |
| 127 | 136 | session, |
| @@ -136,6 +145,32 @@ | ||
| 136 | 145 | pendingPermission: null, |
| 137 | 146 | }; |
| 138 | 147 | |
| 148 | + const syncSessionHistory = () => { | |
| 149 | + try { | |
| 150 | + state.session.history = services.chatHistory.getHistory(); | |
| 151 | + } catch (e) { | |
| 152 | + logger.debug( | |
| 153 | + `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, | |
| 154 | + ); | |
| 155 | + } | |
| 156 | + }; | |
| 157 | + | |
| 158 | + const storageSyncService = services.storageSync; | |
| 159 | + let storageSyncActive = await storageSyncService.startFromOptions({ | |
| 160 | + storageOption: options.id, | |
| 161 | + accessToken, | |
| 162 | + syncSessionHistory, | |
| 163 | + getSessionSnapshot: () => getSessionPersistenceSnapshot(state.session), | |
| 164 | + isActive: () => state.serverRunning, | |
| 165 | + }); | |
| 166 | + | |
| 167 | + const stopStorageSync = () => { | |
| 168 | + if (storageSyncActive) { | |
| 169 | + storageSyncService.stop(); | |
| 170 | + storageSyncActive = false; | |
| 171 | + } | |
| 172 | + }; | |
| 173 | + | |
| 139 | 174 | // Record session start |
| 140 | 175 | telemetryService.recordSessionStart(); |
| 141 | 176 | telemetryService.startActiveTime(); |
| @@ -146,6 +181,7 @@ | ||
| 146 | 181 | // GET /state - Return the current state |
| 147 | 182 | app.get("/state", (_req: Request, res: Response) => { |
| 148 | 183 | state.lastActivity = Date.now(); |
| 184 | + syncSessionHistory(); | |
| 149 | 185 | res.json({ |
| 150 | 186 | session: state.session, // Return session directly instead of converting |
| 151 | 187 | isProcessing: state.isProcessing, |
| @@ -221,34 +257,25 @@ | ||
| 221 | 257 | state.lastActivity = Date.now(); |
| 222 | 258 | |
| 223 | 259 | try { |
| 224 | - // First check if we're in a git repository | |
| 225 | - await execAsync("git rev-parse --git-dir"); | |
| 260 | + const diffResult = await getGitDiffSnapshot(); | |
| 226 | 261 | |
| 227 | - // Get the diff against main branch | |
| 228 | - const { stdout } = await execAsync("git diff main"); | |
| 229 | - | |
| 230 | - res.json({ | |
| 231 | - diff: stdout, | |
| 232 | - }); | |
| 233 | - } catch (error: any) { | |
| 234 | - // Git diff returns exit code 1 when there are differences, which is normal | |
| 235 | - if (error.code === 1 && error.stdout) { | |
| 236 | - res.json({ | |
| 237 | - diff: error.stdout, | |
| 238 | - }); | |
| 239 | - } else if (error.code === 128) { | |
| 240 | - // Handle case where we're not in a git repo or main branch doesn't exist | |
| 262 | + if (!diffResult.repoFound) { | |
| 241 | 263 | res.status(404).json({ |
| 242 | 264 | error: "Not in a git repository or main branch doesn't exist", |
| 243 | 265 | diff: "", |
| 244 | 266 | }); |
| 245 | - } else { | |
| 246 | - logger.error(`Git diff error: ${formatError(error)}`); | |
| 247 | - res.status(500).json({ | |
| 248 | - error: `Failed to get git diff: ${formatError(error)}`, | |
| 249 | - diff: "", | |
| 250 | - }); | |
| 267 | + return; | |
| 251 | 268 | } |
| 269 | + | |
| 270 | + res.json({ | |
| 271 | + diff: diffResult.diff, | |
| 272 | + }); | |
| 273 | + } catch (error) { | |
| 274 | + logger.error(`Git diff error: ${formatError(error)}`); | |
| 275 | + res.status(500).json({ | |
| 276 | + error: `Failed to get git diff: ${formatError(error)}`, | |
| 277 | + diff: "", | |
| 278 | + }); | |
| 252 | 279 | } |
| 253 | 280 | }); |
| 254 | 281 | |
| @@ -269,6 +296,7 @@ | ||
| 269 | 296 | |
| 270 | 297 | // Set server running flag to false to stop processing |
| 271 | 298 | state.serverRunning = false; |
| 299 | + stopStorageSync(); | |
| 272 | 300 | |
| 273 | 301 | // Abort any current processing |
| 274 | 302 | if (state.currentAbortController) { |
| @@ -285,12 +313,16 @@ | ||
| 285 | 313 | } |
| 286 | 314 | |
| 287 | 315 | // Give a moment for the response to be sent |
| 288 | - setTimeout(() => { | |
| 316 | + const handleExitResponse = () => { | |
| 289 | 317 | server.close(() => { |
| 290 | 318 | telemetryService.stopActiveTime(); |
| 291 | - process.exit(0); | |
| 319 | + gracefulExit(0).catch((err) => { | |
| 320 | + logger.error(`Graceful exit failed: ${formatError(err)}`); | |
| 321 | + process.exit(1); | |
| 322 | + }); | |
| 292 | 323 | }); |
| 293 | - }, 100); | |
| 324 | + }; | |
| 325 | + setTimeout(handleExitResponse, 100); | |
| 294 | 326 | }); |
| 295 | 327 | |
| 296 | 328 | const server = app.listen(port, () => { |
| @@ -328,6 +360,27 @@ | ||
| 328 | 360 | }); |
| 329 | 361 | |
| 330 | 362 | // Process messages from the queue |
| 363 | + function removePartialAssistantMessage(state: ServerState) { | |
| 364 | + try { | |
| 365 | + const svcHistory = services.chatHistory.getHistory(); | |
| 366 | + const last = svcHistory[svcHistory.length - 1]; | |
| 367 | + if (last && last.message.role === "assistant" && !last.message.content) { | |
| 368 | + const trimmed = svcHistory.slice(0, -1); | |
| 369 | + services.chatHistory.setHistory(trimmed); | |
| 370 | + } | |
| 371 | + } catch { | |
| 372 | + const lastMessage = | |
| 373 | + state.session.history[state.session.history.length - 1]; | |
| 374 | + if ( | |
| 375 | + lastMessage && | |
| 376 | + lastMessage.message.role === "assistant" && | |
| 377 | + !lastMessage.message.content | |
| 378 | + ) { | |
| 379 | + state.session.history.pop(); | |
| 380 | + } | |
| 381 | + } | |
| 382 | + } | |
| 383 | + | |
| 331 | 384 | async function processMessages(state: ServerState, llmApi: any) { |
| 332 | 385 | while (state.messageQueue.length > 0 && state.serverRunning) { |
| 333 | 386 | const userMessage = state.messageQueue.shift()!; |
| @@ -335,11 +388,16 @@ | ||
| 335 | 388 | state.shouldInterrupt = false; |
| 336 | 389 | state.lastActivity = Date.now(); |
| 337 | 390 | |
| 338 | - // Add user message to history | |
| 339 | - state.session.history.push({ | |
| 340 | - message: { role: "user", content: userMessage }, | |
| 341 | - contextItems: [], | |
| 342 | - }); | |
| 391 | + // Add user message via ChatHistoryService (single source of truth) | |
| 392 | + try { | |
| 393 | + services.chatHistory.addUserMessage(userMessage); | |
| 394 | + } catch { | |
| 395 | + // Fallback to local array if service unavailable | |
| 396 | + state.session.history.push({ | |
| 397 | + message: { role: "user", content: userMessage }, | |
| 398 | + contextItems: [], | |
| 399 | + }); | |
| 400 | + } | |
| 343 | 401 | |
| 344 | 402 | try { |
| 345 | 403 | // Create new abort controller for this response |
| @@ -353,31 +411,26 @@ | ||
| 353 | 411 | () => state.shouldInterrupt, |
| 354 | 412 | ); |
| 355 | 413 | |
| 356 | - // Save session after successful response | |
| 357 | - updateSessionHistory(state.session.history); | |
| 414 | + // No direct persistence here; ChatHistoryService handles persistence when appropriate | |
| 358 | 415 | |
| 359 | 416 | state.lastActivity = Date.now(); |
| 360 | 417 | } catch (e: any) { |
| 361 | 418 | if (e.name === "AbortError") { |
| 362 | 419 | logger.debug("Response interrupted"); |
| 363 | - // Remove the partial assistant message if it exists | |
| 364 | - const lastMessage = | |
| 365 | - state.session.history[state.session.history.length - 1]; | |
| 366 | - if ( | |
| 367 | - lastMessage && | |
| 368 | - lastMessage.message.role === "assistant" && | |
| 369 | - !lastMessage.message.content | |
| 370 | - ) { | |
| 371 | - state.session.history.pop(); | |
| 372 | - } | |
| 420 | + // Remove any partial assistant message | |
| 421 | + removePartialAssistantMessage(state); | |
| 373 | 422 | } else { |
| 374 | 423 | logger.error(`Error: ${formatError(e)}`); |
| 375 | - // Add error message to chat history and display messages | |
| 424 | + // Add error message via ChatHistoryService | |
| 376 | 425 | const errorMessage = `Error: ${formatError(e)}`; |
| 377 | - state.session.history.push({ | |
| 378 | - message: { role: "assistant", content: errorMessage }, | |
| 379 | - contextItems: [], | |
| 380 | - }); | |
| 426 | + try { | |
| 427 | + services.chatHistory.addAssistantMessage(errorMessage); | |
| 428 | + } catch { | |
| 429 | + state.session.history.push({ | |
| 430 | + message: { role: "assistant", content: errorMessage }, | |
| 431 | + contextItems: [], | |
| 432 | + }); | |
| 433 | + } | |
| 381 | 434 | } |
| 382 | 435 | } finally { |
| 383 | 436 | state.currentAbortController = null; |
| @@ -395,9 +448,13 @@ | ||
| 395 | 448 | ), |
| 396 | 449 | ); |
| 397 | 450 | state.serverRunning = false; |
| 451 | + stopStorageSync(); | |
| 398 | 452 | server.close(() => { |
| 399 | 453 | telemetryService.stopActiveTime(); |
| 400 | - process.exit(0); | |
| 454 | + gracefulExit(0).catch((err) => { | |
| 455 | + logger.error(`Graceful exit failed: ${formatError(err)}`); | |
| 456 | + process.exit(1); | |
| 457 | + }); | |
| 401 | 458 | }); |
| 402 | 459 | if (inactivityChecker) { |
| 403 | 460 | clearInterval(inactivityChecker); |
| @@ -410,13 +467,17 @@ | ||
| 410 | 467 | process.on("SIGINT", () => { |
| 411 | 468 | console.log(chalk.yellow("\nShutting down server...")); |
| 412 | 469 | state.serverRunning = false; |
| 470 | + stopStorageSync(); | |
| 413 | 471 | if (inactivityChecker) { |
| 414 | 472 | clearInterval(inactivityChecker); |
| 415 | 473 | inactivityChecker = null; |
| 416 | 474 | } |
| 417 | 475 | server.close(() => { |
| 418 | 476 | telemetryService.stopActiveTime(); |
| 419 | - process.exit(0); | |
| 477 | + gracefulExit(0).catch((err) => { | |
| 478 | + logger.error(`Graceful exit failed: ${formatError(err)}`); | |
| 479 | + process.exit(1); | |
| 480 | + }); | |
| 420 | 481 | }); |
| 421 | 482 | }); |
| 422 | 483 | } |
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | * @param model The model configuration |
| 29 | 29 | * @param llmApi The LLM API instance |
| 30 | 30 | * @param callbacks Optional callbacks for streaming updates |
| 31 | + * @param abortController Optional abort controller for cancellation | |
| 31 | 32 | * @returns The compacted history with compaction index |
| 32 | 33 | */ |
| 33 | 34 | export async function compactChatHistory( |
| @@ -35,6 +36,7 @@ | ||
| 35 | 36 | model: ModelConfig, |
| 36 | 37 | llmApi: BaseLlmApi, |
| 37 | 38 | callbacks?: CompactionCallbacks, |
| 39 | + abortController?: AbortController, | |
| 38 | 40 | ): Promise<CompactionResult> { |
| 39 | 41 | // Create a prompt to summarize the conversation |
| 40 | 42 | const compactionPrompt: ChatHistoryItem = { |
| @@ -80,8 +82,8 @@ | ||
| 80 | 82 | historyForCompaction = [...historyToUse, compactionPrompt]; |
| 81 | 83 | } |
| 82 | 84 | |
| 83 | - // Stream the compaction response | |
| 84 | - const controller = new AbortController(); | |
| 85 | + // Stream the compaction response (service drives updates; this collects content locally) | |
| 86 | + const controller = abortController || new AbortController(); | |
| 85 | 87 | |
| 86 | 88 | let compactionContent = ""; |
| 87 | 89 | const streamCallbacks: StreamCallbacks = { |
| @@ -19,25 +19,14 @@ | ||
| 19 | 19 | import { env } from "./env.js"; |
| 20 | 20 | import { MCPService } from "./services/MCPService.js"; |
| 21 | 21 | |
| 22 | -export function getLlmApi( | |
| 23 | - assistant: AssistantUnrolled, | |
| 24 | - authConfig: AuthConfig, | |
| 25 | -): [BaseLlmApi, ModelConfig] { | |
| 26 | - if (!assistant.models || assistant.models.length === 0) { | |
| 27 | - throw new Error("No models found in the configured assistant"); | |
| 28 | - } | |
| 29 | - | |
| 30 | - const model = assistant.models?.find( | |
| 31 | - (model) => | |
| 32 | - model?.roles?.includes("chat") || (model && model.roles === undefined), | |
| 33 | - ); | |
| 34 | - | |
| 35 | - if (!model) { | |
| 36 | - throw new Error( | |
| 37 | - "No models with the chat role found in the configured assistant", | |
| 38 | - ); | |
| 39 | - } | |
| 40 | - | |
| 22 | +/** | |
| 23 | + * Creates an LLM API instance from a ModelConfig and auth configuration | |
| 24 | + * Handles special logic for continue-proxy provider and constructs the API | |
| 25 | + */ | |
| 26 | +export function createLlmApi( | |
| 27 | + model: ModelConfig, | |
| 28 | + authConfig: AuthConfig | null, | |
| 29 | +): BaseLlmApi | null { | |
| 41 | 30 | const accessToken = getAccessToken(authConfig); |
| 42 | 31 | const organizationId = getOrganizationId(authConfig); |
| 43 | 32 | |
| @@ -50,9 +39,10 @@ | ||
| 50 | 39 | apiKey: accessToken ?? undefined, |
| 51 | 40 | env: { |
| 52 | 41 | apiKeyLocation: (model as any).apiKeyLocation, |
| 53 | - // envSecretLocations: model.env, | |
| 54 | - orgScopeId: organizationId, | |
| 55 | - proxyUrl: undefined, // TODO | |
| 42 | + orgScopeId: organizationId ?? null, | |
| 43 | + proxyUrl: | |
| 44 | + (model as { onPremProxyUrl: string | undefined }) | |
| 45 | + .onPremProxyUrl ?? undefined, | |
| 56 | 46 | }, |
| 57 | 47 | } |
| 58 | 48 | : { |
| @@ -63,7 +53,29 @@ | ||
| 63 | 53 | env: model.env, |
| 64 | 54 | }; |
| 65 | 55 | |
| 66 | - const llmApi = constructLlmApi(config); | |
| 56 | + return constructLlmApi(config) ?? null; | |
| 57 | +} | |
| 58 | + | |
| 59 | +export function getLlmApi( | |
| 60 | + assistant: AssistantUnrolled, | |
| 61 | + authConfig: AuthConfig, | |
| 62 | +): [BaseLlmApi, ModelConfig] { | |
| 63 | + if (!assistant.models || assistant.models.length === 0) { | |
| 64 | + throw new Error("No models found in the configured assistant"); | |
| 65 | + } | |
| 66 | + | |
| 67 | + const model = assistant.models?.find( | |
| 68 | + (model) => | |
| 69 | + model?.roles?.includes("chat") || (model && model.roles === undefined), | |
| 70 | + ); | |
| 71 | + | |
| 72 | + if (!model) { | |
| 73 | + throw new Error( | |
| 74 | + "No models with the chat role found in the configured assistant", | |
| 75 | + ); | |
| 76 | + } | |
| 77 | + | |
| 78 | + const llmApi = createLlmApi(model, authConfig); | |
| 67 | 79 | |
| 68 | 80 | if (!llmApi) { |
| 69 | 81 | throw new Error( |
| @@ -55,7 +55,7 @@ | ||
| 55 | 55 | const config = await loadFromSource( |
| 56 | 56 | configSource, |
| 57 | 57 | accessToken, |
| 58 | - organizationId, | |
| 58 | + organizationId ?? null, | |
| 59 | 59 | apiClient, |
| 60 | 60 | ); |
| 61 | 61 | |
| @@ -229,9 +229,18 @@ | ||
| 229 | 229 | |
| 230 | 230 | if (assistants.length > 0) { |
| 231 | 231 | const result = assistants[0].configResult; |
| 232 | - if (result.errors?.length || !result.config) { | |
| 232 | + if (!result.config) { | |
| 233 | 233 | throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); |
| 234 | 234 | } |
| 235 | + | |
| 236 | + const errors = result.errors; | |
| 237 | + if (errors?.some((e: any) => e.fatal)) { | |
| 238 | + throw new Error( | |
| 239 | + errors.map((e: any) => e.message).join("\n") ?? | |
| 240 | + "Failed to load assistant.", | |
| 241 | + ); | |
| 242 | + } | |
| 243 | + | |
| 235 | 244 | return result.config as AssistantUnrolled; |
| 236 | 245 | } |
| 237 | 246 | |
| @@ -373,8 +382,12 @@ | ||
| 373 | 382 | }); |
| 374 | 383 | |
| 375 | 384 | const result = resp.configResult; |
| 376 | - if (result.errors?.length || !result.config) { | |
| 377 | - throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); | |
| 385 | + const errors = result.errors; | |
| 386 | + if (errors?.some((e: any) => e.fatal)) { | |
| 387 | + throw new Error( | |
| 388 | + errors.map((e: any) => e.message).join("\n") ?? | |
| 389 | + "Failed to load assistant.", | |
| 390 | + ); | |
| 378 | 391 | } |
| 379 | 392 | |
| 380 | 393 | return result.config as AssistantUnrolled; |
| @@ -0,0 +1,258 @@ | ||
| 1 | +import { execSync } from "child_process"; | |
| 2 | +import fs from "fs/promises"; | |
| 3 | +import path from "path"; | |
| 4 | + | |
| 5 | +import { afterEach, beforeEach, describe, expect, it } from "vitest"; | |
| 6 | + | |
| 7 | +import { | |
| 8 | + cleanupTestContext, | |
| 9 | + createTestConfig, | |
| 10 | + createTestContext, | |
| 11 | + runCLI, | |
| 12 | + type CLITestContext, | |
| 13 | +} from "../test-helpers/cli-helpers.js"; | |
| 14 | + | |
| 15 | +describe("E2E: Git Branch Display", () => { | |
| 16 | + let context: CLITestContext; | |
| 17 | + let originalCwd: string; | |
| 18 | + | |
| 19 | + const testConfig = `name: Test Assistant | |
| 20 | +version: 1.0.0 | |
| 21 | +schema: v1 | |
| 22 | +models: | |
| 23 | + - model: gpt-4 | |
| 24 | + provider: openai | |
| 25 | + apiKey: test-key | |
| 26 | + roles: | |
| 27 | + - chat`; | |
| 28 | + | |
| 29 | + beforeEach(async () => { | |
| 30 | + context = await createTestContext(); | |
| 31 | + originalCwd = process.cwd(); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + afterEach(async () => { | |
| 35 | + await cleanupTestContext(context); | |
| 36 | + process.chdir(originalCwd); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + describe("git branch display in status bar", () => { | |
| 40 | + it("should show branch name when in a git repository", async () => { | |
| 41 | + // Initialize a git repo in the test directory | |
| 42 | + process.chdir(context.testDir); | |
| 43 | + | |
| 44 | + try { | |
| 45 | + // Initialize git repo | |
| 46 | + execSync("git init", { stdio: "ignore" }); | |
| 47 | + execSync("git config user.email 'test@example.com'", { | |
| 48 | + stdio: "ignore", | |
| 49 | + }); | |
| 50 | + execSync("git config user.name 'Test User'", { stdio: "ignore" }); | |
| 51 | + | |
| 52 | + // Create a test file and initial commit | |
| 53 | + await fs.writeFile( | |
| 54 | + path.join(context.testDir, "test.txt"), | |
| 55 | + "test content", | |
| 56 | + ); | |
| 57 | + execSync("git add .", { stdio: "ignore" }); | |
| 58 | + execSync("git commit -m 'Initial commit'", { stdio: "ignore" }); | |
| 59 | + | |
| 60 | + // Create and checkout a test branch | |
| 61 | + const testBranchName = "feature/test-branch"; | |
| 62 | + execSync(`git checkout -b ${testBranchName}`, { stdio: "ignore" }); | |
| 63 | + | |
| 64 | + // Create config file | |
| 65 | + await createTestConfig(context, testConfig); | |
| 66 | + | |
| 67 | + // Run CLI in TUI mode - it should fail quickly but show the branch in output | |
| 68 | + const result = await runCLI(context, { | |
| 69 | + args: ["--config", context.configPath!, "--help"], | |
| 70 | + timeout: 3000, | |
| 71 | + }); | |
| 72 | + | |
| 73 | + // The help command should succeed | |
| 74 | + expect(result.exitCode).toBe(0); | |
| 75 | + expect(result.stdout).toContain("Continue CLI"); | |
| 76 | + | |
| 77 | + // Now let's test that our git utils work in this context | |
| 78 | + // We can't easily test the full TUI display, but we can verify the git functions work | |
| 79 | + const { getGitBranch } = await import("../util/git.js"); | |
| 80 | + const branch = getGitBranch(); | |
| 81 | + expect(branch).toBe(testBranchName); | |
| 82 | + } catch (error) { | |
| 83 | + // Skip test if git is not available or fails | |
| 84 | + console.warn("Skipping git branch test - git not available:", error); | |
| 85 | + return; | |
| 86 | + } | |
| 87 | + }); | |
| 88 | + | |
| 89 | + it("should handle non-git directory gracefully", async () => { | |
| 90 | + // Don't initialize git in test directory | |
| 91 | + process.chdir(context.testDir); | |
| 92 | + | |
| 93 | + await createTestConfig(context, testConfig); | |
| 94 | + | |
| 95 | + // Test that git functions return null in non-git directory | |
| 96 | + const { getGitBranch, isGitRepo } = await import("../util/git.js"); | |
| 97 | + | |
| 98 | + expect(isGitRepo()).toBe(false); | |
| 99 | + expect(getGitBranch()).toBeNull(); | |
| 100 | + | |
| 101 | + // CLI should still work without git | |
| 102 | + const result = await runCLI(context, { | |
| 103 | + args: ["--help"], | |
| 104 | + timeout: 3000, | |
| 105 | + }); | |
| 106 | + | |
| 107 | + expect(result.exitCode).toBe(0); | |
| 108 | + expect(result.stdout).toContain("Continue CLI"); | |
| 109 | + }); | |
| 110 | + | |
| 111 | + it("should handle detached HEAD state", async () => { | |
| 112 | + process.chdir(context.testDir); | |
| 113 | + | |
| 114 | + try { | |
| 115 | + // Initialize git repo | |
| 116 | + execSync("git init", { stdio: "ignore" }); | |
| 117 | + execSync("git config user.email 'test@example.com'", { | |
| 118 | + stdio: "ignore", | |
| 119 | + }); | |
| 120 | + execSync("git config user.name 'Test User'", { stdio: "ignore" }); | |
| 121 | + | |
| 122 | + // Create initial commit | |
| 123 | + await fs.writeFile( | |
| 124 | + path.join(context.testDir, "test.txt"), | |
| 125 | + "test content", | |
| 126 | + ); | |
| 127 | + execSync("git add .", { stdio: "ignore" }); | |
| 128 | + execSync("git commit -m 'Initial commit'", { stdio: "ignore" }); | |
| 129 | + | |
| 130 | + // Create another commit | |
| 131 | + await fs.writeFile( | |
| 132 | + path.join(context.testDir, "test2.txt"), | |
| 133 | + "test content 2", | |
| 134 | + ); | |
| 135 | + execSync("git add .", { stdio: "ignore" }); | |
| 136 | + execSync("git commit -m 'Second commit'", { stdio: "ignore" }); | |
| 137 | + | |
| 138 | + // Get first commit hash and checkout to detached HEAD | |
| 139 | + const firstCommit = execSync( | |
| 140 | + "git rev-list --max-count=1 --reverse HEAD", | |
| 141 | + { | |
| 142 | + encoding: "utf-8", | |
| 143 | + }, | |
| 144 | + ).trim(); | |
| 145 | + execSync(`git checkout ${firstCommit}`, { stdio: "ignore" }); | |
| 146 | + | |
| 147 | + // Test git functions in detached HEAD state | |
| 148 | + const { getGitBranch, isGitRepo } = await import("../util/git.js"); | |
| 149 | + | |
| 150 | + expect(isGitRepo()).toBe(true); | |
| 151 | + // In detached HEAD state, git branch --show-current returns empty string | |
| 152 | + // which our function converts to null | |
| 153 | + expect(getGitBranch()).toBeNull(); | |
| 154 | + } catch (error) { | |
| 155 | + // Skip test if git operations fail | |
| 156 | + console.warn( | |
| 157 | + "Skipping detached HEAD test - git operations failed:", | |
| 158 | + error, | |
| 159 | + ); | |
| 160 | + return; | |
| 161 | + } | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("should handle branch names with special characters", async () => { | |
| 165 | + process.chdir(context.testDir); | |
| 166 | + | |
| 167 | + try { | |
| 168 | + // Initialize git repo | |
| 169 | + execSync("git init", { stdio: "ignore" }); | |
| 170 | + execSync("git config user.email 'test@example.com'", { | |
| 171 | + stdio: "ignore", | |
| 172 | + }); | |
| 173 | + execSync("git config user.name 'Test User'", { stdio: "ignore" }); | |
| 174 | + | |
| 175 | + // Create initial commit | |
| 176 | + await fs.writeFile( | |
| 177 | + path.join(context.testDir, "test.txt"), | |
| 178 | + "test content", | |
| 179 | + ); | |
| 180 | + execSync("git add .", { stdio: "ignore" }); | |
| 181 | + execSync("git commit -m 'Initial commit'", { stdio: "ignore" }); | |
| 182 | + | |
| 183 | + // Create branch with special characters | |
| 184 | + const specialBranchName = "feature/fix-123_with-dashes.and.dots"; | |
| 185 | + execSync(`git checkout -b "${specialBranchName}"`, { stdio: "ignore" }); | |
| 186 | + | |
| 187 | + // Test git functions | |
| 188 | + const { getGitBranch } = await import("../util/git.js"); | |
| 189 | + const branch = getGitBranch(); | |
| 190 | + expect(branch).toBe(specialBranchName); | |
| 191 | + } catch (error) { | |
| 192 | + // Skip test if git operations fail | |
| 193 | + console.warn( | |
| 194 | + "Skipping special characters test - git operations failed:", | |
| 195 | + error, | |
| 196 | + ); | |
| 197 | + return; | |
| 198 | + } | |
| 199 | + }); | |
| 200 | + }); | |
| 201 | + | |
| 202 | + describe("getRepoUrlText function with branch", () => { | |
| 203 | + it("should format repo URL with branch correctly", async () => { | |
| 204 | + process.chdir(context.testDir); | |
| 205 | + | |
| 206 | + try { | |
| 207 | + // Initialize git repo with remote | |
| 208 | + execSync("git init", { stdio: "ignore" }); | |
| 209 | + execSync("git config user.email 'test@example.com'", { | |
| 210 | + stdio: "ignore", | |
| 211 | + }); | |
| 212 | + execSync("git config user.name 'Test User'", { stdio: "ignore" }); | |
| 213 | + | |
| 214 | + // Add a fake remote | |
| 215 | + execSync( | |
| 216 | + "git remote add origin https://github.com/testuser/testrepo.git", | |
| 217 | + { stdio: "ignore" }, | |
| 218 | + ); | |
| 219 | + | |
| 220 | + // Create initial commit and branch | |
| 221 | + await fs.writeFile( | |
| 222 | + path.join(context.testDir, "test.txt"), | |
| 223 | + "test content", | |
| 224 | + ); | |
| 225 | + execSync("git add .", { stdio: "ignore" }); | |
| 226 | + execSync("git commit -m 'Initial commit'", { stdio: "ignore" }); | |
| 227 | + execSync("git checkout -b test-branch", { stdio: "ignore" }); | |
| 228 | + | |
| 229 | + // Test the formatting function | |
| 230 | + const { getResponsiveRepoText } = await import( | |
| 231 | + "../ui/hooks/useTUIChatHooks.js" | |
| 232 | + ); | |
| 233 | + const repoText = getResponsiveRepoText(); | |
| 234 | + | |
| 235 | + // Should include both repo and branch | |
| 236 | + expect(repoText).toEqual(""); | |
| 237 | + } catch (error) { | |
| 238 | + // Skip test if git operations fail | |
| 239 | + console.warn( | |
| 240 | + "Skipping repo URL formatting test - git operations failed:", | |
| 241 | + error, | |
| 242 | + ); | |
| 243 | + return; | |
| 244 | + } | |
| 245 | + }); | |
| 246 | + | |
| 247 | + it("should handle repo URL without branch when not in git repo", async () => { | |
| 248 | + process.chdir(context.testDir); | |
| 249 | + | |
| 250 | + // Test without git repo | |
| 251 | + const { getRepoUrlText } = await import("../ui/hooks/useTUIChatHooks.js"); | |
| 252 | + const repoText = getRepoUrlText(); | |
| 253 | + | |
| 254 | + // Should not contain branch separator | |
| 255 | + expect(repoText).toEqual(""); | |
| 256 | + }); | |
| 257 | + }); | |
| 258 | +}); |
| @@ -8,8 +8,8 @@ | ||
| 8 | 8 | } from "../test-helpers/cli-helpers.js"; |
| 9 | 9 | import { |
| 10 | 10 | cleanupMockLLMServer, |
| 11 | - type MockLLMServer, | |
| 12 | 11 | createMockLLMServer, |
| 12 | + type MockLLMServer, | |
| 13 | 13 | } from "../test-helpers/mock-llm-server.js"; |
| 14 | 14 | |
| 15 | 15 | describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { |
| @@ -80,9 +80,9 @@ | ||
| 80 | 80 | expect(userMessage.content).toBe("Hi there"); |
| 81 | 81 | }, 20000); |
| 82 | 82 | |
| 83 | - it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { | |
| 83 | + it("should create config but fail with invalid API key when no config exists", async () => { | |
| 84 | 84 | // This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY |
| 85 | - // when no config file exists in headless mode | |
| 85 | + // when no config file exists, but fails when the API key is invalid | |
| 86 | 86 | |
| 87 | 87 | const result = await runCLI(context, { |
| 88 | 88 | args: ["-p", "test prompt"], |
| @@ -90,13 +90,17 @@ | ||
| 90 | 90 | ANTHROPIC_API_KEY: "TEST-test-invalid-key-format", |
| 91 | 91 | CONTINUE_GLOBAL_DIR: context.testDir + "/.continue", |
| 92 | 92 | }, |
| 93 | - expectError: false, // Config creation succeeds even with invalid key | |
| 93 | + expectError: true, // API call should fail with invalid key | |
| 94 | 94 | timeout: 15000, |
| 95 | 95 | }); |
| 96 | 96 | |
| 97 | - // The CLI should create config and exit successfully in headless mode | |
| 98 | - // (it doesn't actually make API calls unless there's a valid provider setup) | |
| 99 | - expect(result.exitCode).toBe(0); | |
| 97 | + // The CLI should create config but fail due to invalid API key | |
| 98 | + // This is expected behavior - invalid API keys should cause authentication errors | |
| 99 | + expect(result.exitCode).toBe(1); | |
| 100 | + | |
| 101 | + // Should contain authentication error (not service initialization error) | |
| 102 | + expect(result.stderr).toContain("authentication_error"); | |
| 103 | + expect(result.stderr).toContain("invalid x-api-key"); | |
| 100 | 104 | |
| 101 | 105 | // Should NOT contain the old error about service initialization |
| 102 | 106 | expect(result.stderr).not.toContain("Failed to initialize ConfigService"); |
| @@ -16,6 +16,10 @@ | ||
| 16 | 16 | auto?: boolean; |
| 17 | 17 | config?: string; |
| 18 | 18 | |
| 19 | + // Session flags | |
| 20 | + resume?: boolean; | |
| 21 | + fork?: string; | |
| 22 | + | |
| 19 | 23 | // Permission flags |
| 20 | 24 | allow?: string[]; |
| 21 | 25 | ask?: string[]; |
| @@ -101,6 +105,29 @@ | ||
| 101 | 105 | return errors; |
| 102 | 106 | } |
| 103 | 107 | |
| 108 | +/** | |
| 109 | + * Validate session flags | |
| 110 | + */ | |
| 111 | +function validateSessionFlags(options: ValidationOptions): ValidationError[] { | |
| 112 | + const errors: ValidationError[] = []; | |
| 113 | + | |
| 114 | + if (options.resume && options.fork) { | |
| 115 | + errors.push({ | |
| 116 | + code: "CONFLICTING_SESSION_FLAGS", | |
| 117 | + message: "Error: Cannot use both --resume and --fork flags together", | |
| 118 | + }); | |
| 119 | + } | |
| 120 | + | |
| 121 | + if (options.fork !== undefined && (!options.fork || !options.fork.trim())) { | |
| 122 | + errors.push({ | |
| 123 | + code: "FORK_REQUIRES_SESSION_ID", | |
| 124 | + message: "Error: --fork requires a session ID (e.g., --fork abc123)", | |
| 125 | + }); | |
| 126 | + } | |
| 127 | + | |
| 128 | + return errors; | |
| 129 | +} | |
| 130 | + | |
| 104 | 131 | /** |
| 105 | 132 | * Validate config path exists (basic check) |
| 106 | 133 | */ |
| @@ -164,6 +191,7 @@ | ||
| 164 | 191 | validateSilentFlag, |
| 165 | 192 | validateFormatValue, |
| 166 | 193 | validateModeFlags, |
| 194 | + validateSessionFlags, | |
| 167 | 195 | validateConfigPath, |
| 168 | 196 | validatePermissionFlags, |
| 169 | 197 | ]; |
| @@ -191,5 +219,7 @@ | ||
| 191 | 219 | safeStderr(`\nFound ${errors.length} validation errors.\n`); |
| 192 | 220 | } |
| 193 | 221 | |
| 194 | - process.exit(1); | |
| 222 | + // Use async graceful exit without awaiting (we must satisfy never) | |
| 223 | + import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1)); | |
| 224 | + throw new Error("Exiting due to validation errors"); | |
| 195 | 225 | } |
| @@ -4,13 +4,14 @@ | ||
| 4 | 4 | |
| 5 | 5 | import chalk from "chalk"; |
| 6 | 6 | import open from "open"; |
| 7 | -import * as readlineSync from "readline-sync"; | |
| 8 | 7 | |
| 9 | 8 | import { env } from "./env.js"; |
| 10 | 9 | import { |
| 11 | - isValidAnthropicApiKey, | |
| 12 | 10 | getApiKeyValidationError, |
| 11 | + isValidAnthropicApiKey, | |
| 13 | 12 | } from "./util/apiKeyValidation.js"; |
| 13 | +import { gracefulExit } from "./util/exit.js"; | |
| 14 | +import { question, questionWithChoices } from "./util/prompt.js"; | |
| 14 | 15 | import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; |
| 15 | 16 | |
| 16 | 17 | const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); |
| @@ -51,10 +52,12 @@ | ||
| 51 | 52 | console.log(chalk.white("1. 💳 Sign up for models add-on")); |
| 52 | 53 | console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); |
| 53 | 54 | |
| 54 | - const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { | |
| 55 | - limit: ["1", "2", ""], | |
| 56 | - limitMessage: chalk.dim("Please enter 1 or 2"), | |
| 57 | - }); | |
| 55 | + const choice = await questionWithChoices( | |
| 56 | + chalk.yellow("\nEnter choice (1): "), | |
| 57 | + ["1", "2", ""], | |
| 58 | + "1", | |
| 59 | + chalk.dim("Please enter 1 or 2"), | |
| 60 | + ); | |
| 58 | 61 | |
| 59 | 62 | if (choice === "1" || choice === "") { |
| 60 | 63 | // Option 1: Open models setup page |
| @@ -80,20 +83,17 @@ | ||
| 80 | 83 | } |
| 81 | 84 | |
| 82 | 85 | // Wait for user to acknowledge |
| 83 | - readlineSync.question(chalk.dim("\nPress Enter to exit...")); | |
| 84 | - process.exit(0); | |
| 86 | + await question(chalk.dim("\nPress Enter to exit...")); | |
| 87 | + await gracefulExit(0); | |
| 85 | 88 | } else if (choice === "2") { |
| 86 | 89 | // Option 2: Enter Anthropic API key |
| 87 | - const apiKey = readlineSync.question( | |
| 90 | + const apiKey = await question( | |
| 88 | 91 | chalk.white("\nEnter your Anthropic API key: "), |
| 89 | - { | |
| 90 | - hideEchoBack: true, | |
| 91 | - }, | |
| 92 | 92 | ); |
| 93 | 93 | |
| 94 | 94 | if (!isValidAnthropicApiKey(apiKey)) { |
| 95 | 95 | console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`)); |
| 96 | - process.exit(1); | |
| 96 | + await gracefulExit(1); | |
| 97 | 97 | } |
| 98 | 98 | |
| 99 | 99 | try { |
| @@ -108,7 +108,7 @@ | ||
| 108 | 108 | } |
| 109 | 109 | } catch (error) { |
| 110 | 110 | console.log(chalk.red(`❌ Error saving API key: ${error}`)); |
| 111 | - process.exit(1); | |
| 111 | + await gracefulExit(1); | |
| 112 | 112 | } |
| 113 | 113 | } |
| 114 | 114 | |
| @@ -137,5 +137,5 @@ | ||
| 137 | 137 | child.unref(); |
| 138 | 138 | |
| 139 | 139 | // Exit the current process |
| 140 | - process.exit(0); | |
| 140 | + await gracefulExit(0); | |
| 141 | 141 | } |
| @@ -19,10 +19,76 @@ | ||
| 19 | 19 | import { configureConsoleForHeadless, safeStderr } from "./init.js"; |
| 20 | 20 | import { sentryService } from "./sentry.js"; |
| 21 | 21 | import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; |
| 22 | +import { posthogService } from "./telemetry/posthogService.js"; | |
| 23 | +import { gracefulExit } from "./util/exit.js"; | |
| 22 | 24 | import { logger } from "./util/logger.js"; |
| 23 | 25 | import { readStdinSync } from "./util/stdin.js"; |
| 24 | 26 | import { getVersion } from "./version.js"; |
| 25 | 27 | |
| 28 | +// TUI lifecycle and two-stage exit state management | |
| 29 | +let tuiUnmount: (() => void) | null; | |
| 30 | +let showExitMessage: boolean; | |
| 31 | +let exitMessageCallback: (() => void) | null; | |
| 32 | +let lastCtrlCTime: number; | |
| 33 | + | |
| 34 | +// Initialize state immediately to avoid temporal dead zone issues with exported functions | |
| 35 | +(function initializeTUIState() { | |
| 36 | + tuiUnmount = null; | |
| 37 | + showExitMessage = false; | |
| 38 | + exitMessageCallback = null; | |
| 39 | + lastCtrlCTime = 0; | |
| 40 | +})(); | |
| 41 | + | |
| 42 | +// Register TUI cleanup function for graceful shutdown | |
| 43 | +export function setTUIUnmount(unmount: () => void) { | |
| 44 | + tuiUnmount = unmount; | |
| 45 | +} | |
| 46 | + | |
| 47 | +// Register callback to trigger UI updates when exit message state changes | |
| 48 | +export function setExitMessageCallback(callback: () => void) { | |
| 49 | + exitMessageCallback = callback; | |
| 50 | +} | |
| 51 | + | |
| 52 | +// Sets up SIGINT handler that requires double Ctrl+C within 1 second to exit | |
| 53 | +export function enableSigintHandler() { | |
| 54 | + // Remove all existing SIGINT listeners first | |
| 55 | + process.removeAllListeners("SIGINT"); | |
| 56 | + | |
| 57 | + process.on("SIGINT", async () => { | |
| 58 | + const now = Date.now(); | |
| 59 | + const timeSinceLastCtrlC = now - lastCtrlCTime; | |
| 60 | + | |
| 61 | + if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) { | |
| 62 | + // Second Ctrl+C within 1 second - exit | |
| 63 | + showExitMessage = false; | |
| 64 | + if (tuiUnmount) { | |
| 65 | + tuiUnmount(); | |
| 66 | + } | |
| 67 | + await gracefulExit(0); | |
| 68 | + } else { | |
| 69 | + // First Ctrl+C or too much time elapsed - show exit message | |
| 70 | + lastCtrlCTime = now; | |
| 71 | + showExitMessage = true; | |
| 72 | + if (exitMessageCallback) { | |
| 73 | + exitMessageCallback(); | |
| 74 | + } | |
| 75 | + | |
| 76 | + // Hide message after 1 second | |
| 77 | + setTimeout(() => { | |
| 78 | + showExitMessage = false; | |
| 79 | + if (exitMessageCallback) { | |
| 80 | + exitMessageCallback(); | |
| 81 | + } | |
| 82 | + }, 1000); | |
| 83 | + } | |
| 84 | + }); | |
| 85 | +} | |
| 86 | + | |
| 87 | +// Check if "ctrl+c to exit" message should be displayed | |
| 88 | +export function shouldShowExitMessage(): boolean { | |
| 89 | + return showExitMessage; | |
| 90 | +} | |
| 91 | + | |
| 26 | 92 | // Add global error handlers to prevent uncaught errors from crashing the process |
| 27 | 93 | process.on("unhandledRejection", (reason, promise) => { |
| 28 | 94 | logger.error("Unhandled Rejection at:", { promise, reason }); |
| @@ -41,6 +107,11 @@ | ||
| 41 | 107 | // Don't exit the process, just log the error |
| 42 | 108 | }); |
| 43 | 109 | |
| 110 | +// keyboard interruption handler for non-TUI flows | |
| 111 | +process.on("SIGINT", async () => { | |
| 112 | + await gracefulExit(130); | |
| 113 | +}); | |
| 114 | + | |
| 44 | 115 | const program = new Command(); |
| 45 | 116 | |
| 46 | 117 | program |
| @@ -48,7 +119,7 @@ | ||
| 48 | 119 | .description( |
| 49 | 120 | "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.", |
| 50 | 121 | ) |
| 51 | - .version(getVersion()); | |
| 122 | + .version(getVersion(), "-v, --version", "Display version number"); | |
| 52 | 123 | |
| 53 | 124 | // Root command - chat functionality (default) |
| 54 | 125 | // Add common options to the root command |
| @@ -64,7 +135,10 @@ | ||
| 64 | 135 | "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.", |
| 65 | 136 | ) |
| 66 | 137 | .option("--resume", "Resume from last session") |
| 138 | + .option("--fork <sessionId>", "Fork from an existing session ID") | |
| 67 | 139 | .action(async (prompt, options) => { |
| 140 | + // Telemetry: record command invocation | |
| 141 | + await posthogService.capture("cliCommand", { command: "cn" }); | |
| 68 | 142 | // Handle piped input - detect it early and decide on mode |
| 69 | 143 | let stdinInput = null; |
| 70 | 144 | |
| @@ -100,6 +174,8 @@ | ||
| 100 | 174 | readonly: options.readonly, |
| 101 | 175 | auto: options.auto, |
| 102 | 176 | config: options.config, |
| 177 | + resume: options.resume, | |
| 178 | + fork: options.fork, | |
| 103 | 179 | allow: options.allow, |
| 104 | 180 | ask: options.ask, |
| 105 | 181 | exclude: options.exclude, |
| @@ -149,7 +225,7 @@ | ||
| 149 | 225 | safeStderr(' cn -p "please review my current git diff"\n'); |
| 150 | 226 | safeStderr(' echo "hello" | cn -p\n'); |
| 151 | 227 | safeStderr(' cn -p "analyze the code in src/"\n'); |
| 152 | - process.exit(1); | |
| 228 | + await gracefulExit(1); | |
| 153 | 229 | } |
| 154 | 230 | |
| 155 | 231 | // Map --print to headless mode |
| @@ -163,6 +239,8 @@ | ||
| 163 | 239 | .command("login") |
| 164 | 240 | .description("Authenticate with Continue") |
| 165 | 241 | .action(async () => { |
| 242 | + // Telemetry: record command invocation | |
| 243 | + await posthogService.capture("cliCommand", { command: "login" }); | |
| 166 | 244 | await login(); |
| 167 | 245 | }); |
| 168 | 246 | |
| @@ -171,6 +249,8 @@ | ||
| 171 | 249 | .command("logout") |
| 172 | 250 | .description("Log out from Continue") |
| 173 | 251 | .action(async () => { |
| 252 | + // Telemetry: record command invocation | |
| 253 | + await posthogService.capture("cliCommand", { command: "logout" }); | |
| 174 | 254 | await logout(); |
| 175 | 255 | }); |
| 176 | 256 | |
| @@ -180,15 +260,19 @@ | ||
| 180 | 260 | .description("List recent chat sessions and select one to resume") |
| 181 | 261 | .option("--json", "Output in JSON format") |
| 182 | 262 | .action(async (options) => { |
| 263 | + // Telemetry: record command invocation | |
| 264 | + await posthogService.capture("cliCommand", { command: "ls" }); | |
| 183 | 265 | await listSessionsCommand({ |
| 184 | 266 | format: options.json ? "json" : undefined, |
| 185 | 267 | }); |
| 186 | 268 | }); |
| 187 | 269 | |
| 188 | 270 | // Remote subcommand |
| 189 | -program | |
| 190 | - .command("remote [prompt]", { hidden: true }) | |
| 191 | - .description("Launch a remote instance of the cn agent") | |
| 271 | +addCommonOptions( | |
| 272 | + program | |
| 273 | + .command("remote [prompt]", { hidden: true }) | |
| 274 | + .description("Launch a remote instance of the cn agent"), | |
| 275 | +) | |
| 192 | 276 | .option( |
| 193 | 277 | "--url <url>", |
| 194 | 278 | "Connect directly to the specified URL instead of creating a new remote environment", |
| @@ -210,6 +294,11 @@ | ||
| 210 | 294 | "Specify the repository URL to use in the remote environment", |
| 211 | 295 | ) |
| 212 | 296 | .action(async (prompt: string | undefined, options) => { |
| 297 | + // Telemetry: record command invocation | |
| 298 | + await posthogService.capture("cliCommand", { | |
| 299 | + command: "remote", | |
| 300 | + flagS: options.start, | |
| 301 | + }); | |
| 213 | 302 | await remote(prompt, options); |
| 214 | 303 | }); |
| 215 | 304 | |
| @@ -223,7 +312,13 @@ | ||
| 223 | 312 | "300", |
| 224 | 313 | ) |
| 225 | 314 | .option("--port <port>", "Port to run the server on (default: 8000)", "8000") |
| 315 | + .option( | |
| 316 | + "--id <storageId>", | |
| 317 | + "Upload session snapshots to Continue-managed storage using the provided identifier", | |
| 318 | + ) | |
| 226 | 319 | .action(async (prompt, options) => { |
| 320 | + // Telemetry: record command invocation | |
| 321 | + await posthogService.capture("cliCommand", { command: "serve" }); | |
| 227 | 322 | // Merge parent options with subcommand options |
| 228 | 323 | const mergedOptions = mergeParentOptions(program, options); |
| 229 | 324 | |
| @@ -241,6 +336,8 @@ | ||
| 241 | 336 | .description("Test remote TUI mode with a local server") |
| 242 | 337 | .option("--url <url>", "Server URL (default: http://localhost:8000)") |
| 243 | 338 | .action(async (prompt: string | undefined, options) => { |
| 339 | + // Telemetry: record command invocation | |
| 340 | + await posthogService.capture("cliCommand", { command: "remote-test" }); | |
| 244 | 341 | await remoteTest(prompt, options.url); |
| 245 | 342 | }); |
| 246 | 343 | |
| @@ -248,27 +345,22 @@ | ||
| 248 | 345 | program.on("command:*", () => { |
| 249 | 346 | console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); |
| 250 | 347 | program.outputHelp(); |
| 251 | - process.exit(1); | |
| 348 | + void gracefulExit(1); | |
| 252 | 349 | }); |
| 253 | 350 | |
| 254 | -// Parse arguments and handle errors | |
| 255 | -try { | |
| 256 | - program.parse(); | |
| 257 | -} catch (error) { | |
| 258 | - console.error(error); | |
| 259 | - sentryService.captureException( | |
| 260 | - error instanceof Error ? error : new Error(String(error)), | |
| 261 | - ); | |
| 262 | - process.exit(1); | |
| 351 | +export async function runCli(): Promise<void> { | |
| 352 | + // Parse arguments and handle errors | |
| 353 | + try { | |
| 354 | + program.parse(); | |
| 355 | + } catch (error) { | |
| 356 | + console.error(error); | |
| 357 | + sentryService.captureException( | |
| 358 | + error instanceof Error ? error : new Error(String(error)), | |
| 359 | + ); | |
| 360 | + process.exit(1); | |
| 361 | + } | |
| 362 | + | |
| 363 | + process.on("SIGTERM", async () => { | |
| 364 | + await gracefulExit(0); | |
| 365 | + }); | |
| 263 | 366 | } |
| 264 | - | |
| 265 | -// Graceful shutdown - flush Sentry data | |
| 266 | -process.on("SIGINT", async () => { | |
| 267 | - await sentryService.flush(); | |
| 268 | - process.exit(0); | |
| 269 | -}); | |
| 270 | - | |
| 271 | -process.on("SIGTERM", async () => { | |
| 272 | - await sentryService.flush(); | |
| 273 | - process.exit(0); | |
| 274 | -}); |
| @@ -0,0 +1,133 @@ | ||
| 1 | +import { execSync } from "child_process"; | |
| 2 | + | |
| 3 | +import chalk from "chalk"; | |
| 4 | + | |
| 5 | +import { | |
| 6 | + isAuthenticated, | |
| 7 | + isAuthenticatedConfig, | |
| 8 | + loadAuthConfig, | |
| 9 | +} from "./auth/workos.js"; | |
| 10 | +import { services } from "./services/index.js"; | |
| 11 | +import { getCurrentSession, getSessionFilePath } from "./session.js"; | |
| 12 | +import { logger } from "./util/logger.js"; | |
| 13 | +import { getVersion } from "./version.js"; | |
| 14 | + | |
| 15 | +export async function handleInfoSlashCommand() { | |
| 16 | + const infoLines = []; | |
| 17 | + | |
| 18 | + // Version and working directory info | |
| 19 | + const version = getVersion(); | |
| 20 | + const cwd = process.cwd(); | |
| 21 | + | |
| 22 | + infoLines.push( | |
| 23 | + chalk.white("CLI Information:"), | |
| 24 | + ` Version: ${chalk.green(version)}`, | |
| 25 | + ` Working Directory: ${chalk.blue(cwd)}`, | |
| 26 | + ); | |
| 27 | + | |
| 28 | + // Auth info | |
| 29 | + if (isAuthenticated()) { | |
| 30 | + const config = loadAuthConfig(); | |
| 31 | + if (config && isAuthenticatedConfig(config)) { | |
| 32 | + const email = config.userEmail || config.userId; | |
| 33 | + const orgId = config.organizationId; | |
| 34 | + infoLines.push( | |
| 35 | + "", | |
| 36 | + chalk.white("Authentication:"), | |
| 37 | + ` Email: ${chalk.green(email)}`, | |
| 38 | + ` Org ID: ${chalk.cyan(orgId)}`, | |
| 39 | + ); | |
| 40 | + } else { | |
| 41 | + infoLines.push( | |
| 42 | + "", | |
| 43 | + chalk.white("Authentication:"), | |
| 44 | + ` ${chalk.yellow("Authenticated via environment variable")}`, | |
| 45 | + ); | |
| 46 | + } | |
| 47 | + } else { | |
| 48 | + infoLines.push( | |
| 49 | + "", | |
| 50 | + chalk.white("Authentication:"), | |
| 51 | + ` ${chalk.red("Not logged in")}`, | |
| 52 | + ); | |
| 53 | + } | |
| 54 | + | |
| 55 | + // Config info | |
| 56 | + try { | |
| 57 | + const configState = services.config.getState(); | |
| 58 | + infoLines.push("", chalk.white("Configuration:")); | |
| 59 | + if (configState.config) { | |
| 60 | + infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`); | |
| 61 | + } else { | |
| 62 | + infoLines.push(` ${chalk.red(`Config not found`)}`); | |
| 63 | + } | |
| 64 | + if (configState.configPath) { | |
| 65 | + infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); | |
| 66 | + } | |
| 67 | + | |
| 68 | + // Add current model info | |
| 69 | + try { | |
| 70 | + const modelInfo = services.model?.getModelInfo(); | |
| 71 | + if (modelInfo) { | |
| 72 | + infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`); | |
| 73 | + } else { | |
| 74 | + infoLines.push(` Model: ${chalk.red("Not available")}`); | |
| 75 | + } | |
| 76 | + } catch { | |
| 77 | + infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`); | |
| 78 | + } | |
| 79 | + } catch { | |
| 80 | + infoLines.push( | |
| 81 | + "", | |
| 82 | + chalk.white("Configuration:"), | |
| 83 | + ` ${chalk.red("Configuration service not available")}`, | |
| 84 | + ); | |
| 85 | + } | |
| 86 | + | |
| 87 | + // Session info | |
| 88 | + infoLines.push("", chalk.white("Session:")); | |
| 89 | + try { | |
| 90 | + const currentSession = getCurrentSession(); | |
| 91 | + const sessionFilePath = getSessionFilePath(); | |
| 92 | + infoLines.push( | |
| 93 | + ` Title: ${chalk.green(currentSession.title)}`, | |
| 94 | + ` ID: ${chalk.gray(currentSession.sessionId)}`, | |
| 95 | + ` File: ${chalk.blue(sessionFilePath)}`, | |
| 96 | + ); | |
| 97 | + } catch { | |
| 98 | + infoLines.push(` ${chalk.red("Session not available")}`); | |
| 99 | + } | |
| 100 | + | |
| 101 | + // Runtime diagnostic info | |
| 102 | + const nodePath = process.execPath; | |
| 103 | + const invokedPath = process.argv[1]; | |
| 104 | + | |
| 105 | + // Get npm version | |
| 106 | + let npmVersion = "unknown"; | |
| 107 | + try { | |
| 108 | + npmVersion = execSync("npm --version", { | |
| 109 | + encoding: "utf8", | |
| 110 | + timeout: 5000, | |
| 111 | + stdio: ["pipe", "pipe", "ignore"], | |
| 112 | + }).trim(); | |
| 113 | + } catch (error) { | |
| 114 | + // If npm command fails, fallback to "unknown" | |
| 115 | + logger.warn("Failed to get npm version:", error); | |
| 116 | + } | |
| 117 | + | |
| 118 | + // Diagnostic info | |
| 119 | + infoLines.push( | |
| 120 | + "", | |
| 121 | + chalk.white("Diagnostic Info"), | |
| 122 | + ` Currently running: npm-global (${chalk.green(npmVersion)})`, | |
| 123 | + ` Path: ${chalk.blue(nodePath)}`, | |
| 124 | + ` Invoked: ${chalk.blue(invokedPath)}`, | |
| 125 | + ); | |
| 126 | + | |
| 127 | + // TODO add global settings like auto update etc. | |
| 128 | + | |
| 129 | + return { | |
| 130 | + exit: false, | |
| 131 | + output: infoLines.join("\n"), | |
| 132 | + }; | |
| 133 | +} |
| @@ -3,10 +3,11 @@ | ||
| 3 | 3 | * This file intercepts console and stdout/stderr to prevent dependency logging |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | +import { isHeadlessMode as checkIsHeadlessMode } from "./util/cli.js"; | |
| 7 | + | |
| 6 | 8 | // Check if we're in headless mode by looking at process arguments |
| 7 | 9 | // We need to do this before any imports to catch early logging |
| 8 | -const args = process.argv.slice(2); | |
| 9 | -const isHeadlessMode = args.includes("-p") || args.includes("--print"); | |
| 10 | +const isHeadlessMode = checkIsHeadlessMode(); | |
| 10 | 11 | |
| 11 | 12 | // Store original methods before ANY dependencies can use them |
| 12 | 13 | const originalStdoutWrite = process.stdout.write.bind(process.stdout); |
| @@ -5,7 +5,6 @@ | ||
| 5 | 5 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 6 | 6 | import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; |
| 7 | 7 | import chalk from "chalk"; |
| 8 | -import * as readlineSync from "readline-sync"; | |
| 9 | 8 | |
| 10 | 9 | import { processPromptOrRule } from "./args.js"; |
| 11 | 10 | import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; |
| @@ -16,6 +15,7 @@ | ||
| 16 | 15 | getApiKeyValidationError, |
| 17 | 16 | isValidAnthropicApiKey, |
| 18 | 17 | } from "./util/apiKeyValidation.js"; |
| 18 | +import { question, questionWithChoices } from "./util/prompt.js"; | |
| 19 | 19 | import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; |
| 20 | 20 | |
| 21 | 21 | const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); |
| @@ -97,22 +97,24 @@ | ||
| 97 | 97 | console.log(chalk.white("1. ⏩ Log in with Continue")); |
| 98 | 98 | console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); |
| 99 | 99 | |
| 100 | - const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { | |
| 101 | - limit: ["1", "2", ""], | |
| 102 | - limitMessage: chalk.dim("Please enter 1 or 2"), | |
| 103 | - }); | |
| 100 | + const choice = await questionWithChoices( | |
| 101 | + chalk.yellow("\nEnter choice (1): "), | |
| 102 | + ["1", "2", ""], | |
| 103 | + "1", | |
| 104 | + chalk.dim("Please enter 1 or 2"), | |
| 105 | + ); | |
| 104 | 106 | |
| 105 | 107 | if (choice === "1" || choice === "") { |
| 106 | 108 | const newAuthConfig = await login(); |
| 107 | 109 | |
| 108 | - const result = await initialize(newAuthConfig, undefined); | |
| 110 | + const { ensureOrganization } = await import("./auth/workos.js"); | |
| 111 | + const finalAuthConfig = await ensureOrganization(newAuthConfig); | |
| 112 | + | |
| 113 | + const result = await initialize(finalAuthConfig, undefined); | |
| 109 | 114 | return { ...result, wasOnboarded: true }; |
| 110 | 115 | } else if (choice === "2") { |
| 111 | - const apiKey = readlineSync.question( | |
| 116 | + const apiKey = await question( | |
| 112 | 117 | chalk.white("\nEnter your Anthropic API key: "), |
| 113 | - { | |
| 114 | - hideEchoBack: true, | |
| 115 | - }, | |
| 116 | 118 | ); |
| 117 | 119 | |
| 118 | 120 | if (!isValidAnthropicApiKey(apiKey)) { |
| @@ -1,3 +1,7 @@ | ||
| 1 | +import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; | |
| 2 | + | |
| 3 | +import * as toolsModule from "../tools/index.js"; | |
| 4 | + | |
| 1 | 5 | import { |
| 2 | 6 | checkToolPermission, |
| 3 | 7 | filterExcludedTools, |
| @@ -593,4 +597,373 @@ | ||
| 593 | 597 | expect(filtered).toEqual(tools); |
| 594 | 598 | }); |
| 595 | 599 | }); |
| 600 | + | |
| 601 | + describe("Hybrid Permission Model with Dynamic Evaluation", () => { | |
| 602 | + // Mock the runTerminalCommand tool with evaluateToolCallPolicy | |
| 603 | + const mockBashTool = { | |
| 604 | + name: "Bash", | |
| 605 | + displayName: "Bash", | |
| 606 | + description: "Execute bash commands", | |
| 607 | + parameters: {}, | |
| 608 | + isBuiltIn: true, | |
| 609 | + evaluateToolCallPolicy: vi.fn(), | |
| 610 | + run: vi.fn(), | |
| 611 | + }; | |
| 612 | + | |
| 613 | + beforeEach(() => { | |
| 614 | + vi.clearAllMocks(); | |
| 615 | + // Mock getAllBuiltinTools to return our test tool | |
| 616 | + vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([ | |
| 617 | + mockBashTool, | |
| 618 | + ]); | |
| 619 | + | |
| 620 | + // Reset mock between tests | |
| 621 | + mockBashTool.evaluateToolCallPolicy.mockClear(); | |
| 622 | + }); | |
| 623 | + | |
| 624 | + afterEach(() => { | |
| 625 | + vi.restoreAllMocks(); | |
| 626 | + }); | |
| 627 | + | |
| 628 | + describe("User has Bash in 'allow' mode", () => { | |
| 629 | + const permissions: ToolPermissions = { | |
| 630 | + policies: [ | |
| 631 | + { tool: "Bash", permission: "allow" }, | |
| 632 | + { tool: "*", permission: "ask" }, | |
| 633 | + ], | |
| 634 | + }; | |
| 635 | + | |
| 636 | + it("should allow safe commands (echo hello)", () => { | |
| 637 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 638 | + "allowedWithoutPermission", | |
| 639 | + ); | |
| 640 | + | |
| 641 | + const result = checkToolPermission( | |
| 642 | + { name: "Bash", arguments: { command: "echo hello" } }, | |
| 643 | + permissions, | |
| 644 | + ); | |
| 645 | + | |
| 646 | + expect(result.permission).toBe("allow"); // User preference wins | |
| 647 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 648 | + "allowedWithoutPermission", // converted from "allow" | |
| 649 | + { command: "echo hello" }, | |
| 650 | + ); | |
| 651 | + }); | |
| 652 | + | |
| 653 | + it("should allow risky commands based on user preference (curl)", () => { | |
| 654 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 655 | + "allowedWithPermission", | |
| 656 | + ); | |
| 657 | + | |
| 658 | + const result = checkToolPermission( | |
| 659 | + { name: "Bash", arguments: { command: "curl https://example.com" } }, | |
| 660 | + permissions, | |
| 661 | + ); | |
| 662 | + | |
| 663 | + expect(result.permission).toBe("allow"); // User preference wins over "ask" | |
| 664 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 665 | + "allowedWithoutPermission", // converted from "allow" | |
| 666 | + { command: "curl https://example.com" }, | |
| 667 | + ); | |
| 668 | + }); | |
| 669 | + | |
| 670 | + it("should block dangerous commands despite user preference (eval)", () => { | |
| 671 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); | |
| 672 | + | |
| 673 | + const result = checkToolPermission( | |
| 674 | + { name: "Bash", arguments: { command: "eval 'echo safe'" } }, | |
| 675 | + permissions, | |
| 676 | + ); | |
| 677 | + | |
| 678 | + expect(result.permission).toBe("exclude"); // Security wins | |
| 679 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 680 | + "allowedWithoutPermission", // converted from "allow" | |
| 681 | + { command: "eval 'echo safe'" }, | |
| 682 | + ); | |
| 683 | + }); | |
| 684 | + | |
| 685 | + it("should block sudo commands despite user preference", () => { | |
| 686 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); | |
| 687 | + | |
| 688 | + const result = checkToolPermission( | |
| 689 | + { name: "Bash", arguments: { command: "sudo rm -rf /" } }, | |
| 690 | + permissions, | |
| 691 | + ); | |
| 692 | + | |
| 693 | + expect(result.permission).toBe("exclude"); // Security wins | |
| 694 | + }); | |
| 695 | + }); | |
| 696 | + | |
| 697 | + describe("User has Bash in 'ask' mode (default)", () => { | |
| 698 | + const permissions: ToolPermissions = { | |
| 699 | + policies: [ | |
| 700 | + { tool: "Bash", permission: "ask" }, | |
| 701 | + { tool: "*", permission: "ask" }, | |
| 702 | + ], | |
| 703 | + }; | |
| 704 | + | |
| 705 | + it("should ask for safe commands based on user preference (echo)", () => { | |
| 706 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 707 | + "allowedWithoutPermission", | |
| 708 | + ); | |
| 709 | + | |
| 710 | + const result = checkToolPermission( | |
| 711 | + { name: "Bash", arguments: { command: "echo hello" } }, | |
| 712 | + permissions, | |
| 713 | + ); | |
| 714 | + | |
| 715 | + expect(result.permission).toBe("ask"); // User preference wins | |
| 716 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 717 | + "allowedWithPermission", // converted from "ask" | |
| 718 | + { command: "echo hello" }, | |
| 719 | + ); | |
| 720 | + }); | |
| 721 | + | |
| 722 | + it("should ask for risky commands (curl)", () => { | |
| 723 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 724 | + "allowedWithPermission", | |
| 725 | + ); | |
| 726 | + | |
| 727 | + const result = checkToolPermission( | |
| 728 | + { name: "Bash", arguments: { command: "curl https://example.com" } }, | |
| 729 | + permissions, | |
| 730 | + ); | |
| 731 | + | |
| 732 | + expect(result.permission).toBe("ask"); // Both agree on "ask" | |
| 733 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 734 | + "allowedWithPermission", // converted from "ask" | |
| 735 | + { command: "curl https://example.com" }, | |
| 736 | + ); | |
| 737 | + }); | |
| 738 | + | |
| 739 | + it("should block dangerous commands (eval)", () => { | |
| 740 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); | |
| 741 | + | |
| 742 | + const result = checkToolPermission( | |
| 743 | + { name: "Bash", arguments: { command: "eval 'echo safe'" } }, | |
| 744 | + permissions, | |
| 745 | + ); | |
| 746 | + | |
| 747 | + expect(result.permission).toBe("exclude"); // Security wins | |
| 748 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 749 | + "allowedWithPermission", // converted from "ask" | |
| 750 | + { command: "eval 'echo safe'" }, | |
| 751 | + ); | |
| 752 | + }); | |
| 753 | + | |
| 754 | + it("should block rm -rf commands", () => { | |
| 755 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled"); | |
| 756 | + | |
| 757 | + const result = checkToolPermission( | |
| 758 | + { name: "Bash", arguments: { command: "rm -rf /tmp/important" } }, | |
| 759 | + permissions, | |
| 760 | + ); | |
| 761 | + | |
| 762 | + expect(result.permission).toBe("exclude"); // Security wins | |
| 763 | + }); | |
| 764 | + }); | |
| 765 | + | |
| 766 | + describe("User has Bash in 'exclude' mode", () => { | |
| 767 | + const permissions: ToolPermissions = { | |
| 768 | + policies: [{ tool: "Bash", permission: "exclude" }], | |
| 769 | + }; | |
| 770 | + | |
| 771 | + it("should always exclude regardless of dynamic evaluation", () => { | |
| 772 | + // Even if dynamic evaluation would allow it | |
| 773 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 774 | + "allowedWithoutPermission", | |
| 775 | + ); | |
| 776 | + | |
| 777 | + const result = checkToolPermission( | |
| 778 | + { name: "Bash", arguments: { command: "echo hello" } }, | |
| 779 | + permissions, | |
| 780 | + ); | |
| 781 | + | |
| 782 | + expect(result.permission).toBe("exclude"); // User excluded the tool entirely | |
| 783 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 784 | + "disabled", // converted from "exclude" | |
| 785 | + { command: "echo hello" }, | |
| 786 | + ); | |
| 787 | + }); | |
| 788 | + }); | |
| 789 | + | |
| 790 | + describe("Comprehensive command testing", () => { | |
| 791 | + const permissions: ToolPermissions = { | |
| 792 | + policies: [{ tool: "Bash", permission: "allow" }], | |
| 793 | + }; | |
| 794 | + | |
| 795 | + const testCases = [ | |
| 796 | + // Safe commands | |
| 797 | + { | |
| 798 | + command: "ls", | |
| 799 | + dynamicResult: "allowedWithoutPermission", | |
| 800 | + expected: "allow", | |
| 801 | + }, | |
| 802 | + { | |
| 803 | + command: "pwd", | |
| 804 | + dynamicResult: "allowedWithoutPermission", | |
| 805 | + expected: "allow", | |
| 806 | + }, | |
| 807 | + { | |
| 808 | + command: "date", | |
| 809 | + dynamicResult: "allowedWithoutPermission", | |
| 810 | + expected: "allow", | |
| 811 | + }, | |
| 812 | + { | |
| 813 | + command: "echo test", | |
| 814 | + dynamicResult: "allowedWithoutPermission", | |
| 815 | + expected: "allow", | |
| 816 | + }, | |
| 817 | + { | |
| 818 | + command: "git status", | |
| 819 | + dynamicResult: "allowedWithoutPermission", | |
| 820 | + expected: "allow", | |
| 821 | + }, | |
| 822 | + | |
| 823 | + // Risky commands (user preference wins when not disabled) | |
| 824 | + { | |
| 825 | + command: "npm install pkg", | |
| 826 | + dynamicResult: "allowedWithPermission", | |
| 827 | + expected: "allow", | |
| 828 | + }, | |
| 829 | + { | |
| 830 | + command: "rm file.txt", | |
| 831 | + dynamicResult: "allowedWithPermission", | |
| 832 | + expected: "allow", | |
| 833 | + }, | |
| 834 | + { | |
| 835 | + command: "curl https://api.example.com", | |
| 836 | + dynamicResult: "allowedWithPermission", | |
| 837 | + expected: "allow", | |
| 838 | + }, | |
| 839 | + { | |
| 840 | + command: "wget https://example.com/file", | |
| 841 | + dynamicResult: "allowedWithPermission", | |
| 842 | + expected: "allow", | |
| 843 | + }, | |
| 844 | + | |
| 845 | + // Dangerous commands (always blocked) | |
| 846 | + { | |
| 847 | + command: "sudo rm -rf /", | |
| 848 | + dynamicResult: "disabled", | |
| 849 | + expected: "exclude", | |
| 850 | + }, | |
| 851 | + { | |
| 852 | + command: "exec bash", | |
| 853 | + dynamicResult: "disabled", | |
| 854 | + expected: "exclude", | |
| 855 | + }, | |
| 856 | + { | |
| 857 | + command: "eval 'malicious code'", | |
| 858 | + dynamicResult: "disabled", | |
| 859 | + expected: "exclude", | |
| 860 | + }, | |
| 861 | + { command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" }, | |
| 862 | + ]; | |
| 863 | + | |
| 864 | + testCases.forEach(({ command, dynamicResult, expected }) => { | |
| 865 | + it(`should handle '${command}' correctly`, () => { | |
| 866 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult); | |
| 867 | + | |
| 868 | + const result = checkToolPermission( | |
| 869 | + { name: "Bash", arguments: { command } }, | |
| 870 | + permissions, | |
| 871 | + ); | |
| 872 | + | |
| 873 | + expect(result.permission).toBe(expected); | |
| 874 | + }); | |
| 875 | + }); | |
| 876 | + }); | |
| 877 | + | |
| 878 | + describe("Edge cases", () => { | |
| 879 | + it("should handle tools without dynamic evaluation", () => { | |
| 880 | + // Mock a Read tool without evaluateToolCallPolicy | |
| 881 | + const mockReadTool = { | |
| 882 | + name: "Read", | |
| 883 | + displayName: "Read", | |
| 884 | + description: "Read files", | |
| 885 | + parameters: {}, | |
| 886 | + isBuiltIn: true, | |
| 887 | + run: vi.fn(), | |
| 888 | + // No evaluateToolCallPolicy | |
| 889 | + }; | |
| 890 | + vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([ | |
| 891 | + mockReadTool, | |
| 892 | + mockBashTool, | |
| 893 | + ]); | |
| 894 | + | |
| 895 | + const permissions: ToolPermissions = { | |
| 896 | + policies: [{ tool: "Read", permission: "allow" }], | |
| 897 | + }; | |
| 898 | + | |
| 899 | + const result = checkToolPermission( | |
| 900 | + { name: "Read", arguments: { path: "/tmp/file.txt" } }, | |
| 901 | + permissions, | |
| 902 | + ); | |
| 903 | + | |
| 904 | + expect(result.permission).toBe("allow"); | |
| 905 | + expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled(); | |
| 906 | + }); | |
| 907 | + | |
| 908 | + it("should use default 'ask' when no policy matches", () => { | |
| 909 | + const permissions: ToolPermissions = { | |
| 910 | + policies: [], | |
| 911 | + }; | |
| 912 | + | |
| 913 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 914 | + "allowedWithPermission", | |
| 915 | + ); | |
| 916 | + | |
| 917 | + const result = checkToolPermission( | |
| 918 | + { name: "Bash", arguments: { command: "echo test" } }, | |
| 919 | + permissions, | |
| 920 | + ); | |
| 921 | + | |
| 922 | + expect(result.permission).toBe("ask"); // Default fallback, user preference wins | |
| 923 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 924 | + "allowedWithPermission", // converted from default "ask" | |
| 925 | + { command: "echo test" }, | |
| 926 | + ); | |
| 927 | + }); | |
| 928 | + | |
| 929 | + it("should handle null/undefined arguments gracefully", () => { | |
| 930 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 931 | + "allowedWithPermission", | |
| 932 | + ); | |
| 933 | + | |
| 934 | + const permissions: ToolPermissions = { | |
| 935 | + policies: [{ tool: "Bash", permission: "allow" }], | |
| 936 | + }; | |
| 937 | + | |
| 938 | + const result = checkToolPermission( | |
| 939 | + { name: "Bash", arguments: {} }, | |
| 940 | + permissions, | |
| 941 | + ); | |
| 942 | + | |
| 943 | + expect(result.permission).toBe("allow"); | |
| 944 | + expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith( | |
| 945 | + "allowedWithoutPermission", | |
| 946 | + {}, | |
| 947 | + ); | |
| 948 | + }); | |
| 949 | + | |
| 950 | + it("should maintain matched policy information", () => { | |
| 951 | + mockBashTool.evaluateToolCallPolicy.mockReturnValue( | |
| 952 | + "allowedWithoutPermission", | |
| 953 | + ); | |
| 954 | + | |
| 955 | + const policy = { tool: "Bash", permission: "allow" as const }; | |
| 956 | + const permissions: ToolPermissions = { | |
| 957 | + policies: [policy], | |
| 958 | + }; | |
| 959 | + | |
| 960 | + const result = checkToolPermission( | |
| 961 | + { name: "Bash", arguments: { command: "ls" } }, | |
| 962 | + permissions, | |
| 963 | + ); | |
| 964 | + | |
| 965 | + expect(result.matchedPolicy).toBe(policy); | |
| 966 | + }); | |
| 967 | + }); | |
| 968 | + }); | |
| 596 | 969 | }); |
| @@ -1,10 +1,14 @@ | ||
| 1 | +import type { ToolPolicy } from "@continuedev/terminal-security"; | |
| 2 | + | |
| 1 | 3 | import { getServiceSync } from "../services/index.js"; |
| 2 | 4 | import type { ToolPermissionServiceState } from "../services/types.js"; |
| 3 | 5 | import { SERVICE_NAMES } from "../services/types.js"; |
| 6 | +import { getAllBuiltinTools } from "../tools/index.js"; | |
| 4 | 7 | |
| 5 | 8 | import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; |
| 6 | 9 | import { |
| 7 | 10 | PermissionCheckResult, |
| 11 | + PermissionPolicy, | |
| 8 | 12 | ToolCallRequest, |
| 9 | 13 | ToolPermissions, |
| 10 | 14 | } from "./types.js"; |
| @@ -103,6 +107,24 @@ | ||
| 103 | 107 | return true; |
| 104 | 108 | } |
| 105 | 109 | |
| 110 | +/** | |
| 111 | + * Converts CLI's PermissionPolicy to core's ToolPolicy | |
| 112 | + */ | |
| 113 | +function permissionPolicyToToolPolicy( | |
| 114 | + permission: PermissionPolicy, | |
| 115 | +): ToolPolicy { | |
| 116 | + switch (permission) { | |
| 117 | + case "allow": | |
| 118 | + return "allowedWithoutPermission"; | |
| 119 | + case "ask": | |
| 120 | + return "allowedWithPermission"; | |
| 121 | + case "exclude": | |
| 122 | + return "disabled"; | |
| 123 | + default: | |
| 124 | + return "allowedWithPermission"; | |
| 125 | + } | |
| 126 | +} | |
| 127 | + | |
| 106 | 128 | /** |
| 107 | 129 | * Evaluates a tool call request against a set of permission policies. |
| 108 | 130 | * Returns the permission for the first matching policy. |
| @@ -129,21 +151,54 @@ | ||
| 129 | 151 | } |
| 130 | 152 | } |
| 131 | 153 | |
| 154 | + // First, get the base permission from static policies | |
| 155 | + let basePermission: PermissionPolicy = "ask"; | |
| 156 | + let matchedPolicy = undefined; | |
| 157 | + | |
| 132 | 158 | for (const policy of policies) { |
| 133 | 159 | if ( |
| 134 | 160 | matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) && |
| 135 | 161 | matchesArguments(toolCall.arguments, policy.argumentMatches) |
| 136 | 162 | ) { |
| 163 | + basePermission = policy.permission; | |
| 164 | + matchedPolicy = policy; | |
| 165 | + break; | |
| 166 | + } | |
| 167 | + } | |
| 168 | + | |
| 169 | + // Check if tool has dynamic policy evaluation | |
| 170 | + const builtinTools = getAllBuiltinTools(); | |
| 171 | + const tool = builtinTools.find((t) => t.name === toolCall.name); | |
| 172 | + | |
| 173 | + if (tool?.evaluateToolCallPolicy) { | |
| 174 | + // Convert CLI permission to core policy | |
| 175 | + const basePolicy = permissionPolicyToToolPolicy(basePermission); | |
| 176 | + | |
| 177 | + // Evaluate the dynamic policy | |
| 178 | + const evaluatedPolicy = tool.evaluateToolCallPolicy( | |
| 179 | + basePolicy, | |
| 180 | + toolCall.arguments, | |
| 181 | + ); | |
| 182 | + | |
| 183 | + // If dynamic evaluation says disabled, that ALWAYS takes precedence | |
| 184 | + if (evaluatedPolicy === "disabled") { | |
| 137 | 185 | return { |
| 138 | - permission: policy.permission, | |
| 139 | - matchedPolicy: policy, | |
| 186 | + permission: "exclude", | |
| 187 | + matchedPolicy, | |
| 140 | 188 | }; |
| 141 | 189 | } |
| 190 | + | |
| 191 | + // Otherwise, user preference wins - return the original base permission | |
| 192 | + return { | |
| 193 | + permission: basePermission, | |
| 194 | + matchedPolicy, | |
| 195 | + }; | |
| 142 | 196 | } |
| 143 | 197 | |
| 144 | - // Fallback to "ask" if no policy matches | |
| 198 | + // No dynamic evaluation, return static result | |
| 145 | 199 | return { |
| 146 | - permission: "ask", | |
| 200 | + permission: basePermission, | |
| 201 | + matchedPolicy, | |
| 147 | 202 | }; |
| 148 | 203 | } |
| 149 | 204 |
| @@ -1,10 +1,118 @@ | ||
| 1 | -import { describe, expect, test, beforeEach, vi } from "vitest"; | |
| 2 | - | |
| 3 | -import { | |
| 4 | - BaseService, | |
| 5 | - hasDependencies, | |
| 6 | - ServiceWithDependencies, | |
| 7 | -} from "./BaseService.js"; | |
| 1 | +import { EventEmitter } from "events"; | |
| 2 | + | |
| 3 | +import { beforeEach, describe, expect, test, vi } from "vitest"; | |
| 4 | + | |
| 5 | +import { logger } from "../util/logger.js"; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * Base abstract class for all services | |
| 9 | + * Provides common lifecycle methods and state management | |
| 10 | + */ | |
| 11 | +abstract class BaseService<TState> extends EventEmitter { | |
| 12 | + protected serviceName: string; | |
| 13 | + protected currentState: TState; | |
| 14 | + private isInitialized: boolean = false; | |
| 15 | + | |
| 16 | + constructor(serviceName: string, initialState: TState) { | |
| 17 | + super(); | |
| 18 | + this.serviceName = serviceName; | |
| 19 | + this.currentState = initialState; | |
| 20 | + } | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * Initialize the service (must be implemented by subclasses) | |
| 24 | + * This is automatically wrapped with initialization logic | |
| 25 | + */ | |
| 26 | + abstract doInitialize(...args: any[]): Promise<TState>; | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * Public initialization method that wraps the implementation | |
| 30 | + */ | |
| 31 | + async initialize(...args: any[]): Promise<TState> { | |
| 32 | + logger.debug(`Initializing ${this.serviceName}`, { | |
| 33 | + wasInitialized: this.isInitialized, | |
| 34 | + hadPreviousState: !!this.currentState, | |
| 35 | + }); | |
| 36 | + this.emit("initializing"); | |
| 37 | + | |
| 38 | + try { | |
| 39 | + const state = await this.doInitialize(...args); | |
| 40 | + this.currentState = state; | |
| 41 | + this.isInitialized = true; | |
| 42 | + logger.debug(`${this.serviceName} initialized successfully`, { | |
| 43 | + stateKeys: state ? Object.keys(state as any) : [], | |
| 44 | + isNowInitialized: this.isInitialized, | |
| 45 | + }); | |
| 46 | + this.emit("initialized", state); | |
| 47 | + return state; | |
| 48 | + } catch (error: any) { | |
| 49 | + logger.debug(`Failed to initialize ${this.serviceName}:`, error); | |
| 50 | + if (this.listenerCount("error") > 0) { | |
| 51 | + this.emit("error", error); | |
| 52 | + } | |
| 53 | + throw error; | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * Get current service state (shallow copy for immutability) | |
| 59 | + */ | |
| 60 | + getState(): TState { | |
| 61 | + return { ...this.currentState }; | |
| 62 | + } | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * Update service state and emit change event | |
| 66 | + */ | |
| 67 | + protected setState(newState: Partial<TState>): void { | |
| 68 | + const previousState = this.currentState; | |
| 69 | + this.currentState = { ...this.currentState, ...newState }; | |
| 70 | + // Only log state updates if not in production to avoid circular reference issues | |
| 71 | + if (process.env.NODE_ENV !== "production") { | |
| 72 | + logger.debug(`${this.serviceName} state updated`); | |
| 73 | + } | |
| 74 | + this.emit("stateChanged", this.currentState, previousState); | |
| 75 | + } | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * Check if service is ready for use | |
| 79 | + */ | |
| 80 | + isReady(): boolean { | |
| 81 | + return this.isInitialized; | |
| 82 | + } | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * Reload/refresh the service | |
| 86 | + */ | |
| 87 | + async reload(...args: any[]): Promise<TState> { | |
| 88 | + logger.debug(`Reloading ${this.serviceName}`); | |
| 89 | + this.isInitialized = false; | |
| 90 | + return this.initialize(...args); | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * Cleanup resources (can be overridden by subclasses) | |
| 95 | + */ | |
| 96 | + async cleanup(): Promise<void> { | |
| 97 | + logger.debug(`Cleaning up ${this.serviceName}`); | |
| 98 | + this.removeAllListeners(); | |
| 99 | + this.isInitialized = false; | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +/** | |
| 104 | + * Interface for services with dependencies | |
| 105 | + */ | |
| 106 | +interface ServiceWithDependencies { | |
| 107 | + getDependencies(): string[]; | |
| 108 | +} | |
| 109 | + | |
| 110 | +/** | |
| 111 | + * Helper to check if a service has dependencies | |
| 112 | + */ | |
| 113 | +function hasDependencies(service: any): service is ServiceWithDependencies { | |
| 114 | + return !!service && typeof service.getDependencies === "function"; | |
| 115 | +} | |
| 8 | 116 | |
| 9 | 117 | // Test implementation of BaseService |
| 10 | 118 | interface TestState { |
| @@ -0,0 +1,548 @@ | ||
| 1 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 2 | +import { describe, it, expect, beforeEach, vi } from "vitest"; | |
| 3 | + | |
| 4 | +import { ChatHistoryService } from "./ChatHistoryService.js"; | |
| 5 | + | |
| 6 | +// Mock the dependencies | |
| 7 | +vi.mock("../session.js", () => ({ | |
| 8 | + updateSessionHistory: vi.fn(), | |
| 9 | + loadSession: vi.fn(), | |
| 10 | + createSession: vi.fn((history) => ({ | |
| 11 | + sessionId: "test-session-id", | |
| 12 | + history: history || [], | |
| 13 | + title: "Test Session", | |
| 14 | + workspaceDirectory: "/test", | |
| 15 | + })), | |
| 16 | +})); | |
| 17 | + | |
| 18 | +vi.mock("../util/logger.js", () => ({ | |
| 19 | + logger: { | |
| 20 | + debug: vi.fn(), | |
| 21 | + warn: vi.fn(), | |
| 22 | + error: vi.fn(), | |
| 23 | + }, | |
| 24 | +})); | |
| 25 | + | |
| 26 | +describe("ChatHistoryService", () => { | |
| 27 | + let service: ChatHistoryService; | |
| 28 | + | |
| 29 | + beforeEach(() => { | |
| 30 | + service = new ChatHistoryService(); | |
| 31 | + vi.clearAllMocks(); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + describe("initialization", () => { | |
| 35 | + it("should initialize with empty state", async () => { | |
| 36 | + const state = await service.initialize(); | |
| 37 | + | |
| 38 | + expect(state.history).toEqual([]); | |
| 39 | + expect(state.compactionIndex).toBeNull(); | |
| 40 | + expect(state.sessionId).toBe("test-session-id"); | |
| 41 | + expect(state.isRemoteMode).toBe(false); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + it("should initialize with provided session", async () => { | |
| 45 | + const mockHistory: ChatHistoryItem[] = [ | |
| 46 | + { | |
| 47 | + message: { role: "user", content: "Hello" }, | |
| 48 | + contextItems: [], | |
| 49 | + }, | |
| 50 | + ]; | |
| 51 | + | |
| 52 | + const mockSession = { | |
| 53 | + sessionId: "custom-session", | |
| 54 | + history: mockHistory, | |
| 55 | + title: "Custom Session", | |
| 56 | + workspaceDirectory: "/custom", | |
| 57 | + }; | |
| 58 | + | |
| 59 | + const state = await service.initialize(mockSession); | |
| 60 | + | |
| 61 | + expect(state.history).toEqual(mockHistory); | |
| 62 | + expect(state.sessionId).toBe("custom-session"); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("should detect compaction index on initialization", async () => { | |
| 66 | + const mockHistory: ChatHistoryItem[] = [ | |
| 67 | + { | |
| 68 | + message: { role: "user", content: "First message" }, | |
| 69 | + contextItems: [], | |
| 70 | + }, | |
| 71 | + { | |
| 72 | + message: { role: "assistant", content: "Summary here" }, | |
| 73 | + contextItems: [], | |
| 74 | + conversationSummary: "Summary here", | |
| 75 | + }, | |
| 76 | + { | |
| 77 | + message: { role: "user", content: "After compaction" }, | |
| 78 | + contextItems: [], | |
| 79 | + }, | |
| 80 | + ]; | |
| 81 | + | |
| 82 | + const mockSession = { | |
| 83 | + sessionId: "session-with-compaction", | |
| 84 | + history: mockHistory, | |
| 85 | + title: "Compacted Session", | |
| 86 | + workspaceDirectory: "/compacted", | |
| 87 | + }; | |
| 88 | + | |
| 89 | + const state = await service.initialize(mockSession); | |
| 90 | + | |
| 91 | + expect(state.compactionIndex).toBe(1); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should set remote mode on initialization", async () => { | |
| 95 | + const state = await service.initialize(undefined, true); | |
| 96 | + | |
| 97 | + expect(state.isRemoteMode).toBe(true); | |
| 98 | + }); | |
| 99 | + }); | |
| 100 | + | |
| 101 | + describe("addUserMessage", () => { | |
| 102 | + beforeEach(async () => { | |
| 103 | + await service.initialize(); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should add a user message to history", () => { | |
| 107 | + const message = service.addUserMessage("Hello, world!"); | |
| 108 | + | |
| 109 | + expect(message.message.role).toBe("user"); | |
| 110 | + expect(message.message.content).toBe("Hello, world!"); | |
| 111 | + | |
| 112 | + const state = service.getState(); | |
| 113 | + expect(state.history).toHaveLength(1); | |
| 114 | + expect(state.history[0]).toBe(message); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should include context items", () => { | |
| 118 | + const contextItems = [ | |
| 119 | + { content: "file.txt", name: "File", description: "A text file" }, | |
| 120 | + ]; | |
| 121 | + | |
| 122 | + const message = service.addUserMessage("Check this file", contextItems); | |
| 123 | + | |
| 124 | + expect(message.contextItems).toEqual(contextItems); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should emit state change event", () => { | |
| 128 | + const listener = vi.fn(); | |
| 129 | + service.on("stateChanged", listener); | |
| 130 | + | |
| 131 | + service.addUserMessage("Test message"); | |
| 132 | + | |
| 133 | + expect(listener).toHaveBeenCalledTimes(1); | |
| 134 | + expect(listener).toHaveBeenCalledWith( | |
| 135 | + expect.objectContaining({ | |
| 136 | + history: expect.arrayContaining([ | |
| 137 | + expect.objectContaining({ | |
| 138 | + message: expect.objectContaining({ | |
| 139 | + role: "user", | |
| 140 | + content: "Test message", | |
| 141 | + }), | |
| 142 | + }), | |
| 143 | + ]), | |
| 144 | + }), | |
| 145 | + expect.any(Object), | |
| 146 | + ); | |
| 147 | + }); | |
| 148 | + | |
| 149 | + it("should not save to session in remote mode", async () => { | |
| 150 | + const { updateSessionHistory } = await import("../session.js"); | |
| 151 | + | |
| 152 | + await service.initialize(undefined, true); | |
| 153 | + service.addUserMessage("Remote message"); | |
| 154 | + | |
| 155 | + expect(updateSessionHistory).not.toHaveBeenCalled(); | |
| 156 | + }); | |
| 157 | + }); | |
| 158 | + | |
| 159 | + describe("addAssistantMessage", () => { | |
| 160 | + beforeEach(async () => { | |
| 161 | + await service.initialize(); | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("should add an assistant message without tool calls", () => { | |
| 165 | + const message = service.addAssistantMessage("I can help with that"); | |
| 166 | + | |
| 167 | + expect(message.message.role).toBe("assistant"); | |
| 168 | + expect(message.message.content).toBe("I can help with that"); | |
| 169 | + expect(message.toolCallStates).toBeUndefined(); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + it("should add an assistant message with tool calls", () => { | |
| 173 | + const toolCalls = [ | |
| 174 | + { | |
| 175 | + id: "tool-123", | |
| 176 | + name: "readFile", | |
| 177 | + arguments: { path: "test.txt" }, | |
| 178 | + }, | |
| 179 | + ]; | |
| 180 | + | |
| 181 | + const message = service.addAssistantMessage( | |
| 182 | + "Let me read that file", | |
| 183 | + toolCalls, | |
| 184 | + ); | |
| 185 | + | |
| 186 | + expect(message.message.role).toBe("assistant"); | |
| 187 | + expect(message.toolCallStates).toHaveLength(1); | |
| 188 | + expect(message.toolCallStates![0].toolCallId).toBe("tool-123"); | |
| 189 | + expect(message.toolCallStates![0].status).toBe("generated"); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("addSystemMessage", () => { | |
| 194 | + beforeEach(async () => { | |
| 195 | + await service.initialize(); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + it("should add a system message", () => { | |
| 199 | + const message = service.addSystemMessage("System notification"); | |
| 200 | + | |
| 201 | + expect(message.message.role).toBe("system"); | |
| 202 | + expect(message.message.content).toBe("System notification"); | |
| 203 | + }); | |
| 204 | + }); | |
| 205 | + | |
| 206 | + describe("updateToolCallState", () => { | |
| 207 | + beforeEach(async () => { | |
| 208 | + await service.initialize(); | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should update tool call state", () => { | |
| 212 | + // Add assistant message with tool call | |
| 213 | + const toolCalls = [ | |
| 214 | + { | |
| 215 | + id: "tool-456", | |
| 216 | + name: "writeFile", | |
| 217 | + arguments: { path: "output.txt", content: "data" }, | |
| 218 | + }, | |
| 219 | + ]; | |
| 220 | + | |
| 221 | + service.addAssistantMessage("Writing file", toolCalls); | |
| 222 | + | |
| 223 | + // Update the tool call state | |
| 224 | + service.updateToolCallState(0, "tool-456", { | |
| 225 | + status: "done", | |
| 226 | + output: [ | |
| 227 | + { | |
| 228 | + content: "File written successfully", | |
| 229 | + name: "Result", | |
| 230 | + description: "", | |
| 231 | + }, | |
| 232 | + ], | |
| 233 | + }); | |
| 234 | + | |
| 235 | + const state = service.getState(); | |
| 236 | + const toolState = state.history[0].toolCallStates![0]; | |
| 237 | + | |
| 238 | + expect(toolState.status).toBe("done"); | |
| 239 | + expect(toolState.output).toHaveLength(1); | |
| 240 | + expect(toolState.output![0].content).toBe("File written successfully"); | |
| 241 | + }); | |
| 242 | + | |
| 243 | + it("should handle missing tool call gracefully", () => { | |
| 244 | + service.addAssistantMessage("No tools here"); | |
| 245 | + | |
| 246 | + // Should not throw | |
| 247 | + service.updateToolCallState(0, "non-existent", { | |
| 248 | + status: "done", | |
| 249 | + }); | |
| 250 | + | |
| 251 | + // State should remain unchanged | |
| 252 | + const state = service.getState(); | |
| 253 | + expect(state.history[0].toolCallStates).toBeUndefined(); | |
| 254 | + }); | |
| 255 | + }); | |
| 256 | + | |
| 257 | + describe("addToolResult", () => { | |
| 258 | + beforeEach(async () => { | |
| 259 | + await service.initialize(); | |
| 260 | + }); | |
| 261 | + | |
| 262 | + it("should add tool result to the correct message", () => { | |
| 263 | + // Add messages with tool calls | |
| 264 | + service.addUserMessage("Do something"); | |
| 265 | + service.addAssistantMessage("Using tool", [ | |
| 266 | + { id: "tool-789", name: "search", arguments: { query: "test" } }, | |
| 267 | + ]); | |
| 268 | + | |
| 269 | + // Add tool result | |
| 270 | + service.addToolResult("tool-789", "Search results: found 5 items"); | |
| 271 | + | |
| 272 | + const state = service.getState(); | |
| 273 | + const assistantMessage = state.history[1]; | |
| 274 | + const toolState = assistantMessage.toolCallStates![0]; | |
| 275 | + | |
| 276 | + expect(toolState.status).toBe("done"); | |
| 277 | + expect(toolState.output![0].content).toBe( | |
| 278 | + "Search results: found 5 items", | |
| 279 | + ); | |
| 280 | + }); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + describe("compact", () => { | |
| 284 | + beforeEach(async () => { | |
| 285 | + await service.initialize(); | |
| 286 | + }); | |
| 287 | + | |
| 288 | + it("should compact history and update index", () => { | |
| 289 | + // Add initial messages | |
| 290 | + service.addUserMessage("Message 1"); | |
| 291 | + service.addAssistantMessage("Response 1"); | |
| 292 | + service.addUserMessage("Message 2"); | |
| 293 | + service.addAssistantMessage("Response 2"); | |
| 294 | + | |
| 295 | + // Create compacted history | |
| 296 | + const compactedHistory: ChatHistoryItem[] = [ | |
| 297 | + { | |
| 298 | + message: { | |
| 299 | + role: "system", | |
| 300 | + content: "[Compacted] Summary of messages 1-2", | |
| 301 | + }, | |
| 302 | + contextItems: [], | |
| 303 | + }, | |
| 304 | + { | |
| 305 | + message: { role: "user", content: "Message 3" }, | |
| 306 | + contextItems: [], | |
| 307 | + }, | |
| 308 | + ]; | |
| 309 | + | |
| 310 | + service.compact(compactedHistory, 0); | |
| 311 | + | |
| 312 | + const state = service.getState(); | |
| 313 | + expect(state.history).toEqual(compactedHistory); | |
| 314 | + expect(state.compactionIndex).toBe(0); | |
| 315 | + }); | |
| 316 | + }); | |
| 317 | + | |
| 318 | + describe("clear", () => { | |
| 319 | + beforeEach(async () => { | |
| 320 | + await service.initialize(); | |
| 321 | + }); | |
| 322 | + | |
| 323 | + it("should clear all history", () => { | |
| 324 | + service.addUserMessage("Message"); | |
| 325 | + service.addAssistantMessage("Response"); | |
| 326 | + | |
| 327 | + service.clear(); | |
| 328 | + | |
| 329 | + const state = service.getState(); | |
| 330 | + expect(state.history).toEqual([]); | |
| 331 | + expect(state.compactionIndex).toBeNull(); | |
| 332 | + }); | |
| 333 | + }); | |
| 334 | + | |
| 335 | + describe("getHistory and getHistoryForLLM", () => { | |
| 336 | + beforeEach(async () => { | |
| 337 | + await service.initialize(); | |
| 338 | + }); | |
| 339 | + | |
| 340 | + it("should return immutable copy of history", () => { | |
| 341 | + service.addUserMessage("Test"); | |
| 342 | + | |
| 343 | + const history1 = service.getHistory(); | |
| 344 | + const history2 = service.getHistory(); | |
| 345 | + | |
| 346 | + expect(history1).not.toBe(history2); // Different arrays | |
| 347 | + expect(history1).toEqual(history2); // Same content | |
| 348 | + }); | |
| 349 | + | |
| 350 | + it("should return full history when no compaction", () => { | |
| 351 | + service.addUserMessage("Message 1"); | |
| 352 | + service.addAssistantMessage("Response 1"); | |
| 353 | + | |
| 354 | + const historyForLLM = service.getHistoryForLLM(); | |
| 355 | + const fullHistory = service.getHistory(); | |
| 356 | + | |
| 357 | + expect(historyForLLM).toEqual(fullHistory); | |
| 358 | + }); | |
| 359 | + | |
| 360 | + it("should return history after compaction index", () => { | |
| 361 | + const history: ChatHistoryItem[] = [ | |
| 362 | + { | |
| 363 | + message: { role: "user", content: "Old message" }, | |
| 364 | + contextItems: [], | |
| 365 | + }, | |
| 366 | + { | |
| 367 | + message: { role: "system", content: "[Compacted] Summary" }, | |
| 368 | + contextItems: [], | |
| 369 | + }, | |
| 370 | + { | |
| 371 | + message: { role: "user", content: "New message" }, | |
| 372 | + contextItems: [], | |
| 373 | + }, | |
| 374 | + ]; | |
| 375 | + | |
| 376 | + service.setHistory(history); | |
| 377 | + service.setCompactionIndex(1); | |
| 378 | + | |
| 379 | + const historyForLLM = service.getHistoryForLLM(); | |
| 380 | + | |
| 381 | + expect(historyForLLM).toHaveLength(2); // Compacted message + new message | |
| 382 | + expect(historyForLLM[0].message.content).toBe("[Compacted] Summary"); | |
| 383 | + expect(historyForLLM[1].message.content).toBe("New message"); | |
| 384 | + }); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + describe("setHistory", () => { | |
| 388 | + beforeEach(async () => { | |
| 389 | + await service.initialize(); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + it("should set entire history", () => { | |
| 393 | + const newHistory: ChatHistoryItem[] = [ | |
| 394 | + { | |
| 395 | + message: { role: "user", content: "Imported message" }, | |
| 396 | + contextItems: [], | |
| 397 | + }, | |
| 398 | + ]; | |
| 399 | + | |
| 400 | + service.setHistory(newHistory); | |
| 401 | + | |
| 402 | + const state = service.getState(); | |
| 403 | + expect(state.history).toEqual(newHistory); | |
| 404 | + }); | |
| 405 | + | |
| 406 | + it("should detect compaction index when setting history", () => { | |
| 407 | + const historyWithCompaction: ChatHistoryItem[] = [ | |
| 408 | + { | |
| 409 | + message: { role: "assistant", content: "old summary" }, | |
| 410 | + contextItems: [], | |
| 411 | + conversationSummary: "old summary", | |
| 412 | + }, | |
| 413 | + { | |
| 414 | + message: { role: "user", content: "Recent message" }, | |
| 415 | + contextItems: [], | |
| 416 | + }, | |
| 417 | + ]; | |
| 418 | + | |
| 419 | + service.setHistory(historyWithCompaction); | |
| 420 | + | |
| 421 | + const state = service.getState(); | |
| 422 | + expect(state.compactionIndex).toBe(0); | |
| 423 | + }); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + describe("undo/redo", () => { | |
| 427 | + beforeEach(async () => { | |
| 428 | + await service.initialize(); | |
| 429 | + }); | |
| 430 | + | |
| 431 | + it("should undo last change and redo it", () => { | |
| 432 | + service.addUserMessage("A"); | |
| 433 | + service.addAssistantMessage("B"); | |
| 434 | + | |
| 435 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 436 | + "A", | |
| 437 | + "B", | |
| 438 | + ]); | |
| 439 | + | |
| 440 | + expect(service.canUndo()).toBe(true); | |
| 441 | + service.undo(); | |
| 442 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 443 | + "A", | |
| 444 | + ]); | |
| 445 | + | |
| 446 | + expect(service.canRedo()).toBe(true); | |
| 447 | + service.redo(); | |
| 448 | + expect(service.getState().history.map((m) => m.message.content)).toEqual([ | |
| 449 | + "A", | |
| 450 | + "B", | |
| 451 | + ]); | |
| 452 | + }); | |
| 453 | + | |
| 454 | + it("should support undoing tool state updates", () => { | |
| 455 | + service.addAssistantMessage("Using tool", [ | |
| 456 | + { id: "t1", name: "Read", arguments: { path: "file" } }, | |
| 457 | + ]); | |
| 458 | + const before = service.getHistory(); | |
| 459 | + service.addToolResult("t1", "ok", "done"); | |
| 460 | + const after = service.getHistory(); | |
| 461 | + | |
| 462 | + expect(after[0].toolCallStates?.[0].status).toBe("done"); | |
| 463 | + service.undo(); | |
| 464 | + const undone = service.getHistory(); | |
| 465 | + expect(undone[0].toolCallStates?.[0].status).toBe( | |
| 466 | + before[0].toolCallStates?.[0].status, | |
| 467 | + ); | |
| 468 | + }); | |
| 469 | + }); | |
| 470 | + | |
| 471 | + describe("immutability", () => { | |
| 472 | + beforeEach(async () => { | |
| 473 | + await service.initialize(); | |
| 474 | + }); | |
| 475 | + | |
| 476 | + it("should not allow external mutation of state", () => { | |
| 477 | + service.addUserMessage("Test"); | |
| 478 | + | |
| 479 | + const state = service.getState(); | |
| 480 | + const originalLength = state.history.length; | |
| 481 | + | |
| 482 | + // Try to mutate | |
| 483 | + state.history.push({ | |
| 484 | + message: { role: "user", content: "Hacked!" }, | |
| 485 | + contextItems: [], | |
| 486 | + }); | |
| 487 | + | |
| 488 | + // Check that internal state wasn't affected | |
| 489 | + const newState = service.getState(); | |
| 490 | + expect(newState.history).toHaveLength(originalLength); | |
| 491 | + }); | |
| 492 | + | |
| 493 | + it("should not allow mutation through getHistory", () => { | |
| 494 | + service.addUserMessage("Test"); | |
| 495 | + | |
| 496 | + const history = service.getHistory(); | |
| 497 | + const originalLength = history.length; | |
| 498 | + | |
| 499 | + // Try to mutate | |
| 500 | + history.push({ | |
| 501 | + message: { role: "user", content: "Hacked!" }, | |
| 502 | + contextItems: [], | |
| 503 | + }); | |
| 504 | + | |
| 505 | + // Check that internal state wasn't affected | |
| 506 | + const newHistory = service.getHistory(); | |
| 507 | + expect(newHistory).toHaveLength(originalLength); | |
| 508 | + }); | |
| 509 | + }); | |
| 510 | + | |
| 511 | + describe("event emissions", () => { | |
| 512 | + beforeEach(async () => { | |
| 513 | + await service.initialize(); | |
| 514 | + }); | |
| 515 | + | |
| 516 | + it("should emit stateChanged on every update", () => { | |
| 517 | + const listener = vi.fn(); | |
| 518 | + service.on("stateChanged", listener); | |
| 519 | + | |
| 520 | + service.addUserMessage("Message 1"); | |
| 521 | + service.addAssistantMessage("Response 1"); | |
| 522 | + service.addSystemMessage("System"); | |
| 523 | + service.clear(); | |
| 524 | + | |
| 525 | + expect(listener).toHaveBeenCalledTimes(4); | |
| 526 | + }); | |
| 527 | + | |
| 528 | + it("should provide old and new state in event", () => { | |
| 529 | + const listener = vi.fn(); | |
| 530 | + service.on("stateChanged", listener); | |
| 531 | + | |
| 532 | + service.addUserMessage("Test"); | |
| 533 | + | |
| 534 | + expect(listener).toHaveBeenCalledWith( | |
| 535 | + expect.objectContaining({ | |
| 536 | + history: expect.arrayContaining([ | |
| 537 | + expect.objectContaining({ | |
| 538 | + message: expect.objectContaining({ content: "Test" }), | |
| 539 | + }), | |
| 540 | + ]), | |
| 541 | + }), | |
| 542 | + expect.objectContaining({ | |
| 543 | + history: [], | |
| 544 | + }), | |
| 545 | + ); | |
| 546 | + }); | |
| 547 | + }); | |
| 548 | +}); |
| @@ -0,0 +1,534 @@ | ||
| 1 | +import type { ChatHistoryItem, ToolStatus } from "core/index.js"; | |
| 2 | +import { createHistoryItem } from "core/util/messageConversion.js"; | |
| 3 | + | |
| 4 | +import { | |
| 5 | + updateSessionHistory, | |
| 6 | + loadSessionById, | |
| 7 | + createSession, | |
| 8 | +} from "../session.js"; | |
| 9 | +import { logger } from "../util/logger.js"; | |
| 10 | + | |
| 11 | +import { BaseService } from "./BaseService.js"; | |
| 12 | + | |
| 13 | +/** | |
| 14 | + * State managed by the ChatHistoryService | |
| 15 | + */ | |
| 16 | +export interface ChatHistoryState { | |
| 17 | + history: ChatHistoryItem[]; | |
| 18 | + compactionIndex: number | null; | |
| 19 | + sessionId: string; | |
| 20 | + isRemoteMode: boolean; | |
| 21 | +} | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Service for managing chat history as the single source of truth | |
| 25 | + * Provides immutable updates and automatic React integration via events | |
| 26 | + */ | |
| 27 | +export class ChatHistoryService extends BaseService<ChatHistoryState> { | |
| 28 | + // Simple undo/redo stacks for history snapshots | |
| 29 | + private past: ChatHistoryItem[][] = []; | |
| 30 | + private future: ChatHistoryItem[][] = []; | |
| 31 | + // Memoized snapshot for referential stability in getState() | |
| 32 | + private _memoSnapshot: { | |
| 33 | + stateRef: ChatHistoryState | null; | |
| 34 | + historyRef: ChatHistoryItem[] | null; | |
| 35 | + snapshot: ChatHistoryState | null; | |
| 36 | + } = { stateRef: null, historyRef: null, snapshot: null }; | |
| 37 | + | |
| 38 | + constructor() { | |
| 39 | + super("ChatHistoryService", { | |
| 40 | + history: [], | |
| 41 | + compactionIndex: null, | |
| 42 | + sessionId: "", | |
| 43 | + isRemoteMode: false, | |
| 44 | + }); | |
| 45 | + this.setMaxListeners(50); | |
| 46 | + } | |
| 47 | + | |
| 48 | + private setHistoryInternal( | |
| 49 | + history: ChatHistoryItem[], | |
| 50 | + options: { | |
| 51 | + recordUndo?: boolean; | |
| 52 | + compactionIndex?: number | null; | |
| 53 | + persist?: boolean; // set to false to skip persistence (rare) | |
| 54 | + } = {}, | |
| 55 | + ): void { | |
| 56 | + const { recordUndo = true, compactionIndex, persist } = options; | |
| 57 | + const prev = this.currentState.history; | |
| 58 | + if (recordUndo) { | |
| 59 | + this.past.push([...prev]); | |
| 60 | + this.future = []; | |
| 61 | + } | |
| 62 | + this.setState({ | |
| 63 | + history: [...history], | |
| 64 | + compactionIndex: | |
| 65 | + compactionIndex === undefined | |
| 66 | + ? this.findCompactionIndex(history) | |
| 67 | + : compactionIndex, | |
| 68 | + }); | |
| 69 | + | |
| 70 | + if (this.currentState.isRemoteMode) { | |
| 71 | + // Skip persistence in remote mode | |
| 72 | + } else if (persist !== false) { | |
| 73 | + updateSessionHistory(history); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * Initialize the service with optional session | |
| 79 | + */ | |
| 80 | + async doInitialize( | |
| 81 | + session?: any, | |
| 82 | + isRemoteMode = false, | |
| 83 | + ): Promise<ChatHistoryState> { | |
| 84 | + const activeSession = session || createSession([]); | |
| 85 | + | |
| 86 | + logger.debug("Initializing ChatHistoryService", { | |
| 87 | + sessionId: activeSession.sessionId, | |
| 88 | + historyLength: activeSession.history.length, | |
| 89 | + isRemoteMode, | |
| 90 | + }); | |
| 91 | + | |
| 92 | + return { | |
| 93 | + history: activeSession.history || [], | |
| 94 | + compactionIndex: this.findCompactionIndex(activeSession.history || []), | |
| 95 | + sessionId: activeSession.sessionId, | |
| 96 | + isRemoteMode, | |
| 97 | + }; | |
| 98 | + } | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * Add a user message to the history | |
| 102 | + */ | |
| 103 | + addUserMessage(content: string, contextItems: any[] = []): ChatHistoryItem { | |
| 104 | + const newMessage = createHistoryItem( | |
| 105 | + { | |
| 106 | + role: "user", | |
| 107 | + content, | |
| 108 | + }, | |
| 109 | + contextItems, | |
| 110 | + ); | |
| 111 | + | |
| 112 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 113 | + this.setHistoryInternal(newHistory); | |
| 114 | + | |
| 115 | + logger.debug("Added user message", { | |
| 116 | + contentLength: content.length, | |
| 117 | + contextItemCount: contextItems.length, | |
| 118 | + newHistoryLength: newHistory.length, | |
| 119 | + }); | |
| 120 | + | |
| 121 | + return newMessage; | |
| 122 | + } | |
| 123 | + | |
| 124 | + /** | |
| 125 | + * Add an assistant message to the history | |
| 126 | + */ | |
| 127 | + addAssistantMessage(content: string, toolCalls?: any[]): ChatHistoryItem { | |
| 128 | + const message: any = { | |
| 129 | + role: "assistant", | |
| 130 | + content, | |
| 131 | + }; | |
| 132 | + | |
| 133 | + if (toolCalls && toolCalls.length > 0) { | |
| 134 | + message.toolCalls = toolCalls; | |
| 135 | + } | |
| 136 | + | |
| 137 | + const toolCallStates = toolCalls?.map((tc) => { | |
| 138 | + const id = tc.id; | |
| 139 | + const name = tc.function?.name ?? tc.name; | |
| 140 | + // Prefer explicit string arguments; otherwise stringify object arguments | |
| 141 | + let rawArgStr: string; | |
| 142 | + if (typeof tc.arguments === "string") { | |
| 143 | + rawArgStr = tc.arguments; | |
| 144 | + } else if (typeof tc.function?.arguments === "string") { | |
| 145 | + rawArgStr = tc.function.arguments; | |
| 146 | + } else if (tc.arguments === undefined) { | |
| 147 | + rawArgStr = | |
| 148 | + tc.function?.arguments === undefined | |
| 149 | + ? "{}" | |
| 150 | + : String(tc.function.arguments); | |
| 151 | + } else { | |
| 152 | + rawArgStr = JSON.stringify(tc.arguments); | |
| 153 | + } | |
| 154 | + | |
| 155 | + // parsedArgs: prefer object, else parse the string if possible | |
| 156 | + let parsedArgs: any = {}; | |
| 157 | + if (tc && typeof tc.arguments === "object" && tc.arguments !== null) { | |
| 158 | + parsedArgs = tc.arguments; | |
| 159 | + } else if (typeof rawArgStr === "string") { | |
| 160 | + try { | |
| 161 | + parsedArgs = JSON.parse(rawArgStr); | |
| 162 | + } catch { | |
| 163 | + parsedArgs = {}; | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + return { | |
| 168 | + toolCallId: id, | |
| 169 | + toolCall: { | |
| 170 | + id, | |
| 171 | + type: "function" as const, | |
| 172 | + function: { | |
| 173 | + name, | |
| 174 | + arguments: rawArgStr, | |
| 175 | + }, | |
| 176 | + }, | |
| 177 | + status: "generated" as ToolStatus, | |
| 178 | + parsedArgs, | |
| 179 | + }; | |
| 180 | + }); | |
| 181 | + | |
| 182 | + const newMessage = createHistoryItem(message, [], toolCallStates); | |
| 183 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 184 | + this.setHistoryInternal(newHistory); | |
| 185 | + | |
| 186 | + logger.debug("Added assistant message", { | |
| 187 | + contentLength: content.length, | |
| 188 | + toolCallCount: toolCalls?.length || 0, | |
| 189 | + newHistoryLength: newHistory.length, | |
| 190 | + }); | |
| 191 | + | |
| 192 | + return newMessage; | |
| 193 | + } | |
| 194 | + | |
| 195 | + /** | |
| 196 | + * Add a system message to the history | |
| 197 | + */ | |
| 198 | + addSystemMessage(content: string): ChatHistoryItem { | |
| 199 | + const newMessage = createHistoryItem({ | |
| 200 | + role: "system", | |
| 201 | + content, | |
| 202 | + }); | |
| 203 | + | |
| 204 | + const newHistory = [...this.currentState.history, newMessage]; | |
| 205 | + this.setHistoryInternal(newHistory); | |
| 206 | + | |
| 207 | + logger.debug("Added system message", { | |
| 208 | + contentLength: content.length, | |
| 209 | + newHistoryLength: newHistory.length, | |
| 210 | + }); | |
| 211 | + | |
| 212 | + return newMessage; | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * Add a generic history item | |
| 217 | + */ | |
| 218 | + addHistoryItem(item: ChatHistoryItem): ChatHistoryItem { | |
| 219 | + const newHistory = [...this.currentState.history, item]; | |
| 220 | + this.setHistoryInternal(newHistory); | |
| 221 | + | |
| 222 | + logger.debug("Added history item", { | |
| 223 | + role: item.message.role, | |
| 224 | + newHistoryLength: newHistory.length, | |
| 225 | + }); | |
| 226 | + | |
| 227 | + return item; | |
| 228 | + } | |
| 229 | + | |
| 230 | + /** | |
| 231 | + * Update a tool call state within a message | |
| 232 | + */ | |
| 233 | + updateToolCallState( | |
| 234 | + messageIndex: number, | |
| 235 | + toolCallId: string, | |
| 236 | + updates: Partial<{ | |
| 237 | + status: ToolStatus; | |
| 238 | + output: any[]; | |
| 239 | + }>, | |
| 240 | + ): void { | |
| 241 | + const newHistory = [...this.currentState.history]; | |
| 242 | + const message = newHistory[messageIndex]; | |
| 243 | + | |
| 244 | + if (!message?.toolCallStates) { | |
| 245 | + logger.warn("No tool call states found at message index", { | |
| 246 | + messageIndex, | |
| 247 | + toolCallId, | |
| 248 | + }); | |
| 249 | + return; | |
| 250 | + } | |
| 251 | + | |
| 252 | + const toolState = message.toolCallStates.find( | |
| 253 | + (ts) => ts.toolCallId === toolCallId, | |
| 254 | + ); | |
| 255 | + | |
| 256 | + if (!toolState) { | |
| 257 | + logger.warn("Tool call state not found", { | |
| 258 | + messageIndex, | |
| 259 | + toolCallId, | |
| 260 | + availableIds: message.toolCallStates.map((ts) => ts.toolCallId), | |
| 261 | + }); | |
| 262 | + return; | |
| 263 | + } | |
| 264 | + | |
| 265 | + // Create a new message with updated tool state (immutable) | |
| 266 | + newHistory[messageIndex] = { | |
| 267 | + ...message, | |
| 268 | + toolCallStates: message.toolCallStates.map((ts) => | |
| 269 | + ts.toolCallId === toolCallId ? { ...ts, ...updates } : ts, | |
| 270 | + ), | |
| 271 | + }; | |
| 272 | + | |
| 273 | + this.setHistoryInternal(newHistory); | |
| 274 | + | |
| 275 | + logger.debug("Updated tool call state", { | |
| 276 | + messageIndex, | |
| 277 | + toolCallId, | |
| 278 | + updates, | |
| 279 | + }); | |
| 280 | + } | |
| 281 | + | |
| 282 | + /** | |
| 283 | + * Add a tool result to the history | |
| 284 | + */ | |
| 285 | + addToolResult( | |
| 286 | + toolCallId: string, | |
| 287 | + result: string, | |
| 288 | + status: ToolStatus = "done", | |
| 289 | + ): void { | |
| 290 | + // Find the last assistant message with this tool call | |
| 291 | + let targetIndex = -1; | |
| 292 | + for (let i = this.currentState.history.length - 1; i >= 0; i--) { | |
| 293 | + const item = this.currentState.history[i]; | |
| 294 | + if (item.message.role === "assistant" && item.toolCallStates) { | |
| 295 | + const hasToolCall = item.toolCallStates.some( | |
| 296 | + (ts) => ts.toolCallId === toolCallId, | |
| 297 | + ); | |
| 298 | + if (hasToolCall) { | |
| 299 | + targetIndex = i; | |
| 300 | + break; | |
| 301 | + } | |
| 302 | + } | |
| 303 | + } | |
| 304 | + | |
| 305 | + if (targetIndex >= 0) { | |
| 306 | + this.updateToolCallState(targetIndex, toolCallId, { | |
| 307 | + status, | |
| 308 | + output: [ | |
| 309 | + { | |
| 310 | + content: result, | |
| 311 | + name: "Tool Result", | |
| 312 | + description: "Tool execution result", | |
| 313 | + }, | |
| 314 | + ], | |
| 315 | + }); | |
| 316 | + } else { | |
| 317 | + logger.warn("Could not find message for tool result", { toolCallId }); | |
| 318 | + } | |
| 319 | + } | |
| 320 | + | |
| 321 | + /** | |
| 322 | + * Update a tool's status (e.g., set to "calling" immediately on approval) | |
| 323 | + */ | |
| 324 | + updateToolStatus(toolCallId: string, status: ToolStatus): void { | |
| 325 | + // Find the last assistant message with this tool call | |
| 326 | + let targetIndex = -1; | |
| 327 | + for (let i = this.currentState.history.length - 1; i >= 0; i--) { | |
| 328 | + const item = this.currentState.history[i]; | |
| 329 | + if (item.message.role === "assistant" && item.toolCallStates) { | |
| 330 | + const hasToolCall = item.toolCallStates.some( | |
| 331 | + (ts) => ts.toolCallId === toolCallId, | |
| 332 | + ); | |
| 333 | + if (hasToolCall) { | |
| 334 | + targetIndex = i; | |
| 335 | + break; | |
| 336 | + } | |
| 337 | + } | |
| 338 | + } | |
| 339 | + | |
| 340 | + if (targetIndex >= 0) { | |
| 341 | + this.updateToolCallState(targetIndex, toolCallId, { status }); | |
| 342 | + } else { | |
| 343 | + logger.warn("Could not find message for tool status update", { | |
| 344 | + toolCallId, | |
| 345 | + status, | |
| 346 | + }); | |
| 347 | + } | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Perform compaction on the history | |
| 352 | + */ | |
| 353 | + compact(newHistory: ChatHistoryItem[], compactionIndex: number): void { | |
| 354 | + this.setHistoryInternal(newHistory, { compactionIndex }); | |
| 355 | + | |
| 356 | + logger.debug("Compacted history", { | |
| 357 | + oldLength: this.currentState.history.length, | |
| 358 | + newLength: newHistory.length, | |
| 359 | + compactionIndex, | |
| 360 | + }); | |
| 361 | + } | |
| 362 | + | |
| 363 | + /** | |
| 364 | + * Clear the chat history | |
| 365 | + */ | |
| 366 | + clear(): void { | |
| 367 | + this.setHistoryInternal([], { compactionIndex: null }); | |
| 368 | + | |
| 369 | + logger.debug("Cleared chat history"); | |
| 370 | + } | |
| 371 | + | |
| 372 | + /** | |
| 373 | + * Load a session into the service | |
| 374 | + */ | |
| 375 | + async loadSession(sessionId: string): Promise<void> { | |
| 376 | + const session = loadSessionById(sessionId); | |
| 377 | + if (session) { | |
| 378 | + // Load new history without recording undo; set sessionId separately | |
| 379 | + this.setHistoryInternal(session.history, { recordUndo: false }); | |
| 380 | + this.setState({ sessionId: session.sessionId }); | |
| 381 | + | |
| 382 | + logger.debug("Loaded session", { | |
| 383 | + sessionId, | |
| 384 | + historyLength: session.history.length, | |
| 385 | + }); | |
| 386 | + } else { | |
| 387 | + logger.warn("Session not found", { sessionId }); | |
| 388 | + } | |
| 389 | + } | |
| 390 | + | |
| 391 | + /** | |
| 392 | + * Get an immutable copy of the current history | |
| 393 | + */ | |
| 394 | + getHistory(): ChatHistoryItem[] { | |
| 395 | + return [...this.currentState.history]; | |
| 396 | + } | |
| 397 | + | |
| 398 | + /** | |
| 399 | + * Get history for LLM (considering compaction) | |
| 400 | + */ | |
| 401 | + getHistoryForLLM(compactionIndex?: number | null): ChatHistoryItem[] { | |
| 402 | + const index = compactionIndex ?? this.currentState.compactionIndex; | |
| 403 | + const full = this.currentState.history; | |
| 404 | + if (index === null || index === undefined || index >= full.length) { | |
| 405 | + return this.getHistory(); | |
| 406 | + } | |
| 407 | + const systemMessage = full[0]?.message?.role === "system" ? full[0] : null; | |
| 408 | + const messagesFromCompaction = full.slice(index); | |
| 409 | + return systemMessage && index > 0 | |
| 410 | + ? [systemMessage, ...messagesFromCompaction] | |
| 411 | + : messagesFromCompaction; | |
| 412 | + } | |
| 413 | + | |
| 414 | + /** | |
| 415 | + * Set the entire history (for remote mode or special cases) | |
| 416 | + */ | |
| 417 | + setHistory(history: ChatHistoryItem[]): void { | |
| 418 | + this.setHistoryInternal(history); | |
| 419 | + logger.debug("Set entire history", { | |
| 420 | + historyLength: history.length, | |
| 421 | + }); | |
| 422 | + } | |
| 423 | + | |
| 424 | + /** | |
| 425 | + * Update compaction index | |
| 426 | + */ | |
| 427 | + setCompactionIndex(index: number | null): void { | |
| 428 | + this.setState({ | |
| 429 | + compactionIndex: index, | |
| 430 | + }); | |
| 431 | + | |
| 432 | + logger.debug("Updated compaction index", { index }); | |
| 433 | + } | |
| 434 | + | |
| 435 | + /** | |
| 436 | + * Find compaction index in history | |
| 437 | + */ | |
| 438 | + private findCompactionIndex(history: ChatHistoryItem[]): number | null { | |
| 439 | + const idx = history.findIndex( | |
| 440 | + (item) => item.conversationSummary !== undefined, | |
| 441 | + ); | |
| 442 | + return idx === -1 ? null : idx; | |
| 443 | + } | |
| 444 | + | |
| 445 | + // Undo/Redo API | |
| 446 | + canUndo(): boolean { | |
| 447 | + return this.past.length > 0; | |
| 448 | + } | |
| 449 | + | |
| 450 | + canRedo(): boolean { | |
| 451 | + return this.future.length > 0; | |
| 452 | + } | |
| 453 | + | |
| 454 | + undo(): void { | |
| 455 | + if (!this.canUndo()) return; | |
| 456 | + const prev = this.past.pop()!; | |
| 457 | + this.future.push([...this.currentState.history]); | |
| 458 | + this.setHistoryInternal(prev, { recordUndo: false }); | |
| 459 | + } | |
| 460 | + | |
| 461 | + redo(): void { | |
| 462 | + if (!this.canRedo()) return; | |
| 463 | + const next = this.future.pop()!; | |
| 464 | + this.past.push([...this.currentState.history]); | |
| 465 | + this.setHistoryInternal(next, { recordUndo: false }); | |
| 466 | + } | |
| 467 | + | |
| 468 | + /** | |
| 469 | + * Get current session ID | |
| 470 | + */ | |
| 471 | + getSessionId(): string { | |
| 472 | + return this.currentState.sessionId; | |
| 473 | + } | |
| 474 | + | |
| 475 | + /** | |
| 476 | + * Check if in remote mode | |
| 477 | + */ | |
| 478 | + isRemoteMode(): boolean { | |
| 479 | + return this.currentState.isRemoteMode; | |
| 480 | + } | |
| 481 | + | |
| 482 | + /** | |
| 483 | + * Set remote mode | |
| 484 | + */ | |
| 485 | + setRemoteMode(isRemote: boolean): void { | |
| 486 | + this.setState({ | |
| 487 | + isRemoteMode: isRemote, | |
| 488 | + }); | |
| 489 | + } | |
| 490 | + | |
| 491 | + /** | |
| 492 | + * Override getState to ensure deep immutability for history array | |
| 493 | + */ | |
| 494 | + getState(): ChatHistoryState { | |
| 495 | + const stateRef = this.currentState; | |
| 496 | + const historyRef = stateRef.history; | |
| 497 | + | |
| 498 | + // If neither the state object nor the history reference changed, | |
| 499 | + // return the same memoized snapshot to preserve referential stability | |
| 500 | + if ( | |
| 501 | + this._memoSnapshot.snapshot && | |
| 502 | + this._memoSnapshot.stateRef === stateRef && | |
| 503 | + this._memoSnapshot.historyRef === historyRef | |
| 504 | + ) { | |
| 505 | + return this._memoSnapshot.snapshot; | |
| 506 | + } | |
| 507 | + | |
| 508 | + // Build a memoized snapshot object with getters to: | |
| 509 | + // - keep the outer object reference stable when unchanged | |
| 510 | + // - return a fresh copy of history on each access to prevent external mutation | |
| 511 | + const snapshot = {} as ChatHistoryState; | |
| 512 | + Object.defineProperties(snapshot, { | |
| 513 | + history: { | |
| 514 | + enumerable: true, | |
| 515 | + get: () => [...stateRef.history], | |
| 516 | + }, | |
| 517 | + compactionIndex: { | |
| 518 | + enumerable: true, | |
| 519 | + get: () => stateRef.compactionIndex, | |
| 520 | + }, | |
| 521 | + sessionId: { | |
| 522 | + enumerable: true, | |
| 523 | + get: () => stateRef.sessionId, | |
| 524 | + }, | |
| 525 | + isRemoteMode: { | |
| 526 | + enumerable: true, | |
| 527 | + get: () => stateRef.isRemoteMode, | |
| 528 | + }, | |
| 529 | + }); | |
| 530 | + | |
| 531 | + this._memoSnapshot = { stateRef, historyRef, snapshot }; | |
| 532 | + return snapshot; | |
| 533 | + } | |
| 534 | +} |
| @@ -59,24 +59,25 @@ | ||
| 59 | 59 | expect(filePaths).toContain("README.md"); |
| 60 | 60 | }); |
| 61 | 61 | |
| 62 | - it("should filter files correctly", async () => { | |
| 62 | + it("should filter files correctly with fzf", async () => { | |
| 63 | 63 | // Create test files |
| 64 | 64 | fs.writeFileSync("component.tsx", "export default () => <div></div>"); |
| 65 | 65 | fs.writeFileSync("utils.ts", "export const util = () => {}"); |
| 66 | - fs.writeFileSync("styles.css", ".test { color: red; }"); | |
| 66 | + fs.writeFileSync("readme.md", "# Documentation"); | |
| 67 | 67 | |
| 68 | 68 | await service.initialize(); |
| 69 | 69 | |
| 70 | - // Test filtering by extension | |
| 71 | - const tsFiles = service.filterFiles("ts"); | |
| 72 | - expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true); | |
| 73 | - expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true); | |
| 74 | - expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false); | |
| 70 | + // Test filtering with more specific terms that won't fuzzy match | |
| 71 | + const tsxFiles = await service.filterFiles("tsx"); | |
| 72 | + expect(tsxFiles.some((f) => f.path === "component.tsx")).toBe(true); | |
| 73 | + expect(tsxFiles.some((f) => f.path === "utils.ts")).toBe(false); | |
| 74 | + expect(tsxFiles.some((f) => f.path === "readme.md")).toBe(false); | |
| 75 | 75 | |
| 76 | 76 | // Test filtering by name |
| 77 | - const componentFiles = service.filterFiles("component"); | |
| 77 | + const componentFiles = await service.filterFiles("component"); | |
| 78 | 78 | expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true); |
| 79 | 79 | expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false); |
| 80 | + expect(componentFiles.some((f) => f.path === "readme.md")).toBe(false); | |
| 80 | 81 | }); |
| 81 | 82 | |
| 82 | 83 | it("should handle empty directory", async () => { |
| @@ -123,7 +124,7 @@ | ||
| 123 | 124 | |
| 124 | 125 | await service.initialize(); |
| 125 | 126 | |
| 126 | - const files = service.filterFiles(""); | |
| 127 | + const files = await service.filterFiles(""); | |
| 127 | 128 | expect(files[0].path).toBe("alpha.js"); |
| 128 | 129 | expect(files[1].path).toBe("beta.js"); |
| 129 | 130 | expect(files[2].path).toBe("zebra.js"); |
| @@ -137,7 +138,7 @@ | ||
| 137 | 138 | |
| 138 | 139 | await service.initialize(); |
| 139 | 140 | |
| 140 | - const filtered = service.filterFiles("test"); | |
| 141 | + const filtered = await service.filterFiles("test"); | |
| 141 | 142 | |
| 142 | 143 | // Should include both files that match the filter |
| 143 | 144 | expect(filtered.length).toBeGreaterThanOrEqual(2); |
| @@ -155,7 +156,7 @@ | ||
| 155 | 156 | |
| 156 | 157 | await service.initialize(); |
| 157 | 158 | |
| 158 | - const files = service.filterFiles("", 5); | |
| 159 | + const files = await service.filterFiles("", 5); | |
| 159 | 160 | expect(files.length).toBe(5); |
| 160 | 161 | }); |
| 161 | 162 | |
| @@ -173,4 +174,36 @@ | ||
| 173 | 174 | await service.refreshIndex(); |
| 174 | 175 | expect(service.getFiles().length).toBe(2); |
| 175 | 176 | }); |
| 177 | + | |
| 178 | + it("should handle fuzzy search with AsyncFzf", async () => { | |
| 179 | + // Create test files for fuzzy matching | |
| 180 | + fs.writeFileSync("user-service.ts", "export class UserService {}"); | |
| 181 | + fs.writeFileSync("user-model.ts", "export interface User {}"); | |
| 182 | + fs.writeFileSync("config.json", "{}"); | |
| 183 | + | |
| 184 | + await service.initialize(); | |
| 185 | + | |
| 186 | + // Test fuzzy search (should match both user files) | |
| 187 | + const userFiles = await service.filterFiles("usmo"); // us(er) mo(del) | |
| 188 | + expect(userFiles.length).equal(1); | |
| 189 | + expect(userFiles.some((f) => f.path === "user-model.ts")).toBe(true); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + it("should find files with @ symbols when searched with @ pattern", async () => { | |
| 193 | + // Create test file with @ symbols in the name | |
| 194 | + fs.writeFileSync("test@123.txt", "test content"); | |
| 195 | + fs.writeFileSync("regular-file.js", "normal file"); | |
| 196 | + fs.writeFileSync("other@456.md", "other content"); | |
| 197 | + | |
| 198 | + await service.initialize(); | |
| 199 | + | |
| 200 | + // Search for "test@123" - should match "test@123.txt" | |
| 201 | + const results = await service.filterFiles("test@123"); | |
| 202 | + | |
| 203 | + expect(results.length).equal(1); | |
| 204 | + expect(results.some((f) => f.path === "test@123.txt")).toBe(true); | |
| 205 | + | |
| 206 | + // Should not match files that don't contain the @ pattern | |
| 207 | + expect(results.some((f) => f.path === "regular-file.js")).toBe(false); | |
| 208 | + }); | |
| 176 | 209 | }); |
| @@ -1,8 +1,7 @@ | ||
| 1 | -import { glob, GlobOptionsWithFileTypesFalse } from "glob"; | |
| 2 | - | |
| 3 | -import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js"; | |
| 4 | -import { getFileWatcher } from "../util/fileWatcher.js"; | |
| 5 | -import { isGitRepo } from "../util/git.js"; | |
| 1 | +import { fdir } from "fdir"; | |
| 2 | +import { AsyncFzf, FzfResultItem } from "fzf"; | |
| 3 | + | |
| 4 | +import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; | |
| 6 | 5 | import { logger } from "../util/logger.js"; |
| 7 | 6 | |
| 8 | 7 | import { BaseService } from "./BaseService.js"; |
| @@ -11,6 +10,7 @@ | ||
| 11 | 10 | export interface FileItem { |
| 12 | 11 | path: string; |
| 13 | 12 | displayName: string; |
| 13 | + positions?: Set<number>; | |
| 14 | 14 | } |
| 15 | 15 | |
| 16 | 16 | export interface FileIndexServiceState { |
| @@ -20,9 +20,79 @@ | ||
| 20 | 20 | } |
| 21 | 21 | |
| 22 | 22 | export class FileIndexService extends BaseService<FileIndexServiceState> { |
| 23 | - private fileSet = new Set<string>(); | |
| 24 | - private fileWatcherInitialized = false; | |
| 25 | - private fileWatcherUnsubscribe: (() => void) | null = null; | |
| 23 | + private fzf: AsyncFzf<FileItem[]> | null = null; | |
| 24 | + | |
| 25 | + // Helper to check if a file should be included based on FILE_PATTERNS | |
| 26 | + private shouldIncludeFile(filePath: string): boolean { | |
| 27 | + const fileName = filePath.split("/").pop()?.toLowerCase() || ""; | |
| 28 | + const ext = fileName.split(".").pop(); | |
| 29 | + | |
| 30 | + // Check if file matches any of the original FILE_PATTERNS | |
| 31 | + const supportedExtensions = [ | |
| 32 | + "ts", | |
| 33 | + "tsx", | |
| 34 | + "js", | |
| 35 | + "jsx", | |
| 36 | + "py", | |
| 37 | + "java", | |
| 38 | + "cpp", | |
| 39 | + "c", | |
| 40 | + "h", | |
| 41 | + "hpp", | |
| 42 | + "cs", | |
| 43 | + "go", | |
| 44 | + "rs", | |
| 45 | + "rb", | |
| 46 | + "php", | |
| 47 | + "swift", | |
| 48 | + "kt", | |
| 49 | + "scala", | |
| 50 | + "md", | |
| 51 | + "json", | |
| 52 | + "yaml", | |
| 53 | + "yml", | |
| 54 | + "xml", | |
| 55 | + "html", | |
| 56 | + "css", | |
| 57 | + "scss", | |
| 58 | + "sass", | |
| 59 | + "less", | |
| 60 | + "sql", | |
| 61 | + "sh", | |
| 62 | + "dockerfile", | |
| 63 | + "makefile", | |
| 64 | + "cmake", | |
| 65 | + "gradle", | |
| 66 | + "toml", | |
| 67 | + "ini", | |
| 68 | + "env", | |
| 69 | + "txt", | |
| 70 | + "log", | |
| 71 | + ]; | |
| 72 | + | |
| 73 | + // Check extension match | |
| 74 | + if (ext && supportedExtensions.includes(ext)) { | |
| 75 | + return true; | |
| 76 | + } | |
| 77 | + | |
| 78 | + // Check special file patterns | |
| 79 | + if ( | |
| 80 | + fileName.startsWith("readme") || | |
| 81 | + fileName.startsWith("license") || | |
| 82 | + fileName.startsWith("changelog") || | |
| 83 | + fileName === "package.json" || | |
| 84 | + fileName === "cargo.toml" || | |
| 85 | + fileName === "pyproject.toml" || | |
| 86 | + fileName === "composer.json" || | |
| 87 | + fileName === "gemfile" || | |
| 88 | + fileName === ".gitignore" || | |
| 89 | + fileName.startsWith(".env") | |
| 90 | + ) { | |
| 91 | + return true; | |
| 92 | + } | |
| 93 | + | |
| 94 | + return false; | |
| 95 | + } | |
| 26 | 96 | |
| 27 | 97 | constructor() { |
| 28 | 98 | super("FileIndexService", { |
| @@ -34,23 +104,11 @@ | ||
| 34 | 104 | |
| 35 | 105 | async doInitialize(): Promise<FileIndexServiceState> { |
| 36 | 106 | await this.performFullIndex(); |
| 37 | - this.setupFileWatcher(); | |
| 38 | 107 | return this.getState(); |
| 39 | 108 | } |
| 40 | 109 | |
| 41 | 110 | async cleanup(): Promise<void> { |
| 42 | - if (this.fileWatcherUnsubscribe) { | |
| 43 | - this.fileWatcherUnsubscribe(); | |
| 44 | - this.fileWatcherUnsubscribe = null; | |
| 45 | - } | |
| 46 | - | |
| 47 | - // Stop the file watcher to prevent resource leaks | |
| 48 | - if (this.fileWatcherInitialized) { | |
| 49 | - const watcher = getFileWatcher(); | |
| 50 | - watcher.stopWatching(); | |
| 51 | - } | |
| 52 | - | |
| 53 | - this.fileWatcherInitialized = false; | |
| 111 | + // No cleanup needed - no file watchers or subscriptions | |
| 54 | 112 | } |
| 55 | 113 | |
| 56 | 114 | /** |
| @@ -64,28 +122,74 @@ | ||
| 64 | 122 | serviceContainer.set("fileIndex", currentState); |
| 65 | 123 | } |
| 66 | 124 | |
| 67 | - private async performFullIndex(): Promise<void> { | |
| 125 | + private async performFullIndex( | |
| 126 | + bypassTimeout: boolean = false, | |
| 127 | + ): Promise<void> { | |
| 68 | 128 | this.setState({ isIndexing: true, error: null }); |
| 69 | 129 | |
| 70 | 130 | try { |
| 71 | - const inGitRepo = isGitRepo(); | |
| 72 | - const allMatches = await this.throttledGlob(FILE_PATTERNS, { | |
| 73 | - maxDepth: inGitRepo ? 15 : 3, | |
| 74 | - ignore: FILE_IGNORE_PATTERNS, | |
| 75 | - dot: true, | |
| 76 | - absolute: false, | |
| 77 | - }); | |
| 78 | - | |
| 79 | - const uniqueFiles = [...new Set(allMatches)]; | |
| 80 | - this.fileSet.clear(); | |
| 81 | - uniqueFiles.forEach((file) => this.fileSet.add(file)); | |
| 82 | - | |
| 83 | - const files = uniqueFiles.map((path) => ({ | |
| 131 | + const currentDir = process.cwd(); | |
| 132 | + logger.debug(`Starting file index in directory: ${currentDir}`); | |
| 133 | + | |
| 134 | + // Create file indexing promise | |
| 135 | + const fileIndexPromise = new fdir() | |
| 136 | + .withFullPaths() | |
| 137 | + .withRelativePaths() | |
| 138 | + .filter((path) => { | |
| 139 | + // Use the helper function that implements original FILE_PATTERNS logic | |
| 140 | + return this.shouldIncludeFile(path); | |
| 141 | + }) | |
| 142 | + .exclude((dirName) => { | |
| 143 | + // Exclude directories based on FILE_IGNORE_PATTERNS | |
| 144 | + for (const pattern of FILE_IGNORE_PATTERNS) { | |
| 145 | + if (pattern.startsWith("**/") && pattern.endsWith("/**")) { | |
| 146 | + const excludeDirName = pattern.slice(3, -3); | |
| 147 | + if (dirName === excludeDirName) { | |
| 148 | + return true; | |
| 149 | + } | |
| 150 | + } | |
| 151 | + } | |
| 152 | + return false; | |
| 153 | + }) | |
| 154 | + .crawl(currentDir) | |
| 155 | + .withPromise(); | |
| 156 | + | |
| 157 | + let allFiles: string[]; | |
| 158 | + | |
| 159 | + if (bypassTimeout) { | |
| 160 | + // Manual refresh - wait for completion regardless of time | |
| 161 | + allFiles = await fileIndexPromise; | |
| 162 | + } else { | |
| 163 | + // Automatic indexing - race against 1-second timeout | |
| 164 | + const timeoutPromise = new Promise<"timeout">((resolve) => { | |
| 165 | + setTimeout(() => { | |
| 166 | + resolve("timeout"); | |
| 167 | + }, 1000); | |
| 168 | + }); | |
| 169 | + | |
| 170 | + const result = await Promise.race([fileIndexPromise, timeoutPromise]); | |
| 171 | + | |
| 172 | + if (result === "timeout") { | |
| 173 | + this.setState({ | |
| 174 | + files: [], | |
| 175 | + isIndexing: false, | |
| 176 | + error: "directory-too-large", | |
| 177 | + }); | |
| 178 | + return; | |
| 179 | + } | |
| 180 | + | |
| 181 | + allFiles = result as string[]; | |
| 182 | + } | |
| 183 | + | |
| 184 | + const fileItems = allFiles.map((path) => ({ | |
| 84 | 185 | path, |
| 85 | 186 | displayName: path, |
| 86 | 187 | })); |
| 87 | 188 | |
| 88 | - this.setState({ files, isIndexing: false }); | |
| 189 | + this.rebuildFzf(fileItems); | |
| 190 | + this.setState({ files: fileItems, isIndexing: false }); | |
| 191 | + | |
| 192 | + logger.debug(`Indexed ${fileItems.length} files`); | |
| 89 | 193 | } catch (error) { |
| 90 | 194 | const errorMessage = |
| 91 | 195 | error instanceof Error ? error.message : String(error); |
| @@ -94,116 +198,10 @@ | ||
| 94 | 198 | } |
| 95 | 199 | } |
| 96 | 200 | |
| 97 | - private setupFileWatcher(): void { | |
| 98 | - if (this.fileWatcherInitialized) { | |
| 99 | - return; | |
| 100 | - } | |
| 101 | - | |
| 102 | - // Only enable file watching in git repositories | |
| 103 | - // Outside git repos (like home directory), file watching causes performance issues | |
| 104 | - // and provides little value since files change less predictably | |
| 105 | - const inGitRepo = isGitRepo(); | |
| 106 | - if (!inGitRepo) { | |
| 107 | - logger.debug("Skipping file watcher: not in a git repository"); | |
| 108 | - return; | |
| 109 | - } | |
| 110 | - | |
| 111 | - this.fileWatcherInitialized = true; | |
| 112 | - const watcher = getFileWatcher(); | |
| 113 | - | |
| 114 | - // Start watching the current directory | |
| 115 | - watcher.startWatching(); | |
| 116 | - | |
| 117 | - // Set up callback for incremental updates | |
| 118 | - this.fileWatcherUnsubscribe = watcher.onChange(() => { | |
| 119 | - this.handleFileSystemChange(); | |
| 120 | - }); | |
| 121 | - } | |
| 122 | - | |
| 123 | - private async handleFileSystemChange(): Promise<void> { | |
| 124 | - try { | |
| 125 | - // Get current files from file system | |
| 126 | - const inGitRepo = isGitRepo(); | |
| 127 | - const allMatches = await this.throttledGlob(FILE_PATTERNS, { | |
| 128 | - maxDepth: inGitRepo ? 15 : 3, | |
| 129 | - ignore: FILE_IGNORE_PATTERNS, | |
| 130 | - dot: true, | |
| 131 | - absolute: false, | |
| 132 | - }); | |
| 133 | - | |
| 134 | - const currentFiles = new Set(allMatches); | |
| 135 | - const previousFiles = this.fileSet; | |
| 136 | - | |
| 137 | - // Find added and removed files | |
| 138 | - const addedFiles = [...currentFiles].filter( | |
| 139 | - (file) => !previousFiles.has(file), | |
| 140 | - ); | |
| 141 | - const removedFiles = [...previousFiles].filter( | |
| 142 | - (file) => !currentFiles.has(file), | |
| 143 | - ); | |
| 144 | - | |
| 145 | - // Only update if there are actual changes | |
| 146 | - if (addedFiles.length > 0 || removedFiles.length > 0) { | |
| 147 | - // Update internal file set | |
| 148 | - this.fileSet = currentFiles; | |
| 149 | - | |
| 150 | - // Create new files array | |
| 151 | - const files = [...currentFiles].map((path) => ({ | |
| 152 | - path, | |
| 153 | - displayName: path, | |
| 154 | - })); | |
| 155 | - | |
| 156 | - this.setState({ files }); | |
| 157 | - } | |
| 158 | - } catch (error) { | |
| 159 | - logger.error("Error handling file system change:", error); | |
| 160 | - const errorMessage = | |
| 161 | - error instanceof Error ? error.message : String(error); | |
| 162 | - this.setState({ error: errorMessage }); | |
| 163 | - } | |
| 164 | - } | |
| 165 | - | |
| 166 | - private async throttledGlob( | |
| 167 | - patterns: string[], | |
| 168 | - options: GlobOptionsWithFileTypesFalse, | |
| 169 | - batchSize = 100, | |
| 170 | - delay = 20, | |
| 171 | - ): Promise<string[]> { | |
| 172 | - return new Promise<string[]>((resolve, reject) => { | |
| 173 | - const allMatches: string[] = []; | |
| 174 | - let processed = 0; | |
| 175 | - let streamEnded = false; | |
| 176 | - | |
| 177 | - const globStream = glob.stream(patterns, options); | |
| 178 | - | |
| 179 | - globStream.on("data", (file: string) => { | |
| 180 | - allMatches.push(file); | |
| 181 | - processed++; | |
| 182 | - | |
| 183 | - if (processed % batchSize === 0) { | |
| 184 | - if (streamEnded) { | |
| 185 | - return; | |
| 186 | - } | |
| 187 | - globStream.pause(); | |
| 188 | - | |
| 189 | - setTimeout(() => { | |
| 190 | - if (streamEnded) { | |
| 191 | - return; | |
| 192 | - } | |
| 193 | - globStream.resume(); | |
| 194 | - }, delay); | |
| 195 | - } | |
| 196 | - }); | |
| 197 | - | |
| 198 | - globStream.on("end", () => { | |
| 199 | - streamEnded = true; | |
| 200 | - resolve(allMatches); | |
| 201 | - }); | |
| 202 | - | |
| 203 | - globStream.on("error", (err) => { | |
| 204 | - streamEnded = true; | |
| 205 | - reject(err); | |
| 206 | - }); | |
| 201 | + private rebuildFzf(files: FileItem[]): void { | |
| 202 | + this.fzf = new AsyncFzf(files, { | |
| 203 | + selector: (item: FileItem) => item.path, | |
| 204 | + casing: "case-insensitive", | |
| 207 | 205 | }); |
| 208 | 206 | } |
| 209 | 207 | |
| @@ -220,11 +218,14 @@ | ||
| 220 | 218 | return this.getState().error; |
| 221 | 219 | } |
| 222 | 220 | |
| 223 | - public async refreshIndex(): Promise<void> { | |
| 224 | - await this.performFullIndex(); | |
| 221 | + public async refreshIndex(bypassTimeout: boolean = false): Promise<void> { | |
| 222 | + await this.performFullIndex(bypassTimeout); | |
| 225 | 223 | } |
| 226 | 224 | |
| 227 | - public filterFiles(filterText: string, limit: number = 10): FileItem[] { | |
| 225 | + public async filterFiles( | |
| 226 | + filterText: string, | |
| 227 | + limit: number = 10, | |
| 228 | + ): Promise<FileItem[]> { | |
| 228 | 229 | const files = this.getFiles(); |
| 229 | 230 | |
| 230 | 231 | if (filterText.length === 0) { |
| @@ -238,36 +239,16 @@ | ||
| 238 | 239 | .slice(0, limit); |
| 239 | 240 | } |
| 240 | 241 | |
| 241 | - const lowerFilter = filterText.toLowerCase(); | |
| 242 | - | |
| 243 | - return files | |
| 244 | - .filter((file) => { | |
| 245 | - return ( | |
| 246 | - file.displayName.toLowerCase().includes(lowerFilter) || | |
| 247 | - file.path.toLowerCase().includes(lowerFilter) | |
| 248 | - ); | |
| 249 | - }) | |
| 250 | - .sort((a, b) => { | |
| 251 | - const aFileName = a.path.split("/").pop() || a.path; | |
| 252 | - const bFileName = b.path.split("/").pop() || b.path; | |
| 253 | - | |
| 254 | - // Prioritize exact matches in file name | |
| 255 | - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); | |
| 256 | - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); | |
| 257 | - | |
| 258 | - if (aNameMatch && !bNameMatch) return -1; | |
| 259 | - if (!aNameMatch && bNameMatch) return 1; | |
| 260 | - | |
| 261 | - // Then prioritize files that start with the filter | |
| 262 | - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); | |
| 263 | - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); | |
| 264 | - | |
| 265 | - if (aStartsWith && !bStartsWith) return -1; | |
| 266 | - if (!aStartsWith && bStartsWith) return 1; | |
| 267 | - | |
| 268 | - // Finally, sort by file name | |
| 269 | - return aFileName.localeCompare(bFileName); | |
| 270 | - }) | |
| 271 | - .slice(0, limit); | |
| 242 | + // Use fzf for fuzzy search | |
| 243 | + if (!this.fzf) { | |
| 244 | + this.rebuildFzf(files); | |
| 245 | + } | |
| 246 | + | |
| 247 | + const results = await this.fzf!.find(filterText); | |
| 248 | + return results.slice(0, limit).map((entry: FzfResultItem<FileItem>) => ({ | |
| 249 | + path: entry.item.path, | |
| 250 | + displayName: entry.item.displayName, | |
| 251 | + positions: entry.positions, | |
| 252 | + })); | |
| 272 | 253 | } |
| 273 | 254 | } |
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { AssistantConfig } from "@continuedev/sdk"; |
| 2 | -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; | |
| 2 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | 3 | |
| 4 | 4 | import { MCPService } from "./MCPService.js"; |
| 5 | 5 | |
| @@ -21,6 +21,14 @@ | ||
| 21 | 21 | StdioClientTransport: vi.fn(), |
| 22 | 22 | })); |
| 23 | 23 | |
| 24 | +vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({ | |
| 25 | + SSEClientTransport: vi.fn(), | |
| 26 | +})); | |
| 27 | + | |
| 28 | +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ | |
| 29 | + StreamableHTTPClientTransport: vi.fn(), | |
| 30 | +})); | |
| 31 | + | |
| 24 | 32 | describe("MCPService", () => { |
| 25 | 33 | let mcpService: MCPService; |
| 26 | 34 | let mockAssistant: AssistantConfig; |
| @@ -152,4 +160,56 @@ | ||
| 152 | 160 | await expect(mcpService.cleanup()).resolves.not.toThrow(); |
| 153 | 161 | }); |
| 154 | 162 | }); |
| 163 | + | |
| 164 | + describe("transport types", () => { | |
| 165 | + it("should support SSE transport", async () => { | |
| 166 | + const sseAssistant: AssistantConfig = { | |
| 167 | + name: "sse-assistant", | |
| 168 | + version: "1.0.0", | |
| 169 | + mcpServers: [ | |
| 170 | + { | |
| 171 | + name: "sse-server", | |
| 172 | + type: "sse", | |
| 173 | + url: "https://example.com/sse", | |
| 174 | + }, | |
| 175 | + ], | |
| 176 | + } as AssistantConfig; | |
| 177 | + | |
| 178 | + await expect(mcpService.initialize(sseAssistant)).resolves.not.toThrow(); | |
| 179 | + }); | |
| 180 | + | |
| 181 | + it("should support streamable-http transport", async () => { | |
| 182 | + const httpAssistant: AssistantConfig = { | |
| 183 | + name: "http-assistant", | |
| 184 | + version: "1.0.0", | |
| 185 | + mcpServers: [ | |
| 186 | + { | |
| 187 | + name: "http-server", | |
| 188 | + type: "streamable-http", | |
| 189 | + url: "https://example.com/http", | |
| 190 | + }, | |
| 191 | + ], | |
| 192 | + } as AssistantConfig; | |
| 193 | + | |
| 194 | + await expect(mcpService.initialize(httpAssistant)).resolves.not.toThrow(); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should default to stdio transport when type is not specified", async () => { | |
| 198 | + const defaultAssistant: AssistantConfig = { | |
| 199 | + name: "default-assistant", | |
| 200 | + version: "1.0.0", | |
| 201 | + mcpServers: [ | |
| 202 | + { | |
| 203 | + name: "default-server", | |
| 204 | + command: "npx", | |
| 205 | + args: ["-v"], | |
| 206 | + }, | |
| 207 | + ], | |
| 208 | + } as AssistantConfig; | |
| 209 | + | |
| 210 | + await expect( | |
| 211 | + mcpService.initialize(defaultAssistant), | |
| 212 | + ).resolves.not.toThrow(); | |
| 213 | + }); | |
| 214 | + }); | |
| 155 | 215 | }); |
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | import { type AssistantConfig } from "@continuedev/sdk"; |
| 2 | 2 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; |
| 3 | +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; | |
| 3 | 4 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; |
| 5 | +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; | |
| 6 | +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; | |
| 4 | 7 | |
| 5 | 8 | import { getErrorString } from "../util/error.js"; |
| 6 | 9 | import { logger } from "../util/logger.js"; |
| @@ -9,9 +12,9 @@ | ||
| 9 | 12 | import { serviceContainer } from "./ServiceContainer.js"; |
| 10 | 13 | import { |
| 11 | 14 | MCPConnectionInfo, |
| 15 | + MCPServerConfig, | |
| 12 | 16 | MCPServiceState, |
| 13 | 17 | SERVICE_NAMES, |
| 14 | - MCPServerConfig, | |
| 15 | 18 | } from "./types.js"; |
| 16 | 19 | |
| 17 | 20 | interface ServerConnection extends MCPConnectionInfo { |
| @@ -214,31 +217,12 @@ | ||
| 214 | 217 | this.updateState(); |
| 215 | 218 | |
| 216 | 219 | try { |
| 217 | - if (serverConfig.type && serverConfig.type !== "stdio") { | |
| 218 | - throw new Error( | |
| 219 | - `${serverConfig.type} MCP servers are not yet supported in the Continue CLI`, | |
| 220 | - ); | |
| 221 | - } | |
| 222 | - if (!serverConfig.command) { | |
| 223 | - throw new Error("MCP server command is not specified"); | |
| 224 | - } | |
| 225 | - | |
| 226 | 220 | const client = new Client( |
| 227 | 221 | { name: "continue-cli-client", version: "1.0.0" }, |
| 228 | 222 | { capabilities: {} }, |
| 229 | 223 | ); |
| 230 | 224 | |
| 231 | - const env: Record<string, string> = serverConfig.env || {}; | |
| 232 | - if (process.env.PATH !== undefined) { | |
| 233 | - env.PATH = process.env.PATH; | |
| 234 | - } | |
| 235 | - | |
| 236 | - const transport = new StdioClientTransport({ | |
| 237 | - command: serverConfig.command, | |
| 238 | - args: serverConfig.args, | |
| 239 | - env, | |
| 240 | - stderr: "ignore", | |
| 241 | - }); | |
| 225 | + const transport = await this.constructTransport(serverConfig); | |
| 242 | 226 | |
| 243 | 227 | logger.debug("Connecting to MCP server", { |
| 244 | 228 | name: serverName, |
| @@ -363,4 +347,68 @@ | ||
| 363 | 347 | logger.debug("Shutting down MCPService"); |
| 364 | 348 | await this.shutdownConnections(); |
| 365 | 349 | } |
| 350 | + | |
| 351 | + /** | |
| 352 | + * Construct transport based on server configuration | |
| 353 | + */ | |
| 354 | + private async constructTransport( | |
| 355 | + serverConfig: MCPServerConfig, | |
| 356 | + ): Promise<Transport> { | |
| 357 | + const transportType = serverConfig.type || "stdio"; | |
| 358 | + | |
| 359 | + switch (transportType) { | |
| 360 | + case "stdio": | |
| 361 | + if (!serverConfig.command) { | |
| 362 | + throw new Error( | |
| 363 | + "MCP server command is not specified for stdio transport", | |
| 364 | + ); | |
| 365 | + } | |
| 366 | + | |
| 367 | + const env: Record<string, string> = serverConfig.env || {}; | |
| 368 | + if (process.env.PATH !== undefined) { | |
| 369 | + env.PATH = process.env.PATH; | |
| 370 | + } | |
| 371 | + | |
| 372 | + return new StdioClientTransport({ | |
| 373 | + command: serverConfig.command, | |
| 374 | + args: serverConfig.args || [], | |
| 375 | + env, | |
| 376 | + cwd: serverConfig.cwd, | |
| 377 | + stderr: "ignore", | |
| 378 | + }); | |
| 379 | + | |
| 380 | + case "sse": | |
| 381 | + if (!serverConfig.url) { | |
| 382 | + throw new Error("MCP server URL is not specified for SSE transport"); | |
| 383 | + } | |
| 384 | + return new SSEClientTransport(new URL(serverConfig.url), { | |
| 385 | + eventSourceInit: { | |
| 386 | + fetch: (input, init) => | |
| 387 | + fetch(input, { | |
| 388 | + ...init, | |
| 389 | + headers: { | |
| 390 | + ...init?.headers, | |
| 391 | + ...(serverConfig.requestOptions?.headers as | |
| 392 | + | Record<string, string> | |
| 393 | + | undefined), | |
| 394 | + }, | |
| 395 | + }), | |
| 396 | + }, | |
| 397 | + requestInit: { headers: serverConfig.requestOptions?.headers }, | |
| 398 | + }); | |
| 399 | + | |
| 400 | + case "streamable-http": | |
| 401 | + if (!serverConfig.url) { | |
| 402 | + throw new Error( | |
| 403 | + "MCP server URL is not specified for streamable-http transport", | |
| 404 | + ); | |
| 405 | + } | |
| 406 | + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { | |
| 407 | + requestInit: { headers: serverConfig.requestOptions?.headers }, | |
| 408 | + }); | |
| 409 | + | |
| 410 | + default: | |
| 411 | + throw new Error(`Unsupported transport type: ${transportType}`); | |
| 412 | + } | |
| 413 | + } | |
| 366 | 414 | } |
| @@ -1,9 +1,7 @@ | ||
| 1 | 1 | import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; |
| 2 | -import * as openaiAdapters from "@continuedev/openai-adapters"; | |
| 3 | 2 | import { describe, expect, beforeEach, vi, test } from "vitest"; |
| 4 | 3 | |
| 5 | 4 | // Mock dependencies before imports |
| 6 | -vi.mock("@continuedev/openai-adapters"); | |
| 7 | 5 | vi.mock("../config.js"); |
| 8 | 6 | vi.mock("../auth/workos.js"); |
| 9 | 7 | |
| @@ -81,9 +79,7 @@ | ||
| 81 | 79 | |
| 82 | 80 | test("should initialize with persisted model if valid", async () => { |
| 83 | 81 | vi.mocked(workos.getModelName).mockReturnValue("Claude 3"); |
| 84 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 85 | - mockLlmApi as any, | |
| 86 | - ); | |
| 82 | + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); | |
| 87 | 83 | |
| 88 | 84 | const state = await service.initialize(mockAssistant, mockAuthConfig); |
| 89 | 85 | |
| @@ -152,9 +148,7 @@ | ||
| 152 | 148 | await service.initialize(mockAssistant, mockAuthConfig); |
| 153 | 149 | |
| 154 | 150 | const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; |
| 155 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 156 | - newLlmApi as any, | |
| 157 | - ); | |
| 151 | + vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any); | |
| 158 | 152 | |
| 159 | 153 | const state = await service.switchModel(1); |
| 160 | 154 | |
| @@ -204,24 +198,14 @@ | ||
| 204 | 198 | ]); |
| 205 | 199 | await service.initialize(mockAssistant, mockAuthConfig); |
| 206 | 200 | |
| 207 | - vi.mocked(workos.getAccessToken).mockReturnValue("proxy-token"); | |
| 208 | - vi.mocked(workos.getOrganizationId).mockReturnValue("org-123"); | |
| 209 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 210 | - mockLlmApi as any, | |
| 211 | - ); | |
| 201 | + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); | |
| 212 | 202 | |
| 213 | 203 | await service.switchModel(0); |
| 214 | 204 | |
| 215 | - expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({ | |
| 216 | - provider: "continue-proxy", | |
| 217 | - apiBase: "https://proxy.continue.dev", | |
| 218 | - apiKey: "proxy-token", | |
| 219 | - env: { | |
| 220 | - apiKeyLocation: "env.PROXY_KEY", | |
| 221 | - orgScopeId: "org-123", | |
| 222 | - proxyUrl: undefined, | |
| 223 | - }, | |
| 224 | - }); | |
| 205 | + expect(vi.mocked(config.createLlmApi)).toHaveBeenCalledWith( | |
| 206 | + proxyModel, | |
| 207 | + mockAuthConfig, | |
| 208 | + ); | |
| 225 | 209 | }); |
| 226 | 210 | }); |
| 227 | 211 | |
| @@ -292,9 +276,7 @@ | ||
| 292 | 276 | |
| 293 | 277 | expect(service.getCurrentModelIndex()).toBe(0); |
| 294 | 278 | |
| 295 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 296 | - mockLlmApi as any, | |
| 297 | - ); | |
| 279 | + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); | |
| 298 | 280 | await service.switchModel(1); |
| 299 | 281 | expect(service.getCurrentModelIndex()).toBe(1); |
| 300 | 282 | }); |
| @@ -392,9 +374,7 @@ | ||
| 392 | 374 | service.on("stateChanged", listener); |
| 393 | 375 | |
| 394 | 376 | const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; |
| 395 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 396 | - newLlmApi as any, | |
| 397 | - ); | |
| 377 | + vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any); | |
| 398 | 378 | await service.switchModel(1); |
| 399 | 379 | |
| 400 | 380 | expect(listener).toHaveBeenCalledWith( |
| @@ -419,7 +399,7 @@ | ||
| 419 | 399 | const errorListener = vi.fn(); |
| 420 | 400 | service.on("error", errorListener); |
| 421 | 401 | |
| 422 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any); | |
| 402 | + vi.mocked(config.createLlmApi).mockReturnValue(null as any); | |
| 423 | 403 | |
| 424 | 404 | await expect(service.switchModel(1)).rejects.toThrow( |
| 425 | 405 | "Failed to initialize LLM", |
| @@ -1,13 +1,7 @@ | ||
| 1 | 1 | import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; |
| 2 | -import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; | |
| 3 | - | |
| 4 | -import { | |
| 5 | - AuthConfig, | |
| 6 | - getAccessToken, | |
| 7 | - getModelName, | |
| 8 | - getOrganizationId, | |
| 9 | -} from "../auth/workos.js"; | |
| 10 | -import { getLlmApi } from "../config.js"; | |
| 2 | + | |
| 3 | +import { AuthConfig, getModelName } from "../auth/workos.js"; | |
| 4 | +import { createLlmApi, getLlmApi } from "../config.js"; | |
| 11 | 5 | import { logger } from "../util/logger.js"; |
| 12 | 6 | |
| 13 | 7 | import { BaseService, ServiceWithDependencies } from "./BaseService.js"; |
| @@ -89,31 +83,7 @@ | ||
| 89 | 83 | name: (selectedModel as any).name || "unnamed", |
| 90 | 84 | }); |
| 91 | 85 | |
| 92 | - const accessToken = getAccessToken(authConfig); | |
| 93 | - const organizationId = getOrganizationId(authConfig); | |
| 94 | - | |
| 95 | - const config: LLMConfig = | |
| 96 | - selectedModel.provider === "continue-proxy" | |
| 97 | - ? { | |
| 98 | - provider: selectedModel.provider, | |
| 99 | - requestOptions: selectedModel.requestOptions, | |
| 100 | - apiBase: selectedModel.apiBase, | |
| 101 | - apiKey: accessToken ?? undefined, | |
| 102 | - env: { | |
| 103 | - apiKeyLocation: (selectedModel as any).apiKeyLocation, | |
| 104 | - orgScopeId: organizationId, | |
| 105 | - proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined, | |
| 106 | - }, | |
| 107 | - } | |
| 108 | - : { | |
| 109 | - provider: selectedModel.provider as any, | |
| 110 | - apiKey: selectedModel.apiKey, | |
| 111 | - apiBase: selectedModel.apiBase, | |
| 112 | - requestOptions: selectedModel.requestOptions, | |
| 113 | - env: selectedModel.env, | |
| 114 | - }; | |
| 115 | - | |
| 116 | - const llmApi = constructLlmApi(config); | |
| 86 | + const llmApi = createLlmApi(selectedModel, authConfig); | |
| 117 | 87 | |
| 118 | 88 | if (!llmApi) { |
| 119 | 89 | throw new Error("Failed to initialize LLM with persisted model"); |
| @@ -288,31 +258,7 @@ | ||
| 288 | 258 | }); |
| 289 | 259 | |
| 290 | 260 | try { |
| 291 | - const accessToken = getAccessToken(authConfig); | |
| 292 | - const organizationId = getOrganizationId(authConfig); | |
| 293 | - | |
| 294 | - const config: LLMConfig = | |
| 295 | - selectedModel.provider === "continue-proxy" | |
| 296 | - ? { | |
| 297 | - provider: selectedModel.provider, | |
| 298 | - requestOptions: selectedModel.requestOptions, | |
| 299 | - apiBase: selectedModel.apiBase, | |
| 300 | - apiKey: accessToken ?? undefined, | |
| 301 | - env: { | |
| 302 | - apiKeyLocation: (selectedModel as any).apiKeyLocation, | |
| 303 | - orgScopeId: organizationId, | |
| 304 | - proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined, | |
| 305 | - }, | |
| 306 | - } | |
| 307 | - : { | |
| 308 | - provider: selectedModel.provider as any, | |
| 309 | - apiKey: selectedModel.apiKey, | |
| 310 | - apiBase: selectedModel.apiBase, | |
| 311 | - requestOptions: selectedModel.requestOptions, | |
| 312 | - env: selectedModel.env, | |
| 313 | - }; | |
| 314 | - | |
| 315 | - const llmApi = constructLlmApi(config); | |
| 261 | + const llmApi = createLlmApi(selectedModel, authConfig); | |
| 316 | 262 | |
| 317 | 263 | if (!llmApi) { |
| 318 | 264 | throw new Error("Failed to initialize LLM with selected model"); |
| @@ -0,0 +1,203 @@ | ||
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 4 | +import { logger } from "../util/logger.js"; | |
| 5 | + | |
| 6 | +import { StorageSyncService } from "./StorageSyncService.js"; | |
| 7 | + | |
| 8 | +vi.mock("../util/logger.js", () => ({ | |
| 9 | + logger: { | |
| 10 | + debug: vi.fn(), | |
| 11 | + info: vi.fn(), | |
| 12 | + warn: vi.fn(), | |
| 13 | + error: vi.fn(), | |
| 14 | + }, | |
| 15 | +})); | |
| 16 | + | |
| 17 | +vi.mock("../env.js", () => ({ | |
| 18 | + env: { apiBase: "https://api.test/" }, | |
| 19 | +})); | |
| 20 | + | |
| 21 | +vi.mock("../util/git.js", () => ({ | |
| 22 | + getGitDiffSnapshot: vi.fn(), | |
| 23 | +})); | |
| 24 | + | |
| 25 | +describe("StorageSyncService", () => { | |
| 26 | + const fetchMock = vi.fn(); | |
| 27 | + const gitDiffMock = vi.mocked(getGitDiffSnapshot); | |
| 28 | + let service: StorageSyncService; | |
| 29 | + let originalFetch: typeof fetch | undefined; | |
| 30 | + let hadFetch = false; | |
| 31 | + | |
| 32 | + beforeEach(async () => { | |
| 33 | + vi.clearAllMocks(); | |
| 34 | + fetchMock.mockReset(); | |
| 35 | + hadFetch = "fetch" in globalThis; | |
| 36 | + originalFetch = globalThis.fetch; | |
| 37 | + globalThis.fetch = fetchMock as unknown as typeof fetch; | |
| 38 | + gitDiffMock.mockReset(); | |
| 39 | + | |
| 40 | + service = new StorageSyncService(); | |
| 41 | + await service.initialize(); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + afterEach(() => { | |
| 45 | + service.stop(); | |
| 46 | + if (hadFetch) { | |
| 47 | + globalThis.fetch = originalFetch!; | |
| 48 | + } else { | |
| 49 | + delete (globalThis as { fetch?: typeof fetch }).fetch; | |
| 50 | + } | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("returns false when no storage option provided", async () => { | |
| 54 | + const result = await service.startFromOptions({ | |
| 55 | + storageOption: undefined, | |
| 56 | + accessToken: "token", | |
| 57 | + syncSessionHistory: vi.fn(), | |
| 58 | + getSessionSnapshot: vi.fn(), | |
| 59 | + }); | |
| 60 | + | |
| 61 | + expect(result).toBe(false); | |
| 62 | + expect(fetchMock).not.toHaveBeenCalled(); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("warns when storage identifier trims to empty", async () => { | |
| 66 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 67 | + | |
| 68 | + const result = await service.startFromOptions({ | |
| 69 | + storageOption: " ", | |
| 70 | + accessToken: "token", | |
| 71 | + syncSessionHistory: vi.fn(), | |
| 72 | + getSessionSnapshot: vi.fn(), | |
| 73 | + }); | |
| 74 | + | |
| 75 | + expect(result).toBe(false); | |
| 76 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 77 | + expect.stringContaining("storage identifier was empty"), | |
| 78 | + ); | |
| 79 | + warnSpy.mockRestore(); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("warns when storage requested without access token", async () => { | |
| 83 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 84 | + | |
| 85 | + const result = await service.startFromOptions({ | |
| 86 | + storageOption: "session-123", | |
| 87 | + accessToken: null, | |
| 88 | + syncSessionHistory: vi.fn(), | |
| 89 | + getSessionSnapshot: vi.fn(), | |
| 90 | + }); | |
| 91 | + | |
| 92 | + expect(result).toBe(false); | |
| 93 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 94 | + expect.stringContaining("no Continue API key"), | |
| 95 | + ); | |
| 96 | + warnSpy.mockRestore(); | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("starts syncing when presign succeeds", async () => { | |
| 100 | + const syncSessionHistory = vi.fn(); | |
| 101 | + const getSessionSnapshot = vi.fn().mockReturnValue({ foo: "bar" }); | |
| 102 | + | |
| 103 | + fetchMock.mockResolvedValueOnce({ | |
| 104 | + ok: true, | |
| 105 | + json: async () => ({ | |
| 106 | + session: { putUrl: "https://upload/session", key: "session.json" }, | |
| 107 | + diff: { putUrl: "https://upload/diff", key: "diff.txt" }, | |
| 108 | + }), | |
| 109 | + }); | |
| 110 | + fetchMock.mockResolvedValue({ ok: true }); | |
| 111 | + gitDiffMock.mockResolvedValue({ diff: "diff", repoFound: true }); | |
| 112 | + | |
| 113 | + const result = await service.startFromOptions({ | |
| 114 | + storageOption: "session-123", | |
| 115 | + accessToken: "token", | |
| 116 | + syncSessionHistory, | |
| 117 | + getSessionSnapshot, | |
| 118 | + isActive: () => true, | |
| 119 | + }); | |
| 120 | + | |
| 121 | + expect(result).toBe(true); | |
| 122 | + expect(syncSessionHistory).toHaveBeenCalledTimes(1); | |
| 123 | + expect(getSessionSnapshot).toHaveBeenCalledTimes(1); | |
| 124 | + expect(fetchMock).toHaveBeenCalledTimes(3); | |
| 125 | + const [presignUrl, presignOptions] = fetchMock.mock.calls[0]; | |
| 126 | + expect(presignUrl).toBeInstanceOf(URL); | |
| 127 | + expect((presignUrl as URL).toString()).toBe( | |
| 128 | + "https://api.test/agents/storage/presigned-url", | |
| 129 | + ); | |
| 130 | + expect(presignOptions).toMatchObject({ method: "POST" }); | |
| 131 | + | |
| 132 | + const [sessionUrl, sessionOptions] = fetchMock.mock.calls[1]; | |
| 133 | + expect(sessionUrl).toBe("https://upload/session"); | |
| 134 | + expect(sessionOptions).toMatchObject({ | |
| 135 | + method: "PUT", | |
| 136 | + body: expect.any(String), | |
| 137 | + }); | |
| 138 | + | |
| 139 | + service.stop(); | |
| 140 | + expect(service.getState().isEnabled).toBe(false); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + it("returns false when presign request fails", async () => { | |
| 144 | + fetchMock.mockResolvedValueOnce({ | |
| 145 | + ok: false, | |
| 146 | + status: 500, | |
| 147 | + statusText: "Server Error", | |
| 148 | + }); | |
| 149 | + | |
| 150 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 151 | + const result = await service.startFromOptions({ | |
| 152 | + storageOption: "session-123", | |
| 153 | + accessToken: "token", | |
| 154 | + syncSessionHistory: vi.fn(), | |
| 155 | + getSessionSnapshot: vi.fn(), | |
| 156 | + }); | |
| 157 | + | |
| 158 | + expect(result).toBe(false); | |
| 159 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 160 | + expect.stringContaining("presign request failed"), | |
| 161 | + ); | |
| 162 | + expect(service.getState().lastError).toBe( | |
| 163 | + "Failed to obtain presigned URLs", | |
| 164 | + ); | |
| 165 | + warnSpy.mockRestore(); | |
| 166 | + }); | |
| 167 | + | |
| 168 | + it("records upload error details when PUT fails", async () => { | |
| 169 | + fetchMock.mockResolvedValueOnce({ | |
| 170 | + ok: true, | |
| 171 | + json: async () => ({ | |
| 172 | + session: { putUrl: "https://upload/session", key: "session.json" }, | |
| 173 | + diff: { putUrl: "https://upload/diff", key: "diff.txt" }, | |
| 174 | + }), | |
| 175 | + }); | |
| 176 | + fetchMock.mockResolvedValueOnce({ | |
| 177 | + ok: false, | |
| 178 | + status: 403, | |
| 179 | + statusText: "Forbidden", | |
| 180 | + }); | |
| 181 | + gitDiffMock.mockResolvedValue({ diff: "", repoFound: true }); | |
| 182 | + | |
| 183 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 184 | + | |
| 185 | + const result = await service.startFromOptions({ | |
| 186 | + storageOption: "session-123", | |
| 187 | + accessToken: "token", | |
| 188 | + syncSessionHistory: vi.fn(), | |
| 189 | + getSessionSnapshot: vi.fn().mockReturnValue({}), | |
| 190 | + }); | |
| 191 | + | |
| 192 | + expect(result).toBe(true); | |
| 193 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 194 | + expect.stringContaining("Storage upload failed"), | |
| 195 | + ); | |
| 196 | + const state = service.getState(); | |
| 197 | + expect(state.isEnabled).toBe(true); | |
| 198 | + expect(state.lastError).toContain("Storage upload failed"); | |
| 199 | + | |
| 200 | + service.stop(); | |
| 201 | + warnSpy.mockRestore(); | |
| 202 | + }); | |
| 203 | +}); |
| @@ -0,0 +1,283 @@ | ||
| 1 | +import chalk from "chalk"; | |
| 2 | + | |
| 3 | +import { env } from "../env.js"; | |
| 4 | +import { formatError } from "../util/formatError.js"; | |
| 5 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 6 | +import { logger } from "../util/logger.js"; | |
| 7 | + | |
| 8 | +import type { StorageSyncServiceState } from "./types.js"; | |
| 9 | + | |
| 10 | +const DEFAULT_UPLOAD_INTERVAL_MS = 30_000; | |
| 11 | + | |
| 12 | +type StoragePresignedLocation = { | |
| 13 | + key: string; | |
| 14 | + putUrl: string; | |
| 15 | +}; | |
| 16 | + | |
| 17 | +type StoragePresignResponse = { | |
| 18 | + session?: StoragePresignedLocation; | |
| 19 | + diff?: StoragePresignedLocation; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +type StorageTargets = { | |
| 23 | + sessionUrl: string; | |
| 24 | + diffUrl: string; | |
| 25 | +}; | |
| 26 | + | |
| 27 | +export interface StorageSyncStartOptions { | |
| 28 | + storageId: string; | |
| 29 | + accessToken: string; | |
| 30 | + intervalMs?: number; | |
| 31 | + syncSessionHistory: () => void; | |
| 32 | + getSessionSnapshot: () => unknown; | |
| 33 | + isActive?: () => boolean; | |
| 34 | +} | |
| 35 | + | |
| 36 | +export class StorageSyncService { | |
| 37 | + private state: StorageSyncServiceState = { | |
| 38 | + isEnabled: false, | |
| 39 | + lastError: null, | |
| 40 | + }; | |
| 41 | + | |
| 42 | + private intervalHandle: NodeJS.Timeout | null = null; | |
| 43 | + private stopped = true; | |
| 44 | + private uploadInFlight = false; | |
| 45 | + private missingRepoLogged = false; | |
| 46 | + private targets: StorageTargets | null = null; | |
| 47 | + private options: StorageSyncStartOptions | null = null; | |
| 48 | + | |
| 49 | + async initialize(): Promise<StorageSyncServiceState> { | |
| 50 | + this.stop(); | |
| 51 | + return this.getState(); | |
| 52 | + } | |
| 53 | + | |
| 54 | + getState(): StorageSyncServiceState { | |
| 55 | + return { ...this.state }; | |
| 56 | + } | |
| 57 | + | |
| 58 | + getDefaultInterval(): number { | |
| 59 | + return DEFAULT_UPLOAD_INTERVAL_MS; | |
| 60 | + } | |
| 61 | + | |
| 62 | + async startFromOptions( | |
| 63 | + options: { | |
| 64 | + storageOption?: string; | |
| 65 | + accessToken?: string | null; | |
| 66 | + } & Omit<StorageSyncStartOptions, "storageId" | "accessToken">, | |
| 67 | + ): Promise<boolean> { | |
| 68 | + const { storageOption, accessToken, ...rest } = options; | |
| 69 | + | |
| 70 | + if (!storageOption) { | |
| 71 | + return false; | |
| 72 | + } | |
| 73 | + | |
| 74 | + const storageId = storageOption.trim(); | |
| 75 | + if (!storageId) { | |
| 76 | + logger.warn( | |
| 77 | + "Storage sync requested but the provided storage identifier was empty; skipping uploads.", | |
| 78 | + ); | |
| 79 | + return false; | |
| 80 | + } | |
| 81 | + | |
| 82 | + if (!accessToken) { | |
| 83 | + logger.warn( | |
| 84 | + "Storage sync requested but no Continue API key is available; skipping uploads.", | |
| 85 | + ); | |
| 86 | + return false; | |
| 87 | + } | |
| 88 | + | |
| 89 | + return this.start({ | |
| 90 | + storageId, | |
| 91 | + accessToken, | |
| 92 | + ...rest, | |
| 93 | + }); | |
| 94 | + } | |
| 95 | + | |
| 96 | + async start(options: StorageSyncStartOptions): Promise<boolean> { | |
| 97 | + // Ensure any existing sync loop is stopped before starting a new one | |
| 98 | + this.stop(); | |
| 99 | + | |
| 100 | + const targets = await this.requestStorageTargets( | |
| 101 | + options.storageId, | |
| 102 | + options.accessToken, | |
| 103 | + ); | |
| 104 | + | |
| 105 | + if (!targets) { | |
| 106 | + this.setState({ | |
| 107 | + isEnabled: false, | |
| 108 | + storageId: options.storageId, | |
| 109 | + lastError: "Failed to obtain presigned URLs", | |
| 110 | + }); | |
| 111 | + return false; | |
| 112 | + } | |
| 113 | + | |
| 114 | + this.targets = targets; | |
| 115 | + this.options = options; | |
| 116 | + this.stopped = false; | |
| 117 | + this.uploadInFlight = false; | |
| 118 | + this.missingRepoLogged = false; | |
| 119 | + this.setState({ | |
| 120 | + isEnabled: true, | |
| 121 | + storageId: options.storageId, | |
| 122 | + lastError: null, | |
| 123 | + lastUploadAt: undefined, | |
| 124 | + }); | |
| 125 | + | |
| 126 | + const intervalMs = options.intervalMs ?? DEFAULT_UPLOAD_INTERVAL_MS; | |
| 127 | + logger.info( | |
| 128 | + chalk.dim( | |
| 129 | + `Storage sync enabled (uploading every ${Math.round(intervalMs / 1000)}s)`, | |
| 130 | + ), | |
| 131 | + ); | |
| 132 | + | |
| 133 | + await this.performUpload(); | |
| 134 | + | |
| 135 | + this.intervalHandle = setInterval(() => { | |
| 136 | + void this.performUpload(); | |
| 137 | + }, intervalMs); | |
| 138 | + | |
| 139 | + return true; | |
| 140 | + } | |
| 141 | + | |
| 142 | + stop(): void { | |
| 143 | + this.stopped = true; | |
| 144 | + this.targets = null; | |
| 145 | + this.options = null; | |
| 146 | + this.uploadInFlight = false; | |
| 147 | + | |
| 148 | + if (this.intervalHandle) { | |
| 149 | + clearInterval(this.intervalHandle); | |
| 150 | + this.intervalHandle = null; | |
| 151 | + } | |
| 152 | + | |
| 153 | + if (this.state.isEnabled) { | |
| 154 | + this.setState({ | |
| 155 | + isEnabled: false, | |
| 156 | + storageId: this.state.storageId, | |
| 157 | + lastError: null, | |
| 158 | + lastUploadAt: this.state.lastUploadAt, | |
| 159 | + }); | |
| 160 | + } | |
| 161 | + } | |
| 162 | + | |
| 163 | + private setState(next: StorageSyncServiceState): void { | |
| 164 | + this.state = { ...next }; | |
| 165 | + } | |
| 166 | + | |
| 167 | + private async requestStorageTargets( | |
| 168 | + storageId: string, | |
| 169 | + accessToken: string, | |
| 170 | + ): Promise<StorageTargets | null> { | |
| 171 | + const url = new URL("agents/storage/presigned-url", env.apiBase); | |
| 172 | + | |
| 173 | + try { | |
| 174 | + const response = await fetch(url, { | |
| 175 | + method: "POST", | |
| 176 | + headers: { | |
| 177 | + "Content-Type": "application/json", | |
| 178 | + Authorization: `Bearer ${accessToken}`, | |
| 179 | + }, | |
| 180 | + body: JSON.stringify({ storageId }), | |
| 181 | + }); | |
| 182 | + | |
| 183 | + if (!response.ok) { | |
| 184 | + const statusText = `${response.status} ${response.statusText}`.trim(); | |
| 185 | + logger.warn( | |
| 186 | + `Storage sync presign request failed (${statusText}). Storage uploads disabled for this session.`, | |
| 187 | + ); | |
| 188 | + return null; | |
| 189 | + } | |
| 190 | + | |
| 191 | + const body = (await response.json()) as StoragePresignResponse; | |
| 192 | + | |
| 193 | + if (!body.session?.putUrl || !body.diff?.putUrl) { | |
| 194 | + logger.warn( | |
| 195 | + "Storage sync presign response missing required URLs. Storage uploads disabled for this session.", | |
| 196 | + ); | |
| 197 | + return null; | |
| 198 | + } | |
| 199 | + | |
| 200 | + return { | |
| 201 | + sessionUrl: body.session.putUrl, | |
| 202 | + diffUrl: body.diff.putUrl, | |
| 203 | + }; | |
| 204 | + } catch (error) { | |
| 205 | + logger.warn( | |
| 206 | + `Storage sync presign request failed: ${formatError(error)}. Storage uploads disabled for this session.`, | |
| 207 | + ); | |
| 208 | + return null; | |
| 209 | + } | |
| 210 | + } | |
| 211 | + | |
| 212 | + private async uploadToPresignedUrl( | |
| 213 | + url: string, | |
| 214 | + body: string, | |
| 215 | + contentType: string, | |
| 216 | + ): Promise<void> { | |
| 217 | + const response = await fetch(url, { | |
| 218 | + method: "PUT", | |
| 219 | + headers: { | |
| 220 | + "Content-Type": contentType, | |
| 221 | + }, | |
| 222 | + body, | |
| 223 | + }); | |
| 224 | + | |
| 225 | + if (!response.ok) { | |
| 226 | + const statusText = `${response.status} ${response.statusText}`.trim(); | |
| 227 | + throw new Error(`Storage upload failed (${statusText})`); | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + private async performUpload(): Promise<void> { | |
| 232 | + if (this.stopped || this.uploadInFlight || !this.targets || !this.options) { | |
| 233 | + return; | |
| 234 | + } | |
| 235 | + | |
| 236 | + if (this.options.isActive && !this.options.isActive()) { | |
| 237 | + return; | |
| 238 | + } | |
| 239 | + | |
| 240 | + this.uploadInFlight = true; | |
| 241 | + | |
| 242 | + try { | |
| 243 | + this.options.syncSessionHistory(); | |
| 244 | + const snapshot = this.options.getSessionSnapshot(); | |
| 245 | + const sessionPayload = JSON.stringify(snapshot, null, 2); | |
| 246 | + await this.uploadToPresignedUrl( | |
| 247 | + this.targets.sessionUrl, | |
| 248 | + sessionPayload, | |
| 249 | + "application/json", | |
| 250 | + ); | |
| 251 | + | |
| 252 | + const diffResult = await getGitDiffSnapshot(); | |
| 253 | + if (!diffResult.repoFound && !this.missingRepoLogged) { | |
| 254 | + logger.debug( | |
| 255 | + "Storage sync diff upload skipped: not in a git repository or main branch missing.", | |
| 256 | + ); | |
| 257 | + this.missingRepoLogged = true; | |
| 258 | + } | |
| 259 | + await this.uploadToPresignedUrl( | |
| 260 | + this.targets.diffUrl, | |
| 261 | + diffResult.diff, | |
| 262 | + "text/plain", | |
| 263 | + ); | |
| 264 | + | |
| 265 | + this.setState({ | |
| 266 | + isEnabled: true, | |
| 267 | + storageId: this.state.storageId, | |
| 268 | + lastUploadAt: Date.now(), | |
| 269 | + lastError: null, | |
| 270 | + }); | |
| 271 | + } catch (error) { | |
| 272 | + this.setState({ | |
| 273 | + isEnabled: true, | |
| 274 | + storageId: this.state.storageId, | |
| 275 | + lastUploadAt: this.state.lastUploadAt, | |
| 276 | + lastError: formatError(error), | |
| 277 | + }); | |
| 278 | + logger.warn(`Storage sync upload failed: ${formatError(error)}`); | |
| 279 | + } finally { | |
| 280 | + this.uploadInFlight = false; | |
| 281 | + } | |
| 282 | + } | |
| 283 | +} |
| @@ -0,0 +1,241 @@ | ||
| 1 | +import { exec, spawn } from "child_process"; | |
| 2 | +import { promisify } from "util"; | |
| 3 | + | |
| 4 | +import { GlobalContext } from "core/util/GlobalContext.js"; | |
| 5 | + | |
| 6 | +import { logger } from "src/util/logger.js"; | |
| 7 | + | |
| 8 | +import { compareVersions, getLatestVersion, getVersion } from "../version.js"; | |
| 9 | + | |
| 10 | +import { BaseService } from "./BaseService.js"; | |
| 11 | +import { serviceContainer } from "./ServiceContainer.js"; | |
| 12 | +import { UpdateServiceState, UpdateStatus } from "./types.js"; | |
| 13 | +const execAsync = promisify(exec); | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * Service for checking and performing CLI updates | |
| 17 | + */ | |
| 18 | +export class UpdateService extends BaseService<UpdateServiceState> { | |
| 19 | + constructor() { | |
| 20 | + super("update", { | |
| 21 | + autoUpdate: true, | |
| 22 | + isAutoUpdate: true, | |
| 23 | + status: UpdateStatus.IDLE, | |
| 24 | + message: "", | |
| 25 | + error: null, | |
| 26 | + isUpdateAvailable: false, | |
| 27 | + latestVersion: null, | |
| 28 | + currentVersion: getVersion(), | |
| 29 | + }); | |
| 30 | + } | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * Initialize the update service | |
| 34 | + */ | |
| 35 | + async doInitialize(headless?: boolean) { | |
| 36 | + // Don't automatically check in tests/headless | |
| 37 | + if (!headless && process.env.NODE_ENV !== "test") { | |
| 38 | + void this.checkAndAutoUpdate(); | |
| 39 | + } | |
| 40 | + | |
| 41 | + return this.currentState; | |
| 42 | + } | |
| 43 | + | |
| 44 | + private async checkAndAutoUpdate() { | |
| 45 | + // First get auto update setting from global context | |
| 46 | + const globalContext = new GlobalContext(); | |
| 47 | + const autoUpdate = globalContext.get("autoUpdateCli") ?? true; | |
| 48 | + this.setState({ | |
| 49 | + autoUpdate, | |
| 50 | + }); | |
| 51 | + | |
| 52 | + try { | |
| 53 | + // Check for updates | |
| 54 | + this.setState({ | |
| 55 | + status: UpdateStatus.CHECKING, | |
| 56 | + message: "Checking for updates", | |
| 57 | + }); | |
| 58 | + | |
| 59 | + const latestVersion = await getLatestVersion(); | |
| 60 | + this.setState({ | |
| 61 | + latestVersion, | |
| 62 | + }); | |
| 63 | + | |
| 64 | + if (!latestVersion) { | |
| 65 | + this.setState({ | |
| 66 | + status: UpdateStatus.IDLE, | |
| 67 | + message: "Continue CLI", | |
| 68 | + isUpdateAvailable: false, | |
| 69 | + }); | |
| 70 | + return; | |
| 71 | + } | |
| 72 | + | |
| 73 | + const comparison = compareVersions( | |
| 74 | + this.currentState.currentVersion, | |
| 75 | + latestVersion, | |
| 76 | + ); | |
| 77 | + const isUpdateAvailable = comparison === "older"; | |
| 78 | + this.setState({ | |
| 79 | + isUpdateAvailable, | |
| 80 | + }); | |
| 81 | + | |
| 82 | + if (this.currentState.currentVersion === "0.0.0-dev") { | |
| 83 | + this.setState({ | |
| 84 | + status: UpdateStatus.IDLE, | |
| 85 | + message: `Continue CLI`, | |
| 86 | + isUpdateAvailable, | |
| 87 | + latestVersion, | |
| 88 | + }); | |
| 89 | + return; // Uncomment to test auto-update behavior in dev | |
| 90 | + } | |
| 91 | + | |
| 92 | + // If update is available, automatically update | |
| 93 | + if ( | |
| 94 | + autoUpdate && | |
| 95 | + isUpdateAvailable && | |
| 96 | + this.currentState.status !== "updating" && | |
| 97 | + !process.env.CONTINUE_CLI_AUTO_UPDATED //Already auto updated, preventing sequential auto-update | |
| 98 | + ) { | |
| 99 | + await this.performUpdate(true); | |
| 100 | + } else { | |
| 101 | + this.setState({ | |
| 102 | + status: UpdateStatus.IDLE, | |
| 103 | + message: isUpdateAvailable | |
| 104 | + ? `Update available: v${latestVersion}` | |
| 105 | + : `Continue CLI v${this.currentState.currentVersion}`, | |
| 106 | + isUpdateAvailable, | |
| 107 | + latestVersion, | |
| 108 | + }); | |
| 109 | + } | |
| 110 | + } catch (error: any) { | |
| 111 | + logger.error("Error checking for updates:", error); | |
| 112 | + this.setState({ | |
| 113 | + status: UpdateStatus.ERROR, | |
| 114 | + message: `Continue CLI v${this.currentState.currentVersion}`, | |
| 115 | + error, | |
| 116 | + }); | |
| 117 | + } | |
| 118 | + } | |
| 119 | + | |
| 120 | + public async setAutoUpdate(value: boolean) { | |
| 121 | + const globalContext = new GlobalContext(); | |
| 122 | + globalContext.update("autoUpdateCli", value); | |
| 123 | + this.setState({ | |
| 124 | + autoUpdate: value, | |
| 125 | + }); | |
| 126 | + } | |
| 127 | + | |
| 128 | + // TODO this is a hack because our service state update code is broken | |
| 129 | + // Currently all things that need update use serviceContainer.set manually | |
| 130 | + // Rather than actually using the stateChanged event | |
| 131 | + setState(newState: Partial<UpdateServiceState>): void { | |
| 132 | + super.setState(newState); | |
| 133 | + serviceContainer.set("update", this.currentState); | |
| 134 | + } | |
| 135 | + | |
| 136 | + async performUpdate(isAutoUpdate?: boolean) { | |
| 137 | + if (this.currentState.status === "updating") { | |
| 138 | + return; | |
| 139 | + } | |
| 140 | + | |
| 141 | + try { | |
| 142 | + this.setState({ | |
| 143 | + isAutoUpdate, | |
| 144 | + status: UpdateStatus.UPDATING, | |
| 145 | + message: `${isAutoUpdate ? "Auto-updating" : "Updating"} to v${this.currentState.latestVersion}`, | |
| 146 | + }); | |
| 147 | + | |
| 148 | + // Install the update | |
| 149 | + const { stdout, stderr } = await execAsync("npm i -g @continuedev/cli"); | |
| 150 | + logger.debug("Update output:", { stdout, stderr }); | |
| 151 | + | |
| 152 | + if (stderr) { | |
| 153 | + const errLines = stderr.split("\n"); | |
| 154 | + for (const line of errLines) { | |
| 155 | + const lower = line.toLowerCase().trim(); | |
| 156 | + if ( | |
| 157 | + !line || | |
| 158 | + lower.includes("debugger") || | |
| 159 | + lower.includes("npm warn") | |
| 160 | + ) { | |
| 161 | + continue; | |
| 162 | + } | |
| 163 | + this.setState({ | |
| 164 | + status: UpdateStatus.ERROR, | |
| 165 | + message: `Error updating to v${this.currentState.latestVersion}`, | |
| 166 | + error: new Error(stderr), | |
| 167 | + }); | |
| 168 | + return; | |
| 169 | + } | |
| 170 | + } | |
| 171 | + | |
| 172 | + this.setState({ | |
| 173 | + status: UpdateStatus.UPDATED, | |
| 174 | + message: `${isAutoUpdate ? "Auto-updated to" : "Restart for"} v${this.currentState.latestVersion}`, | |
| 175 | + isUpdateAvailable: false, | |
| 176 | + }); | |
| 177 | + if (isAutoUpdate) { | |
| 178 | + this.restartCLI(); | |
| 179 | + } | |
| 180 | + } catch (error: any) { | |
| 181 | + logger.error("Error updating CLI:", error); | |
| 182 | + this.setState({ | |
| 183 | + status: UpdateStatus.ERROR, | |
| 184 | + message: isAutoUpdate ? "Auto-update failed" : "Update failed", | |
| 185 | + error, | |
| 186 | + }); | |
| 187 | + setTimeout(() => { | |
| 188 | + this.setState({ | |
| 189 | + status: UpdateStatus.IDLE, | |
| 190 | + message: `/update to v${this.currentState.latestVersion}`, | |
| 191 | + }); | |
| 192 | + }, 4000); | |
| 193 | + } | |
| 194 | + } | |
| 195 | + | |
| 196 | + private restartCLI(): void { | |
| 197 | + try { | |
| 198 | + const entryPoint = process.argv[1]; | |
| 199 | + const cliArgs = process.argv.slice(2); | |
| 200 | + const nodeExecutable = process.execPath; | |
| 201 | + | |
| 202 | + logger.debug( | |
| 203 | + `Preparing for CLI restart with: ${nodeExecutable} ${entryPoint} ${cliArgs.join( | |
| 204 | + " ", | |
| 205 | + )}`, | |
| 206 | + ); | |
| 207 | + | |
| 208 | + // Halt/clean up parent cn process | |
| 209 | + try { | |
| 210 | + // Remove all input listeners | |
| 211 | + global.clearTimeout = () => {}; | |
| 212 | + global.clearInterval = () => {}; | |
| 213 | + process.stdin.removeAllListeners(); | |
| 214 | + process.stdin.pause(); | |
| 215 | + // console.clear(); // Don't want to clear things that were in console before cn started | |
| 216 | + } catch (e) { | |
| 217 | + logger.debug("Error cleaning up terminal:", e); | |
| 218 | + } | |
| 219 | + | |
| 220 | + // Spawn a new detached cn process | |
| 221 | + const child = spawn(nodeExecutable, [entryPoint, ...cliArgs], { | |
| 222 | + detached: true, | |
| 223 | + stdio: "inherit", | |
| 224 | + env: { | |
| 225 | + ...process.env, | |
| 226 | + CONTINUE_CLI_AUTO_UPDATED: "true", | |
| 227 | + }, | |
| 228 | + }); | |
| 229 | + | |
| 230 | + // I did not find a way on existing to avoid a bug where next process has input glitches without leaving parent in place | |
| 231 | + // So instead of existing, parent will exit when child exits | |
| 232 | + // process.exit(0); | |
| 233 | + child.on("exit", (code) => { | |
| 234 | + process.exit(code); | |
| 235 | + }); | |
| 236 | + child.unref(); | |
| 237 | + } catch (error) { | |
| 238 | + logger.error("Failed to restart CLI:", error); | |
| 239 | + } | |
| 240 | + } | |
| 241 | +} |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | import { ApiClientService } from "./ApiClientService.js"; |
| 6 | 6 | import { AuthService } from "./AuthService.js"; |
| 7 | +import { ChatHistoryService } from "./ChatHistoryService.js"; | |
| 7 | 8 | import { ConfigService } from "./ConfigService.js"; |
| 8 | 9 | import { FileIndexService } from "./FileIndexService.js"; |
| 9 | 10 | import { MCPService } from "./MCPService.js"; |
| @@ -11,6 +12,7 @@ | ||
| 11 | 12 | import { modeService } from "./ModeService.js"; |
| 12 | 13 | import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; |
| 13 | 14 | import { serviceContainer } from "./ServiceContainer.js"; |
| 15 | +import { StorageSyncService } from "./StorageSyncService.js"; | |
| 14 | 16 | import { systemMessageService } from "./SystemMessageService.js"; |
| 15 | 17 | import { |
| 16 | 18 | ApiClientServiceState, |
| @@ -20,6 +22,7 @@ | ||
| 20 | 22 | ServiceInitOptions, |
| 21 | 23 | ServiceInitResult, |
| 22 | 24 | } from "./types.js"; |
| 25 | +import { UpdateService } from "./UpdateService.js"; | |
| 23 | 26 | |
| 24 | 27 | // Service instances |
| 25 | 28 | const authService = new AuthService(); |
| @@ -29,6 +32,9 @@ | ||
| 29 | 32 | const mcpService = new MCPService(); |
| 30 | 33 | const fileIndexService = new FileIndexService(); |
| 31 | 34 | const resourceMonitoringService = new ResourceMonitoringService(); |
| 35 | +const chatHistoryService = new ChatHistoryService(); | |
| 36 | +const updateService = new UpdateService(); | |
| 37 | +const storageSyncService = new StorageSyncService(); | |
| 32 | 38 | |
| 33 | 39 | /** |
| 34 | 40 | * Initialize all services and register them with the service container |
| @@ -130,6 +136,12 @@ | ||
| 130 | 136 | [], // No dependencies |
| 131 | 137 | ); |
| 132 | 138 | |
| 139 | + serviceContainer.register( | |
| 140 | + SERVICE_NAMES.UPDATE, | |
| 141 | + () => updateService.initialize(), | |
| 142 | + [], // No dependencies | |
| 143 | + ); | |
| 144 | + | |
| 133 | 145 | serviceContainer.register( |
| 134 | 146 | SERVICE_NAMES.API_CLIENT, |
| 135 | 147 | async () => { |
| @@ -241,6 +253,18 @@ | ||
| 241 | 253 | [], |
| 242 | 254 | ); |
| 243 | 255 | |
| 256 | + serviceContainer.register( | |
| 257 | + SERVICE_NAMES.STORAGE_SYNC, | |
| 258 | + () => storageSyncService.initialize(), | |
| 259 | + [], | |
| 260 | + ); | |
| 261 | + | |
| 262 | + serviceContainer.register( | |
| 263 | + SERVICE_NAMES.CHAT_HISTORY, | |
| 264 | + () => chatHistoryService.initialize(undefined, initOptions.headless), | |
| 265 | + [], // No dependencies for now, but could depend on SESSION in future | |
| 266 | + ); | |
| 267 | + | |
| 244 | 268 | // Eagerly initialize all services to ensure they're ready when needed |
| 245 | 269 | // This avoids race conditions and "service not ready" errors |
| 246 | 270 | await serviceContainer.initializeAll(); |
| @@ -275,16 +299,9 @@ | ||
| 275 | 299 | * Check if all core services are ready |
| 276 | 300 | */ |
| 277 | 301 | export function areServicesReady(): boolean { |
| 278 | - return [ | |
| 279 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 280 | - SERVICE_NAMES.AUTH, | |
| 281 | - SERVICE_NAMES.API_CLIENT, | |
| 282 | - SERVICE_NAMES.CONFIG, | |
| 283 | - SERVICE_NAMES.MODEL, | |
| 284 | - SERVICE_NAMES.MCP, | |
| 285 | - SERVICE_NAMES.FILE_INDEX, | |
| 286 | - SERVICE_NAMES.RESOURCE_MONITORING, | |
| 287 | - ].every((name) => serviceContainer.isReady(name)); | |
| 302 | + return Object.values(SERVICE_NAMES).every((name) => | |
| 303 | + serviceContainer.isReady(name), | |
| 304 | + ); | |
| 288 | 305 | } |
| 289 | 306 | |
| 290 | 307 | /** |
| @@ -307,6 +324,9 @@ | ||
| 307 | 324 | mode: modeService, |
| 308 | 325 | resourceMonitoring: resourceMonitoringService, |
| 309 | 326 | systemMessage: systemMessageService, |
| 327 | + chatHistory: chatHistoryService, | |
| 328 | + updateService: updateService, | |
| 329 | + storageSync: storageSyncService, | |
| 310 | 330 | } as const; |
| 311 | 331 | |
| 312 | 332 | // Export the service container for advanced usage |
| @@ -81,6 +81,25 @@ | ||
| 81 | 81 | prompts: MCPPrompt[]; |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | +export enum UpdateStatus { | |
| 85 | + IDLE = "idle", | |
| 86 | + CHECKING = "checking", | |
| 87 | + UPDATING = "updating", | |
| 88 | + UPDATED = "updated", | |
| 89 | + ERROR = "error", | |
| 90 | +} | |
| 91 | + | |
| 92 | +export interface UpdateServiceState { | |
| 93 | + autoUpdate: boolean; | |
| 94 | + isAutoUpdate: boolean; | |
| 95 | + status: UpdateStatus; | |
| 96 | + message: string; | |
| 97 | + error?: Error | null; | |
| 98 | + isUpdateAvailable: boolean; | |
| 99 | + latestVersion: string | null; | |
| 100 | + currentVersion: string; | |
| 101 | +} | |
| 102 | + | |
| 84 | 103 | export interface ApiClientServiceState { |
| 85 | 104 | apiClient: DefaultApiInterface | null; |
| 86 | 105 | } |
| @@ -92,6 +111,14 @@ | ||
| 92 | 111 | originalPolicies?: ToolPermissions; |
| 93 | 112 | } |
| 94 | 113 | |
| 114 | +export interface StorageSyncServiceState { | |
| 115 | + isEnabled: boolean; | |
| 116 | + storageId?: string; | |
| 117 | + lastUploadAt?: number; | |
| 118 | + lastError?: string | null; | |
| 119 | +} | |
| 120 | + | |
| 121 | +export type { ChatHistoryState } from "./ChatHistoryService.js"; | |
| 95 | 122 | export type { FileIndexServiceState } from "./FileIndexService.js"; |
| 96 | 123 | |
| 97 | 124 | /** |
| @@ -107,6 +134,9 @@ | ||
| 107 | 134 | FILE_INDEX: "fileIndex", |
| 108 | 135 | RESOURCE_MONITORING: "resourceMonitoring", |
| 109 | 136 | SYSTEM_MESSAGE: "systemMessage", |
| 137 | + CHAT_HISTORY: "chatHistory", | |
| 138 | + UPDATE: "update", | |
| 139 | + STORAGE_SYNC: "storageSync", | |
| 110 | 140 | } as const; |
| 111 | 141 | |
| 112 | 142 | /** |
| @@ -2,15 +2,32 @@ | ||
| 2 | 2 | import os from "os"; |
| 3 | 3 | import path from "path"; |
| 4 | 4 | |
| 5 | -import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js"; | |
| 5 | +import type { | |
| 6 | + BaseSessionMetadata, | |
| 7 | + ChatHistoryItem, | |
| 8 | + Session, | |
| 9 | +} from "core/index.js"; | |
| 6 | 10 | import historyManager from "core/util/history.js"; |
| 7 | 11 | import { v4 as uuidv4 } from "uuid"; |
| 8 | 12 | |
| 13 | +import { | |
| 14 | + getAccessToken, | |
| 15 | + isAuthenticatedConfig, | |
| 16 | + loadAuthConfig, | |
| 17 | +} from "./auth/workos.js"; | |
| 9 | 18 | import { DEFAULT_SESSION_TITLE } from "./constants/session.js"; |
| 19 | +import { env } from "./env.js"; | |
| 10 | 20 | import { logger } from "./util/logger.js"; |
| 11 | 21 | |
| 12 | -// Re-export SessionMetadata for external consumers | |
| 13 | -export type { SessionMetadata }; | |
| 22 | +// Re-export BaseSessionMetadata for external consumers | |
| 23 | +export type { BaseSessionMetadata }; | |
| 24 | + | |
| 25 | +// Extended type for sessions that can be local or remote | |
| 26 | +export interface ExtendedSessionMetadata extends BaseSessionMetadata { | |
| 27 | + firstUserMessage?: string; | |
| 28 | + isRemote?: boolean; | |
| 29 | + remoteId?: string; // For remote sessions, this is the agent ID | |
| 30 | +} | |
| 14 | 31 | |
| 15 | 32 | // Note: We now use UUID-based session IDs instead of terminal-based IDs. |
| 16 | 33 | // Each new chat session gets a unique UUID. |
| @@ -140,13 +157,17 @@ | ||
| 140 | 157 | }; |
| 141 | 158 | } |
| 142 | 159 | |
| 160 | +export function getSessionPersistenceSnapshot(session: Session): Session { | |
| 161 | + return modifySessionBeforeSave(session); | |
| 162 | +} | |
| 163 | + | |
| 143 | 164 | /** |
| 144 | 165 | * Save the current session to file |
| 145 | 166 | */ |
| 146 | 167 | export function saveSession(): void { |
| 147 | 168 | try { |
| 148 | 169 | const session = SessionManager.getInstance().getCurrentSession(); |
| 149 | - const sessionToSave = modifySessionBeforeSave(session); | |
| 170 | + const sessionToSave = getSessionPersistenceSnapshot(session); | |
| 150 | 171 | historyManager.save(sessionToSave); |
| 151 | 172 | } catch (error) { |
| 152 | 173 | logger.error("Error saving session:", error); |
| @@ -244,7 +265,7 @@ | ||
| 244 | 265 | */ |
| 245 | 266 | function getSessionMetadataWithPreview( |
| 246 | 267 | filePath: string, |
| 247 | -): (SessionMetadata & { firstUserMessage?: string }) | null { | |
| 268 | +): ExtendedSessionMetadata | null { | |
| 248 | 269 | try { |
| 249 | 270 | const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8")); |
| 250 | 271 | const stats = fs.statSync(filePath); |
| @@ -285,20 +306,65 @@ | ||
| 285 | 306 | } |
| 286 | 307 | |
| 287 | 308 | /** |
| 288 | - * List all available sessions with metadata | |
| 309 | + * Fetch remote agents/sessions from the API | |
| 310 | + */ | |
| 311 | +export async function getRemoteSessions(): Promise<ExtendedSessionMetadata[]> { | |
| 312 | + try { | |
| 313 | + const authConfig = loadAuthConfig(); | |
| 314 | + const accessToken = getAccessToken(authConfig); | |
| 315 | + | |
| 316 | + if ( | |
| 317 | + !accessToken || | |
| 318 | + !isAuthenticatedConfig(authConfig) || | |
| 319 | + !authConfig.userEmail.endsWith("@continue.dev") | |
| 320 | + ) { | |
| 321 | + return []; | |
| 322 | + } | |
| 323 | + | |
| 324 | + const response = await fetch(new URL("agents/devboxes", env.apiBase), { | |
| 325 | + method: "GET", | |
| 326 | + headers: { | |
| 327 | + "Content-Type": "application/json", | |
| 328 | + Authorization: `Bearer ${accessToken}`, | |
| 329 | + }, | |
| 330 | + }); | |
| 331 | + | |
| 332 | + if (!response.ok) { | |
| 333 | + logger.error(`Failed to fetch remote agents: ${response.status}`); | |
| 334 | + return []; | |
| 335 | + } | |
| 336 | + | |
| 337 | + const agents = await response.json(); | |
| 338 | + | |
| 339 | + return agents.map((agent: any) => ({ | |
| 340 | + sessionId: `remote-${agent.id}`, | |
| 341 | + title: agent.name || "Remote Agent", | |
| 342 | + dateCreated: new Date(agent.create_time_ms).toISOString(), | |
| 343 | + workspaceDirectory: "", | |
| 344 | + isRemote: true, | |
| 345 | + remoteId: agent.id, | |
| 346 | + firstUserMessage: "Remote agent session", | |
| 347 | + })); | |
| 348 | + } catch (error) { | |
| 349 | + logger.error("Error fetching remote sessions:", error); | |
| 350 | + return []; | |
| 351 | + } | |
| 352 | +} | |
| 353 | + | |
| 354 | +/** | |
| 355 | + * List all available sessions with metadata (both local and remote) | |
| 289 | 356 | */ |
| 290 | -export function listSessions( | |
| 291 | - limit: number = 10, | |
| 292 | -): (SessionMetadata & { firstUserMessage?: string })[] { | |
| 357 | +export async function listSessions( | |
| 358 | + limit: number = 100, | |
| 359 | +): Promise<ExtendedSessionMetadata[]> { | |
| 293 | 360 | try { |
| 294 | - const sessions = historyManager.list({ limit }); | |
| 361 | + // Get local sessions | |
| 362 | + const localSessions = historyManager.list({ limit }); | |
| 295 | 363 | |
| 296 | - // Add first user message preview to each session | |
| 297 | - const sessionsWithPreview: (SessionMetadata & { | |
| 298 | - firstUserMessage?: string; | |
| 299 | - })[] = []; | |
| 364 | + // Add first user message preview to each local session | |
| 365 | + const localSessionsWithPreview: ExtendedSessionMetadata[] = []; | |
| 300 | 366 | |
| 301 | - for (const sessionMeta of sessions) { | |
| 367 | + for (const sessionMeta of localSessions) { | |
| 302 | 368 | const sessionFilePath = path.join( |
| 303 | 369 | getSessionDir(), |
| 304 | 370 | `${sessionMeta.sessionId}.json`, |
| @@ -307,15 +373,32 @@ | ||
| 307 | 373 | if (fs.existsSync(sessionFilePath)) { |
| 308 | 374 | const metadata = getSessionMetadataWithPreview(sessionFilePath); |
| 309 | 375 | if (metadata) { |
| 310 | - sessionsWithPreview.push(metadata); | |
| 376 | + localSessionsWithPreview.push({ | |
| 377 | + ...metadata, | |
| 378 | + isRemote: false, | |
| 379 | + }); | |
| 311 | 380 | } |
| 312 | 381 | } else { |
| 313 | 382 | // Fall back to basic metadata if file doesn't exist |
| 314 | - sessionsWithPreview.push(sessionMeta); | |
| 383 | + localSessionsWithPreview.push({ | |
| 384 | + ...sessionMeta, | |
| 385 | + isRemote: false, | |
| 386 | + }); | |
| 315 | 387 | } |
| 316 | 388 | } |
| 317 | 389 | |
| 318 | - return sessionsWithPreview; | |
| 390 | + // Get remote sessions | |
| 391 | + const remoteSessions = await getRemoteSessions(); | |
| 392 | + | |
| 393 | + // Combine and sort by date (most recent first) | |
| 394 | + const allSessions = [...localSessionsWithPreview, ...remoteSessions] | |
| 395 | + .sort( | |
| 396 | + (a, b) => | |
| 397 | + new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(), | |
| 398 | + ) | |
| 399 | + .slice(0, limit); | |
| 400 | + | |
| 401 | + return allSessions; | |
| 319 | 402 | } catch (error) { |
| 320 | 403 | logger.error("Error listing sessions:", error); |
| 321 | 404 | return []; |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | ) |
| 14 | 14 | .option("--readonly", "Start in plan mode (read-only tools)") |
| 15 | 15 | .option("--auto", "Start in auto mode (all tools allowed)") |
| 16 | - .option("-v, --verbose", "Enable verbose logging") | |
| 16 | + .option("--verbose", "Enable verbose logging") | |
| 17 | 17 | .option( |
| 18 | 18 | "--rule <rule>", |
| 19 | 19 | "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", |
| @@ -0,0 +1,52 @@ | ||
| 1 | +import { describe, expect, it, vi, beforeEach } from "vitest"; | |
| 2 | + | |
| 3 | +import { handleSlashCommands } from "./slashCommands.js"; | |
| 4 | + | |
| 5 | +describe("Remote mode slash commands", () => { | |
| 6 | + const mockAssistant = { | |
| 7 | + name: "test", | |
| 8 | + version: "1.0.0", | |
| 9 | + prompts: [], | |
| 10 | + }; | |
| 11 | + | |
| 12 | + beforeEach(() => { | |
| 13 | + vi.clearAllMocks(); | |
| 14 | + }); | |
| 15 | + | |
| 16 | + describe("/diff and /apply commands", () => { | |
| 17 | + it("should not be handled by handleSlashCommands - these are handled by TUI layer", async () => { | |
| 18 | + // /diff and /apply are handled by handleSpecialCommands in useChat.helpers.ts, | |
| 19 | + // not by the general slash command system. These commands are intercepted | |
| 20 | + // at the TUI layer before reaching handleSlashCommands, so handleSlashCommands | |
| 21 | + // should return null (no match) for these commands. | |
| 22 | + | |
| 23 | + const diffResult = await handleSlashCommands("/diff", mockAssistant); | |
| 24 | + expect(diffResult).toBe(null); | |
| 25 | + | |
| 26 | + const applyResult = await handleSlashCommands("/apply", mockAssistant); | |
| 27 | + expect(applyResult).toBe(null); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should return unknown command for remote commands when called directly", async () => { | |
| 31 | + // When called directly (bypassing handleSpecialCommands), /diff and /apply | |
| 32 | + // should return "Unknown command" because they're listed in REMOTE_MODE_SLASH_COMMANDS | |
| 33 | + // for UI display but not implemented as handlers. | |
| 34 | + | |
| 35 | + const diffResult = await handleSlashCommands("/diff", mockAssistant, { | |
| 36 | + remoteUrl: "http://localhost:3000", | |
| 37 | + isRemoteMode: true, | |
| 38 | + }); | |
| 39 | + expect(diffResult).toEqual({ | |
| 40 | + output: "Unknown command: diff", | |
| 41 | + }); | |
| 42 | + | |
| 43 | + const applyResult = await handleSlashCommands("/apply", mockAssistant, { | |
| 44 | + remoteUrl: "http://localhost:3000", | |
| 45 | + isRemoteMode: true, | |
| 46 | + }); | |
| 47 | + expect(applyResult).toEqual({ | |
| 48 | + output: "Unknown command: apply", | |
| 49 | + }); | |
| 50 | + }); | |
| 51 | + }); | |
| 52 | +}); |
| @@ -83,6 +83,10 @@ | ||
| 83 | 83 | () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json", |
| 84 | 84 | ), |
| 85 | 85 | hasSession: vi.fn(() => false), |
| 86 | + getCurrentSession: vi.fn(() => { | |
| 87 | + throw new Error("Session not available"); | |
| 88 | + }), | |
| 89 | + updateSessionTitle: vi.fn(), | |
| 86 | 90 | })); |
| 87 | 91 | |
| 88 | 92 | describe("slashCommands", () => { |
| @@ -141,8 +145,8 @@ | ||
| 141 | 145 | expect(result?.output).toContain("Not logged in"); |
| 142 | 146 | expect(result?.output).toContain("Configuration:"); |
| 143 | 147 | expect(result?.output).toContain("/test/config.yaml"); |
| 144 | - expect(result?.output).toContain("Session History:"); | |
| 145 | - expect(result?.output).toContain(".json"); | |
| 148 | + expect(result?.output).toContain("Session:"); | |
| 149 | + expect(result?.output).toContain("Session not available"); | |
| 146 | 150 | expect(result?.exit).toBe(false); |
| 147 | 151 | }); |
| 148 | 152 | |
| @@ -214,7 +218,7 @@ | ||
| 214 | 218 | expect(result).toBeDefined(); |
| 215 | 219 | expect(result?.output).toContain("Authentication:"); |
| 216 | 220 | expect(result?.output).toContain("test@example.com"); |
| 217 | - expect(result?.output).toContain("(no org)"); | |
| 221 | + expect(result?.output).toContain("test-org-id"); | |
| 218 | 222 | expect(result?.output).toContain("Configuration:"); |
| 219 | 223 | expect(result?.output).toContain("/custom/config.yaml"); |
| 220 | 224 | expect(result?.exit).toBe(false); |
| @@ -244,12 +248,18 @@ | ||
| 244 | 248 | it("should use test session directory when in test mode", async () => { |
| 245 | 249 | const { isAuthenticated } = await import("./auth/workos.js"); |
| 246 | 250 | const { services } = await import("./services/index.js"); |
| 247 | - const { getSessionFilePath } = await import("./session.js"); | |
| 251 | + const { getSessionFilePath, getCurrentSession } = await import( | |
| 252 | + "./session.js" | |
| 253 | + ); | |
| 248 | 254 | |
| 249 | - // Mock the session path for this specific test | |
| 255 | + // Mock the session functions for this specific test | |
| 250 | 256 | (getSessionFilePath as any).mockReturnValue( |
| 251 | 257 | "/test-home/.continue/cli-sessions/continue-cli-test-123.json", |
| 252 | 258 | ); |
| 259 | + (getCurrentSession as any).mockReturnValue({ | |
| 260 | + sessionId: "test-123", | |
| 261 | + title: "Test Session", | |
| 262 | + }); | |
| 253 | 263 | |
| 254 | 264 | ( |
| 255 | 265 | isAuthenticated as MockedFunction<typeof isAuthenticated> |
| @@ -265,8 +275,65 @@ | ||
| 265 | 275 | |
| 266 | 276 | const result = await handleSlashCommands("/info", mockAssistant); |
| 267 | 277 | |
| 278 | + expect(result?.output).toContain("Session:"); | |
| 279 | + expect(result?.output).toContain("Test Session"); | |
| 268 | 280 | expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); |
| 269 | 281 | expect(result?.output).toContain(".json"); |
| 270 | 282 | }); |
| 283 | + | |
| 284 | + it("should handle /title command with valid title", async () => { | |
| 285 | + const { updateSessionTitle } = await import("./session.js"); | |
| 286 | + | |
| 287 | + const result = await handleSlashCommands( | |
| 288 | + "/title My New Session Title", | |
| 289 | + mockAssistant, | |
| 290 | + ); | |
| 291 | + | |
| 292 | + expect(updateSessionTitle).toHaveBeenCalledWith("My New Session Title"); | |
| 293 | + expect(result).toBeDefined(); | |
| 294 | + expect(result?.output).toContain( | |
| 295 | + 'Session title updated to: "My New Session Title"', | |
| 296 | + ); | |
| 297 | + expect(result?.exit).toBe(false); | |
| 298 | + }); | |
| 299 | + | |
| 300 | + it("should handle /title command with empty title", async () => { | |
| 301 | + const result = await handleSlashCommands("/title", mockAssistant); | |
| 302 | + | |
| 303 | + expect(result).toBeDefined(); | |
| 304 | + expect(result?.output).toContain( | |
| 305 | + "Please provide a title. Usage: /title <your title>", | |
| 306 | + ); | |
| 307 | + expect(result?.exit).toBe(false); | |
| 308 | + }); | |
| 309 | + | |
| 310 | + it("should handle /title command with whitespace-only title", async () => { | |
| 311 | + const result = await handleSlashCommands("/title ", mockAssistant); | |
| 312 | + | |
| 313 | + expect(result).toBeDefined(); | |
| 314 | + expect(result?.output).toContain( | |
| 315 | + "Please provide a title. Usage: /title <your title>", | |
| 316 | + ); | |
| 317 | + expect(result?.exit).toBe(false); | |
| 318 | + }); | |
| 319 | + | |
| 320 | + it("should handle /title command when session update fails", async () => { | |
| 321 | + const { updateSessionTitle } = await import("./session.js"); | |
| 322 | + | |
| 323 | + (updateSessionTitle as any).mockImplementation(() => { | |
| 324 | + throw new Error("Failed to save session"); | |
| 325 | + }); | |
| 326 | + | |
| 327 | + const result = await handleSlashCommands( | |
| 328 | + "/title Test Title", | |
| 329 | + mockAssistant, | |
| 330 | + ); | |
| 331 | + | |
| 332 | + expect(result).toBeDefined(); | |
| 333 | + expect(result?.output).toContain( | |
| 334 | + "Failed to update title: Failed to save session", | |
| 335 | + ); | |
| 336 | + expect(result?.exit).toBe(false); | |
| 337 | + }); | |
| 271 | 338 | }); |
| 272 | 339 | }); |
| @@ -7,15 +7,19 @@ | ||
| 7 | 7 | loadAuthConfig, |
| 8 | 8 | } from "./auth/workos.js"; |
| 9 | 9 | import { getAllSlashCommands } from "./commands/commands.js"; |
| 10 | +import { handleInit } from "./commands/init.js"; | |
| 11 | +import { handleInfoSlashCommand } from "./infoScreen.js"; | |
| 10 | 12 | import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; |
| 11 | -import { getSessionFilePath } from "./session.js"; | |
| 13 | +import { getCurrentSession, updateSessionTitle } from "./session.js"; | |
| 12 | 14 | import { posthogService } from "./telemetry/posthogService.js"; |
| 15 | +import { telemetryService } from "./telemetry/telemetryService.js"; | |
| 13 | 16 | import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; |
| 14 | -import { getVersion } from "./version.js"; | |
| 15 | 17 | |
| 16 | 18 | type CommandHandler = ( |
| 17 | 19 | args: string[], |
| 18 | 20 | assistant: AssistantConfig, |
| 21 | + remoteUrl?: string, | |
| 22 | + options?: { isRemoteMode?: boolean }, | |
| 19 | 23 | ) => Promise<SlashCommandResult> | SlashCommandResult; |
| 20 | 24 | |
| 21 | 25 | async function handleHelp(_args: string[], _assistant: AssistantConfig) { |
| @@ -28,6 +32,7 @@ | ||
| 28 | 32 | ` ${chalk.cyan("Enter")} Submit message`, |
| 29 | 33 | ` ${chalk.cyan("Shift+Enter")} New line`, |
| 30 | 34 | ` ${chalk.cyan("\\")} Line continuation (at end of line)`, |
| 35 | + ` ${chalk.cyan("!")} Shell mode - run shell commands`, | |
| 31 | 36 | "", |
| 32 | 37 | chalk.white("Controls:"), |
| 33 | 38 | ` ${chalk.cyan("Ctrl+C")} Clear input`, |
| @@ -39,16 +44,16 @@ | ||
| 39 | 44 | chalk.white("Special Characters:"), |
| 40 | 45 | ` ${chalk.cyan("@")} Search and attach files for context`, |
| 41 | 46 | ` ${chalk.cyan("/")} Access slash commands`, |
| 47 | + ` ${chalk.cyan("!")} Execute bash commands directly`, | |
| 42 | 48 | "", |
| 43 | 49 | chalk.white("Available Commands:"), |
| 44 | 50 | ` Type ${chalk.cyan("/")} to see available slash commands`, |
| 51 | + ` Type ${chalk.cyan("!")} followed by a command to execute bash directly`, | |
| 45 | 52 | ].join("\n"); |
| 46 | - posthogService.capture("useSlashCommand", { name: "help" }); | |
| 47 | 53 | return { output: helpMessage }; |
| 48 | 54 | } |
| 49 | 55 | |
| 50 | 56 | async function handleLogin() { |
| 51 | - posthogService.capture("useSlashCommand", { name: "login" }); | |
| 52 | 57 | try { |
| 53 | 58 | const newAuthState = await services.auth.login(); |
| 54 | 59 | await reloadService(SERVICE_NAMES.AUTH); |
| @@ -74,7 +79,6 @@ | ||
| 74 | 79 | } |
| 75 | 80 | |
| 76 | 81 | async function handleLogout() { |
| 77 | - posthogService.capture("useSlashCommand", { name: "logout" }); | |
| 78 | 82 | try { |
| 79 | 83 | await services.auth.logout(); |
| 80 | 84 | return { |
| @@ -90,7 +94,6 @@ | ||
| 90 | 94 | } |
| 91 | 95 | |
| 92 | 96 | function handleWhoami() { |
| 93 | - posthogService.capture("useSlashCommand", { name: "whoami" }); | |
| 94 | 97 | if (isAuthenticated()) { |
| 95 | 98 | const config = loadAuthConfig(); |
| 96 | 99 | if (config && isAuthenticatedConfig(config)) { |
| @@ -112,133 +115,100 @@ | ||
| 112 | 115 | } |
| 113 | 116 | } |
| 114 | 117 | |
| 115 | -async function handleInfo() { | |
| 116 | - posthogService.capture("useSlashCommand", { name: "info" }); | |
| 117 | - | |
| 118 | - const infoLines = []; | |
| 119 | - | |
| 120 | - // Version and working directory info | |
| 121 | - const version = getVersion(); | |
| 122 | - const cwd = process.cwd(); | |
| 123 | - | |
| 124 | - infoLines.push(chalk.white("CLI Information:")); | |
| 125 | - infoLines.push(` Version: ${chalk.green(version)}`); | |
| 126 | - infoLines.push(` Working Directory: ${chalk.blue(cwd)}`); | |
| 127 | - | |
| 128 | - // Auth info | |
| 129 | - if (isAuthenticated()) { | |
| 130 | - const config = loadAuthConfig(); | |
| 131 | - if (config && isAuthenticatedConfig(config)) { | |
| 132 | - const email = config.userEmail || config.userId; | |
| 133 | - const org = "(no org)"; // Organization info not available in AuthenticatedConfig | |
| 134 | - infoLines.push(""); | |
| 135 | - infoLines.push(chalk.white("Authentication:")); | |
| 136 | - infoLines.push(` Email: ${chalk.green(email)}`); | |
| 137 | - infoLines.push(` Organization: ${chalk.cyan(org)}`); | |
| 138 | - } else { | |
| 139 | - infoLines.push(""); | |
| 140 | - infoLines.push(chalk.white("Authentication:")); | |
| 141 | - infoLines.push( | |
| 142 | - ` ${chalk.yellow("Authenticated via environment variable")}`, | |
| 143 | - ); | |
| 144 | - } | |
| 145 | - } else { | |
| 146 | - infoLines.push(""); | |
| 147 | - infoLines.push(chalk.white("Authentication:")); | |
| 148 | - infoLines.push(` ${chalk.red("Not logged in")}`); | |
| 149 | - } | |
| 150 | - | |
| 151 | - // Config info | |
| 118 | +async function handleFork() { | |
| 152 | 119 | try { |
| 153 | - const configState = services.config.getState(); | |
| 154 | - infoLines.push(""); | |
| 155 | - infoLines.push(chalk.white("Configuration:")); | |
| 156 | - if (configState.config) { | |
| 157 | - infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`); | |
| 158 | - } else { | |
| 159 | - infoLines.push(` ${chalk.red(`Config not found`)}`); | |
| 160 | - } | |
| 161 | - if (configState.configPath) { | |
| 162 | - infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); | |
| 163 | - } | |
| 164 | - | |
| 165 | - // Add current model info | |
| 120 | + const currentSession = getCurrentSession(); | |
| 121 | + const forkCommand = `cn --fork ${currentSession.sessionId}`; | |
| 122 | + // Try to copy to clipboard dynamically to avoid hard dependency in tests | |
| 166 | 123 | try { |
| 167 | - const modelInfo = services.model?.getModelInfo(); | |
| 168 | - if (modelInfo) { | |
| 169 | - infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`); | |
| 170 | - } else { | |
| 171 | - infoLines.push(` Model: ${chalk.red("Not available")}`); | |
| 172 | - } | |
| 124 | + const clipboardy = await import("clipboardy"); | |
| 125 | + await clipboardy.default.write(forkCommand); | |
| 126 | + return { | |
| 127 | + exit: false, | |
| 128 | + output: chalk.gray(`${forkCommand} (copied to clipboard)`), | |
| 129 | + }; | |
| 173 | 130 | } catch { |
| 174 | - infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`); | |
| 131 | + return { | |
| 132 | + exit: false, | |
| 133 | + output: chalk.gray(`${forkCommand}`), | |
| 134 | + }; | |
| 175 | 135 | } |
| 176 | - } catch { | |
| 177 | - infoLines.push(""); | |
| 178 | - infoLines.push(chalk.white("Configuration:")); | |
| 179 | - infoLines.push(` ${chalk.red("Configuration service not available")}`); | |
| 136 | + } catch (error: any) { | |
| 137 | + return { | |
| 138 | + exit: false, | |
| 139 | + output: chalk.red(`Failed to create fork command: ${error.message}`), | |
| 140 | + }; | |
| 180 | 141 | } |
| 142 | +} | |
| 181 | 143 | |
| 182 | - // Session history path | |
| 183 | - infoLines.push(""); | |
| 184 | - infoLines.push(chalk.white("Session History:")); | |
| 185 | - const sessionFilePath = getSessionFilePath(); | |
| 144 | +function handleTitle(args: string[]) { | |
| 145 | + posthogService.capture("useSlashCommand", { name: "title" }); | |
| 186 | 146 | |
| 187 | - infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); | |
| 147 | + const title = args.join(" ").trim(); | |
| 148 | + if (!title) { | |
| 149 | + return { | |
| 150 | + exit: false, | |
| 151 | + output: chalk.yellow( | |
| 152 | + "Please provide a title. Usage: /title <your title>", | |
| 153 | + ), | |
| 154 | + }; | |
| 155 | + } | |
| 188 | 156 | |
| 189 | - return { | |
| 190 | - exit: false, | |
| 191 | - output: infoLines.join("\n"), | |
| 192 | - }; | |
| 157 | + try { | |
| 158 | + updateSessionTitle(title); | |
| 159 | + return { | |
| 160 | + exit: false, | |
| 161 | + output: chalk.green(`Session title updated to: "${title}"`), | |
| 162 | + }; | |
| 163 | + } catch (error: any) { | |
| 164 | + return { | |
| 165 | + exit: false, | |
| 166 | + output: chalk.red(`Failed to update title: ${error.message}`), | |
| 167 | + }; | |
| 168 | + } | |
| 193 | 169 | } |
| 194 | 170 | |
| 195 | 171 | const commandHandlers: Record<string, CommandHandler> = { |
| 196 | 172 | help: handleHelp, |
| 197 | 173 | clear: () => { |
| 198 | - posthogService.capture("useSlashCommand", { name: "clear" }); | |
| 199 | 174 | return { clear: true, output: "Chat history cleared" }; |
| 200 | 175 | }, |
| 201 | 176 | exit: () => { |
| 202 | - posthogService.capture("useSlashCommand", { name: "exit" }); | |
| 203 | 177 | return { exit: true, output: "Goodbye!" }; |
| 204 | 178 | }, |
| 205 | 179 | config: () => { |
| 206 | - posthogService.capture("useSlashCommand", { name: "config" }); | |
| 207 | 180 | return { openConfigSelector: true }; |
| 208 | 181 | }, |
| 209 | 182 | login: handleLogin, |
| 210 | 183 | logout: handleLogout, |
| 211 | 184 | whoami: handleWhoami, |
| 212 | - info: handleInfo, | |
| 185 | + info: handleInfoSlashCommand, | |
| 213 | 186 | model: () => ({ openModelSelector: true }), |
| 214 | 187 | compact: () => { |
| 215 | - posthogService.capture("useSlashCommand", { name: "compact" }); | |
| 216 | 188 | return { compact: true }; |
| 217 | 189 | }, |
| 218 | 190 | mcp: () => { |
| 219 | - posthogService.capture("useSlashCommand", { name: "mcp" }); | |
| 220 | 191 | return { openMcpSelector: true }; |
| 221 | 192 | }, |
| 222 | 193 | resume: () => { |
| 223 | - posthogService.capture("useSlashCommand", { name: "resume" }); | |
| 224 | 194 | return { openSessionSelector: true }; |
| 225 | 195 | }, |
| 196 | + fork: handleFork, | |
| 197 | + title: handleTitle, | |
| 198 | + init: (args, assistant) => { | |
| 199 | + posthogService.capture("useSlashCommand", { name: "init" }); | |
| 200 | + return handleInit(args, assistant); | |
| 201 | + }, | |
| 202 | + update: () => { | |
| 203 | + return { openUpdateSelector: true }; | |
| 204 | + }, | |
| 226 | 205 | }; |
| 227 | 206 | |
| 228 | 207 | export async function handleSlashCommands( |
| 229 | 208 | input: string, |
| 230 | 209 | assistant: AssistantConfig, |
| 231 | -): Promise<{ | |
| 232 | - output?: string; | |
| 233 | - exit?: boolean; | |
| 234 | - newInput?: string; | |
| 235 | - clear?: boolean; | |
| 236 | - openConfigSelector?: boolean; | |
| 237 | - openModelSelector?: boolean; | |
| 238 | - openMCPSelector?: boolean; | |
| 239 | - openSessionSelector?: boolean; | |
| 240 | - compact?: boolean; | |
| 241 | -} | null> { | |
| 210 | + options?: { remoteUrl?: string; isRemoteMode?: boolean }, | |
| 211 | +): Promise<SlashCommandResult | null> { | |
| 242 | 212 | // Only trigger slash commands if slash is the very first character |
| 243 | 213 | if (!input.startsWith("/") || !input.trim().startsWith("/")) { |
| 244 | 214 | return null; |
| @@ -246,9 +216,12 @@ | ||
| 246 | 216 | |
| 247 | 217 | const [command, ...args] = input.slice(1).split(" "); |
| 248 | 218 | |
| 219 | + telemetryService.recordSlashCommand(command); | |
| 220 | + posthogService.capture("useSlashCommand", { name: command }); | |
| 221 | + | |
| 249 | 222 | const handler = commandHandlers[command]; |
| 250 | 223 | if (handler) { |
| 251 | - return await handler(args, assistant); | |
| 224 | + return await handler(args, assistant, options?.remoteUrl, options); | |
| 252 | 225 | } |
| 253 | 226 | |
| 254 | 227 | // Check for custom assistant prompts |
| @@ -261,7 +234,9 @@ | ||
| 261 | 234 | } |
| 262 | 235 | |
| 263 | 236 | // Check if this command would match any available commands (same logic as UI) |
| 264 | - const allCommands = getAllSlashCommands(assistant); | |
| 237 | + const allCommands = getAllSlashCommands(assistant, { | |
| 238 | + isRemoteMode: options?.isRemoteMode, | |
| 239 | + }); | |
| 265 | 240 | const hasMatches = allCommands.some((cmd) => |
| 266 | 241 | cmd.name.toLowerCase().includes(command.toLowerCase()), |
| 267 | 242 | ); |
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | MCPServiceState, |
| 10 | 10 | MCPTool, |
| 11 | 11 | SERVICE_NAMES, |
| 12 | + services, | |
| 12 | 13 | } from "../services/index.js"; |
| 13 | 14 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 14 | 15 | import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; |
| @@ -27,14 +28,23 @@ | ||
| 27 | 28 | callbacks: StreamCallbacks | undefined, |
| 28 | 29 | isHeadless: boolean, |
| 29 | 30 | ): Promise<boolean> { |
| 31 | + const chatHistorySvc = services.chatHistory; | |
| 32 | + const useService = | |
| 33 | + typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady(); | |
| 30 | 34 | if (toolCalls.length === 0) { |
| 31 | 35 | if (content) { |
| 32 | - chatHistory.push( | |
| 33 | - createHistoryItem({ | |
| 34 | - role: "assistant", | |
| 35 | - content, | |
| 36 | - }), | |
| 37 | - ); | |
| 36 | + if (useService) { | |
| 37 | + // Service-driven: write assistant message via service | |
| 38 | + chatHistorySvc.addAssistantMessage(content); | |
| 39 | + } else { | |
| 40 | + // Fallback only when service is unavailable | |
| 41 | + chatHistory.push( | |
| 42 | + createHistoryItem({ | |
| 43 | + role: "assistant", | |
| 44 | + content, | |
| 45 | + }), | |
| 46 | + ); | |
| 47 | + } | |
| 38 | 48 | } |
| 39 | 49 | return false; |
| 40 | 50 | } |
| @@ -68,7 +78,16 @@ | ||
| 68 | 78 | })), |
| 69 | 79 | }; |
| 70 | 80 | |
| 71 | - chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 81 | + if (useService) { | |
| 82 | + // Important: pass ChatCompletion-style toolCalls, not internal ToolCall[] | |
| 83 | + chatHistorySvc.addAssistantMessage( | |
| 84 | + assistantMessage.content || "", | |
| 85 | + assistantMessage.toolCalls, | |
| 86 | + ); | |
| 87 | + } else { | |
| 88 | + // Fallback only when service is unavailable | |
| 89 | + chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 90 | + } | |
| 72 | 91 | |
| 73 | 92 | // First preprocess the tool calls |
| 74 | 93 | const { preprocessedCalls, errorChatEntries } = |
| @@ -77,13 +96,17 @@ | ||
| 77 | 96 | // Add any preprocessing errors to chat history |
| 78 | 97 | // Convert error entries from OpenAI format to ChatHistoryItem format |
| 79 | 98 | errorChatEntries.forEach((errorEntry) => { |
| 80 | - chatHistory.push( | |
| 81 | - createHistoryItem({ | |
| 82 | - role: "tool", | |
| 83 | - content: stripImages(errorEntry.content) || "", | |
| 84 | - toolCallId: errorEntry.tool_call_id, | |
| 85 | - }), | |
| 86 | - ); | |
| 99 | + const item = createHistoryItem({ | |
| 100 | + role: "tool", | |
| 101 | + content: stripImages(errorEntry.content) || "", | |
| 102 | + toolCallId: errorEntry.tool_call_id, | |
| 103 | + }); | |
| 104 | + if (useService) { | |
| 105 | + chatHistorySvc.addHistoryItem(item); | |
| 106 | + } else { | |
| 107 | + // Fallback only when service is unavailable | |
| 108 | + chatHistory.push(item); | |
| 109 | + } | |
| 87 | 110 | }); |
| 88 | 111 | |
| 89 | 112 | // Execute the valid preprocessed tool calls |
| @@ -97,32 +120,55 @@ | ||
| 97 | 120 | return true; // Signal early return needed |
| 98 | 121 | } |
| 99 | 122 | |
| 100 | - // Convert tool results from OpenAI format to ChatHistoryItem format | |
| 101 | - // and add them to the chat history | |
| 123 | + // Convert tool results and add them to the chat history with per-result status | |
| 102 | 124 | toolResults.forEach((toolResult) => { |
| 103 | - // Find the corresponding tool call state to update | |
| 104 | - const lastAssistantIndex = chatHistory.findLastIndex( | |
| 105 | - (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 106 | - ); | |
| 125 | + const resultContent = | |
| 126 | + typeof toolResult.content === "string" ? toolResult.content : ""; | |
| 107 | 127 | |
| 128 | + // Derive per-result status instead of applying batch-wide hasRejection | |
| 129 | + let status: ToolStatus = "done"; | |
| 130 | + const lower = resultContent.toLowerCase(); | |
| 108 | 131 | if ( |
| 109 | - lastAssistantIndex >= 0 && | |
| 110 | - chatHistory[lastAssistantIndex].toolCallStates | |
| 132 | + lower.includes("permission denied by user") || | |
| 133 | + lower.includes("cancelled due to previous tool rejection") || | |
| 134 | + lower.includes("canceled due to previous tool rejection") | |
| 111 | 135 | ) { |
| 112 | - const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 113 | - (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 114 | - ); | |
| 136 | + status = "canceled"; | |
| 137 | + } else if ( | |
| 138 | + lower.startsWith("error executing tool") || | |
| 139 | + lower.startsWith("error:") | |
| 140 | + ) { | |
| 141 | + status = "errored" as ToolStatus; | |
| 142 | + } | |
| 115 | 143 | |
| 116 | - if (toolState) { | |
| 117 | - toolState.status = hasRejection ? "canceled" : "done"; | |
| 118 | - toolState.output = [ | |
| 119 | - { | |
| 120 | - content: | |
| 121 | - typeof toolResult.content === "string" ? toolResult.content : "", | |
| 122 | - name: `Tool Result`, | |
| 123 | - description: "Tool execution result", | |
| 124 | - }, | |
| 125 | - ]; | |
| 144 | + if (useService) { | |
| 145 | + chatHistorySvc.addToolResult( | |
| 146 | + toolResult.tool_call_id, | |
| 147 | + resultContent, | |
| 148 | + status, | |
| 149 | + ); | |
| 150 | + } else { | |
| 151 | + // Fallback only when service is unavailable: update local tool state | |
| 152 | + const lastAssistantIndex = chatHistory.findLastIndex( | |
| 153 | + (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 154 | + ); | |
| 155 | + if ( | |
| 156 | + lastAssistantIndex >= 0 && | |
| 157 | + chatHistory[lastAssistantIndex].toolCallStates | |
| 158 | + ) { | |
| 159 | + const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 160 | + (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 161 | + ); | |
| 162 | + if (toolState) { | |
| 163 | + toolState.status = status; | |
| 164 | + toolState.output = [ | |
| 165 | + { | |
| 166 | + content: resultContent, | |
| 167 | + name: `Tool Result`, | |
| 168 | + description: "Tool execution result", | |
| 169 | + }, | |
| 170 | + ]; | |
| 171 | + } | |
| 126 | 172 | } |
| 127 | 173 | } |
| 128 | 174 | }); |
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +vi.mock("../util/logger.js", () => ({ | |
| 4 | + logger: { | |
| 5 | + debug: vi.fn(), | |
| 6 | + info: vi.fn(), | |
| 7 | + warn: vi.fn(), | |
| 8 | + error: vi.fn(), | |
| 9 | + setLevel: vi.fn(), | |
| 10 | + configureHeadlessMode: vi.fn(), | |
| 11 | + getLogPath: vi.fn(), | |
| 12 | + getSessionId: vi.fn(), | |
| 13 | + }, | |
| 14 | +})); | |
| 15 | + | |
| 16 | +import { messageQueue } from "./messageQueue.js"; | |
| 17 | + | |
| 18 | +describe("messageQueue", () => { | |
| 19 | + beforeEach(() => { | |
| 20 | + // Drain any leftover items from previous tests | |
| 21 | + while (messageQueue.getAllQueuedMessages()) {} | |
| 22 | + }); | |
| 23 | + | |
| 24 | + it("enqueues and emits messageQueued", async () => { | |
| 25 | + const event = new Promise<any>((resolve) => | |
| 26 | + messageQueue.once("messageQueued", resolve), | |
| 27 | + ); | |
| 28 | + | |
| 29 | + const ok = await messageQueue.enqueueMessage("hello world"); | |
| 30 | + expect(ok).toBe(true); | |
| 31 | + expect(messageQueue.getQueueLength()).toBe(1); | |
| 32 | + | |
| 33 | + const queued = await event; | |
| 34 | + expect(queued.message).toBe("hello world"); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + it("combines messages, merges image maps, writes history, and clears queue", async () => { | |
| 38 | + const bufA = Buffer.from("A"); | |
| 39 | + const bufB = Buffer.from("B"); | |
| 40 | + | |
| 41 | + const img1 = new Map<string, Buffer>([["a", bufA]]); | |
| 42 | + const img2 = new Map<string, Buffer>([["b", bufB]]); | |
| 43 | + | |
| 44 | + const history = { addEntry: vi.fn() } as any; | |
| 45 | + | |
| 46 | + await messageQueue.enqueueMessage("one", img1); | |
| 47 | + await messageQueue.enqueueMessage("two", img2, history); | |
| 48 | + | |
| 49 | + const combined = messageQueue.getAllQueuedMessages(); | |
| 50 | + expect(combined).toBeTruthy(); | |
| 51 | + expect(combined!.message).toBe("one\ntwo"); | |
| 52 | + expect(combined!.imageMap).toBeDefined(); | |
| 53 | + expect(combined!.imageMap!.get("a")).toEqual(bufA); | |
| 54 | + expect(combined!.imageMap!.get("b")).toEqual(bufB); | |
| 55 | + | |
| 56 | + // queue should be cleared | |
| 57 | + expect(messageQueue.getQueueLength()).toBe(0); | |
| 58 | + | |
| 59 | + // input history should receive the combined message | |
| 60 | + expect(history.addEntry).toHaveBeenCalledWith("one\ntwo"); | |
| 61 | + }); | |
| 62 | +}); |
| @@ -0,0 +1,94 @@ | ||
| 1 | +import { EventEmitter } from "events"; | |
| 2 | + | |
| 3 | +import { InputHistory } from "../util/inputHistory.js"; | |
| 4 | +import { logger } from "../util/logger.js"; | |
| 5 | + | |
| 6 | +export interface QueuedMessage { | |
| 7 | + message: string; | |
| 8 | + imageMap?: Map<string, Buffer>; | |
| 9 | + timestamp: number; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export interface MessageProcessor { | |
| 13 | + (message: string, imageMap?: Map<string, Buffer>): Promise<void>; | |
| 14 | +} | |
| 15 | + | |
| 16 | +/** | |
| 17 | + * A queue to store messages that need to be processed later | |
| 18 | + */ | |
| 19 | +class MessageQueue extends EventEmitter { | |
| 20 | + private queue: QueuedMessage[] = []; | |
| 21 | + private inputHistory: InputHistory | undefined; | |
| 22 | + | |
| 23 | + constructor() { | |
| 24 | + super(); | |
| 25 | + } | |
| 26 | + | |
| 27 | + async enqueueMessage( | |
| 28 | + message: string, | |
| 29 | + imageMap?: Map<string, Buffer>, | |
| 30 | + inputHistory?: InputHistory, | |
| 31 | + ): Promise<boolean> { | |
| 32 | + this.inputHistory = inputHistory; | |
| 33 | + | |
| 34 | + const queuedMessage: QueuedMessage = { | |
| 35 | + message, | |
| 36 | + imageMap, | |
| 37 | + timestamp: Date.now(), | |
| 38 | + }; | |
| 39 | + | |
| 40 | + this.queue.push(queuedMessage); | |
| 41 | + logger.debug("MessageQueue: Message queued", { | |
| 42 | + queueLength: this.queue.length, | |
| 43 | + }); | |
| 44 | + | |
| 45 | + // Emit event for UI to show the queued message | |
| 46 | + this.emit("messageQueued", queuedMessage); | |
| 47 | + | |
| 48 | + return true; | |
| 49 | + } | |
| 50 | + | |
| 51 | + public getAllQueuedMessages() { | |
| 52 | + if (this.queue.length === 0) return undefined; | |
| 53 | + | |
| 54 | + // Combine all queued messages into one | |
| 55 | + const combinedMessage = this.queue.map((msg) => msg.message).join("\n"); | |
| 56 | + const combinedImageMap = new Map<string, Buffer>(); | |
| 57 | + | |
| 58 | + // Merge all image maps | |
| 59 | + for (const queuedMsg of this.queue) { | |
| 60 | + if (queuedMsg.imageMap) { | |
| 61 | + for (const [key, value] of queuedMsg.imageMap) { | |
| 62 | + combinedImageMap.set(key, value); | |
| 63 | + } | |
| 64 | + } | |
| 65 | + } | |
| 66 | + | |
| 67 | + const result = { | |
| 68 | + message: combinedMessage, | |
| 69 | + imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined, | |
| 70 | + timestamp: Date.now(), | |
| 71 | + }; | |
| 72 | + | |
| 73 | + // Add to input history and clear the queue | |
| 74 | + this.inputHistory?.addEntry(combinedMessage); | |
| 75 | + this.queue = []; | |
| 76 | + | |
| 77 | + logger.debug("MessageQueue: All messages dequeued and combined", { | |
| 78 | + combinedLength: combinedMessage.length, | |
| 79 | + queueLength: this.queue.length, | |
| 80 | + }); | |
| 81 | + | |
| 82 | + return result; | |
| 83 | + } | |
| 84 | + | |
| 85 | + public getLatestMessage() { | |
| 86 | + return this.getAllQueuedMessages(); | |
| 87 | + } | |
| 88 | + | |
| 89 | + getQueueLength(): number { | |
| 90 | + return this.queue.length; | |
| 91 | + } | |
| 92 | +} | |
| 93 | + | |
| 94 | +export const messageQueue = new MessageQueue(); |
| @@ -147,7 +147,7 @@ | ||
| 147 | 147 | "Auto-compacting...", |
| 148 | 148 | ); |
| 149 | 149 | expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( |
| 150 | - "✓ Chat history auto-compacted successfully.", | |
| 150 | + "Chat history auto-compacted successfully.", | |
| 151 | 151 | ); |
| 152 | 152 | |
| 153 | 153 | expect(result).toEqual({ |
| @@ -55,7 +55,7 @@ | ||
| 55 | 55 | ) { |
| 56 | 56 | if (isHeadless) return; |
| 57 | 57 | |
| 58 | - const successMessage = "✓ Chat history auto-compacted successfully."; | |
| 58 | + const successMessage = "Chat history auto-compacted successfully."; | |
| 59 | 59 | |
| 60 | 60 | if (callbacks?.onSystemMessage) { |
| 61 | 61 | callbacks.onSystemMessage(successMessage); |
| @@ -1,10 +1,13 @@ | ||
| 1 | 1 | // Helper functions extracted from streamChatResponse.ts to reduce file size |
| 2 | 2 | |
| 3 | +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; | |
| 3 | 4 | import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; |
| 4 | 5 | |
| 5 | 6 | import { checkToolPermission } from "../permissions/permissionChecker.js"; |
| 6 | 7 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 7 | 8 | import { ToolCallRequest } from "../permissions/types.js"; |
| 9 | +import { services } from "../services/index.js"; | |
| 10 | +import { posthogService } from "../telemetry/posthogService.js"; | |
| 8 | 11 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 9 | 12 | import { calculateTokenCost } from "../telemetry/utils.js"; |
| 10 | 13 | import { |
| @@ -24,11 +27,17 @@ | ||
| 24 | 27 | toolCall: PreprocessedToolCall, |
| 25 | 28 | chatHistoryEntries: ChatCompletionToolMessageParam[], |
| 26 | 29 | callbacks?: StreamCallbacks, |
| 30 | + reason: "user" | "policy" = "user", | |
| 27 | 31 | ): void { |
| 28 | - const deniedMessage = `Permission denied by user`; | |
| 32 | + const deniedMessage = | |
| 33 | + reason === "policy" | |
| 34 | + ? `Command blocked by security policy` | |
| 35 | + : `Permission denied by user`; | |
| 36 | + | |
| 29 | 37 | logger.info("Tool call denied", { |
| 30 | 38 | name: toolCall.name, |
| 31 | 39 | arguments: toolCall.arguments, |
| 40 | + reason, | |
| 32 | 41 | }); |
| 33 | 42 | |
| 34 | 43 | chatHistoryEntries.push({ |
| @@ -38,7 +47,7 @@ | ||
| 38 | 47 | }); |
| 39 | 48 | |
| 40 | 49 | callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled"); |
| 41 | - logger.debug("Tool call rejected - stopping stream"); | |
| 50 | + logger.debug(`Tool call rejected (${reason}) - stopping stream`); | |
| 42 | 51 | } |
| 43 | 52 | |
| 44 | 53 | // Helper function to handle headless mode permission |
| @@ -57,7 +66,11 @@ | ||
| 57 | 66 | `If you don't want the tool to be included, use --exclude ${toolName}.`, |
| 58 | 67 | ); |
| 59 | 68 | |
| 60 | - process.exit(1); | |
| 69 | + // Use graceful exit to flush telemetry even in headless denial | |
| 70 | + // Note: We purposely trigger an async exit without awaiting in this sync path | |
| 71 | + import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1)); | |
| 72 | + // Throw to satisfy the never return type; process will exit shortly | |
| 73 | + throw new Error("Exiting due to headless permission requirement"); | |
| 61 | 74 | } |
| 62 | 75 | |
| 63 | 76 | // Helper function to request user permission |
| @@ -113,22 +126,25 @@ | ||
| 113 | 126 | toolCall: PreprocessedToolCall, |
| 114 | 127 | callbacks?: StreamCallbacks, |
| 115 | 128 | isHeadless?: boolean, |
| 116 | -): Promise<boolean> { | |
| 129 | +): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> { | |
| 117 | 130 | const permissionCheck = checkToolPermission(toolCall); |
| 118 | 131 | |
| 119 | 132 | if (permissionCheck.permission === "allow") { |
| 120 | - return true; | |
| 133 | + return { approved: true }; | |
| 121 | 134 | } else if (permissionCheck.permission === "ask") { |
| 122 | 135 | if (isHeadless) { |
| 123 | 136 | handleHeadlessPermission(toolCall); |
| 124 | 137 | } |
| 125 | - return await requestUserPermission(toolCall, callbacks); | |
| 138 | + const userApproved = await requestUserPermission(toolCall, callbacks); | |
| 139 | + return userApproved | |
| 140 | + ? { approved: true } | |
| 141 | + : { approved: false, denialReason: "user" }; | |
| 126 | 142 | } else if (permissionCheck.permission === "exclude") { |
| 127 | - // This shouldn't happen as excluded tools are filtered out earlier | |
| 128 | - return false; | |
| 143 | + // Tool blocked by security policy | |
| 144 | + return { approved: false, denialReason: "policy" }; | |
| 129 | 145 | } |
| 130 | 146 | |
| 131 | - return false; | |
| 147 | + return { approved: false, denialReason: "policy" }; | |
| 132 | 148 | } |
| 133 | 149 | |
| 134 | 150 | // Helper function to track first token time |
| @@ -276,6 +292,17 @@ | ||
| 276 | 292 | costUsd: cost, |
| 277 | 293 | }); |
| 278 | 294 | |
| 295 | + // Mirror core metrics to PostHog for product analytics | |
| 296 | + try { | |
| 297 | + posthogService.capture("apiRequest", { | |
| 298 | + model: model.model, | |
| 299 | + durationMs: totalDuration, | |
| 300 | + inputTokens, | |
| 301 | + outputTokens, | |
| 302 | + costUsd: cost, | |
| 303 | + }); | |
| 304 | + } catch {} | |
| 305 | + | |
| 279 | 306 | return cost; |
| 280 | 307 | } |
| 281 | 308 | |
| @@ -328,6 +355,11 @@ | ||
| 328 | 355 | // Notify the UI about the tool start, even though it failed |
| 329 | 356 | callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); |
| 330 | 357 | |
| 358 | + const errorReason = | |
| 359 | + error instanceof ContinueError | |
| 360 | + ? error.reason | |
| 361 | + : ContinueErrorReason.Unknown; | |
| 362 | + | |
| 331 | 363 | const errorMessage = |
| 332 | 364 | error instanceof Error ? error.message : String(error); |
| 333 | 365 | |
| @@ -342,6 +374,15 @@ | ||
| 342 | 374 | success: false, |
| 343 | 375 | durationMs: duration, |
| 344 | 376 | error: errorMessage, |
| 377 | + errorReason, | |
| 378 | + // modelName, TODO | |
| 379 | + }); | |
| 380 | + void posthogService.capture("tool_call_outcome", { | |
| 381 | + succeeded: false, | |
| 382 | + toolName: toolCall.name, | |
| 383 | + errorReason, | |
| 384 | + duration_ms: duration, | |
| 385 | + // model: options.modelName, TODO | |
| 345 | 386 | }); |
| 346 | 387 | |
| 347 | 388 | // Add error to chat history |
| @@ -373,81 +414,158 @@ | ||
| 373 | 414 | hasRejection: boolean; |
| 374 | 415 | chatHistoryEntries: ChatCompletionToolMessageParam[]; |
| 375 | 416 | }> { |
| 376 | - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; | |
| 377 | - let hasRejection = false; | |
| 417 | + // Strategy: queue permissions (preserve order), then run approved tools in parallel. | |
| 418 | + // If any permission is rejected, cancel the remaining tools in this batch. | |
| 378 | 419 | |
| 379 | - // Execute each preprocessed tool call | |
| 380 | - for (const toolCall of preprocessedCalls) { | |
| 381 | - if (hasRejection) { | |
| 382 | - const cancelledMessage = `Cancelled due to previous tool rejection`; | |
| 383 | - chatHistoryEntries.push({ | |
| 384 | - role: "tool", | |
| 385 | - tool_call_id: toolCall.id, | |
| 386 | - content: cancelledMessage, | |
| 387 | - }); | |
| 420 | + type IndexedCall = { index: number; call: PreprocessedToolCall }; | |
| 421 | + const indexedCalls: IndexedCall[] = preprocessedCalls.map((call, index) => ({ | |
| 422 | + index, | |
| 423 | + call, | |
| 424 | + })); | |
| 388 | 425 | |
| 389 | - callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); | |
| 390 | - continue; | |
| 391 | - } | |
| 426 | + const entriesByIndex = new Map<number, ChatCompletionToolMessageParam>(); | |
| 427 | + const execPromises: Promise<void>[] = []; | |
| 428 | + | |
| 429 | + let hasRejection = false; | |
| 430 | + | |
| 431 | + // Permission phase (sequential) | |
| 432 | + for (const { index, call } of indexedCalls) { | |
| 433 | + // Do not cancel subsequent tools after a rejection; handle each independently | |
| 392 | 434 | |
| 393 | - // Handle remaining tool calls in this batch to maintain chat history consistency | |
| 394 | 435 | try { |
| 395 | 436 | logger.debug("Checking tool permissions", { |
| 396 | - name: toolCall.name, | |
| 397 | - arguments: toolCall.arguments, | |
| 437 | + name: call.name, | |
| 438 | + arguments: call.arguments, | |
| 398 | 439 | }); |
| 399 | 440 | |
| 400 | - // Notify tool start - before permission check | |
| 401 | - // This ensures the UI shows the tool call even if it's rejected | |
| 402 | - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 441 | + // Notify tool start before permission check to display in UI fallbacks | |
| 442 | + callbacks?.onToolStart?.(call.name, call.arguments); | |
| 403 | 443 | |
| 404 | 444 | // Check tool permissions using helper |
| 405 | - const approved = await checkToolPermissionApproval( | |
| 406 | - toolCall, | |
| 445 | + const permissionResult = await checkToolPermissionApproval( | |
| 446 | + call, | |
| 407 | 447 | callbacks, |
| 408 | 448 | isHeadless, |
| 409 | 449 | ); |
| 410 | 450 | |
| 411 | - if (!approved) { | |
| 412 | - handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); | |
| 451 | + if (!permissionResult.approved) { | |
| 452 | + // Permission denied: record and mark rejection | |
| 453 | + const denialReason = permissionResult.denialReason || "user"; | |
| 454 | + const deniedMessage = | |
| 455 | + denialReason === "policy" | |
| 456 | + ? `Command blocked by security policy` | |
| 457 | + : `Permission denied by user`; | |
| 458 | + | |
| 459 | + const deniedEntry: ChatCompletionToolMessageParam = { | |
| 460 | + role: "tool", | |
| 461 | + tool_call_id: call.id, | |
| 462 | + content: deniedMessage, | |
| 463 | + }; | |
| 464 | + entriesByIndex.set(index, deniedEntry); | |
| 465 | + callbacks?.onToolResult?.( | |
| 466 | + String(deniedEntry.content), | |
| 467 | + call.name, | |
| 468 | + "canceled", | |
| 469 | + ); | |
| 470 | + // Immediate service update for UI feedback | |
| 471 | + try { | |
| 472 | + services.chatHistory.addToolResult( | |
| 473 | + call.id, | |
| 474 | + String(deniedEntry.content), | |
| 475 | + "canceled", | |
| 476 | + ); | |
| 477 | + } catch {} | |
| 413 | 478 | hasRejection = true; |
| 479 | + // Remaining items will be auto-cancelled in subsequent iterations | |
| 414 | 480 | continue; |
| 415 | 481 | } |
| 416 | 482 | |
| 417 | - logger.debug("Executing tool", { | |
| 418 | - name: toolCall.name, | |
| 419 | - arguments: toolCall.arguments, | |
| 420 | - }); | |
| 421 | - | |
| 422 | - const toolResult = await executeToolCall(toolCall); | |
| 423 | - | |
| 424 | - chatHistoryEntries.push({ | |
| 425 | - role: "tool", | |
| 426 | - tool_call_id: toolCall.id, | |
| 427 | - content: toolResult, | |
| 428 | - }); | |
| 429 | - | |
| 430 | - callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); | |
| 483 | + // Immediately mark as calling for instant UI feedback | |
| 484 | + try { | |
| 485 | + services.chatHistory.updateToolStatus(call.id, "calling"); | |
| 486 | + } catch {} | |
| 487 | + | |
| 488 | + // Start execution immediately for approved calls | |
| 489 | + execPromises.push( | |
| 490 | + (async () => { | |
| 491 | + try { | |
| 492 | + logger.debug("Executing tool", { | |
| 493 | + name: call.name, | |
| 494 | + arguments: call.arguments, | |
| 495 | + }); | |
| 496 | + const toolResult = await executeToolCall(call); | |
| 497 | + const entry: ChatCompletionToolMessageParam = { | |
| 498 | + role: "tool", | |
| 499 | + tool_call_id: call.id, | |
| 500 | + content: toolResult, | |
| 501 | + }; | |
| 502 | + entriesByIndex.set(index, entry); | |
| 503 | + callbacks?.onToolResult?.(toolResult, call.name, "done"); | |
| 504 | + // Immediate service update for UI feedback | |
| 505 | + try { | |
| 506 | + services.chatHistory.addToolResult( | |
| 507 | + call.id, | |
| 508 | + String(toolResult), | |
| 509 | + "done", | |
| 510 | + ); | |
| 511 | + } catch {} | |
| 512 | + } catch (error) { | |
| 513 | + const errorMessage = `Error executing tool ${call.name}: ${ | |
| 514 | + error instanceof Error ? error.message : String(error) | |
| 515 | + }`; | |
| 516 | + logger.error("Tool execution failed", { | |
| 517 | + name: call.name, | |
| 518 | + error: errorMessage, | |
| 519 | + }); | |
| 520 | + entriesByIndex.set(index, { | |
| 521 | + role: "tool", | |
| 522 | + tool_call_id: call.id, | |
| 523 | + content: errorMessage, | |
| 524 | + }); | |
| 525 | + callbacks?.onToolError?.(errorMessage, call.name); | |
| 526 | + // Immediate service update for UI feedback | |
| 527 | + try { | |
| 528 | + services.chatHistory.addToolResult( | |
| 529 | + call.id, | |
| 530 | + errorMessage as string, | |
| 531 | + "errored", | |
| 532 | + ); | |
| 533 | + } catch {} | |
| 534 | + } | |
| 535 | + })(), | |
| 536 | + ); | |
| 431 | 537 | } catch (error) { |
| 432 | - const errorMessage = `Error executing tool ${toolCall.name}: ${ | |
| 538 | + const errorMessage = `Error checking permissions for ${call.name}: ${ | |
| 433 | 539 | error instanceof Error ? error.message : String(error) |
| 434 | 540 | }`; |
| 435 | - | |
| 436 | - logger.error("Tool execution failed", { | |
| 437 | - name: toolCall.name, | |
| 541 | + logger.error("Permission check failed", { | |
| 542 | + name: call.name, | |
| 438 | 543 | error: errorMessage, |
| 439 | 544 | }); |
| 440 | - | |
| 441 | - chatHistoryEntries.push({ | |
| 545 | + entriesByIndex.set(index, { | |
| 442 | 546 | role: "tool", |
| 443 | - tool_call_id: toolCall.id, | |
| 547 | + tool_call_id: call.id, | |
| 444 | 548 | content: errorMessage, |
| 445 | 549 | }); |
| 446 | - | |
| 447 | - callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 550 | + callbacks?.onToolError?.(errorMessage, call.name); | |
| 551 | + // Treat permission errors like execution errors but do not stop the batch | |
| 552 | + try { | |
| 553 | + services.chatHistory.addToolResult( | |
| 554 | + call.id, | |
| 555 | + errorMessage as string, | |
| 556 | + "errored", | |
| 557 | + ); | |
| 558 | + } catch {} | |
| 448 | 559 | } |
| 449 | 560 | } |
| 450 | 561 | |
| 562 | + await Promise.all(execPromises); | |
| 563 | + | |
| 564 | + // Assemble final entries in original order | |
| 565 | + const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls | |
| 566 | + .map((_, index) => entriesByIndex.get(index)) | |
| 567 | + .filter((e): e is ChatCompletionToolMessageParam => !!e); | |
| 568 | + | |
| 451 | 569 | return { |
| 452 | 570 | hasRejection, |
| 453 | 571 | chatHistoryEntries, |