Changesets · Branches · Tags · Compare
| Changeset | 75f22779f30e45abd456560e2b21a1d3d6d2c4cc79da8454eb41337336c38cc8 |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-08-23 11:14 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-08-23 11:14 -07:00 |
| Parents | 88b8936f200c, 5d5cc08efab1 |
137 files changed
modified .github/actions/run-jetbrains-tests/action.yml +18 −2
| @@ -44,6 +44,7 @@ | ||
| 44 | 44 | - name: Setup FFmpeg |
| 45 | 45 | uses: AnimMouse/setup-ffmpeg@v1 |
| 46 | 46 | with: |
| 47 | + version: 7.1 | |
| 47 | 48 | token: ${{ inputs.github-token }} |
| 48 | 49 | |
| 49 | 50 | - name: Setup Gradle |
| @@ -93,6 +94,13 @@ | ||
| 93 | 94 | path: binary/node_modules |
| 94 | 95 | key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} |
| 95 | 96 | |
| 97 | + - name: Install binary dependencies | |
| 98 | + if: steps.binary-cache.outputs.cache-hit != 'true' | |
| 99 | + shell: bash | |
| 100 | + run: | | |
| 101 | + cd binary | |
| 102 | + npm ci | |
| 103 | + | |
| 96 | 104 | - name: Build the binaries |
| 97 | 105 | shell: bash |
| 98 | 106 | run: | |
| @@ -128,14 +136,22 @@ | ||
| 128 | 136 | shell: bash |
| 129 | 137 | run: | |
| 130 | 138 | cd extensions/intellij |
| 131 | - mv video build/reports | |
| 139 | + if [ -d "video" ]; then | |
| 140 | + mv video build/reports | |
| 141 | + else | |
| 142 | + echo "No video directory found to move" | |
| 143 | + fi | |
| 132 | 144 | |
| 133 | 145 | - name: Copy logs |
| 134 | 146 | if: ${{ failure() }} |
| 135 | 147 | shell: bash |
| 136 | 148 | run: | |
| 137 | 149 | cd extensions/intellij |
| 138 | - mv build/idea-sandbox/system/log/ build/reports | |
| 150 | + if [ -d "build/idea-sandbox/system/log/" ]; then | |
| 151 | + mv build/idea-sandbox/system/log/ build/reports | |
| 152 | + else | |
| 153 | + echo "No log directory found to copy" | |
| 154 | + fi | |
| 139 | 155 | |
| 140 | 156 | - name: Save fails report |
| 141 | 157 | if: ${{ failure() }} |
added .github/actions/track-rerun/action.yml +19 −0
| @@ -0,0 +1,19 @@ | ||
| 1 | +name: Track Workflow Rerun | |
| 2 | +description: Track when GitHub Actions workflows are rerun (attempt > 1) | |
| 3 | + | |
| 4 | +runs: | |
| 5 | + using: composite | |
| 6 | + steps: | |
| 7 | + # Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.) | |
| 8 | + - name: Track workflow rerun | |
| 9 | + if: github.run_attempt > 1 | |
| 10 | + shell: bash | |
| 11 | + run: | | |
| 12 | + echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}" | |
| 13 | + echo "📊 Workflow: ${{ github.workflow }}" | |
| 14 | + echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}" | |
| 15 | + echo "📝 Commit: ${{ github.sha }}" | |
| 16 | + echo "👤 Actor: ${{ github.actor }}" | |
| 17 | + echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 18 | + echo "" | |
| 19 | + echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'" |
modified .github/workflows/beta-release.yml +12 −3
| @@ -18,19 +18,28 @@ | ||
| 18 | 18 | runs-on: ubuntu-latest |
| 19 | 19 | steps: |
| 20 | 20 | - name: Checkout |
| 21 | - uses: actions/checkout@v4 | |
| 21 | + uses: actions/checkout@v5 | |
| 22 | 22 | with: |
| 23 | 23 | fetch-depth: 0 |
| 24 | 24 | token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} |
| 25 | 25 | |
| 26 | 26 | - name: Setup Node.js |
| 27 | - uses: actions/setup-node@v3 | |
| 27 | + uses: actions/setup-node@v4 | |
| 28 | 28 | with: |
| 29 | 29 | node-version: 20 |
| 30 | 30 | registry-url: "https://registry.npmjs.org" |
| 31 | 31 | always-auth: true |
| 32 | 32 | |
| 33 | - - name: Install dependencies | |
| 33 | + - name: Setup packages | |
| 34 | + uses: ./.github/actions/setup-packages | |
| 35 | + | |
| 36 | + - name: Setup core component | |
| 37 | + uses: ./.github/actions/setup-component | |
| 38 | + with: | |
| 39 | + component: core | |
| 40 | + include-root: true | |
| 41 | + | |
| 42 | + - name: Install CLI dependencies | |
| 34 | 43 | working-directory: extensions/cli |
| 35 | 44 | run: npm ci |
| 36 | 45 | env: |
modified .github/workflows/cli-pr-checks.yml +41 −6
| @@ -10,11 +10,19 @@ | ||
| 10 | 10 | issues: write |
| 11 | 11 | |
| 12 | 12 | jobs: |
| 13 | + track-rerun: | |
| 14 | + runs-on: ubuntu-latest | |
| 15 | + if: github.run_attempt > 1 | |
| 16 | + steps: | |
| 17 | + - uses: actions/checkout@v4 | |
| 18 | + - name: Track workflow rerun | |
| 19 | + uses: ./.github/actions/track-rerun | |
| 20 | + | |
| 13 | 21 | lint: |
| 14 | 22 | runs-on: ubuntu-latest |
| 15 | 23 | steps: |
| 16 | 24 | - name: Checkout code |
| 17 | - uses: actions/checkout@v4 | |
| 25 | + uses: actions/checkout@v5 | |
| 18 | 26 | |
| 19 | 27 | - name: Setup Node.js |
| 20 | 28 | uses: actions/setup-node@v4 |
| @@ -23,10 +31,18 @@ | ||
| 23 | 31 | cache: "npm" |
| 24 | 32 | cache-dependency-path: extensions/cli/package-lock.json |
| 25 | 33 | |
| 34 | + - name: Setup packages | |
| 35 | + uses: ./.github/actions/setup-packages | |
| 36 | + - name: Setup core component | |
| 37 | + uses: ./.github/actions/setup-component | |
| 38 | + with: | |
| 39 | + component: core | |
| 40 | + include-root: true | |
| 41 | + | |
| 26 | 42 | - name: Install dependencies |
| 27 | 43 | run: | |
| 28 | 44 | cd extensions/cli |
| 29 | - npm ci | |
| 45 | + npm ci --include=optional | |
| 30 | 46 | |
| 31 | 47 | - name: Run linting |
| 32 | 48 | run: | |
| @@ -42,25 +58,44 @@ | ||
| 42 | 58 | |
| 43 | 59 | steps: |
| 44 | 60 | - name: Checkout code |
| 45 | - uses: actions/checkout@v4 | |
| 61 | + uses: actions/checkout@v5 | |
| 46 | 62 | |
| 47 | 63 | - name: Setup Node.js ${{ matrix.node-version }} |
| 48 | 64 | uses: actions/setup-node@v4 |
| 49 | 65 | with: |
| 50 | 66 | node-version: ${{ matrix.node-version }} |
| 51 | - cache: "npm" | |
| 52 | - cache-dependency-path: extensions/cli/package-lock.json | |
| 67 | + | |
| 68 | + - name: Cache CLI node_modules | |
| 69 | + uses: actions/cache@v4 | |
| 70 | + with: | |
| 71 | + path: extensions/cli/node_modules | |
| 72 | + key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }} | |
| 73 | + restore-keys: | | |
| 74 | + ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules- | |
| 75 | + | |
| 76 | + - name: Setup packages | |
| 77 | + uses: ./.github/actions/setup-packages | |
| 78 | + - name: Setup core component | |
| 79 | + uses: ./.github/actions/setup-component | |
| 80 | + with: | |
| 81 | + component: core | |
| 82 | + include-root: true | |
| 53 | 83 | |
| 54 | 84 | - name: Install dependencies |
| 55 | 85 | run: | |
| 56 | 86 | cd extensions/cli |
| 57 | - npm ci | |
| 87 | + npm ci --include=optional | |
| 58 | 88 | |
| 59 | 89 | - name: Build |
| 60 | 90 | run: | |
| 61 | 91 | cd extensions/cli |
| 62 | 92 | npm run build |
| 63 | 93 | |
| 94 | + - name: Run smoke tests | |
| 95 | + run: | | |
| 96 | + cd extensions/cli | |
| 97 | + npm run test:smoke | |
| 98 | + | |
| 64 | 99 | # e2e tests are failing on Windows specifically - likely due to stdout flush issues |
| 65 | 100 | - name: Run tests |
| 66 | 101 | if: matrix.os != 'windows-latest' |
deleted .github/workflows/docs.yml +0 −32
| @@ -1,32 +0,0 @@ | ||
| 1 | -name: Docs Check | |
| 2 | - | |
| 3 | -on: | |
| 4 | - push: | |
| 5 | - paths: | |
| 6 | - - 'docs2/**' | |
| 7 | - pull_request: | |
| 8 | - paths: | |
| 9 | - - 'docs2/**' | |
| 10 | - | |
| 11 | -jobs: | |
| 12 | - check-broken-links: | |
| 13 | - runs-on: ubuntu-latest | |
| 14 | - | |
| 15 | - steps: | |
| 16 | - - name: Checkout repository | |
| 17 | - uses: actions/checkout@v5 | |
| 18 | - | |
| 19 | - - name: Setup Node.js | |
| 20 | - uses: actions/setup-node@v4 | |
| 21 | - with: | |
| 22 | - node-version: '18' | |
| 23 | - cache: 'npm' | |
| 24 | - cache-dependency-path: docs2/package-lock.json | |
| 25 | - | |
| 26 | - - name: Install dependencies | |
| 27 | - working-directory: ./docs2 | |
| 28 | - run: npm ci | |
| 29 | - | |
| 30 | - - name: Check for broken links | |
| 31 | - working-directory: ./docs2 | |
| 32 | - run: npx mintlify broken-links | |
| No newline at the end of the file |
modified .github/workflows/jetbrains-release.yaml +6 −4
| @@ -120,7 +120,7 @@ | ||
| 120 | 120 | |
| 121 | 121 | # # Set up Java environment for the next steps |
| 122 | 122 | - name: Setup Java |
| 123 | - uses: actions/setup-java@v4 | |
| 123 | + uses: actions/setup-java@v5 | |
| 124 | 124 | with: |
| 125 | 125 | distribution: zulu |
| 126 | 126 | java-version: 17 |
| @@ -189,6 +189,8 @@ | ||
| 189 | 189 | cd ../../gui |
| 190 | 190 | npm ci |
| 191 | 191 | npm run build |
| 192 | + env: | |
| 193 | + NODE_OPTIONS: "--max-old-space-size=8192" | |
| 192 | 194 | |
| 193 | 195 | # Run prepackage.js script |
| 194 | 196 | - name: Run prepackage script |
| @@ -433,7 +435,7 @@ | ||
| 433 | 435 | |
| 434 | 436 | # Set up Java environment for the next steps |
| 435 | 437 | - name: Setup Java |
| 436 | - uses: actions/setup-java@v4 | |
| 438 | + uses: actions/setup-java@v5 | |
| 437 | 439 | with: |
| 438 | 440 | distribution: zulu |
| 439 | 441 | java-version: 17 |
| @@ -486,7 +488,7 @@ | ||
| 486 | 488 | |
| 487 | 489 | # Set up Java environment for the next steps |
| 488 | 490 | - name: Setup Java |
| 489 | - uses: actions/setup-java@v4 | |
| 491 | + uses: actions/setup-java@v5 | |
| 490 | 492 | with: |
| 491 | 493 | distribution: zulu |
| 492 | 494 | java-version: 17 |
| @@ -517,7 +519,7 @@ | ||
| 517 | 519 | |
| 518 | 520 | # Set up Java environment for the next steps |
| 519 | 521 | - name: Setup Java |
| 520 | - uses: actions/setup-java@v4 | |
| 522 | + uses: actions/setup-java@v5 | |
| 521 | 523 | with: |
| 522 | 524 | distribution: zulu |
| 523 | 525 | java-version: 17 |
modified .github/workflows/main.yaml +1 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | publish_build: |
| 10 | 10 | description: "Whether or not to publish the built extension to the VS Code marketplace" |
| 11 | 11 | required: true |
| 12 | - default: false | |
| 12 | + default: "false" | |
| 13 | 13 | |
| 14 | 14 | jobs: |
| 15 | 15 | check_release_name: |
modified .github/workflows/pr-checks.yaml +8 −0
| @@ -11,6 +11,14 @@ | ||
| 11 | 11 | - main |
| 12 | 12 | |
| 13 | 13 | jobs: |
| 14 | + track-rerun: | |
| 15 | + runs-on: ubuntu-latest | |
| 16 | + if: github.run_attempt > 1 | |
| 17 | + steps: | |
| 18 | + - uses: actions/checkout@v5 | |
| 19 | + - name: Track workflow rerun | |
| 20 | + uses: ./.github/actions/track-rerun | |
| 21 | + | |
| 14 | 22 | prettier-check: |
| 15 | 23 | runs-on: ubuntu-latest |
| 16 | 24 | steps: |
modified .github/workflows/preview.yaml +2 −2
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | publish_build: |
| 10 | 10 | description: "Whether or not to publish the built extension to the VS Code marketplace" |
| 11 | 11 | required: true |
| 12 | - default: false | |
| 12 | + default: "false" | |
| 13 | 13 | |
| 14 | 14 | jobs: |
| 15 | 15 | check_release_name: |
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | - id: check |
| 21 | 21 | working-directory: . |
| 22 | 22 | run: | |
| 23 | - if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then | |
| 23 | + if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then | |
| 24 | 24 | echo "should_run=true" >> $GITHUB_OUTPUT |
| 25 | 25 | else |
| 26 | 26 | echo "should_run=false" >> $GITHUB_OUTPUT |
modified .github/workflows/stable-release.yml +13 −2
| @@ -34,13 +34,13 @@ | ||
| 34 | 34 | runs-on: ubuntu-latest |
| 35 | 35 | steps: |
| 36 | 36 | - name: Checkout |
| 37 | - uses: actions/checkout@v4 | |
| 37 | + uses: actions/checkout@v5 | |
| 38 | 38 | with: |
| 39 | 39 | fetch-depth: 0 |
| 40 | 40 | token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} |
| 41 | 41 | |
| 42 | 42 | - name: Setup Node.js |
| 43 | - uses: actions/setup-node@v3 | |
| 43 | + uses: actions/setup-node@v4 | |
| 44 | 44 | with: |
| 45 | 45 | node-version: 20 |
| 46 | 46 | registry-url: "https://registry.npmjs.org" |
| @@ -141,6 +141,17 @@ | ||
| 141 | 141 | # Update version to stable (remove beta suffix) |
| 142 | 142 | npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version |
| 143 | 143 | |
| 144 | + - name: Setup packages (for direct stable release) | |
| 145 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 146 | + uses: ./.github/actions/setup-packages | |
| 147 | + | |
| 148 | + - name: Setup core component (for direct stable release) | |
| 149 | + if: ${{ inputs.release_type == 'direct-stable' }} | |
| 150 | + uses: ./.github/actions/setup-component | |
| 151 | + with: | |
| 152 | + component: core | |
| 153 | + include-root: true | |
| 154 | + | |
| 144 | 155 | - name: Prepare package for direct stable release |
| 145 | 156 | if: ${{ inputs.release_type == 'direct-stable' }} |
| 146 | 157 | working-directory: extensions/cli |
modified .github/workflows/submit-github-dependency-graph.yml +1 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | - name: Checkout sources |
| 15 | 15 | uses: actions/checkout@v5 |
| 16 | 16 | - name: Setup Java |
| 17 | - uses: actions/setup-java@v4 | |
| 17 | + uses: actions/setup-java@v5 | |
| 18 | 18 | with: |
| 19 | 19 | distribution: "temurin" |
| 20 | 20 | java-version: 17 |
modified .vscode/settings.json +2 −1
| @@ -42,7 +42,8 @@ | ||
| 42 | 42 | "extensions/vscode/e2e/_output": true, |
| 43 | 43 | "extensions/vscode/e2e/storage": true, |
| 44 | 44 | "extensions/vscode/e2e/vsix": true, |
| 45 | - "extensions/.continue-debug": true | |
| 45 | + "extensions/.continue-debug": true, | |
| 46 | + "extensions/cli/dist/**": true | |
| 46 | 47 | // "sync/**": true |
| 47 | 48 | }, |
| 48 | 49 | "editor.formatOnSave": true, |
modified binary/package-lock.json +12 −6
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | "pkg": "^5.8.1", |
| 41 | 41 | "rimraf": "^5.0.7", |
| 42 | 42 | "ts-jest": "^29.1.4", |
| 43 | - "typescript": "^5.3.3" | |
| 43 | + "typescript": "^5.6.3" | |
| 44 | 44 | } |
| 45 | 45 | }, |
| 46 | 46 | "../core": { |
| @@ -59,6 +59,11 @@ | ||
| 59 | 59 | "@modelcontextprotocol/sdk": "^1.12.0", |
| 60 | 60 | "@mozilla/readability": "^0.5.0", |
| 61 | 61 | "@octokit/rest": "^20.1.1", |
| 62 | + "@sentry/cli": "^2.50.2", | |
| 63 | + "@sentry/core": "^9.43.0", | |
| 64 | + "@sentry/esbuild-plugin": "^4.0.2", | |
| 65 | + "@sentry/node": "^9.43.0", | |
| 66 | + "@sentry/vite-plugin": "^4.0.2", | |
| 62 | 67 | "@typescript-eslint/eslint-plugin": "^7.8.0", |
| 63 | 68 | "@xenova/transformers": "2.14.0", |
| 64 | 69 | "adf-to-md": "^1.1.0", |
| @@ -78,7 +83,7 @@ | ||
| 78 | 83 | "http-proxy-agent": "^7.0.1", |
| 79 | 84 | "https-proxy-agent": "^7.0.3", |
| 80 | 85 | "iconv-lite": "^0.6.3", |
| 81 | - "ignore": "^5.3.1", | |
| 86 | + "ignore": "^7.0.5", | |
| 82 | 87 | "is-localhost-ip": "^2.0.0", |
| 83 | 88 | "jinja-js": "0.1.8", |
| 84 | 89 | "js-tiktoken": "^1.0.8", |
| @@ -91,7 +96,7 @@ | ||
| 91 | 96 | "node-html-markdown": "^1.3.0", |
| 92 | 97 | "ollama": "^0.4.6", |
| 93 | 98 | "onnxruntime-node": "1.14.0", |
| 94 | - "openai": "^4.104.0", | |
| 99 | + "openai": "^5.13.1", | |
| 95 | 100 | "p-limit": "^6.1.0", |
| 96 | 101 | "partial-json": "^0.1.7", |
| 97 | 102 | "pg": "^8.11.3", |
| @@ -6758,10 +6763,11 @@ | ||
| 6758 | 6763 | } |
| 6759 | 6764 | }, |
| 6760 | 6765 | "node_modules/typescript": { |
| 6761 | - "version": "5.4.5", | |
| 6762 | - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", | |
| 6763 | - "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", | |
| 6766 | + "version": "5.9.2", | |
| 6767 | + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", | |
| 6768 | + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", | |
| 6764 | 6769 | "dev": true, |
| 6770 | + "license": "Apache-2.0", | |
| 6765 | 6771 | "bin": { |
| 6766 | 6772 | "tsc": "bin/tsc", |
| 6767 | 6773 | "tsserver": "bin/tsserver" |
modified core/autocomplete/CompletionProvider.ts +6 −1
| @@ -6,12 +6,13 @@ | ||
| 6 | 6 | import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; |
| 7 | 7 | import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; |
| 8 | 8 | |
| 9 | +import { isSecurityConcern } from "../indexing/ignore.js"; | |
| 9 | 10 | import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; |
| 10 | 11 | import { CompletionStreamer } from "./generation/CompletionStreamer.js"; |
| 11 | 12 | import { postprocessCompletion } from "./postprocessing/index.js"; |
| 12 | 13 | import { shouldPrefilter } from "./prefiltering/index.js"; |
| 13 | -import { renderPromptWithTokenLimit } from "./templating/index.js"; | |
| 14 | 14 | import { getAllSnippetsWithoutRace } from "./snippets/index.js"; |
| 15 | +import { renderPromptWithTokenLimit } from "./templating/index.js"; | |
| 15 | 16 | import { GetLspDefinitionsFunction } from "./types.js"; |
| 16 | 17 | import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; |
| 17 | 18 | import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; |
| @@ -150,6 +151,10 @@ | ||
| 150 | 151 | return undefined; |
| 151 | 152 | } |
| 152 | 153 | |
| 154 | + if (isSecurityConcern(input.filepath)) { | |
| 155 | + return undefined; | |
| 156 | + } | |
| 157 | + | |
| 153 | 158 | const options = await this._getAutocompleteOptions(llm); |
| 154 | 159 | |
| 155 | 160 | // Debounce |
modified core/autocomplete/prefiltering/index.ts +1 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | import { |
| 5 | 5 | getGlobalContinueIgArray, |
| 6 | 6 | getWorkspaceContinueIgArray, |
| 7 | -} from "../../indexing/ignore"; | |
| 7 | +} from "../../indexing/continueignore"; | |
| 8 | 8 | import { getConfigJsonPath } from "../../util/paths"; |
| 9 | 9 | import { findUriInDirs } from "../../util/uri"; |
| 10 | 10 | import { HelperVars } from "../util/HelperVars"; |
modified core/commands/slash/built-in-legacy/onboard.ts +2 −5
| @@ -1,11 +1,8 @@ | ||
| 1 | 1 | import ignore from "ignore"; |
| 2 | 2 | |
| 3 | 3 | import type { FileType, IDE, SlashCommand } from "../../.."; |
| 4 | -import { | |
| 5 | - DEFAULT_IGNORE, | |
| 6 | - getGlobalContinueIgArray, | |
| 7 | - gitIgArrayFromFile, | |
| 8 | -} from "../../../indexing/ignore"; | |
| 4 | +import { getGlobalContinueIgArray } from "../../../indexing/continueignore"; | |
| 5 | +import { DEFAULT_IGNORE, gitIgArrayFromFile } from "../../../indexing/ignore"; | |
| 9 | 6 | import { renderChatMessage } from "../../../util/messageContent"; |
| 10 | 7 | import { |
| 11 | 8 | findUriInDirs, |
modified core/config/loadContextProviders.ts +14 −10
| @@ -29,11 +29,24 @@ | ||
| 29 | 29 | } { |
| 30 | 30 | const providers: IContextProvider[] = []; |
| 31 | 31 | const errors: ConfigValidationError[] = []; |
| 32 | + | |
| 33 | + const defaultProviders: IContextProvider[] = [ | |
| 34 | + new FileContextProvider({}), | |
| 35 | + new CurrentFileContextProvider({}), | |
| 36 | + new DiffContextProvider({}), | |
| 37 | + new TerminalContextProvider({}), | |
| 38 | + new ProblemsContextProvider({}), | |
| 39 | + new RulesContextProvider({}), | |
| 40 | + ]; | |
| 41 | + | |
| 32 | 42 | // Add from config |
| 33 | 43 | if (configContext) { |
| 34 | 44 | for (const config of configContext) { |
| 35 | 45 | const cls = contextProviderClassFromName(config.provider) as any; |
| 36 | - if (!cls) { | |
| 46 | + if ( | |
| 47 | + !cls && | |
| 48 | + !defaultProviders.find((p) => p.description.title === config.provider) | |
| 49 | + ) { | |
| 37 | 50 | errors.push({ |
| 38 | 51 | fatal: false, |
| 39 | 52 | message: `Unknown context provider ${config.provider}`, |
| @@ -50,15 +63,6 @@ | ||
| 50 | 63 | } |
| 51 | 64 | |
| 52 | 65 | // Add from defaults if not found in config |
| 53 | - const defaultProviders: IContextProvider[] = [ | |
| 54 | - new FileContextProvider({}), | |
| 55 | - new CurrentFileContextProvider({}), | |
| 56 | - new DiffContextProvider({}), | |
| 57 | - new TerminalContextProvider({}), | |
| 58 | - new ProblemsContextProvider({}), | |
| 59 | - new RulesContextProvider({}), | |
| 60 | - ]; | |
| 61 | - | |
| 62 | 66 | for (const defaultProvider of defaultProviders) { |
| 63 | 67 | if ( |
| 64 | 68 | !providers.find( |
modified core/context/providers/FileContextProvider.ts +1 −0
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | ContextSubmenuItem, |
| 7 | 7 | LoadSubmenuItemsArgs, |
| 8 | 8 | } from "../../"; |
| 9 | +import { isSecurityConcern } from "../../indexing/ignore"; | |
| 9 | 10 | import { walkDirs } from "../../indexing/walkDir"; |
| 10 | 11 | import { |
| 11 | 12 | getShortestUniqueRelativeUriPaths, |
modified core/context/providers/OpenFilesContextProvider.ts +15 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ContextProviderDescription, |
| 4 | 4 | ContextProviderExtras, |
| 5 | 5 | } from "../../index.js"; |
| 6 | +import { isSecurityConcern } from "../../indexing/ignore.js"; | |
| 6 | 7 | import { getUriDescription } from "../../util/uri.js"; |
| 7 | 8 | import { BaseContextProvider } from "../index.js"; |
| 8 | 9 | |
| @@ -27,10 +28,23 @@ | ||
| 27 | 28 | |
| 28 | 29 | return await Promise.all( |
| 29 | 30 | openFiles.map(async (filepath: string) => { |
| 30 | - const content = await ide.readFile(filepath); | |
| 31 | 31 | const { relativePathOrBasename, last2Parts, baseName } = |
| 32 | 32 | getUriDescription(filepath, workspaceDirs); |
| 33 | 33 | |
| 34 | + if (isSecurityConcern(filepath)) { | |
| 35 | + return { | |
| 36 | + description: last2Parts, | |
| 37 | + content: | |
| 38 | + "Content redacted, this file cannot be viewed for security reasons", | |
| 39 | + name: baseName, | |
| 40 | + uri: { | |
| 41 | + type: "file", | |
| 42 | + value: filepath, | |
| 43 | + }, | |
| 44 | + }; | |
| 45 | + } | |
| 46 | + const content = await ide.readFile(filepath); | |
| 47 | + | |
| 34 | 48 | return { |
| 35 | 49 | description: last2Parts, |
| 36 | 50 | content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``, |
modified core/context/providers/ProblemsContextProvider.ts +2 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | ContextProviderDescription, |
| 4 | 4 | ContextProviderExtras, |
| 5 | 5 | } from "../../index.js"; |
| 6 | +import { isSecurityConcern } from "../../indexing/ignore.js"; | |
| 6 | 7 | import { getUriDescription } from "../../util/uri.js"; |
| 7 | 8 | import { BaseContextProvider } from "../index.js"; |
| 8 | 9 | |
| @@ -40,7 +41,7 @@ | ||
| 40 | 41 | return { |
| 41 | 42 | description: "Problems in current file", |
| 42 | 43 | content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`, |
| 43 | - name: `Warning in ${baseName}`, | |
| 44 | + name: `Warnings in ${baseName}`, | |
| 44 | 45 | }; |
| 45 | 46 | }), |
| 46 | 47 | ); |
modified core/context/providers/index.ts +2 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | import DiffContextProvider from "./DiffContextProvider"; |
| 13 | 13 | import DiscordContextProvider from "./DiscordContextProvider"; |
| 14 | 14 | import DocsContextProvider from "./DocsContextProvider"; |
| 15 | +import FileContextProvider from "./FileContextProvider"; | |
| 15 | 16 | import FileTreeContextProvider from "./FileTreeContextProvider"; |
| 16 | 17 | import FolderContextProvider from "./FolderContextProvider"; |
| 17 | 18 | import GitCommitContextProvider from "./GitCommitContextProvider"; |
| @@ -41,6 +42,7 @@ | ||
| 41 | 42 | * See this issue for details: https://github.com/continuedev/continue/issues/1365 |
| 42 | 43 | */ |
| 43 | 44 | export const Providers: (typeof BaseContextProvider)[] = [ |
| 45 | + FileContextProvider, | |
| 44 | 46 | DiffContextProvider, |
| 45 | 47 | FileTreeContextProvider, |
| 46 | 48 | GitHubIssuesContextProvider, |
modified core/context/retrieval/retrieval.ts +1 −1
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | const nFinal = |
| 38 | 38 | options?.nFinal ?? |
| 39 | 39 | Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2); |
| 40 | - const useReranking = !!extras.reranker; | |
| 40 | + const useReranking = options?.useReranking ?? !!extras.reranker; | |
| 41 | 41 | const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal; |
| 42 | 42 | |
| 43 | 43 | const branches = (await Promise.race([ |
added core/indexing/continueignore.ts +26 −0
| @@ -0,0 +1,26 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import { IDE } from ".."; | |
| 3 | +import { getGlobalContinueIgnorePath } from "../util/paths"; | |
| 4 | +import { gitIgArrayFromFile } from "./ignore"; | |
| 5 | + | |
| 6 | +export const getGlobalContinueIgArray = () => { | |
| 7 | + const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8"); | |
| 8 | + return gitIgArrayFromFile(contents); | |
| 9 | +}; | |
| 10 | + | |
| 11 | +export const getWorkspaceContinueIgArray = async (ide: IDE) => { | |
| 12 | + const dirs = await ide.getWorkspaceDirs(); | |
| 13 | + return await dirs.reduce( | |
| 14 | + async (accPromise, dir) => { | |
| 15 | + const acc = await accPromise; | |
| 16 | + try { | |
| 17 | + const contents = await ide.readFile(`${dir}/.continueignore`); | |
| 18 | + return [...acc, ...gitIgArrayFromFile(contents)]; | |
| 19 | + } catch (err) { | |
| 20 | + console.error(err); | |
| 21 | + return acc; | |
| 22 | + } | |
| 23 | + }, | |
| 24 | + Promise.resolve([] as string[]), | |
| 25 | + ); | |
| 26 | +}; |
modified core/indexing/ignore.ts +161 −44
| @@ -1,11 +1,100 @@ | ||
| 1 | -import fs from "fs"; | |
| 2 | - | |
| 3 | 1 | import ignore from "ignore"; |
| 4 | 2 | |
| 5 | -import { IDE } from ".."; | |
| 6 | -import { getGlobalContinueIgnorePath } from "../util/paths"; | |
| 3 | +import path from "path"; | |
| 4 | +import { fileURLToPath } from "url"; | |
| 7 | 5 | |
| 8 | -export const DEFAULT_IGNORE_FILETYPES = [ | |
| 6 | +// Security-focused ignore patterns - these should always be excluded for security reasons | |
| 7 | +export const DEFAULT_SECURITY_IGNORE_FILETYPES = [ | |
| 8 | + // Environment and configuration files with secrets | |
| 9 | + "*.env", | |
| 10 | + "*.env.*", | |
| 11 | + ".env*", | |
| 12 | + "config.json", | |
| 13 | + "config.yaml", | |
| 14 | + "config.yml", | |
| 15 | + "settings.json", | |
| 16 | + "appsettings.json", | |
| 17 | + "appsettings.*.json", | |
| 18 | + | |
| 19 | + // Certificate and key files | |
| 20 | + "*.key", | |
| 21 | + "*.pem", | |
| 22 | + "*.p12", | |
| 23 | + "*.pfx", | |
| 24 | + "*.crt", | |
| 25 | + "*.cer", | |
| 26 | + "*.jks", | |
| 27 | + "*.keystore", | |
| 28 | + "*.truststore", | |
| 29 | + | |
| 30 | + // Database files that may contain sensitive data | |
| 31 | + "*.db", | |
| 32 | + "*.sqlite", | |
| 33 | + "*.sqlite3", | |
| 34 | + "*.mdb", | |
| 35 | + "*.accdb", | |
| 36 | + | |
| 37 | + // Credential and secret files | |
| 38 | + "*.secret", | |
| 39 | + "*.secrets", | |
| 40 | + "credentials", | |
| 41 | + "credentials.*", | |
| 42 | + "auth.json", | |
| 43 | + "token", | |
| 44 | + "token.*", | |
| 45 | + "*.token", | |
| 46 | + | |
| 47 | + // Backup files that might contain sensitive data | |
| 48 | + "*.bak", | |
| 49 | + "*.backup", | |
| 50 | + "*.old", | |
| 51 | + "*.orig", | |
| 52 | + | |
| 53 | + // Docker secrets | |
| 54 | + "docker-compose.override.yml", | |
| 55 | + "docker-compose.override.yaml", | |
| 56 | + | |
| 57 | + // SSH and GPG | |
| 58 | + "id_rsa", | |
| 59 | + "id_dsa", | |
| 60 | + "id_ecdsa", | |
| 61 | + "id_ed25519", | |
| 62 | + "*.ppk", | |
| 63 | + "*.gpg", | |
| 64 | +]; | |
| 65 | + | |
| 66 | +export const DEFAULT_SECURITY_IGNORE_DIRS = [ | |
| 67 | + // Environment and configuration directories | |
| 68 | + ".env/", | |
| 69 | + "env/", | |
| 70 | + | |
| 71 | + // Cloud provider credential directories | |
| 72 | + ".aws/", | |
| 73 | + ".gcp/", | |
| 74 | + ".azure/", | |
| 75 | + ".kube/", | |
| 76 | + ".docker/", | |
| 77 | + | |
| 78 | + // Secret directories | |
| 79 | + "secrets/", | |
| 80 | + ".secrets/", | |
| 81 | + "private/", | |
| 82 | + ".private/", | |
| 83 | + "certs/", | |
| 84 | + "certificates/", | |
| 85 | + "keys/", | |
| 86 | + ".ssh/", | |
| 87 | + ".gnupg/", | |
| 88 | + ".gpg/", | |
| 89 | + | |
| 90 | + // Temporary directories that might contain sensitive data | |
| 91 | + "tmp/secrets/", | |
| 92 | + "temp/secrets/", | |
| 93 | + ".tmp/", | |
| 94 | +]; | |
| 95 | + | |
| 96 | +// Additional non-security patterns for general indexing exclusion | |
| 97 | +export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [ | |
| 9 | 98 | "*.DS_Store", |
| 10 | 99 | "*-lock.json", |
| 11 | 100 | "*.lock", |
| @@ -46,8 +135,6 @@ | ||
| 46 | 135 | "*.mpeg", |
| 47 | 136 | "*.mov", |
| 48 | 137 | "*.mp3", |
| 49 | - "*.mp4", | |
| 50 | - "*.mkv", | |
| 51 | 138 | "*.mkv", |
| 52 | 139 | "*.webm", |
| 53 | 140 | "*.jar", |
| @@ -56,20 +143,15 @@ | ||
| 56 | 143 | "*.pqt", |
| 57 | 144 | "*.wav", |
| 58 | 145 | "*.webp", |
| 59 | - "*.db", | |
| 60 | - "*.sqlite", | |
| 61 | 146 | "*.wasm", |
| 62 | 147 | "*.plist", |
| 63 | 148 | "*.profraw", |
| 64 | 149 | "*.gcda", |
| 65 | 150 | "*.gcno", |
| 66 | 151 | "go.sum", |
| 67 | - "*.env", | |
| 68 | 152 | "*.gitignore", |
| 69 | 153 | "*.gitkeep", |
| 70 | 154 | "*.continueignore", |
| 71 | - "config.json", | |
| 72 | - "config.yaml", | |
| 73 | 155 | "*.csv", |
| 74 | 156 | "*.uasset", |
| 75 | 157 | "*.pdb", |
| @@ -78,19 +160,13 @@ | ||
| 78 | 160 | "*.swp", |
| 79 | 161 | "*.jsonl", |
| 80 | 162 | // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt |
| 163 | + // Application specific | |
| 164 | + ".continue/", | |
| 81 | 165 | ]; |
| 82 | 166 | |
| 83 | -export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); | |
| 84 | -export const DEFAULT_IGNORE_DIRS = [ | |
| 167 | +export const ADDITIONAL_INDEXING_IGNORE_DIRS = [ | |
| 85 | 168 | ".git/", |
| 86 | 169 | ".svn/", |
| 87 | - ".vscode/", | |
| 88 | - ".idea/", | |
| 89 | - ".vs/", | |
| 90 | - "venv/", | |
| 91 | - ".venv/", | |
| 92 | - "env/", | |
| 93 | - ".env/", | |
| 94 | 170 | "node_modules/", |
| 95 | 171 | "dist/", |
| 96 | 172 | "build/", |
| @@ -100,7 +176,6 @@ | ||
| 100 | 176 | "bin/", |
| 101 | 177 | ".pytest_cache/", |
| 102 | 178 | ".vscode-test/", |
| 103 | - ".continue/", | |
| 104 | 179 | "__pycache__/", |
| 105 | 180 | "site-packages/", |
| 106 | 181 | ".gradle/", |
| @@ -108,42 +183,84 @@ | ||
| 108 | 183 | ".cache/", |
| 109 | 184 | "gems/", |
| 110 | 185 | "vendor/", |
| 186 | + | |
| 187 | + ".venv/", | |
| 188 | + "venv/", | |
| 189 | + | |
| 190 | + ".vscode/", | |
| 191 | + ".idea/", | |
| 192 | + ".vs/", | |
| 193 | +]; | |
| 194 | + | |
| 195 | +// Combined patterns: security + additional | |
| 196 | +export const DEFAULT_IGNORE_FILETYPES = [ | |
| 197 | + ...DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 198 | + ...ADDITIONAL_INDEXING_IGNORE_FILETYPES, | |
| 199 | +]; | |
| 200 | + | |
| 201 | +export const DEFAULT_IGNORE_DIRS = [ | |
| 202 | + ...DEFAULT_SECURITY_IGNORE_DIRS, | |
| 203 | + ...ADDITIONAL_INDEXING_IGNORE_DIRS, | |
| 111 | 204 | ]; |
| 112 | 205 | |
| 206 | +// Create ignore instances | |
| 207 | +export const defaultSecurityIgnoreFile = ignore().add( | |
| 208 | + DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 209 | +); | |
| 210 | +export const defaultSecurityIgnoreDir = ignore().add( | |
| 211 | + DEFAULT_SECURITY_IGNORE_DIRS, | |
| 212 | +); | |
| 213 | +export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); | |
| 113 | 214 | export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); |
| 114 | 215 | |
| 216 | +// String representations | |
| 217 | +export const DEFAULT_SECURITY_IGNORE = | |
| 218 | + DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") + | |
| 219 | + "\n" + | |
| 220 | + DEFAULT_SECURITY_IGNORE_DIRS.join("\n"); | |
| 221 | + | |
| 115 | 222 | export const DEFAULT_IGNORE = |
| 116 | 223 | DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); |
| 117 | 224 | |
| 225 | +// Combined ignore instances | |
| 226 | +export const defaultFileAndFolderSecurityIgnores = ignore() | |
| 227 | + .add(defaultSecurityIgnoreFile) | |
| 228 | + .add(defaultSecurityIgnoreDir); | |
| 229 | + | |
| 118 | 230 | export const defaultIgnoreFileAndDir = ignore() |
| 119 | 231 | .add(defaultIgnoreFile) |
| 120 | 232 | .add(defaultIgnoreDir); |
| 121 | 233 | |
| 234 | +export function isSecurityConcern(filePathOrUri: string) { | |
| 235 | + if (!filePathOrUri) { | |
| 236 | + return false; | |
| 237 | + } | |
| 238 | + let filepath = filePathOrUri; | |
| 239 | + try { | |
| 240 | + filepath = fileURLToPath(filePathOrUri); | |
| 241 | + } catch {} | |
| 242 | + if (path.isAbsolute(filepath)) { | |
| 243 | + const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? ""; | |
| 244 | + const basename = path.basename(filepath); | |
| 245 | + filepath = `${dir ? dir + "/" : ""}${basename}`; | |
| 246 | + } | |
| 247 | + if (!filepath) { | |
| 248 | + return false; | |
| 249 | + } | |
| 250 | + return defaultFileAndFolderSecurityIgnores.ignores(filepath); | |
| 251 | +} | |
| 252 | + | |
| 253 | +export function throwIfFileIsSecurityConcern(filepath: string) { | |
| 254 | + if (isSecurityConcern(filepath)) { | |
| 255 | + throw new Error( | |
| 256 | + `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 | + ); | |
| 258 | + } | |
| 259 | +} | |
| 260 | + | |
| 122 | 261 | export function gitIgArrayFromFile(file: string) { |
| 123 | 262 | return file |
| 124 | 263 | .split(/\r?\n/) // Split on new line |
| 125 | 264 | .map((l) => l.trim()) // Remove whitespace |
| 126 | 265 | .filter((l) => !/^#|^$/.test(l)); // Remove empty lines |
| 127 | 266 | } |
| 128 | - | |
| 129 | -export const getGlobalContinueIgArray = () => { | |
| 130 | - const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8"); | |
| 131 | - return gitIgArrayFromFile(contents); | |
| 132 | -}; | |
| 133 | - | |
| 134 | -export const getWorkspaceContinueIgArray = async (ide: IDE) => { | |
| 135 | - const dirs = await ide.getWorkspaceDirs(); | |
| 136 | - return await dirs.reduce( | |
| 137 | - async (accPromise, dir) => { | |
| 138 | - const acc = await accPromise; | |
| 139 | - try { | |
| 140 | - const contents = await ide.readFile(`${dir}/.continueignore`); | |
| 141 | - return [...acc, ...gitIgArrayFromFile(contents)]; | |
| 142 | - } catch (err) { | |
| 143 | - console.error(err); | |
| 144 | - return acc; | |
| 145 | - } | |
| 146 | - }, | |
| 147 | - Promise.resolve([] as string[]), | |
| 148 | - ); | |
| 149 | -}; |
added core/indexing/ignore.vitest.ts +257 −0
| @@ -0,0 +1,257 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + DEFAULT_SECURITY_IGNORE_DIRS, | |
| 4 | + DEFAULT_SECURITY_IGNORE_FILETYPES, | |
| 5 | + defaultFileAndFolderSecurityIgnores, | |
| 6 | + isSecurityConcern, | |
| 7 | +} from "./ignore"; | |
| 8 | + | |
| 9 | +describe("isSecurityConcern", () => { | |
| 10 | + describe("Security file types", () => { | |
| 11 | + it("should detect environment files as security concerns", () => { | |
| 12 | + expect(isSecurityConcern(".env")).toBe(true); | |
| 13 | + expect(isSecurityConcern(".env.local")).toBe(true); | |
| 14 | + expect(isSecurityConcern(".env.production")).toBe(true); | |
| 15 | + expect(isSecurityConcern("config/.env")).toBe(true); | |
| 16 | + expect(isSecurityConcern("/path/to/.env")).toBe(true); | |
| 17 | + expect(isSecurityConcern("file:///path/to/.env")).toBe(true); | |
| 18 | + }); | |
| 19 | + | |
| 20 | + it("should detect configuration files as security concerns", () => { | |
| 21 | + expect(isSecurityConcern("config.json")).toBe(true); | |
| 22 | + expect(isSecurityConcern("config.yaml")).toBe(true); | |
| 23 | + expect(isSecurityConcern("config.yml")).toBe(true); | |
| 24 | + expect(isSecurityConcern("settings.json")).toBe(true); | |
| 25 | + expect(isSecurityConcern("appsettings.json")).toBe(true); | |
| 26 | + expect(isSecurityConcern("appsettings.development.json")).toBe(true); | |
| 27 | + expect(isSecurityConcern("appsettings.production.json")).toBe(true); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should detect certificate and key files as security concerns", () => { | |
| 31 | + expect(isSecurityConcern("private.key")).toBe(true); | |
| 32 | + expect(isSecurityConcern("certificate.pem")).toBe(true); | |
| 33 | + expect(isSecurityConcern("server.crt")).toBe(true); | |
| 34 | + expect(isSecurityConcern("keystore.jks")).toBe(true); | |
| 35 | + expect(isSecurityConcern("ssl/server.key")).toBe(true); | |
| 36 | + expect(isSecurityConcern("/etc/ssl/certs/server.pem")).toBe(true); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should detect database files as security concerns", () => { | |
| 40 | + expect(isSecurityConcern("database.db")).toBe(true); | |
| 41 | + expect(isSecurityConcern("users.sqlite")).toBe(true); | |
| 42 | + expect(isSecurityConcern("data.sqlite3")).toBe(true); | |
| 43 | + expect(isSecurityConcern("app.mdb")).toBe(true); | |
| 44 | + expect(isSecurityConcern("data/users.db")).toBe(true); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should detect credential files as security concerns", () => { | |
| 48 | + expect(isSecurityConcern("app.secret")).toBe(true); | |
| 49 | + expect(isSecurityConcern("api.secrets")).toBe(true); | |
| 50 | + expect(isSecurityConcern("credentials")).toBe(true); | |
| 51 | + expect(isSecurityConcern("credentials.json")).toBe(true); | |
| 52 | + expect(isSecurityConcern("auth.json")).toBe(true); | |
| 53 | + expect(isSecurityConcern("token")).toBe(true); | |
| 54 | + expect(isSecurityConcern("api.token")).toBe(true); | |
| 55 | + expect(isSecurityConcern("access.token")).toBe(true); | |
| 56 | + }); | |
| 57 | + | |
| 58 | + it("should detect backup files as security concerns", () => { | |
| 59 | + expect(isSecurityConcern("database.bak")).toBe(true); | |
| 60 | + expect(isSecurityConcern("config.backup")).toBe(true); | |
| 61 | + expect(isSecurityConcern("settings.old")).toBe(true); | |
| 62 | + expect(isSecurityConcern("app.orig")).toBe(true); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("should detect Docker override files as security concerns", () => { | |
| 66 | + expect(isSecurityConcern("docker-compose.override.yml")).toBe(true); | |
| 67 | + expect(isSecurityConcern("docker-compose.override.yaml")).toBe(true); | |
| 68 | + }); | |
| 69 | + | |
| 70 | + it("should detect SSH and GPG files as security concerns", () => { | |
| 71 | + expect(isSecurityConcern("id_rsa")).toBe(true); | |
| 72 | + expect(isSecurityConcern("id_dsa")).toBe(true); | |
| 73 | + expect(isSecurityConcern("id_ecdsa")).toBe(true); | |
| 74 | + expect(isSecurityConcern("id_ed25519")).toBe(true); | |
| 75 | + expect(isSecurityConcern("private.ppk")).toBe(true); | |
| 76 | + expect(isSecurityConcern("secret.gpg")).toBe(true); | |
| 77 | + }); | |
| 78 | + }); | |
| 79 | + | |
| 80 | + describe("Security directories", () => { | |
| 81 | + it("should detect environment directories as security concerns", () => { | |
| 82 | + expect(isSecurityConcern(".env/")).toBe(true); | |
| 83 | + expect(isSecurityConcern("env/")).toBe(true); | |
| 84 | + expect(isSecurityConcern(".env/config")).toBe(true); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("should detect cloud provider directories as security concerns", () => { | |
| 88 | + expect(isSecurityConcern(".aws/")).toBe(true); | |
| 89 | + expect(isSecurityConcern(".gcp/")).toBe(true); | |
| 90 | + expect(isSecurityConcern(".azure/")).toBe(true); | |
| 91 | + expect(isSecurityConcern(".kube/")).toBe(true); | |
| 92 | + expect(isSecurityConcern(".docker/")).toBe(true); | |
| 93 | + expect(isSecurityConcern(".aws/credentials")).toBe(true); | |
| 94 | + expect(isSecurityConcern(".kube/config")).toBe(true); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("should detect secret directories as security concerns", () => { | |
| 98 | + expect(isSecurityConcern("secrets/")).toBe(true); | |
| 99 | + expect(isSecurityConcern(".secrets/")).toBe(true); | |
| 100 | + expect(isSecurityConcern("private/")).toBe(true); | |
| 101 | + expect(isSecurityConcern(".private/")).toBe(true); | |
| 102 | + expect(isSecurityConcern("certs/")).toBe(true); | |
| 103 | + expect(isSecurityConcern("certificates/")).toBe(true); | |
| 104 | + expect(isSecurityConcern("keys/")).toBe(true); | |
| 105 | + expect(isSecurityConcern(".ssh/")).toBe(true); | |
| 106 | + expect(isSecurityConcern(".gnupg/")).toBe(true); | |
| 107 | + expect(isSecurityConcern(".gpg/")).toBe(true); | |
| 108 | + }); | |
| 109 | + | |
| 110 | + it("should detect continue directory as security concern", () => { | |
| 111 | + expect(isSecurityConcern(".continue/config.json")).toBe(true); | |
| 112 | + }); | |
| 113 | + | |
| 114 | + it("should detect temporary secret directories as security concerns", () => { | |
| 115 | + expect(isSecurityConcern("tmp/secrets/")).toBe(true); | |
| 116 | + expect(isSecurityConcern("temp/secrets/")).toBe(true); | |
| 117 | + expect(isSecurityConcern(".tmp/")).toBe(true); | |
| 118 | + expect(isSecurityConcern("tmp/secrets/api.key")).toBe(true); | |
| 119 | + }); | |
| 120 | + }); | |
| 121 | + | |
| 122 | + describe("Path variations", () => { | |
| 123 | + it("should handle absolute paths", () => { | |
| 124 | + expect(isSecurityConcern("/home/user/.env")).toBe(true); | |
| 125 | + expect(isSecurityConcern("/var/www/.secrets/")).toBe(true); | |
| 126 | + expect(isSecurityConcern("/etc/ssl/private.key")).toBe(true); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + it("should handle URI schemes", () => { | |
| 130 | + expect(isSecurityConcern("file:///home/user/.env")).toBe(true); | |
| 131 | + expect(isSecurityConcern("file:///var/secrets/api.key")).toBe(true); | |
| 132 | + }); | |
| 133 | + | |
| 134 | + it("should handle nested paths", () => { | |
| 135 | + expect(isSecurityConcern("project/config/.env")).toBe(true); | |
| 136 | + expect(isSecurityConcern("src/main/resources/application.secret")).toBe( | |
| 137 | + true, | |
| 138 | + ); | |
| 139 | + expect(isSecurityConcern("backend/certs/server.key")).toBe(true); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + // it("should handle Windows-style paths", () => { | |
| 143 | + // expect(isSecurityConcern("C:\\Users\\user\\.env")).toBe(true); | |
| 144 | + // expect(isSecurityConcern("D:\\projects\\app\\secrets\\")).toBe(true); | |
| 145 | + // }); | |
| 146 | + }); | |
| 147 | + | |
| 148 | + describe("Non-security files", () => { | |
| 149 | + it("should not flag regular source code files", () => { | |
| 150 | + expect(isSecurityConcern("src/main.js")).toBe(false); | |
| 151 | + expect(isSecurityConcern("components/App.tsx")).toBe(false); | |
| 152 | + expect(isSecurityConcern("utils/helper.py")).toBe(false); | |
| 153 | + expect(isSecurityConcern("models/User.java")).toBe(false); | |
| 154 | + expect(isSecurityConcern("styles/main.css")).toBe(false); | |
| 155 | + }); | |
| 156 | + | |
| 157 | + it("should not flag regular configuration files", () => { | |
| 158 | + expect(isSecurityConcern("package.json")).toBe(false); | |
| 159 | + expect(isSecurityConcern("tsconfig.json")).toBe(false); | |
| 160 | + expect(isSecurityConcern("webpack.config.js")).toBe(false); | |
| 161 | + expect(isSecurityConcern("babel.config.js")).toBe(false); | |
| 162 | + expect(isSecurityConcern("jest.config.js")).toBe(false); | |
| 163 | + }); | |
| 164 | + | |
| 165 | + it("should not flag documentation files", () => { | |
| 166 | + expect(isSecurityConcern("README.md")).toBe(false); | |
| 167 | + expect(isSecurityConcern("CHANGELOG.md")).toBe(false); | |
| 168 | + expect(isSecurityConcern("docs/api.md")).toBe(false); | |
| 169 | + expect(isSecurityConcern("LICENSE")).toBe(false); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + it("should not flag regular directories", () => { | |
| 173 | + expect(isSecurityConcern("src/")).toBe(false); | |
| 174 | + expect(isSecurityConcern("components/")).toBe(false); | |
| 175 | + expect(isSecurityConcern("utils/")).toBe(false); | |
| 176 | + expect(isSecurityConcern("tests/")).toBe(false); | |
| 177 | + expect(isSecurityConcern("docs/")).toBe(false); | |
| 178 | + }); | |
| 179 | + | |
| 180 | + it("should not flag files with similar names but different extensions", () => { | |
| 181 | + expect(isSecurityConcern("environment.js")).toBe(false); | |
| 182 | + expect(isSecurityConcern("config-template.json")).toBe(false); | |
| 183 | + expect(isSecurityConcern("secret-utils.js")).toBe(false); | |
| 184 | + expect(isSecurityConcern("token-validator.ts")).toBe(false); | |
| 185 | + }); | |
| 186 | + }); | |
| 187 | + | |
| 188 | + describe("Edge cases", () => { | |
| 189 | + it("should handle empty strings", () => { | |
| 190 | + expect(isSecurityConcern("")).toBe(false); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + it("should handle paths with only separators", () => { | |
| 194 | + expect(isSecurityConcern("/")).toBe(false); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + it("should handle paths with multiple extensions", () => { | |
| 198 | + expect(isSecurityConcern("backup.env.old")).toBe(true); // matches *.old | |
| 199 | + expect(isSecurityConcern("config.json.bak")).toBe(true); // matches *.bak | |
| 200 | + expect(isSecurityConcern("server.key.backup")).toBe(true); // matches *.backup | |
| 201 | + }); | |
| 202 | + | |
| 203 | + it("should handle files in root vs subdirectories", () => { | |
| 204 | + expect(isSecurityConcern(".env")).toBe(true); | |
| 205 | + expect(isSecurityConcern("project/.env")).toBe(true); | |
| 206 | + expect(isSecurityConcern("deeply/nested/path/.env")).toBe(true); | |
| 207 | + }); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + describe("Pattern matching consistency", () => { | |
| 211 | + it("should match all defined security file patterns", () => { | |
| 212 | + // Test a sample from each category to ensure patterns work | |
| 213 | + DEFAULT_SECURITY_IGNORE_FILETYPES.forEach((pattern) => { | |
| 214 | + // Create a test file name that should match the pattern | |
| 215 | + let testFile: string; | |
| 216 | + if (pattern.startsWith("*.")) { | |
| 217 | + testFile = `test${pattern.substring(1)}`; | |
| 218 | + } else if (pattern.includes("*")) { | |
| 219 | + testFile = pattern.replace("*", "test"); | |
| 220 | + } else { | |
| 221 | + testFile = pattern; | |
| 222 | + } | |
| 223 | + | |
| 224 | + expect(isSecurityConcern(testFile)).toBe(true); | |
| 225 | + }); | |
| 226 | + }); | |
| 227 | + | |
| 228 | + it("should match all defined security directory patterns", () => { | |
| 229 | + DEFAULT_SECURITY_IGNORE_DIRS.forEach((pattern) => { | |
| 230 | + // Test the directory pattern directly | |
| 231 | + expect(isSecurityConcern(pattern)).toBe(true); | |
| 232 | + | |
| 233 | + // Test a file inside the directory | |
| 234 | + const fileInDir = `${pattern}testfile.txt`; | |
| 235 | + expect(isSecurityConcern(fileInDir)).toBe(true); | |
| 236 | + }); | |
| 237 | + }); | |
| 238 | + }); | |
| 239 | + | |
| 240 | + describe("Integration with ignore library", () => { | |
| 241 | + it("should use the same ignore instance as defaultFileAndFolderSecurityIgnores", () => { | |
| 242 | + // Test that our function uses the same logic as the exported ignore instance | |
| 243 | + const testFiles = [ | |
| 244 | + ".env", | |
| 245 | + "secrets/api.key", | |
| 246 | + ".aws/credentials", | |
| 247 | + "regular-file.js", | |
| 248 | + ]; | |
| 249 | + | |
| 250 | + testFiles.forEach((file) => { | |
| 251 | + const functionResult = isSecurityConcern(file); | |
| 252 | + const ignoreResult = defaultFileAndFolderSecurityIgnores.ignores(file); | |
| 253 | + expect(functionResult).toBe(ignoreResult); | |
| 254 | + }); | |
| 255 | + }); | |
| 256 | + }); | |
| 257 | +}); |
modified core/indexing/shouldIgnore.ts +2 −1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import ignore from "ignore"; |
| 2 | 2 | import type { FileType, IDE } from "../"; |
| 3 | 3 | import { findUriInDirs, getUriPathBasename } from "../util/uri"; |
| 4 | -import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; | |
| 4 | +import { getGlobalContinueIgArray } from "./continueignore"; | |
| 5 | +import { defaultIgnoreFileAndDir } from "./ignore"; | |
| 5 | 6 | import { getIgnoreContext } from "./walkDir"; |
| 6 | 7 | |
| 7 | 8 | /* |
modified core/indexing/walkDir.ts +2 −5
| @@ -3,11 +3,8 @@ | ||
| 3 | 3 | import type { FileType, IDE } from ".."; |
| 4 | 4 | |
| 5 | 5 | import { joinPathsToUri } from "../util/uri"; |
| 6 | -import { | |
| 7 | - defaultIgnoreFileAndDir, | |
| 8 | - getGlobalContinueIgArray, | |
| 9 | - gitIgArrayFromFile, | |
| 10 | -} from "./ignore"; | |
| 6 | +import { getGlobalContinueIgArray } from "./continueignore"; | |
| 7 | +import { defaultIgnoreFileAndDir, gitIgArrayFromFile } from "./ignore"; | |
| 11 | 8 | |
| 12 | 9 | export interface WalkerOptions { |
| 13 | 10 | include?: "dirs" | "files" | "both"; |
modified core/llm/autodetect.ts +0 −1
| @@ -178,7 +178,6 @@ | ||
| 178 | 178 | // update core/nextEdit/templating/NextEditPromptEngine.ts as well. |
| 179 | 179 | const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ |
| 180 | 180 | NEXT_EDIT_MODELS.MERCURY_CODER, |
| 181 | - NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, | |
| 182 | 181 | NEXT_EDIT_MODELS.INSTINCT, |
| 183 | 182 | ]; |
| 184 | 183 |
modified core/llm/autodetect.vitest.ts +12 −12
| @@ -220,7 +220,7 @@ | ||
| 220 | 220 | expect( |
| 221 | 221 | modelSupportsNextEdit( |
| 222 | 222 | { nextEdit: false }, |
| 223 | - "mercury-coder-nextedit", | |
| 223 | + "mercury-coder", | |
| 224 | 224 | "Mercury Coder", |
| 225 | 225 | ), |
| 226 | 226 | ).toBe(false); |
| @@ -231,7 +231,7 @@ | ||
| 231 | 231 | expect( |
| 232 | 232 | modelSupportsNextEdit( |
| 233 | 233 | { nextEdit: false }, |
| 234 | - "mercury-coder-nextedit", | |
| 234 | + "mercury-coder", | |
| 235 | 235 | "Mercury Coder", |
| 236 | 236 | ), |
| 237 | 237 | ).toBe(false); |
| @@ -239,10 +239,10 @@ | ||
| 239 | 239 | }); |
| 240 | 240 | |
| 241 | 241 | describe("when capabilities.nextEdit is undefined", () => { |
| 242 | - it("should return true for mercury-coder-nextedit model (case insensitive)", () => { | |
| 243 | - expect( | |
| 244 | - modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined), | |
| 245 | - ).toBe(true); | |
| 242 | + it("should return true for mercury-coder model (case insensitive)", () => { | |
| 243 | + expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe( | |
| 244 | + true, | |
| 245 | + ); | |
| 246 | 246 | }); |
| 247 | 247 | |
| 248 | 248 | it("should return true for instinct", () => { |
| @@ -255,7 +255,7 @@ | ||
| 255 | 255 | expect( |
| 256 | 256 | modelSupportsNextEdit( |
| 257 | 257 | undefined, |
| 258 | - "provider/mercury-coder-nextedit-v2", | |
| 258 | + "provider/mercury-coder-v2", | |
| 259 | 259 | undefined, |
| 260 | 260 | ), |
| 261 | 261 | ).toBe(true); |
| @@ -266,7 +266,7 @@ | ||
| 266 | 266 | modelSupportsNextEdit( |
| 267 | 267 | undefined, |
| 268 | 268 | "some-model", |
| 269 | - "This is mercury-coder-nextedit model", | |
| 269 | + "This is mercury-coder model", | |
| 270 | 270 | ), |
| 271 | 271 | ).toBe(true); |
| 272 | 272 | }); |
| @@ -312,14 +312,14 @@ | ||
| 312 | 312 | }); |
| 313 | 313 | |
| 314 | 314 | it("should handle undefined title gracefully", () => { |
| 315 | - expect( | |
| 316 | - modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined), | |
| 317 | - ).toBe(true); | |
| 315 | + expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe( | |
| 316 | + true, | |
| 317 | + ); | |
| 318 | 318 | }); |
| 319 | 319 | |
| 320 | 320 | it("should handle case sensitivity correctly", () => { |
| 321 | 321 | expect( |
| 322 | - modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"), | |
| 322 | + modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"), | |
| 323 | 323 | ).toBe(true); |
| 324 | 324 | }); |
| 325 | 325 |
modified core/llm/constants.ts +0 −1
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | |
| 22 | 22 | export enum NEXT_EDIT_MODELS { |
| 23 | 23 | MERCURY_CODER = "mercury-coder", |
| 24 | - MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", | |
| 25 | 24 | INSTINCT = "instinct", |
| 26 | 25 | } |
| 27 | 26 |
modified core/llm/defaultSystemMessages.ts +11 −1
| @@ -46,6 +46,8 @@ | ||
| 46 | 46 | of changes unless the user specifically asks for code only. |
| 47 | 47 | `; |
| 48 | 48 | |
| 49 | +const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`; | |
| 50 | + | |
| 49 | 51 | export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ |
| 50 | 52 | <important_rules> |
| 51 | 53 | You are in chat mode. |
| @@ -64,6 +66,11 @@ | ||
| 64 | 66 | If you need to use multiple tools, you can call multiple read only tools simultaneously. |
| 65 | 67 | |
| 66 | 68 | ${CODEBLOCK_FORMATTING_INSTRUCTIONS} |
| 69 | + | |
| 70 | +${BRIEF_LAZY_INSTRUCTIONS} | |
| 71 | + | |
| 72 | +However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools. | |
| 73 | + | |
| 67 | 74 | </important_rules>`; |
| 68 | 75 | |
| 69 | 76 | // The note about read-only tools is for MCP servers |
| @@ -75,7 +82,10 @@ | ||
| 75 | 82 | If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates. |
| 76 | 83 | |
| 77 | 84 | ${CODEBLOCK_FORMATTING_INSTRUCTIONS} |
| 78 | -${EDIT_CODE_INSTRUCTIONS} | |
| 85 | + | |
| 86 | +${BRIEF_LAZY_INSTRUCTIONS} | |
| 87 | + | |
| 88 | +However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode. | |
| 79 | 89 | |
| 80 | 90 | In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan. |
| 81 | 91 | </important_rules>`; |
modified core/llm/llm.test.ts +1 −1
| @@ -213,7 +213,7 @@ | ||
| 213 | 213 | |
| 214 | 214 | testLLM( |
| 215 | 215 | new Anthropic({ |
| 216 | - model: "claude-3-5-sonnet-latest", | |
| 216 | + model: "claude-sonnet-4-0", | |
| 217 | 217 | apiKey: process.env.ANTHROPIC_API_KEY, |
| 218 | 218 | }), |
| 219 | 219 | { skip: false, testToolCall: true }, |
modified core/llm/toolSupport.test.ts +29 −0
| @@ -280,6 +280,34 @@ | ||
| 280 | 280 | }); |
| 281 | 281 | }); |
| 282 | 282 | |
| 283 | + describe("novita", () => { | |
| 284 | + const supportsFn = PROVIDER_TOOL_SUPPORT["novita"]; | |
| 285 | + | |
| 286 | + it("should return true for exact match models", () => { | |
| 287 | + expect(supportsFn("deepseek/deepseek-r1-0528")).toBe(true); | |
| 288 | + expect(supportsFn("deepseek/deepseek-r1-turbo")).toBe(true); | |
| 289 | + expect(supportsFn("deepseek/deepseek-v3-0324")).toBe(true); | |
| 290 | + expect(supportsFn("deepseek/deepseek-v3-turbo")).toBe(true); | |
| 291 | + expect(supportsFn("meta-llama/llama-3.3-70b-instruct")).toBe(true); | |
| 292 | + expect(supportsFn("qwen/qwen-2.5-72b-instruct")).toBe(true); | |
| 293 | + expect(supportsFn("zai-org/glm-4.5")).toBe(true); | |
| 294 | + expect(supportsFn("moonshotai/kimi-k2-instruct")).toBe(true); | |
| 295 | + }); | |
| 296 | + | |
| 297 | + it("should return true for prefix match models", () => { | |
| 298 | + expect(supportsFn("qwen/qwen3-235b-a22b-instruct-2507")).toBe(true); | |
| 299 | + expect(supportsFn("openai/gpt-oss-20b")).toBe(true); | |
| 300 | + expect(supportsFn("openai/gpt-oss-120b")).toBe(true); | |
| 301 | + }); | |
| 302 | + | |
| 303 | + it("should return false for unsupported models", () => { | |
| 304 | + expect(supportsFn("deepseek/deepseek-chat")).toBe(false); | |
| 305 | + expect(supportsFn("meta-llama/llama-2-7b")).toBe(false); | |
| 306 | + expect(supportsFn("qwen/qwen-2.0-7b")).toBe(false); | |
| 307 | + expect(supportsFn("openai/gpt-4")).toBe(false); | |
| 308 | + }); | |
| 309 | + }); | |
| 310 | + | |
| 283 | 311 | describe("openrouter", () => { |
| 284 | 312 | const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"]; |
| 285 | 313 | |
| @@ -297,6 +325,7 @@ | ||
| 297 | 325 | expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false); |
| 298 | 326 | expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false); |
| 299 | 327 | expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false); |
| 328 | + expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false); | |
| 300 | 329 | }); |
| 301 | 330 | |
| 302 | 331 | it("should handle non-existent provider", () => { |
modified core/llm/toolSupport.ts +32 −0
| @@ -124,6 +124,7 @@ | ||
| 124 | 124 | "nova-pro", |
| 125 | 125 | "nova-micro", |
| 126 | 126 | "nova-premier", |
| 127 | + "gpt-oss", | |
| 127 | 128 | ].some((part) => model.toLowerCase().includes(part)) |
| 128 | 129 | ) { |
| 129 | 130 | return true; |
| @@ -302,6 +303,7 @@ | ||
| 302 | 303 | "meta-llama/llama-3-70b-instruct", |
| 303 | 304 | "arcee-ai/caller-large", |
| 304 | 305 | "nousresearch/hermes-3-llama-3.1-70b", |
| 306 | + "moonshotai/kimi-k2", | |
| 305 | 307 | ]; |
| 306 | 308 | for (const model of specificModels) { |
| 307 | 309 | if (model.toLowerCase() === model) { |
| @@ -332,6 +334,36 @@ | ||
| 332 | 334 | return true; |
| 333 | 335 | } |
| 334 | 336 | |
| 337 | + return false; | |
| 338 | + }, | |
| 339 | + novita: (model) => { | |
| 340 | + const lower = model.toLowerCase(); | |
| 341 | + | |
| 342 | + // Exact match models | |
| 343 | + const exactMatches = [ | |
| 344 | + "deepseek/deepseek-r1-0528", | |
| 345 | + "deepseek/deepseek-r1-turbo", | |
| 346 | + "deepseek/deepseek-v3-0324", | |
| 347 | + "deepseek/deepseek-v3-turbo", | |
| 348 | + "meta-llama/llama-3.3-70b-instruct", | |
| 349 | + "qwen/qwen-2.5-72b-instruct", | |
| 350 | + "zai-org/glm-4.5", | |
| 351 | + "moonshotai/kimi-k2-instruct", | |
| 352 | + ]; | |
| 353 | + | |
| 354 | + if (exactMatches.includes(lower)) { | |
| 355 | + return true; | |
| 356 | + } | |
| 357 | + | |
| 358 | + // Prefix match models | |
| 359 | + const prefixMatches = ["qwen/qwen3", "openai/gpt-oss"]; | |
| 360 | + | |
| 361 | + for (const prefix of prefixMatches) { | |
| 362 | + if (lower.startsWith(prefix)) { | |
| 363 | + return true; | |
| 364 | + } | |
| 365 | + } | |
| 366 | + | |
| 335 | 367 | return false; |
| 336 | 368 | }, |
| 337 | 369 | }; |
modified core/nextEdit/NextEditProvider.ts +140 −596
| @@ -1,15 +1,6 @@ | ||
| 1 | -import * as path from "path"; | |
| 2 | 1 | import { v4 as uuidv4 } from "uuid"; |
| 3 | 2 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 4 | -import { | |
| 5 | - ChatMessage, | |
| 6 | - DiffLine, | |
| 7 | - IDE, | |
| 8 | - ILLM, | |
| 9 | - Position, | |
| 10 | - Range, | |
| 11 | - RangeInFile, | |
| 12 | -} from "../index.js"; | |
| 3 | +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; | |
| 13 | 4 | import OpenAI from "../llm/llms/OpenAI.js"; |
| 14 | 5 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; |
| 15 | 6 | |
| @@ -18,10 +9,7 @@ | ||
| 18 | 9 | import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; |
| 19 | 10 | import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; |
| 20 | 11 | import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; |
| 21 | -import { | |
| 22 | - getAllSnippetsWithoutRace, | |
| 23 | - SnippetPayload, | |
| 24 | -} from "../autocomplete/snippets/index.js"; | |
| 12 | +import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; | |
| 25 | 13 | import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; |
| 26 | 14 | import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; |
| 27 | 15 | import { getAst } from "../autocomplete/util/ast.js"; |
| @@ -29,38 +17,23 @@ | ||
| 29 | 17 | import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; |
| 30 | 18 | import { HelperVars } from "../autocomplete/util/HelperVars.js"; |
| 31 | 19 | import { AutocompleteInput } from "../autocomplete/util/types.js"; |
| 32 | -import { myersDiff } from "../diff/myers.js"; | |
| 20 | +import { isSecurityConcern } from "../indexing/ignore.js"; | |
| 33 | 21 | import { modelSupportsNextEdit } from "../llm/autodetect.js"; |
| 34 | -import { NEXT_EDIT_MODELS } from "../llm/constants.js"; | |
| 35 | 22 | import { countTokens } from "../llm/countTokens.js"; |
| 36 | 23 | import { localPathOrUriToPath } from "../util/pathToUri.js"; |
| 37 | -import { | |
| 38 | - INSTINCT_SYSTEM_PROMPT, | |
| 39 | - MERCURY_SYSTEM_PROMPT, | |
| 40 | - MODEL_WINDOW_SIZES, | |
| 41 | - UNIQUE_TOKEN, | |
| 42 | -} from "./constants.js"; | |
| 43 | 24 | import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; |
| 44 | -import { | |
| 45 | - calculateFinalCursorPosition, | |
| 46 | - DiffGroup, | |
| 47 | - groupDiffLines, | |
| 48 | -} from "./diff/diff.js"; | |
| 49 | 25 | import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; |
| 50 | 26 | import { NextEditLoggingService } from "./NextEditLoggingService.js"; |
| 51 | 27 | import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; |
| 28 | +import { NextEditProviderFactory } from "./NextEditProviderFactory.js"; | |
| 29 | +import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; | |
| 52 | 30 | import { |
| 53 | - renderDefaultSystemPrompt, | |
| 54 | - renderDefaultUserPrompt, | |
| 55 | - renderPrompt, | |
| 56 | -} from "./templating/NextEditPromptEngine.js"; | |
| 57 | -import { | |
| 31 | + ModelSpecificContext, | |
| 58 | 32 | NextEditOutcome, |
| 59 | 33 | Prompt, |
| 60 | 34 | PromptMetadata, |
| 61 | 35 | RecentlyEditedRange, |
| 62 | 36 | } from "./types.js"; |
| 63 | -import { isWhitespaceOnlyDeletion } from "./utils.js"; | |
| 64 | 37 | |
| 65 | 38 | const autocompleteCache = AutocompleteLruCache.get(); |
| 66 | 39 | |
| @@ -91,6 +64,9 @@ | ||
| 91 | 64 | private previousCompletions: NextEditOutcome[] = []; |
| 92 | 65 | // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; |
| 93 | 66 | |
| 67 | + // Model-specific provider instance. | |
| 68 | + private modelProvider: BaseNextEditProvider | null = null; | |
| 69 | + | |
| 94 | 70 | private constructor( |
| 95 | 71 | private readonly configHandler: ConfigHandler, |
| 96 | 72 | private readonly ide: IDE, |
| @@ -285,6 +261,9 @@ | ||
| 285 | 261 | usingFullFileDiff: boolean; |
| 286 | 262 | }, |
| 287 | 263 | ): Promise<NextEditOutcome | undefined> { |
| 264 | + if (isSecurityConcern(input.filepath)) { | |
| 265 | + return undefined; | |
| 266 | + } | |
| 288 | 267 | try { |
| 289 | 268 | this.previousRequest = input; |
| 290 | 269 | const { |
| @@ -294,28 +273,23 @@ | ||
| 294 | 273 | } = await this._initializeCompletionRequest(input, token); |
| 295 | 274 | if (!helper) return undefined; |
| 296 | 275 | |
| 276 | + // Create model-specific provider based on the model name. | |
| 277 | + this.modelProvider = NextEditProviderFactory.createProvider( | |
| 278 | + helper.modelName, | |
| 279 | + ); | |
| 280 | + | |
| 297 | 281 | const { editableRegionStartLine, editableRegionEndLine, prompts } = |
| 298 | 282 | await this._generatePrompts(helper, opts); |
| 299 | 283 | |
| 300 | - if (this.endpointType === "default") { | |
| 301 | - return await this._handleDefaultEndpointCompletion( | |
| 302 | - helper, | |
| 303 | - prompts, | |
| 304 | - abortToken, | |
| 305 | - startTime, | |
| 306 | - editableRegionEndLine, | |
| 307 | - ); | |
| 308 | - } else { | |
| 309 | - return await this._handleFineTunedEndpointCompletion( | |
| 310 | - helper, | |
| 311 | - prompts, | |
| 312 | - abortToken, | |
| 313 | - startTime, | |
| 314 | - editableRegionStartLine, | |
| 315 | - editableRegionEndLine, | |
| 316 | - opts, | |
| 317 | - ); | |
| 318 | - } | |
| 284 | + return await this._handleCompletion( | |
| 285 | + helper, | |
| 286 | + prompts, | |
| 287 | + abortToken, | |
| 288 | + startTime, | |
| 289 | + editableRegionStartLine, | |
| 290 | + editableRegionEndLine, | |
| 291 | + opts, | |
| 292 | + ); | |
| 319 | 293 | } catch (e: any) { |
| 320 | 294 | this.onError(e); |
| 321 | 295 | } finally { |
| @@ -331,7 +305,7 @@ | ||
| 331 | 305 | startTime: number; |
| 332 | 306 | helper: HelperVars | undefined; |
| 333 | 307 | }> { |
| 334 | - // Create abort signal if not given. | |
| 308 | + // Create abort signal if not given | |
| 335 | 309 | if (!token) { |
| 336 | 310 | const controller = this.loggingService.createAbortController( |
| 337 | 311 | input.completionId, |
| @@ -341,7 +315,7 @@ | ||
| 341 | 315 | const startTime = Date.now(); |
| 342 | 316 | const options = await this._getAutocompleteOptions(); |
| 343 | 317 | |
| 344 | - // Debounce. | |
| 318 | + // Debounce | |
| 345 | 319 | if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { |
| 346 | 320 | return { token, startTime, helper: undefined }; |
| 347 | 321 | } |
| @@ -351,9 +325,7 @@ | ||
| 351 | 325 | return { token, startTime, helper: undefined }; |
| 352 | 326 | } |
| 353 | 327 | |
| 354 | - // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts. | |
| 355 | - // For other editors, this check should be done in their respective config reloaders. | |
| 356 | - // This is left for a final check. | |
| 328 | + // Check model capabilities | |
| 357 | 329 | if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) { |
| 358 | 330 | console.error(`${llm.model} is not capable of next edit.`); |
| 359 | 331 | return { token, startTime, helper: undefined }; |
| @@ -383,6 +355,10 @@ | ||
| 383 | 355 | editableRegionEndLine: number; |
| 384 | 356 | prompts: Prompt[]; |
| 385 | 357 | }> { |
| 358 | + if (!this.modelProvider) { | |
| 359 | + throw new Error("Model provider not initialized"); | |
| 360 | + } | |
| 361 | + | |
| 386 | 362 | const [snippetPayload, workspaceDirs] = await Promise.all([ |
| 387 | 363 | getAllSnippetsWithoutRace({ |
| 388 | 364 | helper, |
| @@ -393,56 +369,118 @@ | ||
| 393 | 369 | this.ide.getWorkspaceDirs(), |
| 394 | 370 | ]); |
| 395 | 371 | |
| 396 | - const modelName = helper.modelName.includes( | |
| 397 | - NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, | |
| 398 | - ) | |
| 399 | - ? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT | |
| 400 | - : helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) | |
| 401 | - ? NEXT_EDIT_MODELS.MERCURY_CODER | |
| 402 | - : NEXT_EDIT_MODELS.INSTINCT; | |
| 403 | - | |
| 372 | + // Calculate editable region based on model and options. | |
| 404 | 373 | const { editableRegionStartLine, editableRegionEndLine } = |
| 405 | - opts?.usingFullFileDiff | |
| 406 | - ? this._calculateOptimalEditableRegion(helper, "tokenizer") | |
| 407 | - : { | |
| 408 | - editableRegionStartLine: Math.max( | |
| 409 | - helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin, | |
| 410 | - 0, | |
| 411 | - ), | |
| 412 | - editableRegionEndLine: Math.min( | |
| 413 | - helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin, | |
| 414 | - helper.fileLines.length - 1, | |
| 415 | - ), | |
| 416 | - }; | |
| 417 | - | |
| 418 | - // const editableRegionStartLine = opts?.usingFullFileDiff | |
| 419 | - // ? 0 | |
| 420 | - // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); | |
| 421 | - | |
| 422 | - // const editableRegionEndLine = opts?.usingFullFileDiff | |
| 423 | - // ? helper.fileLines.length - 1 | |
| 424 | - // : Math.min( | |
| 425 | - // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, | |
| 426 | - // helper.fileLines.length - 1, | |
| 427 | - // ); | |
| 428 | - | |
| 429 | - const prompts: Prompt[] = []; | |
| 430 | - | |
| 431 | - if (this.endpointType === "default") { | |
| 432 | - prompts.push(renderDefaultSystemPrompt()); | |
| 433 | - prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); | |
| 374 | + this.modelProvider.calculateEditableRegion( | |
| 375 | + helper, | |
| 376 | + opts?.usingFullFileDiff ?? false, | |
| 377 | + ); | |
| 378 | + | |
| 379 | + // Build context for model-specific prompt generation. | |
| 380 | + const context: ModelSpecificContext = { | |
| 381 | + helper, | |
| 382 | + snippetPayload, | |
| 383 | + editableRegionStartLine, | |
| 384 | + editableRegionEndLine, | |
| 385 | + diffContext: this.diffContext, | |
| 386 | + autocompleteContext: this.autocompleteContext, | |
| 387 | + historyDiff: createDiff({ | |
| 388 | + beforeContent: | |
| 389 | + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( | |
| 390 | + localPathOrUriToPath(helper.filepath), | |
| 391 | + ) ?? "", | |
| 392 | + afterContent: helper.fileContents, | |
| 393 | + filePath: helper.filepath, | |
| 394 | + diffType: DiffFormatType.Unified, | |
| 395 | + contextLines: 3, | |
| 396 | + }), | |
| 397 | + }; | |
| 398 | + | |
| 399 | + const prompts = await this.modelProvider.generatePrompts(context); | |
| 400 | + | |
| 401 | + this.promptMetadata = this.modelProvider.buildPromptMetadata(context); | |
| 402 | + | |
| 403 | + return { editableRegionStartLine, editableRegionEndLine, prompts }; | |
| 404 | + } | |
| 405 | + | |
| 406 | + private async _handleCompletion( | |
| 407 | + helper: HelperVars, | |
| 408 | + prompts: Prompt[], | |
| 409 | + token: AbortSignal, | |
| 410 | + startTime: number, | |
| 411 | + editableRegionStartLine: number, | |
| 412 | + editableRegionEndLine: number, | |
| 413 | + opts?: { | |
| 414 | + withChain: boolean; | |
| 415 | + usingFullFileDiff: boolean; | |
| 416 | + }, | |
| 417 | + ): Promise<NextEditOutcome | undefined> { | |
| 418 | + if (!this.modelProvider) { | |
| 419 | + throw new Error("Model provider not initialized"); | |
| 420 | + } | |
| 421 | + | |
| 422 | + const llm = await this._prepareLlm(); | |
| 423 | + if (!llm) return undefined; | |
| 424 | + | |
| 425 | + // Inject unique token if needed (for Mercury models). | |
| 426 | + if (this.modelProvider.shouldInjectUniqueToken()) { | |
| 427 | + const uniqueToken = this.modelProvider.getUniqueToken(); | |
| 428 | + if (uniqueToken) { | |
| 429 | + const lastPrompt = prompts[prompts.length - 1]; | |
| 430 | + if (lastPrompt && typeof lastPrompt.content === "string") { | |
| 431 | + lastPrompt.content += uniqueToken; | |
| 432 | + } | |
| 433 | + } | |
| 434 | + } | |
| 435 | + | |
| 436 | + // Send prompts to LLM (using only user prompt for fine-tuned models). | |
| 437 | + const msg: ChatMessage = await llm.chat([prompts[1]], token, { | |
| 438 | + stream: false, | |
| 439 | + }); | |
| 440 | + | |
| 441 | + if (typeof msg.content !== "string") { | |
| 442 | + return undefined; | |
| 443 | + } | |
| 444 | + | |
| 445 | + // Extract completion using model-specific logic. | |
| 446 | + const nextCompletion = this.modelProvider.extractCompletion(msg.content); | |
| 447 | + | |
| 448 | + let outcome: NextEditOutcome | undefined; | |
| 449 | + | |
| 450 | + // Handle based on diff type. | |
| 451 | + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { | |
| 452 | + outcome = await this.modelProvider.handlePartialFileDiff( | |
| 453 | + helper, | |
| 454 | + editableRegionStartLine, | |
| 455 | + editableRegionEndLine, | |
| 456 | + startTime, | |
| 457 | + llm, | |
| 458 | + nextCompletion, | |
| 459 | + this.promptMetadata!, | |
| 460 | + this.ide, | |
| 461 | + ); | |
| 434 | 462 | } else { |
| 435 | - prompts.push( | |
| 436 | - ...(await this._generateFineTunedPrompts( | |
| 437 | - helper, | |
| 438 | - snippetPayload, | |
| 439 | - editableRegionStartLine, | |
| 440 | - editableRegionEndLine, | |
| 441 | - )), | |
| 463 | + outcome = await this.modelProvider.handleFullFileDiff( | |
| 464 | + helper, | |
| 465 | + editableRegionStartLine, | |
| 466 | + editableRegionEndLine, | |
| 467 | + startTime, | |
| 468 | + llm, | |
| 469 | + nextCompletion, | |
| 470 | + this.promptMetadata!, | |
| 471 | + this.ide, | |
| 442 | 472 | ); |
| 443 | 473 | } |
| 444 | 474 | |
| 445 | - return { editableRegionStartLine, editableRegionEndLine, prompts }; | |
| 475 | + if (outcome) { | |
| 476 | + // Handle NextEditProvider-specific state | |
| 477 | + this.previousCompletions.push(outcome); | |
| 478 | + | |
| 479 | + // Mark as displayed for JetBrains | |
| 480 | + await this._markDisplayedIfJetBrains(helper.input.completionId, outcome); | |
| 481 | + } | |
| 482 | + | |
| 483 | + return outcome; | |
| 446 | 484 | } |
| 447 | 485 | |
| 448 | 486 | private _calculateOptimalEditableRegion( |
| @@ -536,500 +574,6 @@ | ||
| 536 | 574 | }; |
| 537 | 575 | } |
| 538 | 576 | |
| 539 | - private async _generateFineTunedPrompts( | |
| 540 | - helper: HelperVars, | |
| 541 | - snippetPayload: SnippetPayload, | |
| 542 | - editableRegionStartLine: number, | |
| 543 | - editableRegionEndLine: number, | |
| 544 | - ): Promise<Prompt[]> { | |
| 545 | - const historyDiff = createDiff({ | |
| 546 | - beforeContent: | |
| 547 | - DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( | |
| 548 | - localPathOrUriToPath(helper.filepath), | |
| 549 | - ) ?? "", | |
| 550 | - afterContent: helper.fileContents, | |
| 551 | - filePath: helper.filepath, | |
| 552 | - diffType: DiffFormatType.Unified, | |
| 553 | - contextLines: 3, | |
| 554 | - }); | |
| 555 | - | |
| 556 | - const modelName = helper.modelName; | |
| 557 | - let ctx: any; | |
| 558 | - | |
| 559 | - if ( | |
| 560 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || | |
| 561 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) | |
| 562 | - ) { | |
| 563 | - ctx = { | |
| 564 | - recentlyViewedCodeSnippets: | |
| 565 | - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ | |
| 566 | - filepath: snip.filepath, | |
| 567 | - content: snip.content, | |
| 568 | - })) ?? [], | |
| 569 | - currentFileContent: helper.fileContents, | |
| 570 | - editableRegionStartLine, | |
| 571 | - editableRegionEndLine, | |
| 572 | - editDiffHistory: this.diffContext, | |
| 573 | - currentFilePath: helper.filepath, | |
| 574 | - }; | |
| 575 | - } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { | |
| 576 | - // Calculate the window around the cursor position (25 lines above and below). | |
| 577 | - const windowStart = Math.max(0, helper.pos.line - 25); | |
| 578 | - const windowEnd = Math.min( | |
| 579 | - helper.fileLines.length - 1, | |
| 580 | - helper.pos.line + 25, | |
| 581 | - ); | |
| 582 | - | |
| 583 | - // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). | |
| 584 | - // const actualEditableStart = Math.max( | |
| 585 | - // 0, | |
| 586 | - // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, | |
| 587 | - // ); | |
| 588 | - // const actualEditableEnd = Math.min( | |
| 589 | - // helper.fileLines.length - 1, | |
| 590 | - // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, | |
| 591 | - // ); | |
| 592 | - | |
| 593 | - // Ensure editable region boundaries are within the window. | |
| 594 | - const adjustedEditableStart = Math.max( | |
| 595 | - windowStart, | |
| 596 | - editableRegionStartLine, | |
| 597 | - ); | |
| 598 | - const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine); | |
| 599 | - ctx = { | |
| 600 | - contextSnippets: this.autocompleteContext, | |
| 601 | - currentFileContent: helper.fileContents, | |
| 602 | - windowStart, | |
| 603 | - windowEnd, | |
| 604 | - editableRegionStartLine: adjustedEditableStart, | |
| 605 | - editableRegionEndLine: adjustedEditableEnd, | |
| 606 | - editDiffHistory: this.diffContext, | |
| 607 | - currentFilePath: helper.filepath, | |
| 608 | - languageShorthand: helper.lang.name, | |
| 609 | - }; | |
| 610 | - } else { | |
| 611 | - ctx = {}; | |
| 612 | - } | |
| 613 | - | |
| 614 | - const promptMetadata = await renderPrompt(helper, ctx); | |
| 615 | - this.promptMetadata = promptMetadata; | |
| 616 | - | |
| 617 | - const systemPrompt: Prompt = { | |
| 618 | - role: "system", | |
| 619 | - content: | |
| 620 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || | |
| 621 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) | |
| 622 | - ? MERCURY_SYSTEM_PROMPT | |
| 623 | - : INSTINCT_SYSTEM_PROMPT, | |
| 624 | - }; | |
| 625 | - | |
| 626 | - return [systemPrompt, promptMetadata.prompt]; | |
| 627 | - } | |
| 628 | - | |
| 629 | - private async _handleDefaultEndpointCompletion( | |
| 630 | - helper: HelperVars, | |
| 631 | - prompts: Prompt[], | |
| 632 | - token: AbortSignal, | |
| 633 | - startTime: number, | |
| 634 | - editableRegionEndLine: number, | |
| 635 | - ): Promise<NextEditOutcome | undefined> { | |
| 636 | - const llm = await this._prepareLlm(); | |
| 637 | - if (!llm) return undefined; | |
| 638 | - | |
| 639 | - const msg: ChatMessage = await llm.chat(prompts, token); | |
| 640 | - | |
| 641 | - if (typeof msg.content === "string") { | |
| 642 | - const nextCompletion = JSON.parse(msg.content).newCode; | |
| 643 | - const finalCursorPos: Position = { | |
| 644 | - line: editableRegionEndLine, | |
| 645 | - character: 0, | |
| 646 | - }; | |
| 647 | - | |
| 648 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 649 | - helper, | |
| 650 | - startTime, | |
| 651 | - llm, | |
| 652 | - promptContent: prompts.join("\n"), | |
| 653 | - completion: nextCompletion, | |
| 654 | - finalCursorPosition: finalCursorPos, | |
| 655 | - editableRegionStartLine: 0, | |
| 656 | - editableRegionEndLine: 0, | |
| 657 | - userEdits: "", | |
| 658 | - userExcerpts: "", | |
| 659 | - originalEditableRange: "", | |
| 660 | - diffLines: [], | |
| 661 | - }); | |
| 662 | - | |
| 663 | - // Mark as displayed for JetBrains extension | |
| 664 | - await this._markDisplayedIfJetBrains( | |
| 665 | - helper.input.completionId, | |
| 666 | - outcomeNext, | |
| 667 | - ); | |
| 668 | - | |
| 669 | - return outcomeNext; | |
| 670 | - } | |
| 671 | - | |
| 672 | - return undefined; | |
| 673 | - } | |
| 674 | - | |
| 675 | - private async _handleFineTunedEndpointCompletion( | |
| 676 | - helper: HelperVars, | |
| 677 | - prompts: Prompt[], | |
| 678 | - token: AbortSignal, | |
| 679 | - startTime: number, | |
| 680 | - editableRegionStartLine: number, | |
| 681 | - editableRegionEndLine: number, | |
| 682 | - opts?: { | |
| 683 | - withChain: boolean; | |
| 684 | - usingFullFileDiff: boolean; | |
| 685 | - }, | |
| 686 | - ): Promise<NextEditOutcome | undefined> { | |
| 687 | - const llm = await this._prepareLlm(); | |
| 688 | - if (!llm) return undefined; | |
| 689 | - | |
| 690 | - // Check for mercury models, and inject unique token for next edit. | |
| 691 | - // Capture the unique tokens in llm Inception.ts and apis Inception.ts | |
| 692 | - const modelName = helper.modelName; | |
| 693 | - if ( | |
| 694 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || | |
| 695 | - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) | |
| 696 | - ) { | |
| 697 | - // Inject the unique token to the last prompt's content. | |
| 698 | - const lastPrompt = prompts[prompts.length - 1]; | |
| 699 | - if (lastPrompt && typeof lastPrompt.content === "string") { | |
| 700 | - lastPrompt.content += UNIQUE_TOKEN; | |
| 701 | - } | |
| 702 | - } | |
| 703 | - | |
| 704 | - const msg: ChatMessage = await llm.chat([prompts[1]], token, { | |
| 705 | - stream: false, | |
| 706 | - }); | |
| 707 | - | |
| 708 | - if (typeof msg.content !== "string") { | |
| 709 | - return undefined; | |
| 710 | - } | |
| 711 | - | |
| 712 | - // NOTE: Keep this in case there is a change in spec. | |
| 713 | - // const nextCompletion = | |
| 714 | - // msg.content | |
| 715 | - // .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] | |
| 716 | - // .replace(/\n$/, "") ?? msg.content; | |
| 717 | - const nextCompletion = msg.content.slice( | |
| 718 | - msg.content.indexOf("\`\`\`\n") + "\'\'\'\n".length, | |
| 719 | - msg.content.lastIndexOf("\n\n\`\`\`"), | |
| 720 | - ); | |
| 721 | - | |
| 722 | - if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { | |
| 723 | - return await this._handlePartialFileDiff( | |
| 724 | - // we could use fillFileDiff | |
| 725 | - helper, | |
| 726 | - editableRegionStartLine, | |
| 727 | - editableRegionEndLine, | |
| 728 | - startTime, | |
| 729 | - llm, | |
| 730 | - nextCompletion, | |
| 731 | - ); | |
| 732 | - } else { | |
| 733 | - return await this._handleFullFileDiff( | |
| 734 | - helper, | |
| 735 | - editableRegionStartLine, | |
| 736 | - editableRegionEndLine, | |
| 737 | - startTime, | |
| 738 | - llm, | |
| 739 | - nextCompletion, | |
| 740 | - ); | |
| 741 | - } | |
| 742 | - } | |
| 743 | - | |
| 744 | - private async _handlePartialFileDiff( | |
| 745 | - helper: HelperVars, | |
| 746 | - editableRegionStartLine: number, | |
| 747 | - editableRegionEndLine: number, | |
| 748 | - startTime: number, | |
| 749 | - llm: ILLM, | |
| 750 | - nextCompletion: string, | |
| 751 | - ): Promise<NextEditOutcome | undefined> { | |
| 752 | - const oldEditRangeSlice = helper.fileContents | |
| 753 | - .split("\n") | |
| 754 | - .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 755 | - .join("\n"); | |
| 756 | - | |
| 757 | - const finalCursorPos = calculateFinalCursorPosition( | |
| 758 | - helper.pos, | |
| 759 | - editableRegionStartLine, | |
| 760 | - oldEditRangeSlice, | |
| 761 | - nextCompletion, | |
| 762 | - ); | |
| 763 | - | |
| 764 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 765 | - helper, | |
| 766 | - startTime, | |
| 767 | - llm, | |
| 768 | - promptContent: this.promptMetadata!.prompt.content, | |
| 769 | - completion: nextCompletion, | |
| 770 | - finalCursorPosition: finalCursorPos, | |
| 771 | - editableRegionStartLine, | |
| 772 | - editableRegionEndLine, | |
| 773 | - userEdits: this.promptMetadata!.userEdits, | |
| 774 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 775 | - originalEditableRange: oldEditRangeSlice, | |
| 776 | - diffLines: [], | |
| 777 | - }); | |
| 778 | - | |
| 779 | - this.previousCompletions.push(outcomeNext); | |
| 780 | - | |
| 781 | - // Mark as displayed for JetBrains extension | |
| 782 | - await this._markDisplayedIfJetBrains( | |
| 783 | - helper.input.completionId, | |
| 784 | - outcomeNext, | |
| 785 | - ); | |
| 786 | - | |
| 787 | - return outcomeNext; | |
| 788 | - } | |
| 789 | - | |
| 790 | - private async _handleFullFileDiff( | |
| 791 | - helper: HelperVars, | |
| 792 | - editableRegionStartLine: number, | |
| 793 | - editableRegionEndLine: number, | |
| 794 | - startTime: number, | |
| 795 | - llm: ILLM, | |
| 796 | - nextCompletion: string, | |
| 797 | - ): Promise<NextEditOutcome | undefined> { | |
| 798 | - const fileSlice = helper.fileLines | |
| 799 | - .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 800 | - .join("\n"); | |
| 801 | - const diffLines = myersDiff(fileSlice, nextCompletion); | |
| 802 | - const diffGroups = groupDiffLines( | |
| 803 | - diffLines, | |
| 804 | - editableRegionStartLine, | |
| 805 | - 5, | |
| 806 | - ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); | |
| 807 | - const currentLine = helper.pos.line; | |
| 808 | - const prefetchQueue = PrefetchQueue.getInstance(); | |
| 809 | - | |
| 810 | - // Process diff groups and find the one containing the cursor | |
| 811 | - const cursorLocalDiffGroup = await this._processDiffGroups( | |
| 812 | - diffGroups, | |
| 813 | - currentLine, | |
| 814 | - helper, | |
| 815 | - startTime, | |
| 816 | - llm, | |
| 817 | - prefetchQueue, | |
| 818 | - ); | |
| 819 | - | |
| 820 | - // Handle the diff group containing the cursor if found | |
| 821 | - if (cursorLocalDiffGroup) { | |
| 822 | - return await this._createOutcomeFromDiffGroup( | |
| 823 | - cursorLocalDiffGroup, | |
| 824 | - helper, | |
| 825 | - startTime, | |
| 826 | - llm, | |
| 827 | - helper.input.completionId, | |
| 828 | - true, | |
| 829 | - ); | |
| 830 | - // } else if (diffGroups.length > 0) { | |
| 831 | - // // Fallback to first diff group if cursor's group not found | |
| 832 | - // return await this._createOutcomeFromDiffGroup( | |
| 833 | - // diffGroups[0], | |
| 834 | - // helper, | |
| 835 | - // startTime, | |
| 836 | - // llm, | |
| 837 | - // helper.input.completionId, | |
| 838 | - // false, | |
| 839 | - // ); | |
| 840 | - } | |
| 841 | - | |
| 842 | - return undefined; | |
| 843 | - } | |
| 844 | - | |
| 845 | - private async _processDiffGroups( | |
| 846 | - diffGroups: DiffGroup[], | |
| 847 | - currentLine: number, | |
| 848 | - helper: HelperVars, | |
| 849 | - startTime: number, | |
| 850 | - llm: ILLM, | |
| 851 | - prefetchQueue: PrefetchQueue, | |
| 852 | - ): Promise<DiffGroup | undefined> { | |
| 853 | - let cursorGroup: DiffGroup | undefined; | |
| 854 | - | |
| 855 | - console.log("diffGroups:"); | |
| 856 | - console.log(diffGroups); | |
| 857 | - | |
| 858 | - for (const group of diffGroups) { | |
| 859 | - if (currentLine >= group.startLine && currentLine <= group.endLine) { | |
| 860 | - cursorGroup = group; | |
| 861 | - } else { | |
| 862 | - // Add non-cursor groups to prefetch queue | |
| 863 | - await this._addDiffGroupToPrefetchQueue( | |
| 864 | - group, | |
| 865 | - helper, | |
| 866 | - startTime, | |
| 867 | - llm, | |
| 868 | - prefetchQueue, | |
| 869 | - ); | |
| 870 | - } | |
| 871 | - } | |
| 872 | - | |
| 873 | - return cursorGroup; | |
| 874 | - } | |
| 875 | - | |
| 876 | - private async _addDiffGroupToPrefetchQueue( | |
| 877 | - group: DiffGroup, | |
| 878 | - helper: HelperVars, | |
| 879 | - startTime: number, | |
| 880 | - llm: ILLM, | |
| 881 | - prefetchQueue: PrefetchQueue, | |
| 882 | - ): Promise<void> { | |
| 883 | - const groupContent = group.lines | |
| 884 | - .filter((l) => l.type !== "old") | |
| 885 | - .map((l) => l.line) | |
| 886 | - .join("\n"); | |
| 887 | - | |
| 888 | - // Create a range for this diff group | |
| 889 | - const rangeInFile: RangeInFile = { | |
| 890 | - filepath: helper.filepath, | |
| 891 | - range: { | |
| 892 | - start: { line: group.startLine, character: 0 }, | |
| 893 | - end: { | |
| 894 | - line: group.endLine, | |
| 895 | - character: group.lines[group.lines.length - 1].line.length, | |
| 896 | - }, | |
| 897 | - }, | |
| 898 | - }; | |
| 899 | - | |
| 900 | - const originalContent = group.lines | |
| 901 | - .filter((l) => l.type !== "new") | |
| 902 | - .map((l) => l.line) | |
| 903 | - .join("\n"); | |
| 904 | - | |
| 905 | - // Build outcome for this diff group | |
| 906 | - const groupOutcome = await this._createNextEditOutcome({ | |
| 907 | - helper, | |
| 908 | - startTime, | |
| 909 | - llm, | |
| 910 | - promptContent: this.promptMetadata!.prompt.content, | |
| 911 | - completion: groupContent, | |
| 912 | - finalCursorPosition: { | |
| 913 | - line: group.endLine, | |
| 914 | - character: group.lines[group.lines.length - 1].line.length, | |
| 915 | - }, | |
| 916 | - editableRegionStartLine: group.startLine, | |
| 917 | - editableRegionEndLine: group.endLine, | |
| 918 | - userEdits: this.promptMetadata!.userEdits, | |
| 919 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 920 | - originalEditableRange: originalContent, | |
| 921 | - cursorPosition: { line: group.startLine, character: 0 }, | |
| 922 | - completionId: uuidv4(), // Generate a new ID for this prefetched item | |
| 923 | - diffLines: group.lines, | |
| 924 | - }); | |
| 925 | - | |
| 926 | - // Add to prefetch queue | |
| 927 | - prefetchQueue.enqueueProcessed({ | |
| 928 | - location: rangeInFile, | |
| 929 | - outcome: groupOutcome, | |
| 930 | - }); | |
| 931 | - } | |
| 932 | - | |
| 933 | - private async _createOutcomeFromDiffGroup( | |
| 934 | - diffGroup: DiffGroup, | |
| 935 | - helper: HelperVars, | |
| 936 | - startTime: number, | |
| 937 | - llm: ILLM, | |
| 938 | - completionId: string, | |
| 939 | - isCurrentCursorGroup: boolean, | |
| 940 | - ): Promise<NextEditOutcome> { | |
| 941 | - const groupContent = diffGroup.lines | |
| 942 | - .filter((l) => l.type !== "old") | |
| 943 | - .map((line) => line.line) | |
| 944 | - .join("\n"); | |
| 945 | - | |
| 946 | - const originalContent = diffGroup.lines | |
| 947 | - .filter((l) => l.type !== "new") | |
| 948 | - .map((l) => l.line) | |
| 949 | - .join("\n"); | |
| 950 | - | |
| 951 | - // Use the actual cursor position if this is the group containing the cursor | |
| 952 | - // Otherwise use the start of the diff group | |
| 953 | - const cursorPos = isCurrentCursorGroup | |
| 954 | - ? helper.pos | |
| 955 | - : { line: diffGroup.startLine, character: 0 }; | |
| 956 | - | |
| 957 | - const finalCursorPos = calculateFinalCursorPosition( | |
| 958 | - cursorPos, | |
| 959 | - diffGroup.startLine, | |
| 960 | - originalContent, | |
| 961 | - groupContent, | |
| 962 | - ); | |
| 963 | - | |
| 964 | - const outcomeNext = await this._createNextEditOutcome({ | |
| 965 | - helper, | |
| 966 | - startTime, | |
| 967 | - llm, | |
| 968 | - promptContent: this.promptMetadata!.prompt.content, | |
| 969 | - completion: groupContent, | |
| 970 | - finalCursorPosition: finalCursorPos, | |
| 971 | - editableRegionStartLine: diffGroup.startLine, | |
| 972 | - editableRegionEndLine: diffGroup.endLine, | |
| 973 | - userEdits: this.promptMetadata!.userEdits, | |
| 974 | - userExcerpts: this.promptMetadata!.userExcerpts, | |
| 975 | - originalEditableRange: originalContent, | |
| 976 | - cursorPosition: cursorPos, | |
| 977 | - completionId, | |
| 978 | - diffLines: diffGroup.lines, | |
| 979 | - }); | |
| 980 | - | |
| 981 | - this.previousCompletions.push(outcomeNext); | |
| 982 | - | |
| 983 | - // Mark as displayed for JetBrains | |
| 984 | - await this._markDisplayedIfJetBrains(completionId, outcomeNext); | |
| 985 | - | |
| 986 | - return outcomeNext; | |
| 987 | - } | |
| 988 | - | |
| 989 | - private async _createNextEditOutcome(outcomeCtx: { | |
| 990 | - helper: HelperVars; | |
| 991 | - startTime: number; | |
| 992 | - llm: ILLM; | |
| 993 | - promptContent: string; | |
| 994 | - completion: string; | |
| 995 | - finalCursorPosition: Position; | |
| 996 | - editableRegionStartLine: number; | |
| 997 | - editableRegionEndLine: number; | |
| 998 | - userEdits: string; | |
| 999 | - userExcerpts: string; | |
| 1000 | - originalEditableRange: string; | |
| 1001 | - cursorPosition?: Position; | |
| 1002 | - completionId?: string; | |
| 1003 | - diffLines: DiffLine[]; | |
| 1004 | - }): Promise<NextEditOutcome> { | |
| 1005 | - return { | |
| 1006 | - elapsed: Date.now() - outcomeCtx.startTime, | |
| 1007 | - modelProvider: outcomeCtx.llm.underlyingProviderName, | |
| 1008 | - modelName: outcomeCtx.llm.model + ":zetaDataset", | |
| 1009 | - completionOptions: null, | |
| 1010 | - completionId: | |
| 1011 | - outcomeCtx.completionId || outcomeCtx.helper.input.completionId, | |
| 1012 | - gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath), | |
| 1013 | - uniqueId: await this.ide.getUniqueId(), | |
| 1014 | - timestamp: Date.now(), | |
| 1015 | - fileUri: outcomeCtx.helper.filepath, | |
| 1016 | - workspaceDirUri: | |
| 1017 | - outcomeCtx.helper.workspaceUris[0] ?? | |
| 1018 | - path.dirname(outcomeCtx.helper.filepath), | |
| 1019 | - prompt: outcomeCtx.promptContent, | |
| 1020 | - userEdits: outcomeCtx.userEdits ?? "", | |
| 1021 | - userExcerpts: outcomeCtx.userExcerpts ?? "", | |
| 1022 | - originalEditableRange: outcomeCtx.originalEditableRange ?? "", | |
| 1023 | - completion: outcomeCtx.completion, | |
| 1024 | - cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, | |
| 1025 | - finalCursorPosition: outcomeCtx.finalCursorPosition, | |
| 1026 | - editableRegionStartLine: outcomeCtx.editableRegionStartLine, | |
| 1027 | - editableRegionEndLine: outcomeCtx.editableRegionEndLine, | |
| 1028 | - diffLines: outcomeCtx.diffLines, | |
| 1029 | - ...outcomeCtx.helper.options, | |
| 1030 | - }; | |
| 1031 | - } | |
| 1032 | - | |
| 1033 | 577 | private async _markDisplayedIfJetBrains( |
| 1034 | 578 | completionId: string, |
| 1035 | 579 | outcome: NextEditOutcome, |
added core/nextEdit/NextEditProviderFactory.ts +16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { NEXT_EDIT_MODELS } from "../llm/constants.js"; | |
| 2 | +import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; | |
| 3 | +import { InstinctProvider } from "./providers/InstinctNextEditProvider.js"; | |
| 4 | +import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js"; | |
| 5 | + | |
| 6 | +export class NextEditProviderFactory { | |
| 7 | + static createProvider(modelName: string): BaseNextEditProvider { | |
| 8 | + if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) { | |
| 9 | + return new MercuryCoderProvider(); | |
| 10 | + } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { | |
| 11 | + return new InstinctProvider(); | |
| 12 | + } else { | |
| 13 | + throw new Error(`Unsupported model: ${modelName}`); | |
| 14 | + } | |
| 15 | + } | |
| 16 | +} |
modified core/nextEdit/constants.ts +0 −4
| @@ -12,10 +12,6 @@ | ||
| 12 | 12 | topMargin: 0, |
| 13 | 13 | bottomMargin: 5, |
| 14 | 14 | }, // mercury coder uses full file diff, so this should be unnecessary |
| 15 | - "mercury-coder-nextedit": { | |
| 16 | - topMargin: 0, | |
| 17 | - bottomMargin: 5, | |
| 18 | - }, // mercury coder nextedit uses full file diff, so this should be unnecessary | |
| 19 | 15 | instinct: { topMargin: 1, bottomMargin: 5 }, |
| 20 | 16 | }; |
| 21 | 17 |
modified core/nextEdit/context/autocompleteContextFetching.ts +5 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | } from "../../autocomplete/util/types"; |
| 12 | 12 | import { ConfigHandler } from "../../config/ConfigHandler"; |
| 13 | 13 | import { IDE, ILLM } from "../../index"; |
| 14 | +import { isSecurityConcern } from "../../indexing/ignore"; | |
| 14 | 15 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters"; |
| 15 | 16 | |
| 16 | 17 | /** |
| @@ -61,6 +62,10 @@ | ||
| 61 | 62 | throw new Error("No config available"); |
| 62 | 63 | } |
| 63 | 64 | |
| 65 | + if (isSecurityConcern(input.filepath)) { | |
| 66 | + throw new Error("File is a security concern, autocomplete disabled"); | |
| 67 | + } | |
| 68 | + | |
| 64 | 69 | // Use provided autocomplete model or fall back to configured autocomplete model |
| 65 | 70 | let finalModel: ILLM; |
| 66 | 71 | let modelNameForTemplating: string; |
added core/nextEdit/providers/BaseNextEditProvider.ts +415 −0
| @@ -0,0 +1,415 @@ | ||
| 1 | +import * as path from "path"; | |
| 2 | +import { v4 as uuidv4 } from "uuid"; | |
| 3 | + | |
| 4 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 5 | +import { myersDiff } from "../../diff/myers.js"; | |
| 6 | +import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js"; | |
| 7 | +import { countTokens } from "../../llm/countTokens.js"; | |
| 8 | +import { | |
| 9 | + calculateFinalCursorPosition, | |
| 10 | + DiffGroup, | |
| 11 | + groupDiffLines, | |
| 12 | +} from "../diff/diff.js"; | |
| 13 | +import { PrefetchQueue } from "../NextEditPrefetchQueue.js"; | |
| 14 | +import { | |
| 15 | + ModelSpecificContext, | |
| 16 | + NextEditOutcome, | |
| 17 | + Prompt, | |
| 18 | + PromptMetadata, | |
| 19 | +} from "../types.js"; | |
| 20 | +import { isWhitespaceOnlyDeletion } from "../utils.js"; | |
| 21 | + | |
| 22 | +export abstract class BaseNextEditProvider { | |
| 23 | + protected readonly modelName: string; | |
| 24 | + | |
| 25 | + constructor(modelName: string) { | |
| 26 | + this.modelName = modelName; | |
| 27 | + } | |
| 28 | + | |
| 29 | + // Leave methods as abstract when you must have the models implement their own versions. | |
| 30 | + abstract getSystemPrompt(): string; | |
| 31 | + abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>; | |
| 32 | + abstract extractCompletion(message: string): string; | |
| 33 | + abstract buildPromptContext(context: ModelSpecificContext): any; | |
| 34 | + abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata; | |
| 35 | + abstract getWindowSize(): { topMargin: number; bottomMargin: number }; | |
| 36 | + abstract calculateEditableRegion( | |
| 37 | + helper: HelperVars, | |
| 38 | + usingFullFileDiff: boolean, | |
| 39 | + ): { | |
| 40 | + editableRegionStartLine: number; | |
| 41 | + editableRegionEndLine: number; | |
| 42 | + }; | |
| 43 | + | |
| 44 | + // Methods that can be used as default fallback. | |
| 45 | + public async handlePartialFileDiff( | |
| 46 | + helper: HelperVars, | |
| 47 | + editableRegionStartLine: number, | |
| 48 | + editableRegionEndLine: number, | |
| 49 | + startTime: number, | |
| 50 | + llm: ILLM, | |
| 51 | + nextCompletion: string, | |
| 52 | + promptMetadata: PromptMetadata, | |
| 53 | + ide: IDE, | |
| 54 | + ): Promise<NextEditOutcome> { | |
| 55 | + const oldEditRangeSlice = helper.fileContents | |
| 56 | + .split("\n") | |
| 57 | + .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 58 | + .join("\n"); | |
| 59 | + | |
| 60 | + const finalCursorPos = calculateFinalCursorPosition( | |
| 61 | + helper.pos, | |
| 62 | + editableRegionStartLine, | |
| 63 | + oldEditRangeSlice, | |
| 64 | + nextCompletion, | |
| 65 | + ); | |
| 66 | + | |
| 67 | + const outcome = await this.createNextEditOutcome({ | |
| 68 | + helper, | |
| 69 | + startTime, | |
| 70 | + llm, | |
| 71 | + promptContent: promptMetadata.prompt.content, | |
| 72 | + completion: nextCompletion, | |
| 73 | + finalCursorPosition: finalCursorPos, | |
| 74 | + editableRegionStartLine, | |
| 75 | + editableRegionEndLine, | |
| 76 | + userEdits: promptMetadata.userEdits, | |
| 77 | + userExcerpts: promptMetadata.userExcerpts, | |
| 78 | + originalEditableRange: oldEditRangeSlice, | |
| 79 | + diffLines: [], | |
| 80 | + ide, | |
| 81 | + }); | |
| 82 | + | |
| 83 | + return outcome; | |
| 84 | + } | |
| 85 | + | |
| 86 | + public async handleFullFileDiff( | |
| 87 | + helper: HelperVars, | |
| 88 | + editableRegionStartLine: number, | |
| 89 | + editableRegionEndLine: number, | |
| 90 | + startTime: number, | |
| 91 | + llm: ILLM, | |
| 92 | + nextCompletion: string, | |
| 93 | + promptMetadata: PromptMetadata, | |
| 94 | + ide: IDE, | |
| 95 | + ): Promise<NextEditOutcome | undefined> { | |
| 96 | + const fileSlice = helper.fileLines | |
| 97 | + .slice(editableRegionStartLine, editableRegionEndLine + 1) | |
| 98 | + .join("\n"); | |
| 99 | + | |
| 100 | + const diffLines = myersDiff(fileSlice, nextCompletion); | |
| 101 | + const diffGroups = groupDiffLines( | |
| 102 | + diffLines, | |
| 103 | + editableRegionStartLine, | |
| 104 | + 5, | |
| 105 | + ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); | |
| 106 | + const currentLine = helper.pos.line; | |
| 107 | + const prefetchQueue = PrefetchQueue.getInstance(); | |
| 108 | + | |
| 109 | + const cursorLocalDiffGroup = await this.processDiffGroups( | |
| 110 | + diffGroups, | |
| 111 | + currentLine, | |
| 112 | + helper, | |
| 113 | + startTime, | |
| 114 | + llm, | |
| 115 | + prefetchQueue, | |
| 116 | + promptMetadata, | |
| 117 | + ide, | |
| 118 | + ); | |
| 119 | + | |
| 120 | + if (cursorLocalDiffGroup) { | |
| 121 | + return await this.createOutcomeFromDiffGroup( | |
| 122 | + cursorLocalDiffGroup, | |
| 123 | + helper, | |
| 124 | + startTime, | |
| 125 | + llm, | |
| 126 | + helper.input.completionId, | |
| 127 | + true, | |
| 128 | + promptMetadata, | |
| 129 | + ide, | |
| 130 | + ); | |
| 131 | + } | |
| 132 | + | |
| 133 | + return undefined; | |
| 134 | + } | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * Process diff groups and find the one containing the cursor. | |
| 138 | + */ | |
| 139 | + private async processDiffGroups( | |
| 140 | + diffGroups: DiffGroup[], | |
| 141 | + currentLine: number, | |
| 142 | + helper: HelperVars, | |
| 143 | + startTime: number, | |
| 144 | + llm: ILLM, | |
| 145 | + prefetchQueue: PrefetchQueue, | |
| 146 | + promptMetadata: PromptMetadata, | |
| 147 | + ide: IDE, | |
| 148 | + ): Promise<DiffGroup | undefined> { | |
| 149 | + let cursorGroup: DiffGroup | undefined; | |
| 150 | + | |
| 151 | + for (const group of diffGroups) { | |
| 152 | + if (currentLine >= group.startLine && currentLine <= group.endLine) { | |
| 153 | + cursorGroup = group; | |
| 154 | + } else { | |
| 155 | + await this.addDiffGroupToPrefetchQueue( | |
| 156 | + group, | |
| 157 | + helper, | |
| 158 | + startTime, | |
| 159 | + llm, | |
| 160 | + prefetchQueue, | |
| 161 | + promptMetadata, | |
| 162 | + ide, | |
| 163 | + ); | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + return cursorGroup; | |
| 168 | + } | |
| 169 | + | |
| 170 | + private async addDiffGroupToPrefetchQueue( | |
| 171 | + group: DiffGroup, | |
| 172 | + helper: HelperVars, | |
| 173 | + startTime: number, | |
| 174 | + llm: ILLM, | |
| 175 | + prefetchQueue: PrefetchQueue, | |
| 176 | + promptMetadata: PromptMetadata, | |
| 177 | + ide: IDE, | |
| 178 | + ): Promise<void> { | |
| 179 | + // Extract lines that are not old. | |
| 180 | + const groupContent = group.lines | |
| 181 | + .filter((l) => l.type !== "old") | |
| 182 | + .map((l) => l.line) | |
| 183 | + .join("\n"); | |
| 184 | + | |
| 185 | + const rangeInFile: RangeInFile = { | |
| 186 | + filepath: helper.filepath, | |
| 187 | + range: { | |
| 188 | + start: { line: group.startLine, character: 0 }, | |
| 189 | + end: { | |
| 190 | + line: group.endLine, | |
| 191 | + character: group.lines[group.lines.length - 1].line.length, | |
| 192 | + }, | |
| 193 | + }, | |
| 194 | + }; | |
| 195 | + | |
| 196 | + // Extract lines that are not new. | |
| 197 | + const originalContent = group.lines | |
| 198 | + .filter((l) => l.type !== "new") | |
| 199 | + .map((l) => l.line) | |
| 200 | + .join("\n"); | |
| 201 | + | |
| 202 | + const groupOutcome = await this.createNextEditOutcome({ | |
| 203 | + helper, | |
| 204 | + startTime, | |
| 205 | + llm, | |
| 206 | + promptContent: promptMetadata.prompt.content, | |
| 207 | + completion: groupContent, | |
| 208 | + finalCursorPosition: { | |
| 209 | + line: group.endLine, | |
| 210 | + character: group.lines[group.lines.length - 1].line.length, | |
| 211 | + }, | |
| 212 | + editableRegionStartLine: group.startLine, | |
| 213 | + editableRegionEndLine: group.endLine, | |
| 214 | + userEdits: promptMetadata.userEdits, | |
| 215 | + userExcerpts: promptMetadata.userExcerpts, | |
| 216 | + originalEditableRange: originalContent, | |
| 217 | + cursorPosition: { line: group.startLine, character: 0 }, | |
| 218 | + completionId: uuidv4(), // Generate a new ID for this prefetched item. | |
| 219 | + diffLines: group.lines, | |
| 220 | + ide, | |
| 221 | + }); | |
| 222 | + | |
| 223 | + prefetchQueue.enqueueProcessed({ | |
| 224 | + location: rangeInFile, | |
| 225 | + outcome: groupOutcome, | |
| 226 | + }); | |
| 227 | + } | |
| 228 | + | |
| 229 | + private async createOutcomeFromDiffGroup( | |
| 230 | + diffGroup: DiffGroup, | |
| 231 | + helper: HelperVars, | |
| 232 | + startTime: number, | |
| 233 | + llm: ILLM, | |
| 234 | + completionId: string, | |
| 235 | + isCurrentCursorGroup: boolean, | |
| 236 | + promptMetadata: PromptMetadata, | |
| 237 | + ide: IDE, | |
| 238 | + ): Promise<NextEditOutcome> { | |
| 239 | + const groupContent = diffGroup.lines | |
| 240 | + .filter((l) => l.type !== "old") | |
| 241 | + .map((l) => l.line) | |
| 242 | + .join("\n"); | |
| 243 | + | |
| 244 | + const originalContent = diffGroup.lines | |
| 245 | + .filter((l) => l.type !== "new") | |
| 246 | + .map((l) => l.line) | |
| 247 | + .join("\n"); | |
| 248 | + | |
| 249 | + const cursorPos = isCurrentCursorGroup | |
| 250 | + ? helper.pos | |
| 251 | + : { line: diffGroup.startLine, character: 0 }; | |
| 252 | + | |
| 253 | + const finalCursorPos = calculateFinalCursorPosition( | |
| 254 | + cursorPos, | |
| 255 | + diffGroup.startLine, | |
| 256 | + originalContent, | |
| 257 | + groupContent, | |
| 258 | + ); | |
| 259 | + | |
| 260 | + const outcomeNext = await this.createNextEditOutcome({ | |
| 261 | + helper, | |
| 262 | + startTime, | |
| 263 | + llm, | |
| 264 | + promptContent: promptMetadata.prompt.content, | |
| 265 | + completion: groupContent, | |
| 266 | + finalCursorPosition: finalCursorPos, | |
| 267 | + editableRegionStartLine: diffGroup.startLine, | |
| 268 | + editableRegionEndLine: diffGroup.endLine, | |
| 269 | + userEdits: promptMetadata.userEdits, | |
| 270 | + userExcerpts: promptMetadata.userExcerpts, | |
| 271 | + originalEditableRange: originalContent, | |
| 272 | + cursorPosition: cursorPos, | |
| 273 | + completionId, | |
| 274 | + diffLines: diffGroup.lines, | |
| 275 | + ide, | |
| 276 | + }); | |
| 277 | + | |
| 278 | + return outcomeNext; | |
| 279 | + } | |
| 280 | + | |
| 281 | + protected async createNextEditOutcome(outcomeCtx: { | |
| 282 | + helper: HelperVars; | |
| 283 | + startTime: number; | |
| 284 | + llm: ILLM; | |
| 285 | + promptContent: string; | |
| 286 | + completion: string; | |
| 287 | + finalCursorPosition: Position; | |
| 288 | + editableRegionStartLine: number; | |
| 289 | + editableRegionEndLine: number; | |
| 290 | + userEdits: string; | |
| 291 | + userExcerpts: string; | |
| 292 | + originalEditableRange: string; | |
| 293 | + cursorPosition?: Position; | |
| 294 | + completionId?: string; | |
| 295 | + diffLines: DiffLine[]; | |
| 296 | + ide: IDE; | |
| 297 | + }): Promise<NextEditOutcome> { | |
| 298 | + return { | |
| 299 | + elapsed: Date.now() - outcomeCtx.startTime, | |
| 300 | + modelProvider: outcomeCtx.llm.underlyingProviderName, | |
| 301 | + modelName: outcomeCtx.llm.model + ":zetaDataset", | |
| 302 | + completionOptions: null, | |
| 303 | + completionId: | |
| 304 | + outcomeCtx.completionId || outcomeCtx.helper.input.completionId, | |
| 305 | + gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), | |
| 306 | + uniqueId: await outcomeCtx.ide.getUniqueId(), | |
| 307 | + timestamp: Date.now(), | |
| 308 | + fileUri: outcomeCtx.helper.filepath, | |
| 309 | + workspaceDirUri: | |
| 310 | + outcomeCtx.helper.workspaceUris[0] ?? | |
| 311 | + path.dirname(outcomeCtx.helper.filepath), | |
| 312 | + prompt: outcomeCtx.promptContent, | |
| 313 | + userEdits: outcomeCtx.userEdits ?? "", | |
| 314 | + userExcerpts: outcomeCtx.userExcerpts ?? "", | |
| 315 | + originalEditableRange: outcomeCtx.originalEditableRange ?? "", | |
| 316 | + completion: outcomeCtx.completion, | |
| 317 | + cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, | |
| 318 | + finalCursorPosition: outcomeCtx.finalCursorPosition, | |
| 319 | + editableRegionStartLine: outcomeCtx.editableRegionStartLine, | |
| 320 | + editableRegionEndLine: outcomeCtx.editableRegionEndLine, | |
| 321 | + diffLines: outcomeCtx.diffLines, | |
| 322 | + ...outcomeCtx.helper.options, | |
| 323 | + }; | |
| 324 | + } | |
| 325 | + | |
| 326 | + // Shared utility for calculating editable regions. | |
| 327 | + protected calculateOptimalEditableRegion( | |
| 328 | + helper: HelperVars, | |
| 329 | + maxTokens: number = 512, | |
| 330 | + heuristic: "fourChars" | "tokenizer" = "tokenizer", | |
| 331 | + ): { | |
| 332 | + editableRegionStartLine: number; | |
| 333 | + editableRegionEndLine: number; | |
| 334 | + } { | |
| 335 | + const cursorLine = helper.pos.line; | |
| 336 | + const fileLines = helper.fileLines; | |
| 337 | + | |
| 338 | + let editableRegionStartLine = cursorLine; | |
| 339 | + let editableRegionEndLine = cursorLine; | |
| 340 | + | |
| 341 | + let currentContent = fileLines[cursorLine]; | |
| 342 | + let totalTokens = | |
| 343 | + heuristic === "tokenizer" | |
| 344 | + ? countTokens(currentContent, helper.modelName) | |
| 345 | + : Math.ceil(currentContent.length / 4); | |
| 346 | + | |
| 347 | + let addingAbove = true; | |
| 348 | + | |
| 349 | + while (totalTokens < maxTokens) { | |
| 350 | + let addedLine = false; | |
| 351 | + | |
| 352 | + if (addingAbove) { | |
| 353 | + if (editableRegionStartLine > 0) { | |
| 354 | + editableRegionStartLine--; | |
| 355 | + const lineContent = fileLines[editableRegionStartLine]; | |
| 356 | + const lineTokens = | |
| 357 | + heuristic === "tokenizer" | |
| 358 | + ? countTokens(lineContent, helper.modelName) | |
| 359 | + : Math.ceil(lineContent.length / 4); | |
| 360 | + | |
| 361 | + totalTokens += lineTokens; | |
| 362 | + addedLine = true; | |
| 363 | + } | |
| 364 | + } else { | |
| 365 | + if (editableRegionEndLine < fileLines.length - 1) { | |
| 366 | + editableRegionEndLine++; | |
| 367 | + const lineContent = fileLines[editableRegionEndLine]; | |
| 368 | + const lineTokens = | |
| 369 | + heuristic === "tokenizer" | |
| 370 | + ? countTokens(lineContent, helper.modelName) | |
| 371 | + : Math.ceil(lineContent.length / 4); | |
| 372 | + | |
| 373 | + totalTokens += lineTokens; | |
| 374 | + addedLine = true; | |
| 375 | + } | |
| 376 | + } | |
| 377 | + | |
| 378 | + if (!addedLine) { | |
| 379 | + if ( | |
| 380 | + editableRegionStartLine === 0 && | |
| 381 | + editableRegionEndLine === fileLines.length - 1 | |
| 382 | + ) { | |
| 383 | + break; | |
| 384 | + } | |
| 385 | + addingAbove = !addingAbove; | |
| 386 | + continue; | |
| 387 | + } | |
| 388 | + | |
| 389 | + if (totalTokens > maxTokens) { | |
| 390 | + if (addingAbove) { | |
| 391 | + editableRegionStartLine++; | |
| 392 | + } else { | |
| 393 | + editableRegionEndLine--; | |
| 394 | + } | |
| 395 | + break; | |
| 396 | + } | |
| 397 | + | |
| 398 | + addingAbove = !addingAbove; | |
| 399 | + } | |
| 400 | + | |
| 401 | + return { | |
| 402 | + editableRegionStartLine, | |
| 403 | + editableRegionEndLine, | |
| 404 | + }; | |
| 405 | + } | |
| 406 | + | |
| 407 | + // Optional methods with defaults. | |
| 408 | + shouldInjectUniqueToken(): boolean { | |
| 409 | + return false; | |
| 410 | + } | |
| 411 | + | |
| 412 | + getUniqueToken(): string | null { | |
| 413 | + return null; | |
| 414 | + } | |
| 415 | +} |
added core/nextEdit/providers/InstinctNextEditProvider.ts +155 −0
| @@ -0,0 +1,155 @@ | ||
| 1 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 2 | +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; | |
| 3 | +import { INSTINCT_SYSTEM_PROMPT } from "../constants.js"; | |
| 4 | +import { | |
| 5 | + contextSnippetsBlock, | |
| 6 | + currentFileContentBlock, | |
| 7 | + editHistoryBlock, | |
| 8 | +} from "../templating/instinct.js"; | |
| 9 | +import { | |
| 10 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 11 | + PromptTemplateRenderer, | |
| 12 | +} from "../templating/NextEditPromptEngine.js"; | |
| 13 | +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; | |
| 14 | +import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; | |
| 15 | + | |
| 16 | +export class InstinctProvider extends BaseNextEditProvider { | |
| 17 | + private templateRenderer: PromptTemplateRenderer; | |
| 18 | + | |
| 19 | + constructor() { | |
| 20 | + super(NEXT_EDIT_MODELS.INSTINCT); | |
| 21 | + | |
| 22 | + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT]; | |
| 23 | + this.templateRenderer = new PromptTemplateRenderer(template.template); | |
| 24 | + } | |
| 25 | + | |
| 26 | + getSystemPrompt(): string { | |
| 27 | + return INSTINCT_SYSTEM_PROMPT; | |
| 28 | + } | |
| 29 | + | |
| 30 | + getWindowSize() { | |
| 31 | + return { topMargin: 1, bottomMargin: 5 }; | |
| 32 | + } | |
| 33 | + | |
| 34 | + shouldInjectUniqueToken(): boolean { | |
| 35 | + return false; // Instinct doesn't use unique tokens. | |
| 36 | + } | |
| 37 | + | |
| 38 | + extractCompletion(message: string): string { | |
| 39 | + return message; // Instinct returns the completion directly. | |
| 40 | + } | |
| 41 | + | |
| 42 | + buildPromptContext(context: ModelSpecificContext): any { | |
| 43 | + // Calculate the window around the cursor position (25 lines above and below). | |
| 44 | + const windowStart = Math.max(0, context.helper.pos.line - 25); | |
| 45 | + const windowEnd = Math.min( | |
| 46 | + context.helper.fileLines.length - 1, | |
| 47 | + context.helper.pos.line + 25, | |
| 48 | + ); | |
| 49 | + | |
| 50 | + // Ensure editable region boundaries are within the window. | |
| 51 | + const adjustedEditableStart = Math.max( | |
| 52 | + windowStart, | |
| 53 | + context.editableRegionStartLine, | |
| 54 | + ); | |
| 55 | + const adjustedEditableEnd = Math.min( | |
| 56 | + windowEnd, | |
| 57 | + context.editableRegionEndLine, | |
| 58 | + ); | |
| 59 | + | |
| 60 | + return { | |
| 61 | + contextSnippets: context.autocompleteContext, | |
| 62 | + currentFileContent: context.helper.fileContents, | |
| 63 | + windowStart, | |
| 64 | + windowEnd, | |
| 65 | + editableRegionStartLine: adjustedEditableStart, | |
| 66 | + editableRegionEndLine: adjustedEditableEnd, | |
| 67 | + editDiffHistory: context.diffContext, | |
| 68 | + currentFilePath: context.helper.filepath, | |
| 69 | + languageShorthand: context.helper.lang.name, | |
| 70 | + }; | |
| 71 | + } | |
| 72 | + | |
| 73 | + async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> { | |
| 74 | + const promptCtx = this.buildPromptContext(context); | |
| 75 | + | |
| 76 | + const templateVars = { | |
| 77 | + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), | |
| 78 | + currentFileContent: currentFileContentBlock( | |
| 79 | + promptCtx.currentFileContent, | |
| 80 | + promptCtx.windowStart, | |
| 81 | + promptCtx.windowEnd, | |
| 82 | + promptCtx.editableRegionStartLine, | |
| 83 | + promptCtx.editableRegionEndLine, | |
| 84 | + context.helper.pos, | |
| 85 | + ), | |
| 86 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 87 | + currentFilePath: promptCtx.currentFilePath, | |
| 88 | + languageShorthand: promptCtx.languageShorthand, | |
| 89 | + }; | |
| 90 | + | |
| 91 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 92 | + | |
| 93 | + return [ | |
| 94 | + { | |
| 95 | + role: "system", | |
| 96 | + content: this.getSystemPrompt(), | |
| 97 | + }, | |
| 98 | + { | |
| 99 | + role: "user", | |
| 100 | + content: userPromptContent, | |
| 101 | + }, | |
| 102 | + ]; | |
| 103 | + } | |
| 104 | + | |
| 105 | + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { | |
| 106 | + const promptCtx = this.buildPromptContext(context); | |
| 107 | + | |
| 108 | + const templateVars = { | |
| 109 | + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), | |
| 110 | + currentFileContent: currentFileContentBlock( | |
| 111 | + promptCtx.currentFileContent, | |
| 112 | + promptCtx.windowStart, | |
| 113 | + promptCtx.windowEnd, | |
| 114 | + promptCtx.editableRegionStartLine, | |
| 115 | + promptCtx.editableRegionEndLine, | |
| 116 | + context.helper.pos, | |
| 117 | + ), | |
| 118 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 119 | + currentFilePath: promptCtx.currentFilePath, | |
| 120 | + languageShorthand: promptCtx.languageShorthand, | |
| 121 | + }; | |
| 122 | + | |
| 123 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 124 | + | |
| 125 | + return { | |
| 126 | + prompt: { | |
| 127 | + role: "user", | |
| 128 | + content: userPromptContent, | |
| 129 | + }, | |
| 130 | + userEdits: promptCtx.editDiffHistory.join("\n"), | |
| 131 | + userExcerpts: templateVars.currentFileContent, | |
| 132 | + }; | |
| 133 | + } | |
| 134 | + | |
| 135 | + calculateEditableRegion( | |
| 136 | + helper: HelperVars, | |
| 137 | + usingFullFileDiff: boolean, | |
| 138 | + ): { | |
| 139 | + editableRegionStartLine: number; | |
| 140 | + editableRegionEndLine: number; | |
| 141 | + } { | |
| 142 | + if (usingFullFileDiff) { | |
| 143 | + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); | |
| 144 | + } else { | |
| 145 | + const { topMargin, bottomMargin } = this.getWindowSize(); | |
| 146 | + return { | |
| 147 | + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), | |
| 148 | + editableRegionEndLine: Math.min( | |
| 149 | + helper.pos.line + bottomMargin, | |
| 150 | + helper.fileLines.length - 1, | |
| 151 | + ), | |
| 152 | + }; | |
| 153 | + } | |
| 154 | + } | |
| 155 | +} |
added core/nextEdit/providers/MercuryCoderNextEditProvider.ts +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; | |
| 2 | +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; | |
| 3 | +import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js"; | |
| 4 | +import { | |
| 5 | + currentFileContentBlock, | |
| 6 | + editHistoryBlock, | |
| 7 | + recentlyViewedCodeSnippetsBlock, | |
| 8 | +} from "../templating/mercuryCoderNextEdit.js"; | |
| 9 | +import { | |
| 10 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 11 | + PromptTemplateRenderer, | |
| 12 | +} from "../templating/NextEditPromptEngine.js"; | |
| 13 | +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; | |
| 14 | +import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; | |
| 15 | + | |
| 16 | +export class MercuryCoderProvider extends BaseNextEditProvider { | |
| 17 | + private templateRenderer: PromptTemplateRenderer; | |
| 18 | + | |
| 19 | + constructor() { | |
| 20 | + super(NEXT_EDIT_MODELS.MERCURY_CODER); | |
| 21 | + | |
| 22 | + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER]; | |
| 23 | + this.templateRenderer = new PromptTemplateRenderer(template.template); | |
| 24 | + } | |
| 25 | + | |
| 26 | + getSystemPrompt(): string { | |
| 27 | + return MERCURY_SYSTEM_PROMPT; | |
| 28 | + } | |
| 29 | + | |
| 30 | + getWindowSize() { | |
| 31 | + return { topMargin: 0, bottomMargin: 5 }; | |
| 32 | + } | |
| 33 | + | |
| 34 | + shouldInjectUniqueToken(): boolean { | |
| 35 | + return true; | |
| 36 | + } | |
| 37 | + | |
| 38 | + getUniqueToken(): string { | |
| 39 | + return UNIQUE_TOKEN; | |
| 40 | + } | |
| 41 | + | |
| 42 | + extractCompletion(message: string): string { | |
| 43 | + // Extract the code between the markdown code blocks. | |
| 44 | + return message.slice( | |
| 45 | + message.indexOf("```\n") + "```\n".length, | |
| 46 | + message.lastIndexOf("\n\n```"), | |
| 47 | + ); | |
| 48 | + } | |
| 49 | + | |
| 50 | + buildPromptContext(context: ModelSpecificContext): any { | |
| 51 | + return { | |
| 52 | + recentlyViewedCodeSnippets: | |
| 53 | + context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ | |
| 54 | + filepath: snip.filepath, | |
| 55 | + content: snip.content, | |
| 56 | + })) ?? [], | |
| 57 | + currentFileContent: context.helper.fileContents, | |
| 58 | + editableRegionStartLine: context.editableRegionStartLine, | |
| 59 | + editableRegionEndLine: context.editableRegionEndLine, | |
| 60 | + editDiffHistory: context.diffContext, | |
| 61 | + currentFilePath: context.helper.filepath, | |
| 62 | + }; | |
| 63 | + } | |
| 64 | + | |
| 65 | + async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> { | |
| 66 | + const promptCtx = this.buildPromptContext(context); | |
| 67 | + | |
| 68 | + const templateVars = { | |
| 69 | + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 70 | + promptCtx.recentlyViewedCodeSnippets, | |
| 71 | + ), | |
| 72 | + currentFileContent: currentFileContentBlock( | |
| 73 | + promptCtx.currentFileContent, | |
| 74 | + promptCtx.editableRegionStartLine, | |
| 75 | + promptCtx.editableRegionEndLine, | |
| 76 | + context.helper.pos, | |
| 77 | + ), | |
| 78 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 79 | + currentFilePath: promptCtx.currentFilePath, | |
| 80 | + }; | |
| 81 | + | |
| 82 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 83 | + | |
| 84 | + return [ | |
| 85 | + { | |
| 86 | + role: "system", | |
| 87 | + content: this.getSystemPrompt(), | |
| 88 | + }, | |
| 89 | + { | |
| 90 | + role: "user", | |
| 91 | + content: userPromptContent, | |
| 92 | + }, | |
| 93 | + ]; | |
| 94 | + } | |
| 95 | + | |
| 96 | + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { | |
| 97 | + const promptCtx = this.buildPromptContext(context); | |
| 98 | + | |
| 99 | + const templateVars = { | |
| 100 | + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 101 | + promptCtx.recentlyViewedCodeSnippets, | |
| 102 | + ), | |
| 103 | + currentFileContent: currentFileContentBlock( | |
| 104 | + promptCtx.currentFileContent, | |
| 105 | + promptCtx.editableRegionStartLine, | |
| 106 | + promptCtx.editableRegionEndLine, | |
| 107 | + context.helper.pos, | |
| 108 | + ), | |
| 109 | + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), | |
| 110 | + currentFilePath: promptCtx.currentFilePath, | |
| 111 | + }; | |
| 112 | + | |
| 113 | + const userPromptContent = this.templateRenderer.render(templateVars); | |
| 114 | + | |
| 115 | + return { | |
| 116 | + prompt: { | |
| 117 | + role: "user", | |
| 118 | + content: userPromptContent, | |
| 119 | + }, | |
| 120 | + userEdits: promptCtx.editDiffHistory.join("\n"), | |
| 121 | + userExcerpts: templateVars.currentFileContent, | |
| 122 | + }; | |
| 123 | + } | |
| 124 | + | |
| 125 | + calculateEditableRegion( | |
| 126 | + helper: HelperVars, | |
| 127 | + usingFullFileDiff: boolean, | |
| 128 | + ): { | |
| 129 | + editableRegionStartLine: number; | |
| 130 | + editableRegionEndLine: number; | |
| 131 | + } { | |
| 132 | + if (usingFullFileDiff) { | |
| 133 | + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); | |
| 134 | + } else { | |
| 135 | + const { topMargin, bottomMargin } = this.getWindowSize(); | |
| 136 | + return { | |
| 137 | + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), | |
| 138 | + editableRegionEndLine: Math.min( | |
| 139 | + helper.pos.line + bottomMargin, | |
| 140 | + helper.fileLines.length - 1, | |
| 141 | + ), | |
| 142 | + }; | |
| 143 | + } | |
| 144 | + } | |
| 145 | +} |
modified core/nextEdit/templating/NextEditPromptEngine.ts +21 −259
| @@ -1,7 +1,4 @@ | ||
| 1 | 1 | import Handlebars from "handlebars"; |
| 2 | -import { Position } from "../.."; | |
| 3 | -import { SnippetPayload } from "../../autocomplete/snippets"; | |
| 4 | -import { HelperVars } from "../../autocomplete/util/HelperVars"; | |
| 5 | 2 | import { NEXT_EDIT_MODELS } from "../../llm/constants"; |
| 6 | 3 | import { |
| 7 | 4 | INSTINCT_USER_PROMPT_PREFIX, |
| @@ -12,274 +9,39 @@ | ||
| 12 | 9 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, |
| 13 | 10 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, |
| 14 | 11 | } from "../constants"; |
| 15 | -import { | |
| 16 | - InstinctTemplateVars, | |
| 17 | - MercuryTemplateVars, | |
| 18 | - NextEditTemplate, | |
| 19 | - PromptMetadata, | |
| 20 | - SystemPrompt, | |
| 21 | - TemplateVars, | |
| 22 | - UserPrompt, | |
| 23 | -} from "../types"; | |
| 24 | -import { | |
| 25 | - contextSnippetsBlock, | |
| 26 | - currentFileContentBlock as instinctCurrentFileContentBlock, | |
| 27 | - editHistoryBlock as instinctEditHistoryBlock, | |
| 28 | -} from "./instinct"; | |
| 29 | -import { | |
| 30 | - currentFileContentBlock, | |
| 31 | - editHistoryBlock, | |
| 32 | - recentlyViewedCodeSnippetsBlock, | |
| 33 | -} from "./mercuryCoderNextEdit"; | |
| 34 | -import { | |
| 35 | - insertCursorToken, | |
| 36 | - insertEditableRegionTokensWithStaticRange, | |
| 37 | -} from "./utils"; | |
| 38 | - | |
| 39 | -type TemplateRenderer = (vars: TemplateVars) => string; | |
| 40 | - | |
| 41 | -const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = { | |
| 12 | +import { NextEditTemplate, TemplateVars } from "../types"; | |
| 13 | + | |
| 14 | +// Keep the template registry | |
| 15 | +export const NEXT_EDIT_MODEL_TEMPLATES: Record< | |
| 16 | + NEXT_EDIT_MODELS, | |
| 17 | + NextEditTemplate | |
| 18 | +> = { | |
| 42 | 19 | "mercury-coder": { |
| 43 | 20 | template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, |
| 44 | 21 | }, |
| 45 | - "mercury-coder-nextedit": { | |
| 46 | - template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, | |
| 47 | - }, | |
| 48 | 22 | instinct: { |
| 49 | 23 | template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, |
| 50 | 24 | }, |
| 51 | 25 | }; |
| 52 | 26 | |
| 53 | -function templateRendererOfModel( | |
| 54 | - modelName: NEXT_EDIT_MODELS, | |
| 55 | -): TemplateRenderer { | |
| 56 | - let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; | |
| 57 | - if (!template) { | |
| 58 | - throw new Error(`Model ${modelName} is not supported for next edit.`); | |
| 59 | - } | |
| 60 | - | |
| 61 | - const compiledTemplate = Handlebars.compile(template.template); | |
| 62 | - | |
| 63 | - return (vars: TemplateVars): string => { | |
| 64 | - return compiledTemplate(vars); | |
| 65 | - }; | |
| 66 | -} | |
| 67 | - | |
| 68 | -export async function renderPrompt( | |
| 69 | - helper: HelperVars, | |
| 70 | - ctx: any, | |
| 71 | -): Promise<PromptMetadata> { | |
| 72 | - let modelName = helper.modelName as NEXT_EDIT_MODELS; | |
| 27 | +// Export a utility for providers to use | |
| 28 | +export class PromptTemplateRenderer { | |
| 29 | + private compiledTemplate: HandlebarsTemplateDelegate; | |
| 73 | 30 | |
| 74 | - // Validate that the modelName is actually a supported model. | |
| 75 | - if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { | |
| 76 | - // Check if modelName includes any known model name as substring. | |
| 77 | - const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) => | |
| 78 | - modelName.includes(key), | |
| 79 | - ); | |
| 80 | - | |
| 81 | - if (matchingModel) { | |
| 82 | - modelName = matchingModel as NEXT_EDIT_MODELS; | |
| 83 | - } else { | |
| 84 | - throw new Error( | |
| 85 | - `${helper.modelName} is not yet supported for next edit.`, | |
| 86 | - ); | |
| 87 | - } | |
| 31 | + constructor(template: string) { | |
| 32 | + this.compiledTemplate = Handlebars.compile(template); | |
| 88 | 33 | } |
| 89 | 34 | |
| 90 | - const renderer = templateRendererOfModel(modelName); | |
| 91 | - let userEdits = ""; | |
| 92 | - let editedCodeWithTokens = ""; | |
| 93 | - let tv: TemplateVars; | |
| 94 | - | |
| 95 | - switch (modelName) { | |
| 96 | - case NEXT_EDIT_MODELS.MERCURY_CODER: { | |
| 97 | - userEdits = ctx.editDiffHistory; | |
| 98 | - | |
| 99 | - // editedCodeWithTokens = insertTokens( | |
| 100 | - // helper.fileContents.split("\n"), | |
| 101 | - // helper.pos, | |
| 102 | - // MERCURY_CURSOR, | |
| 103 | - // ); | |
| 104 | - | |
| 105 | - const mercuryCtx: MercuryTemplateVars = { | |
| 106 | - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 107 | - ctx.recentlyViewedCodeSnippets, | |
| 108 | - ), | |
| 109 | - currentFileContent: currentFileContentBlock( | |
| 110 | - ctx.currentFileContent, | |
| 111 | - ctx.editableRegionStartLine, | |
| 112 | - ctx.editableRegionEndLine, | |
| 113 | - helper.pos, | |
| 114 | - ), | |
| 115 | - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), | |
| 116 | - currentFilePath: ctx.currentFilePath, | |
| 117 | - }; | |
| 118 | - | |
| 119 | - tv = mercuryCtx; | |
| 120 | - | |
| 121 | - editedCodeWithTokens = mercuryCtx.currentFileContent; | |
| 122 | - | |
| 123 | - break; | |
| 124 | - } | |
| 125 | - case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: { | |
| 126 | - userEdits = ctx.editDiffHistory; | |
| 127 | - | |
| 128 | - // editedCodeWithTokens = insertTokens( | |
| 129 | - // helper.fileContents.split("\n"), | |
| 130 | - // helper.pos, | |
| 131 | - // MERCURY_CURSOR, | |
| 132 | - // ); | |
| 133 | - | |
| 134 | - const mercuryCtx: MercuryTemplateVars = { | |
| 135 | - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( | |
| 136 | - ctx.recentlyViewedCodeSnippets, | |
| 137 | - ), | |
| 138 | - currentFileContent: currentFileContentBlock( | |
| 139 | - ctx.currentFileContent, | |
| 140 | - ctx.editableRegionStartLine, | |
| 141 | - ctx.editableRegionEndLine, | |
| 142 | - helper.pos, | |
| 143 | - ), | |
| 144 | - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), | |
| 145 | - currentFilePath: ctx.currentFilePath, | |
| 146 | - }; | |
| 147 | - | |
| 148 | - tv = mercuryCtx; | |
| 149 | - | |
| 150 | - editedCodeWithTokens = mercuryCtx.currentFileContent; | |
| 151 | - | |
| 152 | - break; | |
| 153 | - } | |
| 154 | - case NEXT_EDIT_MODELS.INSTINCT: { | |
| 155 | - userEdits = ctx.editDiffHistory; | |
| 156 | - | |
| 157 | - // editedCodeWithTokens = insertTokens( | |
| 158 | - // helper.fileContents.split("\n"), | |
| 159 | - // helper.pos, | |
| 160 | - // INSTINCT_USER_CURSOR_IS_HERE_TOKEN, | |
| 161 | - // ); | |
| 162 | - | |
| 163 | - const instinctCtx: InstinctTemplateVars = { | |
| 164 | - contextSnippets: contextSnippetsBlock(ctx.contextSnippets), | |
| 165 | - currentFileContent: instinctCurrentFileContentBlock( | |
| 166 | - ctx.currentFileContent, | |
| 167 | - ctx.windowStart, | |
| 168 | - ctx.windowEnd, | |
| 169 | - ctx.editableRegionStartLine, | |
| 170 | - ctx.editableRegionEndLine, | |
| 171 | - helper.pos, | |
| 172 | - ), | |
| 173 | - editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory), | |
| 174 | - currentFilePath: ctx.currentFilePath, | |
| 175 | - languageShorthand: ctx.languageShorthand, | |
| 176 | - }; | |
| 177 | - | |
| 178 | - tv = instinctCtx; | |
| 179 | - | |
| 180 | - editedCodeWithTokens = instinctCtx.currentFileContent; | |
| 181 | - | |
| 182 | - break; | |
| 183 | - } | |
| 184 | - default: | |
| 185 | - tv = {}; | |
| 186 | - break; | |
| 35 | + render(vars: TemplateVars): string { | |
| 36 | + return this.compiledTemplate(vars); | |
| 187 | 37 | } |
| 188 | - | |
| 189 | - return { | |
| 190 | - prompt: { | |
| 191 | - role: "user", | |
| 192 | - content: renderer(tv), | |
| 193 | - }, | |
| 194 | - userEdits, | |
| 195 | - userExcerpts: editedCodeWithTokens, | |
| 196 | - }; | |
| 197 | -} | |
| 198 | - | |
| 199 | -export function renderDefaultSystemPrompt(): SystemPrompt { | |
| 200 | - return { | |
| 201 | - role: "system", | |
| 202 | - content: [ | |
| 203 | - /* Identity forming */ | |
| 204 | - "You are an expert polyglot developer who is overseeing a junior developer write code in some language.", | |
| 205 | - "You are psychic as well, so you are an expert at reading minds just from what the junior has done.", | |
| 206 | - "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.", | |
| 207 | - /* Action crash course */ | |
| 208 | - "An action is a change in code state that preserves the well-formedness of the code.", | |
| 209 | - "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.", | |
| 210 | - /* Input description */ | |
| 211 | - // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.', | |
| 212 | - // "language is the language the code is written in.", | |
| 213 | - // "originalCode is the code state before the junior has taken some edit action.", | |
| 214 | - // "editedCode is the code state after the junior has taken some edit action.", | |
| 215 | - // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.", | |
| 216 | - // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.", | |
| 217 | - 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.', | |
| 218 | - "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.", | |
| 219 | - "recentlyEditedRange is the code that the junior has recently edited.", | |
| 220 | - "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.", | |
| 221 | - "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.", | |
| 222 | - "The junior might want to add new code, delete existing code, or replace different parts of code.", | |
| 223 | - "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.", | |
| 224 | - /* Output description */ | |
| 225 | - 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.', | |
| 226 | - /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/ | |
| 227 | - /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */ | |
| 228 | - "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.", | |
| 229 | - // "actionType is the type of action the junior has taken.", | |
| 230 | - "newCode is what the full code looks like after applying your nextEditContent.", | |
| 231 | - // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.", | |
| 232 | - "Given the above definition of an action, you should prioritize fixing the following:", | |
| 233 | - "- Patterns and repetition in code.", | |
| 234 | - "- Static errors that the compiler of the language may return.", | |
| 235 | - "- The junior's code style.", | |
| 236 | - "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.", | |
| 237 | - "If the junior has added some code, there's a good chance that the next edit will also be additions.", | |
| 238 | - "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.", | |
| 239 | - "Careful of language intricacies.", | |
| 240 | - // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.", | |
| 241 | - "Do not reply in markdown.", | |
| 242 | - "Do not hallucinate.", | |
| 243 | - ].join(" "), | |
| 244 | - }; | |
| 245 | 38 | } |
| 246 | 39 | |
| 247 | -export function renderDefaultUserPrompt( | |
| 248 | - // originalCode: string, | |
| 249 | - // editedCode: string, | |
| 250 | - snippets: SnippetPayload, | |
| 251 | - helper: HelperVars, | |
| 252 | -): UserPrompt { | |
| 253 | - const userEdit = { | |
| 254 | - language: helper.lang, | |
| 255 | - rootPathSnippets: snippets.rootPathSnippets, | |
| 256 | - importDefinitionSnippets: snippets.importDefinitionSnippets, | |
| 257 | - ideSnippets: snippets.ideSnippets, | |
| 258 | - recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets, | |
| 259 | - diffSnippets: snippets.diffSnippets, | |
| 260 | - clipboardSnippets: snippets.clipboardSnippets, | |
| 261 | - recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets, | |
| 262 | - }; | |
| 263 | - | |
| 264 | - return { | |
| 265 | - role: "user", | |
| 266 | - content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`, | |
| 267 | - }; | |
| 268 | -} | |
| 269 | - | |
| 270 | -function insertTokens( | |
| 271 | - lines: string[], | |
| 272 | - cursorPos: Position, | |
| 273 | - cursorToken: string, | |
| 274 | - editableRegionStart?: number, | |
| 275 | - editableRegionEnd?: number, | |
| 276 | -) { | |
| 277 | - const a = insertCursorToken(lines, cursorPos, cursorToken); | |
| 278 | - const b = insertEditableRegionTokensWithStaticRange( | |
| 279 | - a, | |
| 280 | - cursorPos, | |
| 281 | - editableRegionStart, | |
| 282 | - editableRegionEnd, | |
| 283 | - ); | |
| 284 | - return b.join("\n"); | |
| 40 | +// Keep for backward compatibility or remove if not needed | |
| 41 | +export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string { | |
| 42 | + const template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; | |
| 43 | + if (!template) { | |
| 44 | + throw new Error(`Model ${modelName} is not supported for next edit.`); | |
| 45 | + } | |
| 46 | + return template.template; | |
| 285 | 47 | } |
modified core/nextEdit/templating/NextEditPromptEngine.vitest.ts +81 −212
| @@ -1,243 +1,112 @@ | ||
| 1 | -import { beforeEach, describe, expect, it } from "vitest"; | |
| 2 | -import { Position } from "../.."; | |
| 3 | -import { SnippetPayload } from "../../autocomplete/snippets"; | |
| 4 | -import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; | |
| 5 | -import { HelperVars } from "../../autocomplete/util/HelperVars"; | |
| 1 | +import { describe, expect, it } from "vitest"; | |
| 6 | 2 | import { NEXT_EDIT_MODELS } from "../../llm/constants"; |
| 7 | 3 | import { |
| 8 | - INSTINCT_USER_CURSOR_IS_HERE_TOKEN, | |
| 9 | 4 | INSTINCT_USER_PROMPT_PREFIX, |
| 10 | 5 | MERCURY_CURRENT_FILE_CONTENT_CLOSE, |
| 11 | 6 | MERCURY_CURRENT_FILE_CONTENT_OPEN, |
| 12 | - MERCURY_CURSOR, | |
| 13 | 7 | MERCURY_EDIT_DIFF_HISTORY_CLOSE, |
| 14 | 8 | MERCURY_EDIT_DIFF_HISTORY_OPEN, |
| 15 | 9 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, |
| 16 | 10 | MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, |
| 17 | - MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE, | |
| 18 | - MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN, | |
| 19 | 11 | } from "../constants"; |
| 20 | 12 | import { |
| 21 | - renderDefaultSystemPrompt, | |
| 22 | - renderDefaultUserPrompt, | |
| 23 | - renderPrompt, | |
| 13 | + NEXT_EDIT_MODEL_TEMPLATES, | |
| 14 | + PromptTemplateRenderer, | |
| 15 | + getTemplateForModel, | |
| 24 | 16 | } from "./NextEditPromptEngine"; |
| 25 | 17 | |
| 26 | 18 | describe("NextEditPromptEngine", () => { |
| 27 | - describe("renderPrompt", () => { | |
| 28 | - let mercuryHelper: HelperVars; | |
| 29 | - let instinctHelper: HelperVars; | |
| 30 | - let testHelper: HelperVars; | |
| 31 | - let unsupportedHelper: HelperVars; | |
| 32 | - let ctx: any; | |
| 33 | - | |
| 34 | - beforeEach(() => { | |
| 35 | - mercuryHelper = { | |
| 36 | - modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS, | |
| 37 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 38 | - pos: { line: 1, character: 12 } as Position, | |
| 39 | - lang: { name: "typescript" }, | |
| 40 | - } as HelperVars; | |
| 41 | - instinctHelper = { | |
| 42 | - modelName: "continuedev/instinct" as NEXT_EDIT_MODELS, | |
| 43 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 44 | - pos: { line: 1, character: 12 } as Position, | |
| 45 | - lang: { name: "typescript" }, | |
| 46 | - } as HelperVars; | |
| 47 | - unsupportedHelper = { | |
| 48 | - modelName: "mistral/codestral" as NEXT_EDIT_MODELS, | |
| 49 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 50 | - pos: { line: 1, character: 12 } as Position, | |
| 51 | - lang: { name: "typescript" }, | |
| 52 | - } as HelperVars; | |
| 53 | - | |
| 54 | - ctx = { | |
| 55 | - recentlyViewedCodeSnippets: [ | |
| 56 | - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, | |
| 57 | - ], | |
| 58 | - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", | |
| 59 | - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], | |
| 60 | - editableRegionStartLine: 0, | |
| 61 | - editableRegionEndLine: 3, | |
| 62 | - userEdits: "Added constant a", | |
| 63 | - languageShorthand: "ts", | |
| 64 | - userExcerpts: "const a = 1;", | |
| 65 | - }; | |
| 19 | + describe("NEXT_EDIT_MODEL_TEMPLATES", () => { | |
| 20 | + it("should contain templates for all supported models", () => { | |
| 21 | + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( | |
| 22 | + NEXT_EDIT_MODELS.MERCURY_CODER, | |
| 23 | + ); | |
| 24 | + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( | |
| 25 | + NEXT_EDIT_MODELS.INSTINCT, | |
| 26 | + ); | |
| 66 | 27 | }); |
| 67 | 28 | |
| 68 | - it("should render mercury-coder prompt correctly", async () => { | |
| 69 | - const result = await renderPrompt(mercuryHelper, ctx); | |
| 70 | - | |
| 71 | - expect(result).toHaveProperty("prompt"); | |
| 72 | - expect(result.prompt.role).toBe("user"); | |
| 73 | - | |
| 74 | - const content = result.prompt.content; | |
| 75 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); | |
| 76 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); | |
| 77 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN); | |
| 78 | - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE); | |
| 79 | - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); | |
| 80 | - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); | |
| 81 | - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); | |
| 82 | - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); | |
| 83 | - | |
| 84 | - expect(result.userEdits).toBe(ctx.editDiffHistory); | |
| 85 | - expect(result.userExcerpts).toContain(MERCURY_CURSOR); | |
| 29 | + it("mercury-coder template should contain expected tokens", () => { | |
| 30 | + const template = | |
| 31 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; | |
| 32 | + | |
| 33 | + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); | |
| 34 | + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); | |
| 35 | + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); | |
| 36 | + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); | |
| 37 | + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); | |
| 38 | + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); | |
| 39 | + expect(template).toContain("{{{recentlyViewedCodeSnippets}}}"); | |
| 40 | + expect(template).toContain("{{{currentFileContent}}}"); | |
| 41 | + expect(template).toContain("{{{editDiffHistory}}}"); | |
| 86 | 42 | }); |
| 87 | 43 | |
| 88 | - it("should render instinct prompt correctly", async () => { | |
| 89 | - // Create proper instinct context structure matching NextEditProvider.ts | |
| 90 | - const instinctCtx = { | |
| 91 | - contextSnippets: | |
| 92 | - "+++++ /path/to/context.ts\nconst contextVar = 'test';", | |
| 93 | - currentFileContent: instinctHelper.fileContents, | |
| 94 | - windowStart: 0, // Math.max(0, helper.pos.line - 25) | |
| 95 | - windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) | |
| 96 | - editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window | |
| 97 | - editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window | |
| 98 | - editDiffHistory: [ | |
| 99 | - "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", | |
| 100 | - ], // unified diff | |
| 101 | - currentFilePath: "/path/to/file.ts", | |
| 102 | - languageShorthand: "ts", | |
| 103 | - }; | |
| 104 | - | |
| 105 | - const result = await renderPrompt(instinctHelper, instinctCtx); | |
| 106 | - console.log(result); | |
| 107 | - | |
| 108 | - expect(result).toHaveProperty("prompt"); | |
| 109 | - expect(result.prompt.role).toBe("user"); | |
| 110 | - expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX); | |
| 111 | - expect(result.prompt.content).toContain("### Context:"); | |
| 112 | - expect(result.prompt.content).toContain("### User Edits:"); | |
| 113 | - expect(result.prompt.content).toContain("### User Excerpt:"); | |
| 114 | - | |
| 115 | - expect(result.userEdits).toBe(instinctCtx.editDiffHistory); | |
| 116 | - expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); | |
| 44 | + it("instinct template should contain expected tokens", () => { | |
| 45 | + const template = | |
| 46 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template; | |
| 47 | + | |
| 48 | + expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX); | |
| 49 | + expect(template).toContain("### Context:"); | |
| 50 | + expect(template).toContain("### User Edits:"); | |
| 51 | + expect(template).toContain("### User Excerpt:"); | |
| 52 | + expect(template).toContain("{{{contextSnippets}}}"); | |
| 53 | + expect(template).toContain("{{{currentFileContent}}}"); | |
| 54 | + expect(template).toContain("{{{editDiffHistory}}}"); | |
| 55 | + expect(template).toContain("{{{currentFilePath}}}"); | |
| 117 | 56 | }); |
| 57 | + }); | |
| 118 | 58 | |
| 119 | - it("should throw error for unsupported model name", async () => { | |
| 120 | - await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow( | |
| 121 | - "mistral/codestral is not yet supported for next edit.", | |
| 122 | - ); | |
| 59 | + describe("PromptTemplateRenderer", () => { | |
| 60 | + it("should render a template with provided variables", () => { | |
| 61 | + const template = "Hello {{{name}}}, you have {{{count}}} messages"; | |
| 62 | + const renderer = new PromptTemplateRenderer(template); | |
| 63 | + | |
| 64 | + const result = renderer.render({ | |
| 65 | + name: "Alice", | |
| 66 | + count: "5", | |
| 67 | + }); | |
| 68 | + | |
| 69 | + expect(result).toBe("Hello Alice, you have 5 messages"); | |
| 123 | 70 | }); |
| 124 | - }); | |
| 125 | 71 | |
| 126 | - describe("renderDefaultSystemPrompt", () => { | |
| 127 | - it("should return a system prompt with expected role and content", () => { | |
| 128 | - const result = renderDefaultSystemPrompt(); | |
| 72 | + it("should handle missing variables gracefully", () => { | |
| 73 | + const template = "Hello {{{name}}}"; | |
| 74 | + const renderer = new PromptTemplateRenderer(template); | |
| 129 | 75 | |
| 130 | - expect(result.role).toBe("system"); | |
| 131 | - expect(result.content).toContain("You are an expert polyglot developer"); | |
| 132 | - expect(result.content).toContain("Do not hallucinate."); | |
| 76 | + const result = renderer.render({}); | |
| 77 | + | |
| 78 | + expect(result).toBe("Hello "); | |
| 133 | 79 | }); |
| 134 | - }); | |
| 135 | 80 | |
| 136 | - describe("renderDefaultUserPrompt", () => { | |
| 137 | - it("should render a user prompt with the correct structure", () => { | |
| 138 | - const snippets: SnippetPayload = { | |
| 139 | - rootPathSnippets: [ | |
| 140 | - { | |
| 141 | - type: AutocompleteSnippetType.Code, | |
| 142 | - filepath: "", | |
| 143 | - content: "root path", | |
| 144 | - }, | |
| 145 | - ], | |
| 146 | - importDefinitionSnippets: [ | |
| 147 | - { | |
| 148 | - type: AutocompleteSnippetType.Code, | |
| 149 | - filepath: "", | |
| 150 | - content: "import def", | |
| 151 | - }, | |
| 152 | - ], | |
| 153 | - ideSnippets: [ | |
| 154 | - { | |
| 155 | - type: AutocompleteSnippetType.Code, | |
| 156 | - filepath: "", | |
| 157 | - content: "ide snippets", | |
| 158 | - }, | |
| 159 | - ], | |
| 160 | - recentlyEditedRangeSnippets: [ | |
| 161 | - { | |
| 162 | - type: AutocompleteSnippetType.Code, | |
| 163 | - filepath: "", | |
| 164 | - content: "recent edits", | |
| 165 | - }, | |
| 166 | - ], | |
| 167 | - diffSnippets: [ | |
| 168 | - { | |
| 169 | - type: AutocompleteSnippetType.Diff, | |
| 170 | - content: "diff snippets", | |
| 171 | - }, | |
| 172 | - ], | |
| 173 | - clipboardSnippets: [ | |
| 174 | - { | |
| 175 | - type: AutocompleteSnippetType.Clipboard, | |
| 176 | - content: "clipboard", | |
| 177 | - copiedAt: new Date().toISOString(), | |
| 178 | - }, | |
| 179 | - ], | |
| 180 | - recentlyVisitedRangesSnippets: [ | |
| 181 | - { | |
| 182 | - type: AutocompleteSnippetType.Code, | |
| 183 | - filepath: "", | |
| 184 | - content: "visited ranges", | |
| 185 | - }, | |
| 186 | - ], | |
| 187 | - recentlyOpenedFileSnippets: [ | |
| 188 | - { | |
| 189 | - type: AutocompleteSnippetType.Code, | |
| 190 | - filepath: "", | |
| 191 | - content: "recently opened files", | |
| 192 | - }, | |
| 193 | - ], | |
| 194 | - staticSnippet: [ | |
| 195 | - { | |
| 196 | - type: AutocompleteSnippetType.Static, | |
| 197 | - filepath: "", | |
| 198 | - content: "static content", | |
| 199 | - }, | |
| 200 | - ], | |
| 201 | - }; | |
| 202 | - | |
| 203 | - const helper: HelperVars = { | |
| 204 | - lang: { name: "typescript" }, | |
| 205 | - } as HelperVars; | |
| 206 | - | |
| 207 | - const result = renderDefaultUserPrompt(snippets, helper); | |
| 208 | - | |
| 209 | - expect(result.role).toBe("user"); | |
| 210 | - expect(result.content).toContain("Your junior made the following edit:"); | |
| 211 | - expect(result.content).toContain("typescript"); | |
| 212 | - expect(result.content).toContain("root path"); | |
| 81 | + it("should render complex templates correctly", () => { | |
| 82 | + const template = | |
| 83 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; | |
| 84 | + const renderer = new PromptTemplateRenderer(template); | |
| 85 | + | |
| 86 | + const result = renderer.render({ | |
| 87 | + recentlyViewedCodeSnippets: "snippet1", | |
| 88 | + currentFileContent: "file content", | |
| 89 | + editDiffHistory: "diff history", | |
| 90 | + }); | |
| 91 | + | |
| 92 | + expect(result).toContain("snippet1"); | |
| 93 | + expect(result).toContain("file content"); | |
| 94 | + expect(result).toContain("diff history"); | |
| 213 | 95 | }); |
| 214 | 96 | }); |
| 215 | 97 | |
| 216 | - describe("insertTokens", () => { | |
| 217 | - it("should correctly insert cursor and editable region tokens", () => { | |
| 218 | - const mercuryHelper = { | |
| 219 | - modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, | |
| 220 | - fileContents: "function test() {\n const a = 1;\n return a;\n}", | |
| 221 | - pos: { line: 1, character: 12 } as Position, | |
| 222 | - lang: { name: "typescript" }, | |
| 223 | - } as HelperVars; | |
| 224 | - | |
| 225 | - const ctx = { | |
| 226 | - recentlyViewedCodeSnippets: [ | |
| 227 | - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, | |
| 228 | - ], | |
| 229 | - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", | |
| 230 | - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], | |
| 231 | - editableRegionStartLine: 0, | |
| 232 | - editableRegionEndLine: 3, | |
| 233 | - userEdits: "Added constant a", | |
| 234 | - languageShorthand: "ts", | |
| 235 | - userExcerpts: "const a = 1;", | |
| 236 | - }; | |
| 237 | - | |
| 238 | - return renderPrompt(mercuryHelper, ctx).then((result) => { | |
| 239 | - expect(result.userExcerpts).toContain(MERCURY_CURSOR); | |
| 240 | - }); | |
| 98 | + describe("getTemplateForModel", () => { | |
| 99 | + it("should return the correct template for a supported model", () => { | |
| 100 | + const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER); | |
| 101 | + expect(template).toBe( | |
| 102 | + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template, | |
| 103 | + ); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should throw an error for an unsupported model", () => { | |
| 107 | + expect(() => | |
| 108 | + getTemplateForModel("unsupported" as NEXT_EDIT_MODELS), | |
| 109 | + ).toThrow("Model unsupported is not supported for next edit."); | |
| 241 | 110 | }); |
| 242 | 111 | }); |
| 243 | 112 | }); |
modified core/nextEdit/types.ts +35 −0
| @@ -5,7 +5,9 @@ | ||
| 5 | 5 | RangeInFile, |
| 6 | 6 | TabAutocompleteOptions, |
| 7 | 7 | } from "../"; |
| 8 | +import { SnippetPayload } from "../autocomplete/snippets"; | |
| 8 | 9 | import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; |
| 10 | +import { HelperVars } from "../autocomplete/util/HelperVars"; | |
| 9 | 11 | |
| 10 | 12 | export type RecentlyEditedRange = RangeInFile & { |
| 11 | 13 | timestamp: number; |
| @@ -104,3 +106,36 @@ | ||
| 104 | 106 | editDiffHistory: string; // could be a singe large unified diff |
| 105 | 107 | currentFilePath: string; |
| 106 | 108 | } |
| 109 | + | |
| 110 | +/** | |
| 111 | + * Context object containing all necessary information for model-specific operations. | |
| 112 | + */ | |
| 113 | +export interface ModelSpecificContext { | |
| 114 | + helper: HelperVars; | |
| 115 | + snippetPayload: SnippetPayload; | |
| 116 | + editableRegionStartLine: number; | |
| 117 | + editableRegionEndLine: number; | |
| 118 | + diffContext: string[]; | |
| 119 | + autocompleteContext: string; | |
| 120 | + historyDiff?: string; | |
| 121 | + workspaceDirs?: string[]; | |
| 122 | +} | |
| 123 | + | |
| 124 | +/** | |
| 125 | + * Configuration for editable region calculation. | |
| 126 | + */ | |
| 127 | +export interface EditableRegionConfig { | |
| 128 | + usingFullFileDiff?: boolean; | |
| 129 | + maxTokens?: number; | |
| 130 | + topMargin?: number; | |
| 131 | + bottomMargin?: number; | |
| 132 | +} | |
| 133 | + | |
| 134 | +/** | |
| 135 | + * Configuration for prompt generation. | |
| 136 | + */ | |
| 137 | +export interface PromptConfig { | |
| 138 | + includeHistory?: boolean; | |
| 139 | + includeRecentEdits?: boolean; | |
| 140 | + maxContextSnippets?: number; | |
| 141 | +} |
modified core/nextEdit/utils.ts +9 −0
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { DiffLine } from ".."; |
| 2 | +import { NEXT_EDIT_MODELS } from "../llm/constants"; | |
| 2 | 3 | |
| 3 | 4 | export function isNextEditTest(): boolean { |
| 4 | 5 | const enabled = process.env.NEXT_EDIT_TEST_ENABLED; |
| @@ -21,3 +22,11 @@ | ||
| 21 | 22 | (diff.line.trim() === "" || /^\s+$/.test(diff.line)), |
| 22 | 23 | ); |
| 23 | 24 | } |
| 25 | + | |
| 26 | +export function convertNextEditModelNameToEnum( | |
| 27 | + modelName: string, | |
| 28 | +): NEXT_EDIT_MODELS | undefined { | |
| 29 | + const nextEditModels = Object.values(NEXT_EDIT_MODELS); | |
| 30 | + | |
| 31 | + return nextEditModels.find((model) => modelName.includes(model)); | |
| 32 | +} |
modified core/nextEdit/utils.vitest.ts +38 −1
| @@ -1,6 +1,11 @@ | ||
| 1 | 1 | import { describe, expect, test, vi } from "vitest"; |
| 2 | 2 | import { DiffLine } from ".."; |
| 3 | -import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils"; | |
| 3 | +import { NEXT_EDIT_MODELS } from "../llm/constants"; | |
| 4 | +import { | |
| 5 | + convertNextEditModelNameToEnum, | |
| 6 | + isNextEditTest, | |
| 7 | + isWhitespaceOnlyDeletion, | |
| 8 | +} from "./utils"; | |
| 4 | 9 | |
| 5 | 10 | describe("isNextEditTest", () => { |
| 6 | 11 | test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => { |
| @@ -57,3 +62,35 @@ | ||
| 57 | 62 | expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true); |
| 58 | 63 | }); |
| 59 | 64 | }); |
| 65 | + | |
| 66 | +describe("convertNextEditModelNameToEnum", () => { | |
| 67 | + test("returns correct enum for exact matches", () => { | |
| 68 | + Object.values(NEXT_EDIT_MODELS).forEach((model) => { | |
| 69 | + expect(convertNextEditModelNameToEnum(model)).toBe(model); | |
| 70 | + }); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + test("returns correct enum when model name is contained in a longer string", () => { | |
| 74 | + expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe( | |
| 75 | + NEXT_EDIT_MODELS.MERCURY_CODER, | |
| 76 | + ); | |
| 77 | + expect(convertNextEditModelNameToEnum("blah/instinct")).toBe( | |
| 78 | + NEXT_EDIT_MODELS.INSTINCT, | |
| 79 | + ); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + test("returns undefined for non-matching model names", () => { | |
| 83 | + expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined(); | |
| 84 | + expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined(); | |
| 85 | + expect(convertNextEditModelNameToEnum("")).toBeUndefined(); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + test("returns first match when multiple models could match", () => { | |
| 89 | + const modelName = "model-that-contains-multiple-matches"; | |
| 90 | + const result = convertNextEditModelNameToEnum(modelName); | |
| 91 | + | |
| 92 | + if (result !== undefined) { | |
| 93 | + expect(Object.values(NEXT_EDIT_MODELS)).toContain(result); | |
| 94 | + } | |
| 95 | + }); | |
| 96 | +}); |
modified core/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified core/package.json +3 −2
| @@ -36,6 +36,8 @@ | ||
| 36 | 36 | "@types/tar": "^6.1.13", |
| 37 | 37 | "@types/uuid": "^9.0.7", |
| 38 | 38 | "@types/win-ca": "^3.5.4", |
| 39 | + "@typescript-eslint/eslint-plugin": "^8.40.0", | |
| 40 | + "@typescript-eslint/parser": "^8.40.0", | |
| 39 | 41 | "cross-env": "^7.0.3", |
| 40 | 42 | "esbuild": "0.17.19", |
| 41 | 43 | "eslint": "^8", |
| @@ -66,7 +68,6 @@ | ||
| 66 | 68 | "@sentry/esbuild-plugin": "^4.0.2", |
| 67 | 69 | "@sentry/node": "^9.43.0", |
| 68 | 70 | "@sentry/vite-plugin": "^4.0.2", |
| 69 | - "@typescript-eslint/eslint-plugin": "^7.8.0", | |
| 70 | 71 | "@xenova/transformers": "2.14.0", |
| 71 | 72 | "adf-to-md": "^1.1.0", |
| 72 | 73 | "async-mutex": "^0.5.0", |
| @@ -85,7 +86,7 @@ | ||
| 85 | 86 | "http-proxy-agent": "^7.0.1", |
| 86 | 87 | "https-proxy-agent": "^7.0.3", |
| 87 | 88 | "iconv-lite": "^0.6.3", |
| 88 | - "ignore": "^5.3.1", | |
| 89 | + "ignore": "^7.0.5", | |
| 89 | 90 | "is-localhost-ip": "^2.0.0", |
| 90 | 91 | "jinja-js": "0.1.8", |
| 91 | 92 | "js-tiktoken": "^1.0.8", |
modified core/tools/definitions/readCurrentlyOpenFile.ts +1 −1
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.ReadCurrentlyOpenFile, |
| 15 | 15 | description: |
| 16 | - "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this", | |
| 16 | + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | properties: {}, |
modified core/tools/implementations/lsTool.ts +3 −0
| @@ -1,3 +1,5 @@ | ||
| 1 | +import ignore from "ignore"; | |
| 2 | + | |
| 1 | 3 | import { ToolImpl } from "."; |
| 2 | 4 | import { walkDir } from "../../indexing/walkDir"; |
| 3 | 5 | import { resolveRelativePathInDir } from "../../util/ideUtils"; |
| @@ -27,6 +29,7 @@ | ||
| 27 | 29 | returnRelativeUrisPaths: true, |
| 28 | 30 | include: "both", |
| 29 | 31 | recursive: args?.recursive ?? false, |
| 32 | + overrideDefaultIgnores: ignore(), // Show all directories including dist/, build/, etc. | |
| 30 | 33 | }); |
| 31 | 34 | |
| 32 | 35 | const lines = entries.slice(0, MAX_LS_TOOL_LINES); |
modified core/tools/implementations/readCurrentlyOpenFile.ts +3 −1
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | import { getUriDescription } from "../../util/uri"; |
| 2 | 2 | |
| 3 | 3 | import { ToolImpl } from "."; |
| 4 | +import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; | |
| 4 | 5 | import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; |
| 5 | 6 | |
| 6 | -export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { | |
| 7 | +export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => { | |
| 7 | 8 | const result = await extras.ide.getCurrentFile(); |
| 8 | 9 | |
| 9 | 10 | if (result) { |
| 11 | + throwIfFileIsSecurityConcern(result.path); | |
| 10 | 12 | await throwIfFileExceedsHalfOfContext( |
| 11 | 13 | result.path, |
| 12 | 14 | result.contents, |
modified core/tools/implementations/readFile.ts +2 −0
| @@ -2,11 +2,13 @@ | ||
| 2 | 2 | import { getUriPathBasename } from "../../util/uri"; |
| 3 | 3 | |
| 4 | 4 | import { ToolImpl } from "."; |
| 5 | +import { throwIfFileIsSecurityConcern } from "../../indexing/ignore"; | |
| 5 | 6 | import { getStringArg } from "../parseArgs"; |
| 6 | 7 | import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; |
| 7 | 8 | |
| 8 | 9 | export const readFileImpl: ToolImpl = async (args, extras) => { |
| 9 | 10 | const filepath = getStringArg(args, "filepath"); |
| 11 | + throwIfFileIsSecurityConcern(filepath); | |
| 10 | 12 | |
| 11 | 13 | const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); |
| 12 | 14 | if (!firstUriMatch) { |
modified docs/customization/models.mdx +4 −4
| @@ -18,11 +18,11 @@ | ||
| 18 | 18 | |
| 19 | 19 | | Model role | Best open models | Best closed models | Notes | |
| 20 | 20 | |:------------|:------------------|:-------------------|:--------| |
| 21 | -| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models | | |
| 22 | -| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | | |
| 23 | -| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models | | |
| 21 | +| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Qwen2.5-Coder (32B), Devstral (27B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), GPT-4, [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro), DeepSeek models | Closed models are slightly better than open models | | |
| 22 | +| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B), DeepSeek Chat | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | | |
| 23 | +| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder, Mercury Coder Small, DeepSeek Coder | Closed models are slightly better than open models | | |
| 24 | 24 | | Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role | |
| 25 | -| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role | | |
| 25 | +| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, text-embedding-3-large, text-embedding-004 | Open embeddings models are emerging but closed models still perform better | | |
| 26 | 26 | | Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role | |
| 27 | 27 | | Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models | |
| 28 | 28 |
modified docs/customize/model-providers/top-level/azure.mdx +1 −1
| @@ -92,7 +92,7 @@ | ||
| 92 | 92 | |
| 93 | 93 | ## How to Configure Azure AI Foundry Embeddings Models |
| 94 | 94 | |
| 95 | -We recommend configuring **text-embedding-3-large** as your embeddings model. | |
| 95 | +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). | |
| 96 | 96 | |
| 97 | 97 | <Tabs> |
| 98 | 98 | <Tab title="YAML"> |
modified docs/customize/model-providers/top-level/deepseek.mdx +1 −1
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | |
| 42 | 42 | ## How to Set Up DeepSeek Autocomplete Models |
| 43 | 43 | |
| 44 | -We recommend configuring **DeepSeek Coder** as your autocomplete model. | |
| 44 | +For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models). | |
| 45 | 45 | |
| 46 | 46 | <Tabs> |
| 47 | 47 | <Tab title="YAML"> |
modified docs/customize/model-providers/top-level/gemini.mdx +1 −1
| @@ -48,7 +48,7 @@ | ||
| 48 | 48 | |
| 49 | 49 | ## How to Configure Gemini Embeddings Models |
| 50 | 50 | |
| 51 | -We recommend configuring **text-embedding-004** as your embeddings model. | |
| 51 | +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). | |
| 52 | 52 | |
| 53 | 53 | <Tabs> |
| 54 | 54 | <Tab title="YAML"> |
modified docs/customize/model-providers/top-level/ollama.mdx +2 −2
| @@ -65,7 +65,7 @@ | ||
| 65 | 65 | |
| 66 | 66 | ## How to Set Up Ollama Embeddings Models |
| 67 | 67 | |
| 68 | -We recommend configuring **Nomic Embed Text** as your embeddings model. | |
| 68 | +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). | |
| 69 | 69 | |
| 70 | 70 | <Tabs> |
| 71 | 71 | <Tab title="YAML"> |
| @@ -123,7 +123,7 @@ | ||
| 123 | 123 | ] |
| 124 | 124 | } |
| 125 | 125 | ``` |
| 126 | - </Tab> | |
| 126 | + </Tab> | |
| 127 | 127 | </Tabs> |
| 128 | 128 | |
| 129 | 129 | ## How to Configure Model Capabilities in Ollama |
modified docs/docs.json +8 −0
| @@ -364,6 +364,10 @@ | ||
| 364 | 364 | "source": "/hub/blocks", |
| 365 | 365 | "destination": "/hub/blocks/intro" |
| 366 | 366 | }, |
| 367 | + { | |
| 368 | + "source": "/hub/agents/intro", | |
| 369 | + "destination": "/hub/assistants/intro" | |
| 370 | + }, | |
| 367 | 371 | { |
| 368 | 372 | "source": "/customize", |
| 369 | 373 | "destination": "/customization/overview" |
| @@ -1099,6 +1103,10 @@ | ||
| 1099 | 1103 | { |
| 1100 | 1104 | "source": "/customize/model-providers", |
| 1101 | 1105 | "destination": "/customize/model-providers/overview" |
| 1106 | + }, | |
| 1107 | + { | |
| 1108 | + "source": "/features/edit/next-edit", | |
| 1109 | + "destination": "/features/autocomplete/next-edit" | |
| 1102 | 1110 | } |
| 1103 | 1111 | ] |
| 1104 | 1112 | } |
modified docs/features/agent/model-setup.mdx +1 −16
| @@ -27,22 +27,7 @@ | ||
| 27 | 27 | - **Better reliability** - Models that struggle with native tools often perform better with system message tools |
| 28 | 28 | - **Seamless switching** - Change between providers without modifying your workflow |
| 29 | 29 | |
| 30 | -### What Models Are Recommended for Agent Mode | |
| 31 | - | |
| 32 | -For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities: | |
| 33 | - | |
| 34 | -**Premium Models:** | |
| 35 | - | |
| 36 | -- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning | |
| 37 | -- **GPT-4** models (OpenAI) - Excellent native tool support | |
| 38 | -- **DeepSeek** models - Strong performance with competitive pricing | |
| 39 | - | |
| 40 | -**Local Models:** | |
| 41 | -While more limited in capabilities, these models can work with system message tools: | |
| 42 | - | |
| 43 | -- Qwen2.5-Coder 32B - Best local option for Agent mode | |
| 44 | -- Devstral 27B - Good for code-specific tasks | |
| 45 | -- Smaller models (7B-13B) - May struggle with complex tool interactions | |
| 30 | +For recommended Agent models, please refer to our [Model Recommendations page](/customization/models). | |
| 46 | 31 | |
| 47 | 32 | ### How to Configure Agent Mode |
| 48 | 33 |
modified docs/features/autocomplete/model-setup.mdx +2 −40
| @@ -10,49 +10,11 @@ | ||
| 10 | 10 | For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models). |
| 11 | 11 | </Info> |
| 12 | 12 | |
| 13 | -## Recommended Models for Autocomplete in Continue | |
| 14 | - | |
| 15 | -### Hosted (Best Performance) | |
| 16 | - | |
| 17 | -For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. | |
| 18 | - | |
| 19 | -This model is specifically designed for code completion and offers excellent performance across multiple programming languages. | |
| 20 | - | |
| 21 | -**Codestral Quick Setup:** | |
| 22 | - | |
| 23 | -1. Get your API key from [Mistral AI](https://console.mistral.ai) | |
| 24 | -2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub | |
| 25 | -3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) | |
| 26 | -4. Click `Reload config` in the assistant selector in the Continue IDE extension | |
| 27 | - | |
| 28 | -### Hosted (Best Speed/Quality Tradeoff) | |
| 29 | - | |
| 30 | -For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception. | |
| 31 | - | |
| 32 | -This model is specifically designed for code completion and is particularly fast because it is a diffusion model. | |
| 33 | - | |
| 34 | -**Mercury Coder Small Quick Setup:** | |
| 35 | - | |
| 36 | -1. Get your API key from [Inception](https://platform.inceptionlabs.ai/) | |
| 37 | -2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub | |
| 38 | -3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) | |
| 39 | -4. Click `Reload config` in the assistant selector in the Continue IDE extension | |
| 40 | - | |
| 41 | -### Local (Offline / Privacy First) | |
| 42 | - | |
| 43 | -For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**. | |
| 44 | - | |
| 45 | -This model provides good suggestions while keeping your code completely private. | |
| 46 | - | |
| 47 | -**Quick Setup:** | |
| 48 | - | |
| 49 | -1. Install [Ollama](https://ollama.ai/) | |
| 50 | -2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub | |
| 51 | -3. Click `Reload config` in the assistant selector in the Continue IDE extension | |
| 13 | +For model recommendations, please refer to our [Model Recommendations page](/customization/models). | |
| 52 | 14 | |
| 53 | 15 | ## Next Edit Model |
| 54 | 16 | |
| 55 | -For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/edit/next-edit) models: | |
| 17 | +For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models: | |
| 56 | 18 | |
| 57 | 19 | **Supported Next Edit model:** |
| 58 | 20 |
modified docs/features/chat/model-setup.mdx +1 −10
| @@ -7,16 +7,7 @@ | ||
| 7 | 7 | For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models). |
| 8 | 8 | </Info> |
| 9 | 9 | |
| 10 | -## What Models Are Recommended for Chat? | |
| 11 | - | |
| 12 | -Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic. | |
| 13 | - | |
| 14 | -Its strong tool calling and reasoning capabilities make it the best model for Agent mode. | |
| 15 | - | |
| 16 | -1. Get your API key from [Anthropic](https://console.anthropic.com/) | |
| 17 | -2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub | |
| 18 | -3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) | |
| 19 | -4. Click `Reload config` in the assistant selector in the Continue IDE extension | |
| 10 | +For model recommendations, please refer to our [Model Recommendations page](/customization/models). | |
| 20 | 11 | |
| 21 | 12 | ### What Other Hosted Models Are Available? |
| 22 | 13 |
modified docs/features/edit/how-it-works.mdx +1 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. |
| 15 | 15 | |
| 16 | 16 | <Info> |
| 17 | -**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/edit/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. | |
| 17 | +**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. | |
| 18 | 18 | </Info> |
| 19 | 19 | |
| 20 | 20 | If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs). |
modified docs/features/edit/model-setup.mdx +1 −4
| @@ -16,10 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | We also recommend setting up an Apply model for the best Edit experience. |
| 18 | 18 | |
| 19 | -**Recommended Apply models:** | |
| 20 | - | |
| 21 | -- [Morph v3](https://hub.continue.dev/morphllm/morph-v2) | |
| 22 | -- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply) | |
| 19 | +For recommended Apply models, please refer to our [Model Recommendations page](/customization/models). | |
| 23 | 20 | |
| 24 | 21 | ## How to Determine Model Compatibility |
| 25 | 22 |
modified docs/guides/ollama-guide.mdx +115 −38
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | ## How to Install Ollama - Step-by-Step |
| 16 | 16 | |
| 17 | -### Step 1: How to Install Ollama | |
| 17 | +### Step 1: Install Ollama | |
| 18 | 18 | |
| 19 | 19 | Choose the installation method for your operating system: |
| 20 | 20 | |
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | # Download from ollama.ai |
| 30 | 30 | ``` |
| 31 | 31 | |
| 32 | -### Step 2: How to Start Ollama | |
| 32 | +### Step 2: Start Ollama Service | |
| 33 | 33 | |
| 34 | 34 | After installation, start the Ollama service: |
| 35 | 35 | |
| @@ -40,12 +40,17 @@ | ||
| 40 | 40 | # Verify it's running |
| 41 | 41 | curl http://localhost:11434 |
| 42 | 42 | # Should return "Ollama is running" |
| 43 | + | |
| 44 | +# Check Ollama version | |
| 45 | +ollama --version | |
| 43 | 46 | ``` |
| 44 | 47 | |
| 45 | -### Step 3: How to Download Models | |
| 48 | +### Step 3: Download Models | |
| 46 | 49 | |
| 47 | 50 | <Warning> |
| 48 | -**Important**: Always use `ollama pull` instead of `ollama run` to download models. The `run` command starts an interactive session which isn't needed for Continue. | |
| 51 | + **Important**: Always use `ollama pull` instead of `ollama run` to download | |
| 52 | + models. The `run` command starts an interactive session which isn't needed for | |
| 53 | + Continue. | |
| 49 | 54 | </Warning> |
| 50 | 55 | |
| 51 | 56 | Download models using the exact tag specified: |
| @@ -62,12 +67,15 @@ | ||
| 62 | 67 | ``` |
| 63 | 68 | |
| 64 | 69 | **Common Model Tags:** |
| 70 | + | |
| 65 | 71 | - `:latest` - Default version (used if no tag specified) |
| 66 | 72 | - `:32b`, `:7b`, `:1.5b` - Parameter count versions |
| 67 | 73 | - `:instruct`, `:base` - Model variants |
| 68 | 74 | |
| 69 | 75 | <Note> |
| 70 | -If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be a different size. | |
| 76 | + If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it | |
| 77 | + with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be | |
| 78 | + a different size. | |
| 71 | 79 | </Note> |
| 72 | 80 | |
| 73 | 81 | ## How to Configure Ollama with Continue |
| @@ -76,10 +84,9 @@ | ||
| 76 | 84 | |
| 77 | 85 | ### Method 1: Using Hub Model Blocks in Local config.yaml |
| 78 | 86 | |
| 79 | -The easiest way is to use pre-configured model blocks from the Continue Hub in your local configuration: | |
| 87 | +The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration: | |
| 80 | 88 | |
| 81 | -```yaml | |
| 82 | -# ~/.continue/assistants/My Local Assistant.yaml | |
| 89 | +```yaml title="~/.continue/assistants/My Local Assistant.yaml" | |
| 83 | 90 | name: My Local Assistant |
| 84 | 91 | version: 0.0.1 |
| 85 | 92 | schema: v1 |
| @@ -90,20 +97,20 @@ | ||
| 90 | 97 | ``` |
| 91 | 98 | |
| 92 | 99 | <Warning> |
| 93 | -**Important**: Hub blocks only provide configuration - you still need to pull the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue to use `model: deepseek-r1:32b`, but the actual model must be installed: | |
| 94 | -```bash | |
| 95 | -# Check what the hub block expects (view on hub.continue.dev) | |
| 96 | -# Then pull that exact model tag locally | |
| 97 | -ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block | |
| 98 | -``` | |
| 99 | -If the model isn't installed, Ollama will return: `404 model "deepseek-r1:32b" not found, try pulling it first` | |
| 100 | + **Important**: Hub blocks only provide configuration - you still need to pull | |
| 101 | + the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue | |
| 102 | + to use `model: deepseek-r1:32b`, but the actual model must be installed: | |
| 103 | + ```bash # Check what the hub block expects (view on hub.continue.dev) # Then | |
| 104 | + pull that exact model tag locally ollama pull deepseek-r1:32b # Required for | |
| 105 | + ollama/deepseek-r1-32b hub block ``` If the model isn't installed, Ollama will | |
| 106 | + return: `404 model "deepseek-r1:32b" not found, try pulling it first` | |
| 100 | 107 | </Warning> |
| 101 | 108 | |
| 102 | 109 | ### Method 2: Using Autodetect |
| 103 | 110 | |
| 104 | 111 | Continue can automatically detect available Ollama models. You can configure this in your YAML: |
| 105 | 112 | |
| 106 | -```yaml | |
| 113 | +```yaml title="~/.continue/config.yaml" | |
| 107 | 114 | models: |
| 108 | 115 | - name: Autodetect |
| 109 | 116 | provider: ollama |
| @@ -112,6 +119,8 @@ | ||
| 112 | 119 | - chat |
| 113 | 120 | - edit |
| 114 | 121 | - apply |
| 122 | + - rerank | |
| 123 | + - autocomplete | |
| 115 | 124 | ``` |
| 116 | 125 | |
| 117 | 126 | Or use it through the GUI: |
| @@ -122,7 +131,12 @@ | ||
| 122 | 131 | 4. Select your desired model from the detected list |
| 123 | 132 | |
| 124 | 133 | <Note> |
| 125 | -The Autodetect feature scans your local Ollama installation and lists all available models. When set to `AUTODETECT`, Continue will dynamically populate the model list based on what's installed locally via `ollama list`. This is useful for quickly switching between models without manual configuration. | |
| 134 | + The Autodetect feature scans your local Ollama installation and lists all | |
| 135 | + available models. When set to `AUTODETECT`, Continue will dynamically populate | |
| 136 | + the model list based on what's installed locally via `ollama list`. This is | |
| 137 | + useful for quickly switching between models without manual configuration. For | |
| 138 | + any roles not covered by the detected models, you may need to manually | |
| 139 | + configure them. | |
| 126 | 140 | </Note> |
| 127 | 141 | |
| 128 | 142 | You can update `apiBase` with the IP address of a remote machine serving Ollama. |
| @@ -135,12 +149,12 @@ | ||
| 135 | 149 | models: |
| 136 | 150 | - name: DeepSeek R1 32B |
| 137 | 151 | provider: ollama |
| 138 | - model: deepseek-r1:32b # Must match exactly what `ollama list` shows | |
| 152 | + model: deepseek-r1:32b # Must match exactly what `ollama list` shows | |
| 139 | 153 | apiBase: http://localhost:11434 |
| 140 | 154 | roles: |
| 141 | 155 | - chat |
| 142 | 156 | - edit |
| 143 | - capabilities: # Add if not auto-detected | |
| 157 | + capabilities: # Add if not auto-detected | |
| 144 | 158 | - tool_use |
| 145 | 159 | - name: Qwen2.5-Coder 1.5B |
| 146 | 160 | provider: ollama |
| @@ -161,14 +175,16 @@ | ||
| 161 | 175 | provider: ollama |
| 162 | 176 | model: deepseek-r1:latest |
| 163 | 177 | capabilities: |
| 164 | - - tool_use # Add this to enable tools | |
| 178 | + - tool_use # Add this to enable tools | |
| 165 | 179 | ``` |
| 166 | 180 | |
| 167 | 181 | <Warning> |
| 168 | -**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not supported" or "does not support tools" even with capabilities configured. This is a known limitation where the model's actual tool support differs from its advertised capabilities. | |
| 182 | + **Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not | |
| 183 | + supported" or "does not support tools" even with capabilities configured. This | |
| 184 | + is a known limitation where the model's actual tool support differs from its | |
| 185 | + advertised capabilities. | |
| 169 | 186 | </Warning> |
| 170 | 187 | |
| 171 | - | |
| 172 | 188 | #### If Agent Mode Shows "Not Supported" |
| 173 | 189 | |
| 174 | 190 | 1. First, add `capabilities: [tool_use]` to your model config |
| @@ -181,29 +197,70 @@ | ||
| 181 | 197 | |
| 182 | 198 | For optimal performance, consider these advanced configuration options: |
| 183 | 199 | |
| 184 | -- Memory optimization: Adjust `num_ctx` for context window size | |
| 185 | -- GPU acceleration: Use `num_gpu` to control GPU layers | |
| 186 | -- Custom model parameters: Temperature, top_p, top_k settings | |
| 187 | -- Performance tuning: Batch size and threading options | |
| 200 | +```yaml | |
| 201 | +models: | |
| 202 | + - name: Optimized DeepSeek | |
| 203 | + provider: ollama | |
| 204 | + model: deepseek-r1:32b | |
| 205 | + contextLength: 8192 # Adjust context window (default varies by model) | |
| 206 | + completionOptions: | |
| 207 | + temperature: 0.7 # Controls randomness (0.0-1.0) | |
| 208 | + top_p: 0.9 # Nucleus sampling threshold | |
| 209 | + top_k: 40 # Top-k sampling | |
| 210 | + num_predict: 2048 # Max tokens to generate | |
| 211 | + # Ollama-specific options (set via environment or modelfile) | |
| 212 | + # num_gpu: 35 # Number of GPU layers to offload | |
| 213 | + # num_thread: 8 # CPU threads to use | |
| 214 | +``` | |
| 215 | + | |
| 216 | +For GPU acceleration and memory tuning, create an Ollama Modelfile: | |
| 217 | + | |
| 218 | +``` | |
| 219 | +# Create custom model with optimizations | |
| 220 | +FROM deepseek-r1:32b | |
| 221 | +PARAMETER num_gpu 35 | |
| 222 | +PARAMETER num_thread 8 | |
| 223 | +PARAMETER num_ctx 4096 | |
| 224 | +``` | |
| 188 | 225 | |
| 189 | 226 | ## What Are the Best Practices for Ollama |
| 190 | 227 | |
| 191 | 228 | ### How to Choose the Right Model |
| 192 | 229 | |
| 193 | -Choose models based on your specific needs: | |
| 230 | +Choose models based on your specific needs (see [recommended models](/customization/models#recommended-models) for more options): | |
| 231 | + | |
| 232 | +1. **Code Generation**: | |
| 233 | + | |
| 234 | + - `qwen2.5-coder:7b` - Excellent for code completion | |
| 235 | + - `codellama:13b` - Strong general coding support | |
| 236 | + - `deepseek-coder:6.7b` - Fast and efficient | |
| 237 | + | |
| 238 | +2. **Chat & Reasoning**: | |
| 239 | + | |
| 240 | + - `llama3.1:8b` - Latest Llama with tool support | |
| 241 | + - `mistral:7b` - Fast and versatile | |
| 242 | + - `deepseek-r1:32b` - Advanced reasoning capabilities | |
| 194 | 243 | |
| 195 | -1. **Code Generation**: Use CodeLlama or Mistral | |
| 196 | -2. **Chat**: Llama2 or Mistral | |
| 197 | -3. **Specialized Tasks**: Domain-specific models | |
| 244 | +3. **Autocomplete**: | |
| 245 | + | |
| 246 | + - `qwen2.5-coder:1.5b` - Lightweight and fast | |
| 247 | + - `starcoder2:3b` - Optimized for code completion | |
| 248 | + | |
| 249 | +4. **Memory Requirements**: | |
| 250 | + - 1.5B-3B models: ~4GB RAM | |
| 251 | + - 7B models: ~8GB RAM | |
| 252 | + - 13B models: ~16GB RAM | |
| 253 | + - 32B models: ~32GB RAM | |
| 198 | 254 | |
| 199 | 255 | ### How to Optimize Performance |
| 200 | 256 | |
| 201 | 257 | To get the best performance from Ollama: |
| 202 | 258 | |
| 203 | -- Monitor system resources | |
| 204 | -- Adjust context window size | |
| 205 | -- Use appropriate model sizes | |
| 206 | -- Enable GPU acceleration when available | |
| 259 | +- Monitor system resources with `ollama ps` to see memory usage | |
| 260 | +- Adjust context window size based on available RAM | |
| 261 | +- Use appropriate model sizes for your hardware | |
| 262 | +- Enable GPU acceleration when available (NVIDIA CUDA or AMD ROCm) | |
| 263 | +- Use `ollama logs` to debug performance issues | |
| 207 | 264 | |
| 208 | 265 | ## How to Troubleshoot Ollama Issues |
| 209 | 266 | |
| @@ -214,7 +271,8 @@ | ||
| 214 | 271 | This error occurs when the model isn't installed locally: |
| 215 | 272 | |
| 216 | 273 | **Problem**: Using a hub block or config that references a model not yet pulled |
| 217 | -**Solution**: | |
| 274 | +**Solution**: | |
| 275 | + | |
| 218 | 276 | ```bash |
| 219 | 277 | # Check what models you have |
| 220 | 278 | ollama list |
| @@ -227,6 +285,7 @@ | ||
| 227 | 285 | |
| 228 | 286 | **Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b` |
| 229 | 287 | **Solution**: Always pull with the exact tag: |
| 288 | + | |
| 230 | 289 | ```bash |
| 231 | 290 | # Wrong - pulls :latest |
| 232 | 291 | ollama pull deepseek-r1 |
| @@ -239,6 +298,7 @@ | ||
| 239 | 298 | |
| 240 | 299 | **Problem**: Model doesn't support tools/function calling |
| 241 | 300 | **Solutions**: |
| 301 | + | |
| 242 | 302 | 1. Add `capabilities: [tool_use]` to your model config |
| 243 | 303 | 2. If still not working, the model may not actually support tools |
| 244 | 304 | 3. Switch to a model with confirmed tool support (Llama 3.1, Mistral) |
| @@ -247,6 +307,7 @@ | ||
| 247 | 307 | |
| 248 | 308 | **Problem**: Unclear how to use hub models locally |
| 249 | 309 | **Solution**: Create a local assistant file: |
| 310 | + | |
| 250 | 311 | ```yaml |
| 251 | 312 | # ~/.continue/assistants/Local.yaml |
| 252 | 313 | name: Local Assistant |
| @@ -269,13 +330,29 @@ | ||
| 269 | 330 | - Model too large: Check available memory with `ollama ps` |
| 270 | 331 | - GPU issues: Verify CUDA/ROCm installation for GPU acceleration |
| 271 | 332 | - Slow generation: Adjust `num_gpu` layers in model configuration |
| 333 | +- Check system diagnostics: `ollama ps` for active models and memory usage | |
| 272 | 334 | |
| 273 | 335 | ## What Are Example Workflows with Ollama |
| 274 | 336 | |
| 275 | 337 | ### How to Use Ollama for Code Generation |
| 276 | 338 | |
| 277 | -``` | |
| 278 | -# Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass | |
| 339 | +```python | |
| 340 | +# Example: Generate a FastAPI endpoint | |
| 341 | +from fastapi import FastAPI, HTTPException | |
| 342 | +from pydantic import BaseModel | |
| 343 | + | |
| 344 | +app = FastAPI() | |
| 345 | + | |
| 346 | +class User(BaseModel): | |
| 347 | + name: str | |
| 348 | + email: str | |
| 349 | + age: int | |
| 350 | + | |
| 351 | +@app.post("/users/") | |
| 352 | +async def create_user(user: User): | |
| 353 | + # Continue will help complete this implementation | |
| 354 | + # Use Cmd+I (Mac) or Ctrl+I (Windows/Linux) to generate code | |
| 355 | + pass | |
| 279 | 356 | ``` |
| 280 | 357 | |
| 281 | 358 | ### How to Use Ollama for Code Review |
| @@ -293,4 +370,4 @@ | ||
| 293 | 370 | |
| 294 | 371 | --- |
| 295 | 372 | |
| 296 | -_This guide is based on Ollama v0.1.x and Continue v0.8.x. Please check for updates regularly._ | |
| 373 | +_This guide is based on Ollama v0.11.x and Continue v1.1.x. Please check for updates regularly._ |
added extensions/cli/BUILD.md +74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +# Build Process Documentation | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +The Continue CLI uses esbuild to bundle the application along with local packages (`@continuedev/config-yaml` and `@continuedev/openai-adapters`) into a single distributable file. This ensures that users who install the CLI from npm don't need to worry about local file references. | |
| 6 | + | |
| 7 | +## Build Steps | |
| 8 | + | |
| 9 | +1. **Install dependencies**: `npm install` | |
| 10 | +2. **Build**: `npm run build` | |
| 11 | + - This first builds the local packages | |
| 12 | + - Then bundles everything with esbuild | |
| 13 | + | |
| 14 | +## How it Works | |
| 15 | + | |
| 16 | +### Bundling Strategy | |
| 17 | + | |
| 18 | +The `build.mjs` script uses esbuild to: | |
| 19 | + | |
| 20 | +- Bundle all TypeScript/JavaScript code into a single ES module | |
| 21 | +- Include local packages (`@continuedev/config-yaml`, `@continuedev/openai-adapters`) directly in the bundle | |
| 22 | +- Keep problematic or native dependencies external (e.g., `@sentry/profiling-node`, `winston`, `express`) | |
| 23 | +- Create a wrapper script (`dist/cn.js`) with the proper shebang for CLI execution | |
| 24 | + | |
| 25 | +### Key Features | |
| 26 | + | |
| 27 | +- **Local Package Bundling**: Local packages are bundled directly, avoiding `file:` reference issues | |
| 28 | +- **Stub for Optional Dependencies**: `react-devtools-core` is stubbed to prevent runtime errors | |
| 29 | +- **CommonJS Compatibility**: Adds `createRequire` to support packages that use dynamic requires | |
| 30 | +- **Source Maps**: Generates source maps for debugging | |
| 31 | +- **Metadata**: Creates `dist/meta.json` with bundle analysis information | |
| 32 | + | |
| 33 | +## Testing | |
| 34 | + | |
| 35 | +### Smoke Tests | |
| 36 | + | |
| 37 | +Run smoke tests to verify the build: | |
| 38 | + | |
| 39 | +```bash | |
| 40 | +npm run test:smoke | |
| 41 | +``` | |
| 42 | + | |
| 43 | +The smoke tests verify: | |
| 44 | + | |
| 45 | +- Bundle files exist | |
| 46 | +- CLI commands work (--version, --help) | |
| 47 | +- Bundle size is reasonable (<20MB) | |
| 48 | +- Local packages are properly bundled | |
| 49 | +- No missing runtime dependencies | |
| 50 | + | |
| 51 | +## Troubleshooting | |
| 52 | + | |
| 53 | +### Common Issues | |
| 54 | + | |
| 55 | +1. **Module not found errors**: Check if the module needs to be added to the external list in `build.mjs` | |
| 56 | +2. **Native module issues**: Native modules should be marked as external | |
| 57 | +3. **Bundle too large**: Review bundled packages in `dist/meta.json` and consider marking large packages as external | |
| 58 | + | |
| 59 | +### Analyzing the Bundle | |
| 60 | + | |
| 61 | +After building, check `dist/meta.json` to see: | |
| 62 | + | |
| 63 | +- What packages were bundled | |
| 64 | +- Bundle size breakdown | |
| 65 | +- Input/output file mappings | |
| 66 | + | |
| 67 | +## Publishing | |
| 68 | + | |
| 69 | +When publishing to npm: | |
| 70 | + | |
| 71 | +1. The bundled files in `dist/` are included | |
| 72 | +2. Users install via `npm install -g @continuedev/cli` | |
| 73 | +3. The `cn` command becomes available globally | |
| 74 | +4. No local file references or missing dependencies |
added extensions/cli/build.mjs +97 −0
| @@ -0,0 +1,97 @@ | ||
| 1 | +#!/usr/bin/env node | |
| 2 | + | |
| 3 | +import * as esbuild from "esbuild"; | |
| 4 | +import { chmodSync, writeFileSync } from "fs"; | |
| 5 | +import { dirname, resolve } from "path"; | |
| 6 | +import { fileURLToPath } from "url"; | |
| 7 | + | |
| 8 | +const __dirname = dirname(fileURLToPath(import.meta.url)); | |
| 9 | + | |
| 10 | +// List of packages to mark as external (ONLY native modules that cannot be bundled) | |
| 11 | +// Note: Everything else will be bundled to create a self-contained CLI | |
| 12 | +// Users should not need to install any additional dependencies | |
| 13 | +const external = [ | |
| 14 | + "@sentry/profiling-node", // Contains native profiler bindings (optional) | |
| 15 | + "fsevents", // macOS native file watcher (optional dependency) | |
| 16 | +]; | |
| 17 | + | |
| 18 | +console.log("Building CLI with esbuild..."); | |
| 19 | + | |
| 20 | +// Plugin to handle optional react-devtools-core | |
| 21 | +const optionalDevtoolsPlugin = { | |
| 22 | + name: "optional-devtools", | |
| 23 | + setup(build) { | |
| 24 | + build.onResolve({ filter: /^react-devtools-core$/ }, () => { | |
| 25 | + // Return path to our stub instead of marking as external | |
| 26 | + return { path: resolve(__dirname, "stubs/react-devtools-core.js") }; | |
| 27 | + }); | |
| 28 | + }, | |
| 29 | +}; | |
| 30 | + | |
| 31 | +try { | |
| 32 | + const result = await esbuild.build({ | |
| 33 | + entryPoints: ["src/index.ts"], | |
| 34 | + bundle: true, | |
| 35 | + platform: "node", | |
| 36 | + target: "node18", | |
| 37 | + format: "esm", | |
| 38 | + outfile: "dist/index.js", | |
| 39 | + external, | |
| 40 | + sourcemap: true, | |
| 41 | + minify: true, // Minify for smaller bundle size | |
| 42 | + metafile: true, | |
| 43 | + plugins: [optionalDevtoolsPlugin], | |
| 44 | + | |
| 45 | + // Handle .js extensions in imports | |
| 46 | + resolveExtensions: [".ts", ".tsx", ".js", ".jsx", ".json"], | |
| 47 | + | |
| 48 | + // Handle TypeScript paths and local packages | |
| 49 | + alias: { | |
| 50 | + "@continuedev/config-yaml": resolve( | |
| 51 | + __dirname, | |
| 52 | + "../../packages/config-yaml/dist/index.js", | |
| 53 | + ), | |
| 54 | + "@continuedev/openai-adapters": resolve( | |
| 55 | + __dirname, | |
| 56 | + "../../packages/openai-adapters/dist/index.js", | |
| 57 | + ), | |
| 58 | + "@continuedev/config-types": resolve( | |
| 59 | + __dirname, | |
| 60 | + "../../packages/config-types/dist/index.js", | |
| 61 | + ), | |
| 62 | + core: resolve(__dirname, "../../core"), | |
| 63 | + "@continuedev/fetch": resolve( | |
| 64 | + __dirname, | |
| 65 | + "../../packages/fetch/dist/index.js", | |
| 66 | + ), | |
| 67 | + "@continuedev/llm-info": resolve( | |
| 68 | + __dirname, | |
| 69 | + "../../packages/llm-info/dist/index.js", | |
| 70 | + ), | |
| 71 | + }, | |
| 72 | + | |
| 73 | + // Add banner to create require for CommonJS packages | |
| 74 | + banner: { | |
| 75 | + js: `import { createRequire } from 'module'; | |
| 76 | +const require = createRequire(import.meta.url);`, | |
| 77 | + }, | |
| 78 | + }); | |
| 79 | + | |
| 80 | + // Write metafile for analysis | |
| 81 | + writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2)); | |
| 82 | + | |
| 83 | + // Create wrapper script with shebang | |
| 84 | + writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');"); | |
| 85 | + | |
| 86 | + // Make the wrapper script executable | |
| 87 | + chmodSync("dist/cn.js", 0o755); | |
| 88 | + | |
| 89 | + // Calculate bundle size | |
| 90 | + const bundleSize = result.metafile.outputs["dist/index.js"].bytes; | |
| 91 | + console.log( | |
| 92 | + `✓ Build complete! Bundle size: ${(bundleSize / 1024 / 1024).toFixed(2)} MB`, | |
| 93 | + ); | |
| 94 | +} catch (error) { | |
| 95 | + console.error("Build failed:", error); | |
| 96 | + process.exit(1); | |
| 97 | +} |
modified extensions/cli/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/cli/package.json +18 −11
| @@ -6,15 +6,20 @@ | ||
| 6 | 6 | "types": "dist/index.d.ts", |
| 7 | 7 | "type": "module", |
| 8 | 8 | "bin": { |
| 9 | - "cn": "dist/index.js" | |
| 9 | + "cn": "dist/cn.js" | |
| 10 | 10 | }, |
| 11 | 11 | "scripts": { |
| 12 | 12 | "test": "vitest run", |
| 13 | 13 | "test:watch": "vitest watch", |
| 14 | 14 | "test:ui": "vitest --ui", |
| 15 | 15 | "test:e2e": "vitest run --config vitest.e2e.config.ts", |
| 16 | - "build": "tsc -p tsconfig.build.json", | |
| 17 | - "start": "node dist/index.js", | |
| 16 | + "test:smoke": "node smoke-test.mjs", | |
| 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 && cd ../extensions/cli && npm i", | |
| 19 | + "build:validate": "node validate-aliases.mjs", | |
| 20 | + "build:bundle": "node build.mjs", | |
| 21 | + "build": "npm run build:validate && npm run build:bundle", | |
| 22 | + "start": "node dist/cn.js", | |
| 18 | 23 | "dev": "tsx src/index.ts", |
| 19 | 24 | "repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml", |
| 20 | 25 | "repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml", |
| @@ -39,8 +44,11 @@ | ||
| 39 | 44 | }, |
| 40 | 45 | "homepage": "https://continue.dev", |
| 41 | 46 | "dependencies": { |
| 42 | - "@continuedev/config-yaml": "^1.0.96", | |
| 43 | - "@continuedev/openai-adapters": "^1.4.1", | |
| 47 | + "@sentry/profiling-node": "^9.43.0" | |
| 48 | + }, | |
| 49 | + "devDependencies": { | |
| 50 | + "@continuedev/config-yaml": "file:../../packages/config-yaml", | |
| 51 | + "@continuedev/openai-adapters": "file:../../packages/openai-adapters", | |
| 44 | 52 | "@continuedev/sdk": "^0.0.13", |
| 45 | 53 | "@modelcontextprotocol/sdk": "^1.17.2", |
| 46 | 54 | "@opentelemetry/api": "^1.9.0", |
| @@ -52,13 +60,13 @@ | ||
| 52 | 60 | "@opentelemetry/sdk-node": "^0.203.0", |
| 53 | 61 | "@opentelemetry/semantic-conventions": "^1.36.0", |
| 54 | 62 | "@sentry/node": "^9.43.0", |
| 55 | - "@sentry/profiling-node": "^9.43.0", | |
| 56 | 63 | "@types/express": "^5.0.3", |
| 57 | 64 | "@types/react": "^19.1.8", |
| 58 | 65 | "@types/turndown": "^5.0.5", |
| 59 | 66 | "@workos-inc/node": "^7.45.0", |
| 60 | 67 | "chalk": "^5.4.1", |
| 61 | 68 | "commander": "^14.0.0", |
| 69 | + "core": "file:../../core", | |
| 62 | 70 | "date-fns": "^4.1.0", |
| 63 | 71 | "diff": "^7.0.0", |
| 64 | 72 | "dotenv": "^16.5.0", |
| @@ -66,6 +74,7 @@ | ||
| 66 | 74 | "glob": "^11.0.3", |
| 67 | 75 | "gpt-tokenizer": "^3.0.1", |
| 68 | 76 | "gradient-string": "^3.0.0", |
| 77 | + "ignore": "^7.0.5", | |
| 69 | 78 | "ignore-walk": "^7.0.0", |
| 70 | 79 | "ink": "^6.1.0", |
| 71 | 80 | "jszip": "^3.10.1", |
| @@ -83,9 +92,7 @@ | ||
| 83 | 92 | "typescript": "^5.8.3", |
| 84 | 93 | "uuid": "^9.0.1", |
| 85 | 94 | "winston": "^3.17.0", |
| 86 | - "yaml": "^2.8.0" | |
| 87 | - }, | |
| 88 | - "devDependencies": { | |
| 95 | + "yaml": "^2.8.0", | |
| 89 | 96 | "@semantic-release/changelog": "^6.0.3", |
| 90 | 97 | "@semantic-release/git": "^10.0.1", |
| 91 | 98 | "@semantic-release/github": "^11.0.3", |
| @@ -93,7 +100,6 @@ | ||
| 93 | 100 | "@testing-library/react": "^16.3.0", |
| 94 | 101 | "@types/date-fns": "^2.5.3", |
| 95 | 102 | "@types/diff": "^7.0.2", |
| 96 | - "@types/express": "^5.0.3", | |
| 97 | 103 | "@types/glob": "^8.1.0", |
| 98 | 104 | "@types/ignore-walk": "^4.0.3", |
| 99 | 105 | "@types/ink-testing-library": "^1.0.4", |
| @@ -102,17 +108,18 @@ | ||
| 102 | 108 | "@types/readline-sync": "^1.4.8", |
| 103 | 109 | "@types/shell-quote": "^1.7.5", |
| 104 | 110 | "@types/supertest": "^6.0.3", |
| 111 | + "@types/uuid": "^10.0.0", | |
| 105 | 112 | "@typescript-eslint/eslint-plugin": "^8.39.0", |
| 106 | 113 | "@typescript-eslint/parser": "^8.39.0", |
| 107 | 114 | "@vitest/ui": "^3.2.4", |
| 108 | 115 | "conventional-changelog-conventionalcommits": "^9.1.0", |
| 109 | 116 | "cross-env": "^7.0.3", |
| 117 | + "esbuild": "^0.25.9", | |
| 110 | 118 | "eslint": "^9.32.0", |
| 111 | 119 | "eslint-import-resolver-typescript": "^4.4.4", |
| 112 | 120 | "eslint-plugin-import": "^2.32.0", |
| 113 | 121 | "eslint-plugin-unused-imports": "^4.1.4", |
| 114 | 122 | "execa": "^9.6.0", |
| 115 | - "express": "^5.1.0", | |
| 116 | 123 | "happy-dom": "^18.0.1", |
| 117 | 124 | "ink-testing-library": "^4.0.0", |
| 118 | 125 | "jsdom": "^26.1.0", |
added extensions/cli/smoke-test.mjs +230 −0
| @@ -0,0 +1,230 @@ | ||
| 1 | +#!/usr/bin/env node | |
| 2 | + | |
| 3 | +import { execSync } from "child_process"; | |
| 4 | +import { existsSync, readFileSync } from "fs"; | |
| 5 | +import { resolve, dirname } from "path"; | |
| 6 | +import { fileURLToPath } from "url"; | |
| 7 | + | |
| 8 | +const __dirname = dirname(fileURLToPath(import.meta.url)); | |
| 9 | + | |
| 10 | +// Colors for output | |
| 11 | +const colors = { | |
| 12 | + green: "\x1b[32m", | |
| 13 | + red: "\x1b[31m", | |
| 14 | + yellow: "\x1b[33m", | |
| 15 | + reset: "\x1b[0m", | |
| 16 | +}; | |
| 17 | + | |
| 18 | +let testsPassed = 0; | |
| 19 | +let testsFailed = 0; | |
| 20 | + | |
| 21 | +function runTest(name, testFn) { | |
| 22 | + process.stdout.write(`Testing ${name}... `); | |
| 23 | + try { | |
| 24 | + testFn(); | |
| 25 | + console.log(`${colors.green}✓${colors.reset}`); | |
| 26 | + testsPassed++; | |
| 27 | + } catch (error) { | |
| 28 | + console.log(`${colors.red}✗${colors.reset}`); | |
| 29 | + console.error(` Error: ${error.message}`); | |
| 30 | + testsFailed++; | |
| 31 | + } | |
| 32 | +} | |
| 33 | + | |
| 34 | +function execCommand(command, options = {}) { | |
| 35 | + return execSync(command, { | |
| 36 | + cwd: __dirname, | |
| 37 | + encoding: "utf8", | |
| 38 | + stdio: "pipe", | |
| 39 | + ...options, | |
| 40 | + }); | |
| 41 | +} | |
| 42 | + | |
| 43 | +console.log("🧪 Running smoke tests for bundled CLI...\n"); | |
| 44 | + | |
| 45 | +// Test 1: Check if bundle exists | |
| 46 | +runTest("Bundle file exists", () => { | |
| 47 | + if (!existsSync(resolve(__dirname, "dist/index.js"))) { | |
| 48 | + throw new Error("dist/index.js not found"); | |
| 49 | + } | |
| 50 | + if (!existsSync(resolve(__dirname, "dist/cn.js"))) { | |
| 51 | + throw new Error("dist/cn.js not found"); | |
| 52 | + } | |
| 53 | +}); | |
| 54 | + | |
| 55 | +// Test 2: Check if wrapper script is executable | |
| 56 | +runTest("Wrapper script has shebang", () => { | |
| 57 | + const content = readFileSync(resolve(__dirname, "dist/cn.js"), "utf8"); | |
| 58 | + if (!content.startsWith("#!/usr/bin/env node")) { | |
| 59 | + throw new Error("Wrapper script missing shebang"); | |
| 60 | + } | |
| 61 | +}); | |
| 62 | + | |
| 63 | +// Cross-platform command execution helper | |
| 64 | +function getCLICommand(args = "") { | |
| 65 | + const isWindows = process.platform === "win32"; | |
| 66 | + if (isWindows) { | |
| 67 | + return `node dist/cn.js ${args}`; | |
| 68 | + } else { | |
| 69 | + return `./dist/cn.js ${args}`; | |
| 70 | + } | |
| 71 | +} | |
| 72 | + | |
| 73 | +// Test 3: Version command works | |
| 74 | +runTest("Version command", () => { | |
| 75 | + const output = execCommand(getCLICommand("--version")); | |
| 76 | + const packageJson = JSON.parse( | |
| 77 | + readFileSync(resolve(__dirname, "package.json"), "utf8"), | |
| 78 | + ); | |
| 79 | + if (!output.includes(packageJson.version)) { | |
| 80 | + throw new Error( | |
| 81 | + `Version mismatch. Expected ${packageJson.version}, got: ${output}`, | |
| 82 | + ); | |
| 83 | + } | |
| 84 | +}); | |
| 85 | + | |
| 86 | +// Test 4: Help command works | |
| 87 | +runTest("Help command", () => { | |
| 88 | + const output = execCommand(getCLICommand("--help")); | |
| 89 | + if (!output.includes("Continue CLI") || !output.includes("--version")) { | |
| 90 | + throw new Error("Help output missing expected content"); | |
| 91 | + } | |
| 92 | +}); | |
| 93 | + | |
| 94 | +// Test 5: Check bundle size | |
| 95 | +runTest("Bundle size is reasonable", () => { | |
| 96 | + const isWindows = process.platform === "win32"; | |
| 97 | + const command = isWindows | |
| 98 | + ? `powershell -Command "(Get-Item dist/index.js).length / 1MB"` | |
| 99 | + : `ls -lh dist/index.js`; | |
| 100 | + | |
| 101 | + let sizeInMB; | |
| 102 | + | |
| 103 | + if (isWindows) { | |
| 104 | + try { | |
| 105 | + const output = execCommand(command); | |
| 106 | + sizeInMB = parseFloat(output.trim()); | |
| 107 | + } catch { | |
| 108 | + // Fallback for Windows if PowerShell fails | |
| 109 | + const stats = readFileSync(resolve(__dirname, "dist/index.js")); | |
| 110 | + sizeInMB = stats.length / (1024 * 1024); | |
| 111 | + } | |
| 112 | + } else { | |
| 113 | + const stats = execCommand(command); | |
| 114 | + const sizeMatch = stats.match(/(\d+(?:\.\d+)?[MK])/); | |
| 115 | + if (sizeMatch) { | |
| 116 | + const size = sizeMatch[1]; | |
| 117 | + const numSize = parseFloat(size); | |
| 118 | + const unit = size.slice(-1); | |
| 119 | + sizeInMB = unit === "M" ? numSize : numSize / 1024; | |
| 120 | + } | |
| 121 | + } | |
| 122 | + | |
| 123 | + console.log(`(${sizeInMB.toFixed(1)}M)`); | |
| 124 | + | |
| 125 | + // This is arbitrary. We might go over at some point, | |
| 126 | + // in which case you can just increase this. | |
| 127 | + if (sizeInMB > 20) { | |
| 128 | + throw new Error(`Bundle too large: ${sizeInMB.toFixed(1)}M`); | |
| 129 | + } | |
| 130 | +}); | |
| 131 | + | |
| 132 | +// Test 6: Check that local packages are bundled | |
| 133 | +runTest("Local packages are bundled", () => { | |
| 134 | + const bundleContent = readFileSync( | |
| 135 | + resolve(__dirname, "dist/index.js"), | |
| 136 | + "utf8", | |
| 137 | + ); | |
| 138 | + | |
| 139 | + // Check for code from @continuedev/config-yaml | |
| 140 | + if ( | |
| 141 | + !bundleContent.includes("AssistantUnrolled") && | |
| 142 | + !bundleContent.includes("config-yaml") | |
| 143 | + ) { | |
| 144 | + throw new Error("@continuedev/config-yaml not properly bundled"); | |
| 145 | + } | |
| 146 | + | |
| 147 | + // Check for code from @continuedev/openai-adapters | |
| 148 | + // Since the bundle is minified, check for strings that would be present | |
| 149 | + // even after minification (e.g., error messages, property names) | |
| 150 | + if ( | |
| 151 | + !bundleContent.includes("anthropic") && | |
| 152 | + !bundleContent.includes("gemini") && | |
| 153 | + !bundleContent.includes("openai") && | |
| 154 | + !bundleContent.includes("azure") && | |
| 155 | + !bundleContent.includes("bedrock") | |
| 156 | + ) { | |
| 157 | + throw new Error("@continuedev/openai-adapters not properly bundled"); | |
| 158 | + } | |
| 159 | +}); | |
| 160 | + | |
| 161 | +// Test 7: Test that the CLI can be invoked programmatically | |
| 162 | +runTest("CLI can be invoked", () => { | |
| 163 | + try { | |
| 164 | + // Test that the CLI runs without crashing when given no args | |
| 165 | + const isWindows = process.platform === "win32"; | |
| 166 | + const nullDevice = isWindows ? "nul" : "/dev/null"; | |
| 167 | + execCommand(`${getCLICommand("--help")} > ${nullDevice} 2>&1`); | |
| 168 | + } catch (error) { | |
| 169 | + throw new Error(`CLI invocation failed: ${error.message}`); | |
| 170 | + } | |
| 171 | +}); | |
| 172 | + | |
| 173 | +// Test 8: Check metadata file | |
| 174 | +runTest("Build metadata exists", () => { | |
| 175 | + if (!existsSync(resolve(__dirname, "dist/meta.json"))) { | |
| 176 | + throw new Error("dist/meta.json not found"); | |
| 177 | + } | |
| 178 | + | |
| 179 | + const meta = JSON.parse( | |
| 180 | + readFileSync(resolve(__dirname, "dist/meta.json"), "utf8"), | |
| 181 | + ); | |
| 182 | + if (!meta.inputs || !meta.outputs) { | |
| 183 | + throw new Error("Invalid metadata structure"); | |
| 184 | + } | |
| 185 | +}); | |
| 186 | + | |
| 187 | +// Test 9: Verify no missing external dependencies | |
| 188 | +runTest("No missing runtime dependencies", () => { | |
| 189 | + // This would fail in Test 3 if dependencies were missing, but let's be explicit | |
| 190 | + const output = execCommand(`${getCLICommand("--version")} 2>&1`, { | |
| 191 | + env: { ...process.env, NODE_ENV: "production" }, | |
| 192 | + }); | |
| 193 | + | |
| 194 | + if ( | |
| 195 | + output.includes("Cannot find module") || | |
| 196 | + output.includes("MODULE_NOT_FOUND") | |
| 197 | + ) { | |
| 198 | + throw new Error("Missing module detected in output"); | |
| 199 | + } | |
| 200 | +}); | |
| 201 | + | |
| 202 | +// Test 10: Test npm link scenario | |
| 203 | +runTest("CLI works via npm link", () => { | |
| 204 | + try { | |
| 205 | + // Simply test that we can execute with node directly | |
| 206 | + const output = execCommand("node dist/cn.js --version 2>&1"); | |
| 207 | + const packageJson = JSON.parse( | |
| 208 | + readFileSync(resolve(__dirname, "package.json"), "utf8"), | |
| 209 | + ); | |
| 210 | + if (!output.includes(packageJson.version)) { | |
| 211 | + throw new Error("Version not found when running via node"); | |
| 212 | + } | |
| 213 | + } catch (error) { | |
| 214 | + throw new Error(`npm link scenario failed: ${error.message}`); | |
| 215 | + } | |
| 216 | +}); | |
| 217 | + | |
| 218 | +// Summary | |
| 219 | +console.log("\n" + "=".repeat(50)); | |
| 220 | +if (testsFailed === 0) { | |
| 221 | + console.log( | |
| 222 | + `${colors.green}✅ All ${testsPassed} tests passed!${colors.reset}`, | |
| 223 | + ); | |
| 224 | + process.exit(0); | |
| 225 | +} else { | |
| 226 | + console.log( | |
| 227 | + `${colors.red}❌ ${testsFailed} test(s) failed, ${testsPassed} passed${colors.reset}`, | |
| 228 | + ); | |
| 229 | + process.exit(1); | |
| 230 | +} |
modified extensions/cli/src/asciiArt.test.ts +6 −5
| @@ -27,26 +27,27 @@ | ||
| 27 | 27 | expect(result).toBe(CONTINUE_ASCII_ART); |
| 28 | 28 | }); |
| 29 | 29 | |
| 30 | - it("should return simple text version when terminal is too narrow", () => { | |
| 30 | + it("should return CN ASCII art version when terminal is too narrow", () => { | |
| 31 | 31 | // Set process.stdout.columns to simulate narrow terminal |
| 32 | 32 | process.stdout.columns = 60; |
| 33 | 33 | |
| 34 | 34 | const result = getDisplayableAsciiArt(); |
| 35 | 35 | |
| 36 | - expect(result).toContain("CONTINUE"); | |
| 37 | - // expect(result).toContain("v0.0.0-dev"); | |
| 36 | + expect(result).toContain("██████╗"); | |
| 37 | + expect(result).toContain("(alpha)"); | |
| 38 | 38 | expect(result).not.toBe(CONTINUE_ASCII_ART); |
| 39 | 39 | // Should be much shorter than the full ASCII art |
| 40 | 40 | expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2); |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | - it("should return simple text version when terminal is below threshold", () => { | |
| 43 | + it("should return CN ASCII art version when terminal is below threshold", () => { | |
| 44 | 44 | // Test the edge case at exactly 74 columns (below our threshold of 75) |
| 45 | 45 | process.stdout.columns = 74; |
| 46 | 46 | |
| 47 | 47 | const result = getDisplayableAsciiArt(); |
| 48 | 48 | |
| 49 | - expect(result).toContain("CONTINUE"); | |
| 49 | + expect(result).toContain("██████╗"); | |
| 50 | + expect(result).toContain("(alpha)"); | |
| 50 | 51 | expect(result).not.toBe(CONTINUE_ASCII_ART); |
| 51 | 52 | }); |
| 52 | 53 |
modified extensions/cli/src/asciiArt.ts +13 −3
| @@ -12,7 +12,17 @@ | ||
| 12 | 12 | ██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝ |
| 13 | 13 | ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗ |
| 14 | 14 | ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)} |
| 15 | - ${d("v" + getVersion())}`; | |
| 15 | + ${d("v" + getVersion() + " (alpha)")}`; | |
| 16 | + | |
| 17 | +// ASCII art for just "CN" (first two letters) | |
| 18 | +const CN_ASCII_ART = ` | |
| 19 | +${mind.multiline(` ██████╗███╗ ██╗ | |
| 20 | + ██╔════╝████╗ ██║ | |
| 21 | + ██║ ██╔██╗ ██║ | |
| 22 | + ██║ ██║╚██╗██║ | |
| 23 | + ╚██████╗██║ ╚████║ | |
| 24 | + ╚═════╝╚═╝ ╚═══╝`)} | |
| 25 | + ${d("v" + getVersion() + " (alpha)")}`; | |
| 16 | 26 | |
| 17 | 27 | // Minimum terminal width required to display ASCII art properly |
| 18 | 28 | const MIN_WIDTH_FOR_ASCII_ART = 75; |
| @@ -28,8 +38,8 @@ | ||
| 28 | 38 | return CONTINUE_ASCII_ART; |
| 29 | 39 | } |
| 30 | 40 | |
| 31 | - // If terminal is too narrow, just show a simple version | |
| 32 | - return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`; | |
| 41 | + // If terminal is too narrow, show just "CN" ASCII art | |
| 42 | + return CN_ASCII_ART; | |
| 33 | 43 | } |
| 34 | 44 | |
| 35 | 45 | export const CONTINUE_LOGO_ASCII_ART = ` |
modified extensions/cli/src/commands/chat.ts +67 −60
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | getHistoryForLLM, |
| 11 | 11 | } from "../compaction.js"; |
| 12 | 12 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 13 | +import { safeStdout } from "../init.js"; | |
| 13 | 14 | import { configureLogger } from "../logger.js"; |
| 14 | 15 | import * as logging from "../logging.js"; |
| 15 | 16 | import { sentryService } from "../sentry.js"; |
| @@ -22,7 +23,6 @@ | ||
| 22 | 23 | import { posthogService } from "../telemetry/posthogService.js"; |
| 23 | 24 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 24 | 25 | import { startTUIChat } from "../ui/index.js"; |
| 25 | -import { safeStdout } from "../util/consoleOverride.js"; | |
| 26 | 26 | import { formatAnthropicError, formatError } from "../util/formatError.js"; |
| 27 | 27 | import { logger } from "../util/logger.js"; |
| 28 | 28 | import { |
| @@ -159,7 +159,7 @@ | ||
| 159 | 159 | } |
| 160 | 160 | } |
| 161 | 161 | |
| 162 | -// Helper function to handle auto-compaction | |
| 162 | +// Helper function to handle auto-compaction for headless mode | |
| 163 | 163 | async function handleAutoCompaction( |
| 164 | 164 | chatHistory: ChatCompletionMessageParam[], |
| 165 | 165 | model: ModelConfig, |
| @@ -167,64 +167,71 @@ | ||
| 167 | 167 | isHeadless: boolean, |
| 168 | 168 | format?: "json", |
| 169 | 169 | ): Promise<number | null> { |
| 170 | - logger.info("Auto-compacting triggered due to context limit"); | |
| 171 | - | |
| 172 | - if (!isHeadless) { | |
| 173 | - console.info( | |
| 174 | - chalk.yellow( | |
| 175 | - "\nApproaching context limit. Auto-compacting chat history...", | |
| 176 | - ), | |
| 177 | - ); | |
| 178 | - } else if (format === "json") { | |
| 179 | - safeStdout( | |
| 180 | - JSON.stringify({ | |
| 181 | - status: "info", | |
| 182 | - message: "Auto-compacting triggered", | |
| 183 | - contextUsage: | |
| 184 | - calculateContextUsagePercentage( | |
| 185 | - countChatHistoryTokens(chatHistory), | |
| 186 | - model, | |
| 187 | - ) + "%", | |
| 188 | - }) + "\n", | |
| 189 | - ); | |
| 190 | - } | |
| 191 | - | |
| 192 | - try { | |
| 193 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 194 | - chatHistory.length = 0; | |
| 195 | - chatHistory.push(...result.compactedHistory); | |
| 196 | - saveSession(chatHistory); | |
| 197 | - | |
| 198 | - if (!isHeadless) { | |
| 199 | - console.info(chalk.green("✓ Chat history auto-compacted successfully.")); | |
| 200 | - } else if (format === "json") { | |
| 201 | - safeStdout( | |
| 202 | - JSON.stringify({ | |
| 203 | - status: "success", | |
| 204 | - message: "Auto-compacted successfully", | |
| 205 | - historyLength: chatHistory.length, | |
| 206 | - }) + "\n", | |
| 207 | - ); | |
| 208 | - } | |
| 209 | - | |
| 210 | - return result.compactionIndex; | |
| 211 | - } catch (error) { | |
| 212 | - const errorMsg = `Auto-compaction error: ${formatError(error)}`; | |
| 213 | - logger.error(errorMsg); | |
| 214 | - | |
| 215 | - if (!isHeadless) { | |
| 216 | - console.error(chalk.red(`Warning: ${errorMsg}`)); | |
| 217 | - console.info(chalk.yellow("Continuing without compaction...")); | |
| 218 | - } else if (format === "json") { | |
| 219 | - safeStdout( | |
| 220 | - JSON.stringify({ | |
| 221 | - status: "warning", | |
| 222 | - message: "Auto-compaction failed, continuing without compaction", | |
| 223 | - }) + "\n", | |
| 224 | - ); | |
| 225 | - } | |
| 226 | - return null; | |
| 227 | - } | |
| 170 | + const { handleAutoCompaction: coreAutoCompaction } = await import( | |
| 171 | + "../streamChatResponse.autoCompaction.js" | |
| 172 | + ); | |
| 173 | + | |
| 174 | + // Custom callbacks for headless mode console output | |
| 175 | + const callbacks = { | |
| 176 | + onSystemMessage: (message: string) => { | |
| 177 | + if ( | |
| 178 | + message.includes("Auto-compacting") || | |
| 179 | + message.includes("Approaching") | |
| 180 | + ) { | |
| 181 | + if (!isHeadless) { | |
| 182 | + console.info(chalk.yellow(`\n${message}`)); | |
| 183 | + } else if (format === "json") { | |
| 184 | + safeStdout( | |
| 185 | + JSON.stringify({ | |
| 186 | + status: "info", | |
| 187 | + message: "Auto-compacting triggered", | |
| 188 | + contextUsage: | |
| 189 | + calculateContextUsagePercentage( | |
| 190 | + countChatHistoryTokens(chatHistory), | |
| 191 | + model, | |
| 192 | + ) + "%", | |
| 193 | + }) + "\n", | |
| 194 | + ); | |
| 195 | + } | |
| 196 | + } else if (message.includes("✓")) { | |
| 197 | + if (!isHeadless) { | |
| 198 | + console.info(chalk.green(message)); | |
| 199 | + } else if (format === "json") { | |
| 200 | + safeStdout( | |
| 201 | + JSON.stringify({ | |
| 202 | + status: "success", | |
| 203 | + message: "Auto-compacted successfully", | |
| 204 | + historyLength: chatHistory.length, | |
| 205 | + }) + "\n", | |
| 206 | + ); | |
| 207 | + } | |
| 208 | + } else if (message.includes("Warning:")) { | |
| 209 | + if (!isHeadless) { | |
| 210 | + console.error(chalk.red(message)); | |
| 211 | + console.info(chalk.yellow("Continuing without compaction...")); | |
| 212 | + } else if (format === "json") { | |
| 213 | + safeStdout( | |
| 214 | + JSON.stringify({ | |
| 215 | + status: "warning", | |
| 216 | + message: "Auto-compaction failed, continuing without compaction", | |
| 217 | + }) + "\n", | |
| 218 | + ); | |
| 219 | + } | |
| 220 | + } | |
| 221 | + }, | |
| 222 | + }; | |
| 223 | + | |
| 224 | + const result = await coreAutoCompaction(chatHistory, model, llmApi, { | |
| 225 | + isHeadless, | |
| 226 | + format, | |
| 227 | + callbacks, | |
| 228 | + }); | |
| 229 | + | |
| 230 | + // Update the original array reference for headless mode | |
| 231 | + chatHistory.length = 0; | |
| 232 | + chatHistory.push(...result.chatHistory); | |
| 233 | + | |
| 234 | + return result.compactionIndex; | |
| 228 | 235 | } |
| 229 | 236 | |
| 230 | 237 | interface ProcessMessageOptions { |
modified extensions/cli/src/commands/commands.ts +6 −1
| @@ -4,9 +4,9 @@ | ||
| 4 | 4 | export { chat } from "./chat.js"; |
| 5 | 5 | export { login } from "./login.js"; |
| 6 | 6 | export { logout } from "./logout.js"; |
| 7 | +export { listSessionsCommand } from "./ls.js"; | |
| 7 | 8 | export { remote } from "./remote.js"; |
| 8 | 9 | export { serve } from "./serve.js"; |
| 9 | -export { listSessionsCommand } from "./ls.js"; | |
| 10 | 10 | |
| 11 | 11 | export interface SlashCommand { |
| 12 | 12 | name: string; |
| @@ -45,6 +45,11 @@ | ||
| 45 | 45 | description: "Check who you're currently logged in as", |
| 46 | 46 | category: "system", |
| 47 | 47 | }, |
| 48 | + { | |
| 49 | + name: "info", | |
| 50 | + description: "Show session information", | |
| 51 | + category: "system", | |
| 52 | + }, | |
| 48 | 53 | { |
| 49 | 54 | name: "model", |
| 50 | 55 | description: "Switch between available chat models", |
added extensions/cli/src/compaction.infiniteLoop.test.ts +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | +import { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 4 | +import { describe, it, expect, vi } from "vitest"; | |
| 5 | + | |
| 6 | +import { compactChatHistory } from "./compaction.js"; | |
| 7 | +import { streamChatResponse } from "./streamChatResponse.js"; | |
| 8 | + | |
| 9 | +// Mock the dependencies | |
| 10 | +vi.mock("./streamChatResponse.js", () => ({ | |
| 11 | + streamChatResponse: vi.fn(), | |
| 12 | +})); | |
| 13 | + | |
| 14 | +vi.mock("./util/tokenizer.js", () => ({ | |
| 15 | + countChatHistoryTokens: vi.fn(), | |
| 16 | + getModelContextLimit: vi.fn(), | |
| 17 | +})); | |
| 18 | + | |
| 19 | +describe("compaction infinite loop prevention", () => { | |
| 20 | + const mockModel: ModelConfig = { | |
| 21 | + name: "test-model", | |
| 22 | + provider: "test", | |
| 23 | + model: "test-model", | |
| 24 | + defaultCompletionOptions: { | |
| 25 | + maxTokens: 1000, | |
| 26 | + contextLength: 4000, | |
| 27 | + }, | |
| 28 | + } as ModelConfig; | |
| 29 | + | |
| 30 | + const mockLlmApi = {} as BaseLlmApi; | |
| 31 | + | |
| 32 | + it("should not loop infinitely when pruning doesn't reduce history size", async () => { | |
| 33 | + const { countChatHistoryTokens, getModelContextLimit } = await import( | |
| 34 | + "./util/tokenizer.js" | |
| 35 | + ); | |
| 36 | + const mockStreamResponse = vi.mocked(streamChatResponse); | |
| 37 | + const mockCountTokens = vi.mocked(countChatHistoryTokens); | |
| 38 | + const mockGetContextLimit = vi.mocked(getModelContextLimit); | |
| 39 | + | |
| 40 | + // Setup mocks | |
| 41 | + mockGetContextLimit.mockReturnValue(4000); | |
| 42 | + mockCountTokens.mockReturnValue(5000); // Always too big | |
| 43 | + mockStreamResponse.mockImplementation( | |
| 44 | + async (history, model, api, controller, callbacks) => { | |
| 45 | + callbacks?.onContent?.("Summary"); | |
| 46 | + callbacks?.onContentComplete?.("Summary"); | |
| 47 | + return "Summary"; | |
| 48 | + }, | |
| 49 | + ); | |
| 50 | + | |
| 51 | + // History that can't be pruned further (only system message) | |
| 52 | + const history: ChatCompletionMessageParam[] = [ | |
| 53 | + { role: "system", content: "System message" }, | |
| 54 | + ]; | |
| 55 | + | |
| 56 | + // This should not hang - it should break out of the loop | |
| 57 | + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); | |
| 58 | + | |
| 59 | + // Should complete successfully even though token count is still too high | |
| 60 | + expect(result.compactedHistory).toBeDefined(); | |
| 61 | + expect(mockCountTokens).toHaveBeenCalled(); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("should not loop infinitely with history ending in assistant message", async () => { | |
| 65 | + const { countChatHistoryTokens, getModelContextLimit } = await import( | |
| 66 | + "./util/tokenizer.js" | |
| 67 | + ); | |
| 68 | + const mockStreamResponse = vi.mocked(streamChatResponse); | |
| 69 | + const mockCountTokens = vi.mocked(countChatHistoryTokens); | |
| 70 | + const mockGetContextLimit = vi.mocked(getModelContextLimit); | |
| 71 | + | |
| 72 | + // Setup mocks | |
| 73 | + mockGetContextLimit.mockReturnValue(4000); | |
| 74 | + mockCountTokens.mockReturnValue(5000); // Always too big | |
| 75 | + mockStreamResponse.mockImplementation( | |
| 76 | + async (history, model, api, controller, callbacks) => { | |
| 77 | + callbacks?.onContent?.("Summary"); | |
| 78 | + callbacks?.onContentComplete?.("Summary"); | |
| 79 | + return "Summary"; | |
| 80 | + }, | |
| 81 | + ); | |
| 82 | + | |
| 83 | + // History that ends with assistant - pruning won't change it | |
| 84 | + const history: ChatCompletionMessageParam[] = [ | |
| 85 | + { role: "system", content: "System message" }, | |
| 86 | + { role: "user", content: "Hello" }, | |
| 87 | + { role: "assistant", content: "Hi there" }, | |
| 88 | + ]; | |
| 89 | + | |
| 90 | + // This should not hang | |
| 91 | + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); | |
| 92 | + | |
| 93 | + expect(result.compactedHistory).toBeDefined(); | |
| 94 | + }); | |
| 95 | + | |
| 96 | + it("should successfully prune when pruning actually reduces size", async () => { | |
| 97 | + const { countChatHistoryTokens, getModelContextLimit } = await import( | |
| 98 | + "./util/tokenizer.js" | |
| 99 | + ); | |
| 100 | + const mockStreamResponse = vi.mocked(streamChatResponse); | |
| 101 | + const mockCountTokens = vi.mocked(countChatHistoryTokens); | |
| 102 | + const mockGetContextLimit = vi.mocked(getModelContextLimit); | |
| 103 | + | |
| 104 | + // Setup mocks | |
| 105 | + mockGetContextLimit.mockReturnValue(4000); | |
| 106 | + | |
| 107 | + // Mock token counting to show reduction after pruning | |
| 108 | + let callCount = 0; | |
| 109 | + mockCountTokens.mockImplementation(() => { | |
| 110 | + callCount++; | |
| 111 | + if (callCount === 1) return 5000; // Initial too big | |
| 112 | + if (callCount === 2) return 3000; // After pruning, fits | |
| 113 | + return 2000; // Subsequent calls | |
| 114 | + }); | |
| 115 | + | |
| 116 | + mockStreamResponse.mockImplementation( | |
| 117 | + async (history, model, api, controller, callbacks) => { | |
| 118 | + callbacks?.onContent?.("Summary"); | |
| 119 | + callbacks?.onContentComplete?.("Summary"); | |
| 120 | + return "Summary"; | |
| 121 | + }, | |
| 122 | + ); | |
| 123 | + | |
| 124 | + // History that can be successfully pruned | |
| 125 | + const history: ChatCompletionMessageParam[] = [ | |
| 126 | + { role: "system", content: "System message" }, | |
| 127 | + { role: "user", content: "Hello" }, | |
| 128 | + { role: "assistant", content: "Hi there" }, | |
| 129 | + { role: "user", content: "Another question" }, | |
| 130 | + ]; | |
| 131 | + | |
| 132 | + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); | |
| 133 | + | |
| 134 | + expect(result.compactedHistory).toBeDefined(); | |
| 135 | + // The function will call countTokens multiple times during the process | |
| 136 | + expect(mockCountTokens).toHaveBeenCalled(); | |
| 137 | + }); | |
| 138 | +}); |
added extensions/cli/src/compaction.pruneLastMessage.test.ts +185 −0
| @@ -0,0 +1,185 @@ | ||
| 1 | +import { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 2 | +import { describe, it, expect } from "vitest"; | |
| 3 | + | |
| 4 | +import { pruneLastMessage } from "./compaction.js"; | |
| 5 | + | |
| 6 | +describe("pruneLastMessage", () => { | |
| 7 | + it("should return empty array for empty input", () => { | |
| 8 | + const result = pruneLastMessage([]); | |
| 9 | + expect(result).toEqual([]); | |
| 10 | + }); | |
| 11 | + | |
| 12 | + it("should remove single user message", () => { | |
| 13 | + const history: ChatCompletionMessageParam[] = [ | |
| 14 | + { role: "user", content: "Hello" }, | |
| 15 | + ]; | |
| 16 | + | |
| 17 | + const result = pruneLastMessage(history); | |
| 18 | + expect(result).toEqual([]); | |
| 19 | + }); | |
| 20 | + | |
| 21 | + it("should return empty array for single system message", () => { | |
| 22 | + const history: ChatCompletionMessageParam[] = [ | |
| 23 | + { role: "system", content: "System" }, | |
| 24 | + ]; | |
| 25 | + | |
| 26 | + const result = pruneLastMessage(history); | |
| 27 | + expect(result).toEqual([]); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should return empty array for single assistant message", () => { | |
| 31 | + const history: ChatCompletionMessageParam[] = [ | |
| 32 | + { role: "assistant", content: "Hello" }, | |
| 33 | + ]; | |
| 34 | + | |
| 35 | + const result = pruneLastMessage(history); | |
| 36 | + expect(result).toEqual([]); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + it("should return empty array for single tool message", () => { | |
| 40 | + const history: ChatCompletionMessageParam[] = [ | |
| 41 | + { role: "tool", content: "Tool output", tool_call_id: "1" }, | |
| 42 | + ]; | |
| 43 | + | |
| 44 | + const result = pruneLastMessage(history); | |
| 45 | + expect(result).toEqual([]); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("should remove last message when second-to-last is user", () => { | |
| 49 | + const history: ChatCompletionMessageParam[] = [ | |
| 50 | + { role: "system", content: "System" }, | |
| 51 | + { role: "user", content: "Hello" }, | |
| 52 | + { role: "assistant", content: "Hi there" }, | |
| 53 | + ]; | |
| 54 | + | |
| 55 | + const result = pruneLastMessage(history); | |
| 56 | + expect(result).toEqual([{ role: "system", content: "System" }]); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + it("should remove assistant+tool sequence when second-to-last is assistant with tool calls", () => { | |
| 60 | + const history: ChatCompletionMessageParam[] = [ | |
| 61 | + { role: "system", content: "System" }, | |
| 62 | + { role: "user", content: "Run command" }, | |
| 63 | + { | |
| 64 | + role: "assistant", | |
| 65 | + content: "Running...", | |
| 66 | + tool_calls: [{ id: "1" } as any], | |
| 67 | + }, | |
| 68 | + { role: "tool", content: "Command output", tool_call_id: "1" }, | |
| 69 | + ]; | |
| 70 | + | |
| 71 | + const result = pruneLastMessage(history); | |
| 72 | + expect(result).toEqual([ | |
| 73 | + { role: "system", content: "System" }, | |
| 74 | + { role: "user", content: "Run command" }, | |
| 75 | + ]); | |
| 76 | + }); | |
| 77 | + | |
| 78 | + it("should prune last message when second-to-last is not user or assistant with tool calls", () => { | |
| 79 | + const history: ChatCompletionMessageParam[] = [ | |
| 80 | + { role: "system", content: "System" }, | |
| 81 | + { role: "assistant", content: "Hi there" }, | |
| 82 | + { role: "user", content: "Another question" }, | |
| 83 | + ]; | |
| 84 | + | |
| 85 | + const result = pruneLastMessage(history); | |
| 86 | + expect(result).toEqual([ | |
| 87 | + { role: "system", content: "System" }, | |
| 88 | + { role: "assistant", content: "Hi there" }, | |
| 89 | + ]); | |
| 90 | + }); | |
| 91 | + | |
| 92 | + it("should handle multiple user messages by removing two at a time", () => { | |
| 93 | + const history: ChatCompletionMessageParam[] = [ | |
| 94 | + { role: "system", content: "System" }, | |
| 95 | + { role: "user", content: "Question 1" }, | |
| 96 | + { role: "user", content: "Question 2" }, | |
| 97 | + ]; | |
| 98 | + | |
| 99 | + const result = pruneLastMessage(history); | |
| 100 | + expect(result).toEqual([{ role: "system", content: "System" }]); | |
| 101 | + }); | |
| 102 | + | |
| 103 | + it("should handle tool call sequences by removing user after tool", () => { | |
| 104 | + const history: ChatCompletionMessageParam[] = [ | |
| 105 | + { role: "system", content: "System" }, | |
| 106 | + { role: "user", content: "Do something" }, | |
| 107 | + { | |
| 108 | + role: "assistant", | |
| 109 | + content: "I'll help", | |
| 110 | + tool_calls: [{ id: "1" } as any], | |
| 111 | + }, | |
| 112 | + { role: "tool", content: "Tool result", tool_call_id: "1" }, | |
| 113 | + { role: "user", content: "Follow up question" }, | |
| 114 | + ]; | |
| 115 | + | |
| 116 | + const result = pruneLastMessage(history); | |
| 117 | + expect(result).toEqual([ | |
| 118 | + { role: "system", content: "System" }, | |
| 119 | + { role: "user", content: "Do something" }, | |
| 120 | + { | |
| 121 | + role: "assistant", | |
| 122 | + content: "I'll help", | |
| 123 | + tool_calls: [{ id: "1" } as any], | |
| 124 | + }, | |
| 125 | + { role: "tool", content: "Tool result", tool_call_id: "1" }, | |
| 126 | + ]); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + it("should remove both user messages when consecutive", () => { | |
| 130 | + const history: ChatCompletionMessageParam[] = [ | |
| 131 | + { role: "user", content: "Hello" }, | |
| 132 | + { role: "user", content: "Another message" }, | |
| 133 | + ]; | |
| 134 | + | |
| 135 | + const result = pruneLastMessage(history); | |
| 136 | + expect(result).toEqual([]); | |
| 137 | + }); | |
| 138 | + | |
| 139 | + it("should handle complex conversation flow", () => { | |
| 140 | + const history: ChatCompletionMessageParam[] = [ | |
| 141 | + { role: "system", content: "System" }, | |
| 142 | + { role: "user", content: "Request 1" }, | |
| 143 | + { role: "assistant", content: "Response 1" }, | |
| 144 | + { role: "user", content: "Request 2" }, | |
| 145 | + { | |
| 146 | + role: "assistant", | |
| 147 | + content: "Using tool", | |
| 148 | + tool_calls: [{ id: "1" } as any], | |
| 149 | + }, | |
| 150 | + { role: "tool", content: "Tool result", tool_call_id: "1" }, | |
| 151 | + { role: "assistant", content: "Final response" }, | |
| 152 | + { role: "user", content: "Follow up 1" }, | |
| 153 | + { role: "user", content: "Follow up 2" }, | |
| 154 | + ]; | |
| 155 | + | |
| 156 | + const result = pruneLastMessage(history); | |
| 157 | + expect(result).toEqual([ | |
| 158 | + { role: "system", content: "System" }, | |
| 159 | + { role: "user", content: "Request 1" }, | |
| 160 | + { role: "assistant", content: "Response 1" }, | |
| 161 | + { role: "user", content: "Request 2" }, | |
| 162 | + { | |
| 163 | + role: "assistant", | |
| 164 | + content: "Using tool", | |
| 165 | + tool_calls: [{ id: "1" } as any], | |
| 166 | + }, | |
| 167 | + { role: "tool", content: "Tool result", tool_call_id: "1" }, | |
| 168 | + { role: "assistant", content: "Final response" }, | |
| 169 | + ]); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + it("should handle history starting with non-system message", () => { | |
| 173 | + const history: ChatCompletionMessageParam[] = [ | |
| 174 | + { role: "user", content: "Hello" }, | |
| 175 | + { role: "assistant", content: "Hi" }, | |
| 176 | + { role: "user", content: "Follow up" }, | |
| 177 | + ]; | |
| 178 | + | |
| 179 | + const result = pruneLastMessage(history); | |
| 180 | + expect(result).toEqual([ | |
| 181 | + { role: "user", content: "Hello" }, | |
| 182 | + { role: "assistant", content: "Hi" }, | |
| 183 | + ]); | |
| 184 | + }); | |
| 185 | +}); |
modified extensions/cli/src/compaction.ts +70 −2
| @@ -5,6 +5,10 @@ | ||
| 5 | 5 | import { streamChatResponse } from "./streamChatResponse.js"; |
| 6 | 6 | import { StreamCallbacks } from "./streamChatResponse.types.js"; |
| 7 | 7 | import { logger } from "./util/logger.js"; |
| 8 | +import { | |
| 9 | + countChatHistoryTokens, | |
| 10 | + getModelContextLimit, | |
| 11 | +} from "./util/tokenizer.js"; | |
| 8 | 12 | |
| 9 | 13 | export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; |
| 10 | 14 | |
| @@ -41,8 +45,39 @@ | ||
| 41 | 45 | "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.", |
| 42 | 46 | }; |
| 43 | 47 | |
| 44 | - // Get the current history for compaction | |
| 45 | - const historyForCompaction = [...chatHistory, compactionPrompt]; | |
| 48 | + // Check if the history with compaction prompt is too long, prune if necessary | |
| 49 | + let historyToUse = chatHistory; | |
| 50 | + let historyForCompaction = [...historyToUse, compactionPrompt]; | |
| 51 | + | |
| 52 | + const contextLimit = getModelContextLimit(model); | |
| 53 | + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; | |
| 54 | + const reservedForOutput = | |
| 55 | + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); | |
| 56 | + const availableForInput = contextLimit - reservedForOutput; | |
| 57 | + | |
| 58 | + // Check if we need to prune to fit within context | |
| 59 | + while ( | |
| 60 | + countChatHistoryTokens(historyForCompaction) > availableForInput && | |
| 61 | + historyToUse.length > 0 | |
| 62 | + ) { | |
| 63 | + logger.debug("Compaction history too long, pruning last message", { | |
| 64 | + tokenCount: countChatHistoryTokens(historyForCompaction), | |
| 65 | + availableForInput, | |
| 66 | + historyLength: historyToUse.length, | |
| 67 | + }); | |
| 68 | + const prunedHistory = pruneLastMessage(historyToUse); | |
| 69 | + | |
| 70 | + // Break if pruning didn't change the history (prevents infinite loop) | |
| 71 | + if (prunedHistory.length === historyToUse.length) { | |
| 72 | + logger.warn( | |
| 73 | + "Cannot prune history further while maintaining valid conversation structure", | |
| 74 | + ); | |
| 75 | + break; | |
| 76 | + } | |
| 77 | + | |
| 78 | + historyToUse = prunedHistory; | |
| 79 | + historyForCompaction = [...historyToUse, compactionPrompt]; | |
| 80 | + } | |
| 46 | 81 | |
| 47 | 82 | // Stream the compaction response |
| 48 | 83 | const controller = new AbortController(); |
| @@ -121,6 +156,39 @@ | ||
| 121 | 156 | * @param compactionIndex The index of the compaction message, if any |
| 122 | 157 | * @returns The history to send to the LLM |
| 123 | 158 | */ |
| 159 | +/** | |
| 160 | + * Prunes chat history by removing messages from the end while ensuring | |
| 161 | + * the history ends with either an assistant message or a tool result message | |
| 162 | + * @param chatHistory The chat history to prune | |
| 163 | + * @returns The pruned chat history ending with assistant or tool message | |
| 164 | + */ | |
| 165 | +export function pruneLastMessage( | |
| 166 | + chatHistory: ChatCompletionMessageParam[], | |
| 167 | +): ChatCompletionMessageParam[] { | |
| 168 | + if (chatHistory.length === 0) { | |
| 169 | + return chatHistory; | |
| 170 | + } | |
| 171 | + | |
| 172 | + if (chatHistory.length === 1) { | |
| 173 | + // Only one message - always return empty array | |
| 174 | + return []; | |
| 175 | + } | |
| 176 | + | |
| 177 | + const secondToLastIndex = chatHistory.length - 2; | |
| 178 | + const secondToLastMessage = chatHistory[secondToLastIndex]; | |
| 179 | + | |
| 180 | + if ( | |
| 181 | + secondToLastMessage.role === "assistant" && | |
| 182 | + secondToLastMessage.tool_calls?.length | |
| 183 | + ) { | |
| 184 | + return chatHistory.slice(0, -2); | |
| 185 | + } else if (secondToLastMessage.role === "user") { | |
| 186 | + return chatHistory.slice(0, -2); | |
| 187 | + } | |
| 188 | + | |
| 189 | + return chatHistory.slice(0, -1); | |
| 190 | +} | |
| 191 | + | |
| 124 | 192 | export function getHistoryForLLM( |
| 125 | 193 | fullHistory: ChatCompletionMessageParam[], |
| 126 | 194 | compactionIndex: number | null, |
modified extensions/cli/src/configLoader.ts +2 −2
| @@ -291,7 +291,7 @@ | ||
| 291 | 291 | apiBase: env.apiBase, |
| 292 | 292 | rootPath: |
| 293 | 293 | packageIdentifier.uriType === "file" |
| 294 | - ? dirname(packageIdentifier.filePath) | |
| 294 | + ? dirname(packageIdentifier.fileUri) | |
| 295 | 295 | : undefined, |
| 296 | 296 | }), |
| 297 | 297 | { |
| @@ -328,7 +328,7 @@ | ||
| 328 | 328 | apiClient: DefaultApiInterface, |
| 329 | 329 | ): Promise<AssistantUnrolled> { |
| 330 | 330 | return await unrollAssistantWithConfig( |
| 331 | - { filePath, uriType: "file" }, | |
| 331 | + { fileUri: filePath, uriType: "file" }, | |
| 332 | 332 | accessToken, |
| 333 | 333 | organizationId, |
| 334 | 334 | apiClient, |
modified extensions/cli/src/freeTrialTransition.test.ts +8 −8
| @@ -1,19 +1,19 @@ | ||
| 1 | 1 | import { |
| 2 | - isValidAnthropicApiKey, | |
| 3 | 2 | getApiKeyValidationError, |
| 3 | + isValidAnthropicApiKey, | |
| 4 | 4 | } from "./util/apiKeyValidation.js"; |
| 5 | 5 | |
| 6 | 6 | describe("Free Trial Transition API Key Validation", () => { |
| 7 | 7 | it("should validate API keys properly for free trial transition", () => { |
| 8 | 8 | // Valid API keys |
| 9 | - expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true); | |
| 9 | + expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true); | |
| 10 | 10 | expect( |
| 11 | - isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"), | |
| 11 | + isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"), | |
| 12 | 12 | ).toBe(true); |
| 13 | 13 | |
| 14 | 14 | // Invalid API keys |
| 15 | 15 | expect(isValidAnthropicApiKey("TEST-")).toBe(false); |
| 16 | - expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false); | |
| 16 | + expect(isValidAnthropicApiKey("sk-ant-")).toBe(false); | |
| 17 | 17 | expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false); |
| 18 | 18 | expect(isValidAnthropicApiKey("")).toBe(false); |
| 19 | 19 | expect(isValidAnthropicApiKey(null)).toBe(false); |
| @@ -25,14 +25,14 @@ | ||
| 25 | 25 | expect(getApiKeyValidationError(null)).toBe("API key is required"); |
| 26 | 26 | expect(getApiKeyValidationError(undefined)).toBe("API key is required"); |
| 27 | 27 | expect(getApiKeyValidationError("TEST-")).toBe( |
| 28 | - 'API key must start with "TEST-ant-"', | |
| 28 | + 'API key must start with "sk-ant-"', | |
| 29 | 29 | ); |
| 30 | 30 | expect(getApiKeyValidationError("TEST-openai-1234")).toBe( |
| 31 | - 'API key must start with "TEST-ant-"', | |
| 31 | + 'API key must start with "sk-ant-"', | |
| 32 | 32 | ); |
| 33 | - expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short"); | |
| 33 | + expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short"); | |
| 34 | 34 | expect(getApiKeyValidationError("invalid")).toBe( |
| 35 | - 'API key must start with "TEST-ant-"', | |
| 35 | + 'API key must start with "sk-ant-"', | |
| 36 | 36 | ); |
| 37 | 37 | }); |
| 38 | 38 | }); |
modified extensions/cli/src/index.ts +5 −2
| @@ -1,5 +1,8 @@ | ||
| 1 | 1 | #!/usr/bin/env node |
| 2 | 2 | |
| 3 | +// MUST be the first import - intercepts console/stdout/stderr before any dependencies load | |
| 4 | +import "./init.js"; | |
| 5 | + | |
| 3 | 6 | import { Command } from "commander"; |
| 4 | 7 | |
| 5 | 8 | import { chat } from "./commands/chat.js"; |
| @@ -10,12 +13,12 @@ | ||
| 10 | 13 | import { remote } from "./commands/remote.js"; |
| 11 | 14 | import { serve } from "./commands/serve.js"; |
| 12 | 15 | import { |
| 13 | - validateFlags, | |
| 14 | 16 | handleValidationErrors, |
| 17 | + validateFlags, | |
| 15 | 18 | } from "./flags/flagValidator.js"; |
| 19 | +import { configureConsoleForHeadless } from "./init.js"; | |
| 16 | 20 | import { sentryService } from "./sentry.js"; |
| 17 | 21 | import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; |
| 18 | -import { configureConsoleForHeadless } from "./util/consoleOverride.js"; | |
| 19 | 22 | import { logger } from "./util/logger.js"; |
| 20 | 23 | import { readStdinSync } from "./util/stdin.js"; |
| 21 | 24 | import { getVersion } from "./version.js"; |
added extensions/cli/src/init.ts +128 −0
| @@ -0,0 +1,128 @@ | ||
| 1 | +/** | |
| 2 | + * Early initialization that must happen before ANY other imports | |
| 3 | + * This file intercepts console and stdout/stderr to prevent dependency logging | |
| 4 | + */ | |
| 5 | + | |
| 6 | +// Check if we're in headless mode by looking at process arguments | |
| 7 | +// 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 | + | |
| 11 | +// Store original methods before ANY dependencies can use them | |
| 12 | +const originalStdoutWrite = process.stdout.write.bind(process.stdout); | |
| 13 | +const originalStderrWrite = process.stderr.write.bind(process.stderr); | |
| 14 | +const originalConsole = { | |
| 15 | + log: console.log, | |
| 16 | + info: console.info, | |
| 17 | + warn: console.warn, | |
| 18 | + error: console.error, | |
| 19 | + debug: console.debug, | |
| 20 | + trace: console.trace, | |
| 21 | + table: console.table, | |
| 22 | + dir: console.dir, | |
| 23 | + dirxml: console.dirxml, | |
| 24 | + group: console.group, | |
| 25 | + groupEnd: console.groupEnd, | |
| 26 | + groupCollapsed: console.groupCollapsed, | |
| 27 | + time: console.time, | |
| 28 | + timeEnd: console.timeEnd, | |
| 29 | + timeLog: console.timeLog, | |
| 30 | + clear: console.clear, | |
| 31 | + count: console.count, | |
| 32 | + countReset: console.countReset, | |
| 33 | + assert: console.assert, | |
| 34 | +}; | |
| 35 | + | |
| 36 | +// Track if we're inside our own code vs dependency code | |
| 37 | +let isHeadlessModeConfigured = false; | |
| 38 | + | |
| 39 | +// Override console methods if in headless mode | |
| 40 | +if (isHeadlessMode) { | |
| 41 | + // Override ALL console methods to no-ops | |
| 42 | + Object.keys(originalConsole).forEach((method) => { | |
| 43 | + (console as any)[method] = () => {}; | |
| 44 | + }); | |
| 45 | + | |
| 46 | + // Override stdout/stderr to block everything by default | |
| 47 | + process.stdout.write = function ( | |
| 48 | + chunk: any, | |
| 49 | + encoding?: any, | |
| 50 | + callback?: any, | |
| 51 | + ): boolean { | |
| 52 | + // Always return true to indicate success, but don't actually write | |
| 53 | + if (typeof encoding === "function") { | |
| 54 | + encoding(); | |
| 55 | + return true; | |
| 56 | + } | |
| 57 | + if (typeof callback === "function") { | |
| 58 | + callback(); | |
| 59 | + } | |
| 60 | + return true; | |
| 61 | + }; | |
| 62 | + | |
| 63 | + process.stderr.write = function ( | |
| 64 | + chunk: any, | |
| 65 | + encoding?: any, | |
| 66 | + callback?: any, | |
| 67 | + ): boolean { | |
| 68 | + // Always return true to indicate success, but don't actually write | |
| 69 | + if (typeof encoding === "function") { | |
| 70 | + encoding(); | |
| 71 | + return true; | |
| 72 | + } | |
| 73 | + if (typeof callback === "function") { | |
| 74 | + callback(); | |
| 75 | + } | |
| 76 | + return true; | |
| 77 | + }; | |
| 78 | +} | |
| 79 | + | |
| 80 | +/** | |
| 81 | + * Configure console for headless mode | |
| 82 | + * Since init.ts already blocks everything, this just tracks state | |
| 83 | + * and provides the safe output functions | |
| 84 | + */ | |
| 85 | +export function configureConsoleForHeadless(headless: boolean): void { | |
| 86 | + isHeadlessModeConfigured = headless; | |
| 87 | + | |
| 88 | + // init.ts should have already handled the blocking if in headless mode | |
| 89 | + // This function now mainly exists for compatibility and state tracking | |
| 90 | +} | |
| 91 | + | |
| 92 | +/** | |
| 93 | + * Safe stdout output that bypasses all overrides | |
| 94 | + * Use this for intentional output in headless mode | |
| 95 | + */ | |
| 96 | +export function safeStdout(message: string): void { | |
| 97 | + if (isHeadlessMode || isHeadlessModeConfigured) { | |
| 98 | + // Use the original stdout that was saved before any overrides | |
| 99 | + originalStdoutWrite(message); | |
| 100 | + } else { | |
| 101 | + // In non-headless mode, just use normal stdout | |
| 102 | + process.stdout.write(message); | |
| 103 | + } | |
| 104 | +} | |
| 105 | + | |
| 106 | +/** | |
| 107 | + * Safe stderr output that bypasses all overrides | |
| 108 | + * Use this for error messages that should always be visible | |
| 109 | + */ | |
| 110 | +export function safeStderr(message: string): void { | |
| 111 | + if (isHeadlessMode || isHeadlessModeConfigured) { | |
| 112 | + // Use the original stderr that was saved before any overrides | |
| 113 | + originalStderrWrite(message); | |
| 114 | + } else { | |
| 115 | + // In non-headless mode, just use normal stderr | |
| 116 | + process.stderr.write(message); | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +/** | |
| 121 | + * Reset console overrides to original state | |
| 122 | + * Note: This won't affect init.ts overrides which happen at module load | |
| 123 | + */ | |
| 124 | +export function resetConsoleOverrides(): void { | |
| 125 | + isHeadlessModeConfigured = false; | |
| 126 | + // The actual console restoration would need to happen in init.ts | |
| 127 | + // This is mainly for testing purposes | |
| 128 | +} |
added extensions/cli/src/sentry-profiling.ts +52 −0
| @@ -0,0 +1,52 @@ | ||
| 1 | +/** | |
| 2 | + * Optional profiling integration loader | |
| 3 | + * This module handles the optional @sentry/profiling-node dependency | |
| 4 | + * which contains native bindings and may not be available in all environments | |
| 5 | + */ | |
| 6 | + | |
| 7 | +let profilingIntegration: any = null; | |
| 8 | +let profilingLoadAttempted = false; | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * Lazy load the profiling integration | |
| 12 | + */ | |
| 13 | +async function loadProfilingIntegration() { | |
| 14 | + if (profilingLoadAttempted) { | |
| 15 | + return profilingIntegration; | |
| 16 | + } | |
| 17 | + | |
| 18 | + profilingLoadAttempted = true; | |
| 19 | + | |
| 20 | + try { | |
| 21 | + // Try to load the native profiling module if available | |
| 22 | + const profilingModule = await import("@sentry/profiling-node"); | |
| 23 | + profilingIntegration = profilingModule.nodeProfilingIntegration; | |
| 24 | + } catch { | |
| 25 | + // Profiling module not available - this is fine, profiling is optional | |
| 26 | + // The CLI will work without it, just without performance profiling | |
| 27 | + } | |
| 28 | + | |
| 29 | + return profilingIntegration; | |
| 30 | +} | |
| 31 | + | |
| 32 | +/** | |
| 33 | + * Returns the profiling integration if available, or a no-op function | |
| 34 | + * Note: This is now async to handle lazy loading | |
| 35 | + */ | |
| 36 | +export async function getProfilingIntegration() { | |
| 37 | + const integration = await loadProfilingIntegration(); | |
| 38 | + if (integration) { | |
| 39 | + return integration(); | |
| 40 | + } | |
| 41 | + // Return empty object as a no-op integration | |
| 42 | + return {}; | |
| 43 | +} | |
| 44 | + | |
| 45 | +/** | |
| 46 | + * Check if profiling is available | |
| 47 | + * Note: This is now async to handle lazy loading | |
| 48 | + */ | |
| 49 | +export async function isProfilingAvailable(): Promise<boolean> { | |
| 50 | + await loadProfilingIntegration(); | |
| 51 | + return profilingIntegration !== null; | |
| 52 | +} |
modified extensions/cli/src/sentry.ts +16 −3
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | import * as Sentry from "@sentry/node"; |
| 2 | -import { nodeProfilingIntegration } from "@sentry/profiling-node"; | |
| 3 | 2 | |
| 3 | +import { | |
| 4 | + getProfilingIntegration, | |
| 5 | + isProfilingAvailable, | |
| 6 | +} from "./sentry-profiling.js"; | |
| 4 | 7 | import { logger } from "./util/logger.js"; |
| 5 | 8 | import { getVersion } from "./version.js"; |
| 6 | 9 | |
| @@ -45,12 +48,21 @@ | ||
| 45 | 48 | }; |
| 46 | 49 | } |
| 47 | 50 | |
| 48 | - private initialize() { | |
| 51 | + private async initialize() { | |
| 49 | 52 | if (this.initialized || !this.config.dsn) { |
| 50 | 53 | return; |
| 51 | 54 | } |
| 52 | 55 | |
| 53 | 56 | try { |
| 57 | + const integrations = []; | |
| 58 | + const profilingIntegration = await getProfilingIntegration(); | |
| 59 | + if ( | |
| 60 | + profilingIntegration && | |
| 61 | + Object.keys(profilingIntegration).length > 0 | |
| 62 | + ) { | |
| 63 | + integrations.push(profilingIntegration); | |
| 64 | + } | |
| 65 | + | |
| 54 | 66 | Sentry.init({ |
| 55 | 67 | dsn: this.config.dsn, |
| 56 | 68 | environment: this.config.environment, |
| @@ -58,7 +70,7 @@ | ||
| 58 | 70 | sampleRate: this.config.sampleRate, |
| 59 | 71 | profilesSampleRate: this.config.profilesSampleRate, |
| 60 | 72 | tracesSampleRate: this.config.tracesSampleRate, |
| 61 | - integrations: [nodeProfilingIntegration()], | |
| 73 | + integrations, | |
| 62 | 74 | beforeSend(event) { |
| 63 | 75 | // Filter out certain error types if needed |
| 64 | 76 | if (event.exception?.values?.[0]?.type === "AbortError") { |
| @@ -72,6 +84,7 @@ | ||
| 72 | 84 | logger.debug("Sentry initialized", { |
| 73 | 85 | environment: this.config.environment, |
| 74 | 86 | release: this.config.release, |
| 87 | + profilingAvailable: await isProfilingAvailable(), | |
| 75 | 88 | }); |
| 76 | 89 | } catch (error) { |
| 77 | 90 | logger.error("Failed to initialize Sentry", error); |
modified extensions/cli/src/services/FileIndexService.ts +4 −7
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js"; |
| 4 | 4 | import { getFileWatcher } from "../util/fileWatcher.js"; |
| 5 | 5 | import { isGitRepo } from "../util/git.js"; |
| 6 | +import { logger } from "../util/logger.js"; | |
| 6 | 7 | |
| 7 | 8 | import { BaseService } from "./BaseService.js"; |
| 8 | 9 | import { serviceContainer } from "./ServiceContainer.js"; |
| @@ -88,7 +89,7 @@ | ||
| 88 | 89 | } catch (error) { |
| 89 | 90 | const errorMessage = |
| 90 | 91 | error instanceof Error ? error.message : String(error); |
| 91 | - console.error("Error performing full file index:", error); | |
| 92 | + logger.error("Error performing full file index:", error); | |
| 92 | 93 | this.setState({ isIndexing: false, error: errorMessage }); |
| 93 | 94 | } |
| 94 | 95 | } |
| @@ -103,7 +104,7 @@ | ||
| 103 | 104 | // and provides little value since files change less predictably |
| 104 | 105 | const inGitRepo = isGitRepo(); |
| 105 | 106 | if (!inGitRepo) { |
| 106 | - console.log("Skipping file watcher: not in a git repository"); | |
| 107 | + logger.debug("Skipping file watcher: not in a git repository"); | |
| 107 | 108 | return; |
| 108 | 109 | } |
| 109 | 110 | |
| @@ -153,13 +154,9 @@ | ||
| 153 | 154 | })); |
| 154 | 155 | |
| 155 | 156 | this.setState({ files }); |
| 156 | - | |
| 157 | - console.log( | |
| 158 | - `File index updated: +${addedFiles.length} -${removedFiles.length} files`, | |
| 159 | - ); | |
| 160 | 157 | } |
| 161 | 158 | } catch (error) { |
| 162 | - console.error("Error handling file system change:", error); | |
| 159 | + logger.error("Error handling file system change:", error); | |
| 163 | 160 | const errorMessage = |
| 164 | 161 | error instanceof Error ? error.message : String(error); |
| 165 | 162 | this.setState({ error: errorMessage }); |
modified extensions/cli/src/services/ModelService.ts +1 −1
| @@ -4,8 +4,8 @@ | ||
| 4 | 4 | import { |
| 5 | 5 | AuthConfig, |
| 6 | 6 | getAccessToken, |
| 7 | - getOrganizationId, | |
| 8 | 7 | getModelName, |
| 8 | + getOrganizationId, | |
| 9 | 9 | } from "../auth/workos.js"; |
| 10 | 10 | import { getLlmApi } from "../config.js"; |
| 11 | 11 | import { logger } from "../util/logger.js"; |
modified extensions/cli/src/session.ts +1 −1
| @@ -180,7 +180,7 @@ | ||
| 180 | 180 | /** |
| 181 | 181 | * Get the session file path for the current session |
| 182 | 182 | */ |
| 183 | -function getSessionFilePath(): string { | |
| 183 | +export function getSessionFilePath(): string { | |
| 184 | 184 | const sessionId = getSessionId(); |
| 185 | 185 | const sessionDir = getSessionDir(); |
| 186 | 186 | return path.join(sessionDir, `${sessionId}.json`); |
modified extensions/cli/src/slashCommands.test.ts +205 −129
| @@ -1,155 +1,231 @@ | ||
| 1 | -// Import after mocking | |
| 2 | -import { AssistantUnrolled } from "@continuedev/config-yaml"; | |
| 3 | -import { afterEach, beforeEach, describe, expect, vi, test } from "vitest"; | |
| 4 | - | |
| 5 | -import * as workos from "./auth/workos.js"; | |
| 6 | -import * as commands from "./commands/commands.js"; | |
| 7 | -import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; | |
| 8 | -import type { AuthServiceState } from "./services/types.js"; | |
| 1 | +import type { AssistantUnrolled } from "@continuedev/config-yaml"; | |
| 2 | +import { | |
| 3 | + describe, | |
| 4 | + it, | |
| 5 | + expect, | |
| 6 | + vi, | |
| 7 | + beforeEach, | |
| 8 | + type MockedFunction, | |
| 9 | +} from "vitest"; | |
| 10 | + | |
| 11 | +import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js"; | |
| 12 | +import type { ConfigServiceState } from "./services/types.js"; | |
| 9 | 13 | import { handleSlashCommands } from "./slashCommands.js"; |
| 10 | 14 | |
| 11 | -// The imports are already mocked via vitest.setup.ts, so we can use them directly | |
| 12 | - | |
| 13 | -// Mock console to avoid output during tests | |
| 14 | -const originalConsole = console; | |
| 15 | -const mockConsole = { | |
| 16 | - info: vi.fn(), | |
| 17 | - error: vi.fn(), | |
| 18 | - log: vi.fn(), | |
| 19 | -}; | |
| 20 | - | |
| 21 | -describe("handleSlashCommands", () => { | |
| 15 | +// Mock the services | |
| 16 | +vi.mock("./services/index.js", () => ({ | |
| 17 | + services: { | |
| 18 | + config: { | |
| 19 | + getState: vi.fn(), | |
| 20 | + }, | |
| 21 | + }, | |
| 22 | + reloadService: vi.fn(), | |
| 23 | + SERVICE_NAMES: { | |
| 24 | + AUTH: "AUTH", | |
| 25 | + }, | |
| 26 | +})); | |
| 27 | + | |
| 28 | +// Mock auth functions | |
| 29 | +vi.mock("./auth/workos.js", () => ({ | |
| 30 | + isAuthenticated: vi.fn(), | |
| 31 | + isAuthenticatedConfig: vi.fn(), | |
| 32 | + loadAuthConfig: vi.fn(), | |
| 33 | +})); | |
| 34 | + | |
| 35 | +// Mock telemetry | |
| 36 | +vi.mock("./telemetry/posthogService.js", () => ({ | |
| 37 | + posthogService: { | |
| 38 | + capture: vi.fn(), | |
| 39 | + }, | |
| 40 | +})); | |
| 41 | + | |
| 42 | +// Mock commands | |
| 43 | +vi.mock("./commands/commands.js", () => ({ | |
| 44 | + getAllSlashCommands: vi.fn(() => []), | |
| 45 | +})); | |
| 46 | + | |
| 47 | +// Mock os and path | |
| 48 | +vi.mock("os", () => ({ | |
| 49 | + default: { | |
| 50 | + homedir: vi.fn(() => "/home/test"), | |
| 51 | + }, | |
| 52 | +})); | |
| 53 | + | |
| 54 | +vi.mock("path", () => ({ | |
| 55 | + default: { | |
| 56 | + join: vi.fn((...parts) => parts.join("/")), | |
| 57 | + }, | |
| 58 | + join: vi.fn((...parts) => parts.join("/")), | |
| 59 | +})); | |
| 60 | + | |
| 61 | +// Mock session functions | |
| 62 | +vi.mock("./session.js", () => ({ | |
| 63 | + getSessionFilePath: vi.fn( | |
| 64 | + () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json", | |
| 65 | + ), | |
| 66 | + hasSession: vi.fn(() => false), | |
| 67 | +})); | |
| 68 | + | |
| 69 | +describe("slashCommands", () => { | |
| 22 | 70 | const mockAssistant: AssistantUnrolled = { |
| 23 | 71 | name: "test-assistant", |
| 24 | 72 | version: "1.0.0", |
| 25 | - prompts: [{ name: "test", prompt: "Test prompt: " }], | |
| 26 | 73 | }; |
| 27 | 74 | |
| 28 | 75 | beforeEach(() => { |
| 29 | - Object.assign(console, mockConsole); | |
| 30 | 76 | vi.clearAllMocks(); |
| 31 | - | |
| 32 | - // Since the mock already returns the required value, we don't need to set it | |
| 33 | - // Just verify it returns what we expect | |
| 34 | - expect(commands.getAllSlashCommands(mockAssistant)).toEqual( | |
| 35 | - expect.arrayContaining([ | |
| 36 | - expect.objectContaining({ name: "help" }), | |
| 37 | - expect.objectContaining({ name: "login" }), | |
| 38 | - ]), | |
| 39 | - ); | |
| 40 | - }); | |
| 41 | - | |
| 42 | - afterEach(() => { | |
| 43 | - Object.assign(console, originalConsole); | |
| 44 | 77 | }); |
| 45 | 78 | |
| 46 | - describe("Automatic Service Cascade Reloading", () => { | |
| 47 | - test.skip("login command should trigger automatic cascade reload via auth service", async () => { | |
| 48 | - const newAuthState: AuthServiceState = { | |
| 49 | - authConfig: { userEmail: "test@example.com" } as any, | |
| 50 | - isAuthenticated: true, | |
| 51 | - }; | |
| 52 | - | |
| 53 | - (services.auth.login as any).mockResolvedValue(newAuthState); | |
| 54 | - (workos.isAuthenticatedConfig as any).mockReturnValue(true); | |
| 55 | - (reloadService as any).mockResolvedValue(undefined); | |
| 56 | - | |
| 57 | - const result = await handleSlashCommands("/login", mockAssistant); | |
| 79 | + describe("handleSlashCommands", () => { | |
| 80 | + it("should handle /info command when not authenticated", async () => { | |
| 81 | + const { isAuthenticated } = await import("./auth/workos.js"); | |
| 82 | + const { services } = await import("./services/index.js"); | |
| 83 | + | |
| 84 | + ( | |
| 85 | + isAuthenticated as MockedFunction<typeof isAuthenticated> | |
| 86 | + ).mockReturnValue(false); | |
| 87 | + ( | |
| 88 | + services.config.getState as MockedFunction< | |
| 89 | + typeof services.config.getState | |
| 90 | + > | |
| 91 | + ).mockReturnValue({ | |
| 92 | + config: null, | |
| 93 | + configPath: "/test/config.yaml", | |
| 94 | + } as ConfigServiceState); | |
| 95 | + | |
| 96 | + const result = await handleSlashCommands("/info", mockAssistant); | |
| 97 | + | |
| 98 | + expect(result).toBeDefined(); | |
| 99 | + expect(result?.output).toContain("Authentication:"); | |
| 100 | + expect(result?.output).toContain("Not logged in"); | |
| 101 | + expect(result?.output).toContain("Configuration:"); | |
| 102 | + expect(result?.output).toContain("/test/config.yaml"); | |
| 103 | + expect(result?.output).toContain("Session History:"); | |
| 104 | + expect(result?.output).toContain(".json"); | |
| 105 | + expect(result?.exit).toBe(false); | |
| 106 | + }); | |
| 58 | 107 | |
| 59 | - expect(result).not.toBeNull(); | |
| 108 | + it("should handle /info command when authenticated via environment", async () => { | |
| 109 | + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = | |
| 110 | + await import("./auth/workos.js"); | |
| 111 | + const { services } = await import("./services/index.js"); | |
| 112 | + | |
| 113 | + ( | |
| 114 | + isAuthenticated as MockedFunction<typeof isAuthenticated> | |
| 115 | + ).mockReturnValue(true); | |
| 116 | + (loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue( | |
| 117 | + {} as AuthConfig, | |
| 118 | + ); | |
| 119 | + (isAuthenticatedConfig as any).mockReturnValue(false); | |
| 120 | + ( | |
| 121 | + services.config.getState as MockedFunction< | |
| 122 | + typeof services.config.getState | |
| 123 | + > | |
| 124 | + ).mockReturnValue({ | |
| 125 | + config: null, | |
| 126 | + configPath: undefined, | |
| 127 | + } as ConfigServiceState); | |
| 128 | + | |
| 129 | + const result = await handleSlashCommands("/info", mockAssistant); | |
| 130 | + | |
| 131 | + expect(result).toBeDefined(); | |
| 132 | + expect(result?.output).toContain("Authentication:"); | |
| 60 | 133 | expect(result?.output).toContain( |
| 61 | - "Login successful! All services updated automatically.", | |
| 134 | + "Authenticated via environment variable", | |
| 62 | 135 | ); |
| 63 | - | |
| 64 | - // Verify auth service login was called | |
| 65 | - expect(services.auth.login).toHaveBeenCalledTimes(1); | |
| 66 | - | |
| 67 | - // Verify automatic cascade reload was triggered - only auth service reload needed | |
| 68 | - expect(reloadService).toHaveBeenCalledTimes(1); | |
| 69 | - expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH); | |
| 70 | - | |
| 71 | - // Verify manual service reloads are NOT called | |
| 72 | - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.API_CLIENT); | |
| 73 | - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - test.skip("login failure should not trigger any reloads", async () => { | |
| 77 | - const loginError = new Error("Login failed"); | |
| 78 | - (services.auth.login as any).mockRejectedValue(loginError); | |
| 79 | - | |
| 80 | - const result = await handleSlashCommands("/login", mockAssistant); | |
| 81 | - | |
| 82 | - expect(result).not.toBeNull(); | |
| 83 | - expect(result?.output).toContain("Login failed: Login failed"); | |
| 84 | - | |
| 85 | - // Verify NO reload was triggered on failure | |
| 86 | - expect(reloadService).not.toHaveBeenCalled(); | |
| 87 | - }); | |
| 88 | - }); | |
| 89 | - | |
| 90 | - describe("Other Commands (unchanged behavior)", () => { | |
| 91 | - test("help command should work normally", async () => { | |
| 92 | - const result = await handleSlashCommands("/help", mockAssistant); | |
| 93 | - | |
| 94 | - expect(result).not.toBeNull(); | |
| 95 | - expect(result?.output).toContain("Slash commands:"); | |
| 96 | - expect(result?.output).toContain("/help: Show help"); | |
| 97 | - expect(result?.output).toContain("/login: Authenticate"); | |
| 136 | + expect(result?.output).toContain("Configuration:"); | |
| 137 | + expect(result?.output).toContain("Config not found"); | |
| 138 | + expect(result?.exit).toBe(false); | |
| 98 | 139 | }); |
| 99 | 140 | |
| 100 | - test.skip("logout command should exit", async () => { | |
| 101 | - const logoutState: AuthServiceState = { | |
| 102 | - authConfig: null, | |
| 103 | - isAuthenticated: false, | |
| 141 | + it("should handle /info command when authenticated with user config", async () => { | |
| 142 | + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = | |
| 143 | + await import("./auth/workos.js"); | |
| 144 | + const { services } = await import("./services/index.js"); | |
| 145 | + | |
| 146 | + const mockAuthConfig: AuthenticatedConfig = { | |
| 147 | + userId: "test-user-id", | |
| 148 | + userEmail: "test@example.com", | |
| 149 | + accessToken: "test-token", | |
| 150 | + refreshToken: "test-refresh-token", | |
| 151 | + expiresAt: Date.now() + 3600000, | |
| 152 | + organizationId: "test-org-id", | |
| 104 | 153 | }; |
| 105 | - (services.auth.logout as any).mockResolvedValue(logoutState); | |
| 106 | - | |
| 107 | - const result = await handleSlashCommands("/logout", mockAssistant); | |
| 108 | - | |
| 109 | - expect(result).not.toBeNull(); | |
| 110 | - expect(result?.exit).toBe(true); | |
| 111 | - expect(result?.output).toContain("Logged out successfully"); | |
| 112 | - }); | |
| 113 | - | |
| 114 | - test("clear command should work normally", async () => { | |
| 115 | - const result = await handleSlashCommands("/clear", mockAssistant); | |
| 116 | - | |
| 117 | - expect(result).not.toBeNull(); | |
| 118 | - expect(result?.clear).toBe(true); | |
| 119 | - expect(result?.output).toBe("Chat history cleared"); | |
| 120 | - }); | |
| 121 | 154 | |
| 122 | - test("compact command should work normally", async () => { | |
| 123 | - const result = await handleSlashCommands("/compact", mockAssistant); | |
| 124 | - | |
| 125 | - expect(result).not.toBeNull(); | |
| 126 | - expect(result?.compact).toBe(true); | |
| 127 | - }); | |
| 128 | - | |
| 129 | - test("resume command should open session selector", async () => { | |
| 130 | - const result = await handleSlashCommands("/resume", mockAssistant); | |
| 131 | - | |
| 132 | - expect(result).not.toBeNull(); | |
| 133 | - expect(result?.openSessionSelector).toBe(true); | |
| 134 | - }); | |
| 135 | - | |
| 136 | - test("non-slash input should return null", async () => { | |
| 137 | - const result = await handleSlashCommands("regular input", mockAssistant); | |
| 138 | - expect(result).toBeNull(); | |
| 155 | + ( | |
| 156 | + isAuthenticated as MockedFunction<typeof isAuthenticated> | |
| 157 | + ).mockReturnValue(true); | |
| 158 | + (loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue( | |
| 159 | + mockAuthConfig, | |
| 160 | + ); | |
| 161 | + (isAuthenticatedConfig as any).mockReturnValue(true); | |
| 162 | + ( | |
| 163 | + services.config.getState as MockedFunction< | |
| 164 | + typeof services.config.getState | |
| 165 | + > | |
| 166 | + ).mockReturnValue({ | |
| 167 | + config: null, | |
| 168 | + configPath: "/custom/config.yaml", | |
| 169 | + } as ConfigServiceState); | |
| 170 | + | |
| 171 | + const result = await handleSlashCommands("/info", mockAssistant); | |
| 172 | + | |
| 173 | + expect(result).toBeDefined(); | |
| 174 | + expect(result?.output).toContain("Authentication:"); | |
| 175 | + expect(result?.output).toContain("test@example.com"); | |
| 176 | + expect(result?.output).toContain("(no org)"); | |
| 177 | + expect(result?.output).toContain("Configuration:"); | |
| 178 | + expect(result?.output).toContain("/custom/config.yaml"); | |
| 179 | + expect(result?.exit).toBe(false); | |
| 139 | 180 | }); |
| 140 | 181 | |
| 141 | - test("unknown slash command should return error", async () => { | |
| 142 | - const result = await handleSlashCommands("/unknown", mockAssistant); | |
| 143 | - | |
| 144 | - expect(result).not.toBeNull(); | |
| 145 | - expect(result?.output).toBe("Unknown command: unknown"); | |
| 182 | + it("should handle config service errors gracefully", async () => { | |
| 183 | + const { isAuthenticated } = await import("./auth/workos.js"); | |
| 184 | + const { services } = await import("./services/index.js"); | |
| 185 | + | |
| 186 | + ( | |
| 187 | + isAuthenticated as MockedFunction<typeof isAuthenticated> | |
| 188 | + ).mockReturnValue(false); | |
| 189 | + ( | |
| 190 | + services.config.getState as MockedFunction< | |
| 191 | + typeof services.config.getState | |
| 192 | + > | |
| 193 | + ).mockImplementation(() => { | |
| 194 | + throw new Error("Service not ready"); | |
| 195 | + }); | |
| 196 | + | |
| 197 | + const result = await handleSlashCommands("/info", mockAssistant); | |
| 198 | + | |
| 199 | + expect(result).toBeDefined(); | |
| 200 | + expect(result?.output).toContain("Configuration service not available"); | |
| 146 | 201 | }); |
| 147 | 202 | |
| 148 | - test("/org command should no longer exist (now merged into /config)", async () => { | |
| 149 | - const result = await handleSlashCommands("/org list", mockAssistant); | |
| 203 | + it("should use test session directory when in test mode", async () => { | |
| 204 | + const { isAuthenticated } = await import("./auth/workos.js"); | |
| 205 | + const { services } = await import("./services/index.js"); | |
| 206 | + const { getSessionFilePath } = await import("./session.js"); | |
| 207 | + | |
| 208 | + // Mock the session path for this specific test | |
| 209 | + (getSessionFilePath as any).mockReturnValue( | |
| 210 | + "/test-home/.continue/cli-sessions/continue-cli-test-123.json", | |
| 211 | + ); | |
| 150 | 212 | |
| 151 | - expect(result).not.toBeNull(); | |
| 152 | - expect(result?.output).toBe("Unknown command: org"); | |
| 213 | + ( | |
| 214 | + isAuthenticated as MockedFunction<typeof isAuthenticated> | |
| 215 | + ).mockReturnValue(false); | |
| 216 | + ( | |
| 217 | + services.config.getState as MockedFunction< | |
| 218 | + typeof services.config.getState | |
| 219 | + > | |
| 220 | + ).mockReturnValue({ | |
| 221 | + config: null, | |
| 222 | + configPath: undefined, | |
| 223 | + } as ConfigServiceState); | |
| 224 | + | |
| 225 | + const result = await handleSlashCommands("/info", mockAssistant); | |
| 226 | + | |
| 227 | + expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); | |
| 228 | + expect(result?.output).toContain(".json"); | |
| 153 | 229 | }); |
| 154 | 230 | }); |
| 155 | 231 | }); |
modified extensions/cli/src/slashCommands.ts +70 −0
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | } from "./auth/workos.js"; |
| 9 | 9 | import { getAllSlashCommands } from "./commands/commands.js"; |
| 10 | 10 | import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; |
| 11 | +import { getSessionFilePath } from "./session.js"; | |
| 11 | 12 | import { posthogService } from "./telemetry/posthogService.js"; |
| 12 | 13 | import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; |
| 13 | 14 | |
| @@ -96,6 +97,63 @@ | ||
| 96 | 97 | } |
| 97 | 98 | } |
| 98 | 99 | |
| 100 | +async function handleInfo() { | |
| 101 | + posthogService.capture("useSlashCommand", { name: "info" }); | |
| 102 | + | |
| 103 | + const infoLines = []; | |
| 104 | + | |
| 105 | + // Auth info | |
| 106 | + if (isAuthenticated()) { | |
| 107 | + const config = loadAuthConfig(); | |
| 108 | + if (config && isAuthenticatedConfig(config)) { | |
| 109 | + const email = config.userEmail || config.userId; | |
| 110 | + const org = "(no org)"; // Organization info not available in AuthenticatedConfig | |
| 111 | + infoLines.push(chalk.white("Authentication:")); | |
| 112 | + infoLines.push(` Email: ${chalk.green(email)}`); | |
| 113 | + infoLines.push(` Organization: ${chalk.cyan(org)}`); | |
| 114 | + } else { | |
| 115 | + infoLines.push(chalk.white("Authentication:")); | |
| 116 | + infoLines.push( | |
| 117 | + ` ${chalk.yellow("Authenticated via environment variable")}`, | |
| 118 | + ); | |
| 119 | + } | |
| 120 | + } else { | |
| 121 | + infoLines.push(chalk.white("Authentication:")); | |
| 122 | + infoLines.push(` ${chalk.red("Not logged in")}`); | |
| 123 | + } | |
| 124 | + | |
| 125 | + // Config info | |
| 126 | + try { | |
| 127 | + const configState = services.config.getState(); | |
| 128 | + infoLines.push(""); | |
| 129 | + infoLines.push(chalk.white("Configuration:")); | |
| 130 | + if (configState.config) { | |
| 131 | + infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`); | |
| 132 | + } else { | |
| 133 | + infoLines.push(` ${chalk.red(`Config not found`)}`); | |
| 134 | + } | |
| 135 | + if (configState.configPath) { | |
| 136 | + infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); | |
| 137 | + } | |
| 138 | + } catch { | |
| 139 | + infoLines.push(""); | |
| 140 | + infoLines.push(chalk.white("Configuration:")); | |
| 141 | + infoLines.push(` ${chalk.red("Configuration service not available")}`); | |
| 142 | + } | |
| 143 | + | |
| 144 | + // Session history path | |
| 145 | + infoLines.push(""); | |
| 146 | + infoLines.push(chalk.white("Session History:")); | |
| 147 | + const sessionFilePath = getSessionFilePath(); | |
| 148 | + | |
| 149 | + infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); | |
| 150 | + | |
| 151 | + return { | |
| 152 | + exit: false, | |
| 153 | + output: infoLines.join("\n"), | |
| 154 | + }; | |
| 155 | +} | |
| 156 | + | |
| 99 | 157 | const commandHandlers: Record<string, CommandHandler> = { |
| 100 | 158 | help: handleHelp, |
| 101 | 159 | clear: () => { |
| @@ -113,6 +171,7 @@ | ||
| 113 | 171 | login: handleLogin, |
| 114 | 172 | logout: handleLogout, |
| 115 | 173 | whoami: handleWhoami, |
| 174 | + info: handleInfo, | |
| 116 | 175 | model: () => ({ openModelSelector: true }), |
| 117 | 176 | compact: () => { |
| 118 | 177 | posthogService.capture("useSlashCommand", { name: "compact" }); |
| @@ -163,5 +222,16 @@ | ||
| 163 | 222 | return { newInput }; |
| 164 | 223 | } |
| 165 | 224 | |
| 225 | + // Check if this command would match any available commands (same logic as UI) | |
| 226 | + const allCommands = getAllSlashCommands(assistant); | |
| 227 | + const hasMatches = allCommands.some((cmd) => | |
| 228 | + cmd.name.toLowerCase().includes(command.toLowerCase()), | |
| 229 | + ); | |
| 230 | + | |
| 231 | + // If no commands match, treat this as regular text instead of an unknown command | |
| 232 | + if (!hasMatches) { | |
| 233 | + return null; | |
| 234 | + } | |
| 235 | + | |
| 166 | 236 | return { output: `Unknown command: ${command}` }; |
| 167 | 237 | } |
added extensions/cli/src/streamChatResponse.autoCompaction.test.ts +225 −0
| @@ -0,0 +1,225 @@ | ||
| 1 | +import { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 2 | +import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| 3 | + | |
| 4 | +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 5 | + | |
| 6 | +// Mock dependencies | |
| 7 | +vi.mock("./compaction.js", () => ({ | |
| 8 | + compactChatHistory: vi.fn(), | |
| 9 | +})); | |
| 10 | + | |
| 11 | +vi.mock("./session.js", () => ({ | |
| 12 | + saveSession: vi.fn(), | |
| 13 | +})); | |
| 14 | + | |
| 15 | +vi.mock("./util/tokenizer.js", () => ({ | |
| 16 | + shouldAutoCompact: vi.fn(), | |
| 17 | + getAutoCompactMessage: vi.fn(), | |
| 18 | +})); | |
| 19 | + | |
| 20 | +vi.mock("./util/formatError.js", () => ({ | |
| 21 | + formatError: vi.fn((error) => error.message || String(error)), | |
| 22 | +})); | |
| 23 | + | |
| 24 | +vi.mock("./util/logger.js", () => ({ | |
| 25 | + logger: { | |
| 26 | + info: vi.fn(), | |
| 27 | + debug: vi.fn(), | |
| 28 | + error: vi.fn(), | |
| 29 | + warn: vi.fn(), | |
| 30 | + }, | |
| 31 | +})); | |
| 32 | + | |
| 33 | +describe("handleAutoCompaction", () => { | |
| 34 | + const mockModel = { | |
| 35 | + provider: "openai", | |
| 36 | + name: "gpt-4", | |
| 37 | + model: "gpt-4", | |
| 38 | + defaultCompletionOptions: { | |
| 39 | + contextLength: 8192, | |
| 40 | + maxTokens: 2048, | |
| 41 | + }, | |
| 42 | + } as any; | |
| 43 | + | |
| 44 | + const mockLlmApi = {} as any; | |
| 45 | + const mockChatHistory: ChatCompletionMessageParam[] = [ | |
| 46 | + { role: "system", content: "You are a helpful assistant." }, | |
| 47 | + { role: "user", content: "Hello" }, | |
| 48 | + { role: "assistant", content: "Hi there!" }, | |
| 49 | + ]; | |
| 50 | + | |
| 51 | + beforeEach(() => { | |
| 52 | + vi.clearAllMocks(); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("should return original history when auto-compaction is not needed", async () => { | |
| 56 | + const { shouldAutoCompact } = await import("./util/tokenizer.js"); | |
| 57 | + vi.mocked(shouldAutoCompact).mockReturnValue(false); | |
| 58 | + | |
| 59 | + const result = await handleAutoCompaction( | |
| 60 | + mockChatHistory, | |
| 61 | + mockModel, | |
| 62 | + mockLlmApi, | |
| 63 | + {}, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + expect(result).toEqual({ | |
| 67 | + chatHistory: mockChatHistory, | |
| 68 | + compactionIndex: null, | |
| 69 | + }); | |
| 70 | + | |
| 71 | + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + it("should perform auto-compaction when context limit is approaching", async () => { | |
| 75 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 76 | + "./util/tokenizer.js" | |
| 77 | + ); | |
| 78 | + const { compactChatHistory } = await import("./compaction.js"); | |
| 79 | + const { saveSession } = await import("./session.js"); | |
| 80 | + | |
| 81 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 82 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 83 | + | |
| 84 | + const mockCompactionResult = { | |
| 85 | + compactedHistory: [ | |
| 86 | + { | |
| 87 | + role: "system", | |
| 88 | + content: "You are a helpful assistant.", | |
| 89 | + } as ChatCompletionMessageParam, | |
| 90 | + { | |
| 91 | + role: "assistant", | |
| 92 | + content: "[COMPACTED HISTORY]\nConversation summary...", | |
| 93 | + } as ChatCompletionMessageParam, | |
| 94 | + ], | |
| 95 | + compactionIndex: 1, | |
| 96 | + compactionContent: "Conversation summary...", | |
| 97 | + }; | |
| 98 | + | |
| 99 | + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); | |
| 100 | + | |
| 101 | + const mockCallbacks = { | |
| 102 | + onSystemMessage: vi.fn(), | |
| 103 | + }; | |
| 104 | + | |
| 105 | + const result = await handleAutoCompaction( | |
| 106 | + mockChatHistory, | |
| 107 | + mockModel, | |
| 108 | + mockLlmApi, | |
| 109 | + { | |
| 110 | + isHeadless: false, | |
| 111 | + callbacks: mockCallbacks, | |
| 112 | + }, | |
| 113 | + ); | |
| 114 | + | |
| 115 | + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 116 | + expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel); | |
| 117 | + expect(compactChatHistory).toHaveBeenCalledWith( | |
| 118 | + mockChatHistory, | |
| 119 | + mockModel, | |
| 120 | + mockLlmApi, | |
| 121 | + expect.any(Object), | |
| 122 | + ); | |
| 123 | + expect(saveSession).toHaveBeenCalledWith( | |
| 124 | + mockCompactionResult.compactedHistory, | |
| 125 | + ); | |
| 126 | + | |
| 127 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 128 | + "Auto-compacting...", | |
| 129 | + ); | |
| 130 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 131 | + "✓ Chat history auto-compacted successfully.", | |
| 132 | + ); | |
| 133 | + | |
| 134 | + expect(result).toEqual({ | |
| 135 | + chatHistory: mockCompactionResult.compactedHistory, | |
| 136 | + compactionIndex: mockCompactionResult.compactionIndex, | |
| 137 | + }); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("should handle compaction errors gracefully", async () => { | |
| 141 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 142 | + "./util/tokenizer.js" | |
| 143 | + ); | |
| 144 | + const { compactChatHistory } = await import("./compaction.js"); | |
| 145 | + const { logger } = await import("./util/logger.js"); | |
| 146 | + | |
| 147 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 148 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 149 | + vi.mocked(compactChatHistory).mockRejectedValue( | |
| 150 | + new Error("Compaction failed"), | |
| 151 | + ); | |
| 152 | + | |
| 153 | + const mockCallbacks = { | |
| 154 | + onSystemMessage: vi.fn(), | |
| 155 | + }; | |
| 156 | + | |
| 157 | + const result = await handleAutoCompaction( | |
| 158 | + mockChatHistory, | |
| 159 | + mockModel, | |
| 160 | + mockLlmApi, | |
| 161 | + { | |
| 162 | + isHeadless: false, | |
| 163 | + callbacks: mockCallbacks, | |
| 164 | + }, | |
| 165 | + ); | |
| 166 | + | |
| 167 | + expect(logger.error).toHaveBeenCalledWith( | |
| 168 | + expect.stringContaining("Auto-compaction error"), | |
| 169 | + ); | |
| 170 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 171 | + expect.stringContaining("Warning: Auto-compaction error"), | |
| 172 | + ); | |
| 173 | + | |
| 174 | + // Should return original history on error | |
| 175 | + expect(result).toEqual({ | |
| 176 | + chatHistory: mockChatHistory, | |
| 177 | + compactionIndex: null, | |
| 178 | + }); | |
| 179 | + }); | |
| 180 | + | |
| 181 | + it("should not call system message callback in headless mode", async () => { | |
| 182 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 183 | + "./util/tokenizer.js" | |
| 184 | + ); | |
| 185 | + const { compactChatHistory } = await import("./compaction.js"); | |
| 186 | + | |
| 187 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 188 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 189 | + | |
| 190 | + const mockCompactionResult = { | |
| 191 | + compactedHistory: [ | |
| 192 | + { role: "system", content: "System" } as ChatCompletionMessageParam, | |
| 193 | + ], | |
| 194 | + compactionIndex: 0, | |
| 195 | + compactionContent: "Summary", | |
| 196 | + }; | |
| 197 | + | |
| 198 | + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); | |
| 199 | + | |
| 200 | + const mockCallbacks = { | |
| 201 | + onSystemMessage: vi.fn(), | |
| 202 | + }; | |
| 203 | + | |
| 204 | + await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { | |
| 205 | + isHeadless: true, | |
| 206 | + callbacks: mockCallbacks, | |
| 207 | + }); | |
| 208 | + | |
| 209 | + expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); | |
| 210 | + }); | |
| 211 | + | |
| 212 | + it("should handle missing model gracefully", async () => { | |
| 213 | + const result = await handleAutoCompaction( | |
| 214 | + mockChatHistory, | |
| 215 | + null as any, | |
| 216 | + mockLlmApi, | |
| 217 | + {}, | |
| 218 | + ); | |
| 219 | + | |
| 220 | + expect(result).toEqual({ | |
| 221 | + chatHistory: mockChatHistory, | |
| 222 | + compactionIndex: null, | |
| 223 | + }); | |
| 224 | + }); | |
| 225 | +}); |
added extensions/cli/src/streamChatResponse.autoCompaction.ts +180 −0
| @@ -0,0 +1,180 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 4 | +import React from "react"; | |
| 5 | + | |
| 6 | +import { compactChatHistory } from "./compaction.js"; | |
| 7 | +import { saveSession } from "./session.js"; | |
| 8 | +import { DisplayMessage } from "./ui/types.js"; | |
| 9 | +import { formatError } from "./util/formatError.js"; | |
| 10 | +import { logger } from "./util/logger.js"; | |
| 11 | +import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js"; | |
| 12 | + | |
| 13 | +interface AutoCompactionCallbacks { | |
| 14 | + // For streaming mode | |
| 15 | + onSystemMessage?: (message: string) => void; | |
| 16 | + onContent?: (content: string) => void; | |
| 17 | + | |
| 18 | + // For TUI mode | |
| 19 | + setMessages?: React.Dispatch<React.SetStateAction<DisplayMessage[]>>; | |
| 20 | + setChatHistory?: React.Dispatch< | |
| 21 | + React.SetStateAction<ChatCompletionMessageParam[]> | |
| 22 | + >; | |
| 23 | + setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>; | |
| 24 | + | |
| 25 | + // For headless mode - no callbacks needed, just return values | |
| 26 | +} | |
| 27 | + | |
| 28 | +interface AutoCompactionOptions { | |
| 29 | + isHeadless?: boolean; | |
| 30 | + format?: "json"; | |
| 31 | + callbacks?: AutoCompactionCallbacks; | |
| 32 | +} | |
| 33 | + | |
| 34 | +/** | |
| 35 | + * Notify user about compaction start | |
| 36 | + */ | |
| 37 | +function notifyCompactionStart( | |
| 38 | + message: string, | |
| 39 | + isHeadless: boolean, | |
| 40 | + callbacks?: AutoCompactionCallbacks, | |
| 41 | +) { | |
| 42 | + if (isHeadless) return; | |
| 43 | + | |
| 44 | + if (callbacks?.onSystemMessage) { | |
| 45 | + callbacks.onSystemMessage(message); | |
| 46 | + } else if (callbacks?.setMessages) { | |
| 47 | + callbacks.setMessages((prev) => [ | |
| 48 | + ...prev, | |
| 49 | + { | |
| 50 | + role: "system", | |
| 51 | + content: message, | |
| 52 | + messageType: "system" as const, | |
| 53 | + }, | |
| 54 | + ]); | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +/** | |
| 59 | + * Handle successful compaction state updates | |
| 60 | + */ | |
| 61 | +function handleCompactionSuccess( | |
| 62 | + result: any, | |
| 63 | + isHeadless: boolean, | |
| 64 | + callbacks?: AutoCompactionCallbacks, | |
| 65 | +) { | |
| 66 | + if (isHeadless) return; | |
| 67 | + | |
| 68 | + const successMessage = "✓ Chat history auto-compacted successfully."; | |
| 69 | + | |
| 70 | + if (callbacks?.onSystemMessage) { | |
| 71 | + callbacks.onSystemMessage(successMessage); | |
| 72 | + } else if ( | |
| 73 | + callbacks?.setMessages && | |
| 74 | + callbacks?.setChatHistory && | |
| 75 | + callbacks?.setCompactionIndex | |
| 76 | + ) { | |
| 77 | + callbacks.setChatHistory(result.compactedHistory); | |
| 78 | + callbacks.setCompactionIndex(result.compactionIndex); | |
| 79 | + callbacks.setMessages((prev) => [ | |
| 80 | + ...prev, | |
| 81 | + { | |
| 82 | + role: "system", | |
| 83 | + content: successMessage, | |
| 84 | + messageType: "system" as const, | |
| 85 | + }, | |
| 86 | + ]); | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +/** | |
| 91 | + * Handle compaction error notification | |
| 92 | + */ | |
| 93 | +function handleCompactionError( | |
| 94 | + error: any, | |
| 95 | + isHeadless: boolean, | |
| 96 | + callbacks?: AutoCompactionCallbacks, | |
| 97 | +) { | |
| 98 | + const errorMessage = `Auto-compaction error: ${formatError(error)}`; | |
| 99 | + logger.error(errorMessage); | |
| 100 | + | |
| 101 | + if (isHeadless) return; | |
| 102 | + | |
| 103 | + const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; | |
| 104 | + | |
| 105 | + if (callbacks?.onSystemMessage) { | |
| 106 | + callbacks.onSystemMessage(warningMessage); | |
| 107 | + } else if (callbacks?.setMessages) { | |
| 108 | + callbacks.setMessages((prev) => [ | |
| 109 | + ...prev, | |
| 110 | + { | |
| 111 | + role: "system", | |
| 112 | + content: warningMessage, | |
| 113 | + messageType: "system" as const, | |
| 114 | + }, | |
| 115 | + ]); | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +/** | |
| 120 | + * Unified auto-compaction handler for all modes (streaming, TUI, headless) | |
| 121 | + * @param chatHistory Current chat history | |
| 122 | + * @param model Model configuration | |
| 123 | + * @param llmApi LLM API instance | |
| 124 | + * @param options Configuration options for different usage contexts | |
| 125 | + * @returns Updated chat history and compaction index, or original if no compaction needed | |
| 126 | + */ | |
| 127 | +export async function handleAutoCompaction( | |
| 128 | + chatHistory: ChatCompletionMessageParam[], | |
| 129 | + model: ModelConfig, | |
| 130 | + llmApi: BaseLlmApi, | |
| 131 | + options: AutoCompactionOptions = {}, | |
| 132 | +): Promise<{ | |
| 133 | + chatHistory: ChatCompletionMessageParam[]; | |
| 134 | + compactionIndex: number | null; | |
| 135 | +}> { | |
| 136 | + const { isHeadless = false, callbacks } = options; | |
| 137 | + | |
| 138 | + if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 139 | + return { chatHistory, compactionIndex: null }; | |
| 140 | + } | |
| 141 | + | |
| 142 | + logger.info( | |
| 143 | + `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, | |
| 144 | + ); | |
| 145 | + | |
| 146 | + // Notify about compaction start | |
| 147 | + notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); | |
| 148 | + | |
| 149 | + try { | |
| 150 | + // Compact the history | |
| 151 | + const result = await compactChatHistory( | |
| 152 | + chatHistory, | |
| 153 | + model, | |
| 154 | + llmApi, | |
| 155 | + isHeadless | |
| 156 | + ? undefined | |
| 157 | + : { | |
| 158 | + onStreamContent: callbacks?.onContent, | |
| 159 | + onStreamComplete: () => {}, | |
| 160 | + }, | |
| 161 | + ); | |
| 162 | + | |
| 163 | + // Save the compacted session | |
| 164 | + saveSession(result.compactedHistory); | |
| 165 | + | |
| 166 | + // Handle success notification | |
| 167 | + handleCompactionSuccess(result, isHeadless, callbacks); | |
| 168 | + | |
| 169 | + return { | |
| 170 | + chatHistory: result.compactedHistory, | |
| 171 | + compactionIndex: result.compactionIndex, | |
| 172 | + }; | |
| 173 | + } catch (error: any) { | |
| 174 | + // Handle error notification | |
| 175 | + handleCompactionError(error, isHeadless, callbacks); | |
| 176 | + | |
| 177 | + // Continue without compaction on error | |
| 178 | + return { chatHistory, compactionIndex: null }; | |
| 179 | + } | |
| 180 | +} |
modified extensions/cli/src/streamChatResponse.ts +19 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | SERVICE_NAMES, |
| 16 | 16 | } from "./services/index.js"; |
| 17 | 17 | import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; |
| 18 | +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 18 | 19 | import { |
| 19 | 20 | executeStreamedToolCalls, |
| 20 | 21 | preprocessStreamedToolCalls, |
| @@ -513,6 +514,24 @@ | ||
| 513 | 514 | return finalResponse || content || fullResponse; |
| 514 | 515 | } |
| 515 | 516 | |
| 517 | + // Check for auto-compaction after tool execution | |
| 518 | + if (shouldContinue) { | |
| 519 | + const { chatHistory: updatedChatHistory, compactionIndex } = | |
| 520 | + await handleAutoCompaction(chatHistory, model, llmApi, { | |
| 521 | + isHeadless, | |
| 522 | + callbacks: { | |
| 523 | + onSystemMessage: callbacks?.onSystemMessage, | |
| 524 | + onContent: callbacks?.onContent, | |
| 525 | + }, | |
| 526 | + }); | |
| 527 | + | |
| 528 | + // Only update chat history if compaction actually occurred | |
| 529 | + if (compactionIndex !== null && updatedChatHistory !== chatHistory) { | |
| 530 | + chatHistory.length = 0; | |
| 531 | + chatHistory.push(...updatedChatHistory); | |
| 532 | + } | |
| 533 | + } | |
| 534 | + | |
| 516 | 535 | // Check if we should continue |
| 517 | 536 | if (!shouldContinue) { |
| 518 | 537 | break; |
modified extensions/cli/src/streamChatResponse.types.ts +1 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | requestId: string, |
| 16 | 16 | preview?: ToolCallPreview[], |
| 17 | 17 | ) => void; |
| 18 | + onSystemMessage?: (message: string) => void; | |
| 18 | 19 | } |
| 19 | 20 | |
| 20 | 21 | export function getDefaultCompletionOptions( |
modified extensions/cli/src/test-helpers/ui-test-context.ts +1 −1
| @@ -72,7 +72,7 @@ | ||
| 72 | 72 | responseStartTime: null, |
| 73 | 73 | inputMode: true, |
| 74 | 74 | attachedFiles: [], |
| 75 | - handleUserMessage: vi.fn(), | |
| 75 | + handleUserMessage: vi.fn().mockResolvedValue(undefined), | |
| 76 | 76 | handleInterrupt: vi.fn(), |
| 77 | 77 | handleFileAttached: vi.fn(), |
| 78 | 78 | resetChatHistory: vi.fn(), |
modified extensions/cli/src/tools/edit.ts +3 −1
| @@ -1,5 +1,7 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | |
| 3 | +import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; | |
| 4 | + | |
| 3 | 5 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 4 | 6 | import { |
| 5 | 7 | calculateLinesOfCodeDiff, |
| @@ -80,7 +82,7 @@ | ||
| 80 | 82 | new_string, |
| 81 | 83 | replace_all = false, |
| 82 | 84 | } = args as EditArgs; |
| 83 | - | |
| 85 | + throwIfFileIsSecurityConcern(file_path); | |
| 84 | 86 | // Check if file has been read |
| 85 | 87 | if (!readFilesSet.has(file_path)) { |
| 86 | 88 | throw new Error( |
modified extensions/cli/src/tools/multiEdit.ts +4 −0
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | import * as path from "path"; |
| 3 | 3 | |
| 4 | +import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; | |
| 5 | + | |
| 4 | 6 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 5 | 7 | import { |
| 6 | 8 | calculateLinesOfCodeDiff, |
| @@ -237,6 +239,8 @@ | ||
| 237 | 239 | // Validate and extract arguments |
| 238 | 240 | const { original_path, file_path, edits } = validateMultiEditArgs(args); |
| 239 | 241 | |
| 242 | + throwIfFileIsSecurityConcern(file_path); | |
| 243 | + | |
| 240 | 244 | // Validate each edit operation |
| 241 | 245 | validateEdits(edits); |
| 242 | 246 |
modified extensions/cli/src/tools/readFile.ts +10 −0
| @@ -1,5 +1,7 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | |
| 3 | +import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; | |
| 4 | + | |
| 3 | 5 | import { markFileAsRead } from "./edit.js"; |
| 4 | 6 | import { formatToolArgument } from "./formatters.js"; |
| 5 | 7 | import { Tool } from "./types.js"; |
| @@ -18,6 +20,7 @@ | ||
| 18 | 20 | readonly: true, |
| 19 | 21 | isBuiltIn: true, |
| 20 | 22 | preprocess: async (args) => { |
| 23 | + throwIfFileIsSecurityConcern(args.filepath); | |
| 21 | 24 | return { |
| 22 | 25 | args, |
| 23 | 26 | preview: [ |
| @@ -36,6 +39,13 @@ | ||
| 36 | 39 | const content = fs.readFileSync(args.filepath, "utf-8"); |
| 37 | 40 | // Mark this file as read for the edit tool |
| 38 | 41 | markFileAsRead(args.filepath); |
| 42 | + | |
| 43 | + const lines = content.split("\n"); | |
| 44 | + if (lines.length > 5000) { | |
| 45 | + const truncatedContent = lines.slice(0, 5000).join("\n"); | |
| 46 | + return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`; | |
| 47 | + } | |
| 48 | + | |
| 39 | 49 | return `Content of ${args.filepath}:\n${content}`; |
| 40 | 50 | } catch (error) { |
| 41 | 51 | return `Error reading file: ${ |
modified extensions/cli/src/ui/FreeTrialTransitionUI.tsx +2 −2
| @@ -9,8 +9,8 @@ | ||
| 9 | 9 | import { listUserOrganizations } from "../auth/workos.js"; |
| 10 | 10 | import { env } from "../env.js"; |
| 11 | 11 | import { |
| 12 | - isValidAnthropicApiKey, | |
| 13 | 12 | getApiKeyValidationError, |
| 13 | + isValidAnthropicApiKey, | |
| 14 | 14 | } from "../util/apiKeyValidation.js"; |
| 15 | 15 | import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; |
| 16 | 16 | |
| @@ -270,7 +270,7 @@ | ||
| 270 | 270 | <Text></Text> |
| 271 | 271 | {errorMessage && <Text color="red">{errorMessage}</Text>} |
| 272 | 272 | <Text color="gray"> |
| 273 | - Type your API key and press Enter (must start with 'TEST-ant-') | |
| 273 | + Type your API key and press Enter (must start with 'sk-ant-') | |
| 274 | 274 | </Text> |
| 275 | 275 | </Box> |
| 276 | 276 | ); |
modified extensions/cli/src/ui/IntroMessage.tsx +3 −1
| @@ -85,7 +85,9 @@ | ||
| 85 | 85 | {/* Rules */} |
| 86 | 86 | {allRules.length > 0 && ( |
| 87 | 87 | <> |
| 88 | - <Text color="blue">Rules:</Text> | |
| 88 | + <Text bold color="blue"> | |
| 89 | + Rules: | |
| 90 | + </Text> | |
| 89 | 91 | {allRules.map((rule, index) => ( |
| 90 | 92 | <Text key={index}> |
| 91 | 93 | - <Text color="white">{rule}</Text> |
modified extensions/cli/src/ui/UserInput.tsx +11 −0
| @@ -152,6 +152,17 @@ | ||
| 152 | 152 | } |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | + // Check if there are any matching commands | |
| 156 | + const filteredCommands = allCommands.filter((cmd) => | |
| 157 | + cmd.name.toLowerCase().includes(afterSlash.toLowerCase()), | |
| 158 | + ); | |
| 159 | + | |
| 160 | + // If no commands match, hide the dropdown to allow normal Enter behavior | |
| 161 | + if (filteredCommands.length === 0) { | |
| 162 | + setShowSlashCommands(false); | |
| 163 | + return; | |
| 164 | + } | |
| 165 | + | |
| 155 | 166 | // Show selector for partial matches |
| 156 | 167 | setShowSlashCommands(true); |
| 157 | 168 | setSlashCommandFilter(afterSlash); |
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +5 −2
| @@ -20,7 +20,10 @@ | ||
| 20 | 20 | case "tool-start": |
| 21 | 21 | return ( |
| 22 | 22 | <Box key={index} marginLeft={1} marginBottom={1}> |
| 23 | - <Text color="white">○ {message.content}</Text> | |
| 23 | + {/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */} | |
| 24 | + <Text color="green"> | |
| 25 | + ●<Text color="white"> {message.content}</Text> | |
| 26 | + </Text> | |
| 24 | 27 | </Box> |
| 25 | 28 | ); |
| 26 | 29 | |
| @@ -87,7 +90,7 @@ | ||
| 87 | 90 | |
| 88 | 91 | return ( |
| 89 | 92 | <Box key={index} marginLeft={1} marginBottom={1}> |
| 90 | - <Text color={isUser ? "green" : "magenta"}>●</Text> | |
| 93 | + <Text color={isUser ? "green" : "white"}>●</Text> | |
| 91 | 94 | <Text> </Text> |
| 92 | 95 | {isUser ? ( |
| 93 | 96 | <Text color="gray">{message.content}</Text> |
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +17 −66
| @@ -7,7 +7,6 @@ | ||
| 7 | 7 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 8 | 8 | import { formatError } from "../../util/formatError.js"; |
| 9 | 9 | import { logger } from "../../util/logger.js"; |
| 10 | -import { shouldAutoCompact } from "../../util/tokenizer.js"; | |
| 11 | 10 | import { DisplayMessage } from "../types.js"; |
| 12 | 11 | |
| 13 | 12 | import { SlashCommandResult } from "./useChat.types.js"; |
| @@ -278,13 +277,13 @@ | ||
| 278 | 277 | } |
| 279 | 278 | |
| 280 | 279 | /** |
| 281 | - * Handle auto-compaction when approaching context limit | |
| 280 | + * Handle auto-compaction when approaching context limit - TUI wrapper | |
| 282 | 281 | */ |
| 283 | 282 | export async function handleAutoCompaction({ |
| 284 | 283 | chatHistory, |
| 285 | 284 | model, |
| 286 | 285 | llmApi, |
| 287 | - compactionIndex, | |
| 286 | + compactionIndex: _compactionIndex, | |
| 288 | 287 | setMessages, |
| 289 | 288 | setChatHistory, |
| 290 | 289 | setCompactionIndex, |
| @@ -292,69 +291,21 @@ | ||
| 292 | 291 | currentChatHistory: ChatCompletionMessageParam[]; |
| 293 | 292 | currentCompactionIndex: number | null; |
| 294 | 293 | }> { |
| 295 | - if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 296 | - return { | |
| 297 | - currentChatHistory: chatHistory, | |
| 298 | - currentCompactionIndex: compactionIndex, | |
| 299 | - }; | |
| 300 | - } | |
| 301 | - | |
| 302 | - logger.info("Auto-compacting triggered in TUI mode"); | |
| 303 | - | |
| 304 | - setMessages((prev) => [ | |
| 305 | - ...prev, | |
| 306 | - { | |
| 307 | - role: "system", | |
| 308 | - content: "Approaching context limit. Auto-compacting chat history...", | |
| 309 | - messageType: "system" as const, | |
| 294 | + const { handleAutoCompaction: coreAutoCompaction } = await import( | |
| 295 | + "../../streamChatResponse.autoCompaction.js" | |
| 296 | + ); | |
| 297 | + | |
| 298 | + const result = await coreAutoCompaction(chatHistory, model, llmApi, { | |
| 299 | + isHeadless: false, | |
| 300 | + callbacks: { | |
| 301 | + setMessages, | |
| 302 | + setChatHistory, | |
| 303 | + setCompactionIndex, | |
| 310 | 304 | }, |
| 311 | - ]); | |
| 312 | - | |
| 313 | - try { | |
| 314 | - if (!llmApi) { | |
| 315 | - throw new Error("LLM API is not available for auto-compaction"); | |
| 316 | - } | |
| 317 | - | |
| 318 | - // Compact the history WITHOUT the current user message | |
| 319 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 320 | - | |
| 321 | - // Update state | |
| 322 | - setChatHistory(result.compactedHistory); | |
| 323 | - setCompactionIndex(result.compactionIndex); | |
| 324 | - | |
| 325 | - // Save the compacted session | |
| 326 | - saveSession(result.compactedHistory); | |
| 327 | - | |
| 328 | - setMessages((prev) => [ | |
| 329 | - ...prev, | |
| 330 | - { | |
| 331 | - role: "system", | |
| 332 | - content: "✓ Chat history auto-compacted successfully.", | |
| 333 | - messageType: "system" as const, | |
| 334 | - }, | |
| 335 | - ]); | |
| 336 | - | |
| 337 | - return { | |
| 338 | - currentChatHistory: result.compactedHistory, | |
| 339 | - currentCompactionIndex: result.compactionIndex, | |
| 340 | - }; | |
| 341 | - } catch (error: any) { | |
| 342 | - const errorMessage = `Auto-compaction error: ${formatError(error)}`; | |
| 343 | - logger.error(errorMessage); | |
| 344 | - | |
| 345 | - setMessages((prev) => [ | |
| 346 | - ...prev, | |
| 347 | - { | |
| 348 | - role: "system", | |
| 349 | - content: `Warning: ${errorMessage}. Continuing without compaction...`, | |
| 350 | - messageType: "system" as const, | |
| 351 | - }, | |
| 352 | - ]); | |
| 305 | + }); | |
| 353 | 306 | |
| 354 | - // Continue without compaction on error | |
| 355 | - return { | |
| 356 | - currentChatHistory: chatHistory, | |
| 357 | - currentCompactionIndex: compactionIndex, | |
| 358 | - }; | |
| 359 | - } | |
| 307 | + return { | |
| 308 | + currentChatHistory: result.chatHistory, | |
| 309 | + currentCompactionIndex: result.compactionIndex, | |
| 310 | + }; | |
| 360 | 311 | } |
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +10 −0
| @@ -111,6 +111,16 @@ | ||
| 111 | 111 | toolCallPreview, |
| 112 | 112 | }); |
| 113 | 113 | }, |
| 114 | + onSystemMessage: (message: string) => { | |
| 115 | + setMessages((prev) => [ | |
| 116 | + ...prev, | |
| 117 | + { | |
| 118 | + role: "system", | |
| 119 | + content: message, | |
| 120 | + messageType: "system" as const, | |
| 121 | + }, | |
| 122 | + ]); | |
| 123 | + }, | |
| 114 | 124 | }; |
| 115 | 125 | } |
| 116 | 126 |
modified extensions/cli/src/util/apiKeyValidation.test.ts +10 −10
| @@ -1,21 +1,21 @@ | ||
| 1 | 1 | import { |
| 2 | - isValidAnthropicApiKey, | |
| 3 | 2 | getApiKeyValidationError, |
| 3 | + isValidAnthropicApiKey, | |
| 4 | 4 | } from "./apiKeyValidation.js"; |
| 5 | 5 | |
| 6 | 6 | describe("isValidAnthropicApiKey", () => { |
| 7 | 7 | it("should return true for valid API keys", () => { |
| 8 | - expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true); | |
| 9 | - expect(isValidAnthropicApiKey("TEST-ant-abcdefghijklmnop")).toBe(true); | |
| 10 | - expect(isValidAnthropicApiKey("TEST-ant-test-key-with-dashes")).toBe(true); | |
| 8 | + expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true); | |
| 9 | + expect(isValidAnthropicApiKey("sk-ant-abcdefghijklmnop")).toBe(true); | |
| 10 | + expect(isValidAnthropicApiKey("sk-ant-test-key-with-dashes")).toBe(true); | |
| 11 | 11 | expect( |
| 12 | - isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"), | |
| 12 | + isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"), | |
| 13 | 13 | ).toBe(true); |
| 14 | 14 | }); |
| 15 | 15 | |
| 16 | 16 | it("should return false for invalid API keys", () => { |
| 17 | 17 | expect(isValidAnthropicApiKey("")).toBe(false); |
| 18 | - expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false); | |
| 18 | + expect(isValidAnthropicApiKey("sk-ant-")).toBe(false); | |
| 19 | 19 | expect(isValidAnthropicApiKey("TEST-")).toBe(false); |
| 20 | 20 | expect(isValidAnthropicApiKey("TEST-openai-1234567890")).toBe(false); |
| 21 | 21 | expect(isValidAnthropicApiKey("invalid-key")).toBe(false); |
| @@ -40,14 +40,14 @@ | ||
| 40 | 40 | expect(getApiKeyValidationError(null)).toBe("API key is required"); |
| 41 | 41 | expect(getApiKeyValidationError(undefined)).toBe("API key is required"); |
| 42 | 42 | expect(getApiKeyValidationError("TEST-")).toBe( |
| 43 | - 'API key must start with "TEST-ant-"', | |
| 43 | + 'API key must start with "sk-ant-"', | |
| 44 | 44 | ); |
| 45 | 45 | expect(getApiKeyValidationError("TEST-openai-1234")).toBe( |
| 46 | - 'API key must start with "TEST-ant-"', | |
| 46 | + 'API key must start with "sk-ant-"', | |
| 47 | 47 | ); |
| 48 | - expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short"); | |
| 48 | + expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short"); | |
| 49 | 49 | expect(getApiKeyValidationError("invalid")).toBe( |
| 50 | - 'API key must start with "TEST-ant-"', | |
| 50 | + 'API key must start with "sk-ant-"', | |
| 51 | 51 | ); |
| 52 | 52 | }); |
| 53 | 53 | }); |
modified extensions/cli/src/util/apiKeyValidation.ts +5 −5
| @@ -10,8 +10,8 @@ | ||
| 10 | 10 | return false; |
| 11 | 11 | } |
| 12 | 12 | |
| 13 | - // Anthropic API keys must start with "TEST-ant-" and have additional characters | |
| 14 | - return apiKey.startsWith("TEST-ant-") && apiKey.length > "TEST-ant-".length; | |
| 13 | + // Anthropic API keys must start with "sk-ant-" and have additional characters | |
| 14 | + return apiKey.startsWith("sk-ant-") && apiKey.length > "sk-ant-".length; | |
| 15 | 15 | } |
| 16 | 16 | |
| 17 | 17 | /** |
| @@ -26,11 +26,11 @@ | ||
| 26 | 26 | return "API key is required"; |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | - if (!apiKey.startsWith("TEST-ant-")) { | |
| 30 | - return 'API key must start with "TEST-ant-"'; | |
| 29 | + if (!apiKey.startsWith("sk-ant-")) { | |
| 30 | + return 'API key must start with "sk-ant-"'; | |
| 31 | 31 | } |
| 32 | 32 | |
| 33 | - if (apiKey.length <= "TEST-ant-".length) { | |
| 33 | + if (apiKey.length <= "sk-ant-".length) { | |
| 34 | 34 | return "API key is too short"; |
| 35 | 35 | } |
| 36 | 36 |
deleted extensions/cli/src/util/consoleOverride.ts +0 −115
| @@ -1,115 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Console override utility to prevent unwanted output in headless mode | |
| 3 | - * This ensures that only intentional stdout output reaches the user | |
| 4 | - */ | |
| 5 | - | |
| 6 | -interface ConsoleBackup { | |
| 7 | - log: typeof console.log; | |
| 8 | - info: typeof console.info; | |
| 9 | - warn: typeof console.warn; | |
| 10 | - error: typeof console.error; | |
| 11 | - debug: typeof console.debug; | |
| 12 | -} | |
| 13 | - | |
| 14 | -let originalConsole: ConsoleBackup | null = null; | |
| 15 | -let isHeadlessMode = false; | |
| 16 | - | |
| 17 | -/** | |
| 18 | - * Override console methods to prevent unwanted output in headless mode | |
| 19 | - * In headless mode, only console.error and explicitly allowed outputs should reach stdout | |
| 20 | - */ | |
| 21 | -export function configureConsoleForHeadless(headless: boolean): void { | |
| 22 | - isHeadlessMode = headless; | |
| 23 | - | |
| 24 | - if (headless && !originalConsole) { | |
| 25 | - // Backup original console methods | |
| 26 | - originalConsole = { | |
| 27 | - log: console.log, | |
| 28 | - info: console.info, | |
| 29 | - warn: console.warn, | |
| 30 | - error: console.error, | |
| 31 | - debug: console.debug, | |
| 32 | - }; | |
| 33 | - | |
| 34 | - // Override console methods to suppress output in headless mode | |
| 35 | - console.log = () => {}; // Suppress all console.log | |
| 36 | - console.info = () => {}; // Suppress all console.info | |
| 37 | - console.warn = () => {}; // Suppress all console.warn | |
| 38 | - console.debug = () => {}; // Suppress all console.debug | |
| 39 | - | |
| 40 | - // Keep console.error for genuine errors, but send to stderr | |
| 41 | - console.error = (...args: any[]) => { | |
| 42 | - originalConsole!.error(...args); | |
| 43 | - }; | |
| 44 | - } else if (!headless && originalConsole) { | |
| 45 | - // Restore original console methods | |
| 46 | - console.log = originalConsole.log; | |
| 47 | - console.info = originalConsole.info; | |
| 48 | - console.warn = originalConsole.warn; | |
| 49 | - console.error = originalConsole.error; | |
| 50 | - console.debug = originalConsole.debug; | |
| 51 | - | |
| 52 | - originalConsole = null; | |
| 53 | - } | |
| 54 | -} | |
| 55 | - | |
| 56 | -/** | |
| 57 | - * Safe stdout output that bypasses console overrides | |
| 58 | - * Use this for intentional output in headless mode | |
| 59 | - */ | |
| 60 | -export function safeStdout(message: string): void { | |
| 61 | - process.stdout.write(message); | |
| 62 | -} | |
| 63 | - | |
| 64 | -/** | |
| 65 | - * Safe stderr output that bypasses console overrides | |
| 66 | - * Use this for error messages that should always be visible | |
| 67 | - */ | |
| 68 | -export function safeStderr(message: string): void { | |
| 69 | - process.stderr.write(message); | |
| 70 | -} | |
| 71 | - | |
| 72 | -/** | |
| 73 | - * Temporarily restore console for a specific operation | |
| 74 | - * Useful for debugging or when you need original console behavior | |
| 75 | - */ | |
| 76 | -export function withOriginalConsole<T>(fn: () => T): T { | |
| 77 | - if (!originalConsole || !isHeadlessMode) { | |
| 78 | - return fn(); | |
| 79 | - } | |
| 80 | - | |
| 81 | - // Temporarily restore | |
| 82 | - const tempConsole = { ...console }; | |
| 83 | - Object.assign(console, originalConsole); | |
| 84 | - | |
| 85 | - try { | |
| 86 | - return fn(); | |
| 87 | - } finally { | |
| 88 | - // Restore overrides | |
| 89 | - Object.assign(console, tempConsole); | |
| 90 | - } | |
| 91 | -} | |
| 92 | - | |
| 93 | -/** | |
| 94 | - * Check if currently in headless mode | |
| 95 | - */ | |
| 96 | -export function isInHeadlessMode(): boolean { | |
| 97 | - return isHeadlessMode; | |
| 98 | -} | |
| 99 | - | |
| 100 | -/** | |
| 101 | - * Reset console overrides to original state | |
| 102 | - * Useful for testing to ensure clean state | |
| 103 | - */ | |
| 104 | -export function resetConsoleOverrides(): void { | |
| 105 | - if (originalConsole) { | |
| 106 | - console.log = originalConsole.log; | |
| 107 | - console.info = originalConsole.info; | |
| 108 | - console.warn = originalConsole.warn; | |
| 109 | - console.error = originalConsole.error; | |
| 110 | - console.debug = originalConsole.debug; | |
| 111 | - | |
| 112 | - originalConsole = null; | |
| 113 | - } | |
| 114 | - isHeadlessMode = false; | |
| 115 | -} |
added extensions/cli/src/util/tokenizer.test.ts +292 −0
| @@ -0,0 +1,292 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 3 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 4 | + | |
| 5 | +import { logger } from "./logger.js"; | |
| 6 | +import { | |
| 7 | + AUTO_COMPACT_THRESHOLD, | |
| 8 | + calculateContextUsagePercentage, | |
| 9 | + countChatHistoryTokens, | |
| 10 | + countMessageTokens, | |
| 11 | + getModelContextLimit, | |
| 12 | + shouldAutoCompact, | |
| 13 | +} from "./tokenizer.js"; | |
| 14 | + | |
| 15 | +// Mock the logger | |
| 16 | +vi.mock("./logger.js", () => ({ | |
| 17 | + logger: { | |
| 18 | + debug: vi.fn(), | |
| 19 | + warn: vi.fn(), | |
| 20 | + error: vi.fn(), | |
| 21 | + }, | |
| 22 | +})); | |
| 23 | + | |
| 24 | +// Mock gpt-tokenizer | |
| 25 | +vi.mock("gpt-tokenizer", () => ({ | |
| 26 | + encode: (text: string) => new Array(Math.ceil(text.length / 4)), // Rough 4 chars per token | |
| 27 | +})); | |
| 28 | + | |
| 29 | +describe("tokenizer", () => { | |
| 30 | + beforeEach(() => { | |
| 31 | + vi.clearAllMocks(); | |
| 32 | + }); | |
| 33 | + | |
| 34 | + describe("getModelContextLimit", () => { | |
| 35 | + it("should return contextLength from model config", () => { | |
| 36 | + const model: ModelConfig = { | |
| 37 | + name: "test-model", | |
| 38 | + model: "test", | |
| 39 | + provider: "openai", | |
| 40 | + defaultCompletionOptions: { | |
| 41 | + contextLength: 8192, | |
| 42 | + }, | |
| 43 | + }; | |
| 44 | + | |
| 45 | + expect(getModelContextLimit(model)).toBe(8192); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("should return default when no contextLength specified", () => { | |
| 49 | + const model: ModelConfig = { | |
| 50 | + name: "test-model", | |
| 51 | + model: "test", | |
| 52 | + provider: "openai", | |
| 53 | + }; | |
| 54 | + | |
| 55 | + expect(getModelContextLimit(model)).toBe(200_000); | |
| 56 | + }); | |
| 57 | + }); | |
| 58 | + | |
| 59 | + describe("countMessageTokens", () => { | |
| 60 | + it("should count tokens for string content", () => { | |
| 61 | + const message: ChatCompletionMessageParam = { | |
| 62 | + role: "user", | |
| 63 | + content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5 | |
| 64 | + }; | |
| 65 | + | |
| 66 | + const tokenCount = countMessageTokens(message); | |
| 67 | + expect(tokenCount).toBeGreaterThan(0); | |
| 68 | + expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("should count tokens for array content", () => { | |
| 72 | + const message: ChatCompletionMessageParam = { | |
| 73 | + role: "user", | |
| 74 | + content: [ | |
| 75 | + { type: "text", text: "Hello" }, // 5 chars -> ~2 tokens | |
| 76 | + { type: "image_url", image_url: { url: "test.jpg" } }, // +85 tokens | |
| 77 | + ], | |
| 78 | + }; | |
| 79 | + | |
| 80 | + const tokenCount = countMessageTokens(message); | |
| 81 | + expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should count tokens for tool calls", () => { | |
| 85 | + const message: ChatCompletionMessageParam = { | |
| 86 | + role: "assistant", | |
| 87 | + content: "I'll help you", | |
| 88 | + tool_calls: [ | |
| 89 | + { | |
| 90 | + id: "call_1", | |
| 91 | + type: "function", | |
| 92 | + function: { | |
| 93 | + name: "test_function", // ~3 tokens + 10 overhead | |
| 94 | + arguments: '{"param": "value"}', // ~5 tokens | |
| 95 | + }, | |
| 96 | + }, | |
| 97 | + ], | |
| 98 | + }; | |
| 99 | + | |
| 100 | + const tokenCount = countMessageTokens(message); | |
| 101 | + expect(tokenCount).toBeGreaterThan(20); | |
| 102 | + }); | |
| 103 | + | |
| 104 | + it("should handle errors gracefully", () => { | |
| 105 | + // We'll skip this test for now since mocking gpt-tokenizer is complex | |
| 106 | + // The error handling is tested implicitly by the fallback behavior | |
| 107 | + expect(true).toBe(true); | |
| 108 | + }); | |
| 109 | + }); | |
| 110 | + | |
| 111 | + describe("countChatHistoryTokens", () => { | |
| 112 | + it("should count tokens for multiple messages", () => { | |
| 113 | + const chatHistory: ChatCompletionMessageParam[] = [ | |
| 114 | + { role: "system", content: "You are helpful" }, | |
| 115 | + { role: "user", content: "Hello" }, | |
| 116 | + { role: "assistant", content: "Hi there" }, | |
| 117 | + ]; | |
| 118 | + | |
| 119 | + const tokenCount = countChatHistoryTokens(chatHistory); | |
| 120 | + expect(tokenCount).toBeGreaterThan(0); | |
| 121 | + // Should include message overhead (3 * 3 = 9 tokens) | |
| 122 | + expect(tokenCount).toBeGreaterThan(9); | |
| 123 | + }); | |
| 124 | + | |
| 125 | + it("should handle empty chat history", () => { | |
| 126 | + const tokenCount = countChatHistoryTokens([]); | |
| 127 | + expect(tokenCount).toBe(0); | |
| 128 | + }); | |
| 129 | + }); | |
| 130 | + | |
| 131 | + describe("calculateContextUsagePercentage", () => { | |
| 132 | + it("should calculate percentage correctly", () => { | |
| 133 | + const model: ModelConfig = { | |
| 134 | + name: "test-model", | |
| 135 | + model: "test", | |
| 136 | + provider: "openai", | |
| 137 | + defaultCompletionOptions: { | |
| 138 | + contextLength: 1000, | |
| 139 | + }, | |
| 140 | + }; | |
| 141 | + | |
| 142 | + expect(calculateContextUsagePercentage(800, model)).toBe(80); | |
| 143 | + expect(calculateContextUsagePercentage(500, model)).toBe(50); | |
| 144 | + expect(calculateContextUsagePercentage(1200, model)).toBe(100); // Capped at 100% | |
| 145 | + }); | |
| 146 | + }); | |
| 147 | + | |
| 148 | + describe("shouldAutoCompact", () => { | |
| 149 | + const createModel = ( | |
| 150 | + contextLength: number, | |
| 151 | + maxTokens?: number, | |
| 152 | + ): ModelConfig => ({ | |
| 153 | + name: "test-model", | |
| 154 | + model: "test", | |
| 155 | + provider: "openai", | |
| 156 | + defaultCompletionOptions: { | |
| 157 | + contextLength, | |
| 158 | + maxTokens, | |
| 159 | + }, | |
| 160 | + }); | |
| 161 | + | |
| 162 | + const createChatHistory = ( | |
| 163 | + tokenCount: number, | |
| 164 | + ): ChatCompletionMessageParam[] => { | |
| 165 | + // Create a message that will result in approximately the desired token count | |
| 166 | + const content = "x".repeat(tokenCount * 4); // 4 chars per token | |
| 167 | + return [{ role: "user", content }]; | |
| 168 | + }; | |
| 169 | + | |
| 170 | + it("should compact when input tokens exceed threshold with maxTokens", () => { | |
| 171 | + const model = createModel(1000, 200); // 1000 context, 200 max output | |
| 172 | + // Available for input: 1000 - 200 = 800 | |
| 173 | + // Threshold: 800 * 0.8 = 640 | |
| 174 | + const chatHistory = createChatHistory(650); // Above threshold | |
| 175 | + | |
| 176 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 177 | + }); | |
| 178 | + | |
| 179 | + it("should not compact when input tokens are below threshold with maxTokens", () => { | |
| 180 | + const model = createModel(1000, 200); // 1000 context, 200 max output | |
| 181 | + // Available for input: 1000 - 200 = 800 | |
| 182 | + // Threshold: 800 * 0.8 = 640 | |
| 183 | + const chatHistory = createChatHistory(600); // Below threshold | |
| 184 | + | |
| 185 | + expect(shouldAutoCompact(chatHistory, model)).toBe(false); | |
| 186 | + }); | |
| 187 | + | |
| 188 | + it("should use 35% default reservation when maxTokens is not set", () => { | |
| 189 | + const model = createModel(1000); // No maxTokens | |
| 190 | + // Reserved: 1000 * 0.35 = 350 | |
| 191 | + // Available for input: 1000 - 350 = 650 | |
| 192 | + // Threshold: 650 * 0.8 = 520 | |
| 193 | + const chatHistory = createChatHistory(530); // Above threshold | |
| 194 | + | |
| 195 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + it("should not compact when below default threshold without maxTokens", () => { | |
| 199 | + const model = createModel(1000); // No maxTokens | |
| 200 | + // Available for input: 1000 - 350 = 650 | |
| 201 | + // Threshold: 650 * 0.8 = 520 | |
| 202 | + const chatHistory = createChatHistory(500); // Below threshold | |
| 203 | + | |
| 204 | + expect(shouldAutoCompact(chatHistory, model)).toBe(false); | |
| 205 | + }); | |
| 206 | + | |
| 207 | + it("should throw error when maxTokens >= contextLength", () => { | |
| 208 | + const model = createModel(1000, 1000); // maxTokens equals contextLength | |
| 209 | + const chatHistory = createChatHistory(1); // Minimal input | |
| 210 | + | |
| 211 | + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( | |
| 212 | + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", | |
| 213 | + ); | |
| 214 | + }); | |
| 215 | + | |
| 216 | + it("should throw error when maxTokens > contextLength", () => { | |
| 217 | + const model = createModel(1000, 1200); // maxTokens exceeds contextLength | |
| 218 | + const chatHistory = createChatHistory(1); // Minimal input | |
| 219 | + | |
| 220 | + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( | |
| 221 | + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", | |
| 222 | + ); | |
| 223 | + }); | |
| 224 | + | |
| 225 | + it("should handle edge case with very small context limit", () => { | |
| 226 | + const model = createModel(100, 50); // Small context | |
| 227 | + // Available: 100 - 50 = 50 | |
| 228 | + // Threshold: 50 * 0.8 = 40 | |
| 229 | + const chatHistory = createChatHistory(45); // Above threshold | |
| 230 | + | |
| 231 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 232 | + }); | |
| 233 | + | |
| 234 | + it("should log debug information correctly", () => { | |
| 235 | + const model = createModel(1000, 200); | |
| 236 | + const chatHistory = createChatHistory(600); | |
| 237 | + | |
| 238 | + shouldAutoCompact(chatHistory, model); | |
| 239 | + | |
| 240 | + expect(logger.debug).toHaveBeenCalledWith("Context usage check", { | |
| 241 | + inputTokens: expect.any(Number), | |
| 242 | + contextLimit: 1000, | |
| 243 | + maxTokens: 200, | |
| 244 | + reservedForOutput: 200, | |
| 245 | + availableForInput: 800, | |
| 246 | + usage: expect.any(String), | |
| 247 | + threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, | |
| 248 | + shouldCompact: expect.any(Boolean), | |
| 249 | + }); | |
| 250 | + }); | |
| 251 | + | |
| 252 | + it("should handle model with zero maxTokens correctly", () => { | |
| 253 | + const model = createModel(1000, 0); // Explicit zero | |
| 254 | + // Should use default 35% reservation: 1000 * 0.35 = 350 | |
| 255 | + const chatHistory = createChatHistory(530); // Above threshold | |
| 256 | + | |
| 257 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 258 | + }); | |
| 259 | + | |
| 260 | + describe("real-world scenarios", () => { | |
| 261 | + it("should prevent Claude 3.5 Sonnet context overflow", () => { | |
| 262 | + // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens | |
| 263 | + const model = createModel(200_000, 4_000); | |
| 264 | + // Available: 200k - 4k = 196k | |
| 265 | + // Threshold: 196k * 0.8 = 156.8k | |
| 266 | + const chatHistory = createChatHistory(160_000); // Above threshold | |
| 267 | + | |
| 268 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 269 | + }); | |
| 270 | + | |
| 271 | + it("should prevent GPT-4 context overflow", () => { | |
| 272 | + // GPT-4: 128k context, often uses 4k max_tokens | |
| 273 | + const model = createModel(128_000, 4_000); | |
| 274 | + // Available: 128k - 4k = 124k | |
| 275 | + // Threshold: 124k * 0.8 = 99.2k | |
| 276 | + const chatHistory = createChatHistory(100_000); // Above threshold | |
| 277 | + | |
| 278 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 279 | + }); | |
| 280 | + | |
| 281 | + it("should handle models with very high max_tokens", () => { | |
| 282 | + // Some models allow very high max_tokens (e.g., 64k like in the error message) | |
| 283 | + const model = createModel(200_000, 64_000); | |
| 284 | + // Available: 200k - 64k = 136k | |
| 285 | + // Threshold: 136k * 0.8 = 108.8k | |
| 286 | + const chatHistory = createChatHistory(110_000); // Above threshold | |
| 287 | + | |
| 288 | + expect(shouldAutoCompact(chatHistory, model)).toBe(true); | |
| 289 | + }); | |
| 290 | + }); | |
| 291 | + }); | |
| 292 | +}); |
modified extensions/cli/src/util/tokenizer.ts +35 −6
| @@ -117,20 +117,39 @@ | ||
| 117 | 117 | /** |
| 118 | 118 | * Check if the chat history exceeds the auto-compact threshold |
| 119 | 119 | * @param chatHistory The chat history to check |
| 120 | - * @param modelName The model name | |
| 120 | + * @param model The model configuration | |
| 121 | 121 | * @returns Whether auto-compacting should be triggered |
| 122 | 122 | */ |
| 123 | 123 | export function shouldAutoCompact( |
| 124 | 124 | chatHistory: ChatCompletionMessageParam[], |
| 125 | 125 | model: ModelConfig, |
| 126 | 126 | ): boolean { |
| 127 | - const tokenCount = countChatHistoryTokens(chatHistory); | |
| 128 | - const limit = getModelContextLimit(model); | |
| 129 | - const usage = tokenCount / limit; | |
| 127 | + const inputTokens = countChatHistoryTokens(chatHistory); | |
| 128 | + const contextLimit = getModelContextLimit(model); | |
| 129 | + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; | |
| 130 | + | |
| 131 | + // Calculate available space considering max_tokens reservation | |
| 132 | + // If maxTokens is not set, reserve 35% of context for output as a safe default | |
| 133 | + // (64k/200k with claude = 32%, round up to give a buffer) | |
| 134 | + const reservedForOutput = | |
| 135 | + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); | |
| 136 | + const availableForInput = contextLimit - reservedForOutput; | |
| 137 | + | |
| 138 | + // Ensure we have positive space available for input | |
| 139 | + if (availableForInput <= 0) { | |
| 140 | + throw new Error( | |
| 141 | + `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, | |
| 142 | + ); | |
| 143 | + } | |
| 144 | + | |
| 145 | + const usage = inputTokens / availableForInput; | |
| 130 | 146 | |
| 131 | 147 | logger.debug("Context usage check", { |
| 132 | - tokenCount, | |
| 133 | - limit, | |
| 148 | + inputTokens, | |
| 149 | + contextLimit, | |
| 150 | + maxTokens, | |
| 151 | + reservedForOutput, | |
| 152 | + availableForInput, | |
| 134 | 153 | usage: `${Math.round(usage * 100)}%`, |
| 135 | 154 | threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, |
| 136 | 155 | shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, |
| @@ -138,3 +157,13 @@ | ||
| 138 | 157 | |
| 139 | 158 | return usage >= AUTO_COMPACT_THRESHOLD; |
| 140 | 159 | } |
| 160 | + | |
| 161 | +/** | |
| 162 | + * Get a descriptive message for auto-compaction that shows the context limit | |
| 163 | + * @param model The model configuration | |
| 164 | + * @returns A descriptive message explaining why compaction is needed | |
| 165 | + */ | |
| 166 | +export function getAutoCompactMessage(model: ModelConfig): string { | |
| 167 | + const limit = getModelContextLimit(model); | |
| 168 | + return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; | |
| 169 | +} |
modified extensions/cli/src/util/yamlConfigUpdater.test.ts +13 −13
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | import { updateAnthropicModelInYaml } from "./yamlConfigUpdater.js"; |
| 4 | 4 | |
| 5 | 5 | describe("updateAnthropicModelInYaml", () => { |
| 6 | - const testApiKey = "TEST-ant-test123456789"; | |
| 6 | + const testApiKey = "sk-ant-test123456789"; | |
| 7 | 7 | |
| 8 | 8 | describe("empty or invalid input", () => { |
| 9 | 9 | it("should create new config from empty string", () => { |
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | expect(result).toContain("version: 1.0.0"); |
| 14 | 14 | expect(result).toContain("schema: v1"); |
| 15 | 15 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 16 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 16 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 17 | 17 | }); |
| 18 | 18 | |
| 19 | 19 | it("should create new config from invalid YAML", () => { |
| @@ -22,7 +22,7 @@ | ||
| 22 | 22 | |
| 23 | 23 | expect(result).toContain("name: Local Config"); |
| 24 | 24 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 25 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 25 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 26 | 26 | }); |
| 27 | 27 | }); |
| 28 | 28 | |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | expect(result).toContain("# List of available models"); |
| 46 | 46 | expect(result).toContain("uses: openai/gpt-4"); |
| 47 | 47 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 48 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 48 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 49 | 49 | }); |
| 50 | 50 | |
| 51 | 51 | it("should preserve comments when updating existing model", () => { |
| @@ -65,7 +65,7 @@ | ||
| 65 | 65 | expect(result).toContain("# My Continue config"); |
| 66 | 66 | expect(result).toContain("# List of available models"); |
| 67 | 67 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 68 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 68 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 69 | 69 | expect(result).not.toContain("old-key"); |
| 70 | 70 | }); |
| 71 | 71 | }); |
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | |
| 86 | 86 | expect(result).toContain("uses: openai/gpt-4"); |
| 87 | 87 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 88 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 88 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 89 | 89 | expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); |
| 90 | 90 | }); |
| 91 | 91 | |
| @@ -106,7 +106,7 @@ | ||
| 106 | 106 | |
| 107 | 107 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 108 | 108 | expect(result).toContain("uses: openai/gpt-4"); |
| 109 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 109 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 110 | 110 | expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); |
| 111 | 111 | expect(result).not.toContain("old-anthropic-key"); |
| 112 | 112 | |
| @@ -131,7 +131,7 @@ | ||
| 131 | 131 | expect(result).toContain("name: Local Config"); |
| 132 | 132 | expect(result).toContain("models:"); |
| 133 | 133 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 134 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 134 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 135 | 135 | }); |
| 136 | 136 | |
| 137 | 137 | it("should handle config with empty models array", () => { |
| @@ -148,7 +148,7 @@ | ||
| 148 | 148 | |
| 149 | 149 | expect(result).toContain("name: Local Config"); |
| 150 | 150 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 151 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 151 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 152 | 152 | }); |
| 153 | 153 | }); |
| 154 | 154 | |
| @@ -190,14 +190,14 @@ | ||
| 190 | 190 | const result = updateAnthropicModelInYaml(malformedConfig, testApiKey); |
| 191 | 191 | |
| 192 | 192 | expect(result).toContain("uses: anthropic/claude-4-sonnet"); |
| 193 | - expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789"); | |
| 193 | + expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); | |
| 194 | 194 | }); |
| 195 | 195 | |
| 196 | 196 | it("should handle different API key formats", () => { |
| 197 | 197 | const differentKeys = [ |
| 198 | - "TEST-ant-1234567890", | |
| 199 | - "TEST-ant-abcdefghijklmnop", | |
| 200 | - "TEST-ant-test-key-with-dashes", | |
| 198 | + "sk-ant-1234567890", | |
| 199 | + "sk-ant-abcdefghijklmnop", | |
| 200 | + "sk-ant-test-key-with-dashes", | |
| 201 | 201 | ]; |
| 202 | 202 | |
| 203 | 203 | differentKeys.forEach((key) => { |
added extensions/cli/stubs/react-devtools-core.js +6 −0
| @@ -0,0 +1,6 @@ | ||
| 1 | +// Stub for react-devtools-core to prevent errors when it's not installed | |
| 2 | +export default { | |
| 3 | + connectToDevTools: () => { | |
| 4 | + // No-op - devtools not available in production bundle | |
| 5 | + }, | |
| 6 | +}; |
added extensions/cli/validate-aliases.mjs +188 −0
| @@ -0,0 +1,188 @@ | ||
| 1 | +#!/usr/bin/env node | |
| 2 | + | |
| 3 | +import { readFileSync, existsSync } from "fs"; | |
| 4 | +import { resolve, dirname } from "path"; | |
| 5 | +import { fileURLToPath } from "url"; | |
| 6 | + | |
| 7 | +const __dirname = dirname(fileURLToPath(import.meta.url)); | |
| 8 | + | |
| 9 | +// Colors for output | |
| 10 | +const colors = { | |
| 11 | + green: "\x1b[32m", | |
| 12 | + red: "\x1b[31m", | |
| 13 | + yellow: "\x1b[33m", | |
| 14 | + blue: "\x1b[34m", | |
| 15 | + reset: "\x1b[0m", | |
| 16 | +}; | |
| 17 | + | |
| 18 | +/** | |
| 19 | + * Parse the build.mjs file to extract defined aliases | |
| 20 | + */ | |
| 21 | +function getDefinedAliases() { | |
| 22 | + const buildPath = resolve(__dirname, "build.mjs"); | |
| 23 | + const buildContent = readFileSync(buildPath, "utf8"); | |
| 24 | + | |
| 25 | + // Find the alias object in the build file | |
| 26 | + const aliasMatch = buildContent.match(/alias:\s*{([^}]+)}/s); | |
| 27 | + if (!aliasMatch) { | |
| 28 | + console.warn(`${colors.yellow}Warning: No aliases found in build.mjs${colors.reset}`); | |
| 29 | + return new Set(); | |
| 30 | + } | |
| 31 | + | |
| 32 | + // Extract package names from the alias definitions | |
| 33 | + // Split by lines and filter out comments | |
| 34 | + const aliasBlock = aliasMatch[1]; | |
| 35 | + const lines = aliasBlock.split('\n'); | |
| 36 | + const aliases = new Set(); | |
| 37 | + | |
| 38 | + for (const line of lines) { | |
| 39 | + // Skip commented lines | |
| 40 | + if (line.trim().startsWith('//')) { | |
| 41 | + continue; | |
| 42 | + } | |
| 43 | + | |
| 44 | + // Look for package names in non-commented lines | |
| 45 | + // Match both quoted and unquoted keys | |
| 46 | + const quotedMatch = line.match(/"([^"]+)":/); | |
| 47 | + const unquotedMatch = line.match(/\s+([a-zA-Z@][a-zA-Z0-9@\/_-]*)\s*:/); | |
| 48 | + | |
| 49 | + if (quotedMatch) { | |
| 50 | + aliases.add(quotedMatch[1]); | |
| 51 | + } else if (unquotedMatch && !unquotedMatch[1].includes('__dirname') && unquotedMatch[1] !== 'js') { | |
| 52 | + aliases.add(unquotedMatch[1]); | |
| 53 | + } | |
| 54 | + } | |
| 55 | + | |
| 56 | + return aliases; | |
| 57 | +} | |
| 58 | + | |
| 59 | +/** | |
| 60 | + * Find all local packages referenced with file: in package.json files | |
| 61 | + */ | |
| 62 | +function findLocalPackages(startPath, visited = new Set()) { | |
| 63 | + const localPackages = new Set(); | |
| 64 | + | |
| 65 | + function scanPackageJson(packageJsonPath, depth = 0) { | |
| 66 | + // Avoid infinite recursion | |
| 67 | + if (visited.has(packageJsonPath) || depth > 10) { | |
| 68 | + return; | |
| 69 | + } | |
| 70 | + visited.add(packageJsonPath); | |
| 71 | + | |
| 72 | + if (!existsSync(packageJsonPath)) { | |
| 73 | + return; | |
| 74 | + } | |
| 75 | + | |
| 76 | + try { | |
| 77 | + const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")); | |
| 78 | + const packageDir = dirname(packageJsonPath); | |
| 79 | + | |
| 80 | + // Check both dependencies and devDependencies | |
| 81 | + const allDeps = { | |
| 82 | + ...packageJson.dependencies, | |
| 83 | + ...packageJson.devDependencies, | |
| 84 | + }; | |
| 85 | + | |
| 86 | + for (const [depName, depVersion] of Object.entries(allDeps)) { | |
| 87 | + if (typeof depVersion === "string" && depVersion.startsWith("file:")) { | |
| 88 | + // This is a local package | |
| 89 | + localPackages.add(depName); | |
| 90 | + | |
| 91 | + // Recursively check this package's dependencies | |
| 92 | + const depPath = resolve(packageDir, depVersion.replace("file:", "")); | |
| 93 | + const depPackageJson = resolve(depPath, "package.json"); | |
| 94 | + | |
| 95 | + if (existsSync(depPackageJson)) { | |
| 96 | + scanPackageJson(depPackageJson, depth + 1); | |
| 97 | + } | |
| 98 | + } | |
| 99 | + } | |
| 100 | + } catch (error) { | |
| 101 | + console.error(`${colors.red}Error reading ${packageJsonPath}: ${error.message}${colors.reset}`); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + // Start from the CLI's package.json | |
| 106 | + scanPackageJson(startPath); | |
| 107 | + | |
| 108 | + return localPackages; | |
| 109 | +} | |
| 110 | + | |
| 111 | +/** | |
| 112 | + * Main validation function | |
| 113 | + */ | |
| 114 | +function validateAliases() { | |
| 115 | + console.log(`${colors.blue}🔍 Validating esbuild aliases...${colors.reset}\n`); | |
| 116 | + | |
| 117 | + // Get defined aliases from build.mjs | |
| 118 | + const definedAliases = getDefinedAliases(); | |
| 119 | + console.log(`Found ${definedAliases.size} aliases in build.mjs:`); | |
| 120 | + definedAliases.forEach(alias => { | |
| 121 | + console.log(` ✓ ${alias}`); | |
| 122 | + }); | |
| 123 | + console.log(); | |
| 124 | + | |
| 125 | + // Find all local packages that need aliases | |
| 126 | + const cliPackageJson = resolve(__dirname, "package.json"); | |
| 127 | + const localPackages = findLocalPackages(cliPackageJson); | |
| 128 | + console.log(`Found ${localPackages.size} local package dependencies:`); | |
| 129 | + localPackages.forEach(pkg => { | |
| 130 | + console.log(` • ${pkg}`); | |
| 131 | + }); | |
| 132 | + console.log(); | |
| 133 | + | |
| 134 | + // Check for missing aliases | |
| 135 | + const missingAliases = []; | |
| 136 | + for (const pkg of localPackages) { | |
| 137 | + if (!definedAliases.has(pkg)) { | |
| 138 | + missingAliases.push(pkg); | |
| 139 | + } | |
| 140 | + } | |
| 141 | + | |
| 142 | + // Check for unnecessary aliases (defined but not used) | |
| 143 | + const unnecessaryAliases = []; | |
| 144 | + for (const alias of definedAliases) { | |
| 145 | + if (!localPackages.has(alias)) { | |
| 146 | + unnecessaryAliases.push(alias); | |
| 147 | + } | |
| 148 | + } | |
| 149 | + | |
| 150 | + // Report results | |
| 151 | + if (missingAliases.length > 0) { | |
| 152 | + console.log(`${colors.red}❌ Missing aliases (WILL CAUSE RUNTIME ERRORS):${colors.reset}`); | |
| 153 | + missingAliases.forEach(pkg => { | |
| 154 | + console.log(` ✗ ${pkg}`); | |
| 155 | + }); | |
| 156 | + console.log(); | |
| 157 | + console.log(`${colors.red}Add these to the alias section in build.mjs:${colors.reset}`); | |
| 158 | + missingAliases.forEach(pkg => { | |
| 159 | + const packageName = pkg.replace("@continuedev/", "").replace(/-/g, "_"); | |
| 160 | + console.log(` "${pkg}": resolve(__dirname, "../../packages/${pkg.replace("@continuedev/", "")}/dist/index.js"),`); | |
| 161 | + }); | |
| 162 | + console.log(); | |
| 163 | + } | |
| 164 | + | |
| 165 | + if (unnecessaryAliases.length > 0) { | |
| 166 | + console.log(`${colors.yellow}⚠️ Potentially unnecessary aliases:${colors.reset}`); | |
| 167 | + unnecessaryAliases.forEach(alias => { | |
| 168 | + console.log(` ? ${alias}`); | |
| 169 | + }); | |
| 170 | + console.log(); | |
| 171 | + } | |
| 172 | + | |
| 173 | + // Exit with appropriate code | |
| 174 | + if (missingAliases.length > 0) { | |
| 175 | + console.log(`${colors.red}✗ Validation failed! Missing ${missingAliases.length} required alias(es).${colors.reset}`); | |
| 176 | + console.log(`${colors.red}This would cause runtime errors in the bundled CLI.${colors.reset}`); | |
| 177 | + process.exit(1); | |
| 178 | + } else if (unnecessaryAliases.length > 0) { | |
| 179 | + console.log(`${colors.yellow}✓ Validation passed with warnings.${colors.reset}`); | |
| 180 | + process.exit(0); | |
| 181 | + } else { | |
| 182 | + console.log(`${colors.green}✅ All aliases are correctly configured!${colors.reset}`); | |
| 183 | + process.exit(0); | |
| 184 | + } | |
| 185 | +} | |
| 186 | + | |
| 187 | +// Run validation | |
| 188 | +validateAliases(); | |
| No newline at the end of the file |
modified extensions/cli/vitest.setup.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { vi } from "vitest"; |
| 2 | 2 | |
| 3 | -import { resetConsoleOverrides } from "./src/util/consoleOverride.js"; | |
| 3 | +import { resetConsoleOverrides } from "./src/init.js"; | |
| 4 | 4 | |
| 5 | 5 | // Disable telemetry for tests |
| 6 | 6 | process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; |
modified extensions/intellij/gradle.properties +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | pluginGroup=com.github.continuedev.continueintellijextension |
| 2 | -pluginVersion=1.0.38 | |
| 2 | +pluginVersion=1.0.40 | |
| 3 | 3 | platformVersion=2024.1 |
| 4 | 4 | kotlin.stdlib.default.dependency=false |
| 5 | 5 | org.gradle.configuration-cache=true |
modified extensions/vscode/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/vscode/package.json +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.79", | |
| 5 | + "version": "1.3.1", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
modified extensions/vscode/src/activation/NextEditWindowManager.ts +101 −21
| @@ -122,6 +122,11 @@ | ||
| 122 | 122 | private editableRegionStartLine: number = 0; |
| 123 | 123 | private editableRegionEndLine: number = 0; |
| 124 | 124 | |
| 125 | + // State tracking for key reservation. | |
| 126 | + // By default it is set to free, and is only set to reserved when the transition is done. | |
| 127 | + private keyReservationState: "free" | "reserved" | "transitioning" = "free"; | |
| 128 | + private latestOperationId = 0; | |
| 129 | + | |
| 125 | 130 | // Disposables |
| 126 | 131 | private disposables: vscode.Disposable[] = []; |
| 127 | 132 | |
| @@ -170,20 +175,71 @@ | ||
| 170 | 175 | this.loggingService = NextEditLoggingService.getInstance(); |
| 171 | 176 | } |
| 172 | 177 | |
| 178 | + // This is an implementation of last-action-wins. | |
| 179 | + // For each action that fires setKeyReservation, it keeps its own operationId while incrementing latestOperationId. | |
| 180 | + // When an action completes, checking for operationId === latestOperationId will determine which one came last. | |
| 181 | + private async setKeyReservation(reserve: boolean): Promise<void> { | |
| 182 | + // Increment and capture this operation's ID. | |
| 183 | + const operationId = ++this.latestOperationId; | |
| 184 | + | |
| 185 | + // Return early when already in desired state. | |
| 186 | + if ( | |
| 187 | + (reserve && this.keyReservationState === "reserved") || | |
| 188 | + (!reserve && this.keyReservationState === "free") | |
| 189 | + ) { | |
| 190 | + return; | |
| 191 | + } | |
| 192 | + | |
| 193 | + try { | |
| 194 | + await this.performKeyReservation(reserve); | |
| 195 | + | |
| 196 | + // Only update state if we're still the latest operation. | |
| 197 | + if (operationId === this.latestOperationId) { | |
| 198 | + this.keyReservationState = reserve ? "reserved" : "free"; | |
| 199 | + } | |
| 200 | + } catch (err) { | |
| 201 | + console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`); | |
| 202 | + | |
| 203 | + // Only reset to free if we're still the latest operation. | |
| 204 | + if (operationId === this.latestOperationId) { | |
| 205 | + this.keyReservationState = "free"; | |
| 206 | + } | |
| 207 | + throw err; | |
| 208 | + } | |
| 209 | + } | |
| 210 | + | |
| 211 | + public async resetKeyReservation(): Promise<void> { | |
| 212 | + // Reset internal tracking. | |
| 213 | + this.keyReservationState = "free"; | |
| 214 | + this.latestOperationId = 0; | |
| 215 | + | |
| 216 | + // Ensure VS Code context matches. | |
| 217 | + try { | |
| 218 | + await this.performKeyReservation(false); | |
| 219 | + } catch (err) { | |
| 220 | + console.error(`Failed to reset nextEditWindowActive context: ${err}`); | |
| 221 | + } | |
| 222 | + } | |
| 223 | + | |
| 224 | + private async performKeyReservation(reserve: boolean): Promise<void> { | |
| 225 | + try { | |
| 226 | + await vscode.commands.executeCommand( | |
| 227 | + "setContext", | |
| 228 | + "nextEditWindowActive", | |
| 229 | + reserve, | |
| 230 | + ); | |
| 231 | + } catch (err) { | |
| 232 | + console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`); | |
| 233 | + throw err; | |
| 234 | + } | |
| 235 | + } | |
| 236 | + | |
| 173 | 237 | public static async reserveTabAndEsc() { |
| 174 | - await vscode.commands.executeCommand( | |
| 175 | - "setContext", | |
| 176 | - "nextEditWindowActive", | |
| 177 | - true, | |
| 178 | - ); | |
| 238 | + await NextEditWindowManager.getInstance().setKeyReservation(true); | |
| 179 | 239 | } |
| 180 | 240 | |
| 181 | 241 | public static async freeTabAndEsc() { |
| 182 | - await vscode.commands.executeCommand( | |
| 183 | - "setContext", | |
| 184 | - "nextEditWindowActive", | |
| 185 | - false, | |
| 186 | - ); | |
| 242 | + await NextEditWindowManager.getInstance().setKeyReservation(false); | |
| 187 | 243 | } |
| 188 | 244 | |
| 189 | 245 | /** |
| @@ -202,7 +258,8 @@ | ||
| 202 | 258 | |
| 203 | 259 | // Set nextEditWindowActive to false to free esc and tab, |
| 204 | 260 | // letting them return to their original behaviors. |
| 205 | - await NextEditWindowManager.freeTabAndEsc(); | |
| 261 | + await this.resetKeyReservation(); | |
| 262 | + // await NextEditWindowManager.freeTabAndEsc(); | |
| 206 | 263 | |
| 207 | 264 | // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. |
| 208 | 265 | this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { |
| @@ -353,14 +410,21 @@ | ||
| 353 | 410 | |
| 354 | 411 | // Create and apply decoration with the text. |
| 355 | 412 | if (newEditRangeSlice !== "") { |
| 356 | - await this.renderWindow( | |
| 357 | - editor, | |
| 358 | - currCursorPos, | |
| 359 | - oldEditRangeSlice, | |
| 360 | - newEditRangeSlice, | |
| 361 | - this.editableRegionStartLine, | |
| 362 | - diffLines, | |
| 363 | - ); | |
| 413 | + try { | |
| 414 | + await this.renderWindow( | |
| 415 | + editor, | |
| 416 | + currCursorPos, | |
| 417 | + oldEditRangeSlice, | |
| 418 | + newEditRangeSlice, | |
| 419 | + this.editableRegionStartLine, | |
| 420 | + diffLines, | |
| 421 | + ); | |
| 422 | + } catch (error) { | |
| 423 | + console.error("Failed to render window:", error); | |
| 424 | + // Clean up and reset state. | |
| 425 | + await this.hideAllNextEditWindows(); | |
| 426 | + return; | |
| 427 | + } | |
| 364 | 428 | } |
| 365 | 429 | |
| 366 | 430 | const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); |
| @@ -368,14 +432,26 @@ | ||
| 368 | 432 | this.renderDeletions(editor, diffChars); |
| 369 | 433 | |
| 370 | 434 | // Reserve tab and esc to either accept or reject the displayed next edit contents. |
| 371 | - await NextEditWindowManager.reserveTabAndEsc(); | |
| 435 | + try { | |
| 436 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 437 | + } catch (err) { | |
| 438 | + console.error( | |
| 439 | + `Error reserving Tab/Esc after showing decorations: ${err}`, | |
| 440 | + ); | |
| 441 | + await this.hideAllNextEditWindows(); | |
| 442 | + return; | |
| 443 | + } | |
| 372 | 444 | } |
| 373 | 445 | |
| 374 | 446 | /** |
| 375 | 447 | * Hide all tooltips in all editors. |
| 376 | 448 | */ |
| 377 | 449 | public async hideAllNextEditWindows() { |
| 378 | - await NextEditWindowManager.freeTabAndEsc(); | |
| 450 | + try { | |
| 451 | + await NextEditWindowManager.freeTabAndEsc(); | |
| 452 | + } catch (err) { | |
| 453 | + console.error(`Error freeing Tab/Esc while hiding: ${err}`); | |
| 454 | + } | |
| 379 | 455 | |
| 380 | 456 | if (this.currentDecoration) { |
| 381 | 457 | vscode.window.visibleTextEditors.forEach((editor) => { |
| @@ -502,6 +578,10 @@ | ||
| 502 | 578 | * Dispose of the NextEditWindowManager. |
| 503 | 579 | */ |
| 504 | 580 | public dispose() { |
| 581 | + void this.resetKeyReservation().catch((err) => | |
| 582 | + console.error(`Failed to reset keys on dispose: ${err}`), | |
| 583 | + ); | |
| 584 | + | |
| 505 | 585 | // Dispose current decoration. |
| 506 | 586 | if (this.currentDecoration) { |
| 507 | 587 | this.currentDecoration.dispose(); |
added extensions/vscode/src/activation/NextEditWindowManager.vitest.ts +970 −0
| @@ -0,0 +1,970 @@ | ||
| 1 | +import { | |
| 2 | + afterEach, | |
| 3 | + beforeEach, | |
| 4 | + describe, | |
| 5 | + expect, | |
| 6 | + it, | |
| 7 | + MockedFunction, | |
| 8 | + vi, | |
| 9 | +} from "vitest"; | |
| 10 | + | |
| 11 | +// Mock all modules FIRST with inline factories (no external references) | |
| 12 | +vi.mock("vscode", () => ({ | |
| 13 | + commands: { | |
| 14 | + executeCommand: vi.fn(), | |
| 15 | + registerCommand: vi.fn(), | |
| 16 | + }, | |
| 17 | + window: { | |
| 18 | + activeTextEditor: undefined, | |
| 19 | + visibleTextEditors: [], | |
| 20 | + createTextEditorDecorationType: vi.fn(), | |
| 21 | + onDidChangeTextEditorSelection: vi.fn(() => ({ dispose: vi.fn() })), | |
| 22 | + onDidChangeVisibleTextEditors: vi.fn(() => ({ dispose: vi.fn() })), | |
| 23 | + onDidChangeActiveColorTheme: vi.fn(() => ({ dispose: vi.fn() })), | |
| 24 | + showInformationMessage: vi.fn(), | |
| 25 | + }, | |
| 26 | + workspace: { | |
| 27 | + getConfiguration: vi.fn(() => ({ | |
| 28 | + get: vi.fn((key: string) => { | |
| 29 | + const config: Record<string, any> = { | |
| 30 | + fontSize: 14, | |
| 31 | + fontFamily: "monospace", | |
| 32 | + showInlineTip: true, | |
| 33 | + }; | |
| 34 | + return config[key]; | |
| 35 | + }), | |
| 36 | + })), | |
| 37 | + onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), | |
| 38 | + }, | |
| 39 | + Position: class { | |
| 40 | + constructor( | |
| 41 | + public line: number, | |
| 42 | + public character: number, | |
| 43 | + ) {} | |
| 44 | + }, | |
| 45 | + Range: class { | |
| 46 | + constructor( | |
| 47 | + public start: any, | |
| 48 | + public end: any, | |
| 49 | + ) {} | |
| 50 | + }, | |
| 51 | + Selection: class { | |
| 52 | + constructor( | |
| 53 | + public anchor: any, | |
| 54 | + public active: any, | |
| 55 | + ) {} | |
| 56 | + }, | |
| 57 | + Uri: { | |
| 58 | + parse: vi.fn((str: string) => ({ toString: () => str, scheme: "file" })), | |
| 59 | + }, | |
| 60 | + DecorationRangeBehavior: { | |
| 61 | + ClosedClosed: 1, | |
| 62 | + }, | |
| 63 | + MarkdownString: class { | |
| 64 | + value: string = ""; | |
| 65 | + isTrusted: boolean = false; | |
| 66 | + supportHtml: boolean = false; | |
| 67 | + constructor(value: string) { | |
| 68 | + this.value = value; | |
| 69 | + } | |
| 70 | + }, | |
| 71 | + ExtensionContext: class { | |
| 72 | + subscriptions: any[] = []; | |
| 73 | + }, | |
| 74 | + ViewColumn: { | |
| 75 | + One: 1, | |
| 76 | + Two: 2, | |
| 77 | + }, | |
| 78 | +})); | |
| 79 | + | |
| 80 | +vi.mock("core/control-plane/env", () => ({ | |
| 81 | + EXTENSION_NAME: "continue", | |
| 82 | +})); | |
| 83 | + | |
| 84 | +vi.mock("../util/getTheme", () => ({ | |
| 85 | + getThemeString: vi.fn(() => "dark"), | |
| 86 | +})); | |
| 87 | + | |
| 88 | +vi.mock("core/codeRenderer/CodeRenderer", () => ({ | |
| 89 | + CodeRenderer: { | |
| 90 | + getInstance: vi.fn(() => ({ | |
| 91 | + setTheme: vi.fn(), | |
| 92 | + getDataUri: vi.fn().mockResolvedValue("data:image/svg+xml;base64,mock"), | |
| 93 | + })), | |
| 94 | + }, | |
| 95 | +})); | |
| 96 | + | |
| 97 | +vi.mock("core/nextEdit/NextEditProvider", () => ({ | |
| 98 | + NextEditProvider: { | |
| 99 | + getInstance: vi.fn(() => ({ | |
| 100 | + deleteChain: vi.fn(), | |
| 101 | + })), | |
| 102 | + }, | |
| 103 | +})); | |
| 104 | + | |
| 105 | +vi.mock("core/nextEdit/NextEditLoggingService", () => ({ | |
| 106 | + NextEditLoggingService: { | |
| 107 | + getInstance: vi.fn(() => ({ | |
| 108 | + cancelRejectionTimeout: vi.fn(), | |
| 109 | + cancelRejectionTimeoutButKeepCompletionId: vi.fn(), | |
| 110 | + })), | |
| 111 | + }, | |
| 112 | +})); | |
| 113 | + | |
| 114 | +vi.mock("core/diff/myers", () => ({ | |
| 115 | + myersCharDiff: vi.fn(() => []), | |
| 116 | +})); | |
| 117 | + | |
| 118 | +vi.mock("core/nextEdit/diff/diff", () => ({ | |
| 119 | + getOffsetPositionAtLastNewLine: vi.fn(() => ({ line: 0, character: 0 })), | |
| 120 | +})); | |
| 121 | + | |
| 122 | +// Import after mocks are set up | |
| 123 | +import * as vscode from "vscode"; | |
| 124 | + | |
| 125 | +import { | |
| 126 | + ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 127 | + HIDE_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 128 | + NextEditWindowManager, | |
| 129 | +} from "./NextEditWindowManager"; | |
| 130 | + | |
| 131 | +const mockVscode = vi.mocked(vscode); | |
| 132 | + | |
| 133 | +describe("NextEditWindowManager", () => { | |
| 134 | + let manager: NextEditWindowManager; | |
| 135 | + let mockEditor: any; | |
| 136 | + let mockDocument: any; | |
| 137 | + let mockContext: any; | |
| 138 | + | |
| 139 | + beforeEach(() => { | |
| 140 | + vi.clearAllMocks(); | |
| 141 | + | |
| 142 | + // Clear singleton instance | |
| 143 | + NextEditWindowManager.clearInstance(); | |
| 144 | + | |
| 145 | + // Create mock document | |
| 146 | + mockDocument = { | |
| 147 | + uri: { toString: () => "file:///test.ts", scheme: "file" }, | |
| 148 | + version: 1, | |
| 149 | + lineCount: 10, | |
| 150 | + lineAt: vi.fn((line: number) => ({ | |
| 151 | + text: `line ${line} content`, | |
| 152 | + range: new mockVscode.Range( | |
| 153 | + new mockVscode.Position(line, 0), | |
| 154 | + new mockVscode.Position(line, 20), | |
| 155 | + ), | |
| 156 | + })), | |
| 157 | + }; | |
| 158 | + | |
| 159 | + // Create mock editor | |
| 160 | + mockEditor = { | |
| 161 | + document: mockDocument, | |
| 162 | + selection: { | |
| 163 | + active: new mockVscode.Position(0, 0), | |
| 164 | + }, | |
| 165 | + setDecorations: vi.fn(), | |
| 166 | + edit: vi.fn((callback: any) => { | |
| 167 | + callback({ | |
| 168 | + replace: vi.fn(), | |
| 169 | + delete: vi.fn(), | |
| 170 | + }); | |
| 171 | + return Promise.resolve(true); | |
| 172 | + }), | |
| 173 | + }; | |
| 174 | + | |
| 175 | + // Create mock context | |
| 176 | + mockContext = { | |
| 177 | + subscriptions: [], | |
| 178 | + }; | |
| 179 | + | |
| 180 | + // Setup default mock implementations | |
| 181 | + ( | |
| 182 | + mockVscode.commands.executeCommand as MockedFunction<any> | |
| 183 | + ).mockResolvedValue(undefined); | |
| 184 | + (mockVscode.commands.registerCommand as MockedFunction<any>) | |
| 185 | + //@ts-ignore | |
| 186 | + .mockImplementation((command: string, callback: any) => ({ | |
| 187 | + dispose: vi.fn(), | |
| 188 | + })); | |
| 189 | + ( | |
| 190 | + mockVscode.window.createTextEditorDecorationType as MockedFunction<any> | |
| 191 | + ).mockReturnValue({ | |
| 192 | + dispose: vi.fn(), | |
| 193 | + }); | |
| 194 | + | |
| 195 | + // Get manager instance | |
| 196 | + manager = NextEditWindowManager.getInstance(); | |
| 197 | + }); | |
| 198 | + | |
| 199 | + afterEach(() => { | |
| 200 | + NextEditWindowManager.clearInstance(); | |
| 201 | + }); | |
| 202 | + | |
| 203 | + describe("Singleton Pattern", () => { | |
| 204 | + it("should return the same instance", () => { | |
| 205 | + const instance1 = NextEditWindowManager.getInstance(); | |
| 206 | + const instance2 = NextEditWindowManager.getInstance(); | |
| 207 | + expect(instance1).toBe(instance2); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + it("should properly clear instance", () => { | |
| 211 | + const instance1 = NextEditWindowManager.getInstance(); | |
| 212 | + NextEditWindowManager.clearInstance(); | |
| 213 | + const instance2 = NextEditWindowManager.getInstance(); | |
| 214 | + expect(instance1).not.toBe(instance2); | |
| 215 | + }); | |
| 216 | + }); | |
| 217 | + | |
| 218 | + describe("Key Reservation State Management", () => { | |
| 219 | + beforeEach(async () => { | |
| 220 | + await manager.setupNextEditWindowManager(mockContext); | |
| 221 | + }); | |
| 222 | + | |
| 223 | + it("should start with keys in free state", () => { | |
| 224 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 225 | + }); | |
| 226 | + | |
| 227 | + it("should reserve keys when showing window", async () => { | |
| 228 | + await manager.showNextEditWindow( | |
| 229 | + mockEditor, | |
| 230 | + new mockVscode.Position(0, 0), | |
| 231 | + 0, | |
| 232 | + 0, | |
| 233 | + "old", | |
| 234 | + "new", | |
| 235 | + [], | |
| 236 | + ); | |
| 237 | + | |
| 238 | + expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( | |
| 239 | + "setContext", | |
| 240 | + "nextEditWindowActive", | |
| 241 | + true, | |
| 242 | + ); | |
| 243 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 244 | + }); | |
| 245 | + | |
| 246 | + it("should free keys when hiding windows", async () => { | |
| 247 | + // First show a window | |
| 248 | + await manager.showNextEditWindow( | |
| 249 | + mockEditor, | |
| 250 | + new mockVscode.Position(0, 0), | |
| 251 | + 0, | |
| 252 | + 0, | |
| 253 | + "old", | |
| 254 | + "new", | |
| 255 | + [], | |
| 256 | + ); | |
| 257 | + | |
| 258 | + // Then hide it | |
| 259 | + await manager.hideAllNextEditWindows(); | |
| 260 | + | |
| 261 | + expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( | |
| 262 | + "setContext", | |
| 263 | + "nextEditWindowActive", | |
| 264 | + false, | |
| 265 | + ); | |
| 266 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 267 | + }); | |
| 268 | + | |
| 269 | + it("should handle sequential reserve/free operations", async () => { | |
| 270 | + const executeCommand = mockVscode.commands | |
| 271 | + .executeCommand as MockedFunction<any>; | |
| 272 | + | |
| 273 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 274 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 275 | + | |
| 276 | + await NextEditWindowManager.freeTabAndEsc(); | |
| 277 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 278 | + | |
| 279 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 280 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 281 | + | |
| 282 | + // Should have been called 3 times + 1 from beforeEach | |
| 283 | + expect(executeCommand).toHaveBeenCalledTimes(4); | |
| 284 | + }); | |
| 285 | + | |
| 286 | + it("should skip redundant reserve operations", async () => { | |
| 287 | + const executeCommand = mockVscode.commands | |
| 288 | + .executeCommand as MockedFunction<any>; | |
| 289 | + | |
| 290 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 291 | + executeCommand.mockClear(); | |
| 292 | + | |
| 293 | + // Try to reserve again | |
| 294 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 295 | + | |
| 296 | + // Should not have called executeCommand again | |
| 297 | + expect(executeCommand).not.toHaveBeenCalled(); | |
| 298 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 299 | + }); | |
| 300 | + | |
| 301 | + it("should skip redundant free operations", async () => { | |
| 302 | + const executeCommand = mockVscode.commands | |
| 303 | + .executeCommand as MockedFunction<any>; | |
| 304 | + executeCommand.mockClear(); | |
| 305 | + | |
| 306 | + // Already free, try to free again | |
| 307 | + await NextEditWindowManager.freeTabAndEsc(); | |
| 308 | + | |
| 309 | + // Should not have called executeCommand | |
| 310 | + expect(executeCommand).not.toHaveBeenCalled(); | |
| 311 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 312 | + }); | |
| 313 | + }); | |
| 314 | + | |
| 315 | + describe("Race Condition Prevention", () => { | |
| 316 | + beforeEach(async () => { | |
| 317 | + await manager.setupNextEditWindowManager(mockContext); | |
| 318 | + }); | |
| 319 | + | |
| 320 | + it("should handle concurrent operations with random delays and last-write-wins", async () => { | |
| 321 | + const executeCommand = mockVscode.commands | |
| 322 | + .executeCommand as MockedFunction<any>; | |
| 323 | + let completedOperations: string[] = []; | |
| 324 | + | |
| 325 | + // Reset key reservation to ensure clean state | |
| 326 | + await manager.resetKeyReservation(); | |
| 327 | + | |
| 328 | + // Start from reserved state so first free() will proceed | |
| 329 | + manager["keyReservationState"] = "reserved"; | |
| 330 | + executeCommand.mockClear(); | |
| 331 | + | |
| 332 | + // Make executeCommand take random time and track completions | |
| 333 | + executeCommand.mockImplementation((cmd, key, value) => { | |
| 334 | + const operationId = `${value ? "reserve" : "free"}-${Date.now()}-${Math.random()}`; | |
| 335 | + return new Promise((resolve) => { | |
| 336 | + setTimeout(() => { | |
| 337 | + completedOperations.push(operationId); | |
| 338 | + // Immediately update state to ensure next operation proceeds | |
| 339 | + // This simulates fast state changes | |
| 340 | + manager["keyReservationState"] = value ? "reserved" : "free"; | |
| 341 | + resolve(undefined); | |
| 342 | + }, Math.random() * 50); | |
| 343 | + }); | |
| 344 | + }); | |
| 345 | + | |
| 346 | + // Fire multiple operations concurrently | |
| 347 | + const operations = [ | |
| 348 | + NextEditWindowManager.reserveTabAndEsc(), // operation 1: reserve (skipped - already reserved) | |
| 349 | + NextEditWindowManager.freeTabAndEsc(), // operation 2: free (proceeds) | |
| 350 | + NextEditWindowManager.reserveTabAndEsc(), // operation 3: reserve (proceeds after 2 completes) | |
| 351 | + NextEditWindowManager.freeTabAndEsc(), // operation 4: free (proceeds after 3 completes) | |
| 352 | + ]; | |
| 353 | + | |
| 354 | + await Promise.all(operations); | |
| 355 | + | |
| 356 | + // Count how many actually proceeded (those that didn't early return) | |
| 357 | + const actualCalls = executeCommand.mock.calls.length; | |
| 358 | + | |
| 359 | + // The state should match the last operation's intent | |
| 360 | + // But the actual number of calls depends on timing and early returns | |
| 361 | + expect(manager["latestOperationId"]).toBeGreaterThanOrEqual(actualCalls); | |
| 362 | + }); | |
| 363 | + | |
| 364 | + it("should ignore stale operations", async () => { | |
| 365 | + const executeCommand = mockVscode.commands | |
| 366 | + .executeCommand as MockedFunction<any>; | |
| 367 | + | |
| 368 | + await manager.resetKeyReservation(); | |
| 369 | + executeCommand.mockClear(); | |
| 370 | + | |
| 371 | + // Create deferred promises with guaranteed resolvers | |
| 372 | + const createDeferred = () => { | |
| 373 | + let resolve: Function; | |
| 374 | + const promise = new Promise((res) => { | |
| 375 | + resolve = res; | |
| 376 | + }); | |
| 377 | + return { promise, resolve: resolve! }; | |
| 378 | + }; | |
| 379 | + | |
| 380 | + const deferred1 = createDeferred(); | |
| 381 | + const deferred2 = createDeferred(); | |
| 382 | + | |
| 383 | + // Control when each operation completes | |
| 384 | + executeCommand | |
| 385 | + .mockImplementationOnce(() => deferred1.promise) | |
| 386 | + .mockImplementationOnce(() => deferred2.promise); | |
| 387 | + | |
| 388 | + // Start operations | |
| 389 | + const op1 = NextEditWindowManager.reserveTabAndEsc(); | |
| 390 | + const op2 = NextEditWindowManager.freeTabAndEsc(); | |
| 391 | + | |
| 392 | + // Complete op2 first (even though op1 started first) | |
| 393 | + deferred2.resolve(undefined); | |
| 394 | + await op2; | |
| 395 | + | |
| 396 | + // State should be free (from op2) | |
| 397 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 398 | + expect(manager["latestOperationId"]).toBe(2); | |
| 399 | + | |
| 400 | + // Now complete op1 (should be ignored as stale) | |
| 401 | + deferred1.resolve(undefined); | |
| 402 | + await op1; | |
| 403 | + | |
| 404 | + // State should still be free (op1 was ignored) | |
| 405 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 406 | + expect(manager["latestOperationId"]).toBe(2); | |
| 407 | + }); | |
| 408 | + | |
| 409 | + it("should handle rapid fire operations correctly (loop)", async () => { | |
| 410 | + const executeCommand = mockVscode.commands | |
| 411 | + .executeCommand as MockedFunction<any>; | |
| 412 | + | |
| 413 | + await manager.resetKeyReservation(); | |
| 414 | + executeCommand.mockClear(); | |
| 415 | + | |
| 416 | + // Make operations instant | |
| 417 | + executeCommand.mockResolvedValue(undefined); | |
| 418 | + | |
| 419 | + // Fire many operations rapidly | |
| 420 | + const operations = []; | |
| 421 | + for (let i = 0; i < 20; i++) { | |
| 422 | + operations.push( | |
| 423 | + i % 2 === 0 | |
| 424 | + ? NextEditWindowManager.reserveTabAndEsc() | |
| 425 | + : NextEditWindowManager.freeTabAndEsc(), | |
| 426 | + ); | |
| 427 | + } | |
| 428 | + | |
| 429 | + await Promise.all(operations); | |
| 430 | + | |
| 431 | + // Last operation (i=19) was free (odd number) | |
| 432 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 433 | + expect(manager["latestOperationId"]).toBe(20); | |
| 434 | + }); | |
| 435 | + | |
| 436 | + it("should handle alternating reserve/free with delays", async () => { | |
| 437 | + const executeCommand = mockVscode.commands | |
| 438 | + .executeCommand as MockedFunction<any>; | |
| 439 | + | |
| 440 | + await manager.resetKeyReservation(); | |
| 441 | + executeCommand.mockClear(); | |
| 442 | + | |
| 443 | + // Track actual VS Code context values set | |
| 444 | + const contextValues: boolean[] = []; | |
| 445 | + executeCommand.mockImplementation((cmd, key, value) => { | |
| 446 | + if (cmd === "setContext") { | |
| 447 | + //@ts-ignore | |
| 448 | + contextValues.push(value); | |
| 449 | + } | |
| 450 | + return Promise.resolve(undefined); | |
| 451 | + }); | |
| 452 | + | |
| 453 | + // Alternating operations | |
| 454 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 455 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 456 | + | |
| 457 | + await NextEditWindowManager.freeTabAndEsc(); | |
| 458 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 459 | + | |
| 460 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 461 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 462 | + | |
| 463 | + // Check that context was set correctly each time | |
| 464 | + expect(contextValues).toEqual([true, false, true]); | |
| 465 | + }); | |
| 466 | + | |
| 467 | + it("should handle rapid alternations correctly", async () => { | |
| 468 | + const executeCommand = mockVscode.commands | |
| 469 | + .executeCommand as MockedFunction<any>; | |
| 470 | + | |
| 471 | + await manager.resetKeyReservation(); | |
| 472 | + executeCommand.mockClear(); | |
| 473 | + | |
| 474 | + // Track all setContext calls | |
| 475 | + const contextCalls: boolean[] = []; | |
| 476 | + executeCommand.mockImplementation((cmd, key, value) => { | |
| 477 | + if (cmd === "setContext" && key === "nextEditWindowActive") { | |
| 478 | + //@ts-ignore | |
| 479 | + contextCalls.push(value); | |
| 480 | + } | |
| 481 | + return Promise.resolve(); | |
| 482 | + }); | |
| 483 | + | |
| 484 | + // Simulate rapid SEQUENTIAL user interactions: | |
| 485 | + // These need to be sequential to ensure state changes between calls | |
| 486 | + await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved | |
| 487 | + await NextEditWindowManager.freeTabAndEsc(); // reserved -> free | |
| 488 | + await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved | |
| 489 | + await NextEditWindowManager.freeTabAndEsc(); // reserved -> free | |
| 490 | + | |
| 491 | + // Should end in free state (last operation) | |
| 492 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 493 | + | |
| 494 | + // Should have made all 4 calls since state alternates | |
| 495 | + expect(contextCalls).toEqual([true, false, true, false]); | |
| 496 | + }); | |
| 497 | + | |
| 498 | + it("should handle concurrent duplicate operations efficiently", async () => { | |
| 499 | + const executeCommand = mockVscode.commands | |
| 500 | + .executeCommand as MockedFunction<any>; | |
| 501 | + | |
| 502 | + await manager.resetKeyReservation(); | |
| 503 | + executeCommand.mockClear(); | |
| 504 | + | |
| 505 | + // Track all setContext calls | |
| 506 | + const contextCalls: boolean[] = []; | |
| 507 | + executeCommand.mockImplementation((cmd, key, value) => { | |
| 508 | + if (cmd === "setContext" && key === "nextEditWindowActive") { | |
| 509 | + //@ts-ignore | |
| 510 | + contextCalls.push(value); | |
| 511 | + } | |
| 512 | + return Promise.resolve(); | |
| 513 | + }); | |
| 514 | + | |
| 515 | + // When multiple reserve operations happen concurrently (e.g., multiple completions) | |
| 516 | + // Only the first should actually make the call | |
| 517 | + const operations = [ | |
| 518 | + NextEditWindowManager.reserveTabAndEsc(), | |
| 519 | + NextEditWindowManager.reserveTabAndEsc(), | |
| 520 | + NextEditWindowManager.reserveTabAndEsc(), | |
| 521 | + ]; | |
| 522 | + | |
| 523 | + await Promise.all(operations); | |
| 524 | + | |
| 525 | + // Should have made only the necessary calls | |
| 526 | + // Since all start with state "free", all will proceed to call setContext | |
| 527 | + // This is because they all check state before any completes | |
| 528 | + expect(contextCalls.length).toBeGreaterThan(0); | |
| 529 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 530 | + | |
| 531 | + // All calls should be trying to reserve (true) | |
| 532 | + expect(contextCalls.every((call) => call === true)).toBe(true); | |
| 533 | + }); | |
| 534 | + | |
| 535 | + it("should handle truly concurrent mixed operations", async () => { | |
| 536 | + const executeCommand = mockVscode.commands | |
| 537 | + .executeCommand as MockedFunction<any>; | |
| 538 | + | |
| 539 | + await manager.resetKeyReservation(); | |
| 540 | + // Start in reserved state | |
| 541 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 542 | + executeCommand.mockClear(); | |
| 543 | + | |
| 544 | + // Track all setContext calls | |
| 545 | + const contextCalls: boolean[] = []; | |
| 546 | + executeCommand.mockImplementation((cmd, key, value) => { | |
| 547 | + if (cmd === "setContext" && key === "nextEditWindowActive") { | |
| 548 | + //@ts-ignore | |
| 549 | + contextCalls.push(value); | |
| 550 | + // Add small delay to simulate real async behavior | |
| 551 | + return new Promise((resolve) => setTimeout(resolve, 5)); | |
| 552 | + } | |
| 553 | + return Promise.resolve(); | |
| 554 | + }); | |
| 555 | + | |
| 556 | + // Mix of operations starting from "reserved" state | |
| 557 | + const operations = [ | |
| 558 | + NextEditWindowManager.freeTabAndEsc(), // Will proceed (reserved -> free) | |
| 559 | + NextEditWindowManager.freeTabAndEsc(), // Will proceed (checks while first is in flight) | |
| 560 | + NextEditWindowManager.reserveTabAndEsc(), // Will proceed (different operation) | |
| 561 | + ]; | |
| 562 | + | |
| 563 | + await Promise.all(operations); | |
| 564 | + | |
| 565 | + // The last operation to complete wins (but order is non-deterministic) | |
| 566 | + // State should be either "free" or "reserved" depending on completion order | |
| 567 | + expect(["free", "reserved"]).toContain(manager["keyReservationState"]); | |
| 568 | + | |
| 569 | + // Should have made at least some calls | |
| 570 | + expect(contextCalls.length).toBeGreaterThan(0); | |
| 571 | + }); | |
| 572 | + | |
| 573 | + it("should maintain correct state with stale operations", async () => { | |
| 574 | + const executeCommand = mockVscode.commands | |
| 575 | + .executeCommand as MockedFunction<any>; | |
| 576 | + | |
| 577 | + await manager.resetKeyReservation(); | |
| 578 | + executeCommand.mockClear(); | |
| 579 | + | |
| 580 | + // Create a controlled execution order | |
| 581 | + let resolveFirst: () => void; | |
| 582 | + let resolveSecond: () => void; | |
| 583 | + | |
| 584 | + const firstPromise = new Promise<void>((resolve) => { | |
| 585 | + resolveFirst = resolve; | |
| 586 | + }); | |
| 587 | + | |
| 588 | + const secondPromise = new Promise<void>((resolve) => { | |
| 589 | + resolveSecond = resolve; | |
| 590 | + }); | |
| 591 | + | |
| 592 | + executeCommand | |
| 593 | + .mockImplementationOnce(() => firstPromise) | |
| 594 | + .mockImplementationOnce(() => secondPromise); | |
| 595 | + | |
| 596 | + // Start operations | |
| 597 | + const op1 = NextEditWindowManager.reserveTabAndEsc(); | |
| 598 | + const op2 = NextEditWindowManager.freeTabAndEsc(); | |
| 599 | + | |
| 600 | + // Complete second operation first (out of order) | |
| 601 | + resolveSecond!(); | |
| 602 | + await op2; | |
| 603 | + | |
| 604 | + // State should be free (last operation to start, even though it completed first) | |
| 605 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 606 | + | |
| 607 | + // Complete first operation | |
| 608 | + resolveFirst!(); | |
| 609 | + await op1; | |
| 610 | + | |
| 611 | + // State should still be free (op1 was stale) | |
| 612 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 613 | + }); | |
| 614 | + }); | |
| 615 | + | |
| 616 | + describe("Error Recovery", () => { | |
| 617 | + beforeEach(async () => { | |
| 618 | + await manager.setupNextEditWindowManager(mockContext); | |
| 619 | + }); | |
| 620 | + | |
| 621 | + it("should recover from failed key reservation", async () => { | |
| 622 | + const executeCommand = mockVscode.commands | |
| 623 | + .executeCommand as MockedFunction<any>; | |
| 624 | + | |
| 625 | + // Make reservation fail | |
| 626 | + executeCommand.mockRejectedValueOnce(new Error("VS Code busy")); | |
| 627 | + | |
| 628 | + await expect(NextEditWindowManager.reserveTabAndEsc()).rejects.toThrow( | |
| 629 | + "VS Code busy", | |
| 630 | + ); | |
| 631 | + | |
| 632 | + // State should reset to free | |
| 633 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 634 | + | |
| 635 | + // Should be able to try again | |
| 636 | + executeCommand.mockResolvedValueOnce(undefined); | |
| 637 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 638 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 639 | + }); | |
| 640 | + | |
| 641 | + it("should recover from failed key freeing", async () => { | |
| 642 | + const executeCommand = mockVscode.commands | |
| 643 | + .executeCommand as MockedFunction<any>; | |
| 644 | + | |
| 645 | + // First reserve successfully | |
| 646 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 647 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 648 | + | |
| 649 | + // Make freeing fail | |
| 650 | + executeCommand.mockRejectedValueOnce(new Error("VS Code busy")); | |
| 651 | + | |
| 652 | + await expect(NextEditWindowManager.freeTabAndEsc()).rejects.toThrow( | |
| 653 | + "VS Code busy", | |
| 654 | + ); | |
| 655 | + | |
| 656 | + // State should still reset to free (safety mechanism) | |
| 657 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 658 | + }); | |
| 659 | + | |
| 660 | + it("should handle decoration creation failure", async () => { | |
| 661 | + const createDecoration = mockVscode.window | |
| 662 | + .createTextEditorDecorationType as MockedFunction<any>; | |
| 663 | + createDecoration.mockImplementationOnce(() => { | |
| 664 | + throw new Error("Failed to create decoration"); | |
| 665 | + }); | |
| 666 | + | |
| 667 | + // Should not throw, but should clean up | |
| 668 | + await manager.showNextEditWindow( | |
| 669 | + mockEditor, | |
| 670 | + new mockVscode.Position(0, 0), | |
| 671 | + 0, | |
| 672 | + 0, | |
| 673 | + "old", | |
| 674 | + "new", | |
| 675 | + [], | |
| 676 | + ); | |
| 677 | + | |
| 678 | + // Keys should be freed due to error | |
| 679 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 680 | + expect(manager["currentDecoration"]).toBeNull(); | |
| 681 | + }); | |
| 682 | + }); | |
| 683 | + | |
| 684 | + describe("Command Registration", () => { | |
| 685 | + it("should register hide command", async () => { | |
| 686 | + await manager.setupNextEditWindowManager(mockContext); | |
| 687 | + | |
| 688 | + expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith( | |
| 689 | + HIDE_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 690 | + expect.any(Function), | |
| 691 | + ); | |
| 692 | + }); | |
| 693 | + | |
| 694 | + it("should register accept command", async () => { | |
| 695 | + await manager.setupNextEditWindowManager(mockContext); | |
| 696 | + | |
| 697 | + expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith( | |
| 698 | + ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 699 | + expect.any(Function), | |
| 700 | + ); | |
| 701 | + }); | |
| 702 | + | |
| 703 | + it("should handle command registration failure gracefully", async () => { | |
| 704 | + const registerCommand = mockVscode.commands | |
| 705 | + .registerCommand as MockedFunction<any>; | |
| 706 | + registerCommand.mockImplementationOnce(() => { | |
| 707 | + throw new Error("Command already registered"); | |
| 708 | + }); | |
| 709 | + | |
| 710 | + // Should not throw | |
| 711 | + await expect( | |
| 712 | + manager.setupNextEditWindowManager(mockContext), | |
| 713 | + ).resolves.not.toThrow(); | |
| 714 | + }); | |
| 715 | + }); | |
| 716 | + | |
| 717 | + describe("Window Management", () => { | |
| 718 | + beforeEach(async () => { | |
| 719 | + await manager.setupNextEditWindowManager(mockContext); | |
| 720 | + }); | |
| 721 | + | |
| 722 | + it("should store tooltip text when showing window", async () => { | |
| 723 | + await manager.showNextEditWindow( | |
| 724 | + mockEditor, | |
| 725 | + new mockVscode.Position(0, 0), | |
| 726 | + 0, | |
| 727 | + 2, | |
| 728 | + "old code", | |
| 729 | + "new code", | |
| 730 | + [], | |
| 731 | + ); | |
| 732 | + | |
| 733 | + expect(manager["currentTooltipText"]).toBe("new code"); | |
| 734 | + expect(manager["activeEditor"]).toBe(mockEditor); | |
| 735 | + }); | |
| 736 | + | |
| 737 | + it("should clear tooltip text when hiding windows", async () => { | |
| 738 | + // Show first | |
| 739 | + await manager.showNextEditWindow( | |
| 740 | + mockEditor, | |
| 741 | + new mockVscode.Position(0, 0), | |
| 742 | + 0, | |
| 743 | + 2, | |
| 744 | + "old", | |
| 745 | + "new", | |
| 746 | + [], | |
| 747 | + ); | |
| 748 | + | |
| 749 | + // Then hide | |
| 750 | + await manager.hideAllNextEditWindows(); | |
| 751 | + | |
| 752 | + expect(manager["currentTooltipText"]).toBeNull(); | |
| 753 | + expect(manager["activeEditor"]).toBeNull(); | |
| 754 | + }); | |
| 755 | + | |
| 756 | + it("should handle line deletion case", async () => { | |
| 757 | + mockEditor.document.lineAt = vi.fn((lineNumber: number) => ({ | |
| 758 | + text: "line to delete", | |
| 759 | + })); | |
| 760 | + | |
| 761 | + await manager.showNextEditWindow( | |
| 762 | + mockEditor, | |
| 763 | + new mockVscode.Position(1, 0), | |
| 764 | + 1, | |
| 765 | + 1, | |
| 766 | + "line to delete", | |
| 767 | + "", // Empty means deletion | |
| 768 | + [{ type: "old", line: "line to delete" }], | |
| 769 | + ); | |
| 770 | + | |
| 771 | + expect(manager["isLineDelete"]).toBe(true); | |
| 772 | + // Final cursor should be at end of previous line | |
| 773 | + expect(manager["finalCursorPos"]?.line).toBe(0); | |
| 774 | + }); | |
| 775 | + | |
| 776 | + it("should skip rendering for excluded URIs", async () => { | |
| 777 | + mockEditor.document.uri = { | |
| 778 | + toString: () => "output://test", | |
| 779 | + scheme: "output", | |
| 780 | + }; | |
| 781 | + | |
| 782 | + await manager.showNextEditWindow( | |
| 783 | + mockEditor, | |
| 784 | + new mockVscode.Position(0, 0), | |
| 785 | + 0, | |
| 786 | + 0, | |
| 787 | + "old", | |
| 788 | + "new", | |
| 789 | + [], | |
| 790 | + ); | |
| 791 | + | |
| 792 | + // Should not create decoration for excluded URI | |
| 793 | + expect( | |
| 794 | + mockVscode.window.createTextEditorDecorationType, | |
| 795 | + ).not.toHaveBeenCalled(); | |
| 796 | + expect(manager["currentDecoration"]).toBeNull(); | |
| 797 | + }); | |
| 798 | + }); | |
| 799 | + | |
| 800 | + describe("Accept/Reject Flow", () => { | |
| 801 | + beforeEach(async () => { | |
| 802 | + await manager.setupNextEditWindowManager(mockContext); | |
| 803 | + }); | |
| 804 | + | |
| 805 | + it("should apply text when accepting", async () => { | |
| 806 | + // Show window first | |
| 807 | + await manager.showNextEditWindow( | |
| 808 | + mockEditor, | |
| 809 | + new mockVscode.Position(0, 0), | |
| 810 | + 0, | |
| 811 | + 0, | |
| 812 | + "old", | |
| 813 | + "new text", | |
| 814 | + [], | |
| 815 | + ); | |
| 816 | + | |
| 817 | + // Get the accept command callback | |
| 818 | + const registerCalls = ( | |
| 819 | + mockVscode.commands.registerCommand as MockedFunction<any> | |
| 820 | + ).mock.calls; | |
| 821 | + const acceptCall = registerCalls.find( | |
| 822 | + (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 823 | + ); | |
| 824 | + //@ts-ignore | |
| 825 | + const acceptCallback = acceptCall[1]; | |
| 826 | + | |
| 827 | + // Call accept | |
| 828 | + //@ts-ignore | |
| 829 | + await acceptCallback(); | |
| 830 | + | |
| 831 | + // Should have called edit | |
| 832 | + expect(mockEditor.edit).toHaveBeenCalled(); | |
| 833 | + | |
| 834 | + // Should have cleared the decoration | |
| 835 | + expect(manager["currentTooltipText"]).toBeNull(); | |
| 836 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 837 | + }); | |
| 838 | + | |
| 839 | + it("should not accept when no active window", async () => { | |
| 840 | + // Get the accept command callback | |
| 841 | + const registerCalls = ( | |
| 842 | + mockVscode.commands.registerCommand as MockedFunction<any> | |
| 843 | + ).mock.calls; | |
| 844 | + const acceptCall = registerCalls.find( | |
| 845 | + (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 846 | + ); | |
| 847 | + //@ts-ignore | |
| 848 | + const acceptCallback = acceptCall[1]; | |
| 849 | + | |
| 850 | + // Call accept without showing window | |
| 851 | + //@ts-ignore | |
| 852 | + await acceptCallback(); | |
| 853 | + | |
| 854 | + // Should not have called edit | |
| 855 | + expect(mockEditor.edit).not.toHaveBeenCalled(); | |
| 856 | + }); | |
| 857 | + | |
| 858 | + it("should hide window when rejecting", async () => { | |
| 859 | + // Show window first | |
| 860 | + await manager.showNextEditWindow( | |
| 861 | + mockEditor, | |
| 862 | + new mockVscode.Position(0, 0), | |
| 863 | + 0, | |
| 864 | + 0, | |
| 865 | + "old", | |
| 866 | + "new", | |
| 867 | + [], | |
| 868 | + ); | |
| 869 | + | |
| 870 | + // Get the hide command callback | |
| 871 | + const registerCalls = ( | |
| 872 | + mockVscode.commands.registerCommand as MockedFunction<any> | |
| 873 | + ).mock.calls; | |
| 874 | + const hideCall = registerCalls.find( | |
| 875 | + (call) => call[0] === HIDE_NEXT_EDIT_SUGGESTION_COMMAND, | |
| 876 | + ); | |
| 877 | + //@ts-ignore | |
| 878 | + const hideCallback = hideCall[1]; | |
| 879 | + | |
| 880 | + // Call hide | |
| 881 | + //@ts-ignore | |
| 882 | + await hideCallback(); | |
| 883 | + | |
| 884 | + // Should have cleared everything | |
| 885 | + expect(manager["currentTooltipText"]).toBeNull(); | |
| 886 | + expect(manager["activeEditor"]).toBeNull(); | |
| 887 | + expect(manager["keyReservationState"]).toBe("free"); | |
| 888 | + }); | |
| 889 | + }); | |
| 890 | + | |
| 891 | + describe("Disposal", () => { | |
| 892 | + it("should free keys on disposal", async () => { | |
| 893 | + await manager.setupNextEditWindowManager(mockContext); | |
| 894 | + | |
| 895 | + // Reserve keys first | |
| 896 | + await NextEditWindowManager.reserveTabAndEsc(); | |
| 897 | + expect(manager["keyReservationState"]).toBe("reserved"); | |
| 898 | + | |
| 899 | + // Dispose | |
| 900 | + manager.dispose(); | |
| 901 | + | |
| 902 | + // Should attempt to free keys | |
| 903 | + expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith( | |
| 904 | + "setContext", | |
| 905 | + "nextEditWindowActive", | |
| 906 | + false, | |
| 907 | + ); | |
| 908 | + }); | |
| 909 | + | |
| 910 | + it("should dispose decorations on disposal", async () => { | |
| 911 | + await manager.setupNextEditWindowManager(mockContext); | |
| 912 | + | |
| 913 | + const mockDecoration = { dispose: vi.fn() }; | |
| 914 | + const mockDisposable1 = { dispose: vi.fn() }; | |
| 915 | + const mockDisposable2 = { dispose: vi.fn() }; | |
| 916 | + | |
| 917 | + manager["currentDecoration"] = mockDecoration as any; | |
| 918 | + manager["disposables"] = [mockDisposable1, mockDisposable2]; | |
| 919 | + | |
| 920 | + manager.dispose(); | |
| 921 | + | |
| 922 | + expect(mockDecoration.dispose).toHaveBeenCalled(); | |
| 923 | + expect(mockDisposable1.dispose).toHaveBeenCalled(); | |
| 924 | + expect(mockDisposable2.dispose).toHaveBeenCalled(); | |
| 925 | + }); | |
| 926 | + }); | |
| 927 | + | |
| 928 | + describe("Configuration Changes", () => { | |
| 929 | + it("should update on theme change", async () => { | |
| 930 | + await manager.setupNextEditWindowManager(mockContext); | |
| 931 | + | |
| 932 | + // Get the configuration change listener | |
| 933 | + const onDidChange = mockVscode.workspace | |
| 934 | + .onDidChangeConfiguration as MockedFunction<any>; | |
| 935 | + const changeCallback = onDidChange.mock.calls[0][0]; | |
| 936 | + | |
| 937 | + // Simulate theme change | |
| 938 | + //@ts-ignore | |
| 939 | + await changeCallback({ | |
| 940 | + affectsConfiguration: (key: string) => key === "workbench.colorTheme", | |
| 941 | + }); | |
| 942 | + | |
| 943 | + // Should have updated theme | |
| 944 | + const { getThemeString } = await import("../util/getTheme"); | |
| 945 | + expect(getThemeString).toHaveBeenCalled(); | |
| 946 | + }); | |
| 947 | + | |
| 948 | + it("should update on font size change", async () => { | |
| 949 | + await manager.setupNextEditWindowManager(mockContext); | |
| 950 | + | |
| 951 | + const onDidChange = mockVscode.workspace | |
| 952 | + .onDidChangeConfiguration as MockedFunction<any>; | |
| 953 | + const changeCallback = onDidChange.mock.calls[0][0]; | |
| 954 | + | |
| 955 | + // Change font size | |
| 956 | + ( | |
| 957 | + mockVscode.workspace.getConfiguration as MockedFunction<any> | |
| 958 | + ).mockReturnValueOnce({ | |
| 959 | + get: (key: string) => (key === "fontSize" ? 16 : "monospace"), | |
| 960 | + }); | |
| 961 | + | |
| 962 | + //@ts-ignore | |
| 963 | + await changeCallback({ | |
| 964 | + affectsConfiguration: (key: string) => key === "editor.fontSize", | |
| 965 | + }); | |
| 966 | + | |
| 967 | + expect(manager["fontSize"]).toBe(16); | |
| 968 | + }); | |
| 969 | + }); | |
| 970 | +}); |
modified extensions/vscode/src/apply/ApplyManager.ts +20 −29
| @@ -50,45 +50,36 @@ | ||
| 50 | 50 | toolCallId, |
| 51 | 51 | }); |
| 52 | 52 | |
| 53 | - try { | |
| 54 | - const hasExistingDocument = !!activeTextEditor.document.getText().trim(); | |
| 55 | - | |
| 56 | - if (hasExistingDocument) { | |
| 57 | - // Currently `isSearchAndReplace` will always provide a full file rewrite | |
| 58 | - // as the contents of `text`, so we can just instantly apply | |
| 59 | - if (isSearchAndReplace) { | |
| 60 | - const diffLinesGenerator = generateLines( | |
| 61 | - myersDiff(activeTextEditor.document.getText(), text), | |
| 62 | - ); | |
| 53 | + const hasExistingDocument = !!activeTextEditor.document.getText().trim(); | |
| 54 | + if (hasExistingDocument) { | |
| 55 | + // Currently `isSearchAndReplace` will always provide a full file rewrite | |
| 56 | + // as the contents of `text`, so we can just instantly apply | |
| 57 | + if (isSearchAndReplace) { | |
| 58 | + const diffLinesGenerator = generateLines( | |
| 59 | + myersDiff(activeTextEditor.document.getText(), text), | |
| 60 | + ); | |
| 63 | 61 | |
| 64 | - await this.verticalDiffManager.streamDiffLines( | |
| 65 | - diffLinesGenerator, | |
| 66 | - true, | |
| 67 | - streamId, | |
| 68 | - toolCallId, | |
| 69 | - ); | |
| 70 | - } else { | |
| 71 | - await this.handleExistingDocument( | |
| 72 | - activeTextEditor, | |
| 73 | - text, | |
| 74 | - streamId, | |
| 75 | - toolCallId, | |
| 76 | - ); | |
| 77 | - } | |
| 62 | + await this.verticalDiffManager.streamDiffLines( | |
| 63 | + diffLinesGenerator, | |
| 64 | + true, | |
| 65 | + streamId, | |
| 66 | + toolCallId, | |
| 67 | + ); | |
| 78 | 68 | } else { |
| 79 | - await this.handleEmptyDocument( | |
| 69 | + await this.handleExistingDocument( | |
| 80 | 70 | activeTextEditor, |
| 81 | 71 | text, |
| 82 | 72 | streamId, |
| 83 | 73 | toolCallId, |
| 84 | 74 | ); |
| 85 | 75 | } |
| 86 | - } finally { | |
| 87 | - await this.webviewProtocol.request("updateApplyState", { | |
| 76 | + } else { | |
| 77 | + await this.handleEmptyDocument( | |
| 78 | + activeTextEditor, | |
| 79 | + text, | |
| 88 | 80 | streamId, |
| 89 | - status: "done", | |
| 90 | 81 | toolCallId, |
| 91 | - }); | |
| 82 | + ); | |
| 92 | 83 | } |
| 93 | 84 | } |
| 94 | 85 |
modified extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +5 −0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | AutocompleteCodeSnippet, |
| 4 | 4 | AutocompleteSnippetType, |
| 5 | 5 | } from "core/autocomplete/snippets/types"; |
| 6 | +import { isSecurityConcern } from "core/indexing/ignore"; | |
| 6 | 7 | import { PosthogFeatureFlag, Telemetry } from "core/util/posthog"; |
| 7 | 8 | import { LRUCache } from "lru-cache"; |
| 8 | 9 | import * as vscode from "vscode"; |
| @@ -51,6 +52,10 @@ | ||
| 51 | 52 | private cacheCurrentSelectionContext = async ( |
| 52 | 53 | event: vscode.TextEditorSelectionChangeEvent, |
| 53 | 54 | ) => { |
| 55 | + const fsPath = event.textEditor.document.fileName; | |
| 56 | + if (isSecurityConcern(fsPath)) { | |
| 57 | + return; | |
| 58 | + } | |
| 54 | 59 | const filepath = event.textEditor.document.uri.toString(); |
| 55 | 60 | const line = event.selections[0].active.line; |
| 56 | 61 | const startLine = Math.max(0, line - this.numSurroundingLines); |
modified gui/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
added gui/src/components/StyledMarkdownPreview/SecureImageComponent.test.tsx +218 −0
| @@ -0,0 +1,218 @@ | ||
| 1 | +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; | |
| 2 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | +import { SecureImageComponent } from "./SecureImageComponent"; | |
| 4 | + | |
| 5 | +describe("SecureImageComponent", () => { | |
| 6 | + beforeEach(() => { | |
| 7 | + vi.clearAllMocks(); | |
| 8 | + }); | |
| 9 | + | |
| 10 | + describe("Default blocking behavior", () => { | |
| 11 | + it("should block images by default and show warning message", () => { | |
| 12 | + render(<SecureImageComponent src="https://example.com/image.jpg" />); | |
| 13 | + | |
| 14 | + expect( | |
| 15 | + screen.getByText( | |
| 16 | + /Image blocked for security.*External images can leak data/, | |
| 17 | + ), | |
| 18 | + ).toBeInTheDocument(); | |
| 19 | + expect(screen.getByText("Load Image")).toBeInTheDocument(); | |
| 20 | + expect(screen.queryByRole("img")).not.toBeInTheDocument(); | |
| 21 | + }); | |
| 22 | + | |
| 23 | + it("should display the image URL", () => { | |
| 24 | + const testUrl = "https://example.com/test-image.png"; | |
| 25 | + render(<SecureImageComponent src={testUrl} />); | |
| 26 | + | |
| 27 | + expect(screen.getByText(testUrl)).toBeInTheDocument(); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + it("should handle invalid src prop", () => { | |
| 31 | + render(<SecureImageComponent src={undefined} />); | |
| 32 | + | |
| 33 | + expect( | |
| 34 | + screen.getByText("[Invalid image: no source]"), | |
| 35 | + ).toBeInTheDocument(); | |
| 36 | + expect(screen.queryByText("Load Image")).not.toBeInTheDocument(); | |
| 37 | + }); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + describe("Query parameter detection", () => { | |
| 41 | + it("should detect and display query parameters", () => { | |
| 42 | + render( | |
| 43 | + <SecureImageComponent src="https://example.com/image.jpg?user=123&token=abc" />, | |
| 44 | + ); | |
| 45 | + | |
| 46 | + expect( | |
| 47 | + screen.getByText(/Warning: URL contains query parameters/), | |
| 48 | + ).toBeInTheDocument(); | |
| 49 | + expect(screen.getByText(/"user": "123"/)).toBeInTheDocument(); | |
| 50 | + expect(screen.getByText(/"token": "abc"/)).toBeInTheDocument(); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("should not show query parameter warning for URLs without parameters", () => { | |
| 54 | + render(<SecureImageComponent src="https://example.com/image.jpg" />); | |
| 55 | + | |
| 56 | + expect( | |
| 57 | + screen.queryByText(/Warning: URL contains query parameters/), | |
| 58 | + ).not.toBeInTheDocument(); | |
| 59 | + }); | |
| 60 | + | |
| 61 | + it("should handle relative URLs with query parameters", () => { | |
| 62 | + render( | |
| 63 | + <SecureImageComponent src="/images/test.jpg?id=456&session=xyz" />, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + expect( | |
| 67 | + screen.getByText(/Warning: URL contains query parameters/), | |
| 68 | + ).toBeInTheDocument(); | |
| 69 | + expect(screen.getByText(/"id": "456"/)).toBeInTheDocument(); | |
| 70 | + expect(screen.getByText(/"session": "xyz"/)).toBeInTheDocument(); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + it("should handle malformed URLs gracefully", () => { | |
| 74 | + render(<SecureImageComponent src="not-a-valid-url://image" />); | |
| 75 | + | |
| 76 | + // Should still display the URL even if it can't be parsed | |
| 77 | + expect(screen.getByText("not-a-valid-url://image")).toBeInTheDocument(); | |
| 78 | + expect(screen.getByText("Load Image")).toBeInTheDocument(); | |
| 79 | + }); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + describe("User interaction", () => { | |
| 83 | + it("should show image when Load Image button is clicked", () => { | |
| 84 | + const testUrl = "https://example.com/image.jpg"; | |
| 85 | + render(<SecureImageComponent src={testUrl} alt="Test image" />); | |
| 86 | + | |
| 87 | + // Initially no image | |
| 88 | + expect(screen.queryByRole("img")).not.toBeInTheDocument(); | |
| 89 | + | |
| 90 | + // Click load button | |
| 91 | + const loadButton = screen.getByText("Load Image"); | |
| 92 | + fireEvent.click(loadButton); | |
| 93 | + | |
| 94 | + // Image should now be displayed (query by tag since it might be role="presentation") | |
| 95 | + const image = screen.getByAltText("Test image"); | |
| 96 | + expect(image).toBeInTheDocument(); | |
| 97 | + expect(image).toHaveAttribute("src", testUrl); | |
| 98 | + expect(image).toHaveAttribute("alt", "Test image"); | |
| 99 | + | |
| 100 | + // Warning message should be gone | |
| 101 | + expect( | |
| 102 | + screen.queryByText( | |
| 103 | + /Image blocked for security.*External images can leak data/, | |
| 104 | + ), | |
| 105 | + ).not.toBeInTheDocument(); | |
| 106 | + }); | |
| 107 | + | |
| 108 | + it("should handle image load errors", async () => { | |
| 109 | + const testUrl = "https://example.com/broken-image.jpg"; | |
| 110 | + render(<SecureImageComponent src={testUrl} alt="broken image" />); | |
| 111 | + | |
| 112 | + // Click load button | |
| 113 | + const loadButton = screen.getByText("Load Image"); | |
| 114 | + fireEvent.click(loadButton); | |
| 115 | + | |
| 116 | + // Simulate image error (query by alt text since role might be presentation) | |
| 117 | + const image = screen.getByAltText("broken image"); | |
| 118 | + fireEvent.error(image); | |
| 119 | + | |
| 120 | + // Should show error message and hide image | |
| 121 | + await waitFor(() => { | |
| 122 | + expect(screen.getByText(/Failed to load image/)).toBeInTheDocument(); | |
| 123 | + expect(screen.queryByAltText("broken image")).not.toBeInTheDocument(); | |
| 124 | + }); | |
| 125 | + | |
| 126 | + // Load button should be available again | |
| 127 | + expect(screen.getByText("Load Image")).toBeInTheDocument(); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should pass through title and className props", () => { | |
| 131 | + render( | |
| 132 | + <SecureImageComponent | |
| 133 | + src="https://example.com/image.jpg" | |
| 134 | + alt="test image" | |
| 135 | + title="Image title" | |
| 136 | + className="custom-class" | |
| 137 | + />, | |
| 138 | + ); | |
| 139 | + | |
| 140 | + // Click load button | |
| 141 | + fireEvent.click(screen.getByText("Load Image")); | |
| 142 | + | |
| 143 | + // Check image has title (query by alt text) | |
| 144 | + const image = screen.getByAltText("test image"); | |
| 145 | + expect(image).toHaveAttribute("title", "Image title"); | |
| 146 | + | |
| 147 | + // Check container has className | |
| 148 | + const container = image.parentElement; | |
| 149 | + expect(container).toHaveClass("custom-class"); | |
| 150 | + }); | |
| 151 | + }); | |
| 152 | + | |
| 153 | + describe("Security features", () => { | |
| 154 | + it("should display query parameters as JSON for transparency", () => { | |
| 155 | + render( | |
| 156 | + <SecureImageComponent src="https://malicious.com/track.gif?email=user@example.com&id=12345&action=view" />, | |
| 157 | + ); | |
| 158 | + | |
| 159 | + // Should show all parameters clearly | |
| 160 | + expect( | |
| 161 | + screen.getByText(/Warning: URL contains query parameters/), | |
| 162 | + ).toBeInTheDocument(); | |
| 163 | + | |
| 164 | + // Check JSON is properly formatted | |
| 165 | + const preElement = screen.getByText(/"email": "user@example.com"/); | |
| 166 | + expect(preElement).toBeInTheDocument(); | |
| 167 | + expect(screen.getByText(/"id": "12345"/)).toBeInTheDocument(); | |
| 168 | + expect(screen.getByText(/"action": "view"/)).toBeInTheDocument(); | |
| 169 | + }); | |
| 170 | + | |
| 171 | + it("should handle encoded query parameters", () => { | |
| 172 | + render( | |
| 173 | + <SecureImageComponent src="https://example.com/img.png?data=%7B%22user%22%3A%22test%22%7D" />, | |
| 174 | + ); | |
| 175 | + | |
| 176 | + // Should decode and display the parameter | |
| 177 | + expect( | |
| 178 | + screen.getByText(/Warning: URL contains query parameters/), | |
| 179 | + ).toBeInTheDocument(); | |
| 180 | + // The decoded value should be shown in the pre element | |
| 181 | + const preElement = document.querySelector("pre"); | |
| 182 | + expect(preElement).toBeTruthy(); | |
| 183 | + // Check that the JSON contains the decoded data | |
| 184 | + expect(preElement?.textContent).toContain('"data"'); | |
| 185 | + // The value is decoded as a string containing JSON | |
| 186 | + expect(preElement?.textContent).toContain('"{'); | |
| 187 | + expect(preElement?.textContent).toContain("user"); | |
| 188 | + expect(preElement?.textContent).toContain("test"); | |
| 189 | + }); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + describe("Alt text handling", () => { | |
| 193 | + it("should use empty string for alt when not provided", () => { | |
| 194 | + render(<SecureImageComponent src="https://example.com/image.jpg" />); | |
| 195 | + | |
| 196 | + fireEvent.click(screen.getByText("Load Image")); | |
| 197 | + | |
| 198 | + // Query by tag name since empty alt makes it role="presentation" | |
| 199 | + const images = document.querySelectorAll("img"); | |
| 200 | + expect(images.length).toBe(1); | |
| 201 | + expect(images[0]).toHaveAttribute("alt", ""); | |
| 202 | + }); | |
| 203 | + | |
| 204 | + it("should use provided alt text", () => { | |
| 205 | + render( | |
| 206 | + <SecureImageComponent | |
| 207 | + src="https://example.com/image.jpg" | |
| 208 | + alt="Description of image" | |
| 209 | + />, | |
| 210 | + ); | |
| 211 | + | |
| 212 | + fireEvent.click(screen.getByText("Load Image")); | |
| 213 | + | |
| 214 | + const image = screen.getByAltText("Description of image"); | |
| 215 | + expect(image).toHaveAttribute("alt", "Description of image"); | |
| 216 | + }); | |
| 217 | + }); | |
| 218 | +}); |
added gui/src/components/StyledMarkdownPreview/SecureImageComponent.tsx +168 −0
| @@ -0,0 +1,168 @@ | ||
| 1 | +import React, { useState } from "react"; | |
| 2 | +import styled from "styled-components"; | |
| 3 | +import { | |
| 4 | + lightGray, | |
| 5 | + vscBackground, | |
| 6 | + vscButtonBackground, | |
| 7 | + vscButtonForeground, | |
| 8 | + vscForeground, | |
| 9 | + vscInputBorder, | |
| 10 | +} from "../"; | |
| 11 | + | |
| 12 | +const ImagePlaceholder = styled.div` | |
| 13 | + border: 1px solid ${vscInputBorder}; | |
| 14 | + border-radius: 4px; | |
| 15 | + padding: 12px; | |
| 16 | + margin: 8px 0; | |
| 17 | + background-color: ${vscBackground}; | |
| 18 | + display: inline-block; | |
| 19 | + max-width: 100%; | |
| 20 | +`; | |
| 21 | + | |
| 22 | +const WarningText = styled.div` | |
| 23 | + color: ${lightGray}; | |
| 24 | + font-size: 12px; | |
| 25 | + margin-bottom: 8px; | |
| 26 | +`; | |
| 27 | + | |
| 28 | +const UrlDisplay = styled.div` | |
| 29 | + font-family: var(--vscode-editor-font-family); | |
| 30 | + font-size: 12px; | |
| 31 | + color: ${vscForeground}; | |
| 32 | + word-break: break-all; | |
| 33 | + margin: 8px 0; | |
| 34 | + padding: 8px; | |
| 35 | + background-color: rgba(0, 0, 0, 0.1); | |
| 36 | + border-radius: 3px; | |
| 37 | +`; | |
| 38 | + | |
| 39 | +const QueryParamsDisplay = styled.div` | |
| 40 | + font-family: var(--vscode-editor-font-family); | |
| 41 | + font-size: 11px; | |
| 42 | + color: ${vscForeground}; | |
| 43 | + margin: 8px 0; | |
| 44 | + padding: 8px; | |
| 45 | + background-color: rgba(128, 128, 128, 0.1); | |
| 46 | + border-radius: 3px; | |
| 47 | + border: 1px solid ${lightGray}; | |
| 48 | +`; | |
| 49 | + | |
| 50 | +const LoadButton = styled.button` | |
| 51 | + background-color: ${vscButtonBackground}; | |
| 52 | + color: ${vscButtonForeground}; | |
| 53 | + border: 1px solid ${vscInputBorder}; | |
| 54 | + padding: 6px 12px; | |
| 55 | + border-radius: 3px; | |
| 56 | + cursor: pointer; | |
| 57 | + font-size: 12px; | |
| 58 | + margin-top: 8px; | |
| 59 | + | |
| 60 | + &:hover { | |
| 61 | + opacity: 0.9; | |
| 62 | + } | |
| 63 | + | |
| 64 | + &:active { | |
| 65 | + transform: translateY(1px); | |
| 66 | + } | |
| 67 | +`; | |
| 68 | + | |
| 69 | +const ImageContainer = styled.div` | |
| 70 | + max-width: 100%; | |
| 71 | + display: inline-block; | |
| 72 | + | |
| 73 | + img { | |
| 74 | + max-width: 100%; | |
| 75 | + height: auto; | |
| 76 | + display: block; | |
| 77 | + } | |
| 78 | +`; | |
| 79 | + | |
| 80 | +interface SecureImageComponentProps { | |
| 81 | + src?: string; | |
| 82 | + alt?: string; | |
| 83 | + title?: string; | |
| 84 | + className?: string; | |
| 85 | +} | |
| 86 | + | |
| 87 | +export const SecureImageComponent: React.FC<SecureImageComponentProps> = ({ | |
| 88 | + src, | |
| 89 | + alt, | |
| 90 | + title, | |
| 91 | + className, | |
| 92 | +}) => { | |
| 93 | + const [showImage, setShowImage] = useState(false); | |
| 94 | + const [imageError, setImageError] = useState(false); | |
| 95 | + | |
| 96 | + if (!src) { | |
| 97 | + return <span>[Invalid image: no source]</span>; | |
| 98 | + } | |
| 99 | + | |
| 100 | + // Parse URL to check for query parameters | |
| 101 | + let queryParams: Record<string, string> = {}; | |
| 102 | + let hasQueryParams = false; | |
| 103 | + | |
| 104 | + try { | |
| 105 | + const url = new URL(src, window.location.href); | |
| 106 | + const params = new URLSearchParams(url.search); | |
| 107 | + params.forEach((value, key) => { | |
| 108 | + queryParams[key] = value; | |
| 109 | + hasQueryParams = true; | |
| 110 | + }); | |
| 111 | + } catch (e) { | |
| 112 | + // If URL parsing fails, treat src as a relative path | |
| 113 | + const queryIndex = src.indexOf("?"); | |
| 114 | + if (queryIndex > -1) { | |
| 115 | + hasQueryParams = true; | |
| 116 | + const params = new URLSearchParams(src.substring(queryIndex)); | |
| 117 | + params.forEach((value, key) => { | |
| 118 | + queryParams[key] = value; | |
| 119 | + }); | |
| 120 | + } | |
| 121 | + } | |
| 122 | + | |
| 123 | + if (showImage && !imageError) { | |
| 124 | + return ( | |
| 125 | + <ImageContainer className={className}> | |
| 126 | + <img | |
| 127 | + src={src} | |
| 128 | + alt={alt || ""} | |
| 129 | + title={title} | |
| 130 | + onError={() => { | |
| 131 | + setImageError(true); | |
| 132 | + setShowImage(false); | |
| 133 | + }} | |
| 134 | + /> | |
| 135 | + </ImageContainer> | |
| 136 | + ); | |
| 137 | + } | |
| 138 | + | |
| 139 | + return ( | |
| 140 | + <ImagePlaceholder> | |
| 141 | + <WarningText> | |
| 142 | + Image blocked for security. External images can leak data through URL | |
| 143 | + parameters. Click to load if you trust the source. | |
| 144 | + </WarningText> | |
| 145 | + | |
| 146 | + <UrlDisplay> | |
| 147 | + <strong>URL:</strong> {src} | |
| 148 | + </UrlDisplay> | |
| 149 | + | |
| 150 | + {hasQueryParams && ( | |
| 151 | + <QueryParamsDisplay> | |
| 152 | + <strong>Warning: URL contains query parameters:</strong> | |
| 153 | + <pre style={{ margin: "4px 0", fontSize: "11px" }}> | |
| 154 | + {JSON.stringify(queryParams, null, 2)} | |
| 155 | + </pre> | |
| 156 | + </QueryParamsDisplay> | |
| 157 | + )} | |
| 158 | + | |
| 159 | + {imageError && ( | |
| 160 | + <div style={{ color: lightGray, fontSize: "12px", marginTop: "8px" }}> | |
| 161 | + Failed to load image. The URL may be invalid or inaccessible. | |
| 162 | + </div> | |
| 163 | + )} | |
| 164 | + | |
| 165 | + <LoadButton onClick={() => setShowImage(true)}>Load Image</LoadButton> | |
| 166 | + </ImagePlaceholder> | |
| 167 | + ); | |
| 168 | +}; |
modified gui/src/components/StyledMarkdownPreview/index.tsx +11 −0
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | import "./markdown.css"; |
| 24 | 24 | import MermaidBlock from "./MermaidBlock"; |
| 25 | 25 | import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin"; |
| 26 | +import { SecureImageComponent } from "./SecureImageComponent"; | |
| 26 | 27 | import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; |
| 27 | 28 | import SymbolLink from "./SymbolLink"; |
| 28 | 29 | import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; |
| @@ -346,6 +347,16 @@ | ||
| 346 | 347 | } |
| 347 | 348 | return <code {...codeProps}>{codeProps.children}</code>; |
| 348 | 349 | }, |
| 350 | + img: ({ ...imgProps }) => { | |
| 351 | + return ( | |
| 352 | + <SecureImageComponent | |
| 353 | + src={imgProps.src} | |
| 354 | + alt={imgProps.alt} | |
| 355 | + title={imgProps.title} | |
| 356 | + className={imgProps.className} | |
| 357 | + /> | |
| 358 | + ); | |
| 359 | + }, | |
| 349 | 360 | }, |
| 350 | 361 | }, |
| 351 | 362 | }); |
modified gui/src/components/mainInput/Lump/EditBlockButton.tsx +3 −3
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | type SectionKey = Exclude< |
| 8 | 8 | keyof ConfigYaml, |
| 9 | - "name" | "version" | "schema" | "metadata" | |
| 9 | + "name" | "version" | "schema" | "metadata" | "env" | |
| 10 | 10 | >; |
| 11 | 11 | |
| 12 | 12 | interface EditBlockButtonProps<T extends SectionKey> { |
| @@ -42,10 +42,10 @@ | ||
| 42 | 42 | element: { sourceFile }, |
| 43 | 43 | }); |
| 44 | 44 | } else if (block && isUsesBlock(block)) { |
| 45 | - openUrl(`${block.uses}/new-version`); | |
| 45 | + void openUrl(`${block.uses}/new-version`); | |
| 46 | 46 | } else if (selectedProfile?.fullSlug) { |
| 47 | 47 | const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`; |
| 48 | - openUrl(`${slug}/new-version`); | |
| 48 | + void openUrl(`${slug}/new-version`); | |
| 49 | 49 | } |
| 50 | 50 | }; |
| 51 | 51 |
modified gui/src/hooks/ParallelListeners.tsx +5 −91
| @@ -1,14 +1,10 @@ | ||
| 1 | 1 | import { useCallback, useContext, useEffect, useRef } from "react"; |
| 2 | 2 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 3 | 3 | |
| 4 | -import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; | |
| 5 | 4 | import { FromCoreProtocol } from "core/protocol"; |
| 6 | 5 | import { useAppDispatch, useAppSelector } from "../redux/hooks"; |
| 7 | 6 | import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice"; |
| 8 | -import { | |
| 9 | - setLastNonEditSessionEmpty, | |
| 10 | - updateEditStateApplyState, | |
| 11 | -} from "../redux/slices/editState"; | |
| 7 | +import { setLastNonEditSessionEmpty } from "../redux/slices/editState"; | |
| 12 | 8 | import { updateIndexingStatus } from "../redux/slices/indexingSlice"; |
| 13 | 9 | import { |
| 14 | 10 | initializeProfilePreferences, |
| @@ -17,27 +13,21 @@ | ||
| 17 | 13 | setSelectedProfile, |
| 18 | 14 | } from "../redux/slices/profilesSlice"; |
| 19 | 15 | import { |
| 20 | - acceptToolCall, | |
| 21 | 16 | addContextItemsAtIndex, |
| 22 | 17 | setHasReasoningEnabled, |
| 23 | 18 | setIsSessionMetadataLoading, |
| 24 | - updateApplyState, | |
| 25 | 19 | } from "../redux/slices/sessionSlice"; |
| 26 | 20 | import { setTTSActive } from "../redux/slices/uiSlice"; |
| 27 | -import { exitEdit } from "../redux/thunks/edit"; | |
| 28 | -import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall"; | |
| 29 | 21 | |
| 30 | -import { store } from "../redux/store"; | |
| 31 | 22 | import { cancelStream } from "../redux/thunks/cancelStream"; |
| 23 | +import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate"; | |
| 32 | 24 | import { refreshSessionMetadata } from "../redux/thunks/session"; |
| 33 | 25 | import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; |
| 34 | -import { findToolCallById, logToolUsage } from "../redux/util"; | |
| 35 | 26 | import { |
| 36 | 27 | setDocumentStylesFromLocalStorage, |
| 37 | 28 | setDocumentStylesFromTheme, |
| 38 | 29 | } from "../styles/theme"; |
| 39 | 30 | import { isJetBrains } from "../util"; |
| 40 | -import { logAgentModeEditOutcome } from "../util/editOutcomeLogger"; | |
| 41 | 31 | import { setLocalStorage } from "../util/localStorage"; |
| 42 | 32 | import { migrateLocalStorage } from "../util/migrateLocalStorage"; |
| 43 | 33 | import { useWebviewListener } from "./useWebviewListener"; |
| @@ -51,9 +41,7 @@ | ||
| 51 | 41 | (store) => store.profiles.selectedProfileId, |
| 52 | 42 | ); |
| 53 | 43 | const hasDoneInitialConfigLoad = useRef(false); |
| 54 | - const autoAcceptEditToolDiffs = useAppSelector( | |
| 55 | - (store) => store.config.config.ui?.autoAcceptEditToolDiffs, | |
| 56 | - ); | |
| 44 | + | |
| 57 | 45 | // Load symbols for chat on any session change |
| 58 | 46 | const sessionId = useAppSelector((state) => state.session.id); |
| 59 | 47 | |
| @@ -235,83 +223,9 @@ | ||
| 235 | 223 | useWebviewListener( |
| 236 | 224 | "updateApplyState", |
| 237 | 225 | async (state) => { |
| 238 | - if (state.streamId === EDIT_MODE_STREAM_ID) { | |
| 239 | - dispatch(updateEditStateApplyState(state)); | |
| 240 | - | |
| 241 | - if (state.status === "closed") { | |
| 242 | - const toolCallState = findToolCallById( | |
| 243 | - store.getState().session.history, | |
| 244 | - state.toolCallId!, | |
| 245 | - ); | |
| 246 | - if (toolCallState) { | |
| 247 | - logToolUsage(toolCallState, true, true, ideMessenger); | |
| 248 | - } | |
| 249 | - void dispatch(exitEdit({})); | |
| 250 | - } | |
| 251 | - } else { | |
| 252 | - // chat or agent | |
| 253 | - dispatch(updateApplyState(state)); | |
| 254 | - | |
| 255 | - // Handle apply status updates - use toolCallId from event payload | |
| 256 | - if (state.toolCallId) { | |
| 257 | - if (state.status === "done" && autoAcceptEditToolDiffs) { | |
| 258 | - ideMessenger.post("acceptDiff", { | |
| 259 | - streamId: state.streamId, | |
| 260 | - filepath: state.filepath, | |
| 261 | - }); | |
| 262 | - } | |
| 263 | - if (state.status === "closed") { | |
| 264 | - // Find the tool call to check if it was canceled | |
| 265 | - const toolCallState = findToolCallById( | |
| 266 | - store.getState().session.history, | |
| 267 | - state.toolCallId, | |
| 268 | - ); | |
| 269 | - | |
| 270 | - if (toolCallState) { | |
| 271 | - const accepted = toolCallState.status !== "canceled"; | |
| 272 | - | |
| 273 | - logToolUsage(toolCallState, accepted, true, ideMessenger); | |
| 274 | - | |
| 275 | - // Log edit outcome for Agent Mode | |
| 276 | - const applyState = store | |
| 277 | - .getState() | |
| 278 | - .session.codeBlockApplyStates.states.find( | |
| 279 | - (s) => s.streamId === state.streamId, | |
| 280 | - ); | |
| 281 | - | |
| 282 | - if (applyState) { | |
| 283 | - void logAgentModeEditOutcome( | |
| 284 | - toolCallState, | |
| 285 | - applyState, | |
| 286 | - accepted, | |
| 287 | - ideMessenger, | |
| 288 | - ); | |
| 289 | - } | |
| 290 | - | |
| 291 | - if (accepted) { | |
| 292 | - dispatch( | |
| 293 | - acceptToolCall({ | |
| 294 | - toolCallId: state.toolCallId, | |
| 295 | - }), | |
| 296 | - ); | |
| 297 | - void dispatch( | |
| 298 | - streamResponseAfterToolCall({ | |
| 299 | - toolCallId: state.toolCallId, | |
| 300 | - }), | |
| 301 | - ); | |
| 302 | - } | |
| 303 | - } | |
| 304 | - // const output: ContextItem = { | |
| 305 | - // name: "Edit tool output", | |
| 306 | - // content: "Completed edit", | |
| 307 | - // description: "", | |
| 308 | - // }; | |
| 309 | - // dispatch(setToolCallOutput([])); | |
| 310 | - } | |
| 311 | - } | |
| 312 | - } | |
| 226 | + void dispatch(handleApplyStateUpdate(state)); | |
| 313 | 227 | }, |
| 314 | - [autoAcceptEditToolDiffs, ideMessenger], | |
| 228 | + [], | |
| 315 | 229 | ); |
| 316 | 230 | |
| 317 | 231 | useEffect(() => { |
modified gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +8 −9
| @@ -1,19 +1,16 @@ | ||
| 1 | 1 | import { BuiltInToolNames } from "core/tools/builtIn"; |
| 2 | +import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; | |
| 2 | 3 | import { |
| 3 | 4 | addAndSelectMockLlm, |
| 4 | 5 | triggerConfigUpdate, |
| 5 | 6 | } from "../../../util/test/config"; |
| 6 | 7 | import { renderWithProviders } from "../../../util/test/render"; |
| 7 | 8 | import { Chat } from "../Chat"; |
| 8 | -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; | |
| 9 | 9 | |
| 10 | 10 | import { waitFor } from "@testing-library/dom"; |
| 11 | 11 | import { act } from "@testing-library/react"; |
| 12 | 12 | import { ChatMessage } from "core"; |
| 13 | -import { | |
| 14 | - setToolPolicy, | |
| 15 | - toggleToolSetting, | |
| 16 | -} from "../../../redux/slices/uiSlice"; | |
| 13 | +import { setToolPolicy } from "../../../redux/slices/uiSlice"; | |
| 17 | 14 | import { |
| 18 | 15 | getElementByTestId, |
| 19 | 16 | getElementByText, |
| @@ -63,6 +60,7 @@ | ||
| 63 | 60 | |
| 64 | 61 | ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; |
| 65 | 62 | const messengerPostSpy = vi.spyOn(ideMessenger, "post"); |
| 63 | + const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); | |
| 66 | 64 | |
| 67 | 65 | addAndSelectMockLlm(store, ideMessenger); |
| 68 | 66 | |
| @@ -92,7 +90,7 @@ | ||
| 92 | 90 | |
| 93 | 91 | // Tool call, check that applyToFile was called for edit |
| 94 | 92 | await waitFor(() => { |
| 95 | - expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { | |
| 93 | + expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { | |
| 96 | 94 | streamId: expect.any(String), |
| 97 | 95 | filepath: EDIT_FILE_URI, |
| 98 | 96 | text: EDIT_CHANGES, |
| @@ -101,7 +99,7 @@ | ||
| 101 | 99 | }); |
| 102 | 100 | |
| 103 | 101 | // Extract stream ID and initiate mock streaming |
| 104 | - const streamId = messengerPostSpy.mock.calls.find( | |
| 102 | + const streamId = messengerRequestSpy.mock.calls.find( | |
| 105 | 103 | (call) => call[0] === "applyToFile", |
| 106 | 104 | )?.[1]?.streamId; |
| 107 | 105 | expect(streamId).toBeDefined(); |
| @@ -172,6 +170,7 @@ | ||
| 172 | 170 | |
| 173 | 171 | ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; |
| 174 | 172 | const messengerPostSpy = vi.spyOn(ideMessenger, "post"); |
| 173 | + const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); | |
| 175 | 174 | |
| 176 | 175 | addAndSelectMockLlm(store, ideMessenger); |
| 177 | 176 | |
| @@ -219,7 +218,7 @@ | ||
| 219 | 218 | ); |
| 220 | 219 | // Tool call, check that applyToFile was called for edit |
| 221 | 220 | await waitFor(() => { |
| 222 | - expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { | |
| 221 | + expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { | |
| 223 | 222 | streamId: expect.any(String), |
| 224 | 223 | filepath: EDIT_FILE_URI, |
| 225 | 224 | text: EDIT_CHANGES, |
| @@ -228,7 +227,7 @@ | ||
| 228 | 227 | }); |
| 229 | 228 | |
| 230 | 229 | // Extract stream ID and initiate mock streaming |
| 231 | - const streamId = messengerPostSpy.mock.calls.find( | |
| 230 | + const streamId = messengerRequestSpy.mock.calls.find( | |
| 232 | 231 | (call) => call[0] === "applyToFile", |
| 233 | 232 | )?.[1]?.streamId; |
| 234 | 233 | expect(streamId).toBeDefined(); |
added gui/src/redux/thunks/handleApplyStateUpdate.ts +153 −0
| @@ -0,0 +1,153 @@ | ||
| 1 | +import { createAsyncThunk } from "@reduxjs/toolkit"; | |
| 2 | +import { ApplyState } from "core"; | |
| 3 | +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; | |
| 4 | +import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger"; | |
| 5 | +import { | |
| 6 | + selectApplyStateByToolCallId, | |
| 7 | + selectToolCallById, | |
| 8 | +} from "../selectors/selectToolCalls"; | |
| 9 | +import { updateEditStateApplyState } from "../slices/editState"; | |
| 10 | +import { | |
| 11 | + acceptToolCall, | |
| 12 | + errorToolCall, | |
| 13 | + updateApplyState, | |
| 14 | + updateToolCallOutput, | |
| 15 | +} from "../slices/sessionSlice"; | |
| 16 | +import { ThunkApiType } from "../store"; | |
| 17 | +import { findToolCallById, logToolUsage } from "../util"; | |
| 18 | +import { exitEdit } from "./edit"; | |
| 19 | +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; | |
| 20 | + | |
| 21 | +export const handleApplyStateUpdate = createAsyncThunk< | |
| 22 | + void, | |
| 23 | + ApplyState, | |
| 24 | + ThunkApiType | |
| 25 | +>( | |
| 26 | + "apply/handleStateUpdate", | |
| 27 | + async (applyState, { dispatch, getState, extra }) => { | |
| 28 | + if (applyState.streamId === EDIT_MODE_STREAM_ID) { | |
| 29 | + dispatch(updateEditStateApplyState(applyState)); | |
| 30 | + | |
| 31 | + if (applyState.status === "closed") { | |
| 32 | + const toolCallState = findToolCallById( | |
| 33 | + getState().session.history, | |
| 34 | + applyState.toolCallId!, | |
| 35 | + ); | |
| 36 | + if (toolCallState) { | |
| 37 | + logToolUsage(toolCallState, true, true, extra.ideMessenger); | |
| 38 | + } | |
| 39 | + void dispatch(exitEdit({})); | |
| 40 | + } | |
| 41 | + } else { | |
| 42 | + // chat or agent | |
| 43 | + dispatch(updateApplyState(applyState)); | |
| 44 | + | |
| 45 | + // Handle apply status updates - use toolCallId from event payload | |
| 46 | + if (applyState.toolCallId) { | |
| 47 | + if ( | |
| 48 | + applyState.status === "done" && | |
| 49 | + getState().config.config?.ui?.autoAcceptEditToolDiffs | |
| 50 | + ) { | |
| 51 | + extra.ideMessenger.post("acceptDiff", { | |
| 52 | + streamId: applyState.streamId, | |
| 53 | + filepath: applyState.filepath, | |
| 54 | + }); | |
| 55 | + } | |
| 56 | + if (applyState.status === "closed") { | |
| 57 | + // Find the tool call to check if it was canceled | |
| 58 | + const toolCallState = findToolCallById( | |
| 59 | + getState().session.history, | |
| 60 | + applyState.toolCallId, | |
| 61 | + ); | |
| 62 | + | |
| 63 | + if (toolCallState) { | |
| 64 | + const accepted = toolCallState.status !== "canceled"; | |
| 65 | + | |
| 66 | + logToolUsage(toolCallState, accepted, true, extra.ideMessenger); | |
| 67 | + | |
| 68 | + // Log edit outcome for Agent Mode | |
| 69 | + const newApplyState = | |
| 70 | + getState().session.codeBlockApplyStates.states.find( | |
| 71 | + (s) => s.streamId === applyState.streamId, | |
| 72 | + ); | |
| 73 | + const newState = getState(); | |
| 74 | + if (newApplyState) { | |
| 75 | + void logAgentModeEditOutcome( | |
| 76 | + newState.session.history, | |
| 77 | + newState.config.config, | |
| 78 | + toolCallState, | |
| 79 | + newApplyState, | |
| 80 | + accepted, | |
| 81 | + extra.ideMessenger, | |
| 82 | + ); | |
| 83 | + } | |
| 84 | + | |
| 85 | + if (accepted) { | |
| 86 | + if (toolCallState.status !== "errored") { | |
| 87 | + dispatch( | |
| 88 | + acceptToolCall({ | |
| 89 | + toolCallId: applyState.toolCallId, | |
| 90 | + }), | |
| 91 | + ); | |
| 92 | + } | |
| 93 | + | |
| 94 | + void dispatch( | |
| 95 | + streamResponseAfterToolCall({ | |
| 96 | + toolCallId: applyState.toolCallId, | |
| 97 | + }), | |
| 98 | + ); | |
| 99 | + } | |
| 100 | + } | |
| 101 | + // TODO return output from edit tools so the model knows the result | |
| 102 | + } | |
| 103 | + } | |
| 104 | + } | |
| 105 | + }, | |
| 106 | +); | |
| 107 | + | |
| 108 | +export const handleEditToolApplyError = createAsyncThunk< | |
| 109 | + void, | |
| 110 | + { toolCallId: string }, | |
| 111 | + ThunkApiType | |
| 112 | +>( | |
| 113 | + "apply/handleEditError", | |
| 114 | + async ({ toolCallId }, { dispatch, getState, extra }) => { | |
| 115 | + const state = getState(); | |
| 116 | + | |
| 117 | + const toolCallState = selectToolCallById(state, toolCallId); | |
| 118 | + const applyState = selectApplyStateByToolCallId(state, toolCallId); | |
| 119 | + if ( | |
| 120 | + toolCallState && | |
| 121 | + applyState && | |
| 122 | + applyState.status !== "closed" && | |
| 123 | + toolCallState.status === "calling" | |
| 124 | + ) { | |
| 125 | + dispatch( | |
| 126 | + errorToolCall({ | |
| 127 | + toolCallId, | |
| 128 | + }), | |
| 129 | + ); | |
| 130 | + dispatch( | |
| 131 | + updateToolCallOutput({ | |
| 132 | + toolCallId, | |
| 133 | + contextItems: [ | |
| 134 | + { | |
| 135 | + icon: "problems", | |
| 136 | + name: "Apply Error", | |
| 137 | + description: "Failed to apply changes", | |
| 138 | + content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`, | |
| 139 | + hidden: false, | |
| 140 | + }, | |
| 141 | + ], | |
| 142 | + }), | |
| 143 | + ); | |
| 144 | + void dispatch( | |
| 145 | + handleApplyStateUpdate({ | |
| 146 | + status: "closed", | |
| 147 | + streamId: applyState.streamId, | |
| 148 | + toolCallId, | |
| 149 | + }), | |
| 150 | + ); | |
| 151 | + } | |
| 152 | + }, | |
| 153 | +); |
modified gui/src/util/clientTools/editImpl.ts +25 −7
| @@ -1,5 +1,7 @@ | ||
| 1 | 1 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 2 | 2 | import { v4 as uuid } from "uuid"; |
| 3 | +import { updateApplyState } from "../../redux/slices/sessionSlice"; | |
| 4 | +import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate"; | |
| 3 | 5 | import { ClientToolImpl } from "./callClientTool"; |
| 4 | 6 | export const editToolImpl: ClientToolImpl = async ( |
| 5 | 7 | args, |
| @@ -19,13 +21,29 @@ | ||
| 19 | 21 | throw new Error(`${args.filepath} does not exist`); |
| 20 | 22 | } |
| 21 | 23 | const streamId = uuid(); |
| 22 | - extras.ideMessenger.post("applyToFile", { | |
| 23 | - streamId, | |
| 24 | - text: args.changes, | |
| 25 | - toolCallId, | |
| 26 | - filepath: firstUriMatch, | |
| 27 | - }); | |
| 28 | - | |
| 24 | + extras.dispatch( | |
| 25 | + updateApplyState({ | |
| 26 | + streamId, | |
| 27 | + toolCallId, | |
| 28 | + status: "not-started", | |
| 29 | + }), | |
| 30 | + ); | |
| 31 | + void extras.ideMessenger | |
| 32 | + .request("applyToFile", { | |
| 33 | + streamId, | |
| 34 | + text: args.changes, | |
| 35 | + toolCallId, | |
| 36 | + filepath: firstUriMatch, | |
| 37 | + }) | |
| 38 | + .then((res) => { | |
| 39 | + if (res.status === "error") { | |
| 40 | + void extras.dispatch( | |
| 41 | + handleEditToolApplyError({ | |
| 42 | + toolCallId, | |
| 43 | + }), | |
| 44 | + ); | |
| 45 | + } | |
| 46 | + }); | |
| 29 | 47 | return { |
| 30 | 48 | respondImmediately: false, |
| 31 | 49 | output: undefined, // No immediate output. |
modified gui/src/util/clientTools/searchReplaceImpl.test.ts +0 −26
| @@ -581,32 +581,6 @@ | ||
| 581 | 581 | ), |
| 582 | 582 | ).rejects.toThrow("Failed to apply search and replace: File read error"); |
| 583 | 583 | }); |
| 584 | - | |
| 585 | - it("should handle applyToFile errors", async () => { | |
| 586 | - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); | |
| 587 | - mockParseAllSearchReplaceBlocks.mockReturnValue([ | |
| 588 | - { | |
| 589 | - isComplete: true, | |
| 590 | - searchContent: "content", | |
| 591 | - replaceContent: "replacement", | |
| 592 | - }, | |
| 593 | - ]); | |
| 594 | - mockIdeMessenger.ide.readFile.mockResolvedValue("content"); | |
| 595 | - mockFindSearchMatch.mockReturnValue({ | |
| 596 | - startIndex: 0, | |
| 597 | - endIndex: 7, | |
| 598 | - strategyName: "exactMatch", | |
| 599 | - }); | |
| 600 | - mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed")); | |
| 601 | - | |
| 602 | - await expect( | |
| 603 | - searchReplaceToolImpl( | |
| 604 | - { filepath: "test.txt", diffs: ["mock diff content"] }, | |
| 605 | - "tool-call-id", | |
| 606 | - mockExtras, | |
| 607 | - ), | |
| 608 | - ).rejects.toThrow("Failed to apply search and replace: Apply failed"); | |
| 609 | - }); | |
| 610 | 584 | }); |
| 611 | 585 | |
| 612 | 586 | describe("edge cases", () => { |
modified gui/src/util/clientTools/searchReplaceImpl.ts +27 −8
| @@ -3,6 +3,8 @@ | ||
| 3 | 3 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 4 | 4 | import posthog from "posthog-js"; |
| 5 | 5 | import { v4 as uuid } from "uuid"; |
| 6 | +import { updateApplyState } from "../../redux/slices/sessionSlice"; | |
| 7 | +import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate"; | |
| 6 | 8 | import { ClientToolImpl } from "./callClientTool"; |
| 7 | 9 | |
| 8 | 10 | export const searchReplaceToolImpl: ClientToolImpl = async ( |
| @@ -81,14 +83,31 @@ | ||
| 81 | 83 | // Single applyToFile call with all accumulated changes |
| 82 | 84 | // This works becaues of our logic in `applyCodeBlock` that determines |
| 83 | 85 | // that the full file rewrite here can be applied instantly, so the diff |
| 84 | - // lines are just st | |
| 85 | - await extras.ideMessenger.request("applyToFile", { | |
| 86 | - streamId, | |
| 87 | - toolCallId, | |
| 88 | - text: currentContent, | |
| 89 | - filepath: resolvedFilepath, | |
| 90 | - isSearchAndReplace: true, | |
| 91 | - }); | |
| 86 | + // lines are generated with meyers diff and streamed instantaneously | |
| 87 | + extras.dispatch( | |
| 88 | + updateApplyState({ | |
| 89 | + streamId, | |
| 90 | + toolCallId, | |
| 91 | + status: "not-started", | |
| 92 | + }), | |
| 93 | + ); | |
| 94 | + void extras.ideMessenger | |
| 95 | + .request("applyToFile", { | |
| 96 | + streamId, | |
| 97 | + toolCallId, | |
| 98 | + text: currentContent, | |
| 99 | + filepath: resolvedFilepath, | |
| 100 | + isSearchAndReplace: true, | |
| 101 | + }) | |
| 102 | + .then((res) => { | |
| 103 | + if (res.status === "error") { | |
| 104 | + void extras.dispatch( | |
| 105 | + handleEditToolApplyError({ | |
| 106 | + toolCallId, | |
| 107 | + }), | |
| 108 | + ); | |
| 109 | + } | |
| 110 | + }); | |
| 92 | 111 | |
| 93 | 112 | // Return success - applyToFile will handle the completion state |
| 94 | 113 | return { |
modified gui/src/util/editOutcomeLogger.test.ts +33 −3
| @@ -1,5 +1,10 @@ | ||
| 1 | -import { ApplyState, ToolCallState } from "core"; | |
| 1 | +import { | |
| 2 | + ApplyState, | |
| 3 | + BrowserSerializedContinueConfig, | |
| 4 | + ToolCallState, | |
| 5 | +} from "core"; | |
| 2 | 6 | import { describe, expect, it, vi } from "vitest"; |
| 7 | +import { EMPTY_CONFIG } from "../redux/slices/configSlice"; | |
| 3 | 8 | import { assembleEditOutcomeData } from "./editOutcomeLogger"; |
| 4 | 9 | |
| 5 | 10 | vi.mock("../redux/store", () => ({ |
| @@ -17,6 +22,19 @@ | ||
| 17 | 22 | }, |
| 18 | 23 | })); |
| 19 | 24 | |
| 25 | +const EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED: BrowserSerializedContinueConfig = { | |
| 26 | + ...EMPTY_CONFIG, | |
| 27 | + selectedModelByRole: { | |
| 28 | + ...EMPTY_CONFIG.selectedModelByRole, | |
| 29 | + chat: { | |
| 30 | + provider: "test", | |
| 31 | + model: "test-model", | |
| 32 | + title: "Test model", | |
| 33 | + underlyingProviderName: "provider", | |
| 34 | + }, | |
| 35 | + }, | |
| 36 | +}; | |
| 37 | + | |
| 20 | 38 | describe("assembleEditOutcomeData", () => { |
| 21 | 39 | it("should assemble complete edit outcome data correctly", () => { |
| 22 | 40 | const toolCallState: ToolCallState = { |
| @@ -37,7 +55,13 @@ | ||
| 37 | 55 | fileContent: "const new = 2;\nconst another = 3;", |
| 38 | 56 | }; |
| 39 | 57 | |
| 40 | - const result = assembleEditOutcomeData(toolCallState, applyState, true); | |
| 58 | + const result = assembleEditOutcomeData( | |
| 59 | + [], | |
| 60 | + EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED, | |
| 61 | + toolCallState, | |
| 62 | + applyState, | |
| 63 | + true, | |
| 64 | + ); | |
| 41 | 65 | console.log(result); |
| 42 | 66 | |
| 43 | 67 | expect(result).toMatchObject({ |
| @@ -71,7 +95,13 @@ | ||
| 71 | 95 | fileContent: "", |
| 72 | 96 | }; |
| 73 | 97 | |
| 74 | - const result = assembleEditOutcomeData(toolCallState, applyState, false); | |
| 98 | + const result = assembleEditOutcomeData( | |
| 99 | + [], | |
| 100 | + EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED, | |
| 101 | + toolCallState, | |
| 102 | + applyState, | |
| 103 | + false, | |
| 104 | + ); | |
| 75 | 105 | |
| 76 | 106 | expect(result.previousCodeLines).toBe(0); |
| 77 | 107 | expect(result.newCodeLines).toBe(0); |
modified gui/src/util/editOutcomeLogger.ts +26 −12
| @@ -1,18 +1,23 @@ | ||
| 1 | -import { ApplyState, ToolCallState } from "core"; | |
| 1 | +import { | |
| 2 | + ApplyState, | |
| 3 | + BrowserSerializedContinueConfig, | |
| 4 | + ToolCallState, | |
| 5 | +} from "core"; | |
| 2 | 6 | import { IIdeMessenger } from "../context/IdeMessenger"; |
| 3 | -import { store } from "../redux/store"; | |
| 7 | +import { ChatHistoryItemWithMessageId } from "../redux/slices/sessionSlice"; | |
| 4 | 8 | |
| 5 | 9 | /** |
| 6 | 10 | * Extract model information from tool call state |
| 7 | 11 | */ |
| 8 | -function extractModelInfo(toolCallState: ToolCallState): { | |
| 12 | +function extractModelInfo( | |
| 13 | + history: ChatHistoryItemWithMessageId[], | |
| 14 | + config: BrowserSerializedContinueConfig, | |
| 15 | + toolCallState: ToolCallState, | |
| 16 | +): { | |
| 9 | 17 | modelProvider: string; |
| 10 | 18 | modelName: string; |
| 11 | 19 | modelTitle: string; |
| 12 | 20 | } { |
| 13 | - // Get the conversation history to find the model info | |
| 14 | - const history = store.getState().session.history; | |
| 15 | - | |
| 16 | 21 | // Find the assistant message that contains this tool call |
| 17 | 22 | const assistantMessage = history.find( |
| 18 | 23 | (item) => |
| @@ -35,7 +40,6 @@ | ||
| 35 | 40 | } |
| 36 | 41 | |
| 37 | 42 | // Fallback to config if not found in message |
| 38 | - const config = store.getState().config.config; | |
| 39 | 43 | const chatModel = config?.selectedModelByRole?.chat; |
| 40 | 44 | |
| 41 | 45 | return { |
| @@ -48,12 +52,13 @@ | ||
| 48 | 52 | /** |
| 49 | 53 | * Extract prompt and completion from tool call state |
| 50 | 54 | */ |
| 51 | -function extractPromptAndCompletion(toolCallState: ToolCallState): { | |
| 55 | +function extractPromptAndCompletion( | |
| 56 | + history: ChatHistoryItemWithMessageId[], | |
| 57 | + toolCallState: ToolCallState, | |
| 58 | +): { | |
| 52 | 59 | prompt: string; |
| 53 | 60 | completion: string; |
| 54 | 61 | } { |
| 55 | - const history = store.getState().session.history; | |
| 56 | - | |
| 57 | 62 | // Find the assistant message with this tool call |
| 58 | 63 | const assistantMessageIndex = history.findIndex( |
| 59 | 64 | (item) => |
| @@ -144,12 +149,17 @@ | ||
| 144 | 149 | * Assemble complete edit outcome data from tool call and apply state |
| 145 | 150 | */ |
| 146 | 151 | export function assembleEditOutcomeData( |
| 152 | + history: ChatHistoryItemWithMessageId[], | |
| 153 | + config: BrowserSerializedContinueConfig, | |
| 147 | 154 | toolCallState: ToolCallState, |
| 148 | 155 | applyState: ApplyState, |
| 149 | 156 | accepted: boolean, |
| 150 | 157 | ) { |
| 151 | - const modelInfo = extractModelInfo(toolCallState); | |
| 152 | - const promptAndCompletion = extractPromptAndCompletion(toolCallState); | |
| 158 | + const modelInfo = extractModelInfo(history, config, toolCallState); | |
| 159 | + const promptAndCompletion = extractPromptAndCompletion( | |
| 160 | + history, | |
| 161 | + toolCallState, | |
| 162 | + ); | |
| 153 | 163 | const codeChanges = extractCodeChanges(applyState); |
| 154 | 164 | |
| 155 | 165 | return { |
| @@ -174,6 +184,8 @@ | ||
| 174 | 184 | * Log Agent Mode edit outcome to editOutcome.jsonl |
| 175 | 185 | */ |
| 176 | 186 | export async function logAgentModeEditOutcome( |
| 187 | + history: ChatHistoryItemWithMessageId[], | |
| 188 | + config: BrowserSerializedContinueConfig, | |
| 177 | 189 | toolCallState: ToolCallState, |
| 178 | 190 | applyState: ApplyState, |
| 179 | 191 | accepted: boolean, |
| @@ -182,6 +194,8 @@ | ||
| 182 | 194 | // Use the original file content stored in applyState, captured before edits were applied |
| 183 | 195 | |
| 184 | 196 | const editOutcomeData = assembleEditOutcomeData( |
| 197 | + history, | |
| 198 | + config, | |
| 185 | 199 | toolCallState, |
| 186 | 200 | applyState, |
| 187 | 201 | accepted, |
modified package-lock.json +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | { |
| 2 | - "name": "continue", | |
| 2 | + "name": "wt-nate-4", | |
| 3 | 3 | "lockfileVersion": 3, |
| 4 | 4 | "requires": true, |
| 5 | 5 | "packages": { |
modified packages/config-yaml/src/load/merge.ts +2 −0
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | rules: [...(current.rules ?? []), ...(incoming.rules ?? [])], |
| 14 | 14 | prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])], |
| 15 | 15 | docs: [...(current.docs ?? []), ...(incoming.docs ?? [])], |
| 16 | + env: { ...current.env, ...incoming.env }, | |
| 16 | 17 | }; |
| 17 | 18 | } |
| 18 | 19 | |
| @@ -29,5 +30,6 @@ | ||
| 29 | 30 | data: [...(current.data ?? []), ...(incoming.data ?? [])], |
| 30 | 31 | mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])], |
| 31 | 32 | prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])], |
| 33 | + env: { ...current.env, ...incoming.env }, | |
| 32 | 34 | }; |
| 33 | 35 | } |
modified packages/config-yaml/src/load/unroll.ts +1 −1
| @@ -321,7 +321,7 @@ | ||
| 321 | 321 | |
| 322 | 322 | const sections: (keyof Omit< |
| 323 | 323 | ConfigYaml, |
| 324 | - "name" | "version" | "rules" | "schema" | "metadata" | |
| 324 | + "name" | "version" | "rules" | "schema" | "metadata" | "env" | |
| 325 | 325 | >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; |
| 326 | 326 | |
| 327 | 327 | // Process all sections in parallel |
modified packages/config-yaml/src/schemas/index.ts +7 −0
| @@ -105,11 +105,17 @@ | ||
| 105 | 105 | iconUrl: z.string().optional(), |
| 106 | 106 | }); |
| 107 | 107 | |
| 108 | +const envRecord = z.record( | |
| 109 | + z.string(), | |
| 110 | + z.union([z.string(), z.number(), z.boolean()]), | |
| 111 | +); | |
| 112 | + | |
| 108 | 113 | export const baseConfigYamlSchema = z.object({ |
| 109 | 114 | name: z.string(), |
| 110 | 115 | version: z.string(), |
| 111 | 116 | schema: z.string().optional(), |
| 112 | 117 | metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(), |
| 118 | + env: envRecord.optional(), | |
| 113 | 119 | }); |
| 114 | 120 | |
| 115 | 121 | const modelsUsesSchema = z |
| @@ -254,6 +260,7 @@ | ||
| 254 | 260 | proxy: z.string().optional(), |
| 255 | 261 | api_base: z.string().optional(), |
| 256 | 262 | api_key: z.string().optional(), |
| 263 | + env: envRecord.optional(), | |
| 257 | 264 | }); |
| 258 | 265 | |
| 259 | 266 | export type Config = z.infer<typeof configSchema>; |
modified packages/continue-sdk/package-lock.json +5 −3
| @@ -1124,13 +1124,15 @@ | ||
| 1124 | 1124 | } |
| 1125 | 1125 | }, |
| 1126 | 1126 | "node_modules/form-data": { |
| 1127 | - "version": "4.0.2", | |
| 1128 | - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", | |
| 1129 | - "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", | |
| 1127 | + "version": "4.0.4", | |
| 1128 | + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", | |
| 1129 | + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", | |
| 1130 | + "license": "MIT", | |
| 1130 | 1131 | "dependencies": { |
| 1131 | 1132 | "asynckit": "^0.4.0", |
| 1132 | 1133 | "combined-stream": "^1.0.8", |
| 1133 | 1134 | "es-set-tostringtag": "^2.1.0", |
| 1135 | + "hasown": "^2.0.2", | |
| 1134 | 1136 | "mime-types": "^2.1.12" |
| 1135 | 1137 | }, |
| 1136 | 1138 | "engines": { |
modified packages/openai-adapters/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified packages/openai-adapters/package.json +1 −0
| @@ -35,6 +35,7 @@ | ||
| 35 | 35 | "@types/follow-redirects": "^1.14.4", |
| 36 | 36 | "@types/jest": "^29.5.14", |
| 37 | 37 | "@types/json-schema": "^7.0.15", |
| 38 | + "@types/node": "^24.3.0", | |
| 38 | 39 | "cross-env": "^7.0.3", |
| 39 | 40 | "semantic-release": "^24.2.7", |
| 40 | 41 | "ts-jest": "^29.2.3", |