diff --git a/.github/workflows/README.md b/.github/workflows/README.md index f22d06955..ff1b7bd22 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -7,7 +7,7 @@ When merging to `preview`: - the VS Code extension along with Rust extension is built and uploaded as an artifact - all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases. - the version is bumped and this change is commited to preview -- in the future, the Intellij extension will be built and uploaded to the marketplace here +- in the future, the JetBrains extension will be built and uploaded to the marketplace here ## main @@ -16,4 +16,4 @@ When merging to `main`: - the VS Code extension along with Rust extension is built and uploaded as an artifact - all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases. - the version is bumped and this change is commited to main -- in the future, the Intellij extension will be built and uploaded to the marketplace here +- in the future, the JetBrains extension will be built and uploaded to the marketplace here diff --git a/.github/workflows/jetbrains-build.yaml b/.github/workflows/jetbrains-build.yaml deleted file mode 100644 index 16d07163c..000000000 --- a/.github/workflows/jetbrains-build.yaml +++ /dev/null @@ -1,476 +0,0 @@ -# GitHub Actions Workflow is created for testing and preparing the plugin release in the following steps: -# - Validate Gradle Wrapper. -# - Run 'test' and 'verifyPlugin' tasks. -# - Run Qodana inspections. -# - Run the 'buildPlugin' task and prepare artifact for further tests. -# - Run the 'runPluginVerifier' task. -# - Create a draft release. -# -# The workflow is triggered on push and pull_request events. -# -# GitHub Actions reference: https://help.github.com/en/actions -# -## JBIJPPTPL - -name: Build -# on: -# # Trigger the workflow on pushes to only the 'main' branch (this avoids duplicate checks being run e.g., for dependabot pull requests) -# push: -# branches: [main, preview] -# Trigger the workflow on any pull request -# pull_request: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -defaults: - run: - working-directory: ./extensions/intellij - -jobs: - # Prepare environment and build the plugin - build: - name: Build - runs-on: macos-latest - outputs: - version: ${{ steps.properties.outputs.version }} - changelog: ${{ steps.properties.outputs.changelog }} - pluginVerifierHomeDir: ${{ steps.properties.outputs.pluginVerifierHomeDir }} - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Validate wrapper - - name: Gradle Wrapper Validation - uses: gradle/actions/wrapper-validation@v3 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Set environment variables - - name: Export Properties - id: properties - shell: bash - run: | - PROPERTIES="$(./gradlew properties --console=plain -q)" - VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" - # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" - CHANGELOG="" - - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT - - echo "changelog<> $GITHUB_OUTPUT - echo "$CHANGELOG" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT - - ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier - - # Setup Node.js - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - # Cache node_modules - - 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 binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/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') }} - - # npm install core - - name: Install core node_modules - run: | - cd ../../core - npm ci - - # npm install binary - - name: Install core node_modules - run: | - cd ../../binary - npm ci - - # npm install gui - - name: Install gui node_modules - run: | - cd ../../gui - npm ci - - # build gui - - name: Build gui - run: | - cd ../../gui - npm run build - - # Run prepackage.js script - - 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 }} - - # Build binaries - - name: Build the binaries - run: | - cd ../../binary - npm run build - - # Build plugin - - name: Build plugin - run: ./gradlew buildPlugin - - # Prepare plugin archive content for creating artifact - - name: Prepare Plugin Artifact - id: artifact - shell: bash - run: | - cd ../../extensions/intellij/build/distributions - FILENAME=`ls *.zip` - unzip "$FILENAME" -d content - - echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT - - # Store already-built plugin as an artifact for downloading - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: ${{ steps.artifact.outputs.filename }} - path: ./extensions/intellij/build/distributions/content/*/* - - # Upload binaries as artifacts - - name: Upload artifact (darwin-arm64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-arm64 - path: ./binary/bin/darwin-arm64/ - - - name: Upload artifact (darwin-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-x64 - path: ./binary/bin/darwin-x64/ - - - name: Upload artifact (win32-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-win32-x64 - path: ./binary/bin/win32-x64/ - - - name: Upload artifact (linux-arm64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-linux-arm64 - path: ./binary/bin/linux-arm64/ - - - name: Upload artifact (linux-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-linux-x64 - path: ./binary/bin/linux-x64/ - - test-binaries: - needs: build - strategy: - matrix: - include: - - os: windows-latest - platform: win32 - arch: x64 - npm_config_arch: x64 - - os: ubuntu-latest - platform: linux - arch: x64 - npm_config_arch: x64 - # arm64 not actually supported by GitHub - # - os: ubuntu-latest - # platform: linux - # arch: arm64 - # npm_config_arch: arm64 - - os: macos-12 - platform: darwin - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: arm64 - npm_config_arch: arm64 - runs-on: ${{ matrix.os }} - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - 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 binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - - name: Install Core Dependencies - run: | - cd ../../core - npm ci - - - name: Install Binary Dependencies - run: | - cd ../../binary - npm ci - - # Download the binary artifact - - name: Download binary artifact - uses: actions/download-artifact@v4 - with: - name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} - path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ - - # Set execute permissions for the binary (non-Windows) - - name: Set execute permissions - run: | - cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }} - chmod +x continue-binary - chmod +x node_sqlite3.node - chmod +x index.node - chmod +x esbuild - if: ${{ matrix.platform }} != 'win32' - - - name: Copy node_sqlite3.node to necessary location - run: | - cd ../../binary - mkdir build - cp ./bin/${{ matrix.platform }}-${{ matrix.arch }}/node_sqlite3.node ./build/node_sqlite3.node - - # Run tests for binary - - name: Run binary tests - run: | - cd ../../binary - npm run test - - - name: Upload logs - if: ${{ always() }} - uses: actions/upload-artifact@v2 - with: - name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} - path: binary/.continue/logs/core.log - - # Run tests and upload a code coverage report - test: - name: Test - needs: [build] - runs-on: ubuntu-latest - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Run tests - - name: Run Tests - run: ./gradlew check - - # Collect Tests Result of failed tests - - name: Collect Tests Result - if: ${{ failure() }} - uses: actions/upload-artifact@v4 - with: - name: tests-result - path: ${{ github.workspace }}/extensions/intellij/build/reports/tests - - # Upload the Kover report to CodeCov - # - name: Upload Code Coverage Report - # uses: codecov/codecov-action@v4 - # with: - # files: ${{ github.workspace }}/build/reports/kover/report.xml - - # Run Qodana inspections and provide report - inspectCode: - if: false - name: Inspect code - needs: [build] - runs-on: ubuntu-latest - permissions: - contents: write - checks: write - pull-requests: write - steps: - # Free GitHub Actions Environment Disk Space - - name: Maximize Build Space - uses: jlumbroso/free-disk-space@main - with: - tool-cache: false - large-packages: false - - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Run Qodana inspections - - name: Qodana - Code Inspection - uses: JetBrains/qodana-action@v2024.1.5 - with: - cache-default-branch-only: true - - # Run plugin structure verification along with IntelliJ Plugin Verifier - verify: - name: Verify plugin - needs: [build] - runs-on: ubuntu-latest - steps: - # Free GitHub Actions Environment Disk Space - - name: Maximize Build Space - uses: jlumbroso/free-disk-space@main - with: - tool-cache: false - large-packages: false - - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Cache Plugin Verifier IDEs - - name: Setup Plugin Verifier IDEs Cache - uses: actions/cache@v4 - with: - path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides - key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }} - - # Run Verify Plugin task and IntelliJ Plugin Verifier tool - - name: Run Plugin Verification tasks - run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }} - - # Collect Plugin Verifier Result - - name: Collect Plugin Verifier Result - if: ${{ always() }} - uses: actions/upload-artifact@v4 - with: - name: pluginVerifier-result - path: ${{ github.workspace }}/build/reports/pluginVerifier - - # Prepare a draft release for GitHub Releases page for the manual verification - # If accepted and published, release workflow would be triggered - releaseDraft: - name: Release draft - if: github.event_name != 'pull_request' - needs: [build, test, test-binaries, verify] - runs-on: ubuntu-latest - permissions: - contents: write - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - - - name: Tag the repository - id: tag - run: | - # See https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names - TAG=v${{ needs.build.outputs.version }}-jetbrains - echo "$TAG" - echo "tag=$TAG" >> $GITHUB_OUTPUT - git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA} - git push origin $TAG - - # Remove old release drafts by using the curl request for the available releases with a draft flag - - name: Remove Old Release Drafts - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh api repos/{owner}/{repo}/releases \ - --jq '.[] | select(.draft == true) | .id' \ - | xargs -I '{}' gh api -X DELETE repos/{owner}/{repo}/releases/{} - - # Create a new release draft which is not publicly visible and requires manual acceptance - - name: Create Release Draft - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh release create "${{ steps.tag.outputs.tag }}" \ - --draft \ - --title "v${{ needs.build.outputs.version }}-jetbrains" \ - --notes "$(cat << 'EOM' - ${{ needs.build.outputs.changelog }} - EOM - )" - - # Download the Gradle build artifact - - name: Download Gradle build artifact - uses: actions/download-artifact@v4 - with: - name: ${{ needs.build.outputs.filename }} - path: ./artifacts diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 3df1ae29f..e4400f20b 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -2,14 +2,19 @@ # Running the publishPlugin task requires all following secrets to be provided: PUBLISH_TOKEN, PRIVATE_KEY, PRIVATE_KEY_PASSWORD, CERTIFICATE_CHAIN. # See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information. -name: Release -# on: -# release: -# types: [prereleased, released] +name: JetBrains Release + +on: + release: + types: [prereleased] defaults: run: - working-directory: ./extensions/intellij + working-directory: extensions/intellij + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: check_release_name: @@ -18,19 +23,20 @@ jobs: should_run: ${{ steps.check.outputs.should_run }} steps: - id: check + working-directory: . run: | - if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then + if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT fi # Prepare and publish the plugin to JetBrains Marketplace repository - release: + build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' - name: Publish Plugin - runs-on: ubuntu-latest + name: Build Plugin + runs-on: macos-latest permissions: contents: write pull-requests: write @@ -41,14 +47,26 @@ jobs: with: ref: ${{ github.event.release.tag_name }} - # Set up Java environment for the next steps + - name: Import Apple certificate + uses: apple-actions/import-codesign-certs@v3 + with: + keychain: ${{ github.run_id }} + keychain-password: ${{ github.run_id }} + p12-file-base64: ${{ secrets.APPLE_CERT_DATA }} + p12-password: ${{ secrets.APPLE_CERT_PASSWORD }} + + # Validate wrapper + - name: Gradle Wrapper Validation + uses: gradle/actions/wrapper-validation@v3 + + # # Set up Java environment for the next steps - name: Setup Java uses: actions/setup-java@v4 with: distribution: zulu java-version: 17 - # Setup Gradle + # # Setup Gradle - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 with: @@ -59,16 +77,21 @@ jobs: id: properties shell: bash run: | - CHANGELOG="$(cat << 'EOM' | sed -e 's/^[[:space:]]*$//g' -e '/./,$!d' - ${{ github.event.release.body }} - EOM - )" + PROPERTIES="$(./gradlew properties --console=plain -q)" + VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" + # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" + CHANGELOG="" + + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT echo "changelog<> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - # Setup Node.js + ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier + + # # Setup Node.js - name: Use Node.js from .nvmrc uses: actions/setup-node@v4 with: @@ -99,22 +122,11 @@ jobs: cd ../../core npm ci - # npm install binary - - name: Install core node_modules - run: | - cd ../../binary - npm ci - # npm install gui - - name: Install gui node_modules + - name: Install gui node_modules and build run: | cd ../../gui npm ci - - # build gui - - name: Build gui - run: | - cd ../../gui npm run build # Run prepackage.js script @@ -123,26 +135,360 @@ jobs: 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 }} + + # npm install binary + - name: Install binary node_modules + run: | + cd ../../binary + npm ci # Build binaries - - name: Install core node_modules + - name: Build the binaries run: | cd ../../binary npm run build - # Update Unreleased section with the current release note - - name: Patch Changelog - if: ${{ steps.properties.outputs.changelog != '' }} + # - name: Code sign darwin binaries + # run: | + # echo "Signing executable with keychain: ${{ github.run_id }}" + # codesign --sign - ../../binary/bin/darwin-x64/continue-binary + # codesign --sign - ../../binary/bin/darwin-arm64/continue-binary + + # - name: Sign darwin-arm64 binary + # uses: lando/code-sign-action@v2 + # with: + # file: ./binary/bin/darwin-arm64/continue-binary + # certificate-data: ${{ secrets.APPLE_CERT_DATA }} + # certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} + # apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} + # apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} + # apple-notary-tool: altool + # apple-team-id: 43XFLY66ZD + # apple-product-id: dev.continue.continue-binary + # options: --options runtime --entitlements entitlements.xml + + # Build plugin + - name: Build plugin + run: ./gradlew buildPlugin + + # Publish the plugin to JetBrains Marketplace + - name: Publish EAP Plugin env: - CHANGELOG: ${{ steps.properties.outputs.changelog }} + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: eap + run: ./gradlew publishPlugin + + - name: Publish Stable Plugin + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: default + run: ./gradlew publishPlugin + + # Prepare plugin archive content for creating artifact + - name: Prepare Plugin Artifact + id: artifact + shell: bash run: | - ./gradlew patchChangelog --release-note="$CHANGELOG" + cd ../../extensions/intellij/build/distributions + echo "Contents of distributions folder:" + ls + echo "---" + FILENAME=`ls continue-intellij-extension-*.zip` + unzip "$FILENAME" -d content + + echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT + + # Store already-built plugin as an artifact for downloading + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./extensions/intellij/build/distributions/content/*/* + + # Upload binaries as artifacts + - name: Upload artifact (darwin-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-arm64 + path: ./binary/bin/darwin-arm64/ + + - name: Upload artifact (darwin-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-x64 + path: ./binary/bin/darwin-x64/ + + - name: Upload artifact (win32-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-win32-x64 + path: ./binary/bin/win32-x64/ + + - name: Upload artifact (linux-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-linux-arm64 + path: ./binary/bin/linux-arm64/ + + - name: Upload artifact (linux-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-linux-x64 + path: ./binary/bin/linux-x64/ + + test-binaries: + needs: build + strategy: + matrix: + include: + - os: windows-latest + platform: win32 + arch: x64 + npm_config_arch: x64 + - os: ubuntu-latest + platform: linux + arch: x64 + npm_config_arch: x64 + # arm64 not actually supported by GitHub + # - os: ubuntu-latest + # platform: linux + # arch: arm64 + # npm_config_arch: arm64 + - os: macos-12 + platform: darwin + arch: x64 + npm_config_arch: x64 + - os: macos-latest + platform: darwin + arch: arm64 + npm_config_arch: arm64 + runs-on: ${{ matrix.os }} + steps: + # 1. Check-out repository + - name: Check-out repository + uses: actions/checkout@v4 + + # 2. Install npm dependencies + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - 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 binary node_modules + uses: actions/cache@v3 + with: + path: binary/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + + - name: Install Core Dependencies + run: | + cd ../../core + npm ci + + - name: Install Binary Dependencies + run: | + cd ../../binary + npm ci + + # Download the binary artifact + - name: Download binary artifact + uses: actions/download-artifact@v4 + with: + name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} + path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ + + # Set execute permissions for the binary (non-Windows) + - name: Set execute permissions + run: | + cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }} + chmod +x continue-binary + chmod +x build/Release/node_sqlite3.node + chmod +x index.node + chmod +x esbuild + if: ${{ matrix.platform }} != 'win32' + + # Run tests for binary + - name: Run binary tests + run: | + cd ../../binary + npm run test + + - name: Upload logs + if: ${{ always() }} + uses: actions/upload-artifact@v2 + with: + name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} + path: binary/.continue/logs/core.log + + # Run tests and upload a code coverage report + test: + name: Test + needs: [build] + runs-on: ubuntu-latest + steps: + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Setup Gradle + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true + + # Run tests + - name: Run Tests + run: ./gradlew check + + # Collect Tests Result of failed tests + - name: Collect Tests Result + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: tests-result + path: ${{ github.workspace }}/extensions/intellij/build/reports/tests + + # Upload the Kover report to CodeCov + # - name: Upload Code Coverage Report + # uses: codecov/codecov-action@v4 + # with: + # files: ${{ github.workspace }}/build/reports/kover/report.xml + + # Run Qodana inspections and provide report + inspectCode: + if: false + name: Inspect code + needs: [build] + runs-on: ubuntu-latest + permissions: + contents: write + checks: write + pull-requests: write + steps: + # Free GitHub Actions Environment Disk Space + - name: Maximize Build Space + uses: jlumbroso/free-disk-space@main + with: + tool-cache: false + large-packages: false + + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Run Qodana inspections + - name: Qodana - Code Inspection + uses: JetBrains/qodana-action@v2024.1.5 + with: + cache-default-branch-only: true + + # Run plugin structure verification along with IntelliJ Plugin Verifier + verify: + if: false + name: Verify plugin + needs: [build] + runs-on: ubuntu-latest + steps: + # Free GitHub Actions Environment Disk Space + - name: Maximize Build Space + uses: jlumbroso/free-disk-space@main + with: + tool-cache: false + large-packages: false + + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Setup Gradle + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true + + # Cache Plugin Verifier IDEs + - name: Setup Plugin Verifier IDEs Cache + uses: actions/cache@v4 + with: + path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides + key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }} + + # Run Verify Plugin task and IntelliJ Plugin Verifier tool + - name: Run Plugin Verification tasks + run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }} + + # Collect Plugin Verifier Result + - name: Collect Plugin Verifier Result + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: pluginVerifier-result + path: ${{ github.workspace }}/build/reports/pluginVerifier + + upload-release: + if: false + name: Upload Release + needs: + - build + - test-binaries + - test + runs-on: ubuntu-latest + steps: + # # Update Unreleased section with the current release note + # - name: Patch Changelog + # if: ${{ steps.properties.outputs.changelog != '' }} + # env: + # CHANGELOG: ${{ steps.properties.outputs.changelog }} + # run: | + # ./gradlew patchChangelog --release-note="$CHANGELOG" + + - name: Download the plugin + uses: actions/download-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./build/distributions/ # Upload artifact as a release asset - - name: Upload Release Asset - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + # - name: Upload Release Asset + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* # Publish the plugin to JetBrains Marketplace - name: Publish Plugin diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 3591d3e23..8e57aede7 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -1,14 +1,27 @@ name: Publish Extension on: - create: - tags: - - "v0.8.*-vscode" - branches: - - main + release: + types: [released] jobs: + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + working-directory: . + run: | + if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi + build: + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' strategy: matrix: include: @@ -97,10 +110,12 @@ jobs: 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: | diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index aea470286..3958730ec 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,14 +1,27 @@ name: Publish Preview Extension on: - create: - tags: - - "v0.9.*-vscode" - branches: - - dev + release: + types: [prereleased] jobs: + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + working-directory: . + run: | + if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi + build: + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' strategy: matrix: include: @@ -92,17 +105,19 @@ jobs: 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 }} + # - 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 diff --git a/.gitignore b/.gitignore index bf28524cd..3fa43ae1a 100644 --- a/.gitignore +++ b/.gitignore @@ -165,7 +165,5 @@ Icon? .continue -# Sandbox env default file -extensions/vscode/manual-testing-sandbox/example.ts .prompts/ \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 060bc5e6c..f56d10f61 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,6 +15,7 @@ }, "search.exclude": { "**/binary": true, + "binary/": false, "**/core/vendor/**": true, "**/gui/dist": true } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 918115978..2e595561f 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -162,6 +162,13 @@ "options": { "cwd": "docs" } + }, + { + "label": "clean", + "type": "shell", + "command": "node", + "args": ["${workspaceFolder}/scripts/uninstall.js"], + "problemMatcher": [] } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 010e9d1e3..268bbe613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,4 +3,4 @@ Separate changelogs are kept for each extension: - [VS Code Extension](./extensions/vscode/CHANGELOG.md) -- [Intellij Extension](./extensions/intellij/CHANGELOG.md) +- [JetBrains Extension](./extensions/intellij/CHANGELOG.md) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2192b2b8d..0a998802a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -152,7 +152,7 @@ Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](h ##### Debugging -Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. +Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The JetBrains extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. For the sake of rapid development, it is also possible to configure this communication to happen over local TCP sockets: diff --git a/binary/README.md b/binary/README.md index beff54b4b..741cc425f 100644 --- a/binary/README.md +++ b/binary/README.md @@ -30,3 +30,15 @@ The build process is otherwise defined entirely in `build.js`. ## Debugging To debug the binary with IntelliJ, set `useTcp` to `true` in `CoreMessenger.kt`, and then in VS Code run the "Core Binary" debug script. Instead of starting a subprocess for the binary and communicating over stdin/stdout, the IntelliJ extension will connect over TCP to the server started from the VS Code window. You can place breakpoints anywhere in the `core` or `binary` folders. + +## Building + +```bash +npm run build +``` + +## Testing + +```bash +npm run test +``` diff --git a/binary/build.js b/binary/build.js index d2f01ee35..016afe9bd 100644 --- a/binary/build.js +++ b/binary/build.js @@ -162,6 +162,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { "../core/vendor/tree-sitter.wasm", "../core/llm/llamaTokenizerWorkerPool.mjs", "../core/llm/llamaTokenizer.mjs", + "../core/llm/tiktokenWorkerPool.mjs", ]; for (const f of filesToCopy) { fs.copyFileSync( @@ -237,9 +238,20 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { }.tar.gz`; execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); - fs.copyFileSync( - `${targetDir}/build/Release/node_sqlite3.node`, - `${targetDir}/node_sqlite3.node`, + + // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + fs.writeFileSync( + `${targetDir}/package.json`, + JSON.stringify( + { + name: "binary", + version: "1.0.0", + author: "Continue Dev, Inc", + license: "Apache-2.0", + }, + undefined, + 2, + ), ); // Copy to build directory for testing @@ -247,7 +259,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { const [platform, arch] = target.split("-"); if (platform === currentPlatform && arch === currentArch) { fs.copyFileSync( - `${targetDir}/node_sqlite3.node`, + `${targetDir}/build/Release/node_sqlite3.node`, `build/node_sqlite3.node`, ); } @@ -257,10 +269,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } fs.unlinkSync(`${targetDir}/build.tar.gz`); - fs.rmSync(`${targetDir}/build`, { - recursive: true, - force: true, - }); // Download and unzip prebuilt esbuild binary for the target console.log(`[info] Downloading esbuild for ${target}...`); @@ -299,9 +307,18 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `${targetDir}/continue-binary${exe}`, `${targetDir}/esbuild${exe}`, `${targetDir}/index.node`, // @lancedb - `${targetDir}/node_sqlite3.node`, + "package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + `${targetDir}/build/Release/node_sqlite3.node`, ); } + + // Note that this doesn't verify they actually made it into the binary, just that they were in the expected folder before it was built + pathsToVerify.push("out/index.js"); + pathsToVerify.push("out/llamaTokenizerWorkerPool.mjs"); + pathsToVerify.push("out/tiktokenWorkerPool.mjs"); + pathsToVerify.push("out/xhr-sync-worker.js"); + pathsToVerify.push("out/tree-sitter.wasm"); + validateFilesPresent(pathsToVerify); console.log("[info] Done!"); diff --git a/binary/pkgJson/darwin-arm64/package.json b/binary/pkgJson/darwin-arm64/package.json index cc41ae801..ce6f2cace 100644 --- a/binary/pkgJson/darwin-arm64/package.json +++ b/binary/pkgJson/darwin-arm64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-macos-arm64" diff --git a/binary/pkgJson/darwin-x64/package.json b/binary/pkgJson/darwin-x64/package.json index 8ccb256e1..178ef6471 100644 --- a/binary/pkgJson/darwin-x64/package.json +++ b/binary/pkgJson/darwin-x64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-macos-x64" diff --git a/binary/pkgJson/linux-arm64/package.json b/binary/pkgJson/linux-arm64/package.json index 9fe88da50..4a3b2a42f 100644 --- a/binary/pkgJson/linux-arm64/package.json +++ b/binary/pkgJson/linux-arm64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-linux-arm64" diff --git a/binary/pkgJson/linux-x64/package.json b/binary/pkgJson/linux-x64/package.json index 1c875baa0..f62ecede7 100644 --- a/binary/pkgJson/linux-x64/package.json +++ b/binary/pkgJson/linux-x64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-linux-x64" diff --git a/binary/pkgJson/win32-arm64/package.json b/binary/pkgJson/win32-arm64/package.json index 3eeb12234..478cf7eb9 100644 --- a/binary/pkgJson/win32-arm64/package.json +++ b/binary/pkgJson/win32-arm64/package.json @@ -13,7 +13,10 @@ "../../out/tree-sitter-wasms/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", - "../../node_modules/win-ca/lib/roots.exe" + "../../node_modules/win-ca/lib/roots.exe", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-win-arm64" diff --git a/binary/pkgJson/win32-x64/package.json b/binary/pkgJson/win32-x64/package.json index 2e495524b..c466fc942 100644 --- a/binary/pkgJson/win32-x64/package.json +++ b/binary/pkgJson/win32-x64/package.json @@ -13,7 +13,10 @@ "../../out/tree-sitter-wasms/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", - "../../node_modules/win-ca/lib/roots.exe" + "../../node_modules/win-ca/lib/roots.exe", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-win-x64" diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index 66acb1448..341372d8e 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -38,7 +38,7 @@ class IPCMessengerBase< } this.send(msg.messageType, { done: true }, msg.messageId); } else { - this.send(msg.messageType, response || {}, msg.messageId); + this.send(msg.messageType, response, msg.messageId); } } catch (e: any) { console.warn(`Error running handler for "${msg.messageType}": `, e); diff --git a/binary/src/logging.ts b/binary/src/logging.ts index cba34855c..b6dbfba2c 100644 --- a/binary/src/logging.ts +++ b/binary/src/logging.ts @@ -11,5 +11,6 @@ export function setupCoreLogging() { console.log = logger; console.error = logger; console.warn = logger; + console.debug = logger; console.log("[info] Starting Continue core..."); } diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index c0e5c132a..030e0a306 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -33,8 +33,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = { "", "", "", - "<|endoftext|>", "", + "<|endoftext|>", "", "", ], @@ -134,8 +134,8 @@ const starcoder2FimTemplate: AutocompleteTemplate = { "", "", "", - "<|endoftext|>", "", + "<|endoftext|>", ], }, }; diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index dff0b065b..a95da2db1 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -51,12 +51,12 @@ class ProfileLifecycleManager { } // Clear saved config and reload - reloadConfig(): Promise { + async reloadConfig(): Promise { this.savedConfig = undefined; this.savedBrowserConfig = undefined; this.pendingConfigPromise = undefined; - return this.profileLoader.doLoadConfig(); + return await this.profileLoader.doLoadConfig(); } async loadConfig( diff --git a/core/config/load.ts b/core/config/load.ts index a9b2ba94f..2bb836d73 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -355,9 +355,11 @@ async function intermediateToFinalConfig( // These context providers are always included, regardless of what, if anything, // the user has configured in config.json + + const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {}; const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), - new CodebaseContextProvider({}), + new CodebaseContextProvider(codebaseContextParams), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 16f72d40e..2ff3f9294 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,6 +10,7 @@ import { import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js"; import { Telemetry } from "../../util/posthog.js"; +import { TTS } from "../../util/tts.js"; import { loadFullConfigNode } from "../load.js"; export default async function doLoadConfig( @@ -48,9 +49,12 @@ export default async function doLoadConfig( await Telemetry.setup( newConfig.allowAnonymousTelemetry ?? true, await ide.getUniqueId(), - ideInfo.extensionVersion, + ideInfo, ); + // TODO: pass config to pre-load non-system TTS models + await TTS.setup(); + if (newConfig.analytics) { await TeamAnalytics.setup( newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 92d558aaf..f1bfc898d 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,8 +4,8 @@ import * as YAML from "yaml"; import type { IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; -import { getBasename } from "../util/index"; import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import { getBasename } from "../util/index"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; diff --git a/core/continueServer/stubs/headers.ts b/core/continueServer/stubs/headers.ts index e6a864230..ca1e0df9d 100644 --- a/core/continueServer/stubs/headers.ts +++ b/core/continueServer/stubs/headers.ts @@ -6,7 +6,7 @@ export async function getHeaders() { key: constants.c, timestamp: getTimestamp(), v: "1", - extensionVersion: Telemetry.extensionVersion ?? "0.0.0", + extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0", os: Telemetry.os ?? "Unknown", uniqueId: Telemetry.uniqueId ?? "None", }; diff --git a/core/core.ts b/core/core.ts index 6ebbd385b..bf61042b7 100644 --- a/core/core.ts +++ b/core/core.ts @@ -26,6 +26,7 @@ import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { TTS } from "./util/tts"; import { streamDiffLines } from "./util/verticalEdit"; import DocsCrawler from "./indexing/docs/DocsCrawler"; @@ -367,6 +368,13 @@ export class Core { abortedMessageIds: Set, msg: Message, ) { + const config = await configHandler.loadConfig(); + + // Stop TTS on new StreamChat + if(config.experimental?.readResponseTTS) { + TTS.kill(); + } + const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, @@ -391,6 +399,10 @@ export class Core { next = await gen.next(); } + if(config.experimental?.readResponseTTS && "completion" in next.value) { + TTS.read(next.value?.completion); + } + return { done: true, content: next.value }; } @@ -465,6 +477,13 @@ export class Core { } }); + // Provide messenger to TTS so it can set GUI active / inactive state + TTS.messenger = this.messenger; + + on("tts/kill", async () => { + TTS.kill(); + }); + async function* runNodeJsSlashCommand( configHandler: ConfigHandler, abortedMessageIds: Set, diff --git a/core/index.d.ts b/core/index.d.ts index 1dc806f88..9730e2111 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -344,19 +344,23 @@ export interface LLMOptions { apiVersion?: string; apiType?: string; - // GCP Options + // AWS options + profile?: string; + modelArn?: string; + + // AWS and GCP Options region?: string; + + // GCP Options projectId?: string; capabilities?: ModelCapability; - // WatsonX options + // IBM watsonx options watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; } type RequireAtLeastOne = Pick< T, @@ -590,6 +594,7 @@ type ModelProvider = | "ollama" | "huggingface-tgi" | "huggingface-inference-api" + | "kindo" | "llama.cpp" | "replicate" | "text-gen-webui" @@ -598,6 +603,7 @@ type ModelProvider = | "gemini" | "mistral" | "bedrock" + | "bedrockimport" | "sagemaker" | "deepinfra" | "flowise" @@ -892,6 +898,11 @@ interface ExperimentalConfig { * function and class declarations. */ quickActions?: QuickActionConfig[]; + + /** + * Automatically read LLM chat responses aloud using system TTS models + */ + readResponseTTS?: boolean; } interface AnalyticsConfig { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 4dd56e4c2..3ef21f3d7 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -17,7 +17,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { IndexResultType, MarkCompleteCallback, - PathAndCacheKey, RefreshIndexResults, type CodebaseIndex, } from "./types.js"; @@ -184,18 +183,20 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; - const snippetToDelete = await db.get( + const snippets = await db.all( "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run("DELETE FROM code_snippets WHERE id = ?", [ - snippetToDelete.id, - ]); + if (snippets) { + const snippetIds = snippets.map((row) => row.id).join(","); - await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ - snippetToDelete.id, - ]); + await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`); + + await db.run( + `DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`, + ); + } markComplete([del], IndexResultType.Delete); } @@ -203,36 +204,61 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; + let snippets: (ChunkWithoutID & { title: string })[] = []; + try { + snippets = await this.getSnippetsInFile( + addTag.path, + await this.ide.readFile(addTag.path), + ); + } catch (e) { + // If can't parse, assume malformatted code + console.error(`Error parsing ${addTag.path}:`, e); + } - await db.run( - ` - REPLACE INTO code_snippets_tags (tag, snippetId) - SELECT ?, ( - SELECT id - FROM code_snippets - WHERE cacheKey = ? AND path = ? - ) - `, - [tagString, addTag.cacheKey, addTag.path], - ); + for (const snippet of snippets) { + const { lastID } = await db.run( + "INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + [ + addTag.path, + addTag.cacheKey, + snippet.content, + snippet.title, + snippet.startLine, + snippet.endLine, + ], + ); + await db.run( + "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", + [lastID, tagString], + ); + } markComplete([results.addTag[i]], IndexResultType.AddTag); } // Remove tag for (let i = 0; i < results.removeTag.length; i++) { - const item = results.removeTag[i]; - await db.run( - ` - DELETE FROM code_snippets_tags - WHERE tag = ? - AND snippetId IN ( - SELECT id FROM code_snippets - WHERE cacheKey = ? AND path = ? - ) - `, - [tagString, item.cacheKey, item.path], + const removeTag = results.removeTag[i]; + + const snippets = await db.get( + `SELECT id FROM code_snippets + WHERE cacheKey = ? AND path = ?`, + [removeTag.cacheKey, removeTag.path], ); + + if (snippets) { + const snippetIds = snippets.map((row: any) => row.id).join(","); + + await db.run( + ` + DELETE FROM code_snippets_tags + WHERE tag = ? + AND snippetId IN (${snippetIds}) + `, + [tagString], + ); + } + markComplete([results.removeTag[i]], IndexResultType.RemoveTag); } } diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 221035737..f05acfc16 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -3,12 +3,6 @@ import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { ContinueServerClient } from "../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; -import { getComputeDeleteAddRemove } from "./refreshIndex.js"; -import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; -import { CodebaseIndex } from "./types.js"; -import { walkDir } from "./walkDir.js"; -import { getIndexSqlitePath } from "../util/paths.js"; import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { addToTestDir, @@ -16,6 +10,12 @@ import { tearDownTestDir, TEST_DIR, } from "../test/util/testDir.js"; +import { getIndexSqlitePath } from "../util/paths.js"; +import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "./refreshIndex.js"; +import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; +import { CodebaseIndex } from "./types.js"; +import { walkDir } from "./walkDir.js"; jest.useFakeTimers(); @@ -57,7 +57,7 @@ class TestCodebaseIndexer extends CodebaseIndexer { // These are more like integration tests, whereas we should separately test // the individual CodebaseIndex classes -describe.skip("CodebaseIndexer", () => { +describe("CodebaseIndexer", () => { const pauseToken = new PauseToken(false); const continueServerClient = new ContinueServerClient(undefined, undefined); const codebaseIndexer = new TestCodebaseIndexer( @@ -71,6 +71,9 @@ describe.skip("CodebaseIndexer", () => { beforeAll(async () => { tearDownTestDir(); setUpTestDir(); + + execSync('git config --global user.email "test@example.com"'); + execSync('git config --global user.name "Test"'); }); afterAll(async () => { diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index da06bb0d9..b377d5a2f 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,7 +1,7 @@ import * as fs from "fs/promises"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; -import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; @@ -126,6 +126,12 @@ export class CodebaseIndexer { results.removeTag = []; results.addTag = []; results.del = []; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (results.compute.length === 0) { + continue; + } + for await (const _ of index.update( tag, results, @@ -371,28 +377,33 @@ export class CodebaseIndexer { results.addTag.length + results.removeTag.length; let completedOps = 0; - for (const subResult of this.batchRefreshIndexResults(results)) { - for await (const { desc } of codebaseIndex.update( - tag, - subResult, - markComplete, - repoName, - )) { - yield { - progress: progress, - desc, - status: "indexing", - }; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (totalOps > 0) { + for (const subResult of this.batchRefreshIndexResults(results)) { + for await (const { desc } of codebaseIndex.update( + tag, + subResult, + markComplete, + repoName, + )) { + yield { + progress: progress, + desc, + status: "indexing", + }; + } + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); } - completedOps += - subResult.compute.length + - subResult.del.length + - subResult.addTag.length + - subResult.removeTag.length; - progress = - (completedIndexCount + completedOps / totalOps) * - (1 / indexesToBuild.length); } + await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); completedIndexCount += 1; } diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts index eaa614aff..af59d0b3c 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -1,8 +1,8 @@ import { jest } from "@jest/globals"; import { insertMockChunks, - updateIndexAndAwaitGenerator, mockPathAndCacheKey, + updateIndexAndAwaitGenerator, } from "../test/util/indexing"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; @@ -25,7 +25,7 @@ describe("FullTextSearchCodebaseIndex", () => { index = new FullTextSearchCodebaseIndex(); }); - it("should update the index and maintain expected database state", async () => { + it.skip("should update the index and maintain expected database state", async () => { const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index a8ba2173a..0c636df6a 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -1,11 +1,11 @@ import { jest } from "@jest/globals"; import lance from "vectordb"; -import { testIde, testConfigHandler } from "../test/util/fixtures"; +import { testConfigHandler, testIde } from "../test/util/fixtures"; import { - testContinueServerClient, - mockTag, - updateIndexAndAwaitGenerator, mockPathAndCacheKey, + mockTag, + testContinueServerClient, + updateIndexAndAwaitGenerator, } from "../test/util/indexing"; import { getLanceDbPath } from "../util/paths"; import { LanceDbIndex } from "./LanceDbIndex"; @@ -48,7 +48,7 @@ describe("ChunkCodebaseIndex", () => { * - We cannot open either the 'dev' or 'main' tag tables ubtil after we * can assume they've been created through `updateIndexAndAwaitGenerator` */ - it("should update the index and maintain expected database state", async () => { + it.skip("should update the index and maintain expected database state", async () => { const mainTag = mockTag; const mainTagTableName = index.tableNameForTag(mainTag); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 69e138ddc..7c4787529 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,7 +1,7 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; -import { Table } from "vectordb"; +import lance, { Table } from "vectordb"; import { IContinueServerClient } from "../continueServer/interface.js"; import { BranchAndDir, @@ -21,7 +21,6 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; -import lance from "vectordb"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { diff --git a/core/indexing/chunk/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts index ac98d0094..7453e8a78 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.test.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -1,9 +1,5 @@ -import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; -import { DatabaseConnection, SqliteDb } from "../refreshIndex"; -import { IndexResultType } from "../types"; -import { testIde } from "../../test/util/fixtures"; -import { addToTestDir } from "../../test/util/testDir"; import { jest } from "@jest/globals"; +import { testIde } from "../../test/util/fixtures"; import { mockFileContents, mockFilename, @@ -11,6 +7,10 @@ import { testContinueServerClient, updateIndexAndAwaitGenerator, } from "../../test/util/indexing"; +import { addToTestDir } from "../../test/util/testDir"; +import { DatabaseConnection, SqliteDb } from "../refreshIndex"; +import { IndexResultType } from "../types"; +import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; jest.useFakeTimers(); @@ -41,7 +41,7 @@ describe("ChunkCodebaseIndex", () => { db = await SqliteDb.get(); }); - it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + it.skip("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 0990f5000..fcfc893e5 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -292,8 +292,8 @@ export default class DocsService { status: "indexing", }; - // Clear old index if re-indexing. - if (reIndex) { + // Delete indexed docs if re-indexing + if (reIndex && await this.has(startUrl.toString())) { console.log("Deleting old embeddings"); await this.delete(startUrl); } @@ -724,12 +724,13 @@ export default class DocsService { await this.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - this.ide.errorPopup( - "The 'transformers.js' embeddings provider currently cannot be used to index " + - "documentation in JetBrains. To enable documentation indexing, you can use " + - "any of the other providers described in the docs: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - ); + // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider + // this.ide.errorPopup( + // "The 'transformers.js' embeddings provider currently cannot be used to index " + + // "documentation in JetBrains. To enable documentation indexing, you can use " + + // "any of the other providers described in the docs: " + + // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + // ); this.globalContext.update( "curEmbeddingsProviderId", diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index c60a1a4d3..3404a22d5 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,8 +1,8 @@ import crypto from "node:crypto"; import * as fs from "node:fs"; +import plimit from "p-limit"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; -import plimit from "p-limit"; import { IndexTag, IndexingProgressUpdate } from "../index.js"; import { getIndexSqlitePath } from "../util/paths.js"; import { @@ -391,7 +391,7 @@ export async function getComputeDeleteAddRemove( lastUpdated, async (items, resultType) => { // Update tag catalog - markComplete(items, resultType); + await markComplete(items, resultType); // Update the global cache const results: any = { diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index a89c28ff0..a4c024332 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -1,8 +1,7 @@ // https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 -import { TextEncoder, TextDecoder } from "util"; -import fetch, { Request, Response } from "node-fetch"; import { jest } from "@jest/globals"; -import fs from "fs"; +import fetch, { Request, Response } from "node-fetch"; +import { TextDecoder, TextEncoder } from "util"; if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); @@ -16,16 +15,17 @@ globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; -globalThis.beforeAll(() => { - // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` - if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { - fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); - } -}); +// Trying to delete this when for some reason SQLite is still in use causes tests to fail +// globalThis.beforeAll(() => { +// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` +// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { +// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); +// } +// }); -globalThis.afterAll(() => { - // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` - if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { - fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); - } -}); +// globalThis.afterAll(() => { +// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` +// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { +// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); +// } +// }); diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index 0af5f10cb..5fd39eed6 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -1,6 +1,5 @@ -import { encodingForModel as _encodingForModel } from "js-tiktoken"; +import path from "path"; import workerpool from "workerpool"; -import * as path from "path"; export interface AsyncEncoder { encode(text: string): Promise; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 5d042e3ca..06cd4a3bb 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -24,18 +24,37 @@ class LlamaEncoding implements Encoding { } } +class NonWorkerAsyncEncoder implements AsyncEncoder { + constructor(private readonly encoding: Encoding) {} + + async close(): Promise {} + + async encode(text: string): Promise { + return this.encoding.encode(text); + } + + async decode(tokens: number[]): Promise { + return this.encoding.decode(tokens); + } +} + let gptEncoding: Encoding | null = null; const gptAsyncEncoder = new GPTAsyncEncoder(); const llamaEncoding = new LlamaEncoding(); const llamaAsyncEncoder = new LlamaAsyncEncoder(); function asyncEncoderForModel(modelName: string): AsyncEncoder { + // Temporary due to issues packaging the worker files + if (process.env.IS_BINARY) { + const encoding = encodingForModel(modelName); + return new NonWorkerAsyncEncoder(encoding); + } + const modelType = autodetectTemplateType(modelName); if (!modelType || modelType === "none") { return gptAsyncEncoder; } - // Temporary due to issues packaging the worker files - return process.env.IS_BINARY ? gptAsyncEncoder : llamaAsyncEncoder; + return llamaAsyncEncoder; } function encodingForModel(modelName: string): Encoding { diff --git a/core/llm/index.ts b/core/llm/index.ts index 73a0151e9..a6c30ed5a 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -111,15 +111,12 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; - // For WatsonX only. - + // For IBM watsonx only. watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; private _llmOptions: LLMOptions; @@ -173,13 +170,13 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + // for watsonx only this.watsonxUrl = options.watsonxUrl; - this.watsonxApiKey = options.watsonxApiKey; + this.watsonxCreds = options.watsonxCreds; this.watsonxProjectId = options.watsonxProjectId; - this.watsonxUsername = options.watsonxUsername; - this.watsonxPassword = options.watsonxPassword; this.watsonxStopToken = options.watsonxStopToken; + this.watsonxApiVersion = options.watsonxApiVersion; if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 226671c52..415ec0f10 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,19 +14,24 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { - private static PROFILE_NAME: string = "bedrock"; static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", - contextLength: 200_000, + contextLength: 200_000 }; + profile?: string | undefined; constructor(options: LLMOptions) { super(options); if (!options.apiBase) { this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } } protected async *_streamComplete( @@ -124,11 +129,11 @@ class Bedrock extends BaseLLM { private async _getCredentials() { try { return await fromIni({ - profile: Bedrock.PROFILE_NAME, + profile: this.profile, })(); } catch (e) { console.warn( - `AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`, + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); return await fromIni()(); } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts new file mode 100644 index 000000000..f53d4b15e --- /dev/null +++ b/core/llm/llms/BedrockImport.ts @@ -0,0 +1,96 @@ +import { + BedrockRuntimeClient, + InvokeModelWithResponseStreamCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class BedrockImport extends BaseLLM { + static providerName: ModelProvider = "bedrockimport"; + static defaultOptions: Partial = { + region: "us-east-1" + }; + // the BedRock imported custom model ARN + modelArn?: string | undefined; + profile?: string | undefined; + + constructor(options: LLMOptions) { + super(options); + if (!options.apiBase) { + this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + } + if (options.modelArn) { + this.modelArn = options.modelArn; + } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const input = this._generateInvokeModelCommandInput(prompt, options); + const command = new InvokeModelWithResponseStreamCommand(input); + const response = await client.send(command); + + if (response.body) { + for await (const item of response.body) { + const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes)); + if (chunk.outputs[0].text) { + yield chunk.outputs[0].text; + } + } + } + } + + private _generateInvokeModelCommandInput( + prompt: string, + options: CompletionOptions, + ): any { + const payload = { + prompt: prompt + }; + + return { + body: JSON.stringify(payload), + modelId: this.modelArn, + accept: "application/json", + contentType: "application/json" + }; + } + + private async _getCredentials() { + try { + return await + fromIni({ + profile: this.profile + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default BedrockImport; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9fc59313b..10632b90f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -2,7 +2,6 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { constants } from "../../deploy/constants.js"; import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { Telemetry } from "../../util/posthog.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -29,18 +28,19 @@ class FreeTrial extends BaseLLM { } private async _countTokens(prompt: string, model: string, isPrompt: boolean) { - if (!Telemetry.client) { - throw new Error( - "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", - ); - } - const event = isPrompt - ? "free_trial_prompt_tokens" - : "free_trial_completion_tokens"; - Telemetry.capture(event, { - tokens: this.countTokens(prompt), - model, - }); + // Removed to reduce PostHog bill + // if (!Telemetry.client) { + // throw new Error( + // "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", + // ); + // } + // const event = isPrompt + // ? "free_trial_prompt_tokens" + // : "free_trial_completion_tokens"; + // Telemetry.capture(event, { + // tokens: this.countTokens(prompt), + // model, + // }); } private _convertArgs(options: CompletionOptions): any { diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts new file mode 100644 index 000000000..855e386de --- /dev/null +++ b/core/llm/llms/Kindo.ts @@ -0,0 +1,16 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class Kindo extends OpenAI { + static providerName: ModelProvider = "kindo"; + static defaultOptions: Partial = { + apiBase: "https://llm.kindo.ai/v1", + requestOptions: { + headers: { + "kindo-token-transaction-type": "CONTINUE" + } + } + }; +} + +export default Kindo; \ No newline at end of file diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 5a18ab932..68dfef47c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -6,6 +6,7 @@ import { } from "../../index.js"; import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +import { streamResponse } from "../stream.js"; const watsonxConfig = { accessToken: { expiration: 0, @@ -19,14 +20,14 @@ class WatsonX extends BaseLLM { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { + if ( - this.watsonxUrl !== null && - this.watsonxUrl!.includes("cloud.ibm.com") + this.watsonxUrl?.includes("cloud.ibm.com") ) { // watsonx SaaS const wxToken = await ( await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxApiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", headers: { @@ -43,17 +44,16 @@ class WatsonX extends BaseLLM { } else { // watsonx Software if ( - this.watsonxZenApiKeyBase64 && - this.watsonxZenApiKeyBase64 !== "YOUR_WATSONX_ZENAPIKEY" + !this.watsonxCreds?.includes(":") ) { - // Using ZenApiKey auth - return { - token: this.watsonxZenApiKeyBase64, - expiration: -1, - }; + // Using ZenApiKey auth + return { + token: this.watsonxCreds ?? "", + expiration: -1, + }; } else { // Using username/password auth - + const userPass = this.watsonxCreds?.split(":"); const wxToken = await ( await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { method: "POST", @@ -62,8 +62,8 @@ class WatsonX extends BaseLLM { Accept: "application/json", }, body: JSON.stringify({ - username: this.watsonxUsername, - password: this.watsonxPassword, + username: userPass[0], + password: userPass[1], }), }) ).json(); @@ -185,9 +185,9 @@ class WatsonX extends BaseLLM { const stopToken = this.watsonxStopToken ?? - (options.model.includes("granite") ? "<|im_end|>" : undefined); - var streamResponse = await fetch( - `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, + (options.model?.includes("granite") ? "<|im_end|>" : undefined); + var response = await this.fetch( + `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`, { method: "POST", headers: { @@ -207,30 +207,22 @@ class WatsonX extends BaseLLM { repetition_penalty: 1, }, model_id: options.model, - project_id: this.watsonxProjectId, + project_id: this.watsonxProjectId }), }, ); - if (!streamResponse.ok || streamResponse.body === null) { + if (!response.ok || response.body === null) { throw new Error( "Something went wrong. No response received, check your connection", ); } else { - const reader = streamResponse.body.getReader(); - while (true) { - const chunk = await reader.read(); - if (chunk.done) { - break; - } - - // Decode the stream - const textResponseMsg = new TextDecoder().decode(chunk.value); - const lines = textResponseMsg.split(/\r?\n/); + for await (const value of streamResponse(response)) { + const lines = value.split("\n"); let generatedChunk = ""; let generatedTextIndex = undefined; - lines.forEach((el) => { + lines.forEach((el: string) => { // console.log(`${el}`); if (el.startsWith("id:")) { generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 56ff2dff4..84c23c9bb 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -11,6 +11,7 @@ import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; +import BedrockImport from "./BedrockImport"; import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; @@ -22,6 +23,7 @@ import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; +import Kindo from "./Kindo"; import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; @@ -49,11 +51,13 @@ const LLMs = [ Together, HuggingFaceTGI, HuggingFaceInferenceAPI, + Kindo, LlamaCpp, OpenAI, LMStudio, Mistral, Bedrock, + BedrockImport, SageMaker, DeepInfra, Flowise, diff --git a/core/package-lock.json b/core/package-lock.json index 39924969c..133599374 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -3735,6 +3735,18 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.20.tgz", + "integrity": "sha512-ffP2K4sA5mQTgePyARw1y8dPN996FmpvyAYoWO+TSItaXlhcXvc+KVa5udNMCZMDYeEnEv2Xpj6k4PwW3oBz+A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, "node_modules/@lancedb/vectordb-darwin-x64": { "version": "0.4.20", "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.20.tgz", @@ -3747,6 +3759,42 @@ "darwin" ] }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.20.tgz", + "integrity": "sha512-FpNOjOsz3nJVm6EBGyNgbOW2aFhsWZ/igeY45Z8hbZaaK2YBwrg/DASoNlUzgv6IR8cUaGJ2irNVJfsKR2cG6g==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.20.tgz", + "integrity": "sha512-pOqWjrRZQSrLTlQPkjidRii7NZDw8Xu9pN6ouVu2JAK8n81FXaPtFCyAI+Y3v9GpnYDN0rvD4eQ36aHAVPsa2g==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.20.tgz", + "integrity": "sha512-5J5SsYSJ7jRCmU/sgwVHdrGz43B/7R2T9OEoFTKyVAtqTZdu75rkytXyn9SyEayXVhlUOaw76N0ASm0hAoDS/A==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@mozilla/readability": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.5.0.tgz", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 918ba6e66..9cd4d4ec8 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -128,6 +128,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined, { model: string; promptTokens: number; generatedTokens: number }[], ]; + "tts/kill": [undefined, void]; "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dir?: string; shouldClearIndexes?: boolean }, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 2fa70bf73..5e1e74589 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -31,6 +31,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; + setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 5fe14573a..1e2499ca7 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -30,6 +30,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/cancel", "autocomplete/accept", "command/run", + "tts/kill", "llm/complete", "llm/streamComplete", "llm/streamChat", @@ -57,4 +58,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", + "setTTSActive", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 061f2819d..d3b127fdc 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -13,4 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + setTTSActive: [boolean, void]; }; diff --git a/core/test/util/history.test.ts b/core/test/util/history.test.ts new file mode 100644 index 000000000..d3dedac7f --- /dev/null +++ b/core/test/util/history.test.ts @@ -0,0 +1,131 @@ +import { PersistedSessionInfo } from "../.."; +import historyManager from "../../util/history"; +import { getSessionFilePath } from "../../util/paths"; +import { v4 as uuidv4 } from "uuid"; + +const sessionId = uuidv4(); +const testSession: PersistedSessionInfo = { + history: [], + title: `${sessionId} title`, + workspaceDirectory: "workspaceDir", + sessionId: sessionId, +}; + +describe("No sessions have been created", () => { + const testSessionId = "invalid"; + const testSessionPath = getSessionFilePath(testSessionId); + + test("Listing all sessions returns empty list", () => { + const sessions = historyManager.list({}); + expect(sessions).toEqual([]); + }); + + test("Deleting session throws error", () => { + expect(() => { + historyManager.delete(testSessionId); + }).toThrow(`Session file ${testSessionPath} does not exist`); + }); + + test("Loading session returns default session", () => { + const session = historyManager.load(testSessionId); + expect(session).toEqual({ + history: [], + title: "Failed to load session", + workspaceDirectory: "", + sessionId: testSessionId, + }); + }); +}); + +describe("Full session lifecycle", () => { + test("Creating and listing a session", () => { + // save and list + historyManager.save(testSession); + const sessions = historyManager.list({}); + const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId); + expect(sessionExists).toBe(true); + }); + + test("Loading session by ID returns correct object", () => { + const retrievedSession = historyManager.load(testSession.sessionId); + expect(retrievedSession).toEqual(testSession); + }); + + test("Saving session with new title updates session", () => { + const modifiedSession = { ...testSession }; + modifiedSession.title = `Edited: ${testSession.title}`; + historyManager.save(modifiedSession); + const session = historyManager.load(testSession.sessionId); + + expect(session.title).toBe(modifiedSession.title); + }); + + test("Deleting session", () => { + historyManager.delete(testSession.sessionId); + const sessions = historyManager.list({}); + const sessionWasDeleted = sessions.every( + (session) => session?.sessionId !== testSession.sessionId, + ); + expect(sessionWasDeleted).toEqual(true); + }); +}); + +describe("Many sessions created", () => { + test("Create 100 sessions and list all", () => { + for (let i = 0; i < 100; i++) { + historyManager.save({ + history: [], + title: `${i}`, + workspaceDirectory: "workspaceDir", + sessionId: `${i}`, + }); + } + const sessions = historyManager.list({}); + expect(sessions.length).toBe(100); + }); + + test("List 10 sessions, offest by 10", () => { + const limit = 10; + const offset = 10; + + const sessions = historyManager.list({ offset: offset, limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString()); + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List 25 sessions, with no offset", () => { + const limit = 25; + + const sessions = historyManager.list({ limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List sessions offset by 75", () => { + const offset = 75; + + const sessions = historyManager.list({ offset: offset }); + const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) => + (i + offset).toString(), + ); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("Delete all sessions", () => { + let sessions = historyManager.list({}); + + for (let session of sessions) { + historyManager.delete(session.sessionId); + } + sessions = historyManager.list({}); + expect(sessions.length).toBe(0); + }); +}); diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 3a79814d0..be62977fc 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -1,12 +1,13 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; +import { IdeInfo } from "../index.js"; export class Telemetry { // Set to undefined whenever telemetry is disabled static client: any = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; - static extensionVersion: string | undefined = undefined; + static ideInfo: IdeInfo | undefined = undefined; static async capture( event: string, @@ -19,7 +20,9 @@ export class Telemetry { properties: { ...properties, os: Telemetry.os, - extensionVersion: Telemetry.extensionVersion, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, }, }); @@ -32,14 +35,10 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async setup( - allow: boolean, - uniqueId: string, - extensionVersion: string, - ) { + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); - Telemetry.extensionVersion = extensionVersion; + Telemetry.ideInfo = ideInfo; if (!allow) { Telemetry.client = undefined; diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts index 1e5a2d1ca..a65f1f1f2 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/util/reverseMessageIde.ts @@ -124,6 +124,11 @@ export class ReverseMessageIde { return this.ide.listFolders(); }); + this.on("getControlPlaneSessionInfo", async (msg) => { + // Not supported in testing + return undefined; + }); + this.on("getContinueDir", () => { return this.ide.getContinueDir(); }); diff --git a/core/util/tts.ts b/core/util/tts.ts new file mode 100644 index 000000000..248c38518 --- /dev/null +++ b/core/util/tts.ts @@ -0,0 +1,117 @@ +import os from "node:os"; +import { exec, ChildProcess } from "child_process"; +import type { IMessenger } from "./messenger"; +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; + +// The amount of time before a process is declared +// a zombie after executing .kill() +const ttsKillTimeout: number = 5000; + +/** + * Removes code blocks from a message. + * + * Return modified message text. + */ +function removeCodeBlocks(msgText: string): string { + const codeBlockRegex = /```[\s\S]*?```/g; + + // Remove code blocks from the message text + const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); + + return textWithoutCodeBlocks.trim(); +} + +/** + * Cleans a message text to safely be used in 'exec' context on host. + * + * Return modified message text. + */ +function sanitizeMessageForTTS(message: string): string { + message = removeCodeBlocks(message); + + // Remove or replace problematic characters + message = message + .replace(/"/g, "") + .replace(/`/g, "") + .replace(/\$/g, "") + .replace(/\\/g, "") + .replace(/[&|;()<>]/g, ""); + + message = message.trim().replace(/\s+/g, " "); + + return message; +} + +export class TTS { + static os: string | undefined = undefined; + static handle: ChildProcess | undefined = undefined; + static messenger: IMessenger; + + static async read(message: string) { + message = sanitizeMessageForTTS(message); + + try { + // Kill any active TTS processes + await TTS.kill(); + } catch (e) { + console.warn("Error killing TTS process: ", e); + return; + } + + switch (TTS.os) { + case "darwin": + TTS.handle = exec(`say "${message}"`); + break; + case "win32": + // Replace single quotes on windows + TTS.handle = exec( + `powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${message.replace( + /'/g, + "''", + )}')"`, + ); + break; + case "linux": + TTS.handle = exec(`espeak "${message}"`); + break; + default: + console.log( + "Text-to-speech is not supported on this operating system.", + ); + return; + } + + TTS.messenger.request("setTTSActive", true); + + TTS.handle?.once("exit", () => { + TTS.messenger.request("setTTSActive", false); + }); + } + + static async kill(): Promise { + return new Promise((resolve, reject) => { + // Only kill a TTS process if it's still running + if (TTS.handle && TTS.handle.exitCode === null) { + // Use a timeout in case of zombie processes + let killTimeout: NodeJS.Timeout = setTimeout(() => { + reject(`Unable to kill TTS process: ${TTS.handle?.pid}`); + }, ttsKillTimeout); + + // Resolve our promise once the program has exited + TTS.handle.once("exit", () => { + clearTimeout(killTimeout); + TTS.handle = undefined; + resolve(); + }); + + TTS.handle.kill(); + } else { + resolve(); + } + }); + } + + static async setup() { + TTS.os = os.platform(); + } +} diff --git a/docs/docs/changelog.mdx b/docs/docs/changelog.mdx index 990953abe..3b703ce52 100644 --- a/docs/docs/changelog.mdx +++ b/docs/docs/changelog.mdx @@ -1,6 +1,6 @@ --- title: 📝 Changelog -description: Changelogs for the latest releases of the VSCode and IntelliJ extensions +description: Changelogs for the latest releases of the VSCode and JetBrains extensions keywords: [changelog] hide_table_of_contents: true --- @@ -8,7 +8,7 @@ hide_table_of_contents: true import VSCodeChangelog from "../../extensions/vscode/CHANGELOG.md"; import IntelliJChangelog from "../../extensions/intellij/CHANGELOG.md"; -Below are the changelogs for the latest releases of the VSCode and IntelliJ extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. +Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. import TOCInline from "@theme/TOCInline"; diff --git a/docs/docs/reference/Model Providers/assets/Watsonx1.gif b/docs/docs/reference/Model Providers/assets/Watsonx1.gif index 4d12fd7b4..e37443ad6 100644 Binary files a/docs/docs/reference/Model Providers/assets/Watsonx1.gif and b/docs/docs/reference/Model Providers/assets/Watsonx1.gif differ diff --git a/docs/docs/reference/Model Providers/bedrock.md b/docs/docs/reference/Model Providers/bedrock.md index daac562af..d720de66f 100644 --- a/docs/docs/reference/Model Providers/bedrock.md +++ b/docs/docs/reference/Model Providers/bedrock.md @@ -1,4 +1,4 @@ -# AWS Bedrock +# AWS Bedrock To setup Bedrock, add the following to your `config.json` file: @@ -9,18 +9,19 @@ To setup Bedrock, add the following to your `config.json` file: "title": "Bedrock: Claude 3 Sonnet", "provider": "bedrock", "model": "anthropic.claude-3-sonnet-20240229-v1:0", - "region": "us-east-1" + "region": "us-east-1", + "profile": "bedrock", } ] } ``` -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a profile called "bedrock". +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). ```title="~/.aws/credentials [bedrock] aws_access_key_id = abcdefg aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. +aws_session_token = pqrstuvwxyz # Optional: means short term creds. ``` diff --git a/docs/docs/reference/Model Providers/bedrockimport.md b/docs/docs/reference/Model Providers/bedrockimport.md new file mode 100644 index 000000000..6a8c50d68 --- /dev/null +++ b/docs/docs/reference/Model Providers/bedrockimport.md @@ -0,0 +1,28 @@ +# AWS Bedrock Custom Imported Models + +To setup Bedrock using custom imported models, add the following to your `config.json` file: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] +} +``` + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/docs/reference/Model Providers/kindo.md b/docs/docs/reference/Model Providers/kindo.md new file mode 100644 index 000000000..442e30b10 --- /dev/null +++ b/docs/docs/reference/Model Providers/kindo.md @@ -0,0 +1,42 @@ +# Kindo +Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins). + +## Config Example + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "" + } + ] +} +``` + +## Tab Autocomplete Config Example + +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "" + }, + { + "title": "DeepSeek", + "provider": "kindo", + "model": "deepseek-ai/deepseek-coder-33b-instruct", + "apiKey": "" + } + ] +} +``` + +## Security + +To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). \ No newline at end of file diff --git a/docs/docs/reference/Model Providers/watsonx.md b/docs/docs/reference/Model Providers/watsonx.md index b6a239946..9e2a345d4 100644 --- a/docs/docs/reference/Model Providers/watsonx.md +++ b/docs/docs/reference/Model Providers/watsonx.md @@ -1,15 +1,38 @@ -# Watsonx +# IBM watsonx -Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. +watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. ## Setup -To access the Watsonx models, create an instance in the [IBM cloud](https://cloud.ibm.com) which supports watsonx studio. Then to create a project refer [this](https://www.ibm.com/docs/en/watsonx/saas?topic=projects-creating-project). +Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance. -You can set it up in two different ways : -1. **Using API** : Create Your IBM cloud API key by referring [this](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). -2. **Using Credentials** : Use your Username and Password to authenticate +### watsonx.ai SaaS - IBM Cloud +To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial. + +To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: +- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. +- Set **watsonx Project ID** to your watsonx project ID. +- Set **watsonx API Key** to your watsonx API Key. + +### watsonx.ai Software + +To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method: +1. *Option 1* (Recommended): using `ZenApiKey` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Zen API Key. To generate it: + 1. Log in to the CPD web client. + 2. From the toolbar, click your avatar. + 3. Click **Profile and settings**. + 4. Click **API key** > **Generate new key**. + 5. Click **Generate**. + 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. + 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. +2. *Option 2*: using `username/password` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format. ## Usage -![usage-gif](../Model%20Providers/assets/Watsonx1.gif) \ No newline at end of file +![usage-gif](../Model%20Providers/assets/watsonx1.gif) diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index ab774d242..3175da802 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -46,7 +46,7 @@ You can run a model on your local computer using: - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server) - [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU) - [Msty](../reference/Model%20Providers/msty.md) -- [Watsonx](../reference/Model%20Providers/watsonx.md) +- [IBM watsonx](../reference/Model%20Providers/watsonx.md) - [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server) ### Remote @@ -63,6 +63,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co You can access both open-source and commercial LLMs via: - [OpenRouter](../reference/Model%20Providers/openrouter.md) +- [Kindo](../reference/Model%20Providers/kindo.md) ### Open-source models diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 459271d47..44742c0de 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -4,7 +4,7 @@ description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- -The Continue VS Code extension is currently in beta, and the Intellij extension is in Alpha. If you are having trouble, please follow the steps below. +The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below. 1. [Check the logs](#check-the-logs) 2. [Try the latest pre-release](#download-the-latest-pre-release) diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index f6611bea0..da74c837e 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -198,6 +199,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,7 +218,7 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" @@ -1231,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2405,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index e3eba0461..ac38ac9fc 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -37,6 +37,7 @@ dependencies { implementation("io.ktor:ktor-server-cors:2.3.7"){ exclude(group = "org.slf4j", module = "slf4j-api") } + implementation("com.posthog.java:posthog:1.+") } @@ -142,6 +143,9 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = properties("pluginVersion").map { listOf(it.split('-').getOrElse(1) { "default" }.split('.').first()) } + channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) + + // We always hide the stable releases until a few days of EAP have proven them stable + hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index c61a7c46e..723551552 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.60 +pluginVersion = 0.0.62 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 444a4d397..caf9b4720 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -9,6 +9,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.SettingsListener +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager @@ -206,22 +207,21 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val targetPath = Paths.get(corePath, target).toString() val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() - // Copy targetPath / node_sqlite3.node to core / node_sqlite3.node - val nodeSqlite3Path = Paths.get(targetPath, "node_sqlite3.node") - - // Create the build/Release path first - File(Paths.get(corePath, "build", "Release").toString()).mkdirs() - - val coreNodeSqlite3Path = Paths.get(corePath, "build", "Release", "node_sqlite3.node") - if (!File(coreNodeSqlite3Path.toString()).exists()) { - Files.copy(nodeSqlite3Path, coreNodeSqlite3Path) - } - // esbuild needs permissions val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString() val coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient) continuePluginService.coreMessenger = coreMessenger + + coreMessenger.request("config/getSerializedProfileInfo", null, null) { resp -> + val data = resp as? Map + val profileInfo = data?.get("config") as? Map + val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean + val telemetryService = service() + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { + telemetryService.setup(getMachineUniqueID()) + } + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index ded887c76..80ec73b70 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,15 +1,12 @@ package com.github.continuedev.continueintellijextension.`continue` + import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import java.io.BufferedReader -import java.io.InputStreamReader -import java.io.OutputStreamWriter - -import java.io.* - +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +import java.io.* import java.net.Socket import java.nio.charset.StandardCharsets import java.nio.file.Files @@ -238,9 +235,24 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) process!!.onExit().thenRun { - val err = process?.errorStream?.bufferedReader()?.readText()?.trim() + var err = process?.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡️Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } + } + println("Core process exited with output: $err") ideProtocolClient.showMessage("Core process exited with output: $err") + + // Log the cause of the failure + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf( + "error" to err + )) } Thread { 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 e8aa27b6c..cead14fbf 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 @@ -31,6 +31,7 @@ import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor +import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware @@ -44,6 +45,8 @@ import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint +import com.intellij.ui.content.ContentManagerUtil +import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.* import java.awt.Toolkit import java.awt.datatransfer.StringSelection @@ -605,8 +608,10 @@ class IdeProtocolClient ( respond(currentFile) } "getPinnedFiles" -> { - val openFiles = visibleFiles() - respond(openFiles) + ApplicationManager.getApplication().invokeLater { + val pinnedFiles = pinnedFiles() + respond(pinnedFiles) + } } "insertAtCursor" -> { val msg = data as Map; @@ -964,6 +969,14 @@ class IdeProtocolClient ( return fileEditorManager.openFiles.toList().map { it.path } } + @RequiresEdt + private fun pinnedFiles(): List { + val fileEditorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return listOf() + val openFiles = fileEditorManager.openFiles.map { it.path }.toList() + val pinnedFiles = fileEditorManager.windows.flatMap { window -> window.files.filter { window.isFilePinned(it) } }.map { it.path }.toSet() + return openFiles.intersect(pinnedFiles).toList() + } + private fun currentFile(): String? { val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index e974cf8fd..1ec77b738 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -195,7 +195,7 @@ class InlineEditAction : AnAction(), DumbAware { background = GetTheme().getSecondaryDark() maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) margin = JBUI.insets(8) - font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) } textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) @@ -260,7 +260,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -315,7 +315,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -352,7 +352,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { val leftLabel = JLabel("Enter follow-up instructions").apply { foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) } val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply { @@ -445,7 +445,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { }) // verticalAlignment = CENTER - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) } override fun paintComponent(g: Graphics) { @@ -477,7 +477,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { // Draw placeholder if (text.isEmpty()) { g.color = Color(128, 128, 128, 255) - g.font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) g.drawString("Enter instructions to edit highlighted code", 8, 20) } 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 new file mode 100644 index 000000000..5b7f00678 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt @@ -0,0 +1,28 @@ +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; + } + this.posthog?.capture(this.distinctId, eventName, properties) + } + + fun shutdown() { + this.posthog?.shutdown() + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index f6611bea0..da74c837e 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -198,6 +199,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,7 +218,7 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" @@ -1231,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2405,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f6611bea0..da74c837e 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -198,6 +199,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,7 +218,7 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" @@ -1231,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2405,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 5bcfaa05c..1fea6afb5 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -174,6 +174,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -201,6 +202,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -219,7 +221,7 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" @@ -2700,6 +2702,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 56071721e..f002e3c50 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -94,7 +94,7 @@ const exe = os === "win32" ? ".exe" : ""; execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -114,7 +114,7 @@ const exe = os === "win32" ? ".exe" : ""; ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -136,7 +136,7 @@ const exe = os === "win32" ? ".exe" : ""; path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 6a129bc61..93c1928ce 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -78,7 +78,7 @@ async function buildGui(isGhAction) { execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -98,7 +98,7 @@ async function buildGui(isGhAction) { ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -120,7 +120,7 @@ async function buildGui(isGhAction) { path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); @@ -256,7 +256,7 @@ async function copyNodeModules() { "@esbuild", "@lancedb", "@vscode/ripgrep", - "workerpool" + "workerpool", ]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -328,15 +328,13 @@ async function downloadEsbuildBinary(target) { "win32-x64": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", }[target]; - execCmdSync( - `curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`, - ); + execCmdSync(`curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`); execCmdSync("cd out/tmp && tar -xvzf esbuild.tgz"); // Copy the installed package back to the current directory let tmpPath = "out/tmp/package/bin"; let outPath = `out/node_modules/@esbuild/${target}/bin`; if (target.startsWith("win")) { - tmpPath = 'out/tmp/package'; + tmpPath = "out/tmp/package"; outPath = `out/node_modules/@esbuild/${target}`; } @@ -347,10 +345,7 @@ async function downloadEsbuildBinary(target) { { dereference: true }, (error) => { if (error) { - console.error( - `[error] Error copying esbuild package`, - error, - ); + console.error(`[error] Error copying esbuild package`, error); reject(error); } else { resolve(); @@ -358,7 +353,7 @@ async function downloadEsbuildBinary(target) { }, ); }); - rimrafSync("out/tmp") + rimrafSync("out/tmp"); } async function downloadSqliteBinary(target) { @@ -408,7 +403,8 @@ async function copySqliteBinary() { async function downloadRipgrepBinary(target) { console.log("[info] Downloading pre-built ripgrep binary"); rimrafSync("node_modules/@vscode/ripgrep/bin"); - fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true });4 + fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true }); + 4; const downloadUrl = { "darwin-arm64": "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-apple-darwin.tar.gz", @@ -424,8 +420,7 @@ async function downloadRipgrepBinary(target) { "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-pc-windows-msvc.zip", }[target]; - - if(target.startsWith("win")) { + if (target.startsWith("win")) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.zip ${downloadUrl}`, ); @@ -435,7 +430,9 @@ async function downloadRipgrepBinary(target) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.tar.gz ${downloadUrl}`, ); - execCmdSync("cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz"); + execCmdSync( + "cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz", + ); fs.unlinkSync("node_modules/@vscode/ripgrep/bin/build.tar.gz"); } } @@ -512,5 +509,5 @@ module.exports = { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, downloadRipgrepBinary, - copyTokenizers + copyTokenizers, }; diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index ed79e1a05..02521c2ae 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -74,12 +74,12 @@ export async function getContextProviderQuickPickVal( const val = await new Promise((resolve) => { quickPick.onDidAccept(async () => { const selectedItems = Array.from(quickPick.selectedItems); - const context = await getContextProvidersString( - selectedItems, - config, - ide, - ); - resolve(context); + getContextProvidersString(selectedItems, config, ide) + .then(resolve) + .catch((e) => { + console.warn(`Fail to get context providers: ${e}`); + resolve(""); + }); }); }); diff --git a/gui/public/logos/WatsonX.png b/gui/public/logos/WatsonX.png index 66cf02a03..ba4807267 100644 Binary files a/gui/public/logos/WatsonX.png and b/gui/public/logos/WatsonX.png differ diff --git a/gui/src/components/index.tsx b/gui/src/components/index.tsx index a186d0e6b..eac6bf022 100644 --- a/gui/src/components/index.tsx +++ b/gui/src/components/index.tsx @@ -192,7 +192,12 @@ const TooltipStyles = { }; export function StyledTooltip(props: any) { - return ; + const combinedStyles = { + ...TooltipStyles, + ...props.style, // Merge any additional styles passed via props + }; + + return ; } export const TextArea = styled.textarea` diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 8ab8f190e..83752c95f 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -56,6 +56,7 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; +import { debounce } from "lodash"; const InputBoxDiv = styled.div` resize: none; @@ -473,6 +474,31 @@ function TipTapEditor(props: TipTapEditorProps) { }, }); + const [shouldHideToolbar, setShouldHideToolbar] = useState(false); + const debouncedShouldHideToolbar = debounce((value) => { + setShouldHideToolbar(value); + }, 200); + + useEffect(() => { + if (editor) { + const handleFocus = () => { + debouncedShouldHideToolbar(false); + } + + const handleBlur = () => { + debouncedShouldHideToolbar(true); + }; + + editor.on('focus', handleFocus); + editor.on('blur', handleBlur); + + return () => { + editor.off('focus', handleFocus); + editor.off('blur', handleBlur); + }; + } + }, [editor]); + const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); useEffect(() => { @@ -831,7 +857,7 @@ function TipTapEditor(props: TipTapEditorProps) { />