diff --git a/.github/actions/build-vscode-extension/action.yml b/.github/actions/build-vscode-extension/action.yml new file mode 100644 index 000000000..fb17816f2 --- /dev/null +++ b/.github/actions/build-vscode-extension/action.yml @@ -0,0 +1,150 @@ +name: 'Build VS Code Extension' +description: 'Build VS Code extension for a specific platform' +inputs: + platform: + description: 'Target platform (win32, linux, alpine, darwin)' + required: true + arch: + description: 'Target architecture (x64, arm64, armhf)' + required: true + npm_config_arch: + description: 'npm config arch (x64, arm64, arm)' + required: true + pre-release: + description: 'Whether to build as pre-release' + required: false + default: 'false' + commit-sha: + description: 'Commit SHA for version modification (optional, uses first 7 chars)' + required: false + default: '' +outputs: + target: + description: 'The target string used for the build' + value: ${{ steps.set-target.outputs.target }} + vsix-path: + description: 'Path to the generated VSIX file' + value: 'extensions/vscode/*.vsix' + build-path: + description: 'Path to the build artifacts' + value: 'extensions/vscode/build' + +runs: + using: 'composite' + steps: + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Set target variable + id: set-target + shell: bash + run: echo "target=${{ inputs.platform }}-${{ inputs.arch }}" >> $GITHUB_OUTPUT + + - name: Cache npm + uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-npm-cache-build-${{ hashFiles('**/package-lock.json') }} + + - name: Cache extension node_modules + uses: actions/cache@v4 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Cache core node_modules + uses: actions/cache@v4 + with: + path: core/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} + + - name: Cache gui node_modules + uses: actions/cache@v4 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + + - name: Cache packages node_modules + uses: actions/cache@v4 + with: + path: | + packages/*/node_modules + key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }} + + - name: Build packages + shell: bash + run: node ./scripts/build-packages.js + + - name: Install extension dependencies + shell: bash + run: | + cd extensions/vscode + npm ci + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ env.GITHUB_TOKEN }} + + - name: Install gui dependencies + shell: bash + run: | + cd gui + npm ci + + - name: Install core dependencies + shell: bash + run: | + cd core + npm ci + npm i vectordb + + - name: Prepackage the extension + shell: bash + run: | + cd extensions/vscode + npm run prepackage -- --target ${{ steps.set-target.outputs.target }} + + - name: Re-install esbuild + shell: bash + run: | + cd extensions/vscode + npm install -f esbuild + + - name: Modify package.json version with commit SHA + if: inputs.commit-sha != '' + shell: bash + run: | + cd extensions/vscode + # Get current version from package.json + CURRENT_VERSION=$(node -p "require('./package.json').version") + + # Create new version with short commit SHA (first 7 chars) + COMMIT_SHORT="${{ inputs.commit-sha }}" + NEW_VERSION="${CURRENT_VERSION}-${COMMIT_SHORT:0:7}" + + echo "๐Ÿ“ Updating package.json version from $CURRENT_VERSION to $NEW_VERSION" + + # Update version in package.json + sed -i.bak "s/\"version\": \"$CURRENT_VERSION\"/\"version\": \"$NEW_VERSION\"/" package.json + + # Remove backup file + rm -f package.json.bak + + # Verify the change + echo "โœ… New version: $(node -p "require('./package.json').version")" + + - name: Package extension (build artifacts) + shell: bash + run: | + cd extensions/vscode + npm run package + + - name: Package extension (.vsix files) + shell: bash + run: | + cd extensions/vscode + if [ "${{ inputs.pre-release }}" = "true" ]; then + npx vsce package --pre-release --no-dependencies --target ${{ steps.set-target.outputs.target }} + else + npx vsce package --no-dependencies --target ${{ steps.set-target.outputs.target }} + fi \ No newline at end of file diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml new file mode 100644 index 000000000..71051101d --- /dev/null +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -0,0 +1,139 @@ +name: "Run JetBrains Tests" +description: "Setup and run JetBrains IntelliJ tests with all dependencies" + +inputs: + github-token: + description: "GitHub token for accessing repositories" + required: true + ci-github-token: + description: "CI GitHub token for vscode extension build" + required: true + +runs: + using: "composite" + steps: + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - name: Build packages and install core dependencies + shell: bash + run: | + node ./scripts/build-packages.js + cd core + npm ci + + - name: Setup Java + uses: actions/setup-java@v4.5.0 + with: + distribution: zulu + java-version: 17 + + - name: Setup FFmpeg + uses: AnimMouse/setup-ffmpeg@v1 + with: + token: ${{ inputs.github-token }} + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-npm-cache-jetbrains-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - uses: actions/cache@v4 + id: vscode-extension-cache + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - uses: actions/cache@v4 + id: gui-cache + with: + path: gui/node_modules + key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + + # Cache prepackaged extension build to share with other jobs + - uses: actions/cache@v4 + id: vscode-prepackage-cache + with: + path: extensions/vscode/build + key: ${{ runner.os }}-vscode-prepackage-${{ hashFiles('extensions/vscode/package-lock.json', 'extensions/vscode/**/*.ts', 'extensions/vscode/**/*.json') }} + + # Only run prepackage if not cached - saves ~1 minute + - name: Run prepackage script + if: steps.vscode-prepackage-cache.outputs.cache-hit != 'true' + shell: bash + run: | + cd extensions/vscode + if [ "${{ steps.vscode-extension-cache.outputs.cache-hit }}" != "true" ]; then + npm ci + fi + npm run prepackage + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ inputs.ci-github-token }} + + - uses: actions/cache@v4 + id: binary-cache + with: + path: binary/node_modules + key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} + + - name: Build the binaries + shell: bash + run: | + cd binary + npm run build + + - name: Start test IDE + shell: bash + run: | + cd extensions/intellij + export DISPLAY=:99.0 + Xvfb -ac :99 -screen 0 1920x1080x24 & + sleep 10 + mkdir -p build/reports + ./gradlew runIdeForUiTests & + + - name: Wait for JB connection + uses: jtalk/url-health-check-action@v3 + with: + url: http://127.0.0.1:8082 + max-attempts: 15 + retry-delay: 30s + + - name: Run tests + shell: bash + run: | + cd extensions/intellij + export DISPLAY=:99.0 + ./gradlew test + + - name: Move video + if: ${{ failure() }} + shell: bash + run: | + cd extensions/intellij + mv video build/reports + + - name: Copy logs + if: ${{ failure() }} + shell: bash + run: | + cd extensions/intellij + mv build/idea-sandbox/system/log/ build/reports + + - name: Save fails report + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: jb-failure-report + path: | + ${{ github.workspace }}/extensions/intellij/build/reports diff --git a/.github/actions/run-vscode-e2e-test/action.yml b/.github/actions/run-vscode-e2e-test/action.yml new file mode 100644 index 000000000..1fcba5245 --- /dev/null +++ b/.github/actions/run-vscode-e2e-test/action.yml @@ -0,0 +1,134 @@ +name: 'Run VS Code E2E Test' +description: 'Run a single VS Code E2E test with all required setup' +inputs: + test_file: + description: 'E2E test file to run' + required: true + command: + description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)' + required: true + ssh_key: + description: 'SSH private key for testing' + required: false + ssh_host: + description: 'SSH host for testing' + required: false + is_fork: + description: 'Whether this is a fork (affects SSH tests)' + required: false + default: 'false' + +runs: + using: 'composite' + steps: + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + id: vscode-node-modules-cache + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + + # We don't want to cache the Continue extension, so it is deleted at the end of the job + - uses: actions/cache@v4 + id: test-extensions-cache + with: + path: extensions/vscode/e2e/.test-extensions + key: CONSTANT + + - uses: actions/cache@v4 + id: storage-cache + with: + path: extensions/vscode/e2e/storage + key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Download build artifact + uses: actions/download-artifact@v4 + with: + name: vscode-extension-build-Linux + path: extensions/vscode/build + + - name: Build packages and download e2e dependencies + shell: bash + run: | + node ./scripts/build-packages.js + if [ "${{ steps.storage-cache.outputs.cache-hit }}" != "true" ]; then + cd core + npm ci + cd ../extensions/vscode + npm run e2e:ci:download + else + cd core + npm ci + fi + + - name: Fix VSCode binary permissions + shell: bash + run: | + chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code + chmod +x extensions/vscode/e2e/storage/chromedriver-linux64/chromedriver + + - name: Set up SSH + if: ${{ inputs.ssh_key != '' && inputs.ssh_host != '' && inputs.is_fork == 'false' }} + shell: bash + env: + SSH_KEY: ${{ inputs.ssh_key }} + SSH_HOST: ${{ inputs.ssh_host }} + run: | + mkdir -p ~/.ssh + echo "$SSH_KEY" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts + echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config + + - name: Set up Xvfb + shell: bash + run: | + Xvfb :99 & + export DISPLAY=:99 + + - name: Run e2e tests + shell: bash + run: | + cd extensions/vscode + IGNORE_SSH_TESTS="${{ inputs.is_fork }}" TEST_FILE="${{ inputs.test_file }}" npm run ${{ inputs.command }} + env: + DISPLAY: :99 + + - name: Delete continue from test extensions + shell: bash + run: | + cd extensions/vscode + rm -rf e2e/.test-extensions/continue* + + - name: Sanitize test file name + id: sanitize_filename + if: always() + shell: bash + run: | + FILENAME="${{ inputs.test_file }}" + SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion + echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT + + - name: Upload e2e test screenshots + if: failure() + uses: actions/upload-artifact@v4 + with: + name: e2e-failure-screenshots-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} + path: extensions/vscode/e2e/storage/screenshots + + - name: Find e2e log file + if: always() + shell: bash + run: | + echo "Searching for e2e.log file..." + find $GITHUB_WORKSPACE -name "e2e.log" -type f + + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} + path: extensions/vscode/e2e.log \ No newline at end of file diff --git a/.github/actions/setup-component/action.yml b/.github/actions/setup-component/action.yml new file mode 100644 index 000000000..d05de3bfb --- /dev/null +++ b/.github/actions/setup-component/action.yml @@ -0,0 +1,51 @@ +name: 'Setup Component' +description: 'Cache and install dependencies for a specific component' +inputs: + component: + description: 'Component name (core, gui, vscode, binary)' + required: true + include-packages: + description: 'Whether to include packages cache (default: true)' + required: false + default: 'true' + include-root: + description: 'Whether to include root cache (default: false)' + required: false + default: 'false' + +runs: + using: 'composite' + steps: + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + - uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-npm-cache-${{ inputs.component }}-${{ hashFiles(inputs.component == 'vscode' && 'extensions/vscode/package-lock.json' || format('{0}/package-lock.json', inputs.component)) }} + + - uses: actions/cache@v4 + if: inputs.include-packages == 'true' + with: + path: | + packages/*/node_modules + key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }} + + - uses: actions/cache@v4 + if: inputs.include-root == 'true' + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: component-cache + with: + path: ${{ inputs.component == 'vscode' && 'extensions/vscode/node_modules' || format('{0}/node_modules', inputs.component) }} + key: ${{ runner.os }}-${{ inputs.component }}-node-modules-${{ hashFiles(inputs.component == 'vscode' && 'extensions/vscode/package-lock.json' || format('{0}/package-lock.json', inputs.component)) }} + + - name: Install component dependencies + if: steps.component-cache.outputs.cache-hit != 'true' + shell: bash + run: | + cd ${{ inputs.component == 'vscode' && 'extensions/vscode' || inputs.component }} + npm ci \ No newline at end of file diff --git a/.github/actions/setup-packages/action.yml b/.github/actions/setup-packages/action.yml new file mode 100644 index 000000000..2c49e21bc --- /dev/null +++ b/.github/actions/setup-packages/action.yml @@ -0,0 +1,23 @@ +name: "Setup Packages" +description: "Cache and build packages with npm caching" + +runs: + using: "composite" + steps: + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + - uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-npm-cache-packages-${{ hashFiles('packages/*/package-lock.json') }} + + - uses: actions/cache@v4 + with: + path: | + packages/*/node_modules + key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }} + + - name: Build packages + shell: bash + run: node ./scripts/build-packages.js diff --git a/.github/auto_assign.yml b/.github/auto_assign.yml deleted file mode 100644 index ed05df6f9..000000000 --- a/.github/auto_assign.yml +++ /dev/null @@ -1,10 +0,0 @@ -# Reference: https://github.com/marketplace/actions/auto-assign-action -addAssignees: true - -assignees: - - sestinj - - Patrick-Erichsen - - tomasz-stefaniak - - RomneyDa - -numberOfAssignees: 2 diff --git a/.github/workflows/auto-assign-pr.yaml b/.github/workflows/auto-assign-pr.yaml deleted file mode 100644 index 4fd701a15..000000000 --- a/.github/workflows/auto-assign-pr.yaml +++ /dev/null @@ -1,10 +0,0 @@ -name: PR assignment -on: - pull_request: - types: [opened, ready_for_review] - -jobs: - add-reviews: - runs-on: ubuntu-latest - steps: - - uses: kentaro-m/auto-assign-action@v2.0.0 diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 43d65d5b5..031ed1fbe 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -4,8 +4,9 @@ on: push: branches: - nate/auto-main-release-draft - schedule: - - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday + # Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases. + # schedule: + # - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday workflow_dispatch: # Keep manual trigger option jobs: diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 1c4adce0c..724227354 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -12,7 +12,7 @@ concurrency: jobs: conventional-commits: - name: Validate Conventional Commits (Warning Only) + name: Validate Conventional Commits runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft }} continue-on-error: true @@ -21,22 +21,26 @@ jobs: issues: write contents: read steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - name: Validate PR title format + id: pr-title-check + run: | + PR_TITLE="${{ github.event.pull_request.title }}" + echo "Checking PR title: $PR_TITLE" - - name: Validate conventional commits - id: commitlint - uses: wagoid/commitlint-github-action@v6 - with: - configFile: .commitlintrc.warning.json - # Only check the last commit instead of all commits in the PR - commitDepth: 1 - continue-on-error: true + # Regex pattern for conventional commits + PATTERN="^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?!?: .+" - - name: Add commit message guidance comment - if: steps.commitlint.outcome == 'failure' + if [[ $PR_TITLE =~ $PATTERN ]]; then + echo "โœ… PR title follows conventional commit format" + echo "valid=true" >> $GITHUB_OUTPUT + else + echo "โŒ PR title does not follow conventional commit format" + echo "valid=false" >> $GITHUB_OUTPUT + exit 1 + fi + + - name: Add PR title guidance comment + if: steps.pr-title-check.outputs.valid == 'false' uses: actions/github-script@v7 with: script: | @@ -48,7 +52,7 @@ jobs: const botComment = comments.find(comment => comment.user.type === 'Bot' && - comment.body.includes('Conventional Commit Format') + comment.body.includes('PR Title Format') ); if (!botComment) { @@ -57,17 +61,13 @@ jobs: repo: context.repo.repo, issue_number: context.issue.number, body: [ - "## โš ๏ธ Conventional Commit Format", + "## โš ๏ธ PR Title Format", "", - "Your latest commit message doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.", + "Your PR title doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend using this format for better project organization.", "", "### Expected Format:", "```", "[optional scope]: ", - "", - "[optional body]", - "", - "[optional footer(s)]", "```", "", "### Examples:", diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 531129c79..fe1351edf 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -87,7 +87,7 @@ jobs: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' name: Build Plugin - runs-on: macos-latest + runs-on: macos-13 permissions: contents: write pull-requests: write @@ -167,7 +167,7 @@ jobs: key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - name: Build packages (Unix) - run: cd ../.. && ./scripts/build-packages.sh + run: cd ../.. && node ./scripts/build-packages.js # npm install core - name: Install core node_modules @@ -325,7 +325,7 @@ jobs: platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-latest + - os: macos-13 platform: darwin arch: arm64 npm_config_arch: arm64 diff --git a/.github/workflows/label-merged-prs.yml b/.github/workflows/label-merged-prs.yml new file mode 100644 index 000000000..c3c034117 --- /dev/null +++ b/.github/workflows/label-merged-prs.yml @@ -0,0 +1,121 @@ +name: Label Merged PRs + +on: + pull_request: + types: [closed] + +jobs: + label-pr: + if: github.event.pull_request.merged == true + runs-on: ubuntu-latest + permissions: + pull-requests: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Check if author is in tier list + id: check-author + run: | + USERS=( + "TyDunn" + "jpoly1219" + "bdougie" + "uinstinct" + "sestinj" + "tingwai" + "tomasz-stefaniak" + "RomneyDa" + "Patrick-Erichsen" + ) + + PR_AUTHOR="${{ github.event.pull_request.user.login }}" + SHOULD_LABEL="false" + + for user in "${USERS[@]}"; do + if [[ "$PR_AUTHOR" == "$user" ]]; then + SHOULD_LABEL="true" + break + fi + done + + echo "should_label=$SHOULD_LABEL" >> $GITHUB_OUTPUT + + - name: Determine and apply tier label + if: steps.check-author.outputs.should_label == 'true' + uses: actions/github-script@v7 + with: + script: | + const pr = context.payload.pull_request; + + // Check if PR already has a tier label + const existingLabels = pr.labels.map(l => l.name); + if (existingLabels.some(label => label.match(/^tier [1-3]$/))) { + console.log('PR already has a tier label, skipping'); + return; + } + + // Function to extract conventional commit prefix + function getConventionalPrefix(title) { + const match = title.match(/^([a-z]+)(\s|$|:)/); + return match ? match[1] : ''; + } + + // Function to determine tier + function determineTier(pr) { + const additions = pr.additions; + const deletions = pr.deletions; + const changedFiles = pr.changed_files; + const title = pr.title; + const body = pr.body || ''; + + const prefix = getConventionalPrefix(title); + + // If no conventional commit prefix, skip + if (!prefix) { + console.log('No conventional commit format, skipping'); + return null; + } + + // Tier 4 (unlabeled): fix, test, docs, style, refactor, perf, build, ci, revert, improve + const tier4Prefixes = ['fix', 'test', 'docs', 'style', 'refactor', 'perf', 'build', 'ci', 'revert', 'chore', 'improve']; + if (tier4Prefixes.includes(prefix)) { + console.log('Tier 4 prefix detected, will remain unlabeled'); + return null; + } + + const totalChanges = additions + deletions; + + // Tier 1: Major features (1000+ lines changed, or 20+ files, or feat with large scope) + if (totalChanges > 1000 || changedFiles > 20 || + (prefix === 'feat' && totalChanges > 800) || + title.match(/(major|milestone|launch)/)) { + return 'tier 1'; + } + + // Tier 2: Important features (500+ lines changed, or 10+ files, or standard feat) + if (totalChanges > 500 || changedFiles > 10 || prefix === 'feat') { + return 'tier 2'; + } + + // Tier 3: Smaller improvements + return 'tier 3'; + } + + const tier = determineTier(pr); + + if (tier) { + console.log(`Assigning ${tier} label to PR #${pr.number}`); + console.log(`Title: ${pr.title}`); + console.log(`Changes: +${pr.additions} -${pr.deletions} (${pr.changed_files} files)`); + + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pr.number, + labels: [tier] + }); + + console.log(`โœ“ Label '${tier}' added successfully`); + } \ No newline at end of file diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml new file mode 100644 index 000000000..75e4104ab --- /dev/null +++ b/.github/workflows/main-build.yaml @@ -0,0 +1,105 @@ +name: Main Branch Build + +# Download and republish VS Code extension artifacts when code is merged to main +on: + push: + branches: + - main + workflow_dispatch: + inputs: + test_pr_number: + description: "PR number to test with" + required: true + +jobs: + republish-pr-artifacts: + runs-on: ubuntu-latest + strategy: + matrix: + platform: [Linux, macOS] + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 2 # Get the last 2 commits to find the merge commit + + - name: Get merged PR number + id: get-pr + run: | + # Get the commit message of the merge commit + COMMIT_MSG=$(git log --format=%B -n 1 HEAD) + echo "Commit message: $COMMIT_MSG" + + # Extract PR number from merge commit message (format: "Merge pull request #123 from...") + PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723") + + if [ -z "$PR_NUMBER" ]; then + echo "โŒ Could not extract PR number from commit message. This might not be a PR merge." + echo "Commit message was: $COMMIT_MSG" + exit 1 + fi + + echo "Found PR number: $PR_NUMBER" + echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT + + - name: Find PR workflow run + id: find-run + env: + PR_NUMBER: ${{ steps.get-pr.outputs.pr_number }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "๐Ÿ” Getting branch name for PR #$PR_NUMBER..." + + # Get the branch name for the PR + BRANCH_NAME=$(gh pr view "$PR_NUMBER" --repo "${{ github.repository }}" --json headRefName --jq '.headRefName') + + if [ -z "$BRANCH_NAME" ]; then + echo "โŒ Could not find PR #$PR_NUMBER" + exit 1 + fi + + echo "Branch name: $BRANCH_NAME" + + # Get the latest successful workflow run for the branch + RUN_ID=$(gh run list \ + --repo "${{ github.repository }}" \ + --workflow="pr_checks.yaml" \ + --branch="$BRANCH_NAME" \ + --json databaseId,status,conclusion \ + --jq ".[] | select(.status == \"completed\" and .conclusion == \"success\") | .databaseId" \ + | head -1) + + if [ -z "$RUN_ID" ]; then + echo "โŒ No successful workflow run found for PR #$PR_NUMBER (branch: $BRANCH_NAME)" + exit 1 + fi + + echo "Found successful workflow run: $RUN_ID" + echo "run_id=$RUN_ID" >> $GITHUB_OUTPUT + + - name: Download PR artifact + env: + RUN_ID: ${{ steps.find-run.outputs.run_id }} + PLATFORM: ${{ matrix.platform }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "๐Ÿ“ฅ Downloading vscode-extension-build-$PLATFORM artifact from run $RUN_ID..." + + # Create temporary directory for download + mkdir -p ./temp-download + + # Download the artifact from the PR workflow run + if ! gh run download "$RUN_ID" \ + --repo "${{ github.repository }}" \ + --name "vscode-extension-build-$PLATFORM" \ + --dir "./temp-download"; then + echo "โŒ Failed to download artifact vscode-extension-build-$PLATFORM from run $RUN_ID" + exit 1 + fi + + echo "โœ… Successfully downloaded artifact" + + - name: Republish as main branch artifact + uses: actions/upload-artifact@v4 + with: + name: vscode-extension-build-${{ matrix.platform }} + path: ./temp-download/* diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index ce1e59e66..2024b083b 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -29,6 +29,7 @@ jobs: build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' + runs-on: ${{ matrix.os }} strategy: matrix: include: @@ -64,9 +65,33 @@ jobs: platform: darwin arch: arm64 npm_config_arch: arm64 - runs-on: ${{ matrix.os }} steps: - # 1. Check-out repository + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: ./.github/actions/build-vscode-extension + with: + platform: ${{ matrix.platform }} + arch: ${{ matrix.arch }} + npm_config_arch: ${{ matrix.npm_config_arch }} + pre-release: false + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Upload .vsix artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix + path: "extensions/vscode/*.vsix" + + check-version: + runs-on: ubuntu-latest + steps: - name: Checkout uses: actions/checkout@v4 with: @@ -80,107 +105,6 @@ jobs: cd extensions/vscode node scripts/versionCheck.js - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - name: Cache extension node_modules - uses: actions/cache@v3 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Build packages (Windows) - run: ./scripts/build-packages.ps1 - if: matrix.os == 'windows-latest' - - - name: Build packages (Unix) - run: ./scripts/build-packages.sh - if: matrix.os != 'windows-latest' - - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Install gui Dependencies - run: | - cd gui - npm ci - - # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - - name: Install Core Dependencies - run: | - cd core - npm ci - npm i vectordb - - # - name: Run core tests - # run: | - # cd core - # npm run test - # env: - # OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - - # 2.5. Pre package - - name: Set var for environment info - shell: pwsh - run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV - - - name: Prepackage the extension - run: | - cd extensions/vscode - npm run prepackage -- --target ${{ env.target }} - - # 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js) - - name: Re-install esbuild - run: | - cd extensions/vscode - npm install -f esbuild - - # 4. Run tests for the extension - # - name: Install Xvfb for Linux and run tests - # run: | - # sudo apt-get install -y xvfb # Install Xvfb - # Xvfb :99 & # Start Xvfb - # export DISPLAY=:99 # Export the display number to the environment - # cd extensions/vscode - # npm run test - # if: matrix.os == 'ubuntu-latest' - - # - name: Run extension tests - # run: | - # cd extensions/vscode - # npm run test - # if: matrix.os != 'ubuntu-latest' - - # 5. Package the extension - - name: Package the extension - run: cd extensions/vscode && npx vsce package --no-dependencies --target ${{ env.target }} - - # 6. Upload the .vsix as an artifact - - uses: actions/upload-artifact@v4 - with: - name: ${{ env.target }}-vsix - path: "extensions/vscode/*.vsix" - release: permissions: contents: write diff --git a/.github/workflows/pr-build-upload-vsix.yaml b/.github/workflows/pr-build-upload-vsix.yaml new file mode 100644 index 000000000..17a3dc5ba --- /dev/null +++ b/.github/workflows/pr-build-upload-vsix.yaml @@ -0,0 +1,52 @@ +name: PR Build And Upload VSIX + +# Builds and uploads VSIX artifacts for the `oneper` script across Linux, Windows, and macOS ARM platforms +on: + pull_request: + branches: + - main + +jobs: + build-and-upload-vsix: + runs-on: ${{ matrix.runner }} + timeout-minutes: 10 + strategy: + matrix: + include: + - platform: linux + arch: x64 + runner: ubuntu-latest + - platform: win32 + arch: x64 + runner: windows-latest + - platform: darwin + arch: arm64 + runner: macos-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Build VS Code extension + uses: ./.github/actions/build-vscode-extension + with: + platform: ${{ matrix.platform }} + arch: ${{ matrix.arch }} + npm_config_arch: ${{ matrix.arch }} + pre-release: false + commit-sha: ${{ github.sha }} + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }} + path: extensions/vscode/build + + - name: Upload .vsix artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix + path: "extensions/vscode/*.vsix" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml new file mode 100644 index 000000000..9ea007d5f --- /dev/null +++ b/.github/workflows/pr-checks.yaml @@ -0,0 +1,337 @@ +name: PR Checks + +# PR Checks run on all PRs to the main branch and must pass before merging. +on: + pull_request: + branches: + - main + + push: + branches: + - main + +jobs: + prettier-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + id: root-cache + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - name: Install root dependencies + if: steps.root-cache.outputs.cache-hit != 'true' + run: npm ci + + - name: Check code formatting with Prettier + run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore + + core-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Setup core component + uses: ./.github/actions/setup-component + with: + component: core + include-root: true + + - name: Type check and lint + run: | + cd core + npx tsc --noEmit + npm run lint + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + + - name: Run tests + run: | + cd core + npm test + npm run vitest + env: + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + + gui-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Setup core component + uses: ./.github/actions/setup-component + with: + component: core + include-root: true + - name: Setup gui component + uses: ./.github/actions/setup-component + with: + component: gui + include-packages: false + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Type check and lint + run: | + cd gui + npx tsc --noEmit + npm run lint + + - name: Run tests + run: | + cd gui + npm test + + binary-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Setup core component + uses: ./.github/actions/setup-component + with: + component: core + include-root: true + - name: Setup binary component + uses: ./.github/actions/setup-component + with: + component: binary + include-packages: false + + - name: Type check + run: | + cd binary + npx tsc --noEmit + + vscode-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Setup core component + uses: ./.github/actions/setup-component + with: + component: core + include-root: true + - name: Setup vscode component + uses: ./.github/actions/setup-component + with: + component: vscode + include-packages: false + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Type check and lint + run: | + cd extensions/vscode + npm run write-build-timestamp + npx tsc --noEmit + npm run lint + + - name: Run vitest tests + run: | + cd extensions/vscode + npm run vitest + + get-packages-matrix: + runs-on: ubuntu-latest + outputs: + packages: ${{ steps.get-packages.outputs.packages }} + steps: + - uses: actions/checkout@v4 + - name: Get package list + id: get-packages + run: | + packages=$(find packages/ -maxdepth 1 -type d -not -path packages/ -exec basename {} \; | sort | jq -R -s -c 'split("\n")[:-1]') + echo "packages=$packages" >> $GITHUB_OUTPUT + echo "Found packages: $packages" + + packages-checks: + needs: get-packages-matrix + runs-on: ubuntu-latest + strategy: + matrix: + package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }} + steps: + - uses: actions/checkout@v4 + - name: Setup packages + uses: ./.github/actions/setup-packages + + - name: Test and check ${{ matrix.package }} + run: | + cd packages/${{ matrix.package }} + npm ci + npm test + env: + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} + + vscode-get-test-file-matrix: + runs-on: ubuntu-latest + outputs: + test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Cache npm + uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-npm-cache-matrix-${{ hashFiles('core/package-lock.json', 'extensions/vscode/package-lock.json') }} + + - name: Cache packages node_modules + uses: actions/cache@v4 + with: + path: | + packages/*/node_modules + key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }} + + - name: Cache core node modules + uses: actions/cache@v4 + with: + path: core/node_modules + key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + + - name: Cache vscode extension node modules + uses: actions/cache@v4 + id: vscode-cache + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Build packages and get test files + id: vscode-get-test-file-matrix + run: | + node ./scripts/build-packages.js + cd extensions/vscode + npm ci + npm run e2e:compile + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi + echo "test_file_matrix<> $GITHUB_OUTPUT + echo "$FILES" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Debug Outputs + run: | + echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}" + + vscode-package-extension-linux: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Build VS Code extension + uses: ./.github/actions/build-vscode-extension + with: + platform: linux + arch: x64 + npm_config_arch: x64 + pre-release: false + commit-sha: ${{ github.sha }} + env: + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: vscode-extension-build-Linux + path: extensions/vscode/build + + vscode-e2e-tests: + name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }}) + needs: [vscode-get-test-file-matrix, vscode-package-extension-linux] + runs-on: ubuntu-latest + timeout-minutes: 15 + # Tests requiring secrets need approval from maintainers + strategy: + fail-fast: false + matrix: + test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} + command: ["e2e:ci:run", "e2e:ci:run-yaml"] + steps: + - uses: actions/checkout@v4 + - name: Run VS Code E2E test + uses: ./.github/actions/run-vscode-e2e-test + with: + test_file: ${{ matrix.test_file }} + command: ${{ matrix.command }} + ssh_key: ${{ secrets.GH_ACTIONS_SSH_TEST_KEY_PEM }} + ssh_host: ${{ secrets.GH_ACTIONS_SSH_TEST_DNS_NAME }} + is_fork: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} + + jetbrains-tests: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - name: Run JetBrains tests + uses: ./.github/actions/run-jetbrains-tests + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + ci-github-token: ${{ secrets.CI_GITHUB_TOKEN }} + + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) + # This action at least lets us manage the list of required tests via source control + # so that creators of new jobs can add them to this list + require-all-checks-to-pass: + if: always() + runs-on: ubuntu-latest + needs: + - prettier-check + - core-checks + - gui-checks + - binary-checks + - vscode-checks + - get-packages-matrix + - packages-checks + - vscode-get-test-file-matrix + - vscode-package-extension-linux + - vscode-e2e-tests + - jetbrains-tests + + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml deleted file mode 100644 index b4333890d..000000000 --- a/.github/workflows/pr_checks.yaml +++ /dev/null @@ -1,1132 +0,0 @@ -name: PR checks - -# PR Checks run on all PRs to the main branch and must pass before merging. -on: - pull_request: - branches: - - main - - push: - branches: - - main - -jobs: - install-root: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: root-cache - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - name: Install root dependencies - if: steps.root-cache.outputs.cache-hit != 'true' - run: npm ci - - prettier-check: - needs: install-root - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - name: Check code formatting with Prettier - run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore - - install-config-yaml: - needs: install-root - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Install config-yaml dependencies - if: steps.config-yaml-cache.outputs.cache-hit != 'true' - run: | - cd packages/config-yaml - npm ci - - install-openai-adapters: - needs: install-root - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Install openai-adapters dependencies - if: steps.openai-adapters-cache.outputs.cache-hit != 'true' - run: | - cd packages/openai-adapters - npm ci - - config-yaml-checks: - needs: install-config-yaml - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build and check config-yaml - run: | - cd packages/config-yaml - npx tsc --noEmit - # Tests are currently failing, commenting out for now - # npm test - npm run build - - install-core: - needs: install-root - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: root-cache - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: core-cache - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - name: Install core dependencies - if: steps.core-cache.outputs.cache-hit != 'true' - run: | - cd core - npm ci - - core-checks: - needs: [install-core, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: root-cache - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: core-cache - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - name: Type check and lint - run: | - cd core - npx tsc --noEmit - npm run lint - env: - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - - install-gui: - needs: - [install-root, install-core, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: gui-cache - with: - path: gui/node_modules - key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Install gui dependencies - if: steps.gui-cache.outputs.cache-hit != 'true' - run: | - cd gui - npm ci - - gui-checks: - needs: install-gui - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: gui-cache - with: - path: gui/node_modules - key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Type check and lint - run: | - cd gui - npx tsc --noEmit - npm run lint - - binary-checks: - needs: - [install-root, install-core, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: binary-cache - with: - path: binary/node_modules - key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Install binary dependencies - if: steps.binary-cache.outputs.cache-hit != 'true' - run: | - cd binary - npm ci - - - name: Type check - run: | - cd binary - npx tsc --noEmit - - install-vscode: - needs: - [install-root, install-core, install-config-yaml, install-openai-adapters] - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: vscode-cache - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Install vscode dependencies - if: steps.vscode-cache.outputs.cache-hit != 'true' - run: | - cd extensions/vscode - npm ci - env: - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - vscode-checks: - needs: install-vscode - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: vscode-cache - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Type check and lint - run: | - cd extensions/vscode - npm run write-build-timestamp - npx tsc --noEmit - npm run lint - - - name: Run vitest tests - run: | - cd extensions/vscode - npm run vitest - - core-tests: - needs: [install-core, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Run core tests - run: | - cd core - npm test - npm run vitest - env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} - MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} - AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} - AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} - AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} - AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} - - package-tests: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Install dependencies - run: | - cd packages/config-yaml - npm ci - - - name: Run config-yaml tests - run: | - cd packages/config-yaml - npm test - - openai-adapters-tests: - needs: install-openai-adapters - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - with: - path: node_modules - key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Run openai-adapters tests - run: | - cd packages/openai-adapters - npm test - env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} - MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} - AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} - AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} - AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} - AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} - VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} - - vscode-get-test-file-matrix: - runs-on: ubuntu-latest - needs: [install-root, install-vscode, install-config-yaml] - outputs: - test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} - steps: - - uses: actions/checkout@v4 - - - name: Cache node modules - uses: actions/cache@v4 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Get test files - id: vscode-get-test-file-matrix - run: | - cd extensions/vscode - npm ci - npm run e2e:compile - if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then - # Exclude SSH tests for forks - FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) - else - # Include all tests for non-forks - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) - fi - echo "test_file_matrix<> $GITHUB_OUTPUT - echo "$FILES" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Debug Outputs - run: | - echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}" - - vscode-package-extension: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - needs: - [ - install-vscode, - install-core, - install-config-yaml, - install-openai-adapters, - ] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: vscode-node-modules-cache - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: core-node-modules-cache - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Package extension - run: | - cd extensions/vscode - npm run package - - - name: Upload build artifact - uses: actions/upload-artifact@v4 - with: - name: vscode-extension-build-${{ runner.os }} - path: extensions/vscode/build - - vscode-download-e2e-dependencies: - runs-on: ubuntu-latest - needs: - [ - install-vscode, - install-core, - install-config-yaml, - install-openai-adapters, - ] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: vscode-node-modules-cache - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: storage-cache - with: - path: extensions/vscode/e2e/storage - key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Download Dependencies - if: steps.storage-cache.outputs.cache-hit != 'true' - run: | - cd extensions/vscode - npm run e2e:ci:download - - - name: Upload e2e dependencies - uses: actions/upload-artifact@v4 - with: - name: vscode-e2e-dependencies - path: extensions/vscode/e2e/storage - - vscode-e2e-tests: - name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }}) - needs: - [ - vscode-download-e2e-dependencies, - vscode-get-test-file-matrix, - vscode-package-extension, - install-vscode, - install-core, - install-config-yaml, - install-openai-adapters, - ] - runs-on: ubuntu-latest - # Tests requiring secrets need approval from maintainers - strategy: - fail-fast: false - matrix: - test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} - command: ["e2e:ci:run", "e2e:ci:run-yaml"] - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: vscode-node-modules-cache - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} - - # We don't want to cache the Continue extension, so it is deleted at the end of the job - - uses: actions/cache@v4 - id: test-extensions-cache - with: - path: extensions/vscode/e2e/.test-extensions - key: CONSTANT - - - name: Download build artifact - uses: actions/download-artifact@v4 - with: - name: vscode-extension-build-Linux - path: extensions/vscode/build - - - name: Download e2e dependencies - uses: actions/download-artifact@v4 - with: - name: vscode-e2e-dependencies - path: extensions/vscode/e2e/storage - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Fix VSCode binary permissions - run: | - chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code - chmod +x extensions/vscode/e2e/storage/chromedriver-linux64/chromedriver - - - name: Set up SSH - env: - SSH_KEY: ${{ secrets.GH_ACTIONS_SSH_TEST_KEY_PEM }} - SSH_HOST: ${{ secrets.GH_ACTIONS_SSH_TEST_DNS_NAME }} - run: | - mkdir -p ~/.ssh - echo "$SSH_KEY" > ~/.ssh/id_rsa - chmod 600 ~/.ssh/id_rsa - ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts - echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config - if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }} - - - name: Set up Xvfb - run: | - Xvfb :99 & - export DISPLAY=:99 - - - name: Run e2e tests - run: | - cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} - env: - DISPLAY: :99 - - - name: Delete continue from test extensions - run: | - cd extensions/vscode - rm -rf e2e/.test-extensions/continue* - - - name: Sanitize test file name - id: sanitize_filename - if: always() - run: | - FILENAME="${{ matrix.test_file }}" - SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion - echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT - - - name: Upload e2e test screenshots - if: failure() - uses: actions/upload-artifact@v4 - with: - name: e2e-failure-screenshots-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} - path: extensions/vscode/e2e/storage/screenshots - - - name: Find e2e log file - if: always() - run: | - echo "Searching for e2e.log file..." - find $GITHUB_WORKSPACE -name "e2e.log" -type f - - - name: Upload e2e logs - if: always() - uses: actions/upload-artifact@v4 - with: - name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} - path: extensions/vscode/e2e.log - - gui-tests: - needs: - [install-gui, install-core, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: gui-cache - with: - path: gui/node_modules - key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} - - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Install GUI dependencies - if: steps.gui-cache.outputs.cache-hit != 'true' - run: cd gui && npm ci - env: - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Run gui tests - run: | - cd gui - npm test - - jetbrains-tests: - needs: - [install-root, core-checks, install-config-yaml, install-openai-adapters] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/cache@v4 - with: - path: core/node_modules - key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} - - - uses: actions/cache@v4 - id: config-yaml-cache - with: - path: packages/config-yaml/node_modules - key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} - - - uses: actions/cache@v4 - id: openai-adapters-cache - with: - path: packages/openai-adapters/node_modules - key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} - - - name: Build config-yaml - run: | - cd packages/config-yaml - npm run build - - - name: Build openai-adapters - run: | - cd packages/openai-adapters - npm run build - - - name: Setup Java - uses: actions/setup-java@v4.5.0 - with: - distribution: zulu - java-version: 17 - - - name: Setup FFmpeg - uses: AnimMouse/setup-ffmpeg@v1 - with: - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - uses: actions/cache@v4 - id: gui-cache - with: - path: gui/node_modules - key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} - - # We can shave off another minute off our CI script by finding a way to share this with vscode-tests - - name: Run prepackage script - run: | - cd extensions/vscode - npm ci - npm run prepackage - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - uses: actions/cache@v4 - id: binary-cache - with: - path: binary/node_modules - key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} - - - name: Build the binaries - run: | - cd binary - npm run build - - - name: Start test IDE - run: | - cd extensions/intellij - export DISPLAY=:99.0 - Xvfb -ac :99 -screen 0 1920x1080x24 & - sleep 10 - mkdir -p build/reports - ./gradlew runIdeForUiTests & - - - name: Wait for JB connection - uses: jtalk/url-health-check-action@v3 - with: - url: http://127.0.0.1:8082 - max-attempts: 15 - retry-delay: 30s - - - name: Run tests - run: | - cd extensions/intellij - export DISPLAY=:99.0 - ./gradlew test - - - name: Move video - if: ${{ failure() }} - run: | - cd extensions/intellij - mv video build/reports - - - name: Copy logs - if: ${{ failure() }} - run: | - cd extensions/intellij - mv build/idea-sandbox/system/log/ build/reports - - - name: Save fails report - if: ${{ failure() }} - uses: actions/upload-artifact@v4 - with: - name: jb-failure-report - path: | - ${{ github.workspace }}/extensions/intellij/build/reports - - # GitHub does not have a way of requiring that all checks pass (you must manually select each job) - # This action at least lets us manage the list of required tests via source control - # so that creators of new jobs can add them to this list - require-all-checks-to-pass: - if: always() - runs-on: ubuntu-latest - needs: - - install-root - - prettier-check - - install-core - - core-checks - - install-gui - - gui-checks - - binary-checks - - install-vscode - - vscode-checks - - core-tests - - package-tests - - vscode-get-test-file-matrix - - vscode-package-extension - - vscode-download-e2e-dependencies - - vscode-e2e-tests - - gui-tests - - jetbrains-tests - - config-yaml-checks - - install-config-yaml - - install-openai-adapters - - openai-adapters-tests - - steps: - - name: Decide whether the needed jobs succeeded or failed - uses: re-actors/alls-green@release/v1 - with: - jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 3ef4920ed..611a96f5e 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -29,6 +29,7 @@ jobs: build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' + runs-on: ${{ matrix.os }} strategy: matrix: include: @@ -64,116 +65,28 @@ jobs: platform: darwin arch: arm64 npm_config_arch: arm64 - runs-on: ${{ matrix.os }} steps: - # 1. Check-out repository - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v4 with: - fetch-depth: 0 # This ensures all tags are fetched + fetch-depth: 0 - - name: Checkout tag - run: git checkout ${GITHUB_REF#refs/tags/} - - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" - - name: Cache extension node_modules - uses: actions/cache@v3 + - uses: ./.github/actions/build-vscode-extension with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Build packages (Windows) - run: ./scripts/build-packages.ps1 - if: matrix.os == 'windows-latest' - - - name: Build packages (Unix) - run: ./scripts/build-packages.sh - if: matrix.os != 'windows-latest' - - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci + platform: ${{ matrix.platform }} + arch: ${{ matrix.arch }} + npm_config_arch: ${{ matrix.npm_config_arch }} + pre-release: true env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - name: Install gui Dependencies - run: | - cd gui - npm ci - - # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - - name: Install Core Dependencies - run: | - cd core - npm ci - npm i vectordb - - # - name: Run core tests - # run: | - # cd core - # npm run test - # env: - # OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - - # 2.5. Pre package - - name: Set var for environment info - shell: pwsh - run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV - - - name: Prepackage the extension - run: | - cd extensions/vscode - npm run prepackage -- --target ${{ env.target }} - - # 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js) - - name: Re-install esbuild - run: | - cd extensions/vscode - npm install -f esbuild - - # 4. Run tests for the extension - # - name: Install Xvfb for Linux and run tests - # run: | - # sudo apt-get install -y xvfb # Install Xvfb - # Xvfb :99 & # Start Xvfb - # export DISPLAY=:99 # Export the display number to the environment - # cd extensions/vscode - # npm run test - # if: matrix.os == 'ubuntu-latest' - - # - name: Run extension tests - # run: | - # cd extensions/vscode - # npm run test - # if: matrix.os != 'ubuntu-latest' - - # 5. Package the extension - - name: Package the extension - run: cd extensions/vscode && npx vsce package --pre-release --no-dependencies --target ${{ env.target }} - - # 6. Upload the .vsix as an artifact - - uses: actions/upload-artifact@v4 + - name: Upload .vsix artifact + uses: actions/upload-artifact@v4 with: - name: ${{ env.target }}-vsix + name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix path: "extensions/vscode/*.vsix" release: diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index c05da185f..a7aaee3d5 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -1,8 +1,9 @@ name: Create VS Code main release draft on: - schedule: - # Runs at 7 AM PST (15:00 UTC) every Friday - - cron: "0 15 * * 5" + # Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases. + # schedule: + # # Runs at 7 AM PST (15:00 UTC) every Friday + # - cron: "0 15 * * 5" workflow_dispatch: # Allows manual triggering diff --git a/.vscode/launch.json b/.vscode/launch.json index 53632f8d2..656f25993 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -18,7 +18,7 @@ ], "pauseForSourceMap": false, "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], - "preLaunchTask": "vscode-extension:build", + "preLaunchTask": "vscode-extension:build-with-packages", "env": { // "CONTROL_PLANE_ENV": "local", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 5b0636368..4b8646f07 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -223,6 +223,34 @@ ], "type": "shell", "problemMatcher": [] + }, + { + "label": "Build Continue packages", + "type": "shell", + "command": "node ./scripts/build-packages.js", + "isBackground": true, + "problemMatcher": { + "pattern": { + "regexp": "__DUMMY_PATTERN_THAT_NEVER_MATCHES__", + "file": 1 + }, + "background": { + "activeOnStart": true, + "beginsPattern": ".", + "endsPattern": "." + } + }, + "presentation": { + "reveal": "silent", + "panel": "shared" + } + }, + { + "label": "vscode-extension:build-with-packages", + // "dependsOn": ["vscode-extension:build"], + "dependsOn": ["Build Continue packages", "vscode-extension:build"], + "type": "shell", + "problemMatcher": [] } ] } diff --git a/README.md b/README.md index 654f22d24..fcef59184 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ and [hub of models, rules, prompts, docs, and other building blocks](https://hub - + diff --git a/binary/package-lock.json b/binary/package-lock.json index 11dd6505b..83a78d4d2 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -53,8 +53,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", @@ -77,6 +77,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -90,7 +91,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 0d974e317..d51c15853 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,8 +10,8 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { renderPromptWithTokenLimit } from "./templating/index.js"; import { getAllSnippetsWithoutRace } from "./snippets/index.js"; -import { renderPrompt } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; @@ -186,11 +186,13 @@ export class CompletionProvider { this.ide.getWorkspaceDirs(), ]); - const { prompt, prefix, suffix, completionOptions } = renderPrompt({ - snippetPayload, - workspaceDirs, - helper, - }); + const { prompt, prefix, suffix, completionOptions } = + renderPromptWithTokenLimit({ + snippetPayload, + workspaceDirs, + helper, + llm, + }); // Completion let completion: string | undefined = ""; @@ -208,6 +210,12 @@ export class CompletionProvider { const multiline = !helper.options.transform || shouldCompleteMultiline(helper); + const rawGeneration = await llm.complete( + prompt, + token, + completionOptions, + ); + const completionStream = this.completionStreamer.streamCompletionWithFilters( token, diff --git a/core/autocomplete/templating/__tests__/renderPrompt.vitest.ts b/core/autocomplete/templating/__tests__/renderPrompt.vitest.ts new file mode 100644 index 000000000..039dde6ca --- /dev/null +++ b/core/autocomplete/templating/__tests__/renderPrompt.vitest.ts @@ -0,0 +1,275 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +// ---------- Module mocks ---------- + +// Simple Handlebars mock that does naive placeholder substitution +vi.mock("handlebars", () => { + return { + default: { + compile: (template: string) => (ctx: Record) => { + return template + .replace(/{{prefix}}/g, ctx.prefix) + .replace(/{{suffix}}/g, ctx.suffix) + .replace(/{{filename}}/g, ctx.filename ?? "") + .replace(/{{reponame}}/g, ctx.reponame ?? "") + .replace(/{{language}}/g, ctx.language ?? ""); + }, + }, + }; +}); + +// Token utilities โ€“ we map 1 char = 1 token for simplicity +vi.mock("../../../llm/countTokens", () => { + const countTokens = (str: string) => str.length; + const pruneLinesFromTop = (str: string, allowed: number) => + str.slice(Math.max(0, str.length - allowed)); + const pruneLinesFromBottom = (str: string, allowed: number) => + str.slice(0, allowed); + const getTokenCountingBufferSafety = () => 0; + + return { + countTokens, + pruneLinesFromTop, + pruneLinesFromBottom, + getTokenCountingBufferSafety, + }; +}); + +// Snippet selection โ€“ configurable via constant return value +vi.mock("../filtering", () => ({ + getSnippets: () => [], +})); + +// Snippet formatting +const FORMATTED_SNIPPETS = "[FORMATTED_SNIPPETS]"; +vi.mock("../formatting", () => ({ + formatSnippets: () => FORMATTED_SNIPPETS, +})); + +// Stop tokens helper โ€“ we expose a variable so each test can override it +let stopTokenReturn: string[] = [""]; +vi.mock("../getStopTokens", () => ({ + getStopTokens: () => stopTokenReturn, +})); + +// AutocompleteTemplate โ€“ provide overridable template + compiler + completionOptions +let templateOverride: any = "{{prefix}}|{{suffix}}"; +let compileFnOverride: ((...args: any[]) => [string, string]) | undefined; +let completionOptionsOverride: Record | undefined; +vi.mock("../AutocompleteTemplate", () => ({ + getTemplateForModel: () => ({ + template: templateOverride, + compilePrefixSuffix: compileFnOverride, + completionOptions: completionOptionsOverride ?? {}, + }), +})); + +// ---------- Imports after mocks ---------- +import { renderPrompt, renderPromptWithTokenLimit } from ".."; +import { AutocompleteLanguageInfo } from "../../constants/AutocompleteLanguageInfo"; +import { SnippetPayload } from "../../snippets"; +import { HelperVars } from "../../util/HelperVars"; + +// ---------- Helper builders ---------- + +const tsLang: AutocompleteLanguageInfo = { + name: "TypeScript", + topLevelKeywords: [], + singleLineComment: "//", + endOfLine: [";"], +}; + +const emptySnippetPayload: SnippetPayload = { + rootPathSnippets: [], + importDefinitionSnippets: [], + ideSnippets: [], + recentlyEditedRangeSnippets: [], + recentlyVisitedRangesSnippets: [], + diffSnippets: [], + clipboardSnippets: [], + recentlyOpenedFileSnippets: [], + staticSnippet: [], +}; + +function makeHelper(overrides: any = {}) { + return { + input: { + filepath: "file:///test.ts", + pos: { line: 0, character: 0 }, + recentlyEditedRanges: [], + recentlyVisitedRanges: [], + ...overrides.input, + }, + prunedPrefix: "PRUNED_PREFIX", + prunedSuffix: "PRUNED_SUFFIX", + lang: tsLang, + modelName: "test-model", + filepath: "file:///test.ts", + workspaceUris: [], + options: { + // Default template can be overridden per test + template: "{{prefix}}|{{suffix}}", + maxPromptTokens: 2048, + prefixPercentage: 0.5, + maxSuffixPercentage: 0.5, + experimental_includeClipboard: false, + useRecentlyOpened: false, + experimental_includeRecentlyVisitedRanges: false, + experimental_includeRecentlyEditedRanges: false, + experimental_includeDiff: false, + onlyMyCode: false, + ...overrides.options, + }, + ...overrides, + } as unknown as HelperVars; +} + +afterEach(() => { + // reset overridable mocks + templateOverride = "{{prefix}}|{{suffix}}"; + compileFnOverride = undefined; + completionOptionsOverride = undefined; + stopTokenReturn = [""]; + vi.restoreAllMocks(); +}); + +// ---------- Test suite ---------- + +describe("renderPrompt prefix/suffix selection", () => { + it("uses manuallyPassPrefix when provided", () => { + const helper = makeHelper({ + input: { manuallyPassPrefix: "MANUAL" }, + }); + + const { prefix, suffix } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(suffix).toBe("\n"); + expect(prefix.endsWith("MANUAL")).toBe(true); + }); + + it("falls back to prunedPrefix when no manual prefix", () => { + const helper = makeHelper({}); + + const { prefix } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(prefix.includes("PRUNED_PREFIX")).toBe(true); + }); +}); + +describe("template rendering paths", () => { + it("handles function template", () => { + templateOverride = ( + p: string, + s: string, + _filepath: string, + _reponame: string, + ) => `FUNC:${p}|${s}`; + + const helper = makeHelper({ options: { template: undefined } }); + + const { prompt } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(prompt.startsWith("FUNC:")).toBe(true); + expect(prompt.includes("PRUNED_PREFIX")).toBe(true); + }); +}); + +describe("compilePrefixSuffix vs snippet formatting", () => { + it("applies compilePrefixSuffix when provided", () => { + compileFnOverride = (p: string, s: string) => [`COMP_${p}`, `COMP_${s}`]; + templateOverride = "{{prefix}}|{{suffix}}"; + const helper = makeHelper({ options: { template: undefined } }); + + const { prefix: compiledPrefix } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(compiledPrefix.startsWith("COMP_PRUNED_PREFIX")).toBe(true); + }); + + it("prepends formatted snippets when no compiler present", () => { + const helper = makeHelper({}); + + const { prefix: compiledPrefix } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(compiledPrefix.startsWith(`${FORMATTED_SNIPPETS}\n`)).toBe(true); + }); +}); + +describe("renderPromptWithTokenLimit parity & pruning", () => { + it("matches renderPrompt when llm is undefined", () => { + const helper = makeHelper({}); + + const res1 = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + const res2 = renderPromptWithTokenLimit({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + llm: undefined, + }); + + expect(res2).toEqual(res1); + }); + + it("prunes prefix/suffix to respect small context length", () => { + const longPrefix = "A".repeat(300); + + const helper = makeHelper({ prunedPrefix: longPrefix }); + + const llmStub = { + contextLength: 120, + completionOptions: { maxTokens: 10 }, + model: "test-model", + } as any; + + const { prefix: compiledPrefix } = renderPromptWithTokenLimit({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + llm: llmStub, + }); + + expect(compiledPrefix.length).toBeLessThan(120); + }); +}); + +describe("stop-token merging", () => { + it("returns stop tokens from getStopTokens", () => { + stopTokenReturn = ["LANG_STOP", "TEMPLATE_STOP"]; + completionOptionsOverride = { stop: ["TEMPLATE_STOP"] }; + templateOverride = "{{prefix}}|{{suffix}}"; + + const helper = makeHelper({ options: { template: undefined } }); + + const { completionOptions } = renderPrompt({ + snippetPayload: emptySnippetPayload, + workspaceDirs: ["file:///workspace"], + helper, + }); + + expect(completionOptions?.stop).toEqual(stopTokenReturn); + }); +}); diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 55fb086c4..3ebf29b71 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -4,8 +4,17 @@ import { CompletionOptions } from "../.."; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../util/HelperVars"; +import { ILLM } from "../../index.js"; +import { DEFAULT_MAX_TOKENS } from "../../llm/constants.js"; +import { + countTokens, + getTokenCountingBufferSafety, + pruneLinesFromBottom, + pruneLinesFromTop, +} from "../../llm/countTokens"; import { getUriPathBasename } from "../../util/uri"; import { SnippetPayload } from "../snippets"; +import { AutocompleteSnippet } from "../snippets/types"; import { AutocompleteTemplate, getTemplateForModel, @@ -45,6 +54,49 @@ function renderStringTemplate( }); } +/** Consolidates shared setup between renderPrompt and renderPromptWithTokenLimit. */ +function preparePromptContext({ + snippetPayload, + workspaceDirs, + helper, +}: { + snippetPayload: SnippetPayload; + workspaceDirs: string[]; + helper: HelperVars; +}): { + prefix: string; + suffix: string; + reponame: string; + template: AutocompleteTemplate["template"]; + compilePrefixSuffix: AutocompleteTemplate["compilePrefixSuffix"] | undefined; + completionOptions: Partial | undefined; + snippets: AutocompleteSnippet[]; +} { + // Determine base prefix/suffix, accounting for any manually supplied prefix. + let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix; + let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix; + if (suffix === "") { + suffix = "\n"; + } + + const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject"); + + const { template, compilePrefixSuffix, completionOptions } = + getTemplate(helper); + + const snippets = getSnippets(helper, snippetPayload); + + return { + prefix, + suffix, + reponame, + template, + compilePrefixSuffix, + completionOptions, + snippets, + }; +} + export function renderPrompt({ snippetPayload, workspaceDirs, @@ -59,22 +111,60 @@ export function renderPrompt({ suffix: string; completionOptions: Partial | undefined; } { - // If prefix is manually passed - let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix; - let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix; - if (suffix === "") { - suffix = "\n"; - } + const { + prefix, + suffix, + reponame, + template, + compilePrefixSuffix, + completionOptions, + snippets, + } = preparePromptContext({ snippetPayload, workspaceDirs, helper }); - const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject"); + // Delegate prompt construction to buildPrompt to avoid duplication. + const { + prompt, + prefix: compiledPrefix, + suffix: compiledSuffix, + } = buildPrompt( + template, + compilePrefixSuffix, + prefix, + suffix, + helper, + snippets, + workspaceDirs, + reponame, + ); - const { template, compilePrefixSuffix, completionOptions } = - getTemplate(helper); + const stopTokens = getStopTokens( + completionOptions, + helper.lang, + helper.modelName, + ); - const snippets = getSnippets(helper, snippetPayload); + return { + prompt, + prefix: compiledPrefix, + suffix: compiledSuffix, + completionOptions: { + ...completionOptions, + stop: stopTokens, + }, + }; +} - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix - // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint +/** Builds the final prompt by applying prefix/suffix compilation or snippet formatting, then rendering the template. */ +function buildPrompt( + template: AutocompleteTemplate["template"], + compilePrefixSuffix: AutocompleteTemplate["compilePrefixSuffix"] | undefined, + prefix: string, + suffix: string, + helper: HelperVars, + snippets: AutocompleteSnippet[], + workspaceDirs: string[], + reponame: string, +): { prompt: string; prefix: string; suffix: string } { if (compilePrefixSuffix) { [prefix, suffix] = compilePrefixSuffix( prefix, @@ -85,12 +175,10 @@ export function renderPrompt({ helper.workspaceUris, ); } else { - const formattedSnippets = formatSnippets(helper, snippets, workspaceDirs); - prefix = [formattedSnippets, prefix].join("\n"); + const formatted = formatSnippets(helper, snippets, workspaceDirs); + prefix = [formatted, prefix].join("\n"); } - const prompt = - // Templates can be passed as a Handlebars template string or a function typeof template === "string" ? renderStringTemplate( template, @@ -109,6 +197,105 @@ export function renderPrompt({ snippets, helper.workspaceUris, ); + return { prompt, prefix, suffix }; +} + +function pruneLength(llm: ILLM, prompt: string): number { + const contextLength = llm.contextLength; + const reservedTokens = llm.completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS; + const safetyBuffer = getTokenCountingBufferSafety(contextLength); + const maxAllowedPromptTokens = contextLength - reservedTokens - safetyBuffer; + const promptTokenCount = countTokens(prompt, llm.model); + return promptTokenCount - maxAllowedPromptTokens; +} + +export function renderPromptWithTokenLimit({ + snippetPayload, + workspaceDirs, + helper, + llm, +}: { + snippetPayload: SnippetPayload; + workspaceDirs: string[]; + helper: HelperVars; + llm: ILLM | undefined; +}): { + prompt: string; + prefix: string; + suffix: string; + completionOptions: Partial | undefined; +} { + const { + prefix: initialPrefix, + suffix: initialSuffix, + reponame, + template, + compilePrefixSuffix, + completionOptions, + snippets, + } = preparePromptContext({ snippetPayload, workspaceDirs, helper }); + + // We'll mutate prefix/suffix during pruning, so copy them. + let prefix = initialPrefix; + let suffix = initialSuffix; + + let { + prompt, + prefix: compiledPrefix, + suffix: compiledSuffix, + } = buildPrompt( + template, + compilePrefixSuffix, + prefix, + suffix, + helper, + snippets, + workspaceDirs, + reponame, + ); + + // Truncate prefix and suffix if prompt tokens exceed maxAllowedPromptTokens + if (llm) { + const prune = pruneLength(llm, prompt); + if (prune > 0) { + const tokensToDrop = prune; + const prefixTokenCount = countTokens(prefix, helper.modelName); + const suffixTokenCount = countTokens(suffix, helper.modelName); + const totalContextTokens = prefixTokenCount + suffixTokenCount; + if (totalContextTokens > 0) { + const dropPrefix = Math.ceil( + tokensToDrop * (prefixTokenCount / totalContextTokens), + ); + const dropSuffix = Math.ceil(tokensToDrop - dropPrefix); + const allowedPrefixTokens = Math.max(0, prefixTokenCount - dropPrefix); + const allowedSuffixTokens = Math.max(0, suffixTokenCount - dropSuffix); + prefix = pruneLinesFromTop( + prefix, + allowedPrefixTokens, + helper.modelName, + ); + suffix = pruneLinesFromBottom( + suffix, + allowedSuffixTokens, + helper.modelName, + ); + } + ({ + prompt, + prefix: compiledPrefix, + suffix: compiledSuffix, + } = buildPrompt( + template, + compilePrefixSuffix, + prefix, + suffix, + helper, + snippets, + workspaceDirs, + reponame, + )); + } + } const stopTokens = getStopTokens( completionOptions, @@ -118,8 +305,8 @@ export function renderPrompt({ return { prompt, - prefix, - suffix, + prefix: compiledPrefix, + suffix: compiledSuffix, completionOptions: { ...completionOptions, stop: stopTokens, diff --git a/core/config/json/loadRcConfigs.ts b/core/config/json/loadRcConfigs.ts new file mode 100644 index 000000000..ceb7de77b --- /dev/null +++ b/core/config/json/loadRcConfigs.ts @@ -0,0 +1,31 @@ +import * as JSONC from "comment-json"; +import { ContinueRcJson, FileType, IDE } from "../.."; +import { joinPathsToUri } from "../../util/uri"; + +export async function getWorkspaceRcConfigs( + ide: IDE, +): Promise { + try { + const workspaces = await ide.getWorkspaceDirs(); + const rcFiles = await Promise.all( + workspaces.map(async (dir) => { + const ls = await ide.listDir(dir); + const rcFiles = ls + .filter( + (entry) => + (entry[1] === (1 as FileType.File) || + entry[1] === (64 as FileType.SymbolicLink)) && + entry[0].endsWith(".continuerc.json"), + ) + .map((entry) => joinPathsToUri(dir, entry[0])); + return await Promise.all(rcFiles.map(ide.readFile)); + }), + ); + return rcFiles + .flat() + .map((file) => JSONC.parse(file) as unknown as ContinueRcJson); + } catch (e) { + console.debug("Failed to load workspace configs: ", e); + return []; + } +} diff --git a/core/config/load.ts b/core/config/load.ts index 5206bb8bb..dac5e2174 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -64,6 +64,7 @@ import { localPathToUri } from "../util/pathToUri"; import { getToolsForIde } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; +import { getWorkspaceRcConfigs } from "./json/loadRcConfigs"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; import { getModelByRole, @@ -877,7 +878,6 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { async function loadContinueConfigFromJson( ide: IDE, - workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, @@ -885,6 +885,7 @@ async function loadContinueConfigFromJson( workOsAccessToken: string | undefined, overrideConfigJson: SerializedContinueConfig | undefined, ): Promise> { + const workspaceConfigs = await getWorkspaceRcConfigs(ide); // Serialized config let { config: serialized, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 858085bf9..ff613652a 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,7 +10,6 @@ import { import { ContinueConfig, - ContinueRcJson, IDE, IdeSettings, ILLMLogger, @@ -86,7 +85,6 @@ export default async function doLoadConfig(options: { packageIdentifier, } = options; - const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); const ideSettings = await ideSettingsPromise; @@ -126,7 +124,6 @@ export default async function doLoadConfig(options: { } else { const result = await loadContinueConfigFromJson( ide, - workspaceConfigs, ideSettings, ideInfo, uniqueId, @@ -365,21 +362,3 @@ async function injectControlPlaneProxyInfo( return config; } - -async function getWorkspaceConfigs(ide: IDE): Promise { - const ideInfo = await ide.getIdeInfo(); - let workspaceConfigs: ContinueRcJson[] = []; - - try { - workspaceConfigs = await ide.getWorkspaceConfigs(); - - // Config is sent over the wire from JB so we need to parse it - if (ideInfo.ideType === "jetbrains") { - workspaceConfigs = (workspaceConfigs as any).map(JSON.parse); - } - } catch (e) { - console.debug("Failed to load workspace configs: ", e); - } - - return workspaceConfigs; -} diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 568a30af8..85a0c084a 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -19,8 +19,8 @@ export const sharedConfigSchema = z readResponseTTS: z.boolean(), promptPath: z.string(), useCurrentFileAsContext: z.boolean(), - optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), + onlyUseSystemMessageTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), enableStaticContextualization: z.boolean(), @@ -181,10 +181,12 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.useCurrentFileAsContext = sharedConfig.useCurrentFileAsContext; } - if (sharedConfig.optInNextEditFeature !== undefined) { - configCopy.experimental.optInNextEditFeature = - sharedConfig.optInNextEditFeature; + + if (sharedConfig.onlyUseSystemMessageTools !== undefined) { + configCopy.experimental.onlyUseSystemMessageTools = + sharedConfig.onlyUseSystemMessageTools; } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; diff --git a/core/config/shouldAutoEnableSystemMessageTools.ts b/core/config/shouldAutoEnableSystemMessageTools.ts new file mode 100644 index 000000000..bdebaab1c --- /dev/null +++ b/core/config/shouldAutoEnableSystemMessageTools.ts @@ -0,0 +1,31 @@ +import { ModelDescription } from "../index.d"; + +/** + * Determines if system message tools should be auto-enabled for the given model. + * This is used to automatically enable system message tools for certain provider/model combinations + * where we have a strong preference, taking priority over user manual settings. + * + * System message tools are an alternative to native tool calling where tool definitions and calls + * are embedded in the system message as text rather than using the provider's native tool calling API. + * This can be beneficial for providers/models that don't support native tool calling or have + * poor tool calling performance. + * + * Current auto-enable rules: + * - OpenRouter provider: true for all models except those containing "claude" (since Claude models + * generally have good native tool calling support) + * - All other providers: undefined (no auto-preference, use manual setting) + * + * @param model The model description to check + * @returns true to force enable, false to force disable, undefined for no auto-preference + */ +export function shouldAutoEnableSystemMessageTools( + model: ModelDescription, +): boolean | undefined { + // Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling + if (model.provider === "openrouter") { + return !model.model.toLowerCase().includes("claude"); + } + + // No auto-preference for all other providers - use manual setting + return undefined; +} diff --git a/core/config/shouldAutoEnableSystemMessageTools.vitest.ts b/core/config/shouldAutoEnableSystemMessageTools.vitest.ts new file mode 100644 index 000000000..9e0e9c59c --- /dev/null +++ b/core/config/shouldAutoEnableSystemMessageTools.vitest.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from "vitest"; +import { ModelDescription } from "../index.d"; +import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools"; + +describe("shouldAutoEnableSystemMessageTools", () => { + const createModel = (provider: string, model: string): ModelDescription => ({ + title: "Test Model", + provider, + underlyingProviderName: provider, + model, + }); + + test("should return true for OpenRouter models that don't contain 'claude'", () => { + expect( + shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")), + ).toBe(true); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "llama-3.3-70b-instruct"), + ), + ).toBe(true); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "qwen/qwen-2.5-72b-instruct"), + ), + ).toBe(true); + }); + + test("should return false for OpenRouter Claude models", () => { + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "anthropic/claude-3-sonnet"), + ), + ).toBe(false); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "anthropic/claude-3.5-sonnet"), + ), + ).toBe(false); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "claude-3-haiku"), + ), + ).toBe(false); + }); + + test("should return undefined for all other providers", () => { + expect( + shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")), + ).toBe(undefined); + expect( + shouldAutoEnableSystemMessageTools( + createModel("anthropic", "claude-3.5-sonnet"), + ), + ).toBe(undefined); + expect( + shouldAutoEnableSystemMessageTools( + createModel("groq", "llama-3.3-70b-versatile"), + ), + ).toBe(undefined); + expect( + shouldAutoEnableSystemMessageTools( + createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"), + ), + ).toBe(undefined); + }); + + test("should be case insensitive for 'claude' detection", () => { + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "CLAUDE-models"), + ), + ).toBe(false); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "Claude-3.5"), + ), + ).toBe(false); + expect( + shouldAutoEnableSystemMessageTools( + createModel("openrouter", "some-model-Claude"), + ), + ).toBe(false); + }); +}); diff --git a/core/config/types.ts b/core/config/types.ts index 5cbe28b1b..b9be2b209 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -682,8 +682,6 @@ declare global { getWorkspaceDirs(): Promise; - getWorkspaceConfigs(): Promise; - fileExists(filepath: string): Promise; writeFile(path: string, contents: string): Promise; @@ -745,6 +743,10 @@ declare global { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; + getSignatureHelp(location: Location): Promise; + getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; @@ -1123,7 +1125,6 @@ declare global { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - useTools?: boolean; modelContextProtocolServers?: MCPOptions[]; } diff --git a/core/config/yaml/loadLocalYamlBlocks.ts b/core/config/yaml/loadLocalYamlBlocks.ts new file mode 100644 index 000000000..8c3cde9cb --- /dev/null +++ b/core/config/yaml/loadLocalYamlBlocks.ts @@ -0,0 +1,62 @@ +import { + AssistantUnrolled, + ConfigResult, + PackageIdentifier, + RegistryClient, + unrollAssistantFromContent, +} from "@continuedev/config-yaml"; +import { IDE } from "../.."; +import { ControlPlaneClient } from "../../control-plane/client"; +import { LocalPlatformClient } from "./LocalPlatformClient"; + +// This is a certain approach to unrolling local YAML where it +// 1. creates an assistant out of all local blocks +// 2. unrolls it like a local assistant +export async function unrollLocalYamlBlocks( + packageIdentifiers: PackageIdentifier[], + ide: IDE, + registryClient: RegistryClient, + orgScopeId: string | null, + controlPlaneClient: ControlPlaneClient, +): Promise> { + try { + const unrollResult = await unrollAssistantFromContent( + { + uriType: "file", + filePath: "", + }, + "name: FILLER\nschema: v1\nversion: 0.0.1", + registryClient, + { + currentUserSlug: "", + onPremProxyUrl: null, + orgScopeId, + platformClient: new LocalPlatformClient( + orgScopeId, + controlPlaneClient, + ide, + ), + renderSecrets: true, + injectBlocks: packageIdentifiers, + }, + ); + const config = + "config" in unrollResult ? unrollResult.config : unrollResult; + const errors = "errors" in unrollResult ? unrollResult.errors : []; + return { + config, + errors, + configLoadInterrupted: false, + }; + } catch (error) { + let message = "An unknown error occurred while loading local YAML blocks"; + if (error instanceof Error) { + message += ": " + error.message; + } + return { + config: undefined, + errors: [{ message, fatal: false }], + configLoadInterrupted: false, + }; + } +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4f1a1632f..dbfd88a08 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -4,11 +4,10 @@ import { ConfigResult, ConfigValidationError, isAssistantUnrolledNonNullable, - MCPServer, + mergeUnrolledAssistants, ModelRole, PackageIdentifier, RegistryClient, - Rule, TEMPLATE_VAR_REGEX, unrollAssistant, validateConfigYaml, @@ -17,13 +16,11 @@ import { dirname } from "node:path"; import { ContinueConfig, - ExperimentalMCPOptions, IContextProvider, IDE, IdeInfo, IdeSettings, ILLMLogger, - RuleWithSource, } from "../.."; import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; @@ -41,41 +38,13 @@ import { getControlPlaneEnvSync } from "../../control-plane/env"; import { getToolsForIde } from "../../tools"; import { getCleanUriPath } from "../../util/uri"; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; +import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; - -function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { - if (typeof rule === "string") { - return { - rule: rule, - source: "rules-block", - }; - } else { - return { - source: "rules-block", - rule: rule.rule, - globs: rule.globs, - name: rule.name, - ruleFile: rule.sourceFile, - alwaysApply: rule.alwaysApply, - }; - } -} - -function convertYamlMcpToContinueMcp( - server: MCPServer, -): ExperimentalMCPOptions { - return { - transport: { - type: "stdio", - command: server.command, - args: server.args ?? [], - env: server.env, - cwd: server.cwd, - } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) - timeout: server.connectionTimeout, - }; -} +import { + convertYamlMcpToContinueMcp, + convertYamlRuleToContinueRule, +} from "./yamlToContinueConfig"; async function loadConfigYaml(options: { overrideConfigYaml: AssistantUnrolled | undefined; @@ -95,46 +64,65 @@ async function loadConfigYaml(options: { } = options; // Add local .continue blocks - const allLocalBlocks: PackageIdentifier[] = []; - for (const blockType of BLOCK_TYPES) { + const localBlockPromises = BLOCK_TYPES.map(async (blockType) => { const localBlocks = await getAllDotContinueDefinitionFiles( ide, { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" }, blockType, ); - allLocalBlocks.push( - ...localBlocks.map((b) => ({ - uriType: "file" as const, - filePath: b.path, - })), - ); - } - - const rootPath = - packageIdentifier.uriType === "file" - ? dirname(getCleanUriPath(packageIdentifier.filePath)) - : undefined; + return localBlocks.map((b) => ({ + uriType: "file" as const, + filePath: b.path, + })); + }); + const localPackageIdentifiers: PackageIdentifier[] = ( + await Promise.all(localBlockPromises) + ).flat(); // logger.info( // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, // ); + // Registry client is only used if local blocks are present, but logic same for hub/local assistants + const getRegistryClient = async () => { + const rootPath = + packageIdentifier.uriType === "file" + ? dirname(getCleanUriPath(packageIdentifier.filePath)) + : undefined; + return new RegistryClient({ + accessToken: await controlPlaneClient.getAccessToken(), + apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment) + .CONTROL_PLANE_URL, + rootPath, + }); + }; + const errors: ConfigValidationError[] = []; let config: AssistantUnrolled | undefined; if (overrideConfigYaml) { config = overrideConfigYaml; + if (localPackageIdentifiers.length > 0) { + const unrolledLocal = await unrollLocalYamlBlocks( + localPackageIdentifiers, + ide, + await getRegistryClient(), + orgScopeId, + controlPlaneClient, + ); + if (unrolledLocal.errors) { + errors.push(...unrolledLocal.errors); + } + if (unrolledLocal.config) { + config = mergeUnrolledAssistants(config, unrolledLocal.config); + } + } } else { // This is how we allow use of blocks locally const unrollResult = await unrollAssistant( packageIdentifier, - new RegistryClient({ - accessToken: await controlPlaneClient.getAccessToken(), - apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment) - .CONTROL_PLANE_URL, - rootPath, - }), + await getRegistryClient(), { renderSecrets: true, currentUserSlug: "", @@ -145,7 +133,7 @@ async function loadConfigYaml(options: { controlPlaneClient, ide, ), - injectBlocks: allLocalBlocks, + injectBlocks: localPackageIdentifiers, }, ); config = unrollResult.config; diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts new file mode 100644 index 000000000..8d61e06bc --- /dev/null +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -0,0 +1,35 @@ +import { MCPServer, Rule } from "@continuedev/config-yaml"; +import { ExperimentalMCPOptions, RuleWithSource } from "../.."; + +export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { + if (typeof rule === "string") { + return { + rule: rule, + source: "rules-block", + }; + } else { + return { + source: "rules-block", + rule: rule.rule, + globs: rule.globs, + name: rule.name, + ruleFile: rule.sourceFile, + alwaysApply: rule.alwaysApply, + }; + } +} + +export function convertYamlMcpToContinueMcp( + server: MCPServer, +): ExperimentalMCPOptions { + return { + transport: { + type: "stdio", + command: server.command, + args: server.args ?? [], + env: server.env, + cwd: server.cwd, + } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union) + timeout: server.connectionTimeout, + }; +} diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 1a97b82e8..58b2ed71b 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -58,7 +58,7 @@ export class ControlPlaneClient { })); } - const resp = await this.request("ide/sync-secrets", { + const resp = await this.requestAndHandleError("ide/sync-secrets", { method: "POST", body: JSON.stringify({ fqsns, orgScopeId }), }); @@ -101,6 +101,15 @@ export class ControlPlaneClient { }, }); + return resp; + } + + private async requestAndHandleError( + path: string, + init: RequestInit, + ): Promise { + const resp = await this.request(path, init); + if (!resp.ok) { throw new Error( `Control plane request failed: ${resp.status} ${await resp.text()}`, @@ -128,7 +137,7 @@ export class ControlPlaneClient { ? `ide/list-assistants?organizationId=${organizationId}` : "ide/list-assistants"; - const resp = await this.request(url, { + const resp = await this.requestAndHandleError(url, { method: "GET", }); return (await resp.json()) as any; @@ -142,15 +151,48 @@ export class ControlPlaneClient { return []; } - try { + // We try again here because when users sign up with an email domain that is + // captured by an org, we need to wait for the user account creation webhook to + // take effect. Otherwise the organization(s) won't show up. + // This error manifests as a 404 (user not found) + let retries = 0; + const maxRetries = 10; + const maxWaitTime = 20000; // 20 seconds in milliseconds + + while (retries < maxRetries) { const resp = await this.request("ide/list-organizations", { method: "GET", }); + + if (resp.status === 404) { + retries++; + if (retries >= maxRetries) { + console.warn( + `Failed to list organizations after ${maxRetries} retries: user not found`, + ); + return []; + } + const waitTime = Math.min( + Math.pow(2, retries) * 100, + maxWaitTime / maxRetries, + ); + await new Promise((resolve) => setTimeout(resolve, waitTime)); + continue; + } else if (!resp.ok) { + console.warn( + `Failed to list organizations (${resp.status}): ${await resp.text()}`, + ); + return []; + } const { organizations } = (await resp.json()) as any; return organizations; - } catch (e) { - return []; } + + // This should never be reached due to the while condition, but adding for safety + console.warn( + `Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`, + ); + return []; } public async listAssistantFullSlugs( @@ -165,7 +207,7 @@ export class ControlPlaneClient { : "ide/list-assistant-full-slugs"; try { - const resp = await this.request(url, { + const resp = await this.requestAndHandleError(url, { method: "GET", }); const { fullSlugs } = (await resp.json()) as any; @@ -181,7 +223,7 @@ export class ControlPlaneClient { } try { - const resp = await this.request("ide/free-trial-status", { + const resp = await this.requestAndHandleError("ide/free-trial-status", { method: "GET", }); return (await resp.json()) as FreeTrialStatus; @@ -212,7 +254,7 @@ export class ControlPlaneClient { params.set("vscode_uri_scheme", vsCodeUriScheme); } - const resp = await this.request( + const resp = await this.requestAndHandleError( `ide/get-models-add-on-checkout-url?${params.toString()}`, { method: "GET", diff --git a/core/core.ts b/core/core.ts index ea3e678dc..2db7856d1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -410,6 +410,10 @@ export class Core { await this.messenger.request("openUrl", url); }); + on("controlPlane/getEnvironment", async (msg) => { + return await getControlPlaneEnv(this.ide.getIdeSettings()); + }); + on("controlPlane/getFreeTrialStatus", async (msg) => { return this.configHandler.controlPlaneClient.getFreeTrialStatus(); }); @@ -599,6 +603,7 @@ export class Core { const outcome = await this.nextEditProvider.provideInlineCompletionItems( msg.data, undefined, + { withChain: false }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); @@ -756,6 +761,9 @@ export class Core { }); on("files/closed", async ({ data }) => { + console.log("deleteChain called from files/closed"); + await NextEditProvider.getInstance().deleteChain(); + try { const fileUris = await this.ide.getOpenFiles(); if (fileUris) { diff --git a/core/index.d.ts b/core/index.d.ts index 65c207e78..5ce9b2dae 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -811,8 +811,6 @@ export interface IDE { getWorkspaceDirs(): Promise; - getWorkspaceConfigs(): Promise; - fileExists(fileUri: string): Promise; writeFile(path: string, contents: string): Promise; @@ -881,6 +879,8 @@ export interface IDE { gotoDefinition(location: Location): Promise; gotoTypeDefinition(location: Location): Promise; // TODO: add to jetbrains getSignatureHelp(location: Location): Promise; // TODO: add to jetbrains + getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -1091,6 +1091,7 @@ export interface Tool { faviconUrl?: string; group: string; originalFunctionName?: string; + systemMessageDescription?: string; } interface ToolChoice { @@ -1521,6 +1522,7 @@ export interface ExperimentalConfig { defaultContext?: DefaultContextProvider[]; promptPath?: string; enableExperimentalTools?: boolean; + onlyUseSystemMessageTools?: boolean; /** * Quick actions are a way to add custom commands to the Code Lens of @@ -1546,11 +1548,6 @@ export interface ExperimentalConfig { */ useCurrentFileAsContext?: boolean; - /** - * If enabled, will enable next edit in place of autocomplete - */ - optInNextEditFeature?: boolean; - /** * If enabled, @codebase will only use tool calling * instead of embeddings, FTS, recently edited files, etc. @@ -1805,3 +1802,56 @@ export interface CompiledMessagesResult { export interface MessageOption { precompiled: boolean; } + +/* LSP-specific interfaces. */ + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolKind. +// We shift this one index down to match vscode.SymbolKind. +export enum SymbolKind { + File = 0, + Module = 1, + Namespace = 2, + Package = 3, + Class = 4, + Method = 5, + Property = 6, + Field = 7, + Constructor = 8, + Enum = 9, + Interface = 10, + Function = 11, + Variable = 12, + Constant = 13, + String = 14, + Number = 15, + Boolean = 16, + Array = 17, + Object = 18, + Key = 19, + Null = 20, + EnumMember = 21, + Struct = 22, + Event = 23, + Operator = 24, + TypeParameter = 25, +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export namespace SymbolTag { + export const Deprecated: 1 = 1; +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export type SymbolTag = 1; + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#documentSymbol. +export interface DocumentSymbol { + name: string; + detail?: string; + kind: SymbolKind; + tags?: SymbolTag[]; + deprecated?: boolean; + range: Range; + selectionRange: Range; + children?: DocumentSymbol[]; +} diff --git a/core/jest.config.js b/core/jest.config.js index e4464b264..2fcbc3c5c 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -7,7 +7,7 @@ export default { "ts-jest", { useESM: true, - useIsolatedModules: true, + isolatedModules: true, tsconfig: { experimentalDecorators: true, emitDecoratorMetadata: true, diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..92693456d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - ModelCapability, - ModelDescription, - TemplateType, -} from "../index.js"; +import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; import { anthropicTemplateMessages, @@ -41,7 +36,6 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit.js"; -import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", @@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "granite-vision", ]; -function modelSupportsTools(modelDescription: ModelDescription) { - if (modelDescription.capabilities?.tools !== undefined) { - return modelDescription.capabilities.tools; - } - const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; - if (!providerSupport) { - return false; - } - return providerSupport(modelDescription.model) ?? false; -} - function modelSupportsImages( provider: string, model: string, @@ -400,5 +383,4 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, }; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index c84003b8b..9d1badd0c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -355,7 +355,7 @@ function pruneStringFromTop( const MAX_TOKEN_SAFETY_BUFFER = 1000; const TOKEN_SAFETY_PROPORTION = 0.02; -function getTokenCountingBufferSafety(contextLength: number) { +export function getTokenCountingBufferSafety(contextLength: number) { return Math.min( MAX_TOKEN_SAFETY_BUFFER, contextLength * TOKEN_SAFETY_PROPORTION, diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index b4ecf8e91..edb5753fb 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -61,6 +61,8 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. + If you need to use multiple tools, you can call call multiple read only tools simultaneously. + ${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; diff --git a/core/llm/index.ts b/core/llm/index.ts index 6a67cac6c..f280eedd4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -531,7 +531,7 @@ export abstract class BaseLLM implements ILLM { let contentToShow = ""; if (msg.role === "tool") { contentToShow = msg.content; - } else if (msg.role === "assistant" && msg.toolCalls) { + } else if (msg.role === "assistant" && msg.toolCalls?.length) { contentToShow = msg.toolCalls ?.map( (toolCall) => @@ -539,10 +539,7 @@ export abstract class BaseLLM implements ILLM { ) .join("\n"); } else if ("content" in msg) { - if (Array.isArray(msg.content)) { - msg.content = renderChatMessage(msg); - } - contentToShow = msg.content; + contentToShow = renderChatMessage(msg); } return `<${msg.role}>\n${contentToShow}\n\n`; diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index c3acdb211..f3afd4c4b 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -213,7 +213,7 @@ describe("LLM", () => { testToolCall: true, }); testLLM( - new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), + new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o3-mini" }), { skip: false, timeout: 60000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { diff --git a/core/llm/llms/OpenAI.vitest.ts b/core/llm/llms/OpenAI.vitest.ts index d48bbd403..b07f05b15 100644 --- a/core/llm/llms/OpenAI.vitest.ts +++ b/core/llm/llms/OpenAI.vitest.ts @@ -275,7 +275,7 @@ describe("OpenAI", () => { test("should handle O1 models correctly", async () => { const openai = new OpenAI({ apiKey: "test-api-key", - model: "o1-preview", + model: "o3-mini", apiBase: "https://api.openai.com/v1/", }); @@ -296,7 +296,7 @@ describe("OpenAI", () => { "api-key": "test-api-key", }, body: { - model: "o1-preview", + model: "o3-mini", messages: [{ role: "user", content: "hello" }], stream: true, max_completion_tokens: 100, diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index a3b643c34..a7edbbd36 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,4 +1,5 @@ import { parseProxyModelName } from "@continuedev/config-yaml"; +import { ModelDescription } from ".."; export const PROVIDER_TOOL_SUPPORT: Record boolean> = { @@ -288,3 +289,31 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, }; + +export function isRecommendedAgentModel(modelName: string): boolean { + // AND behavior + const recs: RegExp[][] = [ + [/o[134]/], + [/deepseek/, /r1|reasoner/], + [/gemini/, /2\.5/, /pro/], + [/gpt/, /4/], + [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], + [/claude/, /opus/, /-4/], + ]; + for (const combo of recs) { + if (combo.every((regex) => modelName.toLowerCase().match(regex))) { + return true; + } + } + return false; +} +export function modelSupportsNativeTools(modelDescription: ModelDescription) { + if (modelDescription.capabilities?.tools !== undefined) { + return modelDescription.capabilities.tools; + } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; + if (!providerSupport) { + return false; + } + return providerSupport(modelDescription.model) ?? false; +} diff --git a/core/llm/utils/retry.test.ts b/core/llm/utils/retry.test.ts index 665e010c1..111463a0d 100644 --- a/core/llm/utils/retry.test.ts +++ b/core/llm/utils/retry.test.ts @@ -450,8 +450,9 @@ describe("Retry Functionality", () => { expect(result).toBe("success"); // Should be capped at maxDelay (200ms) not header value (10000ms) - expect(delays[0]).toBeGreaterThan(190); - expect(delays[0]).toBeLessThan(210); + // Jitter is applied before maxDelay cap, so delay should never exceed maxDelay + expect(delays[0]).toBeGreaterThanOrEqual(190); + expect(delays[0]).toBeLessThanOrEqual(200); }); it("should handle case-insensitive header names", async () => { diff --git a/core/llm/utils/retry.ts b/core/llm/utils/retry.ts index 416851378..dce06ef5c 100644 --- a/core/llm/utils/retry.ts +++ b/core/llm/utils/retry.ts @@ -149,10 +149,10 @@ function calculateDelay( delayMs = Number(retryAfter) * 1000; } - // Respect maxDelay and add small jitter to spread requests - const cappedDelay = Math.min(delayMs, maxDelay); + // Apply small jitter to spread requests, then respect maxDelay as hard limit const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ยฑ5% - return Math.max(0, Math.floor(cappedDelay * jitterMultiplier)); + const jitteredDelay = delayMs * jitterMultiplier; + return Math.max(0, Math.floor(Math.min(jitteredDelay, maxDelay))); } } diff --git a/core/nextEdit/DocumentHistoryTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts new file mode 100644 index 000000000..7cca91f56 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.ts @@ -0,0 +1,137 @@ +import Parser from "web-tree-sitter"; + +/** + * Singleton class that keeps track of a map of document paths to their history. + * The point here is to prevent re-calculating the AST, + * and to preserve an older, original state of the document before any user edits. + */ +export class DocumentHistoryTracker { + private static instance: DocumentHistoryTracker | null = null; + + // Map from document path to history (LIFO stack where newest representation is at the front). + private documentAstMap: Map; + private documentContentHistoryMap: Map; + + private constructor() { + this.documentAstMap = new Map(); + this.documentContentHistoryMap = new Map(); + } + + /** + * Get the singleton instance of DocumentHistoryTracker. + */ + public static getInstance(): DocumentHistoryTracker { + if (!DocumentHistoryTracker.instance) { + DocumentHistoryTracker.instance = new DocumentHistoryTracker(); + } + + return DocumentHistoryTracker.instance; + } + + /** + * Add a document and its first state to the tracker. + * + * @param documentPath The path of the document. + * @param documentContent The first content of the document. + * @param ast The first AST of the document. + */ + public addDocument( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + this.documentAstMap.set(documentPath, [ast]); + this.documentContentHistoryMap.set(documentPath, [documentContent]); + } + + /** + * Push a new AST to an existing document's history stack. + * + * @param documentPath The path of the document. + * @param documentContent The new content to push to the document's history stack. + * @param ast The new AST to push to the document's history stack. + * @throws Error if the document doesn't exist in the tracker. + */ + public push( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + const astHistory = this.documentAstMap.get(documentPath); + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!astHistory || !documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + this.addDocument(documentPath, documentContent, ast); + return; // Early return - document was added with initial state + } + + // Only execute this if the arrays already existed + astHistory.unshift(ast); + documentHistory.unshift(documentContent); + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent AST of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentAst(documentPath: string): Parser.Tree | null { + const astHistory = this.documentAstMap.get(documentPath); + + if (!astHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (astHistory.length === 0) { + console.error(`Document ${documentPath} has no ASTs`); + return null; + } + + // Return the first element (most recent AST). + return astHistory[0]; + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent document history of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentDocumentHistory(documentPath: string): string | null { + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (documentHistory.length === 0) { + console.error(`Document ${documentPath} has no history`); + return null; + } + + // Return the first element (most recent doc history). + return documentHistory[0]; + } + + /** + * Delete a document from the tracker. + * + * @param documentPath The path of the document to delete. + */ + public deleteDocument(documentPath: string): void { + this.documentAstMap.delete(documentPath); + this.documentContentHistoryMap.delete(documentPath); + } + + /** + * Clear all documents from the tracker. + */ + public clearMap(): void { + this.documentAstMap.clear(); + this.documentContentHistoryMap.clear(); + } +} diff --git a/core/nextEdit/DocumentHistoryTracker.vitest.ts b/core/nextEdit/DocumentHistoryTracker.vitest.ts new file mode 100644 index 000000000..f6c9b2dd4 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.vitest.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import Parser from "web-tree-sitter"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +// Mock the Parser.Tree class +vi.mock("web-tree-sitter", () => { + return { + default: { + Tree: class MockTree { + constructor() { + // Mock implementation + } + }, + }, + }; +}); + +describe("DocumentHistoryTracker", () => { + let tracker: DocumentHistoryTracker; + let mockAst1: Parser.Tree; + let mockAst2: Parser.Tree; + const testDocPath = "/test/document.ts"; + const testContent1 = "const x = 1;"; + const testContent2 = "const x = 2;"; + + beforeEach(() => { + // Reset singleton instance for each test + // @ts-ignore - accessing private static property for testing + DocumentHistoryTracker.instance = null; + tracker = DocumentHistoryTracker.getInstance(); + + // Create mock ASTs + //@ts-ignore + mockAst1 = new Parser.Tree() as Parser.Tree; + //@ts-ignore + mockAst2 = new Parser.Tree() as Parser.Tree; + }); + + afterEach(() => { + // Clear the tracker after each test + tracker.clearMap(); + }); + + describe("getInstance", () => { + it("should return a singleton instance", () => { + const instance1 = DocumentHistoryTracker.getInstance(); + const instance2 = DocumentHistoryTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("addDocument", () => { + it("should add a document to the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst1); + expect(content).toBe(testContent1); + }); + }); + + describe("push", () => { + it("should push a new AST to an existing document's history stack", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst2); + expect(content).toBe(testContent2); + }); + + it("should add a document if it doesn't exist when pushing", () => { + tracker.push(testDocPath, testContent1, mockAst1); + + // Check if document was actually added + const ast = tracker.getMostRecentAst(testDocPath); + expect(ast).toBe(mockAst1); + }); + }); + + describe("getMostRecentAst", () => { + it("should return the most recent AST of a document", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBe(mockAst2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst("nonexistent-path"); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no ASTs", () => { + // This test would require modifying private properties + // So we'll mock an empty array situation + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentAstMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no ASTs`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("getMostRecentDocumentHistory", () => { + it("should return the most recent document history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBe(testContent2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory("nonexistent-path"); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentContentHistoryMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no history`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("deleteDocument", () => { + it("should delete a document from the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.deleteDocument(testDocPath); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBeNull(); + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} not found in AST tracker`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("clearMap", () => { + it("should clear all documents from the tracker", () => { + const anotherDocPath = "/test/another-document.ts"; + + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.addDocument(anotherDocPath, testContent1, mockAst1); + + tracker.clearMap(); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + expect(tracker.getMostRecentAst(testDocPath)).toBeNull(); + expect(tracker.getMostRecentAst(anotherDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(testDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(anotherDocPath)).toBeNull(); + + consoleErrorSpy.mockRestore(); + }); + }); +}); diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts new file mode 100644 index 000000000..0bb9537d7 --- /dev/null +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -0,0 +1,800 @@ +import Parser from "web-tree-sitter"; +import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; +import { getAst } from "../autocomplete/util/ast"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +export enum EditableRegionStrategy { + Naive = "naive", + Rerank = "rerank", + StaticRerank = "staticRerank", + Static = "static", +} + +export async function getNextEditableRegion( + strategy: EditableRegionStrategy, + ctx: any, +): Promise { + switch (strategy) { + case EditableRegionStrategy.Naive: + return naiveJump(ctx); + case EditableRegionStrategy.Rerank: + return await rerankJump(ctx); + case EditableRegionStrategy.StaticRerank: + return await staticRerankJump(ctx); + case EditableRegionStrategy.Static: + return await staticJump(ctx); + default: + return null; + } +} + +// Naive assumes that the entire file is editable. +// This relies on the next edit model to figure out where to jump next. +function naiveJump(ctx: any): RangeInFile[] | null { + const { fileLines, filepath } = ctx; + if (!fileLines || !filepath) { + console.warn("Missing required context for naive jump"); + return null; + } + + return [ + { + filepath, + range: { + start: { line: 0, character: 0 }, + end: { + line: fileLines.length - 1, + character: fileLines.at(-1).length, + }, + }, + }, + ]; +} + +// A rerank jump splits the current file into chunks. +// Then it uses a rerank model to get the most relevant chunks and their positions. +async function rerankJump(ctx: { + fileContent: string; + query: string; + filepath: string; + reranker: ILLM; + chunkSize: number; +}): Promise { + try { + const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; + + if (!fileContent || !query || !filepath || !reranker) { + console.warn( + "Missing required context for rerank jump:", + !fileContent, + !query, + !filepath, + !reranker, + ); + return null; + } + + const lines = fileContent.split("\n"); + const chunks: Chunk[] = []; + + // Create chunks from the file. + for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { + const endLine = Math.min(i + chunkSize - 1, lines.length - 1); + const chunkContent = lines.slice(i, endLine + 1).join("\n"); + if (chunkContent === "") continue; // Voyager throws an error if there are empty strings in its document field in the body. + chunks.push({ + content: chunkContent, + startLine: i, + endLine: endLine, + digest: `chunk-${i}-${endLine}`, + filepath: filepath, + index: i, + }); + } + + // Use the reranker to score each chunk against the query. + const scores = await reranker.rerank(query, chunks); + + // Sort by score in descending order and get the highest scoring chunk. + chunks.sort( + (a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)], + ); + + // const mostRelevantChunk = chunks[0]; + // Get the third most relevant chunk if there are enough chunks, + // otherwise fallback to second or first. + // The most relevant chunk seems to be the one that + // is similar enough lexically, + // but different enough to still justify making an edit. + const chunkIndex = Math.min(2, chunks.length - 1); + const mostRelevantChunk = chunks[chunkIndex]; + + // Return the range of the most relevant chunk. + // NOTE: It might be better to return a list of chunks, + // because it's very difficult to gauge when to stop the model. + // We could argue that we should always try to jump until the user says no. + return [ + { + filepath, + range: { + start: { line: mostRelevantChunk.startLine, character: 0 }, + end: { + line: mostRelevantChunk.endLine, + character: lines[mostRelevantChunk.endLine].length, + }, + }, + }, + ]; + } catch (error) { + console.error("Error in rerank jump:", error); + return null; + } +} + +// A static rerank jump runs a lightweight static analysis on the file +// and uses the reranker to jump to relevant locations. +async function staticRerankJump(ctx: { + oldFileContent: string; + newFileContent: string; + completionRange: Range; + filepath: string; + ide: IDE; + reranker?: ILLM; + chunkSize?: number; +}): Promise { + try { + const { oldFileContent, newFileContent, completionRange, filepath, ide } = + ctx; + + if ( + !oldFileContent || + !newFileContent || + !completionRange || + !filepath || + !ide + ) { + console.warn( + "Missing required context for static rerank jump:", + !oldFileContent, + !newFileContent, + !completionRange, + !filepath, + !ide, + ); + return null; + } + + // TODO: + // Parse the old file contents into an AST. + // Parse the new file contents into an AST. + // Compare the two trees and find which nodes have changed. + // Save the queue of changed nodes. The queue should contain the old node and the new node. Each of them can be null if the change is a deletion or insertion. + // Rank the queue by node depth (decreasing order because we want granular edits). + // Pop front until we find a queue item with an old node != null. + // Search the codebase for the old node's expression. For this, either use ide.getReferences(some_location), or other methods you see fit. If you can utilize the strategy pattern, even better. + // For now, filter out results from outside files. We only want to keep the results in the current file. + // Return the first result from this filtered list of results. + + // Parse the old file contents into an AST. + const oldAst = await getAst(filepath, oldFileContent); + if (!oldAst) return null; + + // Parse the new file contents into an AST. + const newAst = await getAst(filepath, newFileContent); + if (!newAst) return null; + + // Compare the two trees and find which nodes have changed. + const changedNodes = compareAsts(oldAst, newAst); + if (!changedNodes || changedNodes.length === 0) return null; + + // Save the queue of changed nodes. + // The queue should contain the old node and the new node. + // Each can be null if the change is a deletion or insertion. + // const nodeQueue = changedNodes.map((change) => ({ + // oldNode: change.oldNode, + // newNode: change.newNode, + // depth: change.depth, + // })); + + // Rank the queue by node depth. + // Decreasing order for granular edits. + // Increasing order for larger definition-based searches. + // Making it decreasing has issues when the deepest node is a string_fragment. + const nodeQueue = changedNodes.sort((a, b) => a.depth - b.depth); + console.log( + "nodeQueue:", + nodeQueue.map((node) => ({ + oldText: node.oldNode?.text || "", + newText: node.newNode?.text || "", + oldType: node.oldNode?.type || "", + newType: node.newNode?.type || "", + depth: node.depth, + })), + ); + + // Find the first item with a non-null old node. + let targetNode = null; + while (nodeQueue.length > 0 && !targetNode) { + const candidate = nodeQueue.shift(); + if ( + candidate && + candidate.oldNode && + candidate.oldNode.type !== "program" + ) { + targetNode = candidate.oldNode; + } + } + + if (!targetNode) return null; + + // Get the text representation of the old node's expression. + const nodeText = getNodeText(targetNode); + if (!nodeText || nodeText.trim() === "") return null; + + // Search for similar code in the file. + let references: RangeInFile[] = []; + + // Try to use IDE's reference finding capabilities if available. + try { + // Get the position of the target node in the old file. + const nodePosition = getNodePosition(targetNode); + if (nodePosition) { + // Use IDE to find references. + + // TODO: + // Get the list of document symbols using await ide.getDocumentSymbols. + // Each document symbol will be our query. + // Use the rerank model to rank the nodeText against the query. + // Get the highest scoring query and its location. + + // Get the list of document symbols using await ide.getDocumentSymbols. + // Filter out symbols that are directly inside the completion range. + const symbols = await ide.getDocumentSymbols(filepath); + + // Filter out symbols that are directly inside the completion range + const filteredSymbols = symbols.filter((symbol) => { + // Check if the symbol's range is outside of the completion range + return !doRangesOverlap(symbol.range, completionRange); + }); + + // Use the reranker to rank the filtered symbols against the node text. + if (!ctx.reranker) { + console.warn("No reranker available for static jump symbol ranking"); + return null; + } + + const symbolChunks: Chunk[] = filteredSymbols.map((symbol) => ({ + content: symbol.name, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + digest: `symbol-${symbol.name}-${symbol.range.start.line}`, + filepath: filepath, + index: symbol.range.start.line, + })); + + if (symbolChunks.length === 0) { + console.warn("No symbols found for ranking"); + return null; + } + + const scores = await ctx.reranker.rerank(nodeText, symbolChunks); + symbolChunks.sort( + (a, b) => + scores[symbolChunks.indexOf(b)] - scores[symbolChunks.indexOf(a)], + ); + + const mostRelevantSymbol = symbolChunks[0]; + const originalSymbol = filteredSymbols.find( + (symbol) => + symbol.range.start.line === mostRelevantSymbol.startLine && + symbol.range.end.line === mostRelevantSymbol.endLine, + ); + + if (originalSymbol) { + references = [ + { + filepath, + range: originalSymbol.range, + }, + ]; + } + + // const foundReferences = await ide.getReferences({ + // filepath, + // position: nodePosition, + // }); + + // if (foundReferences && foundReferences.length > 0) { + // references = foundReferences; + // } + } + } catch (e) { + console.warn( + "Failed to use IDE references, falling back to text search:", + e, + ); + } + + // If IDE reference finding failed or returned no results, fall back to text search. + if (references.length === 0) { + references = findTextOccurrences(oldFileContent, nodeText).map( + (range) => ({ filepath, range }), + ); + } + + // Filter out results from outside the current file. + const currentFileReferences = references.filter( + (ref) => ref.filepath === filepath, + ); + + // Return the first reference if any found. + if (currentFileReferences.length > 0) { + return [currentFileReferences[0]]; + // return currentFileReferences; + } + + return null; + } catch (error) { + console.error("Error in static jump:", error); + return null; + } +} + +// Static jump relies purely on static analysis +// to determine where to edit next. +async function staticJump(ctx: { + cursorPosition: { line: number; character: number }; + filepath: string; + ide: IDE; +}): Promise { + try { + const { cursorPosition, filepath, ide } = ctx; + if (!cursorPosition || !filepath || !ide) { + console.warn( + "Missing required context for static jump:", + !cursorPosition, + !filepath, + !ide, + ); + return null; + } + + // Get the file's AST. + // Getting this once helps us live-track the current node. + const tree = + await DocumentHistoryTracker.getInstance().getMostRecentAst(filepath); + // const tree = await getAst(filepath, fileContent); + if (!tree) return null; + + // Convert cursor position to tree-sitter point format (0-based). + const point = { + row: cursorPosition.line, + column: cursorPosition.character, + }; + + // Find the node at the cursor position. + const nodeAtCursor = tree.rootNode.descendantForPosition(point); + if (!nodeAtCursor) { + console.log("No node found at cursor position"); + return null; + } + + // Find the closest identifier node. + const identifierNode = findClosestIdentifierNode(nodeAtCursor); + if (!identifierNode) { + console.log("No identifier node found near cursor position"); + return null; + } + // console.log("closest identifier:", identifierNode.text); + + // Get all references to this identifier using the IDE's API + const references = await ide.getReferences({ + filepath, + position: { + line: identifierNode.startPosition.row, + character: identifierNode.startPosition.column, + }, + }); + + if (!references || references.length === 0) { + console.log(`No references found for identifier: ${identifierNode.text}`); + return null; + } + + // console.log( + // "references:", + // JSON.stringify( + // references.map((ref) => ({ + // line: ref.range.start.line, + // character: ref.range.start.character, + // })), + // null, + // 2, + // ), + // ); + + return references.length > 1 ? references.slice(1) : null; + } catch (error) { + console.error("Error in staticJump:", error); + return null; + } +} + +/* AST HELPER FUNCTIONS */ + +// Helper function to find the closest identifier node. +function findClosestIdentifierNode( + node: Parser.SyntaxNode | null, +): Parser.SyntaxNode | null { + if (!node) return null; + + if (isIdentifierNode(node)) return node; + if (isDeclarationNode(node)) return findLeftmostIdentifier(node); + + // Check if the parent is an identifier. + // NOTE: This will probably never get triggered. + // Most identifiers are leaf nodes. + const parent = node.parent; + if (parent && isIdentifierNode(parent)) { + return parent; + } + + if (parent) { + if (isDeclarationNode(parent)) return findLeftmostIdentifier(parent); + + // Check if one of the siblings is an identifier. + for (let i = 0; i < parent.childCount; ++i) { + // const sibling = node.child(i); + const sibling = parent.child(i); + if (sibling && isIdentifierNode(sibling)) { + // Get the leftmost identifier sibling. + return sibling; + } + } + } + + return findClosestIdentifierNode(parent); +} + +function findLeftmostIdentifier( + node: Parser.SyntaxNode, +): Parser.SyntaxNode | null { + if (isIdentifierNode(node)) return node; + + for (let i = 0; i < node.childCount; ++i) { + const child = node.child(i); + if (child) { + const result = findLeftmostIdentifier(child); + if (result) return result; + } + } + + return null; +} + +// Helper function to check if a node is an identifier. +function isIdentifierNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + if (nodeType === "identifier") return true; + if (nodeType.includes("identifier")) return true; + + // Most language grammars will use the term "identifier". + // However some might not. + // Update this as they come. + const specialIdentifiers = ["name", "constant"]; + return specialIdentifiers.includes(nodeType); +} + +// Helper function to check if a node is a declaration. +function isDeclarationNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + // Common declaration patterns. + if (nodeType.endsWith("_declaration")) return true; + if (nodeType.endsWith("_definition")) return true; + if (nodeType.endsWith("_item")) return true; // Rust. + + // Language-specific patterns. + const declarationTypes = [ + // Python. + "function_definition", + "class_definition", + "async_function_definition", + "decorated_definition", + + // Ruby. + "method", + "class", + "module", + "singleton_method", + + // Java. + "variable_declarator", + "local_variable_declaration", + + // Go. + "short_var_declaration", + + // General + "method_definition", + ]; + + return declarationTypes.includes(nodeType); +} + +// // Helper function to find the closest identifier node. +// function findClosestIdentifierNode( +// node: Parser.SyntaxNode | undefined, +// ): Parser.SyntaxNode | undefined { +// if (!node) return undefined; + +// // Check if the current node is an identifier +// if (isIdentifierLike(node)) { +// return node; +// } + +// // Check if the parent is an identifier +// const parent = node.parent; +// if (parent && isIdentifierLike(parent)) { +// return parent; +// } + +// // Check if any of the node's children are identifiers +// // Return the leftmost identifier child if found +// for (let i = 0; i < node.childCount; i++) { +// const child = node.child(i); +// if (child && isIdentifierLike(child)) { +// return child; +// } +// } + +// // Check if any of the parent's children are identifiers +// if (parent) { +// for (let i = 0; i < parent.childCount; i++) { +// const sibling = parent.child(i); +// if (sibling && isIdentifierLike(sibling)) { +// return sibling; +// } +// } +// } + +// // Recurse on the parent if we haven't found anything yet +// return findClosestIdentifierNode(parent); +// } + +// // Helper function to determine if a node is identifier-like +// function isIdentifierLike(node: Parser.SyntaxNode): boolean { +// // Common identifier node types across languages +// const commonIdentifierTypes = [ +// "identifier", +// "property_identifier", +// "type_identifier", +// "field_identifier", +// "variable_identifier", +// "constant", +// "symbol", +// ]; + +// if (commonIdentifierTypes.includes(node.type)) { +// return true; +// } + +// // Check for common identifier patterns in node types +// return /identifier$|^identifier|_identifier/.test(node.type); +// } + +// Helper function to compare ASTs and find changed nodes. +function compareAsts(oldAst: Parser.Tree, newAst: Parser.Tree) { + const changedNodes: { + oldNode: Parser.SyntaxNode | null; + newNode: Parser.SyntaxNode | null; + depth: number; + }[] = []; + + // This is a simplified implementation. + // In practice, you would traverse both ASTs in parallel + // and identify nodes that differ. + + function traverse( + oldNode: Parser.SyntaxNode | null, + newNode: Parser.SyntaxNode | null, + depth: number = 0, + ) { + if (!oldNode && !newNode) return; + + // If one node exists and the other doesn't, or they're different types. + if ( + (!oldNode && newNode) || + (oldNode && !newNode) || + oldNode?.type !== newNode?.type + ) { + changedNodes.push({ oldNode, newNode, depth }); + return; + } + + // Compare properties. + if (oldNode?.text !== newNode?.text) { + changedNodes.push({ oldNode, newNode, depth }); + } + + // Recursively compare children. + const oldChildCount = oldNode?.childCount || 0; + const newChildCount = newNode?.childCount || 0; + + const maxLength = Math.max(oldChildCount, newChildCount); + for (let i = 0; i < maxLength; i++) { + const oldChild = i < oldChildCount ? oldNode?.child(i) || null : null; + const newChild = i < newChildCount ? newNode?.child(i) || null : null; + traverse(oldChild, newChild, depth + 1); + } + } + + traverse(oldAst.rootNode, newAst.rootNode); + return changedNodes; +} + +// Helper function to get a node's text. +function getNodeText(node: Parser.SyntaxNode): string { + if (!node) return ""; + + return node.text; +} + +// Helper function to get a node's position. +function getNodePosition(node: Parser.SyntaxNode): Position | null { + if (!node) return null; + + // Tree-sitter nodes have startPosition property that contains row and column. + return { + line: node.startPosition.row, + character: node.startPosition.column, + }; +} + +/* OTHER HELPER FUNCTIONS */ + +// Helper function to find all occurrences of text in a string. +function findTextOccurrences(text: string, searchText: string): Range[] { + const results: Range[] = []; + const lines = text.split("\n"); + + for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { + const line = lines[lineIndex]; + let charIndex = 0; + + while (charIndex < line.length) { + const foundIndex = line.indexOf(searchText, charIndex); + if (foundIndex === -1) break; + + results.push({ + start: { line: lineIndex, character: foundIndex }, + end: { line: lineIndex, character: foundIndex + searchText.length }, + }); + + charIndex = foundIndex + 1; + } + } + + return results; +} + +// Helper function to check if a range is within another range. +function isRangeWithin(innerRange: Range, outerRange: Range): boolean { + // Check if the inner range's start position is after or equal to the outer range's start. + const startWithin = + innerRange.start.line > outerRange.start.line || + (innerRange.start.line === outerRange.start.line && + innerRange.start.character >= outerRange.start.character); + + // Check if the inner range's end position is before or equal to the outer range's end. + const endWithin = + innerRange.end.line < outerRange.end.line || + (innerRange.end.line === outerRange.end.line && + innerRange.end.character <= outerRange.end.character); + + return startWithin && endWithin; +} + +// Helper function to check if two ranges overlap. +function doRangesOverlap(range1: Range, range2: Range): boolean { + // Check if one range starts after the other ends + const range1StartsAfterRange2Ends = + range1.start.line > range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character > range2.end.character); + + const range2StartsAfterRange1Ends = + range2.start.line > range1.end.line || + (range2.start.line === range1.end.line && + range2.start.character > range1.end.character); + + // If either condition is true, the ranges don't overlap + return !(range1StartsAfterRange2Ends || range2StartsAfterRange1Ends); +} + +// Helper function to check if the upper part of range1 overlaps with range2. +function doesUpperPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts before range2 ends + const range1StartsBeforeRange2Ends = + range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character <= range2.end.character); + + // Check if range1 starts before range2 starts (meaning it's "upper" than range2) + const range1StartsBeforeRange2Starts = + range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character); + + // The upper part overlaps if range1 starts before range2 ends + // AND range1 starts before range2 starts + return range1StartsBeforeRange2Ends && range1StartsBeforeRange2Starts; +} + +// Helper function to check if the lower part of range1 overlaps with range2. +function doesLowerPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts inside range2 + const range1StartsInsideRange2 = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)); + + // Check if range1 ends after range2 ends + const range1EndsAfterRange2 = + range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character); + + // The lower part overlaps if range1 starts inside range2 + // AND range1 ends after range2 ends + return range1StartsInsideRange2 && range1EndsAfterRange2; +} + +// Helper function to check if a range overlaps with another range from either end +function doesRangePartiallyOverlap(range1: Range, range2: Range): boolean { + // Upper part overlap: range1 starts before range2 starts but ends inside range2 + const upperPartOverlap = + (range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character)) && + (range1.end.line > range2.start.line || + (range1.end.line === range2.start.line && + range1.end.character > range2.start.character)) && + (range1.end.line < range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character <= range2.end.character)); + + // Lower part overlap: range1 starts inside range2 but ends after range2 ends + const lowerPartOverlap = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)) && + (range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character)); + + return upperPartOverlap || lowerPartOverlap; +} + +// Utility function to print chunks. +function printChunks(chunks: Chunk[]) { + console.log( + "chunks:", + JSON.stringify( + chunks.map((chunk) => ({ + content: chunk.content, + startLine: chunk.startLine, + endLine: chunk.endLine, + })), + null, + 2, + ), + ); +} diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0f0d6ff48..1ae21c152 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,6 +1,7 @@ import * as path from "path"; +import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { ChatMessage, IDE, ILLM } from "../index.js"; +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -10,24 +11,39 @@ import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchin import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; +import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; +import { getAst } from "../autocomplete/util/ast.js"; import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; +import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { + CODE_TO_EDIT_OPEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; +import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; +import { calculateFinalCursorPosition } from "./diff/diff.js"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, renderPrompt, } from "./templating/NextEditPromptEngine.js"; -import { NextEditOutcome, Prompt, PromptMetadata } from "./types.js"; -// import { renderPrompt } from "./templating/NextEditPromptEngine.js"; +import { + NextEditOutcome, + Prompt, + PromptMetadata, + RecentlyEditedRange, +} from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -52,6 +68,10 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; + private currentEditChainId: string | null = null; + private previousRequest: AutocompleteInput | null = null; + private previousCompletions: NextEditOutcome[] = []; + private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; private constructor( private readonly configHandler: ConfigHandler, @@ -185,11 +205,59 @@ export class NextEditProvider { return options; } + public chainExists(): boolean { + return this.currentEditChainId !== null; + } + + public getChainLength(): number { + return this.previousCompletions.length; + } + + public getPreviousCompletion(): NextEditOutcome | null { + return this.previousCompletions[0]; + } + + public async deleteChain(): Promise { + this.currentEditChainId = null; + this.previousCompletions = []; + this.nextEditableRegionsInTheCurrentChain = []; + + if (this.previousRequest) { + const fileContent = ( + await this.ide.readFile(this.previousRequest.filepath) + ).toString(); + const ast = await getAst(this.previousRequest.filepath, fileContent); + if (ast) { + DocumentHistoryTracker.getInstance().push( + localPathOrUriToPath(this.previousRequest.filepath), + fileContent, + ast, + ); + } + } + } + + public startChain(id?: string) { + this.currentEditChainId = id ?? uuidv4(); + } + + public getChain() { + return this.previousCompletions; + } + + public isStartOfChain() { + return this.previousCompletions.length === 1; + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, + opts?: { + withChain: boolean; + }, ): Promise { try { + this.previousRequest = input; // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -205,6 +273,14 @@ export class NextEditProvider { return undefined; } + // Depending on whether this method is called from provideInlineCompletionItemsWithChain, + // shift the next editable regions. + // This is handled here because this must run after the debouncer + // to prevent excessive shifts. + if (opts?.withChain) { + this.shiftNextEditableRegionsInTheCurrentChain(); + } + const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -235,19 +311,92 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); + const editableRegionStartLine = Math.max( + helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + + const editableRegionEndLine = Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ); + // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; + if (this.endpointType === "default") { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { - const promptMetadata = renderPrompt(helper, this.diffContext); + const historyDiff = createDiff({ + beforeContent: + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( + localPathOrUriToPath(helper.filepath), + ) ?? "", + afterContent: helper.fileContents, + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); + + const modelName = helper.modelName; + let ctx: any; + + if (modelName.includes("mercury-coder-nextedit")) { + ctx = { + recentlyViewedCodeSnippets: + snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ + filepath: snip.filepath, + content: snip.content, + })) ?? [], + currentFileContent: helper.fileContents, + editableRegionStartLine, + editableRegionEndLine, + editDiffHistory: historyDiff, + }; + } else if (modelName.includes("model-1")) { + ctx = { + userEdits: historyDiff ?? this.diffContext, + languageShorthand: helper.lang.name, + userExcerpts: helper.fileContents, + }; + } else { + ctx = {}; + } + + const promptMetadata = await renderPrompt(helper, ctx); + this.promptMetadata = promptMetadata; + + // prompts.push({ + // role: "system", + // content: [ + // "When the user deletes or replaces over previous code, you should respect that decision.", + // "Respect the new code the user is writing, and complete it.", + // "For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.", + // "Do not roll back to previous content.", + // "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.", + // ].join("\n"), + // }); + prompts.push(promptMetadata.prompt); } + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + "", + ); + if (this.endpointType === "default") { const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { const nextCompletion = JSON.parse(msg.content).newCode; const outcomeNext: NextEditOutcome = { @@ -255,7 +404,6 @@ export class NextEditProvider { modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), @@ -269,6 +417,9 @@ export class NextEditProvider { originalEditableRange: "", completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: 0, + editableRegionEndLine: 0, ...helper.options, }; @@ -288,34 +439,41 @@ export class NextEditProvider { if (typeof msg.content === "string") { // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined - const nextCompletion = msg.content.split( - "<|editable_region_start|>\n", - )[1] + const nextCompletion = msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1] ? replaceEscapedCharacters( - msg.content.split("<|editable_region_start|>\n")[1], + msg.content.split(`${CODE_TO_EDIT_OPEN}\n`)[1], ).replace(/\n$/, "") : ""; const currCursorPos = helper.pos; + const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, ); + const editableRegionEndLine = Math.min( currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, helper.fileLines.length - 1, ); + const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + nextCompletion, + ); + const outcomeNext: NextEditOutcome = { elapsed: Date.now() - startTime, modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), @@ -329,9 +487,14 @@ export class NextEditProvider { originalEditableRange: oldEditRangeSlice, completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, ...helper.options, }; + this.previousCompletions.push(outcomeNext); + // When using the JetBrains extension, mark as displayed. // This helps us not need to make additional network calls just to mark as displayed. const ideType = (await this.ide.getIdeInfo()).ideType; @@ -350,4 +513,108 @@ export class NextEditProvider { this.loggingService.deleteAbortController(input.completionId); } } + + public async provideInlineCompletionItemsWithChain( + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + token: AbortSignal | undefined, + ) { + try { + const previousOutcome = this.getPreviousCompletion(); + if (!previousOutcome) { + return undefined; + } + + const filepath = localPathOrUriToPath(previousOutcome.fileUri); + + // If we don't have a precomputed list of next editable regions already, compute and load it. + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + this.loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: previousOutcome.cursorPosition, + filepath, + ide: this.ide, + })) ?? [], + ); + + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + console.log( + "deleteChain called from provideInlineCompletionItemsWithChain", + ); + await this.deleteChain(); + return undefined; + } + } + + // Use the frontmost RangeInFile to build an input. + const input = await this.buildAutocompleteInputFromChain( + previousOutcome, + this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check + ctx, + ); + if (!input) { + return undefined; + } + + return await this.provideInlineCompletionItems(input, token, { + withChain: true, + }); + } catch (e: any) { + this.onError(e); + } + } + + private buildAutocompleteInputFromChain( + previousOutcome: NextEditOutcome, + nextEditableRegion: RangeInFile, + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + ): AutocompleteInput | undefined { + const input: AutocompleteInput = { + pos: { + line: nextEditableRegion.range.start.line, + character: nextEditableRegion.range.start.character, + }, + filepath: previousOutcome.fileUri, + ...ctx, + }; + + return input; + } + + public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { + this.nextEditableRegionsInTheCurrentChain = regions; + } + + public shiftNextEditableRegionsInTheCurrentChain() { + return this.nextEditableRegionsInTheCurrentChain.shift(); + } + + public getNextEditableRegionsInTheCurrentChainLength() { + return this.nextEditableRegionsInTheCurrentChain.length; + } + + public getNextEditableRegionsInTheCurrentChain(): RangeInFile[] { + return [...this.nextEditableRegionsInTheCurrentChain]; // Return a copy to prevent external modification + } } diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index c4dd70f51..05ac1caa3 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -4,3 +4,19 @@ export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; + +export const RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = + "<|recently_viewed_code_snippets|>"; +export const RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE = + "<|/recently_viewed_code_snippets|>"; +export const RECENTLY_VIEWED_CODE_SNIPPET_OPEN = + "<|recently_viewed_code_snippet|>"; +export const RECENTLY_VIEWED_CODE_SNIPPET_CLOSE = + "<|/recently_viewed_code_snippet|>"; +export const CURRENT_FILE_CONTENT_OPEN = "<|current_file_content|>"; +export const CURRENT_FILE_CONTENT_CLOSE = "<|/current_file_content|>"; +export const CODE_TO_EDIT_OPEN = "<|code_to_edit|>"; +export const CODE_TO_EDIT_CLOSE = "<|/code_to_edit|>"; +export const EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>"; +export const EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>"; +export const CURSOR = "<|cursor|>"; diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index bca4a6d08..fdcb78fb4 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -1,4 +1,6 @@ +import { Position } from "shiki"; import { DiffLine } from "../.."; +import { myersDiff } from "../../diff/myers"; /** * Given a diff of two editable regions, get the offset position at the last new line inside the editable region. @@ -134,6 +136,8 @@ export function checkFim( isFim: false; fimText: null; } { + // console.log("oldEditRange", oldEditRange); + // console.log("newEditRange", newEditRange); // Find the common prefix. let prefixLength = 0; while ( @@ -168,12 +172,19 @@ export function checkFim( // Convert cursor position to an offset in the string. // For simplicity, we need to calculate the cursor's position in the string. // This requires knowledge of line endings in the oldEditRange. - const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.split("\n"); + // const cursorOffset = + // lines.length > 1 + // ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + + // cursorPosition.character + // : cursorPosition.character; + const oldEditLines = oldEditRange.split("\n"); const cursorOffset = - lines.length > 1 - ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + - cursorPosition.character - : cursorPosition.character; + oldEditLines + .slice(0, cursorPosition.line) + .reduce((sum, line) => sum + line.length + 1, 0) + + cursorPosition.character; // Check if the cursor is positioned between the prefix and suffix. const cursorBetweenPrefixAndSuffix = @@ -192,3 +203,66 @@ export function checkFim( return { isFim, fimText: null }; } } + +export function calculateFinalCursorPosition( + currCursorPos: Position, + editableRegionStartLine: number, + oldEditRangeSlice: string, + newEditRangeSlice: string, +) { + // How far away is the current line from the start of the editable region? + const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; + + // How long is the line at the current cursor position? + const lineContentAtCursorPos = + newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; + + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + const offset = getOffsetPositionAtLastNewLine( + diffLines, + lineContentAtCursorPos, + lineOffsetAtCursorPos, + ); + + // Calculate the actual line number in the editor by adding the startPos offset + // to the line number from the diff calculation. + const finalCursorPos: Position = { + line: editableRegionStartLine + offset.line, + character: offset.character, + }; + + return finalCursorPos; +} + +/** + * Applies a completion to file content by replacing lines starting from a specific line number + * + * @param fileContent The original file content + * @param completion The completion text to apply + * @param startLineNumber The line number (0-based) where replacement should start + * @param linesToReplace Optional number of lines to replace; if not provided, will replace the same number of lines as in the completion + * @returns The file content with the completion applied + */ +export function applyCompletionToFile( + fileContent: string, + completion: string, + startLineNumber: number, + linesToReplace?: number, +): string { + const lines = fileContent.split("\n"); + const completionLines = completion.split("\n"); + + // Determine how many lines to replace + const numLinesToReplace = + linesToReplace !== undefined ? linesToReplace : completionLines.length; + + // Replace the lines + const newLines = [ + ...lines.slice(0, startLineNumber), + ...completionLines, + ...lines.slice(startLineNumber + numLinesToReplace), + ]; + + return newLines.join("\n"); +} diff --git a/core/nextEdit/diff/diff.vitest.ts b/core/nextEdit/diff/diff.vitest.ts index fa161d49c..706fed14c 100644 --- a/core/nextEdit/diff/diff.vitest.ts +++ b/core/nextEdit/diff/diff.vitest.ts @@ -79,6 +79,46 @@ describe("checkFim", () => { "const data = fetchData();\n const result = processData(data);", }, }, + { + name: "interesting case", + oldEditRange: [" }", "}", ""].join("\n"), + newEditRange: [" }", "}", "", "module.exports = Calculator;"].join("\n"), + cursorPosition: { line: 0, character: 0 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "calculator.js divide", + oldEditRange: [ + " ", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + newEditRange: [ + " if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + cursorPosition: { line: 0, character: 4 }, + expected: { + isFim: true, + fimText: [ + "if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + ].join("\n"), + }, + }, ]; testCases.forEach( diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 93f794a63..1369ebbc6 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -3,26 +3,46 @@ import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { - EDITABLE_REGION_END_TOKEN, - EDITABLE_REGION_START_TOKEN, - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + CURRENT_FILE_CONTENT_CLOSE, + CURRENT_FILE_CONTENT_OPEN, + CURSOR, + EDIT_DIFF_HISTORY_CLOSE, + EDIT_DIFF_HISTORY_OPEN, + RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, + RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { + MercuryTemplateVars, + Model1TemplateVars, NextEditTemplate, PromptMetadata, SystemPrompt, TemplateVars, UserPrompt, } from "../types"; +import { + currentFileContentBlock, + editHistoryBlock, + recentlyViewedCodeSnippetsBlock, +} from "./mercuryCoderNextEdit"; +import { + insertCursorToken, + insertEditableRegionTokensWithStaticRange, +} from "./utils"; type TemplateRenderer = (vars: TemplateVars) => string; -type NextEditModelName = "mercury-coder-nextedit" | "this field is not used"; +export type NextEditModelName = + | "mercury-coder-nextedit" + | "model-1" + | "this field is not used"; const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { + template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at [CURRENT FILE PATH].\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + }, + "model-1": { template: "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", }, @@ -46,10 +66,10 @@ function templateRendererOfModel( }; } -export function renderPrompt( +export async function renderPrompt( helper: HelperVars, - userEdits: string, -): PromptMetadata { + ctx: any, +): Promise { let modelName = helper.modelName as NextEditModelName; if (modelName === "this field is not used") { @@ -58,7 +78,7 @@ export function renderPrompt( role: "user", content: "NEXT_EDIT", }, - userEdits, + userEdits: "", userExcerpts: helper.fileContents, }; } @@ -80,16 +100,60 @@ export function renderPrompt( } const renderer = templateRendererOfModel(modelName); - const editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - ); + let userEdits = ""; + let editedCodeWithTokens = ""; + let tv: TemplateVars; - const tv: TemplateVars = { - userEdits, - languageShorthand: helper.lang.name, - userExcerpts: editedCodeWithTokens, - }; + switch (modelName) { + case "mercury-coder-nextedit": { + userEdits = ctx.editDiffHistory; + + editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + CURSOR, + ); + + const mercuryCtx: MercuryTemplateVars = { + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + ctx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + ctx.currentFileContent, + ctx.editableRegionStartLine, + ctx.editableRegionEndLine, + helper.pos, + ), + editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + }; + + tv = mercuryCtx; + + break; + } + case "model-1": { + userEdits = ctx.userEdits; + + editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + USER_CURSOR_IS_HERE_TOKEN, + ); + + const model1Ctx: Model1TemplateVars = { + userEdits: ctx.userEdits, + languageShorthand: ctx.languageShorthand, + userExcerpts: ctx.userExcerpts, + }; + + tv = model1Ctx; + + break; + } + default: + tv = {}; + break; + } return { prompt: { @@ -172,165 +236,19 @@ export function renderDefaultUserPrompt( }; } -// export async function renderFineTunedUserPrompt( -// snippets: SnippetPayload, -// ide: IDE, -// helper: HelperVars, -// ): Promise { -// const ideInfo = await ide.getIdeInfo(); -// switch (ideInfo.ideType) { -// case "vscode": -// const editedCodeWithPins = insertTokens( -// helper.fileContents.split("\n"), -// helper.pos, -// ); - -// return { -// role: "user", -// content: renderStringTemplate( -// mercuryCoderTemplate, -// snippets.diffSnippets.join("\n"), -// helper.lang.name, -// editedCodeWithPins, -// ), -// }; - -// case "jetbrains": -// return { -// role: "user", -// content: "", -// }; -// } -// } - -// export async function renderDefaultBasicUserPrompt( -// snippets: SnippetPayload, -// ide: IDE, -// helper: HelperVars, -// ): Promise { -// const ideInfo = await ide.getIdeInfo(); -// switch (ideInfo.ideType) { -// case "vscode": -// const editedCodeWithPins = insertTokens( -// helper.fileContents.split("\n"), -// helper.pos, -// ); - -// return { -// role: "user", -// content: renderStringTemplate( -// mercuryCoderTemplate, -// JSON.stringify(snippets), -// helper.lang.name, -// editedCodeWithPins, -// ), -// }; - -// case "jetbrains": -// return { -// role: "user", -// content: "", -// }; -// } -// } - -// export async function renderFineTunedBasicUserPrompt( -// snippets: SnippetPayload, -// ide: IDE, -// helper: HelperVars, -// diffContext: string, -// ): Promise { -// const ideInfo = await ide.getIdeInfo(); -// switch (ideInfo.ideType) { -// case "vscode": -// const lines = helper.fileContents.split("\n"); -// const editedCodeWithPins = insertTokens(lines, helper.pos); - -// return { -// role: "user", -// content: renderStringTemplate( -// mercuryCoderTemplate, -// diffContext, -// helper.lang.name, -// editedCodeWithPins, -// ), -// }; - -// case "jetbrains": -// return { -// role: "user", -// content: "", -// }; -// } -// } - -function insertTokens(lines: string[], cursorPos: Position) { - const a = insertCursorToken(lines, cursorPos); - const b = insertEditableRegionTokensWithStaticRange(a, cursorPos); +function insertTokens( + lines: string[], + cursorPos: Position, + cursorToken: string, + editableRegionStart?: number, + editableRegionEnd?: number, +) { + const a = insertCursorToken(lines, cursorPos, cursorToken); + const b = insertEditableRegionTokensWithStaticRange( + a, + cursorPos, + editableRegionStart, + editableRegionEnd, + ); return b.join("\n"); } - -function insertCursorToken(lines: string[], cursorPos: Position) { - if (cursorPos.line < 0 || cursorPos.line >= lines.length) { - return lines; - } - - // Ensure character position is within bounds or at the end of the line. - const lineLength = lines[cursorPos.line].length; - const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); - - lines[cursorPos.line] = - lines[cursorPos.line].slice(0, charPos) + - USER_CURSOR_IS_HERE_TOKEN + - lines[cursorPos.line].slice(charPos); - - return lines; -} - -function insertEditableRegionTokensWithStaticRange( - lines: string[], - cursorPos: Position, -) { - if (cursorPos.line < 0 || cursorPos.line >= lines.length) { - return lines; - } - - // Ensure editable regions are within bounds. - const editableRegionStart = Math.max( - cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); - const editableRegionEnd = Math.min( - cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - lines.length - 1, // Line numbers should be zero-indexed. - ); - - const instrumentedLines = [ - ...lines.slice(0, editableRegionStart), - EDITABLE_REGION_START_TOKEN, - ...lines.slice(editableRegionStart, editableRegionEnd + 1), - EDITABLE_REGION_END_TOKEN, - ...lines.slice(editableRegionEnd + 1), - ]; - - return instrumentedLines; -} - -function insertEditableRegionTokensWithAst( - lines: string[], - cursorPos: Position, -) { - if (cursorPos.line < 0 || cursorPos.line >= lines.length) { - return lines; - } - - // Ensure character position is within bounds or at the end of the line. - const lineLength = lines[cursorPos.line].length; - const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); - - (lines[cursorPos.line] = - lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN), - lines[cursorPos.line].slice(charPos); - - return lines; -} diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts new file mode 100644 index 000000000..aa3fad6a6 --- /dev/null +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -0,0 +1,236 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { Position } from "../.."; +import { SnippetPayload } from "../../autocomplete/snippets"; +import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; +import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { + CURRENT_FILE_CONTENT_CLOSE, + CURRENT_FILE_CONTENT_OPEN, + CURSOR, + EDIT_DIFF_HISTORY_CLOSE, + EDIT_DIFF_HISTORY_OPEN, + RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, + RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, + USER_CURSOR_IS_HERE_TOKEN, +} from "../constants"; +import { + NextEditModelName, + renderDefaultSystemPrompt, + renderDefaultUserPrompt, + renderPrompt, +} from "./NextEditPromptEngine"; + +describe("NextEditPromptEngine", () => { + describe("renderPrompt", () => { + let mercuryHelper: HelperVars; + let model1Helper: HelperVars; + let testHelper: HelperVars; + let unsupportedHelper: HelperVars; + let ctx: any; + + beforeEach(() => { + mercuryHelper = { + modelName: "inception/mercury-coder-nextedit" as NextEditModelName, + fileContents: "function test() {\n const a = 1;\n return a;\n}", + pos: { line: 1, character: 12 } as Position, + lang: { name: "typescript" }, + } as HelperVars; + model1Helper = { + modelName: "continuedev/model-1" as NextEditModelName, + fileContents: "function test() {\n const a = 1;\n return a;\n}", + pos: { line: 1, character: 12 } as Position, + lang: { name: "typescript" }, + } as HelperVars; + testHelper = { + modelName: "this field is not used" as NextEditModelName, + fileContents: "function test() {\n const a = 1;\n return a;\n}", + pos: { line: 1, character: 12 } as Position, + lang: { name: "typescript" }, + } as HelperVars; + unsupportedHelper = { + modelName: "mistral/codestral" as NextEditModelName, + fileContents: "function test() {\n const a = 1;\n return a;\n}", + pos: { line: 1, character: 12 } as Position, + lang: { name: "typescript" }, + } as HelperVars; + + ctx = { + recentlyViewedCodeSnippets: [ + { filepath: "/path/to/file1.ts", content: "const b = 2;" }, + ], + currentFileContent: "function test() {\n const a = 1;\n return a;\n}", + editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@", + editableRegionStartLine: 0, + editableRegionEndLine: 3, + userEdits: "Added constant a", + languageShorthand: "ts", + userExcerpts: "const a = 1;", + }; + }); + + it("should render mercury-coder-nextedit prompt correctly", async () => { + const result = await renderPrompt(mercuryHelper, ctx); + + expect(result).toHaveProperty("prompt"); + expect(result.prompt.role).toBe("user"); + + const content = result.prompt.content; + expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); + expect(content).toContain(RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); + expect(content).toContain(CURRENT_FILE_CONTENT_OPEN); + expect(content).toContain(CURRENT_FILE_CONTENT_CLOSE); + expect(content).toContain(EDIT_DIFF_HISTORY_OPEN); + expect(content).toContain(EDIT_DIFF_HISTORY_CLOSE); + + expect(result.userEdits).toBe(ctx.editDiffHistory); + expect(result.userExcerpts).toContain(CURSOR); + }); + + it("should render model-1 prompt correctly", async () => { + const result = await renderPrompt(model1Helper, ctx); + + expect(result).toHaveProperty("prompt"); + expect(result.prompt.role).toBe("user"); + expect(result.prompt.content).toContain("### User Edits:"); + expect(result.prompt.content).toContain("### User Excerpts:"); + expect(result.prompt.content).toContain("```ts"); + + expect(result.userEdits).toBe(ctx.userEdits); + expect(result.userExcerpts).toContain(USER_CURSOR_IS_HERE_TOKEN); + }); + + it("should handle 'this field is not used' model name", async () => { + const result = await renderPrompt(testHelper, ctx); + + expect(result).toHaveProperty("prompt"); + expect(result.prompt.role).toBe("user"); + expect(result.prompt.content).toBe("NEXT_EDIT"); + expect(result.userEdits).toBe(""); + expect(result.userExcerpts).toBe(testHelper.fileContents); + }); + + it("should throw error for unsupported model name", async () => { + await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow( + "mistral/codestral is not yet supported for next edit.", + ); + }); + }); + + describe("renderDefaultSystemPrompt", () => { + it("should return a system prompt with expected role and content", () => { + const result = renderDefaultSystemPrompt(); + + expect(result.role).toBe("system"); + expect(result.content).toContain("You are an expert polyglot developer"); + expect(result.content).toContain("Do not hallucinate."); + }); + }); + + describe("renderDefaultUserPrompt", () => { + it("should render a user prompt with the correct structure", () => { + const snippets: SnippetPayload = { + rootPathSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "root path", + }, + ], + importDefinitionSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "import def", + }, + ], + ideSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "ide snippets", + }, + ], + recentlyEditedRangeSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "recent edits", + }, + ], + diffSnippets: [ + { + type: AutocompleteSnippetType.Diff, + content: "diff snippets", + }, + ], + clipboardSnippets: [ + { + type: AutocompleteSnippetType.Clipboard, + content: "clipboard", + copiedAt: new Date().toISOString(), + }, + ], + recentlyVisitedRangesSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "visited ranges", + }, + ], + recentlyOpenedFileSnippets: [ + { + type: AutocompleteSnippetType.Code, + filepath: "", + content: "recently opened files", + }, + ], + staticSnippet: [ + { + type: AutocompleteSnippetType.Static, + filepath: "", + content: "static content", + }, + ], + }; + + const helper: HelperVars = { + lang: { name: "typescript" }, + } as HelperVars; + + const result = renderDefaultUserPrompt(snippets, helper); + + expect(result.role).toBe("user"); + expect(result.content).toContain("Your junior made the following edit:"); + expect(result.content).toContain("typescript"); + expect(result.content).toContain("root path"); + }); + }); + + describe("insertTokens", () => { + it("should correctly insert cursor and editable region tokens", () => { + const mercuryHelper = { + modelName: "inception/mercury-coder-nextedit" as NextEditModelName, + fileContents: "function test() {\n const a = 1;\n return a;\n}", + pos: { line: 1, character: 12 } as Position, + lang: { name: "typescript" }, + } as HelperVars; + + const ctx = { + recentlyViewedCodeSnippets: [ + { filepath: "/path/to/file1.ts", content: "const b = 2;" }, + ], + currentFileContent: "function test() {\n const a = 1;\n return a;\n}", + editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@", + editableRegionStartLine: 0, + editableRegionEndLine: 3, + userEdits: "Added constant a", + languageShorthand: "ts", + userExcerpts: "const a = 1;", + }; + + return renderPrompt(mercuryHelper, ctx).then((result) => { + expect(result.userExcerpts).toContain(CURSOR); + }); + }); + }); +}); diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts new file mode 100644 index 000000000..616700b17 --- /dev/null +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -0,0 +1,63 @@ +import { Position, Range } from "../.."; +import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants"; +import { insertCursorToken } from "./utils"; + +export function recentlyViewedCodeSnippetsBlock( + recentlyViewedCodeSnippets: { filepath: string; content: string }[], +) { + return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { + const block = [ + `code_snippet_file_path: ${snippet.filepath}`, + snippet.content, + ].join("\n"); + + return ( + acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") + ); + }, ""); +} + +export function currentFileContentBlock( + currentFileContent: string, + editableRegionStartLine: number, + editableRegionEndLine: number, + cursorPosition: Position, +) { + const currentFileContentLines = currentFileContent.split("\n"); + + const insertedCursorLines = insertCursorToken( + currentFileContentLines, + cursorPosition, + CURSOR, + ); + + const instrumentedLines = [ + ...insertedCursorLines.slice(0, editableRegionStartLine), + CODE_TO_EDIT_OPEN, + ...insertedCursorLines.slice( + editableRegionStartLine, + editableRegionEndLine + 1, + ), + CODE_TO_EDIT_CLOSE, + ...insertedCursorLines.slice(editableRegionEndLine + 1), + ]; + + return instrumentedLines.join("\n"); +} + +export function editHistoryBlock( + editDiffHistory: string, // could be a singe large unified diff +) { + return editDiffHistory; +} + +function mercuryNextEditTemplateBuilder( + recentlyViewedCodeSnippets: { filepath: string; code: string }[], + currentFileContent: string, + codeToEdit: string, + codeToEditRange: Range, + cursorPosition: Position, + editDiffHistory: string, // could be a singe large unified diff +): string { + return ""; +} diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts new file mode 100644 index 000000000..2849082b7 --- /dev/null +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vitest"; +import { Position } from "../.."; +import { CODE_TO_EDIT_CLOSE, CODE_TO_EDIT_OPEN, CURSOR } from "../constants"; +import { + currentFileContentBlock, + editHistoryBlock, + recentlyViewedCodeSnippetsBlock, +} from "./mercuryCoderNextEdit"; + +describe("mercuryCoderNextEdit", () => { + describe("recentlyViewedCodeSnippetsBlock", () => { + it("should format a list of code snippets correctly", () => { + const snippets = [ + { filepath: "/path/to/file1.ts", content: "const a = 1;" }, + { + filepath: "/path/to/file2.ts", + content: "function test() { return true; }", + }, + ]; + + const result = recentlyViewedCodeSnippetsBlock(snippets); + + const expected = + "code_snippet_file_path: /path/to/file1.ts\n" + + "const a = 1;\n" + + "code_snippet_file_path: /path/to/file2.ts\n" + + "function test() { return true; }"; + + expect(result).toBe(expected); + }); + + it("should handle empty snippets array", () => { + const result = recentlyViewedCodeSnippetsBlock([]); + expect(result).toBe(""); + }); + }); + + describe("currentFileContentBlock", () => { + it("should correctly format current file content with editable region and cursor", () => { + const fileContent = "line 1\nline 2\nline 3\nline 4\nline 5"; + const editableRegionStartLine = 1; + const editableRegionEndLine = 3; + const cursorPosition: Position = { line: 2, character: 3 }; + + const result = currentFileContentBlock( + fileContent, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = + "line 1\n" + + CODE_TO_EDIT_OPEN + + "\n" + + "line 2\n" + + "lin" + + CURSOR + + "e 3\n" + + "line 4\n" + + CODE_TO_EDIT_CLOSE + + "\n" + + "line 5"; + + expect(result).toBe(expected); + }); + + it("should handle cursor at the beginning of a line", () => { + const fileContent = "line 1\nline 2\nline 3"; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + const cursorPosition: Position = { line: 1, character: 0 }; + + const result = currentFileContentBlock( + fileContent, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + expect(result).toContain(CODE_TO_EDIT_OPEN); + expect(result).toContain(CURSOR + "line 2"); + expect(result).toContain(CODE_TO_EDIT_CLOSE); + }); + + it("should handle cursor at the end of a line", () => { + const fileContent = "line 1\nline 2\nline 3"; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + const cursorPosition: Position = { line: 1, character: 6 }; + + const result = currentFileContentBlock( + fileContent, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + expect(result).toContain("line 2" + CURSOR); + }); + }); + + describe("editHistoryBlock", () => { + it("should return the edit diff history unchanged", () => { + const diffHistory = "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"; + const result = editHistoryBlock(diffHistory); + expect(result).toBe(diffHistory); + }); + + it("should handle empty diff history", () => { + const result = editHistoryBlock(""); + expect(result).toBe(""); + }); + }); +}); diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts new file mode 100644 index 000000000..a75712689 --- /dev/null +++ b/core/nextEdit/templating/utils.ts @@ -0,0 +1,63 @@ +import { Position } from "../.."; +import { + EDITABLE_REGION_END_TOKEN, + EDITABLE_REGION_START_TOKEN, + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "../constants"; + +export function insertCursorToken( + lines: string[], + cursorPos: Position, + cursorToken: string, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + + cursorToken + + lines[cursorPos.line].slice(charPos); + + return lines; +} + +export function insertEditableRegionTokensWithStaticRange( + lines: string[], + cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure editable regions are within bounds. + if (editableRegionStart === undefined) { + editableRegionStart = Math.max( + cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + } + if (editableRegionEnd === undefined) { + editableRegionEnd = Math.min( + cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, // Line numbers should be zero-indexed. + ); + } + + const instrumentedLines = [ + ...lines.slice(0, editableRegionStart), + EDITABLE_REGION_START_TOKEN, + ...lines.slice(editableRegionStart, editableRegionEnd + 1), + EDITABLE_REGION_END_TOKEN, + ...lines.slice(editableRegionEnd + 1), + ]; + + return instrumentedLines; +} diff --git a/core/nextEdit/templating/utils.vitest.ts b/core/nextEdit/templating/utils.vitest.ts new file mode 100644 index 000000000..a2f8772ba --- /dev/null +++ b/core/nextEdit/templating/utils.vitest.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "vitest"; +import { Position } from "../.."; +import { + EDITABLE_REGION_END_TOKEN, + EDITABLE_REGION_START_TOKEN, + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "../constants"; +import { + insertCursorToken, + insertEditableRegionTokensWithStaticRange, +} from "./utils"; + +describe("insertCursorToken", () => { + it("should insert cursor token at the specified position", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: 1, character: 5 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(["line one", "line |CURSOR|two", "line three"]); + }); + + it("should handle cursor at the beginning of a line", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: 1, character: 0 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(["line one", "|CURSOR|line two", "line three"]); + }); + + it("should handle cursor at the end of a line", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: 1, character: 8 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(["line one", "line two|CURSOR|", "line three"]); + }); + + it("should not modify lines if cursor position is out of bounds (negative line)", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: -1, character: 5 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(lines); + }); + + it("should not modify lines if cursor position is out of bounds (line too large)", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: 3, character: 5 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(lines); + }); + + it("should cap the character position to the line length if it exceeds it", () => { + const lines = ["line one", "line two", "line three"]; + const cursorPos: Position = { line: 1, character: 100 }; + const cursorToken = "|CURSOR|"; + + const result = insertCursorToken(lines, cursorPos, cursorToken); + + expect(result).toEqual(["line one", "line two|CURSOR|", "line three"]); + }); +}); + +describe("insertEditableRegionTokensWithStaticRange", () => { + it("should insert editable region tokens with default margins", () => { + const lines = ["line 0", "line 1", "line 2", "line 3", "line 4"]; + const cursorPos: Position = { line: 2, character: 3 }; + + const result = insertEditableRegionTokensWithStaticRange(lines, cursorPos); + + const expectedStart = Math.max(2 - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); + const expectedEnd = Math.min( + 2 + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, + ); + + const expected = [ + ...lines.slice(0, expectedStart), + EDITABLE_REGION_START_TOKEN, + ...lines.slice(expectedStart, expectedEnd + 1), + EDITABLE_REGION_END_TOKEN, + ...lines.slice(expectedEnd + 1), + ]; + + expect(result).toEqual(expected); + }); + + it("should insert editable region tokens with explicit range", () => { + const lines = ["line 0", "line 1", "line 2", "line 3", "line 4"]; + const cursorPos: Position = { line: 2, character: 3 }; + const editableRegionStart = 1; + const editableRegionEnd = 3; + + const result = insertEditableRegionTokensWithStaticRange( + lines, + cursorPos, + editableRegionStart, + editableRegionEnd, + ); + + const expected = [ + "line 0", + EDITABLE_REGION_START_TOKEN, + "line 1", + "line 2", + "line 3", + EDITABLE_REGION_END_TOKEN, + "line 4", + ]; + + expect(result).toEqual(expected); + }); + + it("should not modify lines if cursor position is out of bounds", () => { + const lines = ["line 0", "line 1", "line 2"]; + const cursorPos: Position = { line: 5, character: 3 }; + + const result = insertEditableRegionTokensWithStaticRange(lines, cursorPos); + + expect(result).toEqual(lines); + }); +}); diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 0837c5494..5b3d96eee 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -53,7 +53,10 @@ export interface NextEditOutcome extends TabAutocompleteOptions { originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; + finalCursorPosition: { line: number; character: number }; accepted?: boolean; + editableRegionStartLine: number; + editableRegionEndLine: number; } export interface PromptMetadata { @@ -78,8 +81,16 @@ export interface NextEditTemplate { template: string; } -export interface TemplateVars { +export interface TemplateVars {} + +export interface Model1TemplateVars extends TemplateVars { userEdits: string; languageShorthand: string; userExcerpts: string; } + +export interface MercuryTemplateVars extends TemplateVars { + recentlyViewedCodeSnippets: string; + currentFileContent: string; + editDiffHistory: string; // could be a singe large unified diff +} diff --git a/core/nextEdit/utils.ts b/core/nextEdit/utils.ts new file mode 100644 index 000000000..152e55933 --- /dev/null +++ b/core/nextEdit/utils.ts @@ -0,0 +1,15 @@ +type NextEditModelName = "mercury-coder-nextedit"; + +export function isModelCapableOfNextEdit(modelName: string): boolean { + // In test mode, we can control whether next edit is enabled via environment variable. + if (process.env.NEXT_EDIT_TEST_ENABLED === "false") { + return false; + } + + if (process.env.NEXT_EDIT_TEST_ENABLED === "true") { + return true; + } + + const supportedModels: NextEditModelName[] = ["mercury-coder-nextedit"]; + return supportedModels.some((supported) => modelName.includes(supported)); +} diff --git a/core/package-lock.json b/core/package-lock.json index d2afa4b76..bb018d8f9 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,8 +14,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", @@ -38,6 +38,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -145,7 +146,7 @@ "version": "1.0.96", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-types": "^1.0.14", + "@continuedev/config-types": "file:../config-types", "yaml": "^2.6.1", "zod": "^3.24.2" }, @@ -167,17 +168,44 @@ "zod-to-json-schema": "^3.24.5" } }, + "../packages/fetch": { + "name": "@continuedev/fetch", + "version": "1.0.16", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "file:../config-types", + "follow-redirects": "^1.15.6", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "node-fetch": "^3.3.2" + }, + "devDependencies": { + "@types/follow-redirects": "^1.14.4", + "typescript": "^5.0.0", + "vitest": "^3.2.0" + } + }, + "../packages/llm-info": { + "name": "@continuedev/llm-info", + "version": "1.0.9", + "license": "Apache-2.0", + "devDependencies": { + "@types/node": "^22.15.29", + "typescript": "^5.5.2" + } + }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.0.45", + "version": "1.1.1", "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", - "@continuedev/config-types": "^1.0.5", - "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.15", + "@continuedev/config-types": "file:../config-types", + "@continuedev/config-yaml": "file:../config-yaml", + "@continuedev/fetch": "file:../fetch", "dotenv": "^16.5.0", + "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.104.0", @@ -185,13 +213,20 @@ "zod": "^3.24.2" }, "devDependencies": { + "@semantic-release/changelog": "^6.0.3", + "@semantic-release/commit-analyzer": "^13.0.1", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^11.0.3", + "@semantic-release/npm": "^12.0.2", + "@semantic-release/release-notes-generator": "^14.0.3", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", + "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", "ts-node": "^10.9.2", - "vitest": "^1.6.1" + "vitest": "^3.2.4" } }, "node_modules/@75lb/deep-merge": { @@ -2918,22 +2953,12 @@ "link": true }, "node_modules/@continuedev/fetch": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.14.tgz", - "integrity": "sha512-r/CUwW0tt7VrjLVNeowA281aq7VQvToE+Ro9+0EhfINBMNre4eU2MbNOgbRmYCr5VkIuSnltPUDI357Kns7uCw==", - "license": "Apache-2.0", - "dependencies": { - "@continuedev/config-types": "^1.0.5", - "follow-redirects": "^1.15.6", - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.5", - "node-fetch": "^3.3.2" - } + "resolved": "../packages/fetch", + "link": true }, "node_modules/@continuedev/llm-info": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.8.tgz", - "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" + "resolved": "../packages/llm-info", + "link": true }, "node_modules/@continuedev/openai-adapters": { "resolved": "../packages/openai-adapters", diff --git a/core/package.json b/core/package.json index 13830d83b..cebf2c189 100644 --- a/core/package.json +++ b/core/package.json @@ -54,8 +54,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 743556d15..1a6e4dc20 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -43,7 +43,10 @@ import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "../autocomplete/types"; import { ConfigHandler } from "../config/ConfigHandler"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; -import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; +import { + ControlPlaneEnv, + ControlPlaneSessionInfo, +} from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; export enum OnboardingModes { @@ -248,6 +251,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; + "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; "controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null]; "controlPlane/getModelsAddOnUpgradeUrl": [ { vsCodeUriScheme?: string }, diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index c67b8c94a..d8b86ff96 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,5 +1,5 @@ import type { - ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -52,7 +52,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { showLines: [{ filepath: string; startLine: number; endLine: number }, void]; readRangeInFile: [{ filepath: string; range: Range }, string]; getDiff: [{ includeUnstaged: boolean }, string[]]; - getWorkspaceConfigs: [undefined, ContinueRcJson[]]; getTerminalContents: [undefined, string]; getDebugLocals: [{ threadIndex: number }, string]; getTopLevelCallStackSources: [ @@ -85,6 +84,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { gotoDefinition: [{ location: Location }, RangeInFile[]]; gotoTypeDefinition: [{ location: Location }, RangeInFile[]]; getSignatureHelp: [{ location: Location }, SignatureHelp | null]; + getReferences: [{ location: Location }, RangeInFile[]]; + getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 2365117c0..795b483c4 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -2,7 +2,7 @@ import { FromIdeProtocol } from ".."; import { ToIdeFromWebviewOrCoreProtocol } from "../ide"; import type { - ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -54,6 +54,16 @@ export class MessageIde implements IDE { return this.request("getSignatureHelp", { location }); } + async getReferences(location: Location): Promise { + return this.request("getReferences", { location }); + } + + async getDocumentSymbols( + textDocumentIdentifier: string, + ): Promise { + return this.request("getDocumentSymbols", { textDocumentIdentifier }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } @@ -123,10 +133,6 @@ export class MessageIde implements IDE { return this.request("getUniqueId", undefined); } - getWorkspaceConfigs(): Promise { - return this.request("getWorkspaceConfigs", undefined); - } - async getDiff(includeUnstaged: boolean) { return await this.request("getDiff", { includeUnstaged }); } diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index ba37c610d..9ce82db54 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -89,10 +89,6 @@ export class ReverseMessageIde { return this.ide.getUniqueId(); }); - this.on("getWorkspaceConfigs", () => { - return this.ide.getWorkspaceConfigs(); - }); - this.on("getIdeSettings", () => { return this.ide.getIdeSettings(); }); diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 6e25e5f54..967e0262e 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -66,12 +66,13 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedProfile", "didChangeSelectedOrg", "tools/call", - "controlPlane/openUrl", + "controlPlane/getEnvironment", + "controlPlane/getFreeTrialStatus", "controlPlane/getModelsAddOnUpgradeUrl", + "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", - "controlPlane/getFreeTrialStatus", ]; // Message types to pass through from core to webview diff --git a/core/tools/constants.ts b/core/tools/constants.ts new file mode 100644 index 000000000..0b5278209 --- /dev/null +++ b/core/tools/constants.ts @@ -0,0 +1,2 @@ +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts index fffe51e02..0714a230b 100644 --- a/core/tools/definitions/codebaseTool.ts +++ b/core/tools/definitions/codebaseTool.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const codebaseTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const codebaseTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CodebaseTool, + `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`, + [["query", "How is user authentication handled in this codebase?"]], + ), }; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 41bea0b91..152af5693 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const createNewFileTool: Tool = { type: "function", @@ -30,4 +31,12 @@ export const createNewFileTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CreateNewFile, + `To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`, + [ + ["filepath", "path/to/the_file.txt"], + ["contents", "Contents of the file"], + ], + ), }; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 8f19c5955..e6bf6689e 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,5 +1,20 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; + +const NAME_ARG_DESC = + "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')"; +const RULE_ARG_DESC = + "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard."; +const DESC_ARG_DESC = + "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types."; +const GLOB_ARG_DESC = + "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])"; +const REGEX_ARG_DESC = + "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)"; + +const ALWAYS_APPLY_DESC = + "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules."; export const createRuleBlock: Tool = { type: "function", @@ -20,35 +35,54 @@ export const createRuleBlock: Tool = { properties: { name: { type: "string", - description: - "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')", + description: NAME_ARG_DESC, }, rule: { type: "string", - description: - "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", + description: RULE_ARG_DESC, }, description: { type: "string", - description: - "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.", + description: DESC_ARG_DESC, }, globs: { type: "string", - description: - "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])", + description: GLOB_ARG_DESC, }, regex: { type: "string", - description: - "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)", + description: REGEX_ARG_DESC, }, alwaysApply: { type: "boolean", - description: - "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.", + description: ALWAYS_APPLY_DESC, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CreateRuleBlock, + `Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions. +This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules. +To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments: +- name: ${NAME_ARG_DESC} +- rule: ${RULE_ARG_DESC} +- description: ${DESC_ARG_DESC} +- globs: ${GLOB_ARG_DESC} +- alwaysApply: ${ALWAYS_APPLY_DESC} +For example:`, + [ + ["name", "Use PropTypes"], + [ + "rule", + "Always use PropTypes when declaring React component properties", + ], + [ + "description", + "Ensure that all prop types are explicitly declared for better type safety and code maintainability in React components.", + ], + ["globs", "**/*.js"], + ["alwaysApply", "false"], + ], + ), }; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 7abd658fc..59e20c681 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; export interface EditToolArgs { @@ -8,6 +9,9 @@ export interface EditToolArgs { changes: string; } +const CHANGES_DESCRIPTION = + "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; + export const editFileTool: Tool = { type: "function", displayTitle: "Edit File", @@ -31,10 +35,24 @@ export const editFileTool: Tool = { }, changes: { type: "string", - description: - "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'", + description: CHANGES_DESCRIPTION, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.EditExistingFile, + `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with +- filepath: the relative filepath to the file. +- changes: ${CHANGES_DESCRIPTION} +Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first. +For example:`, + [ + ["filepath", "path/to/the_file.ts"], + [ + "changes", + "// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...", + ], + ], + ), }; diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts index e0122f55b..ae57fc532 100644 --- a/core/tools/definitions/fetchUrlContent.ts +++ b/core/tools/definitions/fetchUrlContent.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const fetchUrlContentTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const fetchUrlContentTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.FetchUrlContent, + `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, + [["url", "https://example.com"]], + ), }; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index 42e8afd2d..e0f195a66 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const globSearchTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const globSearchTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.FileGlobSearch, + `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, + [["pattern", "*.py"]], + ), }; diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index 60a4e2710..e276d5a8f 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const grepSearchTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const grepSearchTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.GrepSearch, + `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, + [["query", ".*main_services.*"]], + ), }; diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 71f4e5cf9..97d23f4f6 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const lsTool: Tool = { type: "function", @@ -30,4 +31,12 @@ export const lsTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.LSTool, + `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`, + [ + ["dirPath", "path/to/dir"], + ["recursive", "false"], + ], + ), }; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 9c15105a6..3f07f816f 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readCurrentlyOpenFileTool: Tool = { type: "function", @@ -19,4 +20,10 @@ export const readCurrentlyOpenFileTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ReadCurrentlyOpenFile, + `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. +If the user is asking about a file and you don't see any code, use this to check the current file`, + [], + ), }; diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 42737fe63..fb13eba05 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readFileTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const readFileTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ReadFile, + `To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`, + [["filepath", "path/to/the_file.txt"]], + ), }; diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts index e1d0feb81..0fd7b5de8 100644 --- a/core/tools/definitions/requestRule.test.ts +++ b/core/tools/definitions/requestRule.test.ts @@ -25,7 +25,8 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); expect(result).toBe( - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.", + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + + "No rules available.", ); }); @@ -69,7 +70,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Agent Rule 1: First agent-requested rule\n" + "Agent Rule 2: Second agent-requested rule"; @@ -90,7 +91,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Rule Without Description: undefined"; expect(result).toBe(expected); @@ -110,7 +111,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "undefined: Rule without name"; expect(result).toBe(expected); @@ -130,7 +131,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Rule Without File: Rule without file path"; expect(result).toBe(expected); @@ -159,7 +160,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Valid Agent Rule: This should be included"; expect(result).toBe(expected); @@ -198,7 +199,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Valid Agent Rule: This should be included"; expect(result).toBe(expected); @@ -210,7 +211,8 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); expect(result).toBe( - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.", + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + + "No rules available.", ); }); @@ -229,7 +231,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Single Rule: The only agent-requested rule"; expect(result).toBe(expected); diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts index cb60cda73..4e2f1ef61 100644 --- a/core/tools/definitions/requestRule.ts +++ b/core/tools/definitions/requestRule.ts @@ -1,30 +1,41 @@ import { ConfigDependentToolParams, GetTool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface RequestRuleArgs { name: string; } -export function getRequestRuleDescription( - rules: ConfigDependentToolParams["rules"], -): string { +function getAvailableRules(rules: ConfigDependentToolParams["rules"]) { // Must be explicitly false and no globs const agentRequestedRules = rules.filter( (rule) => rule.alwaysApply === false && !rule.globs, ); - const prefix = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n"; - - const body = agentRequestedRules - .map((rule) => `${rule.name}: ${rule.description}`) - .join("\n"); - - if (body.length === 0) { - return prefix + "No rules available."; + if (agentRequestedRules.length === 0) { + return "No rules available."; } - return prefix + body; + return agentRequestedRules + .map((rule) => `${rule.name}: ${rule.description}`) + .join("\n"); +} + +export function getRequestRuleDescription( + rules: ConfigDependentToolParams["rules"], +): string { + const prefix = + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n"; + return prefix + getAvailableRules(rules); +} + +function getRequestRuleSystemMessageDescription( + rules: ConfigDependentToolParams["rules"], +): string { + const prefix = `To retrieve "rules" that contain more context/instructions based on their descriptions, use the ${BuiltInToolNames.RequestRule} tool with the name of the rule. The available rules are:\n`; + const availableRules = getAvailableRules(rules); + const suffix = "\n\nFor example, you might respond with:"; + return prefix + availableRules + suffix; } export const requestRuleTool: GetTool = ({ rules }) => ({ @@ -49,4 +60,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({ }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.RequestRule, + getRequestRuleSystemMessageDescription(rules), + [["name", "rule_name"]], + ), }); diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index fe5e032de..8ab379e1b 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,17 +1,17 @@ +import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; - -import os from "os"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; /** * Get the preferred shell for the current platform * @returns The preferred shell command or path */ -export function getPreferredShell(): string { +function getPreferredShell(): string { const platform = os.platform(); if (platform === "win32") { - return process.env.COMSPEC || "cmd.exe"; + return "powershell.exe"; } else if (platform === "darwin") { return process.env.SHELL || "/bin/zsh"; } else { @@ -20,7 +20,13 @@ export function getPreferredShell(): string { } } -export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; +const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; + +const RUN_COMMAND_NOTES = `The shell is not stateful and will not remember any previous commands.\ + When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\ + When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\ + Do NOT perform actions requiring special/admin privileges.\ + ${PLATFORM_INFO}`; export const runTerminalCommandTool: Tool = { type: "function", @@ -32,12 +38,7 @@ export const runTerminalCommandTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.RunTerminalCommand, - description: `Run a terminal command in the current directory.\ - The shell is not stateful and will not remember any previous commands.\ - When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\ - When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\ - Do NOT perform actions requiring special/admin privileges.\ - ${PLATFORM_INFO}`, + description: `Run a terminal command in the current directory.\n${RUN_COMMAND_NOTES}`, parameters: { type: "object", required: ["command"], @@ -55,4 +56,12 @@ export const runTerminalCommandTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.RunTerminalCommand, + `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool +${RUN_COMMAND_NOTES} +You can also optionally include the waitForCompletion argument set to false to run the command in the background. +For example, to see the git log, you could respond with:`, + [["command", "git log"]], + ), }; diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index 97b79ca4d..96dac65da 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface SearchAndReplaceInFileArgs { filepath: string; @@ -10,46 +11,16 @@ export interface SearchAndReplaceInFileArgs { export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = "Note this tool CANNOT be called in parallel."; -/** - * This tool is in an experimental state. - * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 - */ -export const searchAndReplaceInFileTool: Tool = { - type: "function", - displayTitle: "Edit File", - wouldLikeTo: "edit {{{ filepath }}}", - isCurrently: "editing {{{ filepath }}}", - hasAlready: "edited {{{ filepath }}}", - group: BUILT_IN_GROUP_NAME, - readonly: false, - isInstant: false, - function: { - name: BuiltInToolNames.SearchAndReplaceInFile, - description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, - parameters: { - type: "object", - required: ["filepath", "diffs"], - properties: { - filepath: { - type: "string", - description: - "The path of the file to modify, relative to the root of the workspace.", - }, - diffs: { - type: "array", - items: { - type: "string", - }, - description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: -\`\`\` -------- SEARCH +const SEARCH_AND_REPLACE_TOOL_DESCRIPTION = `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`; +const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION = + "The path of the file to modify, relative to the root of the workspace."; +const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH [exact content to find] ======= [new content to replace with] -+++++++ REPLACE -\`\`\` ++++++++ REPLACE`; -Critical rules: +const SEARCH_AND_REPLACE_RULES = `Critical rules: 1. SEARCH content must match the associated file section to find EXACTLY: * Match character-for-character including whitespace, indentation, line endings * Include all comments, docstrings, etc. @@ -69,26 +40,84 @@ Critical rules: * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] 6. Special operations: * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) - * To delete code: Use empty REPLACE section + * To delete code: Use empty REPLACE section`; + +const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: +\`\`\` +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} +\`\`\` + +${SEARCH_AND_REPLACE_RULES} Usage: \`\`\` -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE - \`\`\` +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} +\`\`\` -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, +Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`; + +/** + * This tool is in an experimental state. + * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 + */ +export const searchAndReplaceInFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + isInstant: false, + function: { + name: BuiltInToolNames.SearchAndReplaceInFile, + description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION, + parameters: { + type: "object", + required: ["filepath", "diffs"], + properties: { + filepath: { + type: "string", + description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION, + }, + diffs: { + type: "array", + items: { + type: "string", + }, + description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.SearchAndReplaceInFile, + `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. +Each block should follow this format: +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} + +${SEARCH_AND_REPLACE_RULES} + + For example, you could respond with:`, + [ + ["filepath", "path/to/file.ts"], + [ + "diffs", + `[ +"------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE", +"------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE" +]`, + ], + ], + ), }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index d2ce78efc..bcaa743a3 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const searchWebTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const searchWebTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.SearchWeb, + `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, + [["query", "What is the current weather in San Francisco?"]], + ), }; diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index d835986b0..bf488f171 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewDiffTool: Tool = { type: "function", @@ -19,4 +20,9 @@ export const viewDiffTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewDiff, + `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, + [], + ), }; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index dc76e8309..a58584fc1 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewRepoMapTool: Tool = { type: "function", @@ -19,4 +20,9 @@ export const viewRepoMapTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewRepoMap, + `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, + [], + ), }; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 41c1a904c..11c27a775 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewSubdirectoryTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const viewSubdirectoryTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewSubdirectory, + `To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`, + [["directory_path", "path/to/subdirectory"]], + ), }; diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index a026d0f47..ae8964445 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -10,7 +10,9 @@ export const readFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); if (!firstUriMatch) { - throw new Error(`Could not find file ${filepath}`); + throw new Error( + `File "${filepath}" does not exist. You might want to check the path and try again.`, + ); } const content = await extras.ide.readFile(firstUriMatch); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 201d76358..c48ba2ade 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -16,6 +16,19 @@ function getDecodedOutput(data: Buffer): string { } else { return data.toString(); } +} // Simple helper function to use login shell on Unix/macOS and PowerShell on Windows +function getShellCommand(command: string): { shell: string; args: string[] } { + if (process.platform === "win32") { + // Windows: Use PowerShell + return { + shell: "powershell.exe", + args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command], + }; + } else { + // Unix/macOS: Use login shell to source .bashrc/.zshrc etc. + const userShell = process.env.SHELL || "/bin/bash"; + return { shell: userShell, args: ["-l", "-c", command] }; + } } import { fileURLToPath } from "node:url"; @@ -88,9 +101,9 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } // Use spawn with color environment - const childProc = childProcess.spawn(command, { + const { shell, args } = getShellCommand(command); + const childProc = childProcess.spawn(shell, args, { cwd, - shell: true, env: getColorEnv(), // Add enhanced environment for colors }); @@ -232,11 +245,49 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (waitForCompletion) { // Standard execution, waiting for completion try { - // Use color environment for exec as well - const output = await asyncExec(command, { - cwd, - env: getColorEnv(), - }); + // Use spawn approach for consistency with streaming version + const { shell: nonStreamingShell, args: nonStreamingArgs } = + getShellCommand(command); + const output = await new Promise<{ stdout: string; stderr: string }>( + (resolve, reject) => { + const childProc = childProcess.spawn( + nonStreamingShell, + nonStreamingArgs, + { + cwd, + env: getColorEnv(), + }, + ); + + let stdout = ""; + let stderr = ""; + + childProc.stdout?.on("data", (data) => { + stdout += getDecodedOutput(data); + }); + + childProc.stderr?.on("data", (data) => { + stderr += getDecodedOutput(data); + }); + + childProc.on("close", (code) => { + if (code === 0) { + resolve({ stdout, stderr }); + } else { + const error = new Error( + `Command failed with exit code ${code}`, + ); + (error as any).stderr = stderr; + reject(error); + } + }); + + childProc.on("error", (error) => { + reject(error); + }); + }, + ); + const status = "Command completed"; return [ { @@ -262,9 +313,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // but don't attach any listeners other than error try { // Use spawn with color environment - const childProc = childProcess.spawn(command, { + const { shell: detachedShell, args: detachedArgs } = + getShellCommand(command); + const childProc = childProcess.spawn(detachedShell, detachedArgs, { cwd, - shell: true, env: getColorEnv(), // Add color environment // Detach the process so it's not tied to the parent detached: true, diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.ts new file mode 100644 index 000000000..8536c794f --- /dev/null +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.ts @@ -0,0 +1,167 @@ +import { Tool } from "../.."; +import { closeTag } from "./systemToolUtils"; + +export const TOOL_INSTRUCTIONS_TAG = ""; +export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION"; +export const TOOL_DESCRIPTION_TAG = "DESCRIPTION"; + +const EXAMPLE_DYNAMIC_TOOL = ` +\`\`\`tool_definition +TOOL_NAME: example_tool +TOOL_ARG: arg_1 (string, required) +Description of the first argument +END_ARG +TOOL_ARG: arg_2 (number, optional) +END_ARG +\`\`\``.trim(); + +const EXAMPLE_DYNAMIC_TOOL_CALL = ` +\`\`\`tool +TOOL_NAME: example_tool +BEGIN_ARG: arg_1 +The value +of arg 1 +END_ARG +BEGIN_ARG: arg_2 +3 +END_ARG +\`\`\``.trim(); + +export function createSystemMessageExampleCall( + name: string, + instructions: string, + args: Array<[string, string]> = [], +) { + let callExample = `\`\`\`tool +TOOL_NAME: ${name}`; + + // Add each argument dynamically + for (const [argName, argValue] of args) { + callExample += ` +BEGIN_ARG: ${argName} +${argValue} +END_ARG`; + } + + callExample += ` +\`\`\``; + + return `${instructions.trim()} +${callExample}`; +} + +function toolToSystemToolDefinition(tool: Tool): string { + let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`; + + if (tool.function.description) { + toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`; + } + + if (tool.function.parameters && "properties" in tool.function.parameters) { + for (const [key, value] of Object.entries( + tool.function.parameters.properties as object, + )) { + const isRequired = tool.function.parameters.required?.includes(key); + const requiredText = isRequired ? "required" : "optional"; + + let argType = "string"; + if ("type" in value) { + argType = value.type; + } + let argDescription = ""; + if ("description" in value) { + argDescription = value.description; + } + + toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`; + if (argDescription) { + toolDefinition += argDescription + "\n"; + } + toolDefinition += `END_ARG\n`; + } + } + + toolDefinition += `\`\`\``; + return toolDefinition.trim(); +} + +export const generateToolsSystemMessage = (tools: Tool[]): string => { + if (tools.length === 0) { + return ""; + } + const withPredefinedMessage = tools.filter( + (tool) => !!tool.systemMessageDescription, + ); + + const withDynamicMessage = tools.filter( + (tool) => !tool.systemMessageDescription, + ); + + const instructions: string[] = []; + instructions.push(TOOL_INSTRUCTIONS_TAG); + instructions.push( + `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`, + ); + instructions.push( + `To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`, + ); + + if (withPredefinedMessage.length > 0) { + instructions.push(`\nThe following tools are available to you:`); + for (const tool of withPredefinedMessage) { + instructions.push(`\n${tool.systemMessageDescription}`); + } + } + + if (withDynamicMessage.length > 0) { + instructions.push( + `\nAlso, these additional tool definitions show other tools you can call with the same syntax:`, + ); + + for (const tool of tools) { + try { + const definition = toolToSystemToolDefinition(tool); + instructions.push(`\n${definition}`); + } catch (e) { + console.error( + "Failed to convert tool to system message tool:\n" + + JSON.stringify(tool), + ); + } + } + + instructions.push(`\nFor example, this tool definition:\n`); + instructions.push(EXAMPLE_DYNAMIC_TOOL); + instructions.push("\nCan be called like this:\n"); + instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL); + } + + instructions.push( + `\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`, + ); + instructions.push( + `Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`, + ); + instructions.push( + `Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`, + ); + instructions.push( + `You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`, + ); + + instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`); + return instructions.join("\n"); +}; + +export function addSystemMessageToolsToSystemMessage( + baseSystemMessage: string, + systemMessageTools: Tool[], +): string { + let systemMessage = baseSystemMessage; + if (systemMessageTools.length > 0) { + const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools); + systemMessage += `\n\n${toolsSystemMessage}`; + } + + return systemMessage; +} diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts new file mode 100644 index 000000000..70215c477 --- /dev/null +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts @@ -0,0 +1,252 @@ +import { describe, expect, it } from "vitest"; +import { Tool } from "../.."; +import { + TOOL_INSTRUCTIONS_TAG, + addSystemMessageToolsToSystemMessage, + createSystemMessageExampleCall, + generateToolsSystemMessage, +} from "./buildToolsSystemMessage"; +import { closeTag } from "./systemToolUtils"; + +const SHARED_TOOL_FIELDS = { + displayTitle: "DUD", + group: "DUD", + readonly: true, + type: "function" as const, +}; + +describe("createSystemMessageExampleCall", () => { + it("creates a system message example call with no args", () => { + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + ); + expect(result).includes("Use this tool to test things"); + expect(result).includes("```tool"); + expect(result).includes("TOOL_NAME: test_tool"); + expect(result).includes("```"); + }); + + it("creates a system message example call with args", () => { + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + [ + ["arg1", "value1"], + ["arg2", "value2"], + ], + ); + + expect(result).includes("Use this tool to test things"); + expect(result).includes("```tool"); + expect(result).includes("TOOL_NAME: test_tool"); + expect(result).includes("BEGIN_ARG: arg1"); + expect(result).includes("value1"); + expect(result).includes("END_ARG"); + expect(result).includes("BEGIN_ARG: arg2"); + expect(result).includes("value2"); + }); + + it("handles multiline arg values correctly", () => { + const multilineValue = "value\nwith\nmultiple\nlines"; + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + [["arg1", multilineValue]], + ); + + expect(result).includes("BEGIN_ARG: arg1"); + expect(result).includes(multilineValue); + expect(result).includes("END_ARG"); + }); +}); + +describe("generateToolsSystemMessage", () => { + it("returns empty string for empty tools array", () => { + const result = generateToolsSystemMessage([]); + expect(result).toBe(""); + }); + + it("generates system message for tools with system message descriptions", () => { + const customDescription = + "This is test tool 1's system message description"; + const tools: Tool[] = [ + { + function: { + name: "test_tool1", + description: "Test tool 1 description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + systemMessageDescription: customDescription, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check structure rather than exact text + expect(result).includes(TOOL_INSTRUCTIONS_TAG); + expect(result).includes(customDescription); + expect(result).includes(closeTag(TOOL_INSTRUCTIONS_TAG)); + + // Check for general section about available tools without requiring exact wording + const hasToolsAvailableSection = /tools are available to you/i.test(result); + expect(hasToolsAvailableSection).toBe(true); + }); + + it("generates system message for tools without system message descriptions", () => { + const toolName = "test_tool2"; + const toolDesc = "Test tool 2 description"; + const paramDesc = "Parameter 1 description"; + + const tools: Tool[] = [ + { + function: { + name: toolName, + description: toolDesc, + parameters: { + type: "object", + properties: { + param1: { + type: "string", + description: paramDesc, + }, + }, + required: ["param1"], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for key elements without requiring exact wording + expect(result).includes(`TOOL_NAME: ${toolName}`); + expect(result).includes("TOOL_DESCRIPTION:"); + expect(result).includes(toolDesc); + expect(result).includes("TOOL_ARG: param1 (string, required)"); + expect(result).includes(paramDesc); + + // Check for dynamic tool section without exact text matching + const hasDynamicToolsSection = /additional tool definitions/i.test(result); + expect(hasDynamicToolsSection).toBe(true); + }); + + it("handles tools with and without system message descriptions", () => { + const customMsg = "Custom system message"; + const tools: Tool[] = [ + { + function: { + name: "tool_with_description", + description: "Tool description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + systemMessageDescription: customMsg, + ...SHARED_TOOL_FIELDS, + }, + { + function: { + name: "tool_without_description", + description: "Another tool description", + parameters: { + type: "object", + properties: { + param1: { + type: "string", + description: "Parameter description", + }, + }, + required: ["param1"], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for both types of tools + expect(result).includes(customMsg); + expect(result).includes("TOOL_NAME: tool_without_description"); + + // Verify structure without exact text matching + const hasAvailableToolsSection = /tools are available to you/i.test(result); + expect(hasAvailableToolsSection).toBe(true); + + const hasDynamicToolsSection = /additional tool definitions/i.test(result); + expect(hasDynamicToolsSection).toBe(true); + }); + + it("includes example tool definition and call", () => { + const tools: Tool[] = [ + { + function: { + name: "test_tool", + description: "Test description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for example sections without exact text + expect(result).includes("```tool_definition"); + expect(result).includes("TOOL_NAME: example_tool"); + expect(result).includes("```tool"); + + // Check for example format structure + const hasExampleDefinition = /example.*tool definition/i.test(result); + const hasExampleCall = /called like this/i.test(result); + + expect(hasExampleDefinition).toBe(true); + expect(hasExampleCall).toBe(true); + }); +}); + +describe("addSystemMessageToolsToSystemMessage", () => { + it("returns original system message when no tools are provided", () => { + const baseMessage = "This is the base system message"; + const result = addSystemMessageToolsToSystemMessage(baseMessage, []); + expect(result).toBe(baseMessage); + }); + + it("appends tools system message to base message", () => { + const baseMessage = "This is the base system message"; + const toolName = "test_tool"; + const tools: Tool[] = [ + { + function: { + name: toolName, + description: "Test description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = addSystemMessageToolsToSystemMessage(baseMessage, tools); + + expect(result.startsWith(baseMessage)).toBe(true); + expect(result).includes(TOOL_INSTRUCTIONS_TAG); + expect(result).includes(`TOOL_NAME: ${toolName}`); + }); +}); diff --git a/core/tools/systemMessageTools/convertSystemTools.ts b/core/tools/systemMessageTools/convertSystemTools.ts new file mode 100644 index 000000000..4517915d0 --- /dev/null +++ b/core/tools/systemMessageTools/convertSystemTools.ts @@ -0,0 +1,95 @@ +import { + AssistantChatMessage, + MessagePart, + ToolCallState, + UserChatMessage, +} from "../.."; +import { + normalizeToMessageParts, + renderContextItems, +} from "../../util/messageContent"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "../constants"; +function toolCallStateToSystemToolCall(state: ToolCallState): string { + let parts = ["```tool"]; + parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); + try { + for (const arg in state.parsedArgs) { + parts.push(`BEGIN_ARG: ${arg}`); + parts.push(JSON.stringify(state.parsedArgs[arg])); + parts.push(`END_ARG`); + } + } catch (e) { + console.log("Failed to stringify json args", state.parsedArgs); + } + // TODO - include tool call id for parallel. Confuses dumb models + parts.push("```"); + return parts.join("\n"); +} + +function toolCallStateToSystemToolOutput(state: ToolCallState): string { + let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; + // TODO - include tool call id for parallel. Confuses dumb models + // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`; + if (state.status === "canceled") { + output += CANCELLED_TOOL_CALL_MESSAGE; + } else if (state.output?.length) { + output += renderContextItems(state.output); + } else { + output += NO_TOOL_CALL_OUTPUT_MESSAGE; + } + return output; +} + +export function convertToolCallStatesToSystemCallsAndOutput( + originalAssistantMessage: AssistantChatMessage, + toolCallStates: ToolCallState[], +): { + assistantMessage: AssistantChatMessage; + userMessage: UserChatMessage; +} { + const parts = normalizeToMessageParts(originalAssistantMessage); + if (originalAssistantMessage.toolCalls) { + parts.push( + ...toolCallStates.map((state) => ({ + type: "text" as const, + text: toolCallStateToSystemToolCall(state), + })), + ); + } + + // new message with tool calls moved to content + const assistantMessage: AssistantChatMessage = { + ...originalAssistantMessage, + content: parts, + toolCalls: undefined, // remove tool calls from the assistant message + }; + + const userParts: MessagePart[] = []; + if (toolCallStates) { + for (const state of toolCallStates) { + userParts.push({ + type: "text", + text: toolCallStateToSystemToolOutput(state), + }); + } + } + if (userParts.length === 0) { + userParts.push({ + type: "text", + text: "Error: no tool output for tool calls", + }); + } + + const userMessage: UserChatMessage = { + role: "user", + content: userParts, + }; + + return { + assistantMessage, + userMessage, + }; +} diff --git a/core/tools/systemMessageTools/detectToolCallStart.ts b/core/tools/systemMessageTools/detectToolCallStart.ts new file mode 100644 index 000000000..f99ce03d5 --- /dev/null +++ b/core/tools/systemMessageTools/detectToolCallStart.ts @@ -0,0 +1,33 @@ +let boundaryTypeIndex = 0; + +// Poor models are really bad at following instructions +// Give some leeway in how the initiate +const acceptedToolStarts: [string, string][] = [ + ["```tool\n", "```tool\n"], + ["tool_name:", "```tool\nTOOL_NAME:"], +]; + +export function detectToolCallStart(buffer: string) { + let modifiedBuffer = buffer; + let isInToolCall = false; + let isInPartialStart = false; + const lowerCaseBuffer = buffer.toLowerCase(); + for (let i = 0; i < acceptedToolStarts.length; i++) { + const [start, replacement] = acceptedToolStarts[i]; + if (lowerCaseBuffer.startsWith(start)) { + // for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive + if (i !== 0) { + modifiedBuffer = buffer.replace(new RegExp(start, "i"), replacement); + } + isInToolCall = true; + break; + } else if (start.startsWith(lowerCaseBuffer)) { + isInPartialStart = true; + } + } + return { + isInToolCall, + isInPartialStart, + modifiedBuffer, + }; +} diff --git a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts b/core/tools/systemMessageTools/detectToolCallStart.vitest.ts new file mode 100644 index 000000000..715113475 --- /dev/null +++ b/core/tools/systemMessageTools/detectToolCallStart.vitest.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { detectToolCallStart } from "./detectToolCallStart"; + +describe("detectToolCallStart", () => { + it("detects standard tool call start", () => { + const buffer = "```tool\nTOOL_NAME: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("detects tool_name start without codeblock", () => { + const buffer = "tool_name: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool"); + }); + + it("detects case-insensitive tool call start", () => { + const buffer = "```ToOl\nTOOL_NAME: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("detects case-insensitive tool_name start", () => { + const buffer = "ToOl_NaMe: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool"); + }); + + it("identifies partial tool call start", () => { + const buffer = "```to"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(true); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("identifies partial tool_name start", () => { + const buffer = "tool_na"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(true); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("does not detect tool call in unrelated text", () => { + const buffer = "This is some regular text."; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("does not detect tool call in similar but different markdown block", () => { + const buffer = "```javascript\nconst x = 10;"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); +}); diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.ts new file mode 100644 index 000000000..31fb562bf --- /dev/null +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.ts @@ -0,0 +1,114 @@ +import { ChatMessage, PromptLog, TextMessagePart } from "../.."; +import { normalizeToMessageParts } from "../../util/messageContent"; +import { detectToolCallStart } from "./detectToolCallStart"; +import { + getInitialTooLCallParseState, + handleToolCallBuffer, + ToolCallParseState, +} from "./parseSystemToolCall"; +import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils"; + +/* + Function to intercept tool calls in markdown code blocks format from a chat message stream + 1. Skips non-assistant messages + 2. Intercepts text that looks like a tool call in a markdown code block format: + ```tool + TOOL_NAME: example_tool + BEGIN_ARG: arg1 + value + END_ARG + ``` + 3. Parses tool calls line by line and generates proper tool call deltas + 4. Once the tool call is complete, resets state for potential future tool calls +*/ +export async function* interceptSystemToolCalls( + messageGenerator: AsyncGenerator, + abortController: AbortController, +): AsyncGenerator { + let buffer = ""; + let parseState: ToolCallParseState | undefined; + + while (true) { + const result = await messageGenerator.next(); + if (result.done) { + // Case: non-standard tool termination causes hanging args + if (parseState && !parseState.done && parseState.processedArgNames.size) { + yield [ + { + role: "assistant", + content: "", + toolCalls: [createDelta("", "}", parseState.toolCallId)], + }, + ]; + } + + return result.value; + } else { + for await (const message of result.value) { + if (abortController.signal.aborted || parseState?.done) { + break; + } + // Skip non-assistant messages or messages with native tool calls + if (message.role !== "assistant" || message.toolCalls) { + yield [message]; + continue; + } + + const parts = normalizeToMessageParts(message); + + // Image output cannot be combined with tools + if (parts.find((part) => part.type === "imageUrl")) { + yield [message]; + continue; + } + + const chunks = (parts as TextMessagePart[]) + .map((part) => splitAtCodeblocksAndNewLines(part.text)) + .flat(); + + for (const chunk of chunks) { + buffer += chunk; + if (!parseState) { + const { isInPartialStart, isInToolCall, modifiedBuffer } = + detectToolCallStart(buffer); + + if (isInPartialStart) { + continue; + } + if (isInToolCall) { + parseState = getInitialTooLCallParseState(); + buffer = modifiedBuffer; + } + } + + if (parseState && !parseState.done) { + const delta = handleToolCallBuffer(buffer, parseState); + if (delta) { + yield [ + { + ...message, + content: "", + toolCalls: [delta], + }, + ]; + } + } else { + // Prevent content after tool calls for now + if (parseState) { + continue; + } + + // Yield normal assistant message + yield [ + { + ...message, + content: [{ type: "text", text: buffer }], + }, + ]; + } + buffer = ""; + } + } + } + } +} diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts new file mode 100644 index 000000000..756125bd4 --- /dev/null +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts @@ -0,0 +1,325 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; +import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; + +describe("interceptSystemToolCalls", () => { + let abortController: AbortController; + + beforeEach(() => { + abortController = new AbortController(); + }); + + const createAsyncGenerator = async function* ( + messages: ChatMessage[][], + ): AsyncGenerator { + for (const messageGroup of messages) { + yield messageGroup; + } + return undefined; + }; + + it("passes through non-assistant messages unchanged", async () => { + const messages: ChatMessage[][] = [ + [{ role: "user", content: "Hello" }], + [{ role: "system", content: "System message" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + let result = await generator.next(); + expect(result.value).toEqual([{ role: "user", content: "Hello" }]); + + result = await generator.next(); + expect(result.value).toEqual([ + { role: "system", content: "System message" }, + ]); + + result = await generator.next(); + expect(result.done).toBe(true); + }); + + it("passes through assistant messages with existing tool calls", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: "", + toolCalls: [ + { + type: "function", + function: { + name: "existing_tool", + arguments: '{"arg1":"value1"}', + }, + id: "existing_call_id", + }, + ], + }, + ], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const result = await generator.next(); + expect(result.value).toEqual(messages[0]); + }); + + it("passes through assistant messages with image URLs unchanged", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: [ + { type: "text", text: "Here's an image:" }, + { + type: "imageUrl", + imageUrl: { + url: "https://example.com/image.png", + }, + }, + ], + }, + ], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const result = await generator.next(); + expect(result.value).toEqual(messages[0]); + }); + + it("processes standard tool call format", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: "I'll help you with that. Let me use a tool:\n", + }, + ], + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // First chunk should be normal text + let result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "I'll help you with that. Let me use a tool:", + }, + ], + }, + ]); + + result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "\n", + }, + ], + }, + ]); + + // Tool name detection + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name, + ).toBe("test_tool"); + + // Begin argument + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toContain('{"arg1":'); + + // Argument value + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('"value1"'); + + // End of tool call + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("}"); + }); + + it("processes tool_name without codeblock format", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "I'll help you with that.\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // First chunk should be normal text + let result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [{ type: "text", text: "I'll help you with that." }], + }, + ]); + + result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "\n", + }, + ], + }, + ]); + + // The system should detect the tool_name format and convert it + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name, + ).toBe("test_tool"); + + // Rest of processing should work as normal + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('{"arg1":'); + + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('"value1"'); + + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("}"); + }); + + it("ignores content after a tool call", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```\n" }], + [{ role: "assistant", content: "This content should be ignored" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + let result; + // Process through all the tool call parts + for (let i = 0; i < 6; i++) { + result = await generator.next(); + } + + // The content after the tool call should be ignored + result = await generator.next(); + expect(result.value).toBeUndefined(); + }); + + it("stops processing when aborted", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // Process the first part + let result = await generator.next(); + + // Abort before processing the second part + abortController.abort(); + + // The next value should be undefined + result = await generator.next(); + expect(result.value).toBeUndefined(); + }); + + it("handles JSON parsing for argument values", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: number_arg\n" }], + [{ role: "assistant", content: "123\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "BEGIN_ARG: boolean_arg\n" }], + [{ role: "assistant", content: "true\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // Skip to number arg end + await generator.next(); + await generator.next(); + let result; + result = await generator.next(); + + expect( + (result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("123"); + + // Skip to boolean arg end + await generator.next(); + result = await generator.next(); + + expect( + (result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("true"); + }); +}); diff --git a/core/tools/systemMessageTools/parseSystemToolCall.ts b/core/tools/systemMessageTools/parseSystemToolCall.ts new file mode 100644 index 000000000..0300654d9 --- /dev/null +++ b/core/tools/systemMessageTools/parseSystemToolCall.ts @@ -0,0 +1,143 @@ +import { ToolCallDelta } from "../.."; +import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils"; + +export type ToolCallParseState = { + toolCallId: string; + isOnArgBeginLine: boolean; + currentArgName: string | undefined; + currentArgLines: string[]; + processedArgNames: Set; + currentLineIndex: number; + lineChunks: string[][]; + done: boolean; +}; + +export const getInitialTooLCallParseState = (): ToolCallParseState => ({ + toolCallId: generateOpenAIToolCallId(), + isOnArgBeginLine: false, + currentArgName: undefined, + currentArgLines: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, +}); + +/* + Efficiently applies chunks to a tool call state as they come in + Expects chunks to be broken so that new lines and codeblocks are alone + For now, this parser collects entire arg before + This is because support for JSON booleans is tricky otherwise + +*/ +export function handleToolCallBuffer( + chunk: string, + state: ToolCallParseState, +): ToolCallDelta | undefined { + // Add chunks + const lineIndex = state.currentLineIndex; + if (!state.lineChunks[lineIndex]) { + state.lineChunks[lineIndex] = []; + } + state.lineChunks[lineIndex].push(chunk); + + const isNewLine = chunk === "\n"; + if (isNewLine) { + state.currentLineIndex++; + } + + const line = state.lineChunks[lineIndex].join(""); + + switch (lineIndex) { + // The first line will be skipped (e.g. ```tool\n) + case 0: + // non-standard start sequences will sometimes include stuff in the tool_name line + const splitBuffer = line.split("\n"); + if (splitBuffer[0]) { + state.lineChunks[0] = [splitBuffer[0], "\n"]; + } + if (splitBuffer[1]) { + state.lineChunks[1] = [splitBuffer[1]]; + } + + state.currentLineIndex = 1; + // Tool name line - process once line 2 is reached + case 1: + if (isNewLine) { + const name = (line.split(/tool_?name:/i)[1] ?? "").trim(); + if (!name) { + throw new Error("Invalid tool name"); + } + return createDelta(name, "", state.toolCallId); + } + return; + default: + if (state.isOnArgBeginLine) { + if (isNewLine) { + const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim(); + if (!argName) { + throw new Error("Invalid begin arg line"); + } + state.currentArgName = argName; + state.isOnArgBeginLine = false; + const argPrefix = state.processedArgNames.size === 0 ? "{" : ","; + return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId); + } + } else if (state.currentArgName) { + if (isNewLine) { + const isEndArgTag = line.match(/end_?arg/i); + if (isEndArgTag) { + let trimmedValue = state.currentArgLines.join("").trim(); + state.currentArgLines.length = 0; + state.processedArgNames.add(state.currentArgName); + state.currentArgName = undefined; + + try { + if ( + trimmedValue.startsWith("[") || + trimmedValue.startsWith("{") + ) { + trimmedValue = trimmedValue.replace( + /"((?:\\[\s\S]|[^"\\])*?)"/g, + (match) => { + const content = match.slice(1, -1); + // Replace unescaped newlines + return ( + '"' + + content + .replace(/([^\\])\n/g, "$1\\n") + .replace(/^\n/g, "\\n") + + '"' + ); + }, + ); + } + const parsed = JSON.parse(trimmedValue); + const stringifiedArg = JSON.stringify(parsed); + return createDelta("", stringifiedArg, state.toolCallId); + } catch (e) { + const stringifiedArg = JSON.stringify(trimmedValue); + return createDelta("", stringifiedArg, state.toolCallId); + } + } else { + state.currentArgLines.push(line); + } + } + } else { + // Check for entry into arg + const isBeginArgLine = line.match(/begin_?arg:/i); + if (isBeginArgLine) { + state.isOnArgBeginLine = true; + } + + // Check for exit + if (line === "```" || isNewLine) { + state.done = true; + // finish args JSON if applicable + if (state.processedArgNames.size > 0) { + return createDelta("", "}", state.toolCallId); + } + } + } + } +} diff --git a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts new file mode 100644 index 000000000..2aeac2ce8 --- /dev/null +++ b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts @@ -0,0 +1,301 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + ToolCallParseState, + getInitialTooLCallParseState, + handleToolCallBuffer, +} from "./parseSystemToolCall"; + +describe("getInitialTooLCallParseState", () => { + it("returns a properly initialized parse state", () => { + const state = getInitialTooLCallParseState(); + + expect(state).toEqual({ + isOnArgBeginLine: false, + currentArgName: undefined, + currentArgLines: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, + toolCallId: expect.any(String), + }); + }); +}); + +describe("handleToolCallBuffer", () => { + let state: ToolCallParseState; + + beforeEach(() => { + state = getInitialTooLCallParseState(); + }); + + it("handles the ```tool\ntool_name the name", () => { + handleToolCallBuffer("```tool\ntool_name: my_name", state); + expect(state.currentLineIndex).toBe(1); + + const result = handleToolCallBuffer("\n", state); + expect(result).toEqual({ + type: "function", + function: { + name: "my_name", + arguments: "", + }, + id: expect.any(String), + }); + expect(state.currentLineIndex).toBe(2); + }); + + it("handles the tool name line", () => { + // Line 0 (```tool) is skipped internally + state.currentLineIndex = 1; + + const result = handleToolCallBuffer("TOOL_NAME: test_tool", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "test_tool", + arguments: "", + }, + id: expect.any(String), + }); + expect(state.currentLineIndex).toBe(2); + }); + + it("handles case-insensitive tool name line", () => { + state.currentLineIndex = 1; + + const result = handleToolCallBuffer("tool_name: test_tool", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "test_tool", + arguments: "", + }, + id: expect.any(String), + }); + }); + + it("begins an argument correctly", () => { + state.currentLineIndex = 2; + + const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state); + expect(result).toBeUndefined(); + expect(state.isOnArgBeginLine).toBe(true); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '{"test_arg":', + }, + id: expect.any(String), + }); + expect(state.currentArgName).toBe("test_arg"); + expect(state.isOnArgBeginLine).toBe(false); + }); + + it("handles case-insensitive begin arg", () => { + state.currentLineIndex = 2; + + const result = handleToolCallBuffer("begin_arg: test_arg", state); + expect(result).toBeUndefined(); + expect(state.isOnArgBeginLine).toBe(true); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '{"test_arg":', + }, + id: expect.any(String), + }); + }); + + it("collects arg value lines", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + + handleToolCallBuffer("line 1", state); + const newLineResult1 = handleToolCallBuffer("\n", state); + expect(newLineResult1).toBeUndefined(); + + handleToolCallBuffer("line 2", state); + const newLineResult2 = handleToolCallBuffer("\n", state); + expect(newLineResult2).toBeUndefined(); + + expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]); + }); + + it("ends an argument correctly with string value", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["string value"]; + + const result = handleToolCallBuffer("END_ARG", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"string value"', + }, + id: expect.any(String), + }); + expect(state.currentArgName).toBeUndefined(); + expect(state.processedArgNames.has("test_arg")).toBe(true); + }); + + it("handles case-insensitive end arg", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["string value"]; + + const result = handleToolCallBuffer("end_arg", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"string value"', + }, + id: expect.any(String), + }); + }); + + it("attempts to parse JSON values", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["123"]; + + handleToolCallBuffer("END_ARG", state); + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: "123", + }, + id: expect.any(String), + }); + }); + + it("handles multiple arguments", () => { + // Setup first arg + state.currentLineIndex = 2; + state.isOnArgBeginLine = true; + state.lineChunks[2] = ["BEGIN_ARG: first_arg"]; + + handleToolCallBuffer("\n", state); + handleToolCallBuffer("value1", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("END_ARG", state); + handleToolCallBuffer("\n", state); + + expect(state.processedArgNames.has("first_arg")).toBe(true); + + // Setup second arg + state.isOnArgBeginLine = true; + handleToolCallBuffer("BEGIN_ARG: second_arg", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("value2", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("END_ARG", state); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"value2"', + }, + id: expect.any(String), + }); + expect(state.processedArgNames.has("second_arg")).toBe(true); + }); + + it("finalizes JSON object at end of tool call", () => { + state.currentLineIndex = 5; + state.processedArgNames.add("test_arg"); + + const result = handleToolCallBuffer("```", state); + + expect(result).toEqual({ + type: "function", + function: { + name: "", + arguments: "}", + }, + id: expect.any(String), + }); + expect(state.done).toBe(true); + }); + + it("finalizes on newline after all args processed", () => { + state.currentLineIndex = 5; + state.processedArgNames.add("test_arg"); + + const result = handleToolCallBuffer("\n", state); + + expect(result).toEqual({ + type: "function", + function: { + name: "", + arguments: "}", + }, + id: expect.any(String), + }); + expect(state.done).toBe(true); + }); + + it("handles JSON array args", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = [ + "[\n", + '"------- SEARCH\n', + " subtract(number) {\n", + " return this;\n", + " }\n", + "=======\n", + " subtract(number) {\n", + " this -= number\n", + " return this;\n", + " }\n", + '+++++++ REPLACE"\n', + "]\n", + ]; + + handleToolCallBuffer("END_ARG", state); + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: + '["------- SEARCH\\n subtract(number) {\\n return this;\\n }\\n=======\\n subtract(number) {\\n this -= number\\n return this;\\n }\\n+++++++ REPLACE"]', + }, + id: expect.any(String), + }); + }); +}); diff --git a/core/tools/systemMessageTools/systemToolUtils.ts b/core/tools/systemMessageTools/systemToolUtils.ts new file mode 100644 index 000000000..2271f269b --- /dev/null +++ b/core/tools/systemMessageTools/systemToolUtils.ts @@ -0,0 +1,38 @@ +import { ToolCallDelta } from "../.."; + +export function closeTag(openingTag: string): string { + return ` { + const testCases = [ + { + input: "
", + expectedOutput: "
", + }, + { + input: "

", + expectedOutput: "

", + }, + // Add more test cases as needed + ]; + + testCases.forEach((testCase) => { + test(`closes tag "${testCase.input}" to " { + const result = closeTag(testCase.input); + expect(result).toEqual(testCase.expectedOutput); + }); + }); +}); + +describe("splitAtCodeblocks", () => { + test("doesn't split plain text without codeblocks", () => { + expect(splitAtCodeblocksAndNewLines("hello world")).toEqual([ + "hello world", + ]); + }); + + test("splits at codeblocks", () => { + expect(splitAtCodeblocksAndNewLines("```middle```")).toEqual([ + "```", + "middle", + "```", + "", + ]); + }); + + test("splits at new lines", () => { + expect(splitAtCodeblocksAndNewLines("hello\nhoware\n you\n")).toEqual([ + "hello", + "\n", + "howare", + "\n", + " you", + "\n", + ]); + }); + + test("splits at both codeblocks and new lines", () => { + expect(splitAtCodeblocksAndNewLines("hello```\nho```ware\n you\n")).toEqual( + ["hello", "```", "\n", "ho", "```", "ware", "\n", " you", "\n"], + ); + }); +}); diff --git a/core/tools/systemMessageTools/textifySystemTools.ts b/core/tools/systemMessageTools/textifySystemTools.ts new file mode 100644 index 000000000..f654037df --- /dev/null +++ b/core/tools/systemMessageTools/textifySystemTools.ts @@ -0,0 +1,102 @@ +import { + AssistantChatMessage, + MessagePart, + ToolCallState, + UserChatMessage, +} from "../.."; +import { + normalizeToMessageParts, + renderContextItems, +} from "../../util/messageContent"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "../constants"; +function toolCallStateToSystemToolCall(state: ToolCallState): string { + let parts = ["```tool"]; + parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); + try { + for (const arg in state.parsedArgs) { + parts.push(`BEGIN_ARG: ${arg}`); + parts.push(JSON.stringify(state.parsedArgs[arg])); + parts.push(`END_ARG`); + } + } catch (e) { + console.log("Failed to stringify json args", state.parsedArgs); + } + // TODO - include tool call id for parallel. Confuses dumb models + parts.push("```"); + return parts.join("\n"); +} + +function toolCallStateToSystemToolOutput(state: ToolCallState): string { + let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; + // TODO - include tool call id for parallel. Confuses dumb models + // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`; + if (state.status === "canceled") { + output += CANCELLED_TOOL_CALL_MESSAGE; + } else if (state.output?.length) { + output += renderContextItems(state.output); + } else { + output += NO_TOOL_CALL_OUTPUT_MESSAGE; + } + return output; +} + +export function convertToolCallStatesToSystemCallsAndOutput( + originalAssistantMessage: AssistantChatMessage, + toolCallStates: ToolCallState[], +): { + assistantMessage: AssistantChatMessage; + userMessage: UserChatMessage; +} { + const assistantParts = normalizeToMessageParts(originalAssistantMessage); + if (originalAssistantMessage.toolCalls) { + assistantParts.push( + ...toolCallStates.map((state) => ({ + type: "text" as const, + text: toolCallStateToSystemToolCall(state), + })), + ); + } + + const userParts: MessagePart[] = []; + if (toolCallStates) { + for (const state of toolCallStates) { + userParts.push({ + type: "text", + text: toolCallStateToSystemToolOutput(state), + }); + } + } + if (userParts.length === 0) { + userParts.push({ + type: "text", + text: "No tool output for tool calls", + }); + } + + const nonEmptyAssistantParts = assistantParts.filter( + (p) => p.type !== "text" || !!p.text, + ); + const nonEmptyUserParts = userParts.filter( + (p) => p.type !== "text" || !!p.text, + ); + + // new message with tool calls moved to content + const assistantMessage: AssistantChatMessage = { + ...originalAssistantMessage, + content: nonEmptyAssistantParts, + toolCalls: undefined, // remove tool calls from the assistant message + }; + + const userMessage: UserChatMessage = { + role: "user", + content: nonEmptyUserParts, + }; + + return { + assistantMessage, + userMessage, + }; +} diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 72c66740f..67a70374a 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -2,7 +2,7 @@ import * as fs from "node:fs"; import { fileURLToPath } from "node:url"; import { - ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -53,6 +53,14 @@ class FileSystemIde implements IDE { return Promise.resolve(null); } + getReferences(location: Location): Promise { + return Promise.resolve([]); + } + + getDocumentSymbols(fileUri: string): Promise { + return Promise.resolve([]); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } @@ -145,10 +153,6 @@ class FileSystemIde implements IDE { return Promise.resolve("NOT_UNIQUE"); } - getWorkspaceConfigs(): Promise { - return Promise.resolve([]); - } - getDiff(includeUnstaged: boolean): Promise { return Promise.resolve([]); } diff --git a/docs/customization/overview.mdx b/docs/customization/overview.mdx index 8f6b2cabd..ad86194af 100644 --- a/docs/customization/overview.mdx +++ b/docs/customization/overview.mdx @@ -3,10 +3,10 @@ title: "Overview" description: "Continue can be deeply customized. For example you might:" --- -- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customization/models#openai). +- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers/top-level/openai). - **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](/customize/model-roles). - **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/custom-providers). -- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customization/overview#slash-commands). +- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands). - **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools) Whatever you choose, you'll probably start by editing your Assistant. @@ -18,4 +18,4 @@ You can easily access your assistant configuration from the Continue Chat sideba ![configure an assistant](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png) - See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant -- See the [Config Deep Dive](/customization/overview#configuration) for more details on configuring local assistants. +- See the [Config Deep Dive](/reference) for more details on configuring local assistants. diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx index 8850e603f..e0b405dd4 100644 --- a/docs/customization/rules.mdx +++ b/docs/customization/rules.mdx @@ -15,6 +15,4 @@ By implementing rules, you transform the AI from a generic coding assistant into Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. -## Learn More - -Learn more in the [rules deep dive](/customization/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. +Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. diff --git a/docs/customize/context/documentation.mdx b/docs/customize/context/documentation.mdx index 2b36fb721..76f0218c3 100644 --- a/docs/customize/context/documentation.mdx +++ b/docs/customize/context/documentation.mdx @@ -77,7 +77,7 @@ Documentation sources may be suggested based on package files in your repo. This - Packages with partial information (with a pen icon) can be clicked to fill the form with the available information - Note that you can hover over the information icon to see where the package suggestion was found. -![Add documentation form](/img/docs-form.png) +![Add documentation form](/images/docs-form.png) ### In a configuration file @@ -212,8 +212,9 @@ If your documentation is private, you can skip the default crawler and use a loc - Chromium crawling has been deprecated - {/* The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../deep-dives/settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. */} + The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. + + **Note:** Chromium crawling support is being deprecated and may be removed in future versions. Further notes: @@ -230,11 +231,11 @@ You can view indexing statuses and manage your documentation sites from the `@do - Failed indexing attempts will show an error status bar and icon - Delete a documentation site from your configuration using the trash icon -![More Page @docs indexes section](/img/docs-indexes.png) +![More Page @docs indexes section](/images/docs-indexes.png) You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page -![Documentation indexing peek](/img/docs-indexing-peek.png) +![Documentation indexing peek](/images/docs-indexing-peek.png) You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`. @@ -400,4 +401,4 @@ The following configuration example includes: -{/* This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../deep-dives/settings.md). */} +This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../settings). diff --git a/docs/customize/model-roles/00-intro.mdx b/docs/customize/model-roles/00-intro.mdx index 9bc936da9..5ae734269 100644 --- a/docs/customize/model-roles/00-intro.mdx +++ b/docs/customize/model-roles/00-intro.mdx @@ -21,7 +21,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. -![Settings Active Models Section](/img/settings-model-roles.png) +![Settings Active Models Section](/images/settings-model-roles.png) `roles` are not explicitly defined within `config.json` (deprecated) - they diff --git a/docs/docs.json b/docs/docs.json index ec993cdb7..04fc66d35 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -988,6 +988,14 @@ { "source": "/agent/context-selection", "destination": "/features/agent/context-selection" + }, + { + "source": "/customization/overview#codebase-context", + "destination": "/customize/context/codebase" + }, + { + "source": "/customization/overview#documentation-context", + "destination": "/customize/context/documentation" } ] } diff --git a/docs/features/agent/how-to-customize.mdx b/docs/features/agent/how-to-customize.mdx index a912292d2..7e5fd634b 100644 --- a/docs/features/agent/how-to-customize.mdx +++ b/docs/features/agent/how-to-customize.mdx @@ -2,6 +2,21 @@ Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details. +## Customize System Messages + +You can customize the system messages for Chat, Agent, and Plan modes using model-level configuration: + +```yaml +models: + - name: GPT-4o + provider: openai + model: gpt-4o + chatOptions: + baseSystemMessage: "You are a helpful coding assistant." + baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically." + basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps." +``` + ## Add MCP Tools You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details. diff --git a/docs/features/chat/how-it-works.mdx b/docs/features/chat/how-it-works.mdx index 43f3794d3..eeb35276f 100644 --- a/docs/features/chat/how-it-works.mdx +++ b/docs/features/chat/how-it-works.mdx @@ -51,8 +51,8 @@ View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting Learn more about how context providers work: -- [Codebase Context](/customization/overview#codebase-context) -- [Documentation Context](/customization/overview#documentation-context) +- [Codebase Context](/customize/context/codebase) +- [Documentation Context](/customize/context/documentation) --- diff --git a/docs/features/chat/model-setup.mdx b/docs/features/chat/model-setup.mdx index c1ebd019a..9e0a1c213 100644 --- a/docs/features/chat/model-setup.mdx +++ b/docs/features/chat/model-setup.mdx @@ -18,6 +18,20 @@ Its strong tool calling and reasoning capabilities make it the best model for Ag These models have varying tool calling and reasoning capabilities. +[Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) from Moonshot AI + +1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) +2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) to your assistant on Continue Hub +3. Add `OPENROUTER_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) +4. Click `Reload config` in the assistant selector in the Continue IDE extension + +[Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) from Qwen + +1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys) +2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) to your assistant on Continue Hub +3. Add `OPENROUTER_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) +4. Click `Reload config` in the assistant selector in the Continue IDE extension + [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google 1. Get your API key from [Google AI Studio](https://aistudio.google.com) @@ -25,13 +39,6 @@ These models have varying tool calling and reasoning capabilities. 3. Add `GEMINI_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) 4. Click `Reload config` in the assistant selector in the Continue IDE extension -[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI - -1. Get your API key from [Together AI](https://api.together.ai) -2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub -3. Add `TOGETHER_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) -4. Click `Reload config` in the assistant selector in the Continue IDE extension - [o3](https://hub.continue.dev/openai/o3) from OpenAI 1. Get your API key from [OpenAI](https://platform.openai.com) diff --git a/docs/hub/blocks/block-types.mdx b/docs/hub/blocks/block-types.mdx index f97563d94..cd97d12ae 100644 --- a/docs/hub/blocks/block-types.mdx +++ b/docs/hub/blocks/block-types.mdx @@ -18,7 +18,7 @@ Learn more about context providers [here](/reference#context), and check out [th Docs are blocks that point to documentation sites, which will be indexed locally and then can be referenced as context using @Docs in Chat. [Explore docs](https://hub.continue.dev/explore/docs) on the hub. -Learn more in the [@Docs deep dive](/customization/overview#documentation-context), and view [`docs`](/reference#docs) in the YAML Reference for more details. +Learn more in the [@Docs context provider documentation](/customize/context/documentation), and view [`docs`](/reference#docs) in the YAML Reference for more details. ## MCP Servers diff --git a/docs/reference.mdx b/docs/reference.mdx index 670100f24..836d8e7dc 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -79,9 +79,7 @@ Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME } Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: -Block config.yaml - -```yaml +```yaml title="config.yaml" name: myprofile/custom-model models: - name: My Favorite Model @@ -91,11 +89,9 @@ models: temperature: ${{ inputs.TEMP }} ``` -Which can then be imported like +Which can then be imported like this: -Assistant config.yaml - -```yaml +```yaml title="config.yaml" name: myprofile/custom-assistant models: - uses: myprofile/custom-model @@ -110,9 +106,7 @@ Note that hub secrets can be passed as inputs, using a similar mustache format: Block properties can be also be directly overriden using `override`. For example: -Assistant config.yaml - -```yaml +```yaml title="config.yaml" name: myprofile/custom-assistant models: - uses: myprofile/custom-model @@ -149,9 +143,7 @@ The top-level properties in the `config.yaml` configuration file are: The `name` property specifies the name of your project or configuration. -config.yaml - -```yaml +```yaml title="config.yaml" name: MyProject ``` @@ -192,6 +184,8 @@ The `models` section defines the language models used in your configuration. Mod - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - `baseSystemMessage`: Can be used to override the default system prompt for **Chat** mode. + - `baseAgentSystemMessage`: Can be used to override the default system prompt for **Agent** mode. + - `basePlanSystemMessage`: Can be used to override the default system prompt for **Plan** mode. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: @@ -230,11 +224,9 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. -#### Example +**Example:** -config.yaml - -```yaml +```yaml title="config.yaml" models: - name: GPT-4o provider: openai @@ -279,9 +271,7 @@ More information about usage/params for each context provider can be found [here **Example:** -config.yaml - -```yaml +```yaml title="config.yaml" context: - provider: file - provider: code @@ -310,9 +300,7 @@ Explicit rules can either be simple text or an object with the following propert - `rule` (**required**): The text content of the rule - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). -config.yaml - -```yaml +```yaml title="config.yaml"l rules: - Always annotate Python functions with their parameter and return types - name: TypeScript best practices @@ -334,9 +322,7 @@ rules: A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. -config.yaml - -```yaml +```yaml title="config.yaml" prompts: - name: check description: Check for mistakes in my code @@ -360,11 +346,9 @@ List of documentation sites to index. - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). - `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. -Example +**Example:** -config.yaml - -```yaml +```yaml title="config.yaml" docs: - name: Continue startUrl: https://docs.continue.dev/intro @@ -388,9 +372,7 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a **Example:** -config.yaml - -```yaml +```yaml title="config.yaml" mcpServers: - name: My MCP Server command: uvx @@ -410,27 +392,18 @@ Destinations to which [development data](/customize/overview#development-data) w **Properties:** - `name` (**required**): The display name of the data destination - - `destination` (**required**): The destination/endpoint that will receive the data. Can be: - - an HTTP endpoint that will receive a POST request with a JSON blob - a file URL to a directory in which events will be dumpted to `.jsonl` files - - `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0` - - `events`: an array of event names to include. Defaults to all events if not specified. - - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` - - `apiKey`: api key to be sent with request (Bearer header) - - `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). - **Example:** +**Example:** -config.yaml - -```yaml +```yaml title="config.yaml" data: - name: Local Data Bank destination: file:///Users/dallin/Documents/code/continuedev/continue-extras/external-data @@ -451,9 +424,7 @@ data: Putting it all together, here's a complete example of a `config.yaml` configuration file: -config.yaml - -```yaml +```yaml title="config.yaml" name: MyProject version: 0.0.1 schema: v1 @@ -527,9 +498,7 @@ data: You can also use node anchors to avoid duplication of properties. To do so, adding the YAML version header `%YAML 1.1` is needed, here's an example of a `config.yaml` configuration file using anchors: -config.yaml - -```yaml +```yaml title="config.yaml" %YAML 1.1 --- name: MyProject diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index 45a1f05f0..ae56a541c 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -4,7 +4,7 @@
-[**Continue**](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extension and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev). +[**Continue**](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [JetBrains extension](https://plugins.jetbrains.com/plugin/22707-continue-extension) and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev).
@@ -38,6 +38,6 @@ Agent equips the Chat model with the tools needed to handle a wide range of codi ## License -[Apache 2.0 ยฉ 2023-2024 Continue Dev, Inc.](./LICENSE) +[Apache 2.0 ยฉ 2023-2025 Continue Dev, Inc.](./LICENSE) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index e52a69711..edb2a167c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -1,6 +1,6 @@ package com.github.continuedev.continueintellijextension.auth -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -90,7 +90,7 @@ class ContinueAuthService { ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) .handleUpdatedSessionInfo(sessionInfo) } catch (e: Exception) { - service().report(e, "Exception while refreshing token ${e.message}") + service().report(e, "Exception while refreshing token ${e.message}") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 02fedb3b3..1945bf546 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -6,7 +6,6 @@ class MessageTypes { "readRangeInFile", "isTelemetryEnabled", "getUniqueId", - "getWorkspaceConfigs", "getDiff", "getTerminalContents", "getWorkspaceDirs", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt index 71b367e20..4acfb461d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -1,8 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.github.continuedev.continueintellijextension.services.TelemetryService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project @@ -20,10 +18,6 @@ class CoreMessengerManager( private var backoffIntervalSeconds = 1 private val log = Logger.getInstance(CoreMessengerManager::class.java) - init { - setupAnonymousTelemetry() - } - private fun onUnexpectedExit() { coroutineScope.launch { try { @@ -32,17 +26,8 @@ class CoreMessengerManager( log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds") coreMessenger.restart() } catch (e: Exception) { - service().capture("jetbrains_core_start_error", mapOf("error" to e)) + service().capture("jetbrains_core_start_error", mapOf("error" to e)) } } } - - private fun setupAnonymousTelemetry() { - coreMessenger.request("config/getSerializedProfileInfo", null, null) { response -> - val allowAnonymousTelemetry = - response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") - if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) - service().setup(getMachineUniqueID()) - } - } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 66ea992a4..983b7cbda 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -6,7 +6,7 @@ import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -196,11 +196,6 @@ class IdeProtocolClient( respond(tags) } - "getWorkspaceConfigs" -> { - val configs = ide.getWorkspaceConfigs() - respond(configs) - } - "getTerminalContents" -> { val contents = ide.getTerminalContents() respond(contents) @@ -478,7 +473,7 @@ class IdeProtocolClient( } } catch (exception: Exception) { val exceptionMessage = "Error handling message of type $messageType: $exception" - service().report(exception, exceptionMessage) + service().report(exception, exceptionMessage) ide.showToast(ToastType.ERROR, exceptionMessage) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 8bdb7f964..d377cb3b1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -4,7 +4,7 @@ import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.ContinueConstants import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.* @@ -28,7 +28,6 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile @@ -180,29 +179,6 @@ class IntelliJIDE( return workspaceDirectories().toList() } - override suspend fun getWorkspaceConfigs(): List { - val workspaceDirs = this.getWorkspaceDirs() - - val configs = mutableListOf() - - for (workspaceDir in workspaceDirs) { - val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir) - if (dir != null) { - val contents = dir.children.mapNotNull { it.toUriOrNull() } - - // Find any .continuerc.json files - for (file in contents) { - if (file.endsWith(".continuerc.json")) { - val fileContent = UriUtils.uriToFile(file).readText() - configs.add(fileContent) - } - } - } - } - - return configs as List - } - override suspend fun fileExists(filepath: String): Boolean = fileUtils.fileExists(filepath) @@ -397,7 +373,7 @@ class IntelliJIDE( return results.split("\n") } catch (exception: Exception) { val message = "Error executing ripgrep: ${exception.message}" - service().report(exception, message) + service().report(exception, message) showToast(ToastType.ERROR, message) return emptyList() } @@ -439,7 +415,7 @@ class IntelliJIDE( return ExecUtil.execAndGetOutput(command).stdout } catch (exception: Exception) { val message = "Error executing ripgrep: ${exception.message}" - service().report(exception, message) + service().report(exception, message) showToast(ToastType.ERROR, message) return "Error: Unable to execute ripgrep command." } @@ -646,6 +622,14 @@ class IntelliJIDE( throw NotImplementedError("getSignatureHelp not implemented yet") } + override suspend fun getReferences(location: Location): List { + throw NotImplementedError("getReferences not implemented yet") + } + + override suspend fun getDocumentSymbols(textDocumentIdentifier: String): List { + throw NotImplementedError("getDocumentSymbols not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt index 6ef0c335b..38631446e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt @@ -1,8 +1,8 @@ package com.github.continuedev.continueintellijextension.`continue`.process import com.github.continuedev.continueintellijextension.proxy.ProxySettings -import com.github.continuedev.continueintellijextension.error.ContinueErrorService -import com.github.continuedev.continueintellijextension.services.TelemetryService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath import com.github.continuedev.continueintellijextension.utils.getOS @@ -53,8 +53,8 @@ class ContinueBinaryProcess( err = err.substring(doneIndex + delimiter.length) } } - service().reportMessage("Core process exited with output: $err") - service().capture("jetbrains_core_exit", mapOf("error" to err)) + service().reportMessage("Core process exited with output: $err") + service().capture("jetbrains_core_exit", mapOf("error" to err)) } private companion object { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt index 8e918b2c3..04e4d3d2e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt @@ -1,6 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue`.process -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import kotlinx.coroutines.* @@ -32,13 +32,13 @@ class ContinueProcessHandler( log.debug("Handle: $line") handleMessage(line) } catch (e: Exception) { - service().report(e, "Error handling message: $line") + service().report(e, "Error handling message: $line") } } else delay(100) } } catch (e: IOException) { - service().report(e) + service().report(e) } } scope.launch(Dispatchers.IO) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt index 3f30c17a8..69ea9b911 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -23,10 +23,11 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { try { val event = events.filterIsInstance() .firstOrNull() ?: return false - service().report( + service().report( throwable = event.data.throwable, message = additionalInfo ?: event.data.message, - attachments = event.data.allAttachments + attachments = event.data.allAttachments, + ignoreTelemetrySettings = true ) } catch (_: Exception) { consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED)) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt new file mode 100644 index 000000000..bd9b70942 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinuePostHogService.kt @@ -0,0 +1,32 @@ +package com.github.continuedev.continueintellijextension.error + +import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger +import com.posthog.java.PostHog + +@Service +class ContinuePostHogService( + private val telemetryStatus: ContinueTelemetryStatus = service(), + private val posthog: PostHog = PostHog.Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() +) { + private val log = Logger.getInstance(ContinuePostHogService::class.java) + private val distinctId: String = getMachineUniqueID() + + fun capture(eventName: String, properties: Map) { + if (!telemetryStatus.allowAnonymousTelemetry) { + log.warn("PostHog capture was ignored because telemetry is disabled") + return + } + try { + posthog.capture(distinctId, eventName, properties) + log.warn("Telemetry sent to PostHog: $eventName") + } catch (_: Exception) { + } + } + + private companion object { + private const val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt similarity index 76% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt index 35e23d8a2..6e35a18ca 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueSentryService.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.error import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId @@ -16,8 +17,10 @@ import io.sentry.protocol.Message private typealias SentryAttachment = io.sentry.Attachment @Service -class ContinueErrorService { - private val log = Logger.getInstance(ContinueErrorService::class.java) +class ContinueSentryService( + private val telemetryStatus: ContinueTelemetryStatus = service() +) { + private val log = Logger.getInstance(ContinueSentryService::class.java) init { Sentry.init { config -> @@ -35,8 +38,13 @@ class ContinueErrorService { fun report( throwable: Throwable, message: String? = null, - attachments: List? = null + attachments: List? = null, + ignoreTelemetrySettings: Boolean = false ) { + if (!ignoreTelemetrySettings && !telemetryStatus.allowAnonymousTelemetry) { + log.warn("Sentry report was ignored because telemetry is disabled") + return + } val sentryEvent = SentryEvent() sentryEvent.throwable = throwable sentryEvent.message = Message().apply { this.message = message } @@ -48,6 +56,10 @@ class ContinueErrorService { fun reportMessage( message: String, ) { + if (!telemetryStatus.allowAnonymousTelemetry) { + log.warn("Sentry message report was ignored because telemetry is disabled") + return + } Sentry.captureMessage(message) log.warn("Message sent to Sentry: $message") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt new file mode 100644 index 000000000..bbc9eb1ee --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatus.kt @@ -0,0 +1,5 @@ +package com.github.continuedev.continueintellijextension.error + +interface ContinueTelemetryStatus { + val allowAnonymousTelemetry: Boolean +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt new file mode 100644 index 000000000..192f81caf --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueTelemetryStatusService.kt @@ -0,0 +1,44 @@ +package com.github.continuedev.continueintellijextension.error + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.ProjectManager +import kotlinx.coroutines.* +import kotlin.time.Duration.Companion.seconds + +@Service +class ContinueTelemetryStatusService : ContinueTelemetryStatus { + private val scope = CoroutineScope(Dispatchers.Default) + + @Volatile + override var allowAnonymousTelemetry: Boolean = DISABLED_FALLBACK + private set + + init { + scope.launch { + while (isActive) { + poolTelemetryStatus() + delay(10.seconds) + } + } + } + + private fun poolTelemetryStatus() { + // this works, but ideally, the project should be a dependency injected via constructor + val project = ProjectManager.getInstance().openProjects.firstOrNull() + ?: return + val coreMessenger = project.service().coreMessenger + ?: return + coreMessenger.request("config/getSerializedProfileInfo", null, null) { response -> + allowAnonymousTelemetry = + response.castNestedOrNull("content", "result", "config", "allowAnonymousTelemetry") + ?: DISABLED_FALLBACK + } + } + + private companion object { + const val DISABLED_FALLBACK = false + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 057a87593..a2731dd0f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.services import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath -import com.github.continuedev.continueintellijextension.error.ContinueErrorService +import com.github.continuedev.continueintellijextension.error.ContinueSentryService import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent @@ -132,7 +132,7 @@ open class ContinueExtensionSettings : PersistentStateComponent().report(e, "Unexpected exception during remote config sync") + service().report(e, "Unexpected exception during remote config sync") } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt deleted file mode 100644 index 3b3041ff3..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.github.continuedev.continueintellijextension.services - -import com.intellij.openapi.components.Service -import com.posthog.java.PostHog -import com.posthog.java.PostHog.Builder - -@Service -class TelemetryService { - private val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" - private var posthog: PostHog? = null; - private var distinctId: String? = null; - - fun setup(distinctId: String) { - this.posthog = Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() - this.distinctId = distinctId - } - - fun capture(eventName: String, properties: Map) { - if (this.posthog == null || this.distinctId == null) { - return; - } - try { - this.posthog?.capture(this.distinctId, eventName, properties) - } catch (e: Exception) {} - } - - fun shutdown() { - this.posthog?.shutdown() - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 32c7802ad..cddcd035b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -16,11 +16,6 @@ enum class FileType(val value: Int) { SYMBOLIC_LINK(64) } -enum class ConfigMergeType { - MERGE, - OVERWRITE -} - data class Position(val line: Int, val character: Int) data class Range(val start: Position, val end: Position) @@ -126,6 +121,13 @@ data class ParameterInformation( val label: String // Note: Kotlin doesn't have union types, so this represents the string case ) +data class DocumentSymbol( + val name: String, + val kind: String, + val range: Range, + val selectionRange: Range +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -149,10 +151,6 @@ data class IdeSettings( val continueTestEnvironment: String ) -data class ContinueRcJson( - val mergeBehavior: ConfigMergeType -) - data class TerminalOptions( val reuseTerminal: Boolean?, val terminalName: String?, @@ -187,8 +185,6 @@ interface IDE { suspend fun getWorkspaceDirs(): List - suspend fun getWorkspaceConfigs(): List - suspend fun fileExists(filepath: String): Boolean suspend fun writeFile(path: String, contents: String) @@ -261,6 +257,8 @@ interface IDE { suspend fun gotoDefinition(location: Location): List suspend fun gotoTypeDefinition(location: Location): List suspend fun getSignatureHelp(location: Location): SignatureHelp? + suspend fun getReferences(location: Location): List + suspend fun getDocumentSymbols(textDocumentIdentifier: String): List // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt new file mode 100644 index 000000000..d69f610fa --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinuePostHogServiceTest.kt @@ -0,0 +1,29 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.error.ContinuePostHogService +import com.github.continuedev.continueintellijextension.error.ContinueTelemetryStatus +import com.posthog.java.PostHog +import io.mockk.mockk +import io.mockk.verify +import junit.framework.TestCase + +class ContinuePostHogServiceTest : TestCase() { + + fun `test report when telemetry is enabled`() { + val postHog = mockk(relaxed = true) + val service = ContinuePostHogService(TestTelemetryService(true), postHog) + service.capture("test", mapOf("test" to "test")) + verify { postHog.capture(any(), any(), any()) } + } + + fun `test don't report when telemetry is disabled`() { + val postHog = mockk(relaxed = true) + val service = ContinuePostHogService(TestTelemetryService(false), postHog) + service.capture("test", mapOf("test" to "test")) + verify(exactly = 0) { postHog.capture(any(), any(), any()) } + } + + private class TestTelemetryService( + override val allowAnonymousTelemetry: Boolean + ) : ContinueTelemetryStatus +} \ No newline at end of file diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index a076fdabe..f655c4df2 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -8,7 +8,7 @@
-**[Continue](https://docs.continue.dev) enables to developers create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) extension and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)** +**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code extension](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
@@ -18,7 +18,7 @@
- + @@ -30,30 +30,30 @@ [Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -![agent](../../docs/images/agent.gif) +![agent](./media/agent.gif) ## Chat [Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE -![chat](../../docs/images/chat.gif) +![chat](./media/chat.gif) ## Autocomplete [Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type -![autocomplete](../../docs/images/autocomplete.gif) +![autocomplete](./media/autocomplete.gif) ## Edit [Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file -![edit](../../docs/images/edit.gif) +![edit](./media/edit.gif) ## License -[Apache 2.0 ยฉ 2023-2024 Continue Dev, Inc.](./LICENSE) +[Apache 2.0 ยฉ 2023-2025 Continue Dev, Inc.](./LICENSE) diff --git a/extensions/vscode/e2e/actions/NextEdit.actions.ts b/extensions/vscode/e2e/actions/NextEdit.actions.ts index 0f610b680..626626843 100644 --- a/extensions/vscode/e2e/actions/NextEdit.actions.ts +++ b/extensions/vscode/e2e/actions/NextEdit.actions.ts @@ -18,7 +18,7 @@ export class NextEditActions { ); // Check if HELLO is written into the editor. - const editorText = await editor.getTextAtLine(1); + const editorText = await editor.getTextAtLine(2); return editorText === "HELLO"; } @@ -35,25 +35,35 @@ export class NextEditActions { // Check if the editor text didn't change. const editorText = await editor.getText(); - return editorText === "def main():\n "; + return editorText === "def main():\n s"; } /** * Force a Next Edit suggestion using command. */ public static async forceNextEdit(editor: TextEditor): Promise { - await editor.setText("def main():\n "); + console.log("Starting forceNextEdit..."); + await editor.setText("def main():\n s"); + console.log("Text set in editor"); await editor.moveCursor(2, 4); + console.log("Cursor moved to position 2, 4"); await new Workbench().executeCommand("Continue: Force Next Edit"); - await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL); + console.log("Executed 'Force Next Edit' command"); + + // console.log("Waiting for SVG decoration to appear..."); + // await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.MD); + // console.log("Wait completed, looking for decoration..."); + console.log("Looking for decoration..."); const svgDecoration = await TestUtils.waitForSuccess( () => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver), DEFAULT_TIMEOUT.XL, ); - return svgDecoration !== null; + const result = svgDecoration !== null; + console.log("SVG decoration search result:", result); + return result; } public static async reload(): Promise { diff --git a/extensions/vscode/e2e/constants.ts b/extensions/vscode/e2e/constants.ts index d2fb8f422..39863ca81 100644 --- a/extensions/vscode/e2e/constants.ts +++ b/extensions/vscode/e2e/constants.ts @@ -6,4 +6,5 @@ export const DEFAULT_TIMEOUT = { MD: BASELINE, XL: BASELINE * 5, XXL: BASELINE * 7, + XXLP: BASELINE * 8, }; diff --git a/extensions/vscode/e2e/selectors/NextEdit.selectors.ts b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts index 7ac1e0bb7..de5ff6e65 100644 --- a/extensions/vscode/e2e/selectors/NextEdit.selectors.ts +++ b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts @@ -1,19 +1,92 @@ import { By, WebDriver } from "vscode-extension-tester"; + export class NextEditSelectors { /** * Get the SVG decoration element if present (for next edit). */ public static async getSvgDecoration(driver: WebDriver) { - try { - const decorations = await driver.findElement( - // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") - By.css("[class*='TextEditorDecorationType']"), - ); - return decorations ?? null; - } catch (error) { - console.error("Error finding SVG decoration:", error); - return null; - } + console.log("===") + // return SelectorUtils.getElementByClassName( + // driver, + // "TextEditorDecorationType", + // ); + return Promise.any( + [ + await driver.findElement( + By.css("[class*='TextEditorDecorationType']") + ), + await driver.findElement( + By.css("[class*=TextEditorDecorationType]") + ), + await driver.findElement( + By.css("*[class*='TextEditorDecorationType']") + ), + await driver.findElement( + By.css("*[class*=TextEditorDecorationType]") + ), + await driver.findElement( + By.css("span[class*='TextEditorDecorationType']") + ), + await driver.findElement( + By.css("span[class*=TextEditorDecorationType]") + ), + await driver.findElement( + By.xpath(`//span[contains(@class, 'TextEditorDecorationType')]`) + ), + await driver.findElement( + By.xpath(`//span[contains(@class, TextEditorDecorationType)]`) + ), + await driver.findElement( + By.xpath(`//*[contains(@class, 'TextEditorDecorationType')]`) + ), + await driver.findElement( + By.xpath(`//*[contains(@class, TextEditorDecorationType)]`) + ), + ] + ) + // try { + // const decorations = await driver.findElement( + // // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") + // By.css("[class*='TextEditorDecorationType']"), + // // By.css("div[class*='TextEditorDecorationType'][style*='filter']") + // ); + + // if (!decorations) { + // throw new Error("SVG decoraton not found"); + // } + + // return decorations; + // } catch (error) { + // throw error; + // } } + + // public static async getSvgDecoration(driver: WebDriver) { + // console.log("Attempting to find SVG decoration"); + // try { + // // First check if any decoration elements exist at all + // try { + // const allDecorations = await driver.findElements(By.css("[class*='TextEditorDecorationType']")); + // console.log(`Found ${allDecorations.length} elements with TextEditorDecorationType class`); + // } catch (e) { + // console.log("No decoration elements found:", e.message); + // } + + // const decorations = await driver.findElement( + // By.css("[class*='TextEditorDecorationType']"), + // ); + + // if (!decorations) { + // console.log("SVG decoration not found (null returned)"); + // throw new Error("SVG decoration not found (null returned)"); + // } + + // console.log("SVG decoration found"); + // return decorations; + // } catch (error) { + // console.log(`Error finding SVG decoration: ${error.message}`); + // throw error; + // } + // } } diff --git a/extensions/vscode/e2e/selectors/SelectorUtils.ts b/extensions/vscode/e2e/selectors/SelectorUtils.ts index 7a7067b05..eef58e04e 100644 --- a/extensions/vscode/e2e/selectors/SelectorUtils.ts +++ b/extensions/vscode/e2e/selectors/SelectorUtils.ts @@ -1,4 +1,4 @@ -import { By, WebElement, WebView } from "vscode-extension-tester"; +import { By, WebDriver, WebElement, WebView } from "vscode-extension-tester"; export class SelectorUtils { /** @@ -26,4 +26,16 @@ export class SelectorUtils { ): Promise { return view.findWebElement(By.css(`[aria-label='${ariaLabel}']`)); } + + public static getElementByClassName( + driver: WebDriver, + className: string + ): Promise { + return driver.findElement( + // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") + By.css(`*[class*='${className}']`), + // By.xpath(`//span[contains(@class, '${className}')]`), + // By.css("div[class*='TextEditorDecorationType'][style*='filter']") + ); + } } diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 7685d52ae..6f213d0cb 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -8,6 +8,10 @@ import { DEFAULT_TIMEOUT } from "../constants"; describe("Autocomplete", () => { let editor: TextEditor; + before(async function () { + process.env.NEXT_EDIT_TEST_ENABLED = "false"; + }) + beforeEach(async function () { this.timeout(DEFAULT_TIMEOUT.XL); diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index e53f2129a..66481cb14 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -7,7 +7,7 @@ import { WebDriver, WebElement, WebView, - until, + until } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; @@ -299,8 +299,6 @@ describe("GUI Test", () => { expect(await statusMessage.getText()).contain( "Continue viewed the git diff", ); - // wait for 30 seconds, promise - await new Promise((resolve) => setTimeout(resolve, 30000)); }).timeout(DEFAULT_TIMEOUT.MD * 100); it("should call tool after approval", async () => { @@ -367,8 +365,9 @@ describe("GUI Test", () => { }).timeout(DEFAULT_TIMEOUT.MD); }); - describe("Repeat back the system message", () => { + describe("should repeat back the system message", () => { it("should repeat back the system message", async () => { + await GUIActions.selectModeFromDropdown(view, "Chat"); await GUIActions.selectModelFromDropdown(view, "SYSTEM MESSAGE MOCK LLM"); const [messageInput] = await GUISelectors.getMessageInputFields(view); await messageInput.sendKeys("Hello"); @@ -376,8 +375,8 @@ describe("GUI Test", () => { await TestUtils.waitForSuccess(() => GUISelectors.getThreadMessageByText(view, "TEST_SYS_MSG"), ); - }); - }); + }).timeout(DEFAULT_TIMEOUT.XL * 1000); + }) describe("Chat Paths", () => { it("Send many messages โ†’ chat auto scrolls โ†’ go to history โ†’ open previous chat โ†’ it is scrolled to the bottom", async () => { diff --git a/extensions/vscode/e2e/tests/NextEdit.test.ts b/extensions/vscode/e2e/tests/NextEdit.skip.ts similarity index 99% rename from extensions/vscode/e2e/tests/NextEdit.test.ts rename to extensions/vscode/e2e/tests/NextEdit.skip.ts index 754d1b3a8..3e6cf226d 100644 --- a/extensions/vscode/e2e/tests/NextEdit.test.ts +++ b/extensions/vscode/e2e/tests/NextEdit.skip.ts @@ -1,5 +1,6 @@ -import { expect } from "chai"; import * as fs from "fs/promises"; + +import { expect } from "chai"; import { EditorView, TextEditor } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/e2e/tests/SSH.test.ts b/extensions/vscode/e2e/tests/SSH.skip.ts similarity index 100% rename from extensions/vscode/e2e/tests/SSH.test.ts rename to extensions/vscode/e2e/tests/SSH.skip.ts diff --git a/extensions/vscode/media/agent.gif b/extensions/vscode/media/agent.gif new file mode 100644 index 000000000..7edf735a6 Binary files /dev/null and b/extensions/vscode/media/agent.gif differ diff --git a/extensions/vscode/media/autocomplete.gif b/extensions/vscode/media/autocomplete.gif new file mode 100644 index 000000000..cede26acf Binary files /dev/null and b/extensions/vscode/media/autocomplete.gif differ diff --git a/extensions/vscode/media/chat.gif b/extensions/vscode/media/chat.gif new file mode 100644 index 000000000..f9eedc300 Binary files /dev/null and b/extensions/vscode/media/chat.gif differ diff --git a/extensions/vscode/media/edit.gif b/extensions/vscode/media/edit.gif new file mode 100644 index 000000000..7f7cd0b15 Binary files /dev/null and b/extensions/vscode/media/edit.gif differ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3768befe3..76e958b38 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,16 +1,16 @@ { "name": "continue", - "version": "1.1.68", + "version": "1.1.71", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.68", + "version": "1.1.71", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-types": "^1.0.14", - "@continuedev/fetch": "^1.0.10", + "@continuedev/config-types": "file:../../packages/config-types", + "@continuedev/fetch": "file:../../packages/fetch", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@vscode/ripgrep": "^1.15.9", @@ -105,8 +105,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", @@ -129,6 +129,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -142,7 +143,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -207,6 +208,41 @@ "node": ">=20.19.0" } }, + "../../packages/config-types": { + "name": "@continuedev/config-types", + "version": "1.0.14", + "license": "Apache-2.0", + "dependencies": { + "zod": "^3.24.2" + }, + "devDependencies": { + "@types/node": "^20.11.19", + "typescript": "^5.5.2" + } + }, + "../../packages/fetch": { + "name": "@continuedev/fetch", + "version": "1.0.16", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "file:../config-types", + "follow-redirects": "^1.15.6", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "node-fetch": "^3.3.2" + }, + "devDependencies": { + "@types/follow-redirects": "^1.14.4", + "typescript": "^5.0.0", + "vitest": "^3.2.0" + } + }, + "../packages/config-types": { + "extraneous": true + }, + "../packages/fetch": { + "extraneous": true + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -702,25 +738,12 @@ } }, "node_modules/@continuedev/config-types": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", - "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", - "dependencies": { - "zod": "^3.23.8" - } + "resolved": "../../packages/config-types", + "link": true }, "node_modules/@continuedev/fetch": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", - "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", - "license": "Apache-2.0", - "dependencies": { - "@continuedev/config-types": "^1.0.5", - "follow-redirects": "^1.15.6", - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.5", - "node-fetch": "^3.3.2" - } + "resolved": "../../packages/fetch", + "link": true }, "node_modules/@electron/node-gyp": { "version": "10.2.0-electron.1", @@ -16741,14 +16764,6 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } - }, - "node_modules/zod": { - "version": "3.23.8", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", - "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } } } } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a3ca3a6b7..141b2effb 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.69", + "version": "1.1.71", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -350,6 +350,16 @@ "category": "Continue", "title": "Continue: Force Next Edit" }, + { + "command": "continue.acceptJump", + "category": "Continue", + "title": "Continue: Accept Jump Suggestion" + }, + { + "command": "continue.rejectJump", + "category": "Continue", + "title": "Continue: Reject Jump Suggestion" + }, { "command": "continue.generateRule", "category": "Continue", @@ -451,12 +461,22 @@ { "command": "continue.nextEditWindow.hideNextEditSuggestion", "key": "escape", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" }, { "command": "continue.nextEditWindow.acceptNextEditSuggestion", "key": "tab", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" + }, + { + "command": "continue.acceptJump", + "key": "tab", + "when": "editorTextFocus && continue.jumpDecorationVisible" + }, + { + "command": "continue.rejectJump", + "key": "escape", + "when": "editorTextFocus && continue.jumpDecorationVisible" } ], "submenus": [ @@ -717,8 +737,8 @@ "vscode-extension-tester": "^8.14.1" }, "dependencies": { - "@continuedev/config-types": "^1.0.14", - "@continuedev/fetch": "^1.0.10", + "@continuedev/config-types": "file:../../packages/config-types", + "@continuedev/fetch": "file:../../packages/fetch", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", "@vscode/ripgrep": "^1.15.9", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 599b06062..802a4eb4f 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -67,19 +67,32 @@ const isLinuxTarget = target?.startsWith("linux"); const isMacTarget = target?.startsWith("darwin"); void (async () => { - console.log("[info] Packaging extension for target ", target); + const startTime = Date.now(); + console.log( + `[info] Packaging extension for target ${target} - started at ${new Date().toISOString()}`, + ); // Make sure we have an initial timestamp file writeBuildTimestamp(); if (!skipInstalls) { + const installStart = Date.now(); + console.log(`[timer] Starting npm installs at ${new Date().toISOString()}`); await Promise.all([generateAndCopyConfigYamlSchema(), npmInstall()]); + console.log( + `[timer] npm installs completed in ${Date.now() - installStart}ms`, + ); } process.chdir(path.join(continueDir, "gui")); if (isInGitHubAction) { + const guiBuildStart = Date.now(); + console.log(`[timer] Starting GUI build at ${new Date().toISOString()}`); execCmdSync("npm run build"); + console.log( + `[timer] GUI build completed in ${Date.now() - guiBuildStart}ms`, + ); } // Copy over the dist folder to the JetBrains extension // @@ -98,6 +111,8 @@ void (async () => { rimrafSync(intellijExtensionWebviewPath); fs.mkdirSync(intellijExtensionWebviewPath, { recursive: true }); + const jetbrainsCopyStart = Date.now(); + console.log(`[timer] Starting JetBrains copy at ${new Date().toISOString()}`); await new Promise((resolve, reject) => { ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { @@ -110,6 +125,9 @@ void (async () => { resolve(); }); }); + console.log( + `[timer] JetBrains copy completed in ${Date.now() - jetbrainsCopyStart}ms`, + ); // Put back index.html if (fs.existsSync(indexHtmlPath)) { @@ -123,6 +141,8 @@ void (async () => { // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); fs.mkdirSync(vscodeGuiPath, { recursive: true }); + const vscodeCopyStart = Date.now(); + console.log(`[timer] Starting VSCode copy at ${new Date().toISOString()}`); await new Promise((resolve, reject) => { ncp("dist", vscodeGuiPath, (error) => { if (error) { @@ -137,6 +157,9 @@ void (async () => { } }); }); + console.log( + `[timer] VSCode copy completed in ${Date.now() - vscodeCopyStart}ms`, + ); if (!fs.existsSync(path.join("dist", "assets", "index.js"))) { throw new Error("gui build did not produce index.js"); @@ -151,6 +174,10 @@ void (async () => { fs.mkdirSync("bin", { recursive: true }); // onnxruntime-node + const onnxCopyStart = Date.now(); + console.log( + `[timer] Starting onnxruntime copy at ${new Date().toISOString()}`, + ); await new Promise((resolve, reject) => { ncp( path.join(__dirname, "../../../core/node_modules/onnxruntime-node/bin"), @@ -167,6 +194,9 @@ void (async () => { }, ); }); + console.log( + `[timer] onnxruntime copy completed in ${Date.now() - onnxCopyStart}ms`, + ); if (target) { // If building for production, only need the binaries for current platform try { @@ -433,5 +463,8 @@ void (async () => { `out/node_modules/esbuild/lib/main.js`, ]); + console.log( + `[timer] Prepackage completed in ${Date.now() - startTime}ms - finished at ${new Date().toISOString()}`, + ); process.exit(0); })(); diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index a8ce254ad..bc1f8c2da 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import { executeGotoProvider, executeSignatureHelpProvider, + executeSymbolProvider, } from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; @@ -17,7 +18,7 @@ import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; import type { - ContinueRcJson, + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -113,6 +114,28 @@ class VsCodeIde implements IDE { return result; } + async getReferences(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeReferenceProvider", + }); + + return result; + } + + async getDocumentSymbols( + textDocumentIdentifier: string, // uri + ): Promise { + const result = await executeSymbolProvider({ + uri: vscode.Uri.parse(textDocumentIdentifier), + name: "vscode.executeDocumentSymbolProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { @@ -266,32 +289,6 @@ class VsCodeIde implements IDE { return await this.ideUtils.getAvailableThreads(); } - async getWorkspaceConfigs() { - const workspaceDirs = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; - const configs: ContinueRcJson[] = []; - for (const workspaceDir of workspaceDirs) { - const files = await this.ideUtils.readDirectory(workspaceDir); - if (files === null) { - //Unlikely, but just in case... - continue; - } - for (const [filename, type] of files) { - if ( - (type === vscode.FileType.File || - type === vscode.FileType.SymbolicLink) && - filename === ".continuerc.json" - ) { - const contents = await this.readFile( - vscode.Uri.joinPath(workspaceDir, filename).toString(), - ); - configs.push(JSON.parse(contents)); - } - } - } - return configs; - } - async getWorkspaceDirs(): Promise { return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString()); } diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts new file mode 100644 index 000000000..48797f007 --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -0,0 +1,338 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import * as vscode from "vscode"; + +export interface CompletionDataForAfterJump { + completionId: string; + outcome: NextEditOutcome; + currentPosition: vscode.Position; +} + +export class JumpManager { + private static _instance: JumpManager | undefined; + + // Decoration state. + private _jumpDecoration: vscode.TextEditorDecorationType | undefined; + private _jumpDecorationVisible = false; + private _disposables: vscode.Disposable[] = []; + + private _jumpInProgress: boolean = false; + private _jumpAccepted: boolean = false; + private _completionAfterJump: CompletionDataForAfterJump | null = null; + private _oldCursorPosition: vscode.Position | undefined; + + private constructor() {} + + initialize() {} + + public static getInstance(): JumpManager { + if (!JumpManager._instance) { + JumpManager._instance = new JumpManager(); + } + return JumpManager._instance; + } + + public static clearInstance() { + if (JumpManager._instance) { + JumpManager._instance.dispose(); + JumpManager._instance = undefined; + } + } + + public dispose() { + // Dispose current decoration. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + } + + public async suggestJump( + currentPosition: vscode.Position, + nextJumpLocation: vscode.Position, + completionContent?: string, + ): Promise { + // Deduplication logic. + // If the content at the next jump location is + // identical to the completion content, + // then we don't have to jump. + if (completionContent !== undefined) { + const editor = vscode.window.activeTextEditor; + + if (editor) { + try { + const completionLines = completionContent.split("\n"); + + // Get document content at jump location spanning multiple lines. + const document = editor.document; + const startLine = nextJumpLocation.line; + const endLine = Math.min( + startLine + completionLines.length - 1, + document.lineCount - 1, + ); + + // Check if we have enough lines in the document to compare. + if (endLine - startLine + 1 < completionLines.length) { + // Not enough lines in document, so content can't be identical. + // Proceed to jump! + } else { + // Check the first line first for early exit. + const firstLineText = document.lineAt(startLine).text; + const firstLineSubstring = firstLineText.substring( + nextJumpLocation.character, + ); + const firstCompletionLine = completionLines[0]; + + if (!firstLineSubstring.startsWith(firstCompletionLine)) { + // First line doesn't match, so proceed to jump. + } else { + // Check remaining lines if there are any. + if (completionLines.length > 1) { + let fullMatch = true; + + // Process remaining lines. + for (let i = 1; i < completionLines.length; i++) { + const documentLine = startLine + i; + if (documentLine <= endLine) { + const lineText = document.lineAt(documentLine).text; + if (lineText !== completionLines[i]) { + fullMatch = false; + break; + } + } + } + + if (fullMatch) { + console.log( + "Skipping jump as content is identical at jump location", + ); + return false; // Exit early, don't suggest jump. + } + } else { + // Only one line and it matches. + console.log( + "Skipping jump as content is identical at jump location", + ); + return false; // Exit early, don't suggest jump. + } + } + } + } catch (error) { + console.error("Error checking content at jump location:", error); + // Continue with jump even if there's an error checking content. + } + } + } + + console.log("this._jumpInProgress"); + this._jumpInProgress = true; + this._oldCursorPosition = currentPosition; + + const editor = vscode.window.activeTextEditor; + if (!editor) { + console.log("No active editor, cannot suggest jump"); + this._jumpInProgress = false; + return false; + } + + const visibleRanges = editor.visibleRanges; + if (visibleRanges.length === 0) { + console.log("No visible ranges in editor, cannot suggest jump"); + this._jumpInProgress = false; + return false; + } + + const visibleRange = visibleRanges[0]; + const topLineNumber = visibleRange.start.line; + const bottomLineNumber = visibleRange.end.line; + + const decorationLine = nextJumpLocation.line; + + // Check if jump location is outside the visible range. + if (decorationLine < topLineNumber) { + await this.renderTabToJumpDecoration( + editor, + topLineNumber, + nextJumpLocation, + ); + } else if (decorationLine > bottomLineNumber) { + await this.renderTabToJumpDecoration( + editor, + bottomLineNumber, + nextJumpLocation, + ); + } else { + // No suggestion is made when the decoration is within visibleRange. + await this.renderTabToJumpDecoration( + editor, + decorationLine, + nextJumpLocation, + ); + } + + // Scroll to show the jump location. + editor.revealRange( + new vscode.Range(decorationLine, 0, decorationLine, 0), + vscode.TextEditorRevealType.InCenter, + ); + + // Set up a way to detect when the jump is complete. + const disposable = vscode.window.onDidChangeTextEditorSelection(() => { + console.log("_jumpInProgress is false"); + this._jumpInProgress = false; + disposable.dispose(); + + // If there's a completion waiting to be shown after the jump, + // execute the command to show it. + if (this._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + this._completionAfterJump, + ); + this._completionAfterJump = null; + } + }); + + // Clean up after timeout if no jump has been made. + setTimeout(() => { + this._jumpInProgress = false; + disposable.dispose(); + }, 10000); + + return true; + } + + private async renderTabToJumpDecoration( + editor: vscode.TextEditor, + lineToRenderOn: number, + jumpPosition: vscode.Position, + ) { + // Clean up any existing decoration beforehand. + await this.clearJumpDecoration(); + + // Create a decoration for jump. + this._jumpDecoration = vscode.window.createTextEditorDecorationType({ + before: { + contentText: "๐Ÿฆ˜ Press Tab to jump, Esc to cancel", + color: new vscode.ThemeColor("editorInfo.foreground"), + backgroundColor: new vscode.ThemeColor("editorInfo.background"), + margin: `0 0 0 4px`, + }, + }); + + // Apply the decoration. + const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length; + editor.setDecorations(this._jumpDecoration, [ + new vscode.Range( + lineToRenderOn, + lastIndexOfLine, + lineToRenderOn, + lastIndexOfLine, + ), + ]); + + // Set the context key to enable tab/esc shortcuts. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + this._jumpDecorationVisible = true; + + // Register the key listeners. + await this.registerKeyListeners(editor, jumpPosition); + } + + private async clearJumpDecoration() { + if (this._jumpDecoration) { + this._jumpDecoration.dispose(); + this._jumpDecoration = undefined; + } + + // Dispose any active listeners. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + + // Reset the context. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + this._jumpDecorationVisible = false; + } + + private async registerKeyListeners( + editor: vscode.TextEditor, + jumpPosition: vscode.Position, + ) { + const acceptJumpCommand = vscode.commands.registerCommand( + "continue.acceptJump", + async () => { + if (this._jumpDecorationVisible) { + this._jumpAccepted = true; + + // Move cursor to the jump position. + editor.selection = new vscode.Selection(jumpPosition, jumpPosition); + await this.clearJumpDecoration(); + + this._jumpAccepted = false; + } + }, + ); + + const rejectJumpCommand = vscode.commands.registerCommand( + "continue.rejectJump", + async () => { + if (this._jumpDecorationVisible) { + console.log( + "deleteChain from JumpManager.ts: rejectJump and decoration visible", + ); + NextEditProvider.getInstance().deleteChain(); + await this.clearJumpDecoration(); + } + }, + ); + + // Add a selection change listener to the editor to reject jump when cursor moves. + const selectionChangeListener = + vscode.window.onDidChangeTextEditorSelection((e) => { + // If jump decoration isn't visible, nothing to do. + if (!this._jumpDecorationVisible) { + return; + } + + const currentPosition = e.selections[0].active; + + // If cursor moved to jump position, this is likely the result of acceptJump. + if (currentPosition.isEqual(jumpPosition)) { + return; + } + + // If cursor position changed for any other reason, reject the jump. + if ( + this._oldCursorPosition && + !currentPosition.isEqual(this._oldCursorPosition) + ) { + vscode.commands.executeCommand("continue.rejectJump"); + } + }); + + // This allows us to dispose the command after a jump is completed. + this._disposables.push( + acceptJumpCommand, + rejectJumpCommand, + selectionChangeListener, + ); + } + + isJumpInProgress(): boolean { + return this._jumpInProgress; + } + + wasJumpJustAccepted(): boolean { + return this._jumpAccepted; + } + + setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { + this._completionAfterJump = completionData; + } +} diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts new file mode 100644 index 000000000..3a74f479b --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -0,0 +1,458 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { CompletionDataForAfterJump, JumpManager } from "./JumpManager"; + +// Mock VSCode API +vi.mock("vscode", () => { + return { + window: { + createTextEditorDecorationType: vi.fn(() => ({ + dispose: vi.fn(), + })), + activeTextEditor: { + document: { + lineAt: vi.fn((line) => ({ + text: "Test line content", + lineNumber: line, + })), + lineCount: 10, + }, + setDecorations: vi.fn(), + selection: { active: { line: 0, character: 0 } }, + revealRange: vi.fn(), + visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }], + }, + onDidChangeTextEditorSelection: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + commands: { + executeCommand: vi.fn(), + registerCommand: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + Position: class { + line: number; + character: number; + constructor(line: number, character: number) { + this.line = line; + this.character = character; + } + isEqual(other: any): boolean { + return this.line === other.line && this.character === other.character; + } + }, + Range: class { + start: any; + end: any; + constructor( + startLine: number, + startChar: number, + endLine: number, + endChar: number, + ) { + this.start = { line: startLine, character: startChar }; + this.end = { line: endLine, character: endChar }; + } + }, + Selection: class { + anchor: any; + active: any; + constructor(anchor: any, active: any) { + this.anchor = anchor; + this.active = active; + } + }, + TextEditorDecorationType: class { + dispose: () => void; + constructor() { + this.dispose = vi.fn(); + } + }, + TextEditorRevealType: { + InCenter: "inCenter", + }, + ThemeColor: class { + id: string; + constructor(id: string) { + this.id = id; + } + }, + }; +}); + +// Mock NextEditProvider +vi.mock("core/nextEdit/NextEditProvider", () => { + const mockDeleteChain = vi.fn(); + const mockGetInstance = vi.fn(() => ({ + deleteChain: mockDeleteChain, + })); + + return { + NextEditProvider: { + getInstance: mockGetInstance, + }, + }; +}); + +const createMockNextEditOutcome = ( + overrides: Partial = {}, +): NextEditOutcome => { + return { + // TabAutocompleteOptions properties + disable: false, + maxPromptTokens: 2048, + debounceDelay: 300, + modelTimeout: 5000, + maxSuffixPercentage: 0.5, + prefixPercentage: 0.8, + transform: true, + template: "default", + multilineCompletions: "auto", + slidingWindowPrefixPercentage: 0.5, + slidingWindowSize: 100, + useCache: true, + onlyMyCode: false, + useRecentlyEdited: true, + useRecentlyOpened: true, + disableInFiles: [".env", "node_modules/**"], + useImports: true, + showWhateverWeHaveAtXMs: 2000, + experimental_includeClipboard: true, + experimental_includeRecentlyVisitedRanges: true, + experimental_includeRecentlyEditedRanges: true, + experimental_includeDiff: true, + experimental_enableStaticContextualization: false, + // Base properties + elapsed: 1500, + modelProvider: "openai", + modelName: "gpt-4", + completionOptions: { + temperature: 0.7, + max_tokens: 1000, + }, + completionId: "comp_12345abcde", + uniqueId: "ne_67890fghij", + timestamp: Date.now(), + gitRepo: "continuedev/continue", + + // NextEdit specific properties + fileUri: "file:///workspace/project/src/main.ts", + workspaceDirUri: "file:///workspace/project", + prompt: "Add error handling to this function", + userEdits: "// I added a try/catch block", + userExcerpts: "function example() { ... }", + originalEditableRange: "function example() {\n return fetch(url);\n}", + completion: + "function example() {\n try {\n return fetch(url);\n } catch (error) {\n console.error('Fetch failed:', error);\n throw error;\n }\n}", + cursorPosition: { line: 2, character: 10 }, + finalCursorPosition: { line: 4, character: 5 }, + accepted: true, + editableRegionStartLine: 1, + editableRegionEndLine: 3, + + // Apply any overrides + ...overrides, + }; +}; + +describe("JumpManager", () => { + let jumpManager: JumpManager; + + beforeEach(() => { + // Reset mocks + vi.resetAllMocks(); + + // Clear any existing instance + JumpManager.clearInstance(); + + // Get a fresh instance + jumpManager = JumpManager.getInstance(); + }); + + afterEach(() => { + jumpManager.dispose(); + }); + + describe("getInstance", () => { + it("should return the same instance on multiple calls", () => { + const instance1 = JumpManager.getInstance(); + const instance2 = JumpManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("clearInstance", () => { + it("should dispose the current instance and clear it", () => { + const instance = JumpManager.getInstance(); + const disposeSpy = vi.spyOn(instance, "dispose"); + + JumpManager.clearInstance(); + + expect(disposeSpy).toHaveBeenCalled(); + + // Get a new instance + const newInstance = JumpManager.getInstance(); + expect(newInstance).not.toBe(instance); + }); + }); + + describe("suggestJump", () => { + it("should set jumpInProgress to true", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + expect(jumpManager.isJumpInProgress()).toBe(true); + }); + + it("should not suggest jump if completion content matches document content", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + const completionContent = "Test line content"; + + // Mock document content to match the completion content + vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({ + text: "Test line content", + lineNumber: 3, + })) as any; + + await jumpManager.suggestJump( + currentPosition, + nextJumpLocation, + completionContent, + ); + + // Jump should not be suggested, so decorations should not be created + expect( + vscode.window.createTextEditorDecorationType, + ).not.toHaveBeenCalled(); + }); + + it("should render decoration for jump location outside visible range (below)", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range (below) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + // Should set context + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + // Should register key listeners + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.acceptJump", + expect.any(Function), + ); + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.rejectJump", + expect.any(Function), + ); + }); + + it("should render decoration for jump location outside visible range (above)", async () => { + // Set visible range to be below the jump target + // @ts-ignore + vscode.window.activeTextEditor!.visibleRanges = [ + { start: { line: 5 }, end: { line: 10 } }, + ]; + + const currentPosition = new vscode.Position(6, 0); + const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + }); + }); + + describe("registerKeyListeners", () => { + it("should register acceptJump command that moves cursor", async () => { + // Setup private method access (this is a bit of a hack for testing private methods) + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Create editor mock + const editor = { + selection: null, + setSelection: vi.fn(), + }; + + // Create jump position + const jumpPosition = new vscode.Position(3, 5); + + // Call the private method + await privateJumpManager.registerKeyListeners(editor, jumpPosition); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.acceptJump", + ); + const acceptJumpHandler = commandArgs[1]; + + // Call the handler + await acceptJumpHandler(); + + // Expect selection to be updated + expect(editor.selection).toEqual( + new vscode.Selection(jumpPosition, jumpPosition), + ); + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + + it("should register rejectJump command that deletes the chain", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Get a reference to the mocked deleteChain + const mockDeleteChain = vi.mocked( + NextEditProvider.getInstance().deleteChain, + ); + mockDeleteChain.mockClear(); + + // Call the private method + await privateJumpManager.registerKeyListeners( + {} as vscode.TextEditor, + new vscode.Position(0, 0), + ); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.rejectJump", + ); + expect(commandArgs).toBeDefined(); + const rejectJumpHandler = commandArgs?.[1]; + expect(rejectJumpHandler).toBeDefined(); + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the handler + await rejectJumpHandler(); + + // Debug: Log state after calling handler + console.log("mockDeleteChain called:", mockDeleteChain.mock.calls.length); + + // Expect NextEditProvider.deleteChain to be called + expect(mockDeleteChain).toHaveBeenCalled(); + + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); + + describe("setCompletionAfterJump", () => { + it("should store completion data", () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was stored correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + }); + + it("should process completion data when jump is completed", async () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was set correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + + // Reset executeCommand mock to clear previous calls + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Directly simulate what happens when a jump is completed + // by manipulating the internal state + (jumpManager as any)._jumpInProgress = false; + + // Now directly call the method that would show the completion + // We need to manually implement what the callback would do + if ((jumpManager as any)._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + (jumpManager as any)._completionAfterJump, + ); + (jumpManager as any)._completionAfterJump = null; + } + + // Verify that the command was called with the completion data + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "continue.showNextEditAfterJump", + completionData, + ); + + // Verify that _completionAfterJump was reset to null + expect((jumpManager as any)._completionAfterJump).toBeNull(); + }); + }); + + describe("clearJumpDecoration", () => { + it("should dispose decoration and reset state", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Create a mock decoration with a spy on dispose + const mockDispose = vi.fn(); + privateJumpManager._jumpDecoration = { + dispose: mockDispose, + }; + privateJumpManager._jumpDecorationVisible = true; + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the method + await privateJumpManager.clearJumpDecoration(); + + // Expect dispose to have been called + expect(mockDispose).toHaveBeenCalled(); + + // Expect decoration to be undefined after clearing + expect(privateJumpManager._jumpDecoration).toBeUndefined(); + expect(privateJumpManager._jumpDecorationVisible).toBe(false); + + // Expect context to be reset + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); +}); diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 89c3c1d57..89a43f765 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -8,6 +8,7 @@ import { CodeRenderer } from "core/codeRenderer/CodeRenderer"; import { myersCharDiff } from "core/diff/myers"; import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { getThemeString } from "../util/getTheme"; export interface TextApplier { @@ -198,10 +199,13 @@ export class NextEditWindowManager { await NextEditWindowManager.freeTabAndEsc(); // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. - this.registerCommandSafely( - HIDE_NEXT_EDIT_SUGGESTION_COMMAND, - async () => await this.hideAllNextEditWindowsAndResetCompletionId(), - ); + this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { + console.log( + "deleteChain from NextEditWindowManager.ts: hide next edit command", + ); + NextEditProvider.getInstance().deleteChain(); + await this.hideAllNextEditWindowsAndResetCompletionId(); + }); this.registerCommandSafely( ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, async () => await this.acceptNextEdit(), @@ -404,9 +408,9 @@ export class NextEditWindowManager { // Disable inline suggestions temporarily. // This prevents the race condition between vscode's inline completion provider // and the next edit window manager's cursor repositioning logic. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", false, true); + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", false, true); } if (success && this.finalCursorPos) { @@ -417,10 +421,10 @@ export class NextEditWindowManager { ); } - // Reenable inline suggestions. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", true, true); + // Reenable inline suggestions after we move the cursor. + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", true, true); // Log with accept = true. await vscode.commands.executeCommand( @@ -840,6 +844,10 @@ export class NextEditWindowManager { // If all else fails, return a reasonable default return SVG_CONFIG.fontSize * 0.6; } + + public hasAccepted() { + return this.accepted; + } } export default async function setupNextEditWindowManager( diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts new file mode 100644 index 000000000..a72c67202 --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -0,0 +1,117 @@ +import * as vscode from "vscode"; + +export interface ExpectedGhostTextAcceptance { + documentUri: string; + documentVersion: number; + text: string; + startLine: number; + startCharacter: number; + endLine: number; + endCharacter: number; +} + +/** + * This singleton tracks whether a given ghost text is accepted or not. + * We need this because there is no clean way of determining if a ghost text has been accepted outside of vscode command callback. + * The above mentioned callback is not viable because it's too slow. + * We need a way to reject model predictions on cursor movement, but cursor can move due to many reasons -- one being accepting a ghost text. + * We need to differentiate the ghost text acceptance from a deliberate cursor movement to reject the completion. + * The cursor movement event listener fires much before the vscode command callback, so the chain of edits often breaks when cursor moves due to accepting a ghost text. + * This is not what we want, as we want to keep the current chain of edits alive when the user accepts the completion. + */ +export class GhostTextAcceptanceTracker { + private static instance: GhostTextAcceptanceTracker | undefined; + private expectedAcceptance: ExpectedGhostTextAcceptance | null = null; + + private constructor() {} + + public static getInstance(): GhostTextAcceptanceTracker { + if (!GhostTextAcceptanceTracker.instance) { + GhostTextAcceptanceTracker.instance = new GhostTextAcceptanceTracker(); + } + return GhostTextAcceptanceTracker.instance; + } + + public static clearInstance() { + GhostTextAcceptanceTracker.instance = undefined; + } + + public setExpectedGhostTextAcceptance( + document: vscode.TextDocument, + text: string, + startPosition: vscode.Position, + ) { + // Calculate end position + const lines = text.split("\n"); + let endLine: number; + let endCharacter: number; + + if (lines.length > 1) { + endLine = startPosition.line + lines.length - 1; + endCharacter = lines[lines.length - 1].length; + } else { + endLine = startPosition.line; + endCharacter = startPosition.character + text.length; + } + + this.expectedAcceptance = { + documentUri: document.uri.toString(), + documentVersion: document.version, + text, + startLine: startPosition.line, + startCharacter: startPosition.character, + endLine, + endCharacter, + }; + } + + public checkGhostTextWasAccepted( + document: vscode.TextDocument, + newPosition: vscode.Position, + ): boolean { + if (!this.expectedAcceptance) return false; + + // Check document match. + if (this.expectedAcceptance.documentUri !== document.uri.toString()) { + return false; + } + + // Check document version (must be newer). + if (document.version <= this.expectedAcceptance.documentVersion) { + return false; + } + + // Check if cursor is at expected end position. + const expectedEndPos = new vscode.Position( + this.expectedAcceptance.endLine, + this.expectedAcceptance.endCharacter, + ); + + if (newPosition.isEqual(expectedEndPos)) { + // The cursor is where we'd expect after accepting the ghost text. + + // Verify text was inserted (optional additional check). + const startPos = new vscode.Position( + this.expectedAcceptance.startLine, + this.expectedAcceptance.startCharacter, + ); + const expectedText = this.expectedAcceptance.text; + + try { + const actualRange = new vscode.Range(startPos, expectedEndPos); + + const actualText = document.getText(actualRange); + + if (actualText === expectedText) { + // Clear the expectation. + this.expectedAcceptance = null; + return true; + } + } catch (error) { + // Range might be invalid, just fall through. + } + } + + return false; + } +} diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts new file mode 100644 index 000000000..18a1b80ff --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts @@ -0,0 +1,246 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; + +// Mock the vscode module +vi.mock("vscode", () => ({ + Position: vi.fn((line: number, character: number) => ({ + line, + character, + isEqual: vi.fn( + (other: any) => other.line === line && other.character === character, + ), + })), + Range: vi.fn((start: any, end: any) => ({ start, end })), +})); + +describe("GhostTextAcceptanceTracker", () => { + let tracker: GhostTextAcceptanceTracker; + let mockDocument: vscode.TextDocument; + + beforeEach(() => { + // Clear any existing instance + GhostTextAcceptanceTracker.clearInstance(); + tracker = GhostTextAcceptanceTracker.getInstance(); + + // Create mock document + mockDocument = { + uri: { + toString: () => "file:///test.ts", + }, + version: 1, + getText: vi.fn(), + } as any; + }); + + describe("getInstance", () => { + it("should return the same instance when called multiple times", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + + it("should create a new instance after clearInstance is called", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + GhostTextAcceptanceTracker.clearInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).not.toBe(instance2); + }); + }); + + describe("setExpectedGhostTextAcceptance", () => { + it("should set expected acceptance for single line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('hello')"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // Verify internal state by testing checkGhostTextWasAccepted. + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(5, 30); // 10 in startPosition + 20 characters in text + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should set expected acceptance for multi-line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "function test() {\n return 'hello';\n}"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // For multi-line, end position should be at line 7 (5 + 3 lines - 1), character 1 (length of last line). + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(7, 1); + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + }); + + describe("checkGhostTextWasAccepted", () => { + beforeEach(() => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('test')"; + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + }); + + it("should return false when no expected acceptance is set", () => { + GhostTextAcceptanceTracker.clearInstance(); + const newTracker = GhostTextAcceptanceTracker.getInstance(); + + const newDocument = { ...mockDocument, version: 2 } as any; + const position = new vscode.Position(5, 29); + + expect(newTracker.checkGhostTextWasAccepted(newDocument, position)).toBe( + false, + ); + }); + + it("should return false when document URI doesn't match", () => { + const differentDocument = { + ...mockDocument, + uri: { toString: () => "file:///different.ts" }, + version: 2, + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(differentDocument, position), + ).toBe(false); + }); + + it("should return false when document version is not newer", () => { + const sameVersionDocument = { + ...mockDocument, + version: 1, // same version + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(sameVersionDocument, position), + ).toBe(false); + + const olderVersionDocument = { + ...mockDocument, + version: 0, // older version + } as any; + + expect( + tracker.checkGhostTextWasAccepted(olderVersionDocument, position), + ).toBe(false); + }); + + it("should return false when cursor position doesn't match expected end position", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("console.log('test')"), + } as any; + const wrongPosition = new vscode.Position(5, 20); // wrong position + + expect( + tracker.checkGhostTextWasAccepted(newDocument, wrongPosition), + ).toBe(false); + }); + + it("should return false when text content doesn't match", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("different text"), // wrong text + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should return true when all conditions match and clear expectation", () => { + const expectedText = "console.log('test')"; + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(expectedText), + } as any; + const correctPosition = new vscode.Position(5, 29); // 10 + 19 characters + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(true); + + // Check for clearing logic. + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should handle getText throwing an error gracefully", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockImplementation(() => { + throw new Error("Range invalid"); + }), + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should work with multi-line ghost text acceptance", () => { + const startPosition = new vscode.Position(0, 0); + const multiLineText = "if (condition) {\n doSomething();\n}"; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + multiLineText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(multiLineText), + } as any; + const endPosition = new vscode.Position(2, 1); // line 2, character 1 (length of "}") + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should handle empty text", () => { + const startPosition = new vscode.Position(10, 5); + const emptyText = ""; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + emptyText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(""), + } as any; + const samePosition = new vscode.Position(10, 5); // should be same as start for empty text + + expect(tracker.checkGhostTextWasAccepted(newDocument, samePosition)).toBe( + true, + ); + }); + }); +}); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 39b82c1a0..452df25a6 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,8 +5,6 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; -// import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -24,7 +22,9 @@ import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; +import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; @@ -66,6 +66,7 @@ export class ContinueCompletionProvider private completionProvider: CompletionProvider; private nextEditProvider: NextEditProvider; private nextEditLoggingService: NextEditLoggingService; + private jumpManager: JumpManager; public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; @@ -93,6 +94,7 @@ export class ContinueCompletionProvider } return config.selectedModelByRole.autocomplete ?? undefined; } + this.completionProvider = new CompletionProvider( this.configHandler, this.ide, @@ -112,11 +114,21 @@ export class ContinueCompletionProvider "fineTuned", ); + this.jumpManager = JumpManager.getInstance(); + this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } _lastShownCompletion: AutocompleteOutcome | NextEditOutcome | undefined; + private async getRerankModel() { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return; + } + return config.selectedModelByRole.rerank ?? undefined; + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -167,14 +179,11 @@ export class ContinueCompletionProvider token.onCancellationRequested(() => abortController.abort()); // Handle notebook cells - const pos = { + let pos = { line: position.line, character: position.character, }; - // const pos = { - // line: 0, - // character: 0, - // }; + let manuallyPassFileContents: string | undefined = undefined; if (document.uri.scheme === "vscode-notebook-cell") { const notebook = vscode.workspace.notebookDocuments.find((notebook) => @@ -220,35 +229,100 @@ export class ContinueCompletionProvider const wasManuallyTriggered = context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; - const input: AutocompleteInput = { - pos, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - injectDetails, - isUntitledFile: document.isUntitled, - completionId: uuidv4(), - filepath: document.uri.toString(), - recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - recentlyEditedRanges: - await this.recentlyEditedTracker.getRecentlyEditedRanges(), - }; + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; + const completionId = uuidv4(); + const filepath = document.uri.toString(); + const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); + let recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); - setupStatusBar(undefined, true); + console.log( + "chain exists?", + this.nextEditProvider.chainExists(), + ", length:", + this.nextEditProvider.getChainLength(), + ", next regions queue:", + this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(), + ); - // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. - const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this - .isNextEditActive - ? await this.nextEditProvider.provideInlineCompletionItems( + if (this.nextEditProvider.chainExists()) { + // The chain of edits is alive because the user has accepted the previous completion. + // Get the next editable region and set the pos to be within that range. + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } else { + // If the user has rejected, then we start a new chain of edits. + this.nextEditProvider.startChain(); + + const input: AutocompleteInput = { + pos, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + injectDetails, + isUntitledFile: document.isUntitled, + completionId, + filepath, + recentlyVisitedRanges, + recentlyEditedRanges, + }; + + setupStatusBar(undefined, true); + + // Check if editChainId exists or needs to be refreshed. + if (this.isNextEditActive) { + outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - ) - : await this.completionProvider.provideInlineCompletionItems( + { withChain: false }, + ); + + if (!outcome || !outcome.completion) { + // Hitting this condition means that the model could not predict a next edit action. + // That happens when the user's recent edit is good enough, or if the model is totally lost. + // At this point we assume that the user typed something good enough to maintain a chain of edits. + // All we need to do here is to calculate next editable region. + // We also need to use the user's edits to create a user edits section in renderPrompt. + recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); + + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } + } else { + // Handle autocomplete request. + outcome = await this.completionProvider.provideInlineCompletionItems( input, signal, wasManuallyTriggered, ); + } + } + // If the model cannot predict a completion or a next edit, + // then it's safe to assume that there are no more changes to be made. if (!outcome || !outcome.completion) { return null; } @@ -279,16 +353,16 @@ export class ContinueCompletionProvider return null; } - // Marking the outcome as displayed saves - // the current outcome as a value of the key completionId. + // Marking the outcome as displayed saves the current outcome + // as a value of the key completionId. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( - input.completionId, + completionId, outcome as NextEditOutcome, ); } else { this.completionProvider.markDisplayed( - input.completionId, + completionId, outcome as AutocompleteOutcome, ); } @@ -296,13 +370,9 @@ export class ContinueCompletionProvider // Construct the range/text to show const startPos = selectedCompletionInfo?.range.start ?? position; - // const startPos = new vscode.Position(0, 0); - // const endPos = new vscode.Position(0, 5); let range = new vscode.Range(startPos, startPos); - // let range = new vscode.Range(startPos, endPos); let completionText = outcome.completion; - // NOTE: This seems like an autocomplete logic. const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; if (isSingleLineCompletion) { @@ -339,16 +409,65 @@ export class ContinueCompletionProvider { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", - arguments: [input.completionId, this.completionProvider], + arguments: [completionId, this.completionProvider], }, ); (autocompleteCompletionItem as any).completeBracketPairs = true; + const editor = vscode.window.activeTextEditor; + if (!editor) { + return undefined; + } + + const currCursorPos = editor.selection.active; + if (this.isNextEditActive) { - const editor = vscode.window.activeTextEditor; - if (!editor) { - return undefined; + if (!this.nextEditProvider.isStartOfChain()) { + // Try suggesting jumps for each location in the queue. + let jumpSuccessful = false; + + while ( + this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength() > + 0 && + !jumpSuccessful + ) { + const nextRegion = + this.nextEditProvider.shiftNextEditableRegionsInTheCurrentChain(); + if (!nextRegion) continue; + + const jumpPosition = new vscode.Position( + nextRegion.range.start.line, + nextRegion.range.start.character, + ); + + // Try to suggest a jump to this location. + jumpSuccessful = await this.jumpManager.suggestJump( + currCursorPos, + jumpPosition, + outcome.completion, + ); + + if (jumpSuccessful) { + // Store completion to be rendered after jump. + this.jumpManager.setCompletionAfterJump({ + completionId: completionId, + outcome: outcome as NextEditOutcome, + currentPosition: jumpPosition, + }); + + return undefined; // Don't show anything yet! + } + } + + // If no jump was successful after trying multiple locations, + // proceed with other completion display logic or return undefined. + if (!jumpSuccessful) { + console.log( + "No suitable jump location found after trying multiple positions", + ); + return undefined; + } } // Check the diff between old and new editable region. @@ -356,14 +475,11 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits is empty. if (newEditRangeSlice === "") { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } // Get the contents of the old (current) editable region. - const currCursorPos = editor.selection.active; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, @@ -380,19 +496,42 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits are identical to the previous version. if (oldEditRangeSlice === newEditRangeSlice) { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } + // Create a cursor position relative to the edit range slice. + const relativeCursorPos = { + line: currCursorPos.line - editableRegionStartLine, + character: currCursorPos.character, + }; + // If the diff is a FIM, render a ghost text. const { isFim, fimText } = checkFim( oldEditRangeSlice, newEditRangeSlice, - currCursorPos, + relativeCursorPos, ); + if (isFim) { + if (!fimText) { + console.log("deleteChain from completionProvider.ts: !fimText"); + this.nextEditProvider.deleteChain(); + return undefined; + } + + // Track this ghost text for acceptance detection. + // Ghost text acceptance can *technically* be acted upon in + // the command handler for "continue.logNextEditOutcomeAccept", + // but there is a substantial delay between accepting and logging, + // which introduces a lot of race conditions with different event handlers. + // Plus, separating these concerns seems to make sense logically as well. + GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance( + document, + fimText, + new vscode.Position(currCursorPos.line, currCursorPos.character), + ); + const nextEditCompletionItem = new vscode.InlineCompletionItem( fimText, new vscode.Range( @@ -402,7 +541,7 @@ export class ContinueCompletionProvider { title: "Log Next Edit Outcome", command: "continue.logNextEditOutcomeAccept", - arguments: [input.completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. + arguments: [completionId, this.nextEditLoggingService], }, ); return [nextEditCompletionItem]; @@ -410,10 +549,16 @@ export class ContinueCompletionProvider // Else, render a next edit window. const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log( + "deleteChain from completionProvider.ts: diffLines.length === 0", + ); + NextEditProvider.getInstance().deleteChain(); + } if (NextEditWindowManager.isInstantiated()) { NextEditWindowManager.getInstance().updateCurrentCompletionId( - input.completionId, + completionId, ); await NextEditWindowManager.getInstance().showNextEditWindow( diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index c3d5c11a4..32e8b03f5 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -14,6 +14,7 @@ import * as URI from "uri-js"; import * as vscode from "vscode"; import type { + DocumentSymbol, IDE, Range, RangeInFile, @@ -434,3 +435,90 @@ export async function executeSignatureHelpProvider( return null; } } + +type SymbolProviderName = "vscode.executeDocumentSymbolProvider"; + +interface SymbolInput { + uri: vscode.Uri; + name: SymbolProviderName; +} + +function symbolInputKey(input: SymbolInput) { + return `${input.name}${input.uri.toString()}`; +} + +const MAX_SYMBOL_CACHE_SIZE = 100; +const symbolCache = new Map(); + +export async function executeSymbolProvider( + input: SymbolInput, +): Promise { + const cacheKey = symbolInputKey(input); + const cached = symbolCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const symbols = (await vscode.commands.executeCommand( + input.name, + input.uri, + // )) as vscode.DocumentSymbol[] | vscode.SymbolInformation[]; + )) as vscode.DocumentSymbol[]; + + const results: DocumentSymbol[] = []; + + // Handle both possible return types from the symbol provider + if (symbols.length > 0) { + // if ("location" in symbols[0]) { + // // SymbolInformation type + // results.push( + // ...symbols.map((s: vscode.SymbolInformation) => ({ + // filepath: s.location.uri.toString(), + // range: s.location.range, + // })), + // ); + // } else { + // DocumentSymbol type - collect symbols recursively + function collectSymbols( + symbols: vscode.DocumentSymbol[], + uri: vscode.Uri, + ): DocumentSymbol[] { + const result: DocumentSymbol[] = []; + for (const symbol of symbols) { + result.push({ + name: symbol.name, + range: symbol.range, + selectionRange: symbol.selectionRange, + kind: symbol.kind, + }); + + if (symbol.children && symbol.children.length > 0) { + result.push(...collectSymbols(symbol.children, uri)); + } + } + return result; + } + + results.push( + ...collectSymbols(symbols as vscode.DocumentSymbol[], input.uri), + ); + // } + } + + // Add to cache + if (symbolCache.size >= MAX_SYMBOL_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = symbolCache.keys().next().value; + if (oldestKey) { + symbolCache.delete(oldestKey); + } + } + symbolCache.set(cacheKey, results); + + return results; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return []; + } +} diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 9fa48cd98..fc4eab517 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -67,6 +67,7 @@ export class RecentlyEditedTracker { lines: contents.split("\n"), symbols: getSymbolsForSnippet(contents), }; + this.recentlyEditedRanges[i] = range; return; } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3b247f88b..2ffd24418 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -17,7 +17,16 @@ import * as YAML from "yaml"; import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; +import { myersDiff } from "core/diff/myers"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "core/nextEdit/constants"; +import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { CompletionDataForAfterJump } from "./activation/JumpManager"; +import { NextEditWindowManager } from "./activation/NextEditWindowManager"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -805,6 +814,125 @@ const getCommandsMap: ( "editor.action.inlineSuggest.trigger", ); }, + "continue.showNextEditAfterJump": async ( + data: CompletionDataForAfterJump, + ) => { + // NOTE: This could use some cleanup or abstraction. + // The logic is largely similar to that of completionProvider.ts + // but we don't have access to the class. + + const { completionId, outcome, currentPosition } = data; + + const editor = vscode.window.activeTextEditor; + if (!editor) { + console.log("No active editor when trying to show next edit"); + return; + } + + const documentContent = editor.document.getText(); + + // Calculate the editable region boundaries around the current cursor position/ + const editableRegionStartLine = Math.max( + currentPosition.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + currentPosition.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + editor.document.lineCount - 1, + ); + + // Get the current text in the editable region. + const oldEditRangeSlice = documentContent + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // Get the suggested new text from the completion outcome. + const newEditRangeSlice = outcome.completion; + + // Skip showing edit if the suggestion is empty. + if (newEditRangeSlice === "") { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Skip showing edit if the suggestion is identical to current text. + if (oldEditRangeSlice === newEditRangeSlice) { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Create a cursor position relative to the edit range slice + const relativeCursorPos = { + line: currentPosition.line - editableRegionStartLine, + character: currentPosition.character, + }; + const { isFim, fimText } = checkFim( + oldEditRangeSlice, + newEditRangeSlice, + relativeCursorPos, + ); + + if (isFim) { + if (!fimText) { + console.log("deleteChain from commands.ts: !fimText"); + await NextEditProvider.getInstance().deleteChain(); + } + // For FIM edits, create an inline completion item. + const nextEditCompletionItem = new vscode.InlineCompletionItem( + fimText, + new vscode.Range( + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + ), + { + title: "Log Next Edit Outcome", + command: "continue.logNextEditOutcomeAccept", + arguments: [completionId, NextEditLoggingService.getInstance()], + }, + ); + + // Show the ghost text using VS Code's inline completion API. + // We need to trigger this manually since we're not in the completion provider. + await vscode.commands.executeCommand( + "editor.action.inlineSuggest.trigger", + { + completions: [nextEditCompletionItem], + position: currentPosition, + }, + ); + } else { + // For more complex edits, we display a diff inside a window. + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log("deleteChain from commands.ts: diffLines.length === 0"); + await NextEditProvider.getInstance().deleteChain(); + } + + if (NextEditWindowManager.isInstantiated()) { + const windowManager = NextEditWindowManager.getInstance(); + windowManager.updateCurrentCompletionId(completionId); + + await windowManager.showNextEditWindow( + editor, + currentPosition, + editableRegionStartLine, + editableRegionEndLine, + oldEditRangeSlice, + newEditRangeSlice, + diffLines, + ); + } + } + }, }; }; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f0137bd0c..d5b0766ae 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -42,9 +42,20 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { getAst } from "core/autocomplete/util/ast"; +import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCalculator"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { isModelCapableOfNextEdit } from "core/nextEdit/utils"; +import { localPathOrUriToPath } from "core/util/pathToUri"; +import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "../autocomplete/lsp"; import { handleTextDocumentChange } from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -68,6 +79,18 @@ export class VsCodeExtension { private fileSearch: FileSearch; private uriHandler = new UriEventHandler(); private completionProvider: ContinueCompletionProvider; + // Track whether the user is currently typing + private isTypingSession = false; + private typingTimer: NodeJS.Timeout | null = null; + private lastDocumentChangeTime = 0; + + // Reset typing session after a delay + resetTypingSession = () => { + if (this.typingTimer) clearTimeout(this.typingTimer); + this.typingTimer = setTimeout(() => { + this.isTypingSession = false; + }, 2000); // Typing session considered over after 2 seconds of inactivity + }; constructor(context: vscode.ExtensionContext) { // Register auth provider @@ -165,16 +188,25 @@ export class VsCodeExtension { this.configHandler.onConfigUpdate( async ({ config: newConfig, configLoadInterrupted }) => { - if (newConfig?.experimental?.optInNextEditFeature) { + const autocompleteModel = newConfig?.selectedModelByRole.autocomplete; + if ( + autocompleteModel && + isModelCapableOfNextEdit(autocompleteModel.model) + ) { // Set up next edit window manager only for Continue team members await setupNextEditWindowManager(context); - this.activateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.getInstance(); + GhostTextAcceptanceTracker.getInstance(); } else { NextEditWindowManager.clearInstance(); this.deactivateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.clearInstance(); + GhostTextAcceptanceTracker.clearInstance(); } if (configLoadInterrupted) { @@ -311,6 +343,12 @@ export class VsCodeExtension { }); vscode.workspace.onDidChangeTextDocument(async (event) => { + if (event.contentChanges.length > 0) { + this.isTypingSession = true; + this.lastDocumentChangeTime = Date.now(); + this.resetTypingSession(); + } + const editInfo = await handleTextDocumentChange( event, this.configHandler, @@ -346,6 +384,18 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidOpenTextDocument(async (event) => { + console.log("onDidOpenTextDocument"); + const ast = await getAst(event.fileName, event.getText()); + if (ast) { + DocumentHistoryTracker.getInstance().addDocument( + localPathOrUriToPath(event.fileName), + event.getText(), + ast, + ); + } + }); + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); @@ -373,6 +423,71 @@ export class VsCodeExtension { } }); + // Listen for editor changes to clean up decorations when editor closes. + vscode.window.onDidChangeVisibleTextEditors(async () => { + // If our active editor is no longer visible, clear decorations. + console.log("deleteChain called from onDidChangeVisibleTextEditors"); + await NextEditProvider.getInstance().deleteChain(); + }); + + // Listen for selection changes to hide tooltip when cursor moves. + vscode.window.onDidChangeTextEditorSelection(async (e) => { + // Don't delete the chain of edits if: + + // 1. A next edit window was just accepted. + if ( + NextEditWindowManager.isInstantiated() && + NextEditWindowManager.getInstance().hasAccepted() + ) { + return; + } + + // 2. A jump is in progress. + if ( + JumpManager.getInstance().isJumpInProgress() || + JumpManager.getInstance().wasJumpJustAccepted() + ) { + return; + } + + // 3. A ghost text was just accepted. + // Check if this selection change matches our expected ghost text acceptance. + const wasGhostTextAccepted = + GhostTextAcceptanceTracker.getInstance().checkGhostTextWasAccepted( + e.textEditor.document, + e.selections[0].active, + ); + + if (wasGhostTextAccepted) { + // Ghost text was accepted - don't delete the chain. + return; + } + + // 4. The selection change is part of a typing session + // Check if this selection change is close enough to a document change to be considered typing. + const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime; + const ARBITRARY_TYPING_DELAY = 500; + if ( + this.isTypingSession && + timeSinceLastDocChange < ARBITRARY_TYPING_DELAY + ) { + // This selection change is likely due to typing, don't delete the chain. + return; + } + + // Otherwise, delete the chain (for rejection or unrelated movement). + console.log("deleteChain called from onDidChangeTextEditorSelection"); + await NextEditProvider.getInstance().deleteChain(); + + NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: e.selections[0].anchor, + filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + ide: this.ide, + })) ?? [], + ); + }); + // Refresh index when branch is changed void this.ide.getWorkspaceDirs().then((dirs) => dirs.forEach(async (dir) => { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 430c4fff1..2ecd1c205 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -390,6 +390,14 @@ export class VsCodeMessenger { return await ide.gotoDefinition(msg.data.location); }); + this.onWebviewOrCore("getReferences", async (msg) => { + return await ide.getReferences(msg.data.location); + }); + + this.onWebviewOrCore("getDocumentSymbols", async (msg) => { + return await ide.getDocumentSymbols(msg.data.textDocumentIdentifier); + }); + this.onWebviewOrCore("getFileStats", async (msg) => { return await ide.getFileStats(msg.data.files); }); @@ -418,10 +426,6 @@ export class VsCodeMessenger { return await ide.isTelemetryEnabled(); }); - this.onWebviewOrCore("getWorkspaceConfigs", async (msg) => { - return await ide.getWorkspaceConfigs(); - }); - this.onWebviewOrCore("getUniqueId", async (msg) => { return await ide.getUniqueId(); }); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts index dd46ad401..58b167e66 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts @@ -15,20 +15,34 @@ export class DownloadYamlExtensionCodeLensProvider if (!document.uri.fsPath.includes(".continue")) { return []; } - if (this.yamlExtensionDownloaded()) { - return []; - } - const codeLens: vscode.CodeLens = { + const codeLenses: vscode.CodeLens[] = []; + + // Always show documentation link + const docCodeLens: vscode.CodeLens = { range: new vscode.Range(0, 0, 0, 0), command: { - title: "Download YAML extension for Intellisense", - command: "workbench.extensions.installExtension", - arguments: ["redhat.vscode-yaml"], + title: "๐Ÿ“– View Continue Reference", + command: "vscode.open", + arguments: [vscode.Uri.parse("https://docs.continue.dev/reference")], }, isResolved: true, }; + codeLenses.push(docCodeLens); - return [codeLens]; + if (!this.yamlExtensionDownloaded()) { + const codeLens: vscode.CodeLens = { + range: new vscode.Range(0, 0, 0, 0), + command: { + title: "Download YAML extension for Intellisense", + command: "workbench.extensions.installExtension", + arguments: ["redhat.vscode-yaml"], + }, + isResolved: true, + }; + codeLenses.push(codeLens); + } + + return codeLenses; } } diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 6f213b302..d8593f7d0 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -111,6 +111,7 @@ export class VsCodeIdeUtils { /** * Read the entire contents of a file from the given URI. + * If there are unsaved changes in an open editor, returns those instead of the file on disk. * * @param uri - The URI of the file to read. * @param ignoreMissingProviders - Optional flag to ignore missing file system providers for unsupported schemes. @@ -124,6 +125,18 @@ export class VsCodeIdeUtils { uri: vscode.Uri, ignoreMissingProviders: boolean = true, ): Promise { + // First check if there's an open document with this URI that might have unsaved changes. + const openDocuments = vscode.workspace.textDocuments; + for (const document of openDocuments) { + if (document.uri.toString() === uri.toString()) { + // Found an open document with this URI. + // Return its current content (including any unsaved changes) as Uint8Array. + const docText = document.getText(); + return Buffer.from(docText, "utf8"); + } + } + + // If no open document found or if it's not dirty, fall back to reading from disk. return await this.fsOperation( uri, async (u) => { diff --git a/gui/package-lock.json b/gui/package-lock.json index d611543e2..ce7be87e5 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -116,8 +116,8 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.14", - "@continuedev/llm-info": "^1.0.8", + "@continuedev/fetch": "file:../packages/fetch", + "@continuedev/llm-info": "file:../packages/llm-info", "@continuedev/openai-adapters": "file:../packages/openai-adapters", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", @@ -140,6 +140,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -153,7 +154,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -223,7 +224,7 @@ "version": "1.0.96", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-types": "^1.0.14", + "@continuedev/config-types": "file:../config-types", "yaml": "^2.6.1", "zod": "^3.24.2" }, diff --git a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx deleted file mode 100644 index 98e8adbc5..000000000 --- a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ArrowRightEndOnRectangleIcon, - UserCircleIcon as UserCircleIconOutline, -} from "@heroicons/react/24/outline"; -import { isOnPremSession } from "core/control-plane/AuthTypes"; -import { useAuth } from "../../context/Auth"; -import { ListboxOption, useFontSize } from "../ui"; - -interface AccountOptionProps { - onClose: () => void; -} - -export function AccountOption({ onClose }: AccountOptionProps) { - const { session, logout, login } = useAuth(); - const tinyFont = useFontSize(-4); - - // No account option for on-prem deployments - if (session && isOnPremSession(session)) { - return null; - } - - async function handleClick() { - if (session) { - logout(); - } else { - await login(false); - } - onClose(); - } - - return ( - -
- {session ? ( - - ) : ( - - )} - {session ? "Log out" : "Sign in"} -
-
- ); -} diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx index 23c54184d..89ac2a81b 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -20,14 +20,20 @@ export function AssistantOptions({
- {profiles?.map((profile, idx) => ( - - ))} + {profiles?.length === 0 ? ( +
+ No assistants found +
+ ) : ( + profiles?.map((profile, idx) => ( + + )) + )}
); diff --git a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx index bb0a301e1..86ba08916 100644 --- a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx +++ b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx @@ -9,7 +9,7 @@ import { ListboxButton } from "../ui"; import { AssistantIcon } from "./AssistantIcon"; interface SelectedAssistantButtonProps { - selectedProfile: ProfileDescription; + selectedProfile: ProfileDescription | null; } export function SelectedAssistantButton({ @@ -25,7 +25,9 @@ export function SelectedAssistantButton({ style={{ fontSize: fontSize(-3) }} >
- {configLoading ? ( + {selectedProfile === null ? ( + "Create your first assistant" + ) : configLoading ? ( { let lastToggleTime = 0; const DEBOUNCE_MS = 800; @@ -98,49 +103,32 @@ export function AssistantAndOrgListbox() { }; }, [currentOrg, selectedProfile]); - if (!selectedProfile) { - return ( -
{ - void ideMessenger.request("controlPlane/openUrl", { - path: "/new?type=assistant", - orgSlug: currentOrg?.slug, - }); - }} - className="text-description flex cursor-pointer select-none items-center gap-1" - style={{ fontSize: smallFont }} - > - - - Create your first assistant - -
- ); - } - return (
- {shouldRenderOrgInfo && ( -
-
+
+
+ {session && session?.AUTH_TYPE !== AuthType.OnPrem && ( - {session.account.id} + {session?.account.id} - - -
+ )} + {shouldRenderOrgInfo && ( + <> + + + + )}
- )} +
+ @@ -176,11 +164,25 @@ export function AssistantAndOrgListbox() { configLoading && "animate-spin-slow", )} /> - Reload config + Reload assistants - + {session && ( + +
+ Log out +
+
+ )}
{ + const [showStagingIndicator, setShowStagingIndicator] = useState(false); const navigate = useNavigate(); const location = useLocation(); const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); const ideMessenger = useContext(IdeMessengerContext); - const currentSessionId = useAppSelector((state) => state.session.id); const { mainEditor } = useMainEditor(); const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); @@ -55,6 +55,17 @@ const Layout = () => { const showDialog = useAppSelector((state) => state.ui.showDialog); const isInEdit = useAppSelector((store) => store.session.isInEdit); + useEffect(() => { + (async () => { + const response = await ideMessenger.request( + "controlPlane/getEnvironment", + undefined, + ); + response.status === "success" && + setShowStagingIndicator(response.content.AUTH_TYPE.includes("staging")); + })(); + }, []); + useWebviewListener( "newSession", async () => { @@ -236,6 +247,15 @@ const Layout = () => { + {showStagingIndicator && ( + + )}
{ message={dialogMessage} /> - + diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index b7bc81c2e..07de26fe7 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,12 +1,18 @@ import { CheckIcon, ChevronDownIcon, + ExclamationTriangleIcon, InformationCircleIcon, } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { + isRecommendedAgentModel, + modelSupportsNativeTools, +} from "core/llm/toolSupport"; +import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectUseSystemMessageTools } from "../../redux/selectors/selectUseSystemMessageTools"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; @@ -19,9 +25,22 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); - const agentModeSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + const useSystemTools = useAppSelector(selectUseSystemMessageTools); + + const isAgentSupported = useMemo(() => { + if (!selectedModel) { + return undefined; + } + return !!useSystemTools || modelSupportsNativeTools(selectedModel); + }, [selectedModel, useSystemTools]); + + const isGoodAtAgentMode = useMemo(() => { + if (!selectedModel) { + return undefined; + } + return isRecommendedAgentModel(selectedModel.model); }, [selectedModel]); + const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); @@ -32,10 +51,10 @@ export function ModeSelect() { if (!selectedModel) { return; } - if (mode !== "chat" && !agentModeSupported) { + if (mode !== "chat" && !isAgentSupported) { dispatch(setMode("chat")); } - }, [mode, agentModeSupported, dispatch, selectedModel]); + }, [mode, isAgentSupported, selectedModel]); const cycleMode = useCallback(() => { if (mode === "chat") { @@ -76,6 +95,25 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); + const notSupported = (Not supported); + const notGreatAtAgent = ( + <> + + + {`${capitalize(mode)} might not work well with this model.`} + + + ); + return (
@@ -117,11 +155,7 @@ export function ModeSelect() {
{mode === "chat" && } - +
Plan @@ -138,19 +172,19 @@ export function ModeSelect() { Read-only/MCP tools available
- {agentModeSupported ? ( - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + ) : ( - (Not supported) + notSupported )}
- + +
Agent @@ -167,12 +201,15 @@ export function ModeSelect() { All tools available
- {agentModeSupported ? ( - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + ) : ( - (Not supported) + notSupported )}
diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index d9eae491c..40abbea5f 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -31,6 +31,9 @@ export function OnboardingCardLanding({ // A new assistant is created when the account is created // We want to switch to this immediately void dispatch(selectFirstHubProfile()); + + ideMessenger.post("showTutorial", undefined); + ideMessenger.post("showToast", ["info", "๐ŸŽ‰ Welcome to Continue!"]); } }); } diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 068432792..0dc09a438 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,7 +5,7 @@ import { TrashIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { renderChatMessage } from "core/util/messageContent"; import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -41,7 +41,7 @@ export default function ResponseActions({ ); const isPruned = useAppSelector((state) => state.session.isPruned); const ruleGenerationSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + return selectedModel && modelSupportsNativeTools(selectedModel); }, [selectedModel]); const percent = Math.round((contextPercentage ?? 0) * 100); diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index 6a8744b59..1214b9e24 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -23,7 +23,7 @@ export function ApplyActions(props: ApplyActionsProps) { case "streaming": return (
- + Applying diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 0e2aaa52a..5911f537a 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -5,7 +5,7 @@ import { } from "@heroicons/react/24/outline"; import { LightBulbIcon as LightBulbIconSolid } from "@heroicons/react/24/solid"; import { InputModifiers } from "core"; -import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsImages } from "core/llm/autodetect"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -57,8 +57,6 @@ function InputToolbar(props: InputToolbarProps) { const isEnterDisabled = props.disabled || (isInEdit && codeToEdit.length === 0); - const toolsSupported = defaultModel && modelSupportsTools(defaultModel); - const supportsImages = defaultModel && modelSupportsImages( @@ -75,7 +73,7 @@ function InputToolbar(props: InputToolbarProps) { <>
} {!props.toolbarOptions?.hideUseCodebase && !isInEdit && (