diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5b248d5d8..2b9f266d5 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -9,7 +9,7 @@ ## Screenshots -[ For visual changes, include screenshots. ] +[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ] ## Testing instructions diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml new file mode 100644 index 000000000..43d65d5b5 --- /dev/null +++ b/.github/workflows/auto-release.yml @@ -0,0 +1,70 @@ +name: Create Automatic Release + +on: + push: + branches: + - nate/auto-main-release-draft + schedule: + - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday + workflow_dispatch: # Keep manual trigger option + +jobs: + create-vscode-release: + runs-on: ubuntu-latest + permissions: + contents: write # Needed for creating releases + + steps: + - uses: actions/checkout@v4 + + - name: Get version from package.json + id: get_version + run: | + # Read version from package.json and add -vscode suffix + version=$(node -p "require('./extensions/vscode/package.json').version") + new_version="v${version}-vscode" + echo "New version will be: $new_version" + echo "NEW_VERSION=$new_version" >> $GITHUB_ENV + + - name: Create Release + env: + GH_TOKEN: ${{ github.token }} + run: | + # Create a new draft release with auto-generated release notes + gh release create "$NEW_VERSION" \ + --generate-notes \ + --title "$NEW_VERSION" \ + --draft \ + --latest \ + --prerelease + + create-jetbrains-release: + runs-on: ubuntu-latest + permissions: + contents: write # Needed for creating releases + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Get version from gradle.properties + id: get_version + run: | + # Read version from gradle.properties and add -jetbrains suffix + version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2) + new_version="v${version}-jetbrains" + echo "New version will be: $new_version" + echo "NEW_VERSION=$new_version" >> $GITHUB_ENV + + - name: Create Release + env: + GH_TOKEN: ${{ github.token }} + run: | + # Create a new draft release with auto-generated release notes + gh release create "$NEW_VERSION" \ + --generate-notes \ + --title "$NEW_VERSION" \ + --draft \ + --latest \ + --prerelease diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index bf2fa74a6..252aa76ff 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -37,6 +37,52 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi + bump-version: + runs-on: ubuntu-latest + needs: + - check_release_name + if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' + permissions: + contents: write + pull-requests: write + steps: + # 0. Setup git + - name: Checkout + 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: Create PR branch + run: | + BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" + git checkout -b $BRANCH_NAME + echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + + - name: Bump version in gradle.properties + run: | + cd extensions/intelllij + awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties + rm -rf tmp + NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) + echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.CI_GITHUB_TOKEN }} + commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + body: | + Automated PR to bump the JetBrains extension version after successful pre-release publication. + + - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} + branch: ${{ env.BRANCH_NAME }} + base: main + delete-branch: true + # Prepare and publish the plugin to JetBrains Marketplace repository build: needs: check_release_name @@ -54,7 +100,7 @@ jobs: ref: ${{ github.event.release.tag_name }} - name: Import Apple certificate - uses: apple-actions/import-codesign-certs@v3 + uses: apple-actions/import-codesign-certs@v5 with: keychain: ${{ github.run_id }} keychain-password: ${{ github.run_id }} diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index bf8ce2ecb..4d0a4039b 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -31,6 +31,62 @@ jobs: if: steps.root-cache.outputs.cache-hit != 'true' run: npm ci + install-config-yaml: + needs: install-root + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Install config-yaml dependencies + if: steps.config-yaml-cache.outputs.cache-hit != 'true' + run: | + cd packages/config-yaml + npm ci + + config-yaml-checks: + needs: install-config-yaml + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build and check config-yaml + run: | + cd packages/config-yaml + npx tsc --noEmit + # Tests are currently failing, commenting out for now + # npm test + npm run build + install-core: needs: install-root runs-on: ubuntu-latest @@ -60,7 +116,7 @@ jobs: npm ci core-checks: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -81,6 +137,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd core @@ -90,7 +157,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -115,6 +182,17 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install gui dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: | @@ -147,13 +225,24 @@ jobs: path: gui/node_modules key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check run: | cd gui npx tsc --noEmit binary-checks: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -178,6 +267,17 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install binary dependencies if: steps.binary-cache.outputs.cache-hit != 'true' run: | @@ -190,7 +290,7 @@ jobs: npx tsc --noEmit install-vscode: - needs: [install-root, install-core] + needs: [install-root, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -215,6 +315,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install vscode dependencies if: steps.vscode-cache.outputs.cache-hit != 'true' run: | @@ -249,14 +360,26 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Type check and lint run: | cd extensions/vscode + npm run write-build-timestamp npx tsc --noEmit npm run lint core-tests: - needs: install-core + needs: [install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -270,6 +393,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Run core tests run: | cd core @@ -285,7 +419,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [install-root, install-vscode] + needs: [install-root, install-vscode, install-config-yaml] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -297,6 +431,17 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Get test files id: vscode-get-test-file-matrix run: | @@ -320,7 +465,7 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -340,6 +485,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Package extension run: | cd extensions/vscode @@ -353,7 +509,7 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [install-vscode, install-core, install-config-yaml] steps: - uses: actions/checkout@v4 @@ -373,6 +529,17 @@ jobs: path: extensions/vscode/e2e/storage key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Download Dependencies if: steps.storage-cache.outputs.cache-hit != 'true' run: | @@ -394,6 +561,7 @@ jobs: vscode-package-extension, install-vscode, install-core, + install-config-yaml, ] runs-on: ubuntu-latest # Tests requiring secrets need approval from maintainers @@ -434,6 +602,17 @@ jobs: name: vscode-e2e-dependencies path: extensions/vscode/e2e/storage + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Fix VSCode binary permissions run: | chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code @@ -476,7 +655,7 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [install-gui, install-core] + needs: [install-gui, install-core, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -496,6 +675,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Install GUI dependencies if: steps.gui-cache.outputs.cache-hit != 'true' run: cd gui && npm ci @@ -508,7 +698,7 @@ jobs: npm test jetbrains-tests: - needs: [install-root, core-checks] + needs: [install-root, core-checks, install-config-yaml] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -517,6 +707,17 @@ jobs: path: core/node_modules key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }} + - uses: actions/cache@v4 + id: config-yaml-cache + with: + path: packages/config-yaml/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Build config-yaml + run: | + cd packages/config-yaml + npm run build + - name: Setup Java uses: actions/setup-java@v4.5.0 with: @@ -627,11 +828,11 @@ jobs: - vscode-e2e-tests - gui-tests - jetbrains-tests + - config-yaml-checks + - install-config-yaml steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: - allowed-failures: - allowed-skips: jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 7408cf76f..23ea26bf6 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,4 +1,4 @@ -name: Publish Preview Extension +name: Publish Pre-release Extension on: release: @@ -207,6 +207,7 @@ jobs: if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' permissions: contents: write + pull-requests: write steps: # 0. Setup git - name: Checkout @@ -242,12 +243,44 @@ jobs: cd extensions/vscode npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix - # 4. Update the package.json version and push changes + # 4. Create PR with version bump + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Create PR branch + run: | + BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)" + git checkout -b $BRANCH_NAME + echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + + - name: Bump version in package.json + run: | + cd extensions/vscode + npm version patch --no-git-tag-version + VERSION=$(node -p "require('./package.json').version") + echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.CI_GITHUB_TOKEN }} + commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}" + title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}" + body: | + Automated PR to bump the VS Code extension version after successful pre-release publication. + + - Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }} + branch: ${{ env.BRANCH_NAME }} + base: main + delete-branch: true + + # 5. Update version in package.json # - name: Update version in package.json # run: | # cd extensions/vscode # npm version patch - # - name: Commit changes # run: | # git config --local user.email "action@github.com" diff --git a/.github/workflows/release-config-yaml.yml b/.github/workflows/release-config-yaml.yml new file mode 100644 index 000000000..0847f5c0c --- /dev/null +++ b/.github/workflows/release-config-yaml.yml @@ -0,0 +1,46 @@ +name: Release @continuedev/config-yaml + +on: + push: + branches: + - main + paths: + - "packages/config-yaml/**" + +jobs: + release: + name: Release + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Install dependencies + run: | + cd packages/config-yaml + npm ci + + - name: Build + run: | + cd packages/config-yaml + npm run build + + - name: Run tests + run: | + cd packages/config-yaml + npm test + + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + cd packages/config-yaml + npx semantic-release diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml new file mode 100644 index 000000000..c05da185f --- /dev/null +++ b/.github/workflows/vscode-version-bump.yml @@ -0,0 +1,124 @@ +name: Create VS Code main release draft +on: + schedule: + # Runs at 7 AM PST (15:00 UTC) every Friday + - cron: "0 15 * * 5" + workflow_dispatch: + # Allows manual triggering + +jobs: + version-bump: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetch all history and tags + + - name: Setup GitHub CLI + run: | + gh auth login --with-token <<< "${{ github.token }}" + + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Find and process version tags + run: | + echo "Starting version bump process..." + + # Find last v1.1.x-vscode tag that's at least 6 days old + CURRENT_TIMESTAMP=$(date +%s) + SIX_DAYS_AGO=$((CURRENT_TIMESTAMP - 6*24*60*60)) + echo "Current timestamp: $(date -d @${CURRENT_TIMESTAMP})" + echo "Six days ago: $(date -d @${SIX_DAYS_AGO})" + + echo "Looking for v1.1.x-vscode tags..." + git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:iso)' refs/tags | grep 'v1\.1\.[0-9]\+-vscode' || echo "No matching tags found" + + LAST_1_1_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:unix)' refs/tags \ + | grep 'v1\.1\.[0-9]\+-vscode' \ + | while read tag timestamp; do + if [ $timestamp -le $SIX_DAYS_AGO ]; then + echo ${tag% *} + break + fi + done) + + echo "Selected v1.1.x tag: $LAST_1_1_TAG" + if [ -z "$LAST_1_1_TAG" ]; then + echo "::error::No suitable v1.1.x-vscode tag found" + exit 1 + fi + + # Find last v1.0.y-vscode tag + echo "Looking for v1.0.y-vscode tags..." + git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' || echo "No matching tags found" + + LAST_1_0_TAG=$(git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' | head -n1) + echo "Selected v1.0.y tag: $LAST_1_0_TAG" + if [ -z "$LAST_1_0_TAG" ]; then + echo "::error::No v1.0.y-vscode tag found" + exit 1 + fi + + # Extract the y number and increment it + Y_NUMBER=$(echo $LAST_1_0_TAG | sed 's/v1\.0\.\([0-9]\+\)-vscode/\1/') + NEXT_Y=$((Y_NUMBER + 1)) + NEW_BRANCH="v1.0.${NEXT_Y}-vscode" + NEW_VERSION="1.0.${NEXT_Y}" + echo "Current Y number: $Y_NUMBER" + echo "Next Y number: $NEXT_Y" + echo "New branch name: $NEW_BRANCH" + echo "New version: $NEW_VERSION" + + # Create new branch from the v1.1.x tag + echo "Creating new branch from $LAST_1_1_TAG..." + git checkout $LAST_1_1_TAG + git checkout -b $NEW_BRANCH + + # Update the version in package.json + echo "Current package.json version:" + cat extensions/vscode/package.json | grep version + + echo "Updating version in package.json..." + jq ".version = \"$NEW_VERSION\"" extensions/vscode/package.json > temp.json && mv temp.json extensions/vscode/package.json + + echo "New package.json version:" + cat extensions/vscode/package.json | grep version + + # Configure git + echo "Configuring git..." + git config user.name "GitHub Actions Bot" + git config user.email "actions@github.com" + + # Commit and push changes + echo "Committing changes..." + git add extensions/vscode/package.json + git commit -m "Bump VS Code extension to ${NEW_VERSION}" + + echo "Pushing branch to origin..." + git push origin $NEW_BRANCH + + # Add release creation + echo "Creating draft release..." + gh release create "${NEW_BRANCH}" \ + --title "${NEW_BRANCH}" \ + --generate-notes \ + --draft \ + --latest \ + --notes-start-tag "${LAST_1_0_TAG}" + + echo "Version bump process completed successfully!" + + - name: Check for errors + if: failure() + run: | + echo "::error::Failed to process version tags and create new branch" + echo "Last few lines of git log:" + git log -n 5 --oneline + echo "Current git status:" + git status + echo "Current branches:" + git branch -a diff --git a/.node-version b/.node-version new file mode 100644 index 000000000..18c284172 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +20.11.0 \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 73997880a..4b42593d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -139,7 +139,7 @@ Similarly, any changes to `core` or `extensions/vscode` will be automatically in #### JetBrains -See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension. +See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension. ### Our Git Workflow @@ -147,7 +147,7 @@ We keep a single permanent branch: `main`. When we are ready to create a "pre-re ### Testing -We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you resolve the issue before we merge. +We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge. When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton. @@ -217,7 +217,7 @@ Continue consists of 2 parts that are split so that it can be extended to work i 1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs. -2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts). +2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts). ### Continue VS Code Extension diff --git a/README.md b/README.md index fc07289d7..dffa26b4f 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/binary/package-lock.json b/binary/package-lock.json index 5ce095e37..5c2324e82 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -44,13 +44,13 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.758.0", - "@aws-sdk/client-sagemaker-runtime": "^3.758.0", - "@aws-sdk/credential-providers": "^3.758.0", + "@aws-sdk/client-bedrock-runtime": "^3.779.0", + "@aws-sdk/client-sagemaker-runtime": "^3.777.0", + "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.63", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", - "@continuedev/llm-info": "^1.0.2", + "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", @@ -67,6 +67,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -135,7 +136,8 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", - "ts-jest": "^29.1.1" + "ts-jest": "^29.1.1", + "typescript": "^5.6.3" }, "engines": { "node": ">=20.11.0" @@ -6404,10 +6406,11 @@ } }, "node_modules/tar-fs": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", - "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", + "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", "dev": true, + "license": "MIT", "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", diff --git a/binary/src/index.ts b/binary/src/index.ts index 32bede332..dce9a25ab 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -1,6 +1,7 @@ process.env.IS_BINARY = "true"; import { Command } from "commander"; import { Core } from "core/core"; +import { LLMLogFormatter } from "core/llm/logFormatter"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { IMessenger } from "core/protocol/messenger"; import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths"; @@ -33,9 +34,8 @@ program.action(async () => { const ide = new IpcIde(messenger); const promptLogsPath = getPromptLogsPath(); - new Core(messenger, ide, async (text) => { - fs.appendFileSync(promptLogsPath, text + "\n\n"); - }); + const core = new Core(messenger, ide); + new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath)); console.log("[binary] Core started"); } catch (e) { diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index bd8504986..fb1be39bb 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -234,15 +234,17 @@ describe("Test Suite", () => { result: { config }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(config!.models.some((m) => m.title === model.title)).toBe(true); + expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe( + true, + ); await messenger.request("config/deleteModel", { title: model.title }); const { result: { config: configAfterDelete }, } = await messenger.request("config/getSerializedProfileInfo", undefined); - expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe( - false, - ); + expect( + configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title), + ).toBe(false); }); it("should make an LLM completion", async () => { diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 633895fb7..ac673b38f 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -12,11 +12,11 @@ "curly": "off", "@typescript-eslint/semi": "off", "eqeqeq": "error", - "complexity": ["error", { "max": 38 }], - "max-lines-per-function": ["error", { "max": 996 }], + "complexity": ["error", { "max": 36 }], + "max-lines-per-function": ["error", { "max": 472 }], "max-statements": ["error", { "max": 114 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], - "max-params": ["error", { "max": 11 }] + "max-params": ["error", { "max": 8 }] } } diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 79b598f1e..7a29f8a8f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -88,7 +88,6 @@ export class RootPathContextService { default: // const type = node.type; // console.log(getSyntaxTreeString(node)); - // debugger; query = await getQueryForFile( filepath, @@ -165,7 +164,6 @@ export class RootPathContextService { )) { const key = RootPathContextService.keyFromNode(parentKey, astNode); // const type = astNode.type; - // debugger; const foundInCache = this.cache.get(key); const newSnippets = diff --git a/core/autocomplete/util/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts index a93b23c5a..adac906ff 100644 --- a/core/autocomplete/util/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -39,20 +39,28 @@ export class AutocompleteLruCache { // If the query is "co" and we have "c" -> "ontinue" in the cache, // we should return "ntinue" as the completion. // Have to make sure we take the key with shortest length - const result = await this.db.get( - "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - truncateSqliteLikePattern(prefix), - ); - - // Validate that the cached compeltion is a valid completion for the prefix - if (result && result.value.startsWith(prefix.slice(result.key.length))) { - await this.db.run( - "UPDATE cache SET timestamp = ? WHERE key = ?", - Date.now(), - prefix, + const truncatedPrefix = truncateSqliteLikePattern(prefix); + try { + const result = await this.db.get( + "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", + truncatedPrefix, ); - // And then truncate so we aren't writing something that's already there - return result.value.slice(prefix.length - result.key.length); + // Validate that the cached completion is a valid completion for the prefix + if ( + result && + result.value.startsWith(truncatedPrefix.slice(result.key.length)) + ) { + await this.db.run( + "UPDATE cache SET timestamp = ? WHERE key = ?", + Date.now(), + truncatedPrefix, + ); + // And then truncate so we aren't writing something that's already there + return result.value.slice(truncatedPrefix.length - result.key.length); + } + } catch (e) { + // catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX + console.error(e); } return undefined; @@ -60,13 +68,15 @@ export class AutocompleteLruCache { async put(prefix: string, completion: string) { const release = await this.mutex.acquire(); + + const truncatedPrefix = truncateSqliteLikePattern(prefix); try { await this.db.run("BEGIN TRANSACTION"); try { const result = await this.db.get( "SELECT key FROM cache WHERE key = ?", - prefix, + truncatedPrefix, ); if (result) { @@ -74,7 +84,7 @@ export class AutocompleteLruCache { "UPDATE cache SET value = ?, timestamp = ? WHERE key = ?", completion, Date.now(), - prefix, + truncatedPrefix, ); } else { const count = await this.db.get( @@ -89,7 +99,7 @@ export class AutocompleteLruCache { await this.db.run( "INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)", - prefix, + truncatedPrefix, completion, Date.now(), ); diff --git a/core/commands/index.ts b/core/commands/index.ts index 486eaccf2..3037d7ef7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,5 +1,7 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; +import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -7,68 +9,57 @@ import SlashCommands from "./slash"; export function slashFromCustomCommand( customCommand: CustomCommand, ): SlashCommand { + const commandName = customCommand.name.startsWith("/") + ? customCommand.name.substring(1) + : customCommand.name; return { - name: customCommand.name, + name: commandName, description: customCommand.description ?? "", prompt: customCommand.prompt, - run: async function* ({ input, llm, history, ide, completionOptions }) { - // Remove slash command prefix from input - let userInput = input; - if (userInput.startsWith(`/${customCommand.name}`)) { - userInput = userInput - .slice(customCommand.name.length + 1, userInput.length) - .trimStart(); - } - + run: async function* ({ + input, + llm, + history, + ide, + completionOptions, + config, + selectedCode, + fetch, + }) { // Render prompt template - let promptUserInput: string; + let renderedPrompt: string; if (customCommand.prompt.includes("{{{ input }}}")) { - promptUserInput = await renderTemplatedString( + renderedPrompt = await renderTemplatedString( customCommand.prompt, ide.readFile.bind(ide), - { input: userInput }, + { input }, ); } else { - promptUserInput = customCommand.prompt + "\n\n" + userInput; + const renderedPromptFile = await renderPromptFileV2( + customCommand.prompt, + { + config, + llm, + ide, + selectedCode, + fetch, + fullInput: input, + embeddingsProvider: config.modelsByRole.embed[0], + reranker: config.modelsByRole.rerank[0], + }, + ); + + renderedPrompt = renderedPromptFile[1]; } - const messages = [...history]; - // Find the last chat message with this slash command and replace it with the user input - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages[i]; - const { role, content } = message; - if (role !== "user") { - continue; - } - - if ( - Array.isArray(content) && - content.some( - (part) => - "text" in part && part.text?.startsWith(`/${customCommand.name}`), - ) - ) { - messages[i] = { - ...message, - content: content.map((part) => { - if ( - "text" in part && - part.text.startsWith(`/${customCommand.name}`) - ) { - return { type: "text", text: promptUserInput }; - } - return part; - }), - }; - break; - } else if ( - typeof content === "string" && - content.startsWith(`/${customCommand.name}`) - ) { - messages[i] = { ...message, content: promptUserInput }; - break; - } - } + // Replaces slash command messages with the rendered prompt + // which INCLUDES the input + const messages = replaceSlashCommandWithPromptInChatHistory( + history, + commandName, + renderedPrompt, + undefined, + ); for await (const chunk of llm.streamChat( messages, diff --git a/core/commands/util.ts b/core/commands/util.ts index 5a0ea32e4..3785b4f52 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -34,13 +34,18 @@ export function ctxItemToRifWithContents( ): RangeInFileWithContents { let startLine = 0; let endLine = 0; + let adjustLines = linesOffByOne ? 1 : 0; const nameSplit = item.name.split("("); if (nameSplit.length > 1) { const lines = nameSplit[1].split(")")[0].split("-"); - startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0); - endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0); + startLine = Number.parseInt(lines[0], 10); + if (startLine === 0) { + adjustLines = 0; // safety to make sure doesn't go negative + } + startLine -= adjustLines; + endLine = Number.parseInt(lines[1], 10) - adjustLines; } const rif: RangeInFileWithContents = { diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 031075e90..4b4be0762 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -9,9 +9,9 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { - const profiles = testConfigHandler.listProfiles(); + const profiles = testConfigHandler.currentOrg.profiles; expect(profiles?.length).toBe(1); - expect(profiles?.[0].id).toBe("local"); + expect(profiles?.[0].profileDescription.id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; expect(currentProfile?.profileDescription.id).toBe("local"); @@ -19,7 +19,9 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should load the default config successfully", async () => { const result = await testConfigHandler.loadConfig(); - expect(result.config!.models.length).toBe(defaultConfig.models?.length); + expect(result.config!.modelsByRole.chat.length).toBe( + defaultConfig.models?.length, + ); }); test.skip("should add a system message from config.ts", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 3a3c81fab..fd628eb06 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,4 +1,4 @@ -import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; +import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient, @@ -11,374 +11,306 @@ import { IContextProvider, IDE, IdeSettings, - ILLM, + ILLMLogger, } from "../index.js"; -import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { getAllAssistantFiles } from "./loadLocalAssistants.js"; -import { - LOCAL_ONBOARDING_CHAT_MODEL, - LOCAL_ONBOARDING_PROVIDER_TITLE, -} from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { + OrganizationDescription, + OrgWithProfiles, ProfileDescription, ProfileLifecycleManager, + SerializedOrgWithProfiles, } from "./ProfileLifecycleManager.js"; export type { ProfileDescription }; type ConfigUpdateFunction = (payload: ConfigResult) => void; -// Separately manages saving/reloading each profile - export class ConfigHandler { - private readonly globalContext = new GlobalContext(); - private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded - private selectedProfileId: string | null = null; - private localProfileManager: ProfileLifecycleManager; controlPlaneClient: ControlPlaneClient; + private readonly globalContext = new GlobalContext(); + private globalLocalProfileManager: ProfileLifecycleManager; - initializedPromise: Promise; + private organizations: OrgWithProfiles[] = []; + currentProfile: ProfileLifecycleManager | null; + currentOrg: OrgWithProfiles; constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, - private readonly writeLog: (text: string) => Promise, + private llmLogger: ILLMLogger, sessionInfoPromise: Promise, - private readonly didSelectOrganization?: (orgId: string | null) => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; - this.writeLog = writeLog; this.controlPlaneClient = new ControlPlaneClient( sessionInfoPromise, ideSettingsPromise, ); - // Set local profile as default - const localProfileLoader = new LocalProfileLoader( - ide, - ideSettingsPromise, - this.controlPlaneClient, - writeLog, - ); - this.localProfileManager = new ProfileLifecycleManager( - localProfileLoader, + // This profile manager will always be available + this.globalLocalProfileManager = new ProfileLifecycleManager( + new LocalProfileLoader( + ide, + ideSettingsPromise, + this.controlPlaneClient, + this.llmLogger, + ), this.ide, ); - // Profiles are loaded asynchronously - this.initializedPromise = new Promise((resolve, reject) => { - this.init() - .then(() => { - resolve(); - }) - .catch((e) => { - reject(e); - }); - }); + // Just to be safe, always force a default personal org with local profile manager + this.currentProfile = this.globalLocalProfileManager; + const personalOrg: OrgWithProfiles = { + currentProfile: this.globalLocalProfileManager, + profiles: [this.globalLocalProfileManager], + ...this.PERSONAL_ORG_DESC, + }; + + this.currentOrg = personalOrg; + this.organizations = [personalOrg]; + + void this.cascadeInit(); } - /** - * Users can define as many local assistants as they want in a `.continue/assistants` folder - */ - private async getLocalAssistantProfiles() { + private workspaceDirs: string[] | null = null; + async getWorkspaceId() { + if (!this.workspaceDirs) { + this.workspaceDirs = await this.ide.getWorkspaceDirs(); + } + return this.workspaceDirs.join("&"); + } + + async getProfileKey(orgId: string) { + const workspaceId = await this.getWorkspaceId(); + return `${workspaceId}:::${orgId}`; + } + + private async cascadeInit() { + this.workspaceDirs = null; // forces workspace dirs reload + + const orgs = await this.getOrgs(); + + // Figure out selected org + const workspaceId = await this.getWorkspaceId(); + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + const currentSelection = selectedOrgs[workspaceId]; + + const firstNonPersonal = orgs.find( + (org) => org.id !== this.PERSONAL_ORG_DESC.id, + ); + const fallback = firstNonPersonal ?? orgs[0]; + // note, ignoring case of zero orgs since should never happen + + let selectedOrg: OrgWithProfiles; + if (!currentSelection) { + selectedOrg = fallback; + } else { + const match = orgs.find((org) => org.id === currentSelection); + if (match) { + selectedOrg = match; + } else { + selectedOrg = fallback; + } + } + + this.globalContext.update("lastSelectedOrgIdForWorkspace", { + ...selectedOrgs, + [workspaceId]: selectedOrg.id, + }); + + this.organizations = orgs; + this.currentOrg = selectedOrg; + this.currentProfile = selectedOrg.currentProfile; + await this.reloadConfig(); + } + + private async getOrgs(): Promise { + const userId = await this.controlPlaneClient.userId; + if (userId) { + const orgDescs = await this.controlPlaneClient.listOrganizations(); + if (await useHub(this.ideSettingsPromise)) { + const personalHubOrg = await this.getPersonalHubOrg(); + const hubOrgs = await Promise.all( + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ); + return [...hubOrgs, personalHubOrg]; + } else { + // Should only ever be one teams org. Will be removed soon anyways + return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org))); + } + } else { + return [await this.getLocalOrg()]; + } + } + + getSerializedOrgs(): SerializedOrgWithProfiles[] { + return this.organizations.map((org) => ({ + iconUrl: org.iconUrl, + id: org.id, + name: org.name, + slug: org.slug, + profiles: org.profiles.map((profile) => profile.profileDescription), + selectedProfileId: org.currentProfile?.profileDescription.id || null, + })); + } + + private async getHubProfiles(orgScopeId: string | null) { + const assistants = await this.controlPlaneClient.listAssistants(orgScopeId); + + return await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create({ + configResult: { + ...assistant.configResult, + config: assistant.configResult.config, + }, + ownerSlug: assistant.ownerSlug, + packageSlug: assistant.packageSlug, + iconUrl: assistant.iconUrl, + versionSlug: assistant.configResult.config?.version ?? "latest", + controlPlaneClient: this.controlPlaneClient, + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + llmLogger: this.llmLogger, + rawYaml: assistant.rawYaml, + orgScopeId: orgScopeId, + }); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); + } + + private async getNonPersonalHubOrg( + org: OrganizationDescription, + ): Promise { + const profiles = await this.getHubProfiles(org.id); + return this.rectifyProfilesForOrg(org, profiles); + } + + private PERSONAL_ORG_DESC: OrganizationDescription = { + iconUrl: "", + id: "personal", + name: "Personal", + slug: undefined, + }; + private async getPersonalHubOrg() { + const allLocalProfiles = await this.getAllLocalProfiles(); + const hubProfiles = await this.getHubProfiles(null); + const profiles = [...hubProfiles, ...allLocalProfiles]; + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles); + } + + private async getLocalOrg() { + const allLocalProfiles = await this.getAllLocalProfiles(); + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); + } + + async getTeamsOrg(org: OrganizationDescription): Promise { + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = await this.getAllLocalProfiles(); + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.llmLogger, + this.reloadConfig.bind(this), + ); + + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + }); + return this.rectifyProfilesForOrg(org, profiles); + } + + private async rectifyProfilesForOrg( + org: OrganizationDescription, + profiles: ProfileLifecycleManager[], + ): Promise { + const profileKey = await this.getProfileKey(org.id); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + + const currentSelection = selectedProfiles[profileKey]; + + const firstNonLocal = profiles.find( + (profile) => profile.profileDescription.profileType !== "local", + ); + const fallback = + firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null); + + let currentProfile: ProfileLifecycleManager | null; + if (!currentSelection) { + currentProfile = fallback; + } else { + const match = profiles.find( + (profile) => profile.profileDescription.id === currentSelection, + ); + if (match) { + currentProfile = match; + } else { + currentProfile = fallback; + } + } + + if (currentProfile) { + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: selectedProfiles.id ?? null, + }); + } + + return { + ...org, + profiles, + currentProfile, + }; + } + + async getAllLocalProfiles() { + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ const assistantFiles = await getAllAssistantFiles(this.ide); const profiles = assistantFiles.map((assistant) => { return new LocalProfileLoader( this.ide, this.ideSettingsPromise, this.controlPlaneClient, - this.writeLog, + this.llmLogger, assistant, ); }); - return profiles.map( + const localAssistantProfiles = profiles.map( (profile) => new ProfileLifecycleManager(profile, this.ide), ); + return [this.globalLocalProfileManager, ...localAssistantProfiles]; } - /** - * Retrieves the titles of additional context providers that are of type "submenu". - * - * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu". - */ - getAdditionalSubmenuContextProviders(): string[] { - return this.additionalContextProviders - .filter((provider) => provider.description.type === "submenu") - .map((provider) => provider.description.title); + ////////////////// + // External actions that can cause a cascading config refresh + // Should not be used internally + ////////////////// + async refreshAll() { + await this.cascadeInit(); } - private async init() { - try { - await this.fetchControlPlaneProfiles(); - } catch (e) { - // If this fails, make sure at least local profile is loaded - console.error("Failed to fetch control plane profiles in init: ", e); - await this.loadLocalProfilesOnly(); - } - - try { - const configResult = await this.loadConfig(); - this.notifyConfigListeners(configResult); - } catch (e) { - console.error("Failed to load config: ", e); - } - } - - get currentProfile() { - if (!this.selectedProfileId) { - return null; - } - // IMPORTANT - // We must fall back to null, not the first or local profiles - // Because GUI must be the source of truth for selected profile - return ( - this.profiles?.find( - (p) => p.profileDescription.id === this.selectedProfileId, - ) ?? null - ); - } - - get inactiveProfiles() { - return (this.profiles ?? []).filter( - (p) => p.profileDescription.id !== this.selectedProfileId, - ); - } - - async openConfigProfile(profileId?: string) { - let openProfileId = profileId || this.selectedProfileId; - const profile = this.profiles?.find( - (p) => p.profileDescription.id === openProfileId, - ); - if (profile?.profileDescription.profileType === "local") { - const ideInfo = await this.ide.getIdeInfo(); - await this.ide.openFile(profile.profileDescription.uri); - } else { - const env = await getControlPlaneEnv(this.ide.getIdeSettings()); - await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); - } - } - - async listOrganizations() { - return await this.controlPlaneClient.listOrganizations(); - } - - async loadAssistantsForSelectedOrg() { - // Get the profiles and create their lifecycle managers - const userId = await this.controlPlaneClient.userId; - const selectedOrgId = await this.getSelectedOrgId(); - - let profiles: ProfileLifecycleManager[] | null = null; - if (!userId) { - // Not logged in - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...allLocalProfiles]; - } else { - // Logged in - const assistants = - await this.controlPlaneClient.listAssistants(selectedOrgId); - - const hubProfiles = await Promise.all( - assistants.map(async (assistant) => { - const profileLoader = await PlatformProfileLoader.create( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - assistant.rawYaml, - selectedOrgId, - ); - - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); - - if (selectedOrgId === null) { - // Personal - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...hubProfiles, ...allLocalProfiles]; - } else { - // Organization - profiles = hubProfiles; - } - } - - await this.updateAvailableProfiles(profiles); - } - - private async getAllLocalProfiles() { - const localAssistantProfiles = await this.getLocalAssistantProfiles(); - return [this.localProfileManager, ...localAssistantProfiles]; - } - - private async loadLocalProfilesOnly() { - const allLocalProfiles = await this.getAllLocalProfiles(); - await this.updateAvailableProfiles(allLocalProfiles); - } - - private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { - this.profiles = profiles; - - // If the last selected profile is in the list choose that - // Otherwise, choose the first profile - const previouslySelectedProfileId = - await this.getPersistedSelectedProfileId(); - - // Check if the previously selected profile exists in the current profiles - const profileExists = profiles.some( - (profile) => - profile.profileDescription.id === previouslySelectedProfileId, - ); - - const selectedProfileId = profileExists - ? previouslySelectedProfileId - : (profiles[0]?.profileDescription.id ?? null); - - // Notify listeners - const profileDescriptions = profiles.map( - (profile) => profile.profileDescription, - ); - this.notifyProfileListeners(profileDescriptions, selectedProfileId); - await this.setSelectedProfile(selectedProfileId); - } - - private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; - // We use this to keep track of whether we should reload the assistants - private lastFullSlugsList: FullSlug[] = []; - - private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean { - if (a.length !== b.length) { - return true; - } - for (let i = 0; i < a.length; i++) { - if (a[i].ownerSlug !== b[i].ownerSlug) { - return true; - } - if (a[i].packageSlug !== b[i].packageSlug) { - return true; - } - if (a[i].versionSlug !== b[i].versionSlug) { - return true; - } - } - return false; - } - - private async reloadHubAssistants() { - const selectedOrgId = await this.getSelectedOrgId(); - const newFullSlugsList = - await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId); - - if (newFullSlugsList) { - const shouldReload = this.fullSlugsListsDiffer( - newFullSlugsList, - this.lastFullSlugsList, - ); - if (shouldReload) { - await this.loadAssistantsForSelectedOrg(); - } - this.lastFullSlugsList = newFullSlugsList; - } - } - - private async fetchControlPlaneProfiles() { - if (await useHub(this.ideSettingsPromise)) { - clearInterval(this.platformProfilesRefreshInterval); - await this.loadAssistantsForSelectedOrg(); - - // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds - // If so, we do the full (more expensive) reload - this.platformProfilesRefreshInterval = setInterval( - this.reloadHubAssistants.bind(this), - PlatformProfileLoader.RELOAD_INTERVAL, - ); - } else { - try { - const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); - }); - - await this.updateAvailableProfiles(profiles); - } catch (e: any) { - console.error("Failed to load profiles: ", e); - await this.loadLocalProfilesOnly(); - } - } - } - - async getPersistedSelectedProfileId(): Promise { - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - return lastSelectedIds[workspaceId] ?? null; - } - - async getSelectedOrgId(): Promise { - const selectedOrgs = - this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - const workspaceId = await this.getWorkspaceId(); - return selectedOrgs[workspaceId] ?? null; - } - - async setSelectedOrgId(orgId: string | null) { - const selectedOrgs = - this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - selectedOrgs[await this.getWorkspaceId()] = orgId; - this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); - this.didSelectOrganization?.(orgId); - } - - async setSelectedProfile(profileId: string | null) { - this.selectedProfileId = profileId; - const result = await this.loadConfig(); - this.notifyConfigListeners(result); - const selectedProfiles = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - selectedProfiles[await this.getWorkspaceId()] = profileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - selectedProfiles, - ); - } - - // A unique ID for the current workspace, built from folder names - private async getWorkspaceId(): Promise { - const dirs = await this.ide.getWorkspaceDirs(); - return dirs.join("&"); - } - - // Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed - updateIdeSettings(ideSettings: IdeSettings) { + // Ide settings change: refresh session and cascade refresh from the top + async updateIdeSettings(ideSettings: IdeSettings) { this.ideSettingsPromise = Promise.resolve(ideSettings); - void this.reloadConfig(); + await this.cascadeInit(); } + // Session change: refresh session and cascade refresh from the top async updateControlPlaneSessionInfo( sessionInfo: ControlPlaneSessionInfo | undefined, ) { @@ -386,38 +318,97 @@ export class ConfigHandler { Promise.resolve(sessionInfo), this.ideSettingsPromise, ); + await this.cascadeInit(); + } - this.fetchControlPlaneProfiles().catch(async (e) => { - console.error("Failed to fetch control plane profiles: ", e); - await this.loadLocalProfilesOnly(); - await this.reloadConfig(); + // Org id: check id validity, save selection, switch and reload + async setSelectedOrgId(orgId: string, profileId?: string) { + if (orgId === this.currentOrg.id) { + return; + } + const org = this.organizations.find((org) => org.id === orgId); + if (!org) { + throw new Error(`Org ${orgId} not found`); + } + + const workspaceId = await this.getWorkspaceId(); + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + this.globalContext.update("lastSelectedOrgIdForWorkspace", { + ...selectedOrgs, + [workspaceId]: org.id, }); - } - private profilesListeners: (( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void)[] = []; - onDidChangeAvailableProfiles( - listener: ( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void, - ) { - this.profilesListeners.push(listener); - } + this.currentOrg = org; - private notifyProfileListeners( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) { - for (const listener of this.profilesListeners) { - listener(profiles, selectedProfileId); + if (profileId) { + this.setSelectedProfileId(profileId); + } else { + this.currentProfile = org.currentProfile; + await this.reloadConfig(); } } + // Profile id: check id validity, save selection, switch and reload + async setSelectedProfileId(profileId: string) { + if ( + this.currentProfile && + profileId === this.currentProfile.profileDescription.id + ) { + return; + } + const profile = this.currentOrg.profiles.find( + (profile) => profile.profileDescription.id === profileId, + ); + if (!profile) { + throw new Error(`Profile ${profileId} not found in current org`); + } + + const profileKey = await this.getProfileKey(this.currentOrg.id); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: profileId, + }); + + this.currentProfile = profile; + await this.reloadConfig(); + } + + // Bottom level of cascade: refresh the current profile + // IMPORTANT - must always refresh when switching profiles + // Because of e.g. MCP singleton and docs service using things from config + // Could improve this + async reloadConfig() { + if (!this.currentProfile) { + return { + config: undefined, + errors: [], + configLoadInterrupted: true, + }; + } + + for (const org of this.organizations) { + for (const profile of org.profiles) { + if ( + profile.profileDescription.id !== + this.currentProfile.profileDescription.id + ) { + profile.clearConfig(); + } + } + } + + const { config, errors, configLoadInterrupted } = + await this.currentProfile.reloadConfig(this.additionalContextProviders); + + this.notifyConfigListeners({ config, errors, configLoadInterrupted }); + return { config, errors, configLoadInterrupted }; + } + + // Listeners setup - can listen to current profile updates private notifyConfigListeners(result: ConfigResult) { - // Notify listeners that config changed for (const listener of this.updateListeners) { listener(result); } @@ -429,27 +420,9 @@ export class ConfigHandler { this.updateListeners.push(listener); } - // TODO: this isn't right, there are two different senses in which you want to "reload" - async reloadConfig() { - if (!this.currentProfile) { - return { - config: undefined, - errors: [], - configLoadInterrupted: true, - }; - } - - const { config, errors, configLoadInterrupted } = - await this.currentProfile.reloadConfig(this.additionalContextProviders); - - if (config) { - this.inactiveProfiles.forEach((profile) => profile.clearConfig()); - } - - this.notifyConfigListeners({ config, errors, configLoadInterrupted }); - return { config, errors, configLoadInterrupted }; - } - + // Methods for loading (without reloading) config + // Serialized for passing to GUI + // Load for just awaiting current config load promise for the profile async getSerializedConfig(): Promise< ConfigResult > { @@ -465,10 +438,6 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] | null { - return this.profiles?.map((p) => p.profileDescription) ?? null; - } - async loadConfig(): Promise> { if (!this.currentProfile) { return { @@ -482,28 +451,36 @@ export class ConfigHandler { ); } - async llmFromTitle(title?: string): Promise { - const { config } = await this.loadConfig(); - const model = config?.models.find((m) => m.title === title); - if (!model) { - if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) { - // Special case, make calls to Ollama before we have it in the config - const ollama = new Ollama({ - model: LOCAL_ONBOARDING_CHAT_MODEL, - }); - return ollama; - } else if (config?.models?.length) { - return config?.models[0]; - } - - throw new Error("No model found"); + async openConfigProfile(profileId?: string) { + let openProfileId = profileId || this.currentProfile?.profileDescription.id; + if (!openProfileId) { + return; + } + const profile = this.currentOrg.profiles.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { + await this.ide.openFile(profile.profileDescription.uri); + } else { + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); } - - return model; } + // Ancient method of adding custom providers through vs code + private additionalContextProviders: IContextProvider[] = []; registerCustomContextProvider(contextProvider: IContextProvider) { this.additionalContextProviders.push(contextProvider); void this.reloadConfig(); } + /** + * Retrieves the titles of additional context providers that are of type "submenu". + * + * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu". + */ + getAdditionalSubmenuContextProviders(): string[] { + return this.additionalContextProviders + .filter((provider) => provider.description.type === "submenu") + .map((provider) => provider.description.title); + } } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 9d4bd2842..d93ab9236 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -32,6 +32,16 @@ export interface OrganizationDescription { slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend } +export type OrgWithProfiles = OrganizationDescription & { + profiles: ProfileLifecycleManager[]; + currentProfile: ProfileLifecycleManager | null; +}; + +export type SerializedOrgWithProfiles = OrganizationDescription & { + profiles: ProfileDescription[]; + selectedProfileId: string | null; +}; + export class ProfileLifecycleManager { private savedConfigResult: ConfigResult | undefined; private savedBrowserConfigResult?: ConfigResult; diff --git a/core/config/load.ts b/core/config/load.ts index 1a3acd6c6..6473d3a51 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -8,7 +8,6 @@ import { ConfigValidationError, ModelRole, } from "@continuedev/config-yaml"; -import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as JSONC from "comment-json"; import * as tar from "tar"; @@ -27,6 +26,7 @@ import { IdeSettings, IdeType, ILLM, + ILLMLogger, LLMOptions, ModelDescription, RerankerDescription, @@ -37,7 +37,6 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index"; -import { AllRerankers } from "../context/allRerankers"; import { MCPManagerSingleton } from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; @@ -45,9 +44,8 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import { useHub } from "../control-plane/env"; -import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; -import { llmFromDescription } from "../llm/llms"; +import { LLMClasses, llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; import { LLMReranker } from "../llm/llms/llm"; @@ -72,7 +70,11 @@ import { localPathToUri } from "../util/pathToUri"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; -import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; +import { + getModelByRole, + isSupportedLanceDbCpuTargetForLinux, + serializePromptTemplates, +} from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -216,17 +218,27 @@ export function isContextProviderWithParams( } /** Only difference between intermediate and final configs is the `models` array */ -async function intermediateToFinalConfig( - config: Config, - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - writeLog: (log: string) => Promise, - workOsAccessToken: string | undefined, - loadPromptFiles: boolean = true, - allowFreeTrial: boolean = true, -): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { +async function intermediateToFinalConfig({ + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + workOsAccessToken, + loadPromptFiles = true, + allowFreeTrial = true, +}: { + config: Config; + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + workOsAccessToken: string | undefined; + loadPromptFiles?: boolean; + allowFreeTrial?: boolean; +}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { const errors: ConfigValidationError[] = []; // Auto-detect models @@ -238,7 +250,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, config.completionOptions, config.systemMessage, ); @@ -260,7 +272,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, copyOf(config.completionOptions), config.systemMessage, ); @@ -280,7 +292,7 @@ async function intermediateToFinalConfig( } else { const llm = new CustomLLMClass({ ...desc, - options: { ...desc.options, writeLog } as any, + options: { ...desc.options, logger: llmLogger } as any, }); if (llm.model === "AUTODETECT") { try { @@ -289,7 +301,11 @@ async function intermediateToFinalConfig( (modelName) => new CustomLLMClass({ ...desc, - options: { ...desc.options, model: modelName, writeLog }, + options: { + ...desc.options, + model: modelName, + logger: llmLogger, + }, }), ); @@ -343,7 +359,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, config.completionOptions, config.systemMessage, ); @@ -420,38 +436,32 @@ async function intermediateToFinalConfig( function getEmbeddingsILLM( embedConfig: EmbeddingsProviderDescription | ILLM | undefined, ): ILLM | null { - if (!embedConfig) { - return null; - } - if ("providerName" in embedConfig) { - return embedConfig; - } - const { provider, ...options } = embedConfig; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - return new embeddingsProviderClass(); - } else { - const llmOptions: LLMOptions = { - model: options.model ?? "UNSPECIFIED", - ...options, - }; - return new embeddingsProviderClass( - llmOptions, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...config.requestOptions, - ...options.requestOptions, - }), - ); + if (embedConfig) { + // config.ts-injected ILLM + if ("providerName" in embedConfig) { + return embedConfig; } - } else { - errors.push({ - fatal: false, - message: `Embeddings provider ${provider} not found. Using default`, - }); + const { provider, ...options } = embedConfig; + if (provider === "transformers.js") { + return new TransformersJsEmbeddingsProvider(); + } else { + const cls = LLMClasses.find((c) => c.providerName === provider); + if (cls) { + const llmOptions: LLMOptions = { + model: options.model ?? "UNSPECIFIED", + ...options, + }; + return new cls(llmOptions); + } else { + errors.push({ + fatal: false, + message: `Embeddings provider ${provider} not found`, + }); + } + } + } + if (ideInfo.ideType === "vscode") { + return new TransformersJsEmbeddingsProvider(); } return null; } @@ -464,11 +474,11 @@ async function intermediateToFinalConfig( if (!rerankingConfig) { return null; } + // config.ts-injected ILLM if ("providerName" in rerankingConfig) { return rerankingConfig; } const { name, params } = config.reranker as RerankerDescription; - const rerankerClass = AllRerankers[name]; if (name === "llm") { const llm = models.find((model) => model.title === params?.modelTitle); @@ -481,16 +491,20 @@ async function intermediateToFinalConfig( } else { return new LLMReranker(llm); } - } else if (rerankerClass) { - const llmOptions: LLMOptions = { - model: "rerank-2", - ...params, - }; - return new rerankerClass(llmOptions, (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...params?.requestOptions, - }), - ); + } else { + const cls = LLMClasses.find((c) => c.providerName === name); + if (cls) { + const llmOptions: LLMOptions = { + model: params?.model, + ...params, + }; + return new cls(llmOptions); + } else { + errors.push({ + fatal: false, + message: `Unknown reranking provider ${name}`, + }); + } } return null; } @@ -499,7 +513,6 @@ async function intermediateToFinalConfig( const continueConfig: ContinueConfig = { ...config, contextProviders, - models, tools: [...allTools], mcpServerStatuses: [], slashCommands: config.slashCommands ?? [], @@ -539,7 +552,7 @@ async function intermediateToFinalConfig( // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; if (inlineEditModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === inlineEditModel, ); if (match) { @@ -558,7 +571,7 @@ async function intermediateToFinalConfig( "applyCodeBlock", )?.title; if (applyBlockModel) { - const match = continueConfig.models.find( + const match = continueConfig.modelsByRole.chat.find( (m) => m.title === applyBlockModel, ); if (match) { @@ -598,10 +611,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { template: llm.template, completionOptions: llm.completionOptions, systemMessage: llm.systemMessage, + baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, - promptTemplates: llm.promptTemplates as any, + promptTemplates: serializePromptTemplates(llm.promptTemplates), capabilities: llm.capabilities, roles: llm.roles, + configurationStatus: llm.getConfigurationStatus(), }; } @@ -611,7 +626,6 @@ async function finalToBrowserConfig( ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map(llmToSerializedModelDescription), systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map( @@ -831,7 +845,7 @@ async function loadContinueConfigFromJson( ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, overrideConfigJson: SerializedContinueConfig | undefined, ): Promise> { @@ -925,15 +939,15 @@ async function loadContinueConfigFromJson( // Convert to final config format const { config: finalConfig, errors: finalErrors } = - await intermediateToFinalConfig( - intermediate, + await intermediateToFinalConfig({ + config: intermediate, ide, ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, - ); + }); return { config: finalConfig, errors: [...(errors ?? []), ...finalErrors], diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 85130676b..bf705fd95 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -7,6 +7,7 @@ import { ContinueConfig, IDE, IdeSettings, + ILLMLogger, SerializedContinueConfig, } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; @@ -27,7 +28,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, - private writeLog: (message: string) => Promise, + private llmLogger: ILLMLogger, private readonly onReload: () => void, ) { this.description = { @@ -61,18 +62,18 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { )) as any); const serializedConfig: SerializedContinueConfig = settings; - return await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.writeLog, - serializedConfig, - undefined, - undefined, - this.workspaceId, - undefined, - null, - ); + return await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: serializedConfig, + overrideConfigYaml: undefined, + platformConfigMetadata: undefined, + profileId: this.workspaceId, + overrideConfigYamlByPath: undefined, + orgScopeId: null, + }); } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 464d16804..5b73a13e6 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,7 +1,7 @@ import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; -import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; +import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; import { getPrimaryConfigFilePath } from "../../util/paths.js"; @@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader { private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, - private writeLog: (message: string) => Promise, + private llmLogger: ILLMLogger, private overrideAssistantFile?: | { path: string; content: string } | undefined, @@ -55,18 +55,18 @@ export default class LocalProfileLoader implements IProfileLoader { description: ProfileDescription; async doLoadConfig(): Promise> { - const result = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.writeLog, - undefined, - undefined, - undefined, - this.description.id, - this.overrideAssistantFile?.path, - null, - ); + const result = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: undefined, + overrideConfigYaml: undefined, + platformConfigMetadata: undefined, + profileId: this.description.id, + overrideConfigYamlByPath: this.overrideAssistantFile?.path, + orgScopeId: null, + }); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 468d3511a..66bea1ef2 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; -import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; +import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; @@ -21,33 +21,81 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - private constructor( - private configResult: ConfigResult, - private readonly ownerSlug: string, - private readonly packageSlug: string, - private readonly iconUrl: string, - private readonly versionSlug: string, - private readonly controlPlaneClient: ControlPlaneClient, - private readonly ide: IDE, - private ideSettingsPromise: Promise, - private writeLog: (message: string) => Promise, - readonly description: ProfileDescription, - private readonly orgScopeId: string | null, - ) {} + private configResult: ConfigResult; + private readonly ownerSlug: string; + private readonly packageSlug: string; + private readonly iconUrl: string; + private readonly versionSlug: string; + private readonly controlPlaneClient: ControlPlaneClient; + private readonly ide: IDE; + private ideSettingsPromise: Promise; + private llmLogger: ILLMLogger; + readonly description: ProfileDescription; + private readonly orgScopeId: string | null; - static async create( - configResult: ConfigResult, - ownerSlug: string, - packageSlug: string, - iconUrl: string, - versionSlug: string, - controlPlaneClient: ControlPlaneClient, - ide: IDE, - ideSettingsPromise: Promise, - writeLog: (message: string) => Promise, - rawYaml: string, - orgScopeId: string | null, - ): Promise { + private constructor({ + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + llmLogger, + description, + orgScopeId, + }: { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + versionSlug: string; + controlPlaneClient: ControlPlaneClient; + ide: IDE; + ideSettingsPromise: Promise; + llmLogger: ILLMLogger; + description: ProfileDescription; + orgScopeId: string | null; + }) { + this.configResult = configResult; + this.ownerSlug = ownerSlug; + this.packageSlug = packageSlug; + this.iconUrl = iconUrl; + this.versionSlug = versionSlug; + this.controlPlaneClient = controlPlaneClient; + this.ide = ide; + this.ideSettingsPromise = ideSettingsPromise; + this.llmLogger = llmLogger; + this.description = description; + this.orgScopeId = orgScopeId; + } + + static async create({ + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + llmLogger, + rawYaml, + orgScopeId, + }: { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + versionSlug: string; + controlPlaneClient: ControlPlaneClient; + ide: IDE; + ideSettingsPromise: Promise; + llmLogger: ILLMLogger; + rawYaml: string; + orgScopeId: string | null; + }): Promise { const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); const description: ProfileDescription = { @@ -65,7 +113,7 @@ export default class PlatformProfileLoader implements IProfileLoader { rawYaml, }; - return new PlatformProfileLoader( + return new PlatformProfileLoader({ configResult, ownerSlug, packageSlug, @@ -74,10 +122,10 @@ export default class PlatformProfileLoader implements IProfileLoader { controlPlaneClient, ide, ideSettingsPromise, - writeLog, + llmLogger, description, orgScopeId, - ); + }); } async doLoadConfig(): Promise> { @@ -89,21 +137,21 @@ export default class PlatformProfileLoader implements IProfileLoader { }; } - const results = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.writeLog, - undefined, - this.configResult.config, - { + const results = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: undefined, + overrideConfigYaml: this.configResult.config, + platformConfigMetadata: { ownerSlug: this.ownerSlug, packageSlug: this.packageSlug, }, - this.description.id, - undefined, - this.orgScopeId, - ); + profileId: this.description.id, + overrideConfigYamlByPath: undefined, + orgScopeId: this.orgScopeId, + }); return { config: results.config, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 6351c4474..c7678f216 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -12,6 +12,7 @@ import { ContinueRcJson, IDE, IdeSettings, + ILLMLogger, SerializedContinueConfig, Tool, } from "../../"; @@ -35,18 +36,29 @@ import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -export default async function doLoadConfig( - ide: IDE, - ideSettingsPromise: Promise, - controlPlaneClient: ControlPlaneClient, - writeLog: (message: string) => Promise, - overrideConfigJson: SerializedContinueConfig | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - profileId: string, - overrideConfigYamlByPath: string | undefined, - orgScopeId: string | null, -): Promise> { +export default async function doLoadConfig({ + ide, + ideSettingsPromise, + controlPlaneClient, + llmLogger, + overrideConfigJson, + overrideConfigYaml, + platformConfigMetadata, + profileId, + overrideConfigYamlByPath, + orgScopeId, +}: { + ide: IDE; + ideSettingsPromise: Promise; + controlPlaneClient: ControlPlaneClient; + llmLogger: ILLMLogger; + overrideConfigJson: SerializedContinueConfig | undefined; + overrideConfigYaml: AssistantUnrolled | undefined; + platformConfigMetadata: PlatformConfigMetadata | undefined; + profileId: string; + overrideConfigYamlByPath: string | undefined; + orgScopeId: string | null; +}): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); @@ -69,19 +81,18 @@ export default async function doLoadConfig( let configLoadInterrupted = false; if (overrideConfigYaml || fs.existsSync(configYamlPath)) { - const result = await loadContinueConfigFromYaml( + const result = await loadContinueConfigFromYaml({ ide, ideSettings, ideInfo, uniqueId, - writeLog, - workOsAccessToken, + llmLogger, overrideConfigYaml, platformConfigMetadata, controlPlaneClient, configYamlPath, orgScopeId, - ); + }); newConfig = result.config; errors = result.errors; configLoadInterrupted = result.configLoadInterrupted; @@ -92,7 +103,7 @@ export default async function doLoadConfig( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, overrideConfigJson, ); @@ -160,6 +171,7 @@ export default async function doLoadConfig( const serverContextProvider = new MCPContextProvider({ submenuItems, mcpId: server.id, + serverName: server.name, }); newConfig.contextProviders.push(serverContextProvider); } @@ -256,7 +268,7 @@ async function injectControlPlaneProxyInfo( } }); - config.models.forEach((model) => { + config.modelsByRole.chat.forEach((model) => { if (model.providerName === "continue-proxy") { (model as ContinueProxy).controlPlaneProxyInfo = info; } diff --git a/core/config/selectedModels.ts b/core/config/selectedModels.ts index dd537665d..42b966cf7 100644 --- a/core/config/selectedModels.ts +++ b/core/config/selectedModels.ts @@ -1,6 +1,7 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ContinueConfig, ILLM } from ".."; +import { LLMConfigurationStatuses } from "../llm/constants"; import { GlobalContext, GlobalContextModelSelections, @@ -19,19 +20,20 @@ export function rectifySelectedModelsFromGlobalContext( let fellBack = false; - // chat and summarize not implemented yet - // default chat model is stored in GUI still - + // summarize not implemented yet const roles: ModelRole[] = [ "autocomplete", "apply", "edit", "embed", "rerank", + "chat", ]; + for (const role of roles) { let newModel: ILLM | null = null; const currentSelection = currentForProfile[role] ?? null; + if (currentSelection) { const match = continueConfig.modelsByRole[role].find( (m) => m.title === currentSelection, @@ -40,12 +42,23 @@ export function rectifySelectedModelsFromGlobalContext( newModel = match; } } + if (!newModel && continueConfig.modelsByRole[role].length > 0) { newModel = continueConfig.modelsByRole[role][0]; } + if (!(currentSelection === (newModel?.title ?? null))) { fellBack = true; } + + // Currently only check for configuration status for apply + if ( + role === "apply" && + newModel?.getConfigurationStatus() !== LLMConfigurationStatuses.VALID + ) { + continue; + } + configCopy.selectedModelByRole[role] = newModel; } diff --git a/core/config/types.ts b/core/config/types.ts index 2a68c4c35..3cf978540 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -90,7 +90,7 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + llmLogger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; @@ -433,6 +433,94 @@ declare global { export type ToastType = "info" | "error" | "warning"; + export interface LLMInteractionBase { + interactionId: string; + timestamp: number; + } + + export interface LLMInteractionStartChat extends LLMInteractionBase { + kind: "startChat"; + messages: ChatMessage[]; + options: CompletionOptions; + } + + export interface LLMInteractionStartComplete extends LLMInteractionBase { + kind: "startComplete"; + prompt: string; + options: CompletionOptions; + } + + export interface LLMInteractionStartFim extends LLMInteractionBase { + kind: "startFim"; + prefix: string; + suffix: string; + options: CompletionOptions; + } + + export interface LLMInteractionChunk extends LLMInteractionBase { + kind: "chunk"; + chunk: string; + } + + export interface LLMInteractionMessage extends LLMInteractionBase { + kind: "message"; + message: ChatMessage; + } + + export interface LLMInteractionEnd extends LLMInteractionBase { + promptTokens: number; + generatedTokens: number; + thinkingTokens: number; + } + + export interface LLMInteractionSuccess extends LLMInteractionEnd { + kind: "success"; + } + + export interface LLMInteractionCancel extends LLMInteractionEnd { + kind: "cancel"; + } + + export interface LLMInteractionError extends LLMInteractionEnd { + kind: "error"; + name: string; + message: string; + } + + export type LLMInteractionItem = + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim + | LLMInteractionChunk + | LLMInteractionMessage + | LLMInteractionSuccess + | LLMInteractionCancel + | LLMInteractionError; + + // When we log a LLM interaction, we want to add the interactionId and timestamp + // in the logger code, so we need a type that omits these members from *each* + // member of the union. This can be done by using the distributive behavior of + // conditional types in Typescript. + // + // www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s + type DistributiveOmit = T extends unknown + ? Omit + : never; + + export type LLMInteractionItemDetails = DistributiveOmit< + LLMInteractionItem, + "interactionId" | "timestamp" + >; + + export interface ILLMInteractionLog { + logItem(item: LLMInteractionItemDetails): void; + } + + export interface ILLMLogger { + createInteractionLog(): ILLMInteractionLog; + } + export interface LLMOptions { model: string; @@ -446,7 +534,7 @@ declare global { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; aiGatewaySlug?: string; diff --git a/core/config/util.test.ts b/core/config/util.test.ts new file mode 100644 index 000000000..e7de79e1b --- /dev/null +++ b/core/config/util.test.ts @@ -0,0 +1,45 @@ +import { PromptTemplate } from ".."; +import { serializePromptTemplates } from "./util"; + +describe("serializePromptTemplates", () => { + it("should return undefined for undefined input", () => { + expect(serializePromptTemplates(undefined)).toBeUndefined(); + }); + + it("should convert function templates to empty strings", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + template1: functionTemplate, + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ template1: "" }); + }); + + it("should pass through string templates unchanged", () => { + const templates: Record = { + template1: "This is a static template", + template2: "Another static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual(templates); + }); + + it("should handle mixed template types", () => { + const functionTemplate: PromptTemplate = () => "Generated template"; + const templates: Record = { + function: functionTemplate, + string: "This is a static template", + }; + + const result = serializePromptTemplates(templates); + + expect(result).toEqual({ + function: "", + string: "This is a static template", + }); + }); +}); diff --git a/core/config/util.ts b/core/config/util.ts index ee827c2f9..4c70acb38 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -7,6 +7,7 @@ import { IDE, ILLM, ModelDescription, + PromptTemplate, } from "../"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -94,7 +95,7 @@ export function getModelByRole( return undefined; } - const matchingModel = config.models.find( + const matchingModel = config.modelsByRole.chat.find( (model) => model.title === roleTitle, ); @@ -169,3 +170,22 @@ async function showUnsupportedCpuToast(ide: IDE) { ); } } + +/** + * This is required because users are only able to define prompt templates as a + * string, while internally we also allow prompt templates to be functions + * @param templates + * @returns + */ +export function serializePromptTemplates( + templates: Record | undefined, +): Record | undefined { + if (!templates) return undefined; + + return Object.fromEntries( + Object.entries(templates).map(([key, template]) => { + const serialized = typeof template === "function" ? "" : template; + return [key, serialized]; + }), + ); +} diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 072dc79de..dbc567005 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -2,6 +2,9 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { SerializedContinueConfig } from "../.."; +/* +TODO this is not functional +*/ export function convertConfigJsonToConfigYaml( configJson: SerializedContinueConfig, ): AssistantUnrolled { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..7939a7e83 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -5,6 +5,7 @@ import { ConfigResult, ConfigValidationError, FQSN, + isAssistantUnrolledNonNullable, ModelRole, PlatformClient, RegistryClient, @@ -12,7 +13,6 @@ import { unrollAssistantFromContent, validateConfigYaml, } from "@continuedev/config-yaml"; -import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ContinueConfig, @@ -20,16 +20,15 @@ import { IDE, IdeInfo, IdeSettings, + ILLMLogger, } from "../.."; import { slashFromCustomCommand } from "../../commands"; -import { AllRerankers } from "../../context/allRerankers"; import { MCPManagerSingleton } from "../../context/mcp"; import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; import { ControlPlaneClient } from "../../control-plane/client"; -import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders"; import FreeTrial from "../../llm/llms/FreeTrial"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; @@ -92,7 +91,15 @@ async function loadConfigYaml( renderSecrets: true, }, )); - const errors = validateConfigYaml(config); + + const errors = isAssistantUnrolledNonNullable(config) + ? validateConfigYaml(config) + : [ + { + fatal: true, + message: "Assistant includes blocks that don't exist", + }, + ]; if (errors?.some((error) => error.fatal)) { return { @@ -110,41 +117,32 @@ async function loadConfigYaml( }; } -async function configYamlToContinueConfig( - config: AssistantUnrolled, - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - writeLog: (log: string) => Promise, - workOsAccessToken: string | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - allowFreeTrial: boolean = true, -): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { +async function configYamlToContinueConfig({ + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + platformConfigMetadata, + allowFreeTrial = true, +}: { + config: AssistantUnrolled; + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + allowFreeTrial: boolean; +}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { const localErrors: ConfigValidationError[] = []; + const continueConfig: ContinueConfig = { slashCommands: [], - models: [], tools: [...allTools], mcpServerStatuses: [], systemMessage: config.rules?.join("\n"), - experimental: { - modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ - transport: { - type: "stdio", - command: mcpServer.command, - args: mcpServer.args ?? [], - env: mcpServer.env, - }, - })), - }, - docs: config.docs?.map((doc) => ({ - title: doc.name, - startUrl: doc.startUrl, - rootUrl: doc.rootUrl, - faviconUrl: doc.faviconUrl, - })), - rules: config.rules, contextProviders: [], modelsByRole: { chat: [], @@ -156,7 +154,7 @@ async function configYamlToContinueConfig( summarize: [], }, selectedModelByRole: { - chat: null, // not currently used - defaultModel on GUI is used + chat: null, edit: null, // not currently used apply: null, embed: null, @@ -164,7 +162,38 @@ async function configYamlToContinueConfig( rerank: null, summarize: null, }, - data: config.data, + }; + + // Right now, if there are any missing packages in the config, then we will just throw an error + if (!isAssistantUnrolledNonNullable(config)) { + return { + config: continueConfig, + errors: [ + { + message: "Found missing blocks in config.yaml", + fatal: true, + }, + ], + }; + } + + continueConfig.data = config.data; + continueConfig.rules = config.rules; + continueConfig.docs = config.docs?.map((doc) => ({ + title: doc.name, + startUrl: doc.startUrl, + rootUrl: doc.rootUrl, + faviconUrl: doc.faviconUrl, + })); + continueConfig.experimental = { + modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ + transport: { + type: "stdio", + command: mcpServer.command, + args: mcpServer.args ?? [], + env: mcpServer.env, + }, + })), }; // Prompt files - @@ -211,19 +240,15 @@ async function configYamlToContinueConfig( for (const model of config.models ?? []) { model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified try { - const llms = await llmsFromModelConfig( + const llms = await llmsFromModelConfig({ model, ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, - continueConfig.systemMessage, - ); - - if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - continueConfig.models.push(...llms); - } + config: continueConfig, + }); if (model.roles?.includes("chat")) { continueConfig.modelsByRole.chat.push(...llms); @@ -246,59 +271,25 @@ async function configYamlToContinueConfig( } if (model.roles?.includes("embed")) { - const { provider, ...options } = model; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { + const { provider } = model; + if (provider === "transformers.js") { + if (ideInfo.ideType === "vscode") { continueConfig.modelsByRole.embed.push( - new embeddingsProviderClass(), + new TransformersJsEmbeddingsProvider(), ); } else { - continueConfig.modelsByRole.embed.push( - new embeddingsProviderClass( - { - ...options, - title: options.name, - }, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ), - ); + localErrors.push({ + fatal: false, + message: `Transformers.js embeddings provider not supported in this IDE.`, + }); } } else { - localErrors.push({ - fatal: false, - message: `Unsupported embeddings model provider found: ${provider}`, - }); + continueConfig.modelsByRole.embed.push(...llms); } } if (model.roles?.includes("rerank")) { - const { provider, ...options } = model; - const rerankerClass = AllRerankers[provider]; - if (rerankerClass) { - continueConfig.modelsByRole.rerank.push( - new rerankerClass( - { - ...options, - title: options.name, - }, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ), - ); - } else { - localErrors.push({ - fatal: false, - message: `Unsupported reranking model provider found: ${provider}`, - }); - } + continueConfig.modelsByRole.rerank.push(...llms); } } catch (e) { localErrors.push({ @@ -322,7 +313,7 @@ async function configYamlToContinueConfig( if (allowFreeTrial) { // Obtain auth token (iff free trial being used) - const freeTrialModels = continueConfig.models.filter( + const freeTrialModels = continueConfig.modelsByRole.chat.filter( (model) => model.providerName === "free-trial", ); if (freeTrialModels.length > 0) { @@ -337,14 +328,15 @@ async function configYamlToContinueConfig( message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`, }); // Remove free trial models - continueConfig.models = continueConfig.models.filter( - (model) => model.providerName !== "free-trial", - ); + continueConfig.modelsByRole.chat = + continueConfig.modelsByRole.chat.filter( + (model) => model.providerName !== "free-trial", + ); } } } else { // Remove free trial models - continueConfig.models = continueConfig.models.filter( + continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter( (model) => model.providerName !== "free-trial", ); } @@ -407,19 +399,31 @@ async function configYamlToContinueConfig( return { config: continueConfig, errors: localErrors }; } -export async function loadContinueConfigFromYaml( - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - writeLog: (log: string) => Promise, - workOsAccessToken: string | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - controlPlaneClient: ControlPlaneClient, - configYamlPath: string | undefined, - orgScopeId: string | null, -): Promise> { +export async function loadContinueConfigFromYaml({ + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + // workOsAccessToken, + overrideConfigYaml, + platformConfigMetadata, + controlPlaneClient, + configYamlPath, + orgScopeId, +}: { + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + // workOsAccessToken: string | undefined; + overrideConfigYaml: AssistantUnrolled | undefined; + platformConfigMetadata: PlatformConfigMetadata | undefined; + controlPlaneClient: ControlPlaneClient; + configYamlPath: string | undefined; + orgScopeId: string | null; +}): Promise> { const rawYaml = overrideConfigYaml === undefined ? fs.readFileSync( @@ -445,16 +449,16 @@ export async function loadContinueConfigFromYaml( } const { config: continueConfig, errors: localErrors } = - await configYamlToContinueConfig( - configYamlResult.config, + await configYamlToContinueConfig({ + config: configYamlResult.config, ide, ideSettings, ideInfo, uniqueId, - writeLog, - workOsAccessToken, + llmLogger, platformConfigMetadata, - ); + allowFreeTrial: true, + }); try { const systemPromptDotFile = await getSystemPromptDotFile(ide); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 57caf324a..572d7eb70 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -1,6 +1,12 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { IDE, IdeSettings, LLMOptions } from "../.."; +import { + ContinueConfig, + IDE, + IdeSettings, + ILLMLogger, + LLMOptions, +} from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; @@ -13,22 +19,29 @@ function getModelClass( return LLMClasses.find((llm) => llm.providerName === model.provider); } -function getContinueProxyModelName( - ownerSlug: string, - packageSlug: string, - model: ModelConfig, -): string { - return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; -} +// function getContinueProxyModelName( +// ownerSlug: string, +// packageSlug: string, +// model: ModelConfig, +// ): string { +// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; +// } -async function modelConfigToBaseLLM( - model: ModelConfig, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function modelConfigToBaseLLM({ + model, + uniqueId, + ideSettings, + llmLogger, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + uniqueId: string; + ideSettings: IdeSettings; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { const cls = getModelClass(model); if (!cls) { @@ -39,7 +52,7 @@ async function modelConfigToBaseLLM( let options: LLMOptions = { ...rest, - // contextLength: model.defaultCompletionOptions?.contextLength ?? undefined, + contextLength: model.defaultCompletionOptions?.contextLength, completionOptions: { ...(model.defaultCompletionOptions ?? {}), model: model.model, @@ -47,11 +60,13 @@ async function modelConfigToBaseLLM( model.defaultCompletionOptions?.maxTokens ?? cls.defaultOptions?.completionOptions?.maxTokens, }, - writeLog, + logger: llmLogger, uniqueId, title: model.name, - systemMessage, + systemMessage: config.systemMessage, + rules: config.rules, promptTemplates: model.promptTemplates, + baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { tools: model.capabilities?.includes("tool_use"), uploadImage: model.capabilities?.includes("image_input"), @@ -127,16 +142,25 @@ async function modelConfigToBaseLLM( return llm; } -async function autodetectModels( - llm: BaseLLM, - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function autodetectModels({ + llm, + model, + ide, + uniqueId, + ideSettings, + llmLogger, + platformConfigMetadata, + config, +}: { + llm: BaseLLM; + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { try { const modelNames = await llm.listModels(); const detectedModels = await Promise.all( @@ -146,18 +170,18 @@ async function autodetectModels( return undefined; } - return await modelConfigToBaseLLM( - { + return await modelConfigToBaseLLM({ + model: { ...model, model: modelName, name: modelName, }, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, - systemMessage, - ); + config, + }); }), ); return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[]; @@ -167,38 +191,46 @@ async function autodetectModels( } } -export async function llmsFromModelConfig( - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { - const baseLlm = await modelConfigToBaseLLM( +export async function llmsFromModelConfig({ + model, + ide, + uniqueId, + ideSettings, + llmLogger, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { + const baseLlm = await modelConfigToBaseLLM({ model, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, - systemMessage, - ); + config, + }); if (!baseLlm) { return []; } if (model.model === AUTODETECT) { - const models = await autodetectModels( - baseLlm, + const models = await autodetectModels({ + llm: baseLlm, model, ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, - systemMessage, - ); + config, + }); return models; } else { return [baseLlm]; diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts deleted file mode 100644 index 944a77dbc..000000000 --- a/core/context/allRerankers.ts +++ /dev/null @@ -1,19 +0,0 @@ -import Bedrock from "../llm/llms/Bedrock"; -import Cohere from "../llm/llms/Cohere"; -import FreeTrial from "../llm/llms/FreeTrial"; -import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI"; -import { LLMReranker } from "../llm/llms/llm"; -import ContinueProxy from "../llm/llms/stubs/ContinueProxy"; -import Voyage from "../llm/llms/Voyage"; -import WatsonX from "../llm/llms/WatsonX"; - -export const AllRerankers: { [key: string]: any } = { - cohere: Cohere, - bedrock: Bedrock, - llm: LLMReranker, - voyage: Voyage, - watsonx: WatsonX, - "free-trial": FreeTrial, - "huggingface-tei": HuggingFaceTEI, - "continue-proxy": ContinueProxy, -}; diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts index 42df6ab34..b4d2e0e09 100644 --- a/core/context/providers/FolderContextProvider.ts +++ b/core/context/providers/FolderContextProvider.ts @@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider { const folders = await walkDirs( args.ide, { - onlyDirs: true, + include: "dirs", source: "load submenu items - folder", }, workspaceDirs, diff --git a/core/context/providers/GitCommitContextProvider.ts b/core/context/providers/GitCommitContextProvider.ts index 24d2eab7b..e387b2f66 100644 --- a/core/context/providers/GitCommitContextProvider.ts +++ b/core/context/providers/GitCommitContextProvider.ts @@ -1,12 +1,40 @@ +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { - ContextItem, - ContextProviderDescription, - ContextProviderExtras, - ContextSubmenuItem, - LoadSubmenuItemsArgs, - } from "../../index.js"; + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../index.js"; import { BaseContextProvider } from "../index.js"; -import { fileURLToPath} from "node:url"; + +const runGitCommand = (args: string[], cwd: string): Promise => { + return new Promise((resolve, reject) => { + // First argument is the command, rest are arguments + const gitProcess = spawn("git", args, { + cwd, + }); + let stdout = ""; + let stderr = ""; + + gitProcess.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + gitProcess.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + gitProcess.on("close", (code) => { + if (code !== 0) { + reject(new Error(`Git command failed: ${stderr}`)); + return; + } + resolve(stdout); + }); + }); +}; class GitCommitContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -16,29 +44,55 @@ class GitCommitContextProvider extends BaseContextProvider { type: "submenu", }; - async getContextItems(query: string, extras: ContextProviderExtras): Promise { + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10; + if (typeof lastXCommitsDepth !== "number") { + throw new Error("LastXCommitsDepth must be a number"); + } const topLevelDir = fileURLToPath((await extras.ide.getWorkspaceDirs())[0]); - try{ - if(query.includes("last ")){ + + try { + if (query.includes("last ")) { + const content = await runGitCommand( + [ + "--no-pager", + "log", + '--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"', + "-p", + "-n", + lastXCommitsDepth.toString(), + ], + topLevelDir, + ); return [ { - name: query, - description: query, - content: (await extras.ide.subprocess(`git --no-pager log --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" -p -n ${lastXCommitsDepth}`, topLevelDir))[0], - } - ] - } - else{ + name: query, + description: query, + content, + }, + ]; + } else { + const content = await runGitCommand( + [ + "--no-pager", + "show", + '--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"', + query, + ], + topLevelDir, + ); return [ { name: query, description: `commit ${query}`, - content: (await extras.ide.subprocess(`git --no-pager show --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" ${query}`, topLevelDir))[0], - } - ] + content, + }, + ]; } - }catch(err){ + } catch (err) { return []; } } @@ -48,24 +102,48 @@ class GitCommitContextProvider extends BaseContextProvider { ): Promise { const depth = this.options?.Depth ?? 50; const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10; - const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]); - try{ - const [gitResult] = await args.ide.subprocess(`git --no-pager log --pretty=format:"%H%x00%s" -n ${depth}`, topLevelDir); - const recentCommits = [{ id: `last ${lastXCommitsDepth} commits`, title: `last ${lastXCommitsDepth} commits`, description: "recent commits" }]; - const allCommits = gitResult - .trim() - .split('\n') - .map(line => { - const [hash, message] = line.split("\0"); - return { - id: hash, - title: message, - description: hash - }; - } + + if (typeof depth !== "number") { + throw new Error("Depth must be a number"); + } + if (typeof lastXCommitsDepth !== "number") { + throw new Error("LastXCommitsDepth must be a number"); + } + + const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]); + try { + const gitResult = await runGitCommand( + [ + "--no-pager", + "log", + '--pretty=format:"%H%x00%s"', + `-n`, + depth.toString(), + ], + topLevelDir, ); + const recentCommits = [ + { + id: `last ${lastXCommitsDepth} commits`, + title: `last ${lastXCommitsDepth} commits`, + description: "recent commits", + }, + ]; + const allCommits = gitResult + .trim() + .split("\n") + .map((line) => { + let [hash, message] = line.split("\0"); + hash = hash.replace(/"/g, ""); + message = message.replace(/"/g, ""); + return { + id: hash, + title: message, + description: hash, + }; + }); return recentCommits.concat(allCommits); - }catch(err: any){ + } catch (err: any) { //could be nice to toast the error eg. not a git repo or git is not installed return []; } diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 0cb8e2c66..be9e50cd5 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -10,6 +10,7 @@ import { MCPManagerSingleton } from "../mcp"; interface MCPContextProviderOptions { mcpId: string; + serverName: string; submenuItems: ContextSubmenuItem[]; } @@ -20,6 +21,16 @@ class MCPContextProvider extends BaseContextProvider { description: "Model Context Protocol", type: "submenu", }; + override get description(): ContextProviderDescription { + return { + title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`, + displayTitle: this.options["serverName"] + ? `${this.options["serverName"]} resources` + : "MCP", + description: "Model Context Protocol", + type: "submenu", + }; + } static encodeMCPResourceId(mcpId: string, uri: string): string { return JSON.stringify({ mcpId, uri }); diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 6a2db46fa..575e7af4b 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -54,7 +54,7 @@ class RepoMapContextProvider extends BaseContextProvider { const folders = await walkDirs( args.ide, { - onlyDirs: true, + include: "dirs", source: "load submenu items - repo map", }, workspaceDirs, diff --git a/core/context/providers/SearchContextProvider.ts b/core/context/providers/SearchContextProvider.ts index bc44964ac..ec75994c3 100644 --- a/core/context/providers/SearchContextProvider.ts +++ b/core/context/providers/SearchContextProvider.ts @@ -3,6 +3,7 @@ import { ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; +import { formatGrepSearchResults } from "../../util/grepSearch.js"; import { BaseContextProvider } from "../index.js"; class SearchContextProvider extends BaseContextProvider { @@ -19,10 +20,11 @@ class SearchContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { const results = await extras.ide.getSearchResults(query); + const formatted = formatGrepSearchResults(results); return [ { description: "Search results", - content: `Results of searching codebase for "${query}":\n\n${results}`, + content: `Results of searching codebase for "${query}":\n\n${formatted}`, name: "Search results", }, ]; diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 345d21e37..468aac6ec 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -7,6 +7,7 @@ import { IContextProvider, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; +import { LLMLogger } from "../../llm/logger"; import { TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; @@ -26,13 +27,13 @@ async function getContextProviderExtras( ): Promise { const ide = new FileSystemIde(TEST_DIR); const ideSettingsPromise = ide.getIdeSettings(); + const llmLogger = new LLMLogger(); const configHandler = new ConfigHandler( ide, ideSettingsPromise, - async (text) => {}, + llmLogger, Promise.resolve(undefined), ); - await configHandler.initializedPromise; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); @@ -44,7 +45,7 @@ async function getContextProviderExtras( config, embeddingsProvider: config.selectedModelByRole.embed, fetch: fetch, - llm: config.models[0], + llm: config.modelsByRole.chat[0], reranker: config.selectedModelByRole.rerank, selectedCode: [], }; diff --git a/core/core.ts b/core/core.ts index 11fecffb2..68aa605ac 100644 --- a/core/core.ts +++ b/core/core.ts @@ -5,11 +5,6 @@ import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; -import { - setupBestConfig, - setupLocalConfig, - setupQuickstartConfig, -} from "./config/onboarding"; import { addModel, deleteModel } from "./config/util"; import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; @@ -19,9 +14,9 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { getControlPlaneEnv } from "./control-plane/env"; import { DevDataSqliteDb } from "./data/devdataSqlite"; import { DataLogger } from "./data/log"; -import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { countTokens } from "./llm/countTokens"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -36,6 +31,9 @@ import { TTS } from "./util/tts"; import { DiffLine, + IdeSettings, + ModelDescription, + RangeInFile, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -43,13 +41,51 @@ import { import { ConfigYaml } from "@continuedev/config-yaml"; import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { + setupBestConfig, + setupLocalConfig, + setupQuickstartConfig, +} from "./config/onboarding"; import { MCPManagerSingleton } from "./context/mcp"; +import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; +import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; +async function* streamDiffLinesGenerator( + configHandler: ConfigHandler, + abortedMessageIds: Set, + msg: Message, +): AsyncGenerator { + const data = msg.data; + const llm = (await configHandler.loadConfig()).config?.selectedModelByRole + .chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + for await (const diffLine of streamDiffLines( + data.prefix, + data.highlighted, + data.suffix, + llm, + data.input, + data.language, + false, + undefined, + )) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + break; + } + yield diffLine; + } +} + export class Core { configHandler: ConfigHandler; codebaseIndexerPromise: Promise; @@ -58,6 +94,7 @@ export class Core { codebaseIndexingState: IndexingProgressUpdate; private docsService: DocsService; private globalContext = new GlobalContext(); + llmLogger = new LLMLogger(); private readonly indexingPauseToken = new PauseToken( this.globalContext.get("indexingPaused") === true, @@ -85,7 +122,6 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created migrateV1DevDataFiles(); @@ -106,13 +142,8 @@ export class Core { this.configHandler = new ConfigHandler( this.ide, ideSettingsPromise, - this.onWrite, + this.llmLogger, sessionInfoPromise, - (orgId: string | null) => { - void messenger.request("didSelectOrganization", { - orgId, - }); - }, ); this.docsService = DocsService.createSingleton( @@ -121,10 +152,7 @@ export class Core { this.messenger, ); - const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.onConnectionsRefreshed = async () => { - // This ensures that it triggers a NEW load after waiting for config promise to finish - await this.configHandler.loadConfig(); + MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => { await this.configHandler.reloadConfig(); }; @@ -133,7 +161,11 @@ export class Core { this.messenger.send("configUpdate", { result: serializedResult, profileId: - this.configHandler.currentProfile?.profileDescription.id ?? null, + this.configHandler.currentProfile?.profileDescription.id || null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, + usingContinueForTeams: (await ideSettingsPromise) + .enableControlServerBeta, }); // update additional submenu context providers registered via VSCode API @@ -146,14 +178,6 @@ export class Core { } }); - this.configHandler.onDidChangeAvailableProfiles( - (profiles, selectedProfileId) => - this.messenger.send("didChangeAvailableProfiles", { - profiles, - selectedProfileId, - }), - ); - // Dev Data Logger const dataLogger = DataLogger.getInstance(); dataLogger.core = this; @@ -219,6 +243,10 @@ export class Core { (..._) => Promise.resolve([]), ); + this.registerMessageHandlers(ideSettingsPromise); + } + + private registerMessageHandlers(ideSettingsPromise: Promise) { const on = this.messenger.on.bind(this.messenger); // Note, VsCode's in-process messenger doesn't do anything with this @@ -308,15 +336,8 @@ export class Core { this.configHandler.updateIdeSettings(msg.data); }); - on("config/listProfiles", async (msg) => { - const profiles = this.configHandler.listProfiles(); - const selectedProfileId = - this.configHandler.currentProfile?.profileDescription.id ?? null; - return { profiles, selectedProfileId }; - }); - on("config/refreshProfiles", async (msg) => { - await this.configHandler.loadAssistantsForSelectedOrg(); + await this.configHandler.refreshAll(); }); on("config/updateSharedConfig", async (msg) => { @@ -344,12 +365,8 @@ export class Core { await this.messenger.request("openUrl", url); }); - on("controlPlane/listOrganizations", async (msg) => { - return await this.configHandler.listOrganizations(); - }); - on("mcp/reloadServer", async (msg) => { - mcpManager.refreshConnection(msg.data.id); + MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); // Context providers on("context/addDocs", async (msg) => { @@ -381,94 +398,7 @@ export class Core { return items || []; }); - on("context/getContextItems", async (msg) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - return []; - } - - const { name, query, fullInput, selectedCode, selectedModelTitle } = - msg.data; - - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const provider = - config.contextProviders?.find( - (provider) => provider.description.title === name, - ) ?? - [ - // user doesn't need these in their config.json for the shortcuts to work - // option+enter - new CurrentFileContextProvider({}), - // cmd+enter - new CodebaseContextProvider({}), - ].find((provider) => provider.description.title === name); - if (!provider) { - return []; - } - - try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; - - const items = await provider.getContextItems(query, { - config, - llm, - embeddingsProvider: config.selectedModelByRole.embed, - fullInput, - ide, - selectedCode, - reranker: config.selectedModelByRole.rerank, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - }); - - void Telemetry.capture( - "useContextProvider", - { - name: provider.description.title, - }, - true, - ); - - return items.map((item) => ({ - ...item, - id, - })); - } catch (e) { - let knownError = false; - - if (e instanceof Error) { - // After removing transformers JS embeddings provider from jetbrains - // Should no longer see this error - // if (e.message.toLowerCase().includes("embeddings provider")) { - // knownError = true; - // const toastOption = "See Docs"; - // void this.ide - // .showToast( - // "error", - // `Set up an embeddings model to use @${name}`, - // toastOption, - // ) - // .then((userSelection) => { - // if (userSelection === toastOption) { - // void this.ide.openUrl( - // "https://docs.continue.dev/customize/model-roles/embeddings", - // ); - // } - // }); - // } - } - if (!knownError) { - void this.ide.showToast( - "error", - `Error getting context items from ${name}: ${e}`, - ); - } - return []; - } - }); + on("context/getContextItems", this.getContextItems.bind(this)); on("context/getSymbolsForFiles", async (msg) => { const { uris } = msg.data; @@ -480,6 +410,10 @@ export class Core { result: await this.configHandler.getSerializedConfig(), profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, + usingContinueForTeams: (await ideSettingsPromise) + .enableControlServerBeta, }; }); @@ -497,13 +431,19 @@ export class Core { this.configHandler, this.abortedMessageIds, msg, - ide, + this.ide, this.messenger, ), ); on("llm/complete", async (msg) => { - const model = await this.configHandler.llmFromTitle(msg.data.title); + const model = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } + const completion = await model.complete( msg.data.prompt, new AbortController().signal, @@ -511,31 +451,7 @@ export class Core { ); return completion; }); - on("llm/listModels", async (msg) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - return []; - } - - const model = - config.models.find((model) => model.title === msg.data.title) ?? - config.models.find((model) => model.title?.startsWith(msg.data.title)); - try { - if (model) { - return await model.listModels(); - } else { - if (msg.data.title === "Ollama") { - const models = await new Ollama({ model: "" }).listModels(); - return models; - } else { - return undefined; - } - } - } catch (e) { - console.debug(`Error listing Ollama models: ${e}`); - return undefined; - } - }); + on("llm/listModels", this.handleListModels); // Provide messenger to utils so they can interact with GUI + state TTS.messenger = this.messenger; @@ -546,9 +462,13 @@ export class Core { }); on("chatDescriber/describe", async (msg) => { - const currentModel = await this.configHandler.llmFromTitle( - msg.data.selectedModelTitle, - ); + const currentModel = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!currentModel) { + throw new Error("No chat model selected"); + } + return await ChatDescriber.describe(currentModel, {}, msg.data.text); }); @@ -568,93 +488,13 @@ export class Core { this.completionProvider.cancel(); }); - async function* streamDiffLinesGenerator( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, - ): AsyncGenerator { - const data = msg.data; - const llm = await configHandler.llmFromTitle(msg.data.modelTitle); - for await (const diffLine of streamDiffLines( - data.prefix, - data.highlighted, - data.suffix, - llm, - data.input, - data.language, - false, - undefined, - )) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - yield diffLine; - } - } - on("streamDiffLines", (msg) => streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg), ); - on("completeOnboarding", (msg) => { - const mode = msg.data.mode; + on("completeOnboarding", this.handleCompleteOnboarding); - if (mode === "Custom") { - return; - } - - let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; - - switch (mode) { - case "Local": - editConfigYamlCallback = setupLocalConfig; - break; - - case "Quickstart": - editConfigYamlCallback = setupQuickstartConfig; - break; - - case "Best": - editConfigYamlCallback = setupBestConfig; - break; - - default: - console.error(`Invalid mode: ${mode}`); - editConfigYamlCallback = (config) => config; - } - - editConfigFile((c) => c, editConfigYamlCallback); - - void this.configHandler.reloadConfig(); - }); - - on("addAutocompleteModel", (msg) => { - const model = msg.data.model; - editConfigFile( - (config) => { - return { - ...config, - tabAutocompleteModel: model, - }; - }, - (config) => ({ - ...config, - models: [ - ...(config.models ?? []), - { - name: model.title, - provider: model.provider, - model: model.model, - apiKey: model.apiKey, - roles: ["autocomplete"], - apiBase: model.apiBase, - }, - ], - }), - ); - void this.configHandler.reloadConfig(); - }); + on("addAutocompleteModel", this.handleAddAutocompleteModel); on("stats/getTokensPerDay", async (msg) => { const rows = await DevDataSqliteDb.getTokensPerDay(); @@ -665,7 +505,6 @@ export class Core { return rows; }); - // Codebase indexing on("index/forceReIndex", async ({ data }) => { const { config } = await this.configHandler.loadConfig(); if (!config || config.disableIndexing) { @@ -697,63 +536,12 @@ export class Core { // File changes // TODO - remove remaining logic for these from IDEs where possible - on("files/changed", async ({ data }) => { - if (data?.uris?.length) { - walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes - for (const uri of data.uris) { - const currentProfileUri = - this.configHandler.currentProfile?.profileDescription.uri ?? ""; - - if (URI.equal(uri, currentProfileUri)) { - // Trigger a toast notification to provide UI feedback that config has been updated - const showToast = - this.globalContext.get("showConfigUpdateToast") ?? true; - if (showToast) { - const selection = await this.ide.showToast( - "info", - "Config updated", - "Don't show again", - ); - if (selection === "Don't show again") { - this.globalContext.update("showConfigUpdateToast", false); - } - } - await this.configHandler.reloadConfig(); - continue; - } - - if ( - uri.endsWith(".continuerc.json") || - uri.endsWith(".prompt") || - uri.endsWith(SYSTEM_PROMPT_DOT_FILE) - ) { - await this.configHandler.reloadConfig(); - } else if ( - uri.endsWith(".continueignore") || - uri.endsWith(".gitignore") - ) { - // Reindex the workspaces - this.invoke("index/forceReIndex", { - shouldClearIndexes: true, - }); - } else { - const { config } = await this.configHandler.loadConfig(); - if (config && !config.disableIndexing) { - // Reindex the file - const ignore = await shouldIgnore(uri, this.ide); - if (!ignore) { - await this.refreshCodebaseIndexFiles([uri]); - } - } - } - } - } - }); + on("files/changed", this.handleFilesChanged); const refreshIfNotIgnored = async (uris: string[]) => { const toRefresh: string[] = []; for (const uri of uris) { - const ignore = await shouldIgnore(uri, ide); + const ignore = await shouldIgnore(uri, this.ide); if (!ignore) { toRefresh.push(uri); } @@ -775,11 +563,15 @@ export class Core { void refreshIfNotIgnored(data.uris); // If it's a local assistant being created, we want to reload all assistants so it shows up in the list + let localAssistantCreated = false; for (const uri of data.uris) { if (isLocalAssistantFile(uri)) { - await this.configHandler.loadAssistantsForSelectedOrg(); + localAssistantCreated = true; } } + if (localAssistantCreated) { + await this.configHandler.refreshAll(); + } } }); @@ -798,11 +590,7 @@ export class Core { } }); - on("files/opened", async ({ data }) => { - if (data?.uris?.length) { - // Do something on files opened - } - }); + on("files/opened", async () => {}); // Docs, etc. indexing on("indexing/reindex", async (msg) => { @@ -817,7 +605,6 @@ export class Core { }); on("indexing/setPaused", async (msg) => { if (msg.data.type === "docs") { - // this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet } }); on("docs/initStatuses", async (msg) => { @@ -829,20 +616,14 @@ export class Core { // on("didChangeSelectedProfile", async (msg) => { - await this.configHandler.setSelectedProfile(msg.data.id); - await this.configHandler.reloadConfig(); + await this.configHandler.setSelectedProfileId(msg.data.id); }); on("didChangeSelectedOrg", async (msg) => { - await this.configHandler.setSelectedOrgId(msg.data.id); - await this.configHandler.loadAssistantsForSelectedOrg(); - if (msg.data.profileId) { - this.invoke("didChangeSelectedProfile", { - id: msg.data.profileId, - }); - } else { - await this.configHandler.reloadConfig(); - } + await this.configHandler.setSelectedOrgId( + msg.data.id, + msg.data.profileId, + ); }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -850,6 +631,7 @@ export class Core { msg.data.sessionInfo, ); }); + on("auth/getAuthUrl", async (msg) => { const url = await getAuthUrlForTokenPage( ideSettingsPromise, @@ -885,7 +667,12 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } const contextItems = await callTool( tool, @@ -907,8 +694,284 @@ export class Core { return { contextItems }; }); + + on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + const { config } = await this.configHandler.loadConfig(); + + if (!config) { + return false; + } + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + const tokens = countTokens(item.content); + + if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { + return true; + } + + return false; + }); } + private handleAddAutocompleteModel( + msg: Message<{ + model: ModelDescription; + }>, + ) { + const model = msg.data.model; + editConfigFile( + (config) => { + return { + ...config, + tabAutocompleteModel: model, + }; + }, + (config) => ({ + ...config, + models: [ + ...(config.models ?? []), + { + name: model.title, + provider: model.provider, + model: model.model, + apiKey: model.apiKey, + roles: ["autocomplete"], + apiBase: model.apiBase, + }, + ], + }), + ); + void this.configHandler.reloadConfig(); + } + + private async handleFilesChanged({ + data, + }: Message<{ + uris?: string[]; + }>) { + if (data?.uris?.length) { + walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes + for (const uri of data.uris) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { + // Trigger a toast notification to provide UI feedback that config has been updated + const showToast = + this.globalContext.get("showConfigUpdateToast") ?? true; + if (showToast) { + const selection = await this.ide.showToast( + "info", + "Config updated", + "Don't show again", + ); + if (selection === "Don't show again") { + this.globalContext.update("showConfigUpdateToast", false); + } + } + await this.configHandler.reloadConfig(); + continue; + } + + if ( + uri.endsWith(".continuerc.json") || + uri.endsWith(".prompt") || + uri.endsWith(SYSTEM_PROMPT_DOT_FILE) + ) { + await this.configHandler.reloadConfig(); + } else if ( + uri.endsWith(".continueignore") || + uri.endsWith(".gitignore") + ) { + // Reindex the workspaces + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); + } else { + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } + } + } + } + } + } + + private async handleListModels(msg: Message<{ title: string }>) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + + const model = + config.modelsByRole.chat.find( + (model) => model.title === msg.data.title, + ) ?? + config.modelsByRole.chat.find((model) => + model.title?.startsWith(msg.data.title), + ); + + try { + if (model) { + return await model.listModels(); + } else { + if (msg.data.title === "Ollama") { + const models = await new Ollama({ model: "" }).listModels(); + return models; + } else { + return undefined; + } + } + } catch (e) { + console.debug(`Error listing Ollama models: ${e}`); + return undefined; + } + } + + private async handleCompleteOnboarding(msg: Message<{ mode: string }>) { + const mode = msg.data.mode; + + if (mode === "Custom") { + return; + } + + let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; + + switch (mode) { + case "Local": + editConfigYamlCallback = setupLocalConfig; + break; + + case "Quickstart": + editConfigYamlCallback = setupQuickstartConfig; + break; + + case "Best": + editConfigYamlCallback = setupBestConfig; + break; + + default: + console.error(`Invalid mode: ${mode}`); + editConfigYamlCallback = (config) => config; + } + + editConfigFile((c) => c, editConfigYamlCallback); + + void this.configHandler.reloadConfig(); + } + + private getContextItems = async ( + msg: Message<{ + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + selectedModelTitle: string; + }>, + ) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + + const { name, query, fullInput, selectedCode } = msg.data; + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + const provider = + config.contextProviders?.find( + (provider) => provider.description.title === name, + ) ?? + [ + // user doesn't need these in their config.json for the shortcuts to work + // option+enter + new CurrentFileContextProvider({}), + // cmd+enter + new CodebaseContextProvider({}), + ].find((provider) => provider.description.title === name); + if (!provider) { + return []; + } + + try { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + + const items = await provider.getContextItems(query, { + config, + llm, + embeddingsProvider: config.selectedModelByRole.embed, + fullInput, + ide: this.ide, + selectedCode, + reranker: config.selectedModelByRole.rerank, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + }); + + void Telemetry.capture( + "useContextProvider", + { + name: provider.description.title, + }, + true, + ); + + return items.map((item) => ({ + ...item, + id, + })); + } catch (e) { + let knownError = false; + + if (e instanceof Error) { + // After removing transformers JS embeddings provider from jetbrains + // Should no longer see this error + // if (e.message.toLowerCase().includes("embeddings provider")) { + // knownError = true; + // const toastOption = "See Docs"; + // void this.ide + // .showToast( + // "error", + // `Set up an embeddings model to use @${name}`, + // toastOption, + // ) + // .then((userSelection) => { + // if (userSelection === toastOption) { + // void this.ide.openUrl( + // "https://docs.continue.dev/customize/model-roles/embeddings", + // ); + // } + // }); + // } + } + if (!knownError) { + void this.ide.showToast( + "error", + `Error getting context items from ${name}: ${e}`, + ); + } + return []; + } + }; + private indexingCancellationController: AbortController | undefined; private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) { console.debug( diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..30a977717 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,8 @@ -import { DataDestination, ModelRole } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; +import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; + declare global { interface Window { ide?: "vscode"; @@ -75,39 +77,19 @@ export type PromptTemplateFunction = ( export type PromptTemplate = string | PromptTemplateFunction; -export interface ILLM extends LLMOptions { +type RequiredLLMOptions = + | "uniqueId" + | "contextLength" + | "embeddingId" + | "maxEmbeddingChunkSize" + | "maxEmbeddingBatchSize" + | "completionOptions"; + +export interface ILLM + extends Omit, + Required> { get providerName(): string; - uniqueId: string; - model: string; - - title?: string; - systemMessage?: string; - contextLength: number; - maxStopWords?: number; - completionOptions: CompletionOptions; - requestOptions?: RequestOptions; - promptTemplates?: Record; - templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; - llmRequestHook?: (model: string, prompt: string) => any; - apiKey?: string; - apiBase?: string; - cacheBehavior?: CacheBehavior; - capabilities?: ModelCapability; - roles?: ModelRole[]; - - deployment?: string; - apiVersion?: string; - apiType?: string; - region?: string; - projectId?: string; - - // Embedding options - embeddingId: string; - maxEmbeddingChunkSize: number; - maxEmbeddingBatchSize: number; - complete( prompt: string, signal: AbortSignal, @@ -161,6 +143,8 @@ export interface ILLM extends LLMOptions { otherData: Record, canPutWordsInModelsMouth?: boolean, ): string | ChatMessage[]; + + getConfigurationStatus(): LLMConfigurationStatuses; } export interface ModelInstaller { @@ -482,12 +466,101 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions { export type ToastType = "info" | "error" | "warning"; +export interface LLMInteractionBase { + interactionId: string; + timestamp: number; +} + +export interface LLMInteractionStartChat extends LLMInteractionBase { + kind: "startChat"; + messages: ChatMessage[]; + options: CompletionOptions; +} + +export interface LLMInteractionStartComplete extends LLMInteractionBase { + kind: "startComplete"; + prompt: string; + options: CompletionOptions; +} + +export interface LLMInteractionStartFim extends LLMInteractionBase { + kind: "startFim"; + prefix: string; + suffix: string; + options: CompletionOptions; +} + +export interface LLMInteractionChunk extends LLMInteractionBase { + kind: "chunk"; + chunk: string; +} + +export interface LLMInteractionMessage extends LLMInteractionBase { + kind: "message"; + message: ChatMessage; +} + +export interface LLMInteractionEnd extends LLMInteractionBase { + promptTokens: number; + generatedTokens: number; + thinkingTokens: number; +} + +export interface LLMInteractionSuccess extends LLMInteractionEnd { + kind: "success"; +} + +export interface LLMInteractionCancel extends LLMInteractionEnd { + kind: "cancel"; +} + +export interface LLMInteractionError extends LLMInteractionEnd { + kind: "error"; + name: string; + message: string; +} + +export type LLMInteractionItem = + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim + | LLMInteractionChunk + | LLMInteractionMessage + | LLMInteractionSuccess + | LLMInteractionCancel + | LLMInteractionError; + +// When we log a LLM interaction, we want to add the interactionId and timestamp +// in the logger code, so we need a type that omits these members from *each* +// member of the union. This can be done by using the distributive behavior of +// conditional types in Typescript. +// +// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types +// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s +type DistributiveOmit = T extends unknown + ? Omit + : never; + +export type LLMInteractionItemDetails = DistributiveOmit< + LLMInteractionItem, + "interactionId" | "timestamp" +>; + +export interface ILLMInteractionLog { + logItem(item: LLMInteractionItemDetails): void; +} + +export interface ILLMLogger { + createInteractionLog(): ILLMInteractionLog; +} + export interface LLMOptions { model: string; title?: string; uniqueId?: string; systemMessage?: string; + baseChatSystemMessage?: string; contextLength?: number; maxStopWords?: number; completionOptions?: CompletionOptions; @@ -495,8 +568,9 @@ export interface LLMOptions { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; + rules?: Rule[]; apiKey?: string; // continueProperties @@ -709,6 +783,8 @@ export interface IDE { getSearchResults(query: string): Promise; + getFileResults(pattern: string): Promise; + subprocess(command: string, cwd?: string): Promise<[string, string]>; getProblems(fileUri?: string | undefined): Promise; @@ -964,11 +1040,13 @@ export interface ModelDescription { template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; + baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + configurationStatus?: LLMConfigurationStatuses; } export interface EmbedOptions { @@ -1141,6 +1219,7 @@ export interface ApplyState { numDiffs?: number; filepath?: string; fileContent?: string; + toolCallId?: string; } export interface RangeInFileWithContents { @@ -1296,7 +1375,6 @@ export interface Config { // in the actual Continue source code export interface ContinueConfig { allowAnonymousTelemetry?: boolean; - models: ILLM[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; @@ -1312,7 +1390,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1320,7 +1398,6 @@ export interface ContinueConfig { export interface BrowserSerializedContinueConfig { allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; @@ -1335,7 +1412,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; diff --git a/core/indexing/allEmbeddingsProviders.ts b/core/indexing/allEmbeddingsProviders.ts deleted file mode 100644 index 3986fa2c0..000000000 --- a/core/indexing/allEmbeddingsProviders.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { ILLM } from "../index.js"; -import Bedrock from "../llm/llms/Bedrock.js"; -import Cohere from "../llm/llms/Cohere.js"; -import DeepInfra from "../llm/llms/DeepInfra.js"; -import FreeTrial from "../llm/llms/FreeTrial.js"; -import FunctionNetwork from "../llm/llms/FunctionNetwork.js"; -import Gemini from "../llm/llms/Gemini.js"; -import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js"; -import LMStudio from "../llm/llms/LMStudio.js"; -import Mistral from "../llm/llms/Mistral.js"; -import NCompass from "../llm/llms/NCompass.js"; -import Nebius from "../llm/llms/Nebius.js"; -import Nvidia from "../llm/llms/Nvidia.js"; -import Ollama from "../llm/llms/Ollama.js"; -import OpenAI from "../llm/llms/OpenAI.js"; -import SageMaker from "../llm/llms/SageMaker.js"; -import Scaleway from "../llm/llms/Scaleway.js"; -import SiliconFlow from "../llm/llms/SiliconFlow.js"; -import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js"; -import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js"; -import VertexAI from "../llm/llms/VertexAI.js"; -import Voyage from "../llm/llms/Voyage.js"; -import WatsonX from "../llm/llms/WatsonX.js"; - -type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM; - -export const allEmbeddingsProviders: Record< - string, - EmbeddingsProviderConstructor -> = { - sagemaker: SageMaker, - bedrock: Bedrock, - ollama: Ollama, - "transformers.js": TransformersJsEmbeddingsProvider, - openai: OpenAI, - cohere: Cohere, - "free-trial": FreeTrial, - "function-network": FunctionNetwork, - "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, - gemini: Gemini, - "continue-proxy": ContinueProxy, - deepinfra: DeepInfra, - ncompass: NCompass, - nvidia: Nvidia, - voyage: Voyage, - mistral: Mistral, - nebius: Nebius, - vertexai: VertexAI, - watsonx: WatsonX, - lmstudio: LMStudio, - siliconflow: SiliconFlow, - scaleway: Scaleway, -}; diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 6021fc260..9677abfef 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -3,6 +3,7 @@ // */ // import { ConfigHandler } from "../../config/ConfigHandler.js"; // import { SiteIndexingConfig } from "../../index.js"; +// import { LLMLogger } from "../../llm/logger.js"; // import FileSystemIde from "../../util/filesystem.js"; // import { editConfigJson } from "../../util/paths.js"; @@ -48,7 +49,7 @@ // configHandler = new ConfigHandler( // ide, // ideSettingsPromise, -// async () => {}, +// new LLMLogger(), // Promise.resolve(undefined), // ); diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index ef21149b1..f76c6a7f6 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -158,18 +158,21 @@ async function getAddRemoveForTag( const updateLastUpdated: PathAndCacheKey[] = []; // First, group items by path and find latest timestamp for each - const pathGroups = new Map - }>(); + const pathGroups = new Map< + string, + { + latest: { lastUpdated: number; cacheKey: string }; + allVersions: Array<{ cacheKey: string }>; + } + >(); for (const item of saved) { const { lastUpdated, path, cacheKey } = item; - + if (!pathGroups.has(path)) { pathGroups.set(path, { latest: { lastUpdated, cacheKey }, - allVersions: [{ cacheKey }] + allVersions: [{ cacheKey }], }); } else { const group = pathGroups.get(path)!; @@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string { return input.substring(startIndex, input.length); } -export function truncateSqliteLikePattern(input: string) { - return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); +export function truncateSqliteLikePattern(input: string, safety: number = 100) { + return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety); } diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 399a24875..50acba4ed 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -97,7 +97,7 @@ describe("walkDir functions", () => { ); }); - it("should handle onlyDirs option", async () => { + it("should handle include option", async () => { addToTestDir([ "src/", ["src/file1.ts", "content1"], @@ -109,7 +109,7 @@ describe("walkDir functions", () => { (await testIde.getWorkspaceDirs())[0], testIde, { - onlyDirs: true, + include: "dirs", }, ); diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 2c70006a8..04e45a3ca 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -10,10 +10,11 @@ import { } from "./ignore"; export interface WalkerOptions { - onlyDirs?: boolean; + include?: "dirs" | "files" | "both"; returnRelativeUrisPaths?: boolean; source?: string; overrideDefaultIgnores?: Ignore; + recursive?: boolean; } type Entry = [string, FileType]; @@ -195,7 +196,7 @@ class DFSWalker { if (this.entryIsDirectory(entry)) { relPath = `${relPath}/`; } else { - if (this.options.onlyDirs) { + if (this.options.include === "dirs") { continue; } } @@ -221,19 +222,22 @@ class DFSWalker { } if (this.entryIsDirectory(entry)) { - stack.push({ - walkableEntry, - ignoreContexts, - }); - if (this.options.onlyDirs) { - // when onlyDirs is enabled the walker will only return directory names + if (this.options.recursive) { + stack.push({ + walkableEntry, + ignoreContexts, + }); + } + if (this.options.include !== "files") { + // if yielding dirs or both, walker includes relative paths + const trailingSlash = this.options.include === "dirs" ? "" : "/"; if (this.options.returnRelativeUrisPaths) { - yield walkableEntry.relativeUriPath; + yield walkableEntry.relativeUriPath + trailingSlash; } else { - yield walkableEntry.uri; + yield walkableEntry.uri + trailingSlash; } } - } else { + } else if (this.options.include !== "dirs") { if (this.options.returnRelativeUrisPaths) { yield walkableEntry.relativeUriPath; } else { @@ -257,8 +261,9 @@ class DFSWalker { } const defaultOptions: WalkerOptions = { - onlyDirs: false, + include: "files", returnRelativeUrisPaths: false, + recursive: true, }; export async function* walkDirAsync( diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 7e8b8e9f5..8532aa33b 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -1,5 +1,5 @@ const DEFAULT_MAX_TOKENS = 4096; -const DEFAULT_CONTEXT_LENGTH = 8096; +const DEFAULT_CONTEXT_LENGTH = 8192; const DEFAULT_TEMPERATURE = 0.5; const DEFAULT_ARGS = { @@ -32,6 +32,11 @@ const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; +export enum LLMConfigurationStatuses { + VALID = "valid", + MISSING_API_KEY = "missing-api-key", +} + export { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 69425d33e..f3e6b4d07 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,14 +1,41 @@ import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; import { normalizeToMessageParts } from "../util/messageContent"; -const DEFAULT_SYSTEM_MESSAGE = ` - Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'. +const DEFAULT_SYSTEM_MESSAGE = `\ + + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' + + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For instance: + + \`\`\`typescript /path/to/file + // ... rest of code here ... + + {{ modified code here }} + + // ... rest of code here ... + + {{ another modification }} + + // ... rest of code here ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. `; const CANCELED_TOOL_CALL_MESSAGE = "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; -export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { +export function constructMessages( + history: ChatHistoryItem[], + baseChatSystemMessage: string | undefined, +): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", ); @@ -16,7 +43,7 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { msgs.push({ role: "system", - content: DEFAULT_SYSTEM_MESSAGE, + content: baseChatSystemMessage ?? DEFAULT_SYSTEM_MESSAGE, }); for (let i = 0; i < filteredHistory.length; i++) { diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts index 6895e9269..92f9d92c5 100644 --- a/core/llm/countTokens.test.ts +++ b/core/llm/countTokens.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // Generated by continue import { ChatMessage, MessagePart } from "../index.js"; import { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index a05889c52..2fc01f9b8 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,7 +1,13 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { + ChatMessage, + MessageContent, + MessagePart, + UserChatMessage, +} from "../index.js"; +import { Rule } from "@continuedev/config-yaml"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -11,6 +17,8 @@ import { import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; +import { isRuleActive } from "./rules/isRuleActive.js"; +import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -27,9 +35,9 @@ class LlamaEncoding implements Encoding { } class NonWorkerAsyncEncoder implements AsyncEncoder { - constructor(private readonly encoding: Encoding) { } + constructor(private readonly encoding: Encoding) {} - async close(): Promise { } + async close(): Promise {} async encode(text: string): Promise { return this.encoding.encode(text); @@ -251,16 +259,35 @@ function pruneChatHistory( }, 0); // 0. Prune any messages that take up more than 1/3 of the context length - const longestMessages = [...chatHistory]; - longestMessages.sort((a, b) => b.content.length - a.content.length); + const zippedMessagesAndTokens: [ChatMessage, number][] = []; - const longerThanOneThird = longestMessages.filter( - (message: ChatMessage) => - countTokens(message.content, modelName) > contextLength / 3, + // Zipped ChatMessage with its token counts + chatHistory.forEach((message) => { + const zippedItem: [ChatMessage, number] = [ + message, + countTokens(message.content, modelName), + ]; + zippedMessagesAndTokens.push(zippedItem); + }); + + const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( + ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, ); - const distanceFromThird = longerThanOneThird.map( - (message: ChatMessage) => - countTokens(message.content, modelName) - contextLength / 3, + + zippedLongerThanOneThird.sort( + ( + [_messageA, tokensA]: [ChatMessage, number], + [_messageB, tokensB]: [ChatMessage, number], + ) => { + return tokensB - tokensA; + }, + ); + + const longerThanOneThird = zippedLongerThanOneThird.map( + ([message, _token]: [ChatMessage, number]) => message, + ); + const distanceFromThird = zippedLongerThanOneThird.map( + ([_message, token]: [ChatMessage, number]) => token - contextLength / 3, ); for (let i = 0; i < longerThanOneThird.length; i++) { @@ -280,7 +307,7 @@ function pruneChatHistory( // 1. Replace beyond last 5 messages with summary let i = 0; while (totalTokens > contextLength && i < chatHistory.length - 5) { - const message = chatHistory[0]; + const message = chatHistory[i]; totalTokens -= countTokens(message.content, modelName); totalTokens += countTokens(summarize(message), modelName); message.content = summarize(message); @@ -288,11 +315,7 @@ function pruneChatHistory( } // 2. Remove entire messages until the last 5 - while ( - chatHistory.length > 5 && - totalTokens > contextLength && - chatHistory.length > 0 - ) { + while (chatHistory.length > 5 && totalTokens > contextLength) { const message = chatHistory.shift()!; totalTokens -= countTokens(message.content, modelName); } @@ -313,8 +336,21 @@ function pruneChatHistory( // 4. Remove entire messages in the last 5, except last 1 while (totalTokens > contextLength && chatHistory.length > 1) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // If tool call/response detected prune both (can't have response with no call) + // TODO prune lines from tool response before pruning both messages + if ( + chatHistory.length > 2 && + messageHasToolCalls(chatHistory[0]) && + chatHistory[1].role === "tool" + ) { + const firstMessage = chatHistory.shift()!; + const secondMessage = chatHistory.shift()!; + totalTokens -= countTokens(firstMessage.content, modelName); + totalTokens -= countTokens(secondMessage.content, modelName); + } else { + const message = chatHistory.shift()!; + totalTokens -= countTokens(message.content, modelName); + } } // 5. Truncate last message @@ -328,7 +364,6 @@ function pruneChatHistory( ); totalTokens = contextLength; } - return chatHistory; } @@ -372,20 +407,131 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { } } -function compileChatMessages( - modelName: string, - msgs: ChatMessage[] | undefined, - contextLength: number, - maxTokens: number, - supportsImages: boolean, - prompt: string | undefined = undefined, - functions: any[] | undefined = undefined, - systemMessage: string | undefined = undefined, -): ChatMessage[] { +function addSystemMessage({ + messages, + systemMessage, + originalMessages, +}: { + messages: ChatMessage[]; + systemMessage: string | undefined; + originalMessages: ChatMessage[] | undefined; +}): ChatMessage[] { + if ( + !(systemMessage && systemMessage.trim() !== "") && + originalMessages?.[0]?.role !== "system" + ) { + return messages; + } + + let content = ""; + if (originalMessages?.[0]?.role === "system") { + content = renderChatMessage(originalMessages[0]); + } + if (systemMessage && systemMessage.trim() !== "") { + const shouldAddNewLines = content !== ""; + if (shouldAddNewLines) { + content += "\n\n"; + } + content += systemMessage; + } + + const systemChatMsg: ChatMessage = { + role: "system", + content, + }; + // Insert as second to last + messages.splice(-1, 0, systemChatMsg); + return messages; +} + +function getMessageStringContent(message?: UserChatMessage): string { + if (!message) { + return ""; + } + + if (typeof message.content === "string") { + return message.content; + } + + // Handle MessagePart array + return message.content + .map((part) => { + if (part.type === "text") { + return part.text; + } + + return ""; + }) + .join("\n"); +} + +const getSystemMessage = ({ + userMessage, + rules, + currentModel, +}: { + userMessage?: UserChatMessage; + rules: Rule[]; + currentModel: string; +}) => { + const messageStringContent = getMessageStringContent(userMessage); + const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); + + return rules + .filter((rule) => { + return isRuleActive({ + rule, + activePaths: filePathsFromMessage, + currentModel, + }); + }) + .map((rule) => { + if (typeof rule === "string") { + return rule; + } + return rule.rule; + }) + .join("\n"); +}; + +function getLastUserMessage( + messages: ChatMessage[], +): UserChatMessage | undefined { + // Iterate backwards through messages to find the last user message + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].role === "user") { + return messages[i] as UserChatMessage; + } + } + + return undefined; +} + +function compileChatMessages({ + modelName, + msgs, + contextLength, + maxTokens, + supportsImages, + prompt, + functions, + systemMessage, + rules, +}: { + modelName: string; + msgs: ChatMessage[] | undefined; + contextLength: number; + maxTokens: number; + supportsImages: boolean; + prompt: string | undefined; + functions: any[] | undefined; + systemMessage: string | undefined; + rules: Rule[]; +}): ChatMessage[] { let msgsCopy = msgs ? msgs - .map((msg) => ({ ...msg })) - .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") + .map((msg) => ({ ...msg })) + .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") : []; msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); @@ -398,29 +544,19 @@ function compileChatMessages( msgsCopy.push(promptMsg); } - if ( - (systemMessage && systemMessage.trim() !== "") || - msgs?.[0]?.role === "system" - ) { - let content = ""; - if (msgs?.[0]?.role === "system") { - content = renderChatMessage(msgs?.[0]); - } - if (systemMessage && systemMessage.trim() !== "") { - const shouldAddNewLines = content !== ""; - if (shouldAddNewLines) { - content += "\n\n"; - } - content += systemMessage; - } - const systemChatMsg: ChatMessage = { - role: "system", - content, - }; - // Insert as second to last - // Later moved to top, but want second-priority to last user message - msgsCopy.splice(-1, 0, systemChatMsg); - } + const lastUserMessage = getLastUserMessage(msgsCopy); + + msgsCopy = addSystemMessage({ + messages: msgsCopy, + systemMessage: + systemMessage ?? + getSystemMessage({ + userMessage: lastUserMessage, + rules, + currentModel: modelName, + }), + originalMessages: msgs, + }); let functionTokens = 0; if (functions) { @@ -470,6 +606,5 @@ export { pruneLinesFromTop, pruneRawPromptFromTop, pruneStringFromBottom, - pruneStringFromTop + pruneStringFromTop, }; - diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 404902e91..7f535d1fd 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,6 +1,7 @@ import { ChatMessage, LLMOptions } from ".."; import { BaseLLM } from "."; +import { LLMLogger } from "./logger"; class DummyLLM extends BaseLLM { static providerName = "openai"; @@ -30,7 +31,7 @@ describe("BaseLLM", () => { const templatMessagesFunction = (messages: ChatMessage[]) => { return messages[0]?.content.toString() ?? ""; }; - const writeLogFunction = async () => {}; + const llmLogger = new LLMLogger(); const options: LLMOptions = { model: "gpt-3.5-turbo", uniqueId: "testId", @@ -43,7 +44,7 @@ describe("BaseLLM", () => { requestOptions: {}, promptTemplates: {}, templateMessages: templatMessagesFunction, - writeLog: writeLogFunction, + logger: llmLogger, llmRequestHook: () => {}, apiKey: "testApiKey", aiGatewaySlug: "testSlug", @@ -67,7 +68,7 @@ describe("BaseLLM", () => { expect(instance.requestOptions).toEqual({}); expect(instance.promptTemplates).toEqual({}); expect(instance.templateMessages).toEqual(templatMessagesFunction); - expect(instance.writeLog).toBe(writeLogFunction); + expect(instance.logger).toBe(llmLogger); expect(instance.apiKey).toBe("testApiKey"); expect(instance.aiGatewaySlug).toBe("testSlug"); expect(instance.apiBase).toBe("https://api.example.com/"); diff --git a/core/llm/index.ts b/core/llm/index.ts index 028bc42c3..a380bd5de 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { ModelRole } from "@continuedev/config-yaml"; +import { ModelRole, Rule } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -16,6 +16,8 @@ import { Chunk, CompletionOptions, ILLM, + ILLMInteractionLog, + ILLMLogger, LLMFullCompletionOptions, LLMOptions, ModelCapability, @@ -44,6 +46,7 @@ import { DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, + LLMConfigurationStatuses, } from "./constants.js"; import { compileChatMessages, @@ -72,6 +75,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller { return provider && typeof provider.installModel === "function"; } +type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -122,6 +127,7 @@ export abstract class BaseLLM implements ILLM { title?: string; systemMessage?: string; + baseChatSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; completionOptions: CompletionOptions; @@ -129,7 +135,7 @@ export abstract class BaseLLM implements ILLM { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; @@ -143,6 +149,7 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + rules?: Rule[]; deployment?: string; apiVersion?: string; @@ -189,6 +196,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; this.systemMessage = options.systemMessage; + this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; @@ -219,7 +227,7 @@ export abstract class BaseLLM implements ILLM { options.template, ) ?? undefined; - this.writeLog = options.writeLog; + this.logger = options.logger; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; @@ -242,6 +250,7 @@ export abstract class BaseLLM implements ILLM { this.accountId = options.accountId; this.capabilities = options.capabilities; this.roles = options.roles; + this.rules = options.rules; this.deployment = options.deployment; this.apiVersion = options.apiVersion; @@ -259,6 +268,10 @@ export abstract class BaseLLM implements ILLM { this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; } + getConfigurationStatus() { + return LLMConfigurationStatuses.VALID; + } + protected createOpenAiAdapter() { return constructLlmApi({ provider: this.providerName as any, @@ -286,21 +299,17 @@ export abstract class BaseLLM implements ILLM { CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; } - return compileChatMessages( - options.model, - messages, + return compileChatMessages({ + modelName: options.model, + msgs: messages, contextLength, - options.maxTokens ?? DEFAULT_MAX_TOKENS, - this.supportsImages(), - undefined, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, functions, - this.systemMessage, - ); - } - - private _getSystemMessage(): string | undefined { - // TODO: Merge with config system message - return this.systemMessage; + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); } private _templatePromptLikeMessages(prompt: string): string { @@ -310,7 +319,7 @@ export abstract class BaseLLM implements ILLM { const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; - const systemMessage = this._getSystemMessage(); + const systemMessage = this.systemMessage; if (systemMessage) { msgs.unshift({ role: "system", content: systemMessage }); } @@ -347,13 +356,17 @@ export abstract class BaseLLM implements ILLM { ); } - private _logTokensGenerated( + private _logEnd( model: string, prompt: string, completion: string, - ) { + thinking: string | undefined, + interaction: ILLMInteractionLog | undefined, + error?: any, + ): InteractionStatus { let promptTokens = this.countTokens(prompt); let generatedTokens = this.countTokens(completion); + let thinkingTokens = thinking ? this.countTokens(thinking) : 0; void Telemetry.capture( "tokens_generated", @@ -382,6 +395,37 @@ export abstract class BaseLLM implements ILLM { generatedTokens: generatedTokens, }, }); + + if (error !== undefined) { + if (error === "cancel" || error.name === "AbortError") { + interaction?.logItem({ + kind: "cancel", + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "cancelled"; + } else { + console.log(error); + interaction?.logItem({ + kind: "error", + name: error.name, + message: error.message, + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "error"; + } + } else { + interaction?.logItem({ + kind: "success", + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "success"; + } } fetch(url: RequestInfo | URL, init?: RequestInit): Promise { @@ -462,11 +506,7 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } - //if e instance of LLMError, rethrow - if (e instanceof LLMError) { - throw e; - } - throw new Error(e.message); + throw e; } }; return withExponentialBackoff( @@ -541,52 +581,89 @@ export abstract class BaseLLM implements ILLM { ): AsyncGenerator { const { completionOptions, logEnabled } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`; if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(fimLog, completionOptions), - ); - } + interaction?.logItem({ + kind: "startFim", + prefix, + suffix, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, fimLog); } } let completion = ""; - - if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { - const stream = this.openaiAdapter.fimStream( - toFimBody(prefix, suffix, completionOptions), - signal, - ); - for await (const chunk of stream) { - const result = fromChatCompletionChunk(chunk); - if (result) { - const content = renderChatMessage(result); - completion += content; - yield content; + try { + if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { + const stream = this.openaiAdapter.fimStream( + toFimBody(prefix, suffix, completionOptions), + signal, + ); + for await (const chunk of stream) { + const result = fromChatCompletionChunk(chunk); + if (result) { + const content = renderChatMessage(result); + interaction?.logItem({ + kind: "chunk", + chunk: content, + }); + completion += content; + yield content; + } + } + } else { + for await (const chunk of this._streamFim( + prefix, + suffix, + signal, + completionOptions, + )) { + interaction?.logItem({ + kind: "chunk", + chunk, + }); + completion += chunk; + yield chunk; } } - } else { - for await (const chunk of this._streamFim( - prefix, - suffix, - signal, - completionOptions, - )) { - completion += chunk; - yield chunk; + + status = this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + "cancel", + ); } } - this._logTokensGenerated(completionOptions.model, fimLog, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); - } - return { prompt: fimLog, completion, @@ -601,6 +678,10 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -614,11 +695,11 @@ export abstract class BaseLLM implements ILLM { } if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startComplete", + prompt, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } @@ -646,6 +727,10 @@ export abstract class BaseLLM implements ILLM { )) { const content = chunk.choices[0]?.text ?? ""; completion += content; + interaction?.logItem({ + kind: "chunk", + chunk: content, + }); yield content; } } @@ -656,14 +741,40 @@ export abstract class BaseLLM implements ILLM { completionOptions, )) { completion += chunk; + interaction?.logItem({ + kind: "chunk", + chunk, + }); yield chunk; } } + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + e, + ); + throw e; } finally { - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", + ); } } @@ -682,6 +793,10 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -695,34 +810,65 @@ export abstract class BaseLLM implements ILLM { } if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startComplete", + prompt: prompt, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } } - let completion: string; - if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { - const result = await this.openaiAdapter.completionNonStream( - { - ...toCompleteBody(prompt, completionOptions), - stream: false, - }, - signal, + let completion: string = ""; + + try { + if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { + const result = await this.openaiAdapter.completionNonStream( + { + ...toCompleteBody(prompt, completionOptions), + stream: false, + }, + signal, + ); + completion = result.choices[0].text; + } else { + completion = await this._complete(prompt, signal, completionOptions); + } + + interaction?.logItem({ + kind: "chunk", + chunk: completion, + }); + + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, ); - completion = result.choices[0].text; - } else { - completion = await this._complete(prompt, signal, completionOptions); - } - - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", + ); + } } return completion; @@ -767,6 +913,10 @@ export abstract class BaseLLM implements ILLM { ): AsyncGenerator { let { completionOptions, logEnabled } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; completionOptions = this._modifyCompletionOptions(completionOptions); @@ -776,11 +926,11 @@ export abstract class BaseLLM implements ILLM { ? this.templateMessages(messages) : this._formatChatMessages(messages); if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startChat", + messages, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } @@ -788,7 +938,6 @@ export abstract class BaseLLM implements ILLM { let thinking = ""; let completion = ""; - let citations: null | string[] = null; try { if (this.templateMessages) { @@ -798,6 +947,10 @@ export abstract class BaseLLM implements ILLM { completionOptions, )) { completion += chunk; + interaction?.logItem({ + kind: "chunk", + chunk: chunk, + }); yield { role: "assistant", content: chunk }; } } else { @@ -827,15 +980,12 @@ export abstract class BaseLLM implements ILLM { const result = fromChatCompletionChunk(chunk); if (result) { completion += result.content; + interaction?.logItem({ + kind: "message", + message: result, + }); yield result; } - if ( - !citations && - (chunk as any).citations && - Array.isArray((chunk as any).citations) - ) { - citations = (chunk as any).citations; - } } } } else { @@ -846,44 +996,56 @@ export abstract class BaseLLM implements ILLM { )) { if (chunk.role === "assistant") { completion += chunk.content; - yield chunk; + } else if (chunk.role === "thinking") { + thinking += chunk.content; } - if (chunk.role === "thinking") { - thinking += chunk.content; - yield chunk; - } + interaction?.logItem({ + kind: "message", + message: chunk, + }); + yield chunk; } } } - } catch (error) { - console.log(error); - throw error; - } - - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - if (thinking) { - await this.writeLog(`Thinking:\n${thinking}\n\n`); - } - /* - TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking - During tool use, you must pass thinking and redacted_thinking blocks back to the API, - and you must include the complete unmodified block back to the API. This is critical - for maintaining the model's reasoning flow and conversation integrity. - - On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent - requests when not using tools, so it's the simplest option to always add to history. - */ - await this.writeLog(`Completion:\n${completion}\n\n`); - - if (citations) { - await this.writeLog( - `Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`, + status = this._logEnd( + completionOptions.model, + prompt, + completion, + thinking, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + thinking, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", ); } } + /* + TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking + During tool use, you must pass thinking and redacted_thinking blocks back to the API, + and you must include the complete unmodified block back to the API. This is critical + for maintaining the model's reasoning flow and conversation integrity. + + On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent + requests when not using tools, so it's the simplest option to always add to history. + */ return { modelTitle: this.title ?? completionOptions.model, diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c6abbeb97..b9517bb59 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -2,8 +2,9 @@ import { BedrockRuntimeClient, ContentBlock, ConverseStreamCommand, + ConverseStreamCommandOutput, InvokeModelCommand, - Message + Message, } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; @@ -11,8 +12,9 @@ import { ChatMessage, Chunk, CompletionOptions, - LLMOptions + LLMOptions, } from "../../index.js"; +import { getSecureID } from "../utils/getSecureID.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; @@ -31,6 +33,14 @@ interface ToolUseState { input: string; } +/** + * Interface for prompt caching metrics + */ +interface PromptCachingMetrics { + cacheReadInputTokens: number; + cacheWriteInputTokens: number; +} + class Bedrock extends BaseLLM { static providerName = "bedrock"; static defaultOptions: Partial = { @@ -41,8 +51,16 @@ class Bedrock extends BaseLLM { }; private _currentToolResponse: Partial | null = null; + private _promptCachingMetrics: PromptCachingMetrics = { + cacheReadInputTokens: 0, + cacheWriteInputTokens: 0, + }; - public requestOptions: { region?: string; credentials?: any; headers?: Record }; + public requestOptions: { + region?: string; + credentials?: any; + headers?: Record; + }; constructor(options: LLMOptions) { super(options); @@ -108,12 +126,17 @@ class Bedrock extends BaseLLM { }, ); - const input = this._generateConverseInput(messages, { ...options, stream: true }); + const input = this._generateConverseInput(messages, { + ...options, + stream: true, + }); const command = new ConverseStreamCommand(input); - let response; + let response: ConverseStreamCommandOutput; try { - response = await client.send(command, { abortSignal: signal }); + response = (await client.send(command, { + abortSignal: signal, + })) as ConverseStreamCommandOutput; } catch (error: unknown) { console.error(error); const message = error instanceof Error ? error.message : "Unknown error"; @@ -124,51 +147,82 @@ class Bedrock extends BaseLLM { throw new Error("No stream received from Bedrock API"); } + // Reset cache metrics for new request + this._promptCachingMetrics = { + cacheReadInputTokens: 0, + cacheWriteInputTokens: 0, + }; + try { for await (const chunk of response.stream) { + if (chunk.metadata?.usage) { + console.log(`${JSON.stringify(chunk.metadata.usage)}`); + } if (chunk.contentBlockDelta?.delta) { - - const delta: any = chunk.contentBlockDelta.delta + const delta: any = chunk.contentBlockDelta.delta; // Handle text content if (chunk.contentBlockDelta.delta.text) { - yield { role: "assistant", content: chunk.contentBlockDelta.delta.text }; + yield { + role: "assistant", + content: chunk.contentBlockDelta.delta.text, + }; continue; } // Handle text content if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { - yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text }; + yield { + role: "thinking", + content: (chunk.contentBlockDelta.delta as any).reasoningContent + .text, + }; continue; } // Handle signature for thinking if (delta.reasoningContent?.signature) { - yield { role: "thinking", content: "", signature: delta.reasoningContent.signature }; + yield { + role: "thinking", + content: "", + signature: delta.reasoningContent.signature, + }; continue; } // Handle redacted thinking if (delta.redactedReasoning?.data) { - yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: delta.redactedReasoning.data, + }; continue; } - if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { + if ( + chunk.contentBlockDelta.delta.toolUse?.input && + this._currentToolResponse + ) { // Append the new input to the existing string if (this._currentToolResponse.input === undefined) { this._currentToolResponse.input = ""; } - this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; + this._currentToolResponse.input += + chunk.contentBlockDelta.delta.toolUse.input; continue; } } if (chunk.contentBlockStart?.start) { - const start: any = chunk.contentBlockStart.start + const start: any = chunk.contentBlockStart.start; if (start.redactedReasoning) { - yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: start.redactedReasoning.data, + }; continue; } @@ -177,7 +231,7 @@ class Bedrock extends BaseLLM { this._currentToolResponse = { toolUseId: toolUse.toolUseId, name: toolUse.name, - input: "" + input: "", }; } continue; @@ -188,14 +242,16 @@ class Bedrock extends BaseLLM { yield { role: "assistant", content: "", - toolCalls: [{ - id: this._currentToolResponse.toolUseId, - type: "function", - function: { - name: this._currentToolResponse.name, - arguments: this._currentToolResponse.input - } - }], + toolCalls: [ + { + id: this._currentToolResponse.toolUseId, + type: "function", + function: { + name: this._currentToolResponse.name, + arguments: this._currentToolResponse.input, + }, + }, + ], }; this._currentToolResponse = null; } @@ -207,13 +263,16 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock stream error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error processing Bedrock stream: ${error.message}`); } - throw new Error("Error processing Bedrock stream: Unknown error occurred"); + throw new Error( + "Error processing Bedrock stream: Unknown error occurred", + ); } - } /** @@ -228,22 +287,43 @@ class Bedrock extends BaseLLM { ): any { const convertedMessages = this._convertMessages(messages); - const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const enablePromptCaching = + shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; + + // Add header for prompt caching + if (enablePromptCaching) { + this.requestOptions.headers = { + ...this.requestOptions.headers, + "x-amzn-bedrock-enablepromptcaching": "true", + }; + } + + const supportsTools = + PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; return { modelId: options.model, messages: convertedMessages, - system: this.systemMessage ? [{ text: this.systemMessage }] : undefined, - toolConfig: supportsTools && options.tools ? { - tools: options.tools.map(tool => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters + system: this.systemMessage + ? shouldCacheSystemMessage + ? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }] + : [{ text: this.systemMessage }] + : undefined, + toolConfig: + supportsTools && options.tools + ? { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), } - } - })) - } : undefined, + : undefined, inferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature, @@ -261,20 +341,29 @@ class Bedrock extends BaseLLM { .slice(0, 4), }, additionalModelRequestFields: { - "thinking": options.reasoning ? { - "type": "enabled", - "budget_tokens": options.reasoningBudgetTokens - } : undefined, - } + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, + }, }; } - private _convertMessage(message: ChatMessage): Message | null { + private _convertMessage( + message: ChatMessage, + addCaching: boolean = false, + ): Message | null { // Handle system messages explicitly if (message.role === "system") { return null; } + const cachePoint = addCaching + ? { cachePoint: { type: "default" } } + : undefined; + // Tool response handling if (message.role === "tool") { return { @@ -285,12 +374,12 @@ class Bedrock extends BaseLLM { toolUseId: message.toolCallId, content: [ { - text: message.content || "" - } - ] - } - } - ] + text: message.content || "", + }, + ], + }, + }, + ], }; } @@ -303,8 +392,8 @@ class Bedrock extends BaseLLM { toolUseId: toolCall.id, name: toolCall.function?.name, input: JSON.parse(toolCall.function?.arguments || "{}"), - } - })) + }, + })), }; } @@ -312,84 +401,117 @@ class Bedrock extends BaseLLM { if (message.redactedThinking) { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { - redactedContent: new Uint8Array(Buffer.from(message.redactedThinking)) - } + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, }; return { role: "assistant", - content: [content] + content: [content], }; } else { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { reasoningText: { text: (message.content as string) || "", - signature: message.signature - } - - } + signature: message.signature, + }, + }, }; return { role: "assistant", - content: [content] + content: [content], }; } } // Standard text message if (typeof message.content === "string") { + if (addCaching) { + message.content += getSecureID(); + } + const content: any[] = [{ text: message.content }]; + if (addCaching) { + content.push({ cachePoint: { type: "default" } }); + } return { role: message.role, - content: [{ text: message.content }] + content, }; } // Improved multimodal content handling if (Array.isArray(message.content)) { + const content: any[] = []; + + // Process all parts first + message.content.forEach((part) => { + if (part.type === "text") { + if (addCaching) { + part.text += getSecureID(); + } + content.push({ text: part.text }); + } else if (part.type === "imageUrl" && part.imageUrl) { + try { + const [mimeType, base64Data] = part.imageUrl.url.split(","); + const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; + content.push({ + image: { + format, + source: { + bytes: Buffer.from(base64Data, "base64"), + }, + }, + }); + } catch (error) { + console.warn(`Failed to process image: ${error}`); + } + } + }); + + // Add cache point as a separate block at the end if needed + if (addCaching && content.length > 0) { + content.push({ cachePoint: { type: "default" } }); + } + return { role: message.role, - content: message.content.map(part => { - if (part.type === "text") { - return { text: part.text }; - } - if (part.type === "imageUrl" && part.imageUrl) { - try { - const [mimeType, base64Data] = part.imageUrl.url.split(","); - const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; - return { - image: { - format, - source: { - bytes: Buffer.from(base64Data, "base64") - } - } - }; - } catch (error) { - console.warn(`Failed to process image: ${error}`); - return null; - } - } - return null; - }).filter(Boolean) + content, } as Message; } return null; } private _convertMessages(messages: ChatMessage[]): any[] { + const filteredmessages = messages.filter( + (m) => m.role !== "system" && !!m.content, + ); + const lastTwoUserMsgIndices = filteredmessages + .map((msg, index) => (msg.role === "user" ? index : -1)) + .filter((index) => index !== -1) + .slice(-2); + + const converted = filteredmessages + .map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + const addCaching = + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(filteredMsgIdx); - const converted = messages - .map((message) => { try { - return this._convertMessage(message); + return this._convertMessage(message, addCaching); } catch (error) { console.error(`Failed to convert message: ${error}`); return null; } }) .filter(Boolean); - return converted; + return converted; } private async _getCredentials() { @@ -453,7 +575,6 @@ class Bedrock extends BaseLLM { return modelConfig.extractEmbeddings(responseBody); } - private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { cohere: { @@ -491,7 +612,11 @@ class Bedrock extends BaseLLM { const credentials = await this._getCredentials(); const client = new BedrockRuntimeClient({ region: this.region, - credentials, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, }); // Base payload for both models @@ -530,11 +655,15 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); } - throw new Error("Error in BedrockReranker.rerank: Unknown error occurred"); + throw new Error( + "Error in BedrockReranker.rerank: Unknown error occurred", + ); } } } diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts new file mode 100644 index 000000000..d9c3d5c58 --- /dev/null +++ b/core/llm/llms/Docker.ts @@ -0,0 +1,197 @@ +import { spawn } from "child_process"; +import { LLMOptions, ModelInstaller } from "../../index.js"; +import OpenAI from "./OpenAI.js"; + +/** + * Docker Model Runner provider + * + * Integrates with Docker Desktop's Model Runner feature (currently in beta) + * that allows running local AI models through Docker. + * + * Docker Model Runner provides an OpenAI-compatible API endpoint, making it + * easy to integrate with existing OpenAI-compatible code. + * + * More information at: https://docs.docker.com/desktop/features/model-runner/ + */ +class Docker extends OpenAI implements ModelInstaller { + static providerName = "docker"; + static defaultOptions: Partial = { + apiBase: "http://localhost:12434/engines/v1", + model: "gemma3-4B-F4", // Default model + }; + + private modelMap: Record = { + // Map of "continue model name" to Docker model name + // Models can be pulled using: docker model pull + "llama3.3-70b": "ai/llama3.3:70B-Q4_K_M", + "smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M", + "smollm2-360M-F16": "ai/ai/smollm2:360M-F16", + "qwen2.5-7B-F16": "ai/qwen2.5:7B-F16", + "qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M", + "phi4-14B-F16": "ai/phi4:14B-F16", + "phi4-14B-F4": "ai/phi4:14B-Q4_K_M", + "mistral-7B-F16": "ai/mistral:7B-F16", + "mistral-7B-F4": "ai/mistral:7B-Q4_K_M", + "mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M", + "gemma3-4B-F16": "ai/gemma3:4B-F16", + "gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M", + "llama3.2-3B-F16": "ai/llama3.2:3B-F16", + "llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M", + "llama3.2-1B-F16": "ai/llama3.2:1B-F16", + "llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0", + "qwq-32B-F16": "ai/qwq:32B-F16", + "qwq-32B-F4": "ai/qwq:32B-Q4_K_M", + "deepseek-r1-distill-llama-70B-F4": + "ai/deepseek-r1-distill-llama:70B-Q4_K_M", + "deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16", + "deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M", + }; + + constructor(options: LLMOptions) { + super(options); + + // Handle model name mapping + if (this.model && this.modelMap[this.model]) { + this.model = this.modelMap[this.model]; + } + + // Check if Docker Model Runner is active and enable it if needed + this.ensureModelRunnerEnabled(); + } + + /** + * Checks if Docker Model Runner is running at the expected port + * and enables it if not running + */ + private async ensureModelRunnerEnabled(): Promise { + try { + // Check if the Model Runner service is running on the expected port + const isRunning = await this.isPortBound(12434); + + if (!isRunning) { + console.log( + "Docker Model Runner not detected. Attempting to enable it...", + ); + await this.executeDockerCommand([ + "desktop", + "enable", + "model-runner", + "--tcp", + "12434", + ]); + console.log("Docker Model Runner has been enabled on port 12434"); + } + } catch (error) { + console.warn("Failed to enable Docker Model Runner:", error); + } + } + + /** + * Checks if a port is currently bound/in use + */ + private async isPortBound(port: number): Promise { + try { + await this.fetch(`http://localhost:${port}`, { + method: "HEAD", + signal: AbortSignal.timeout(1000), + }); + return true; + } catch (e) { + return false; + } + } + + private async executeDockerCommand( + args: string[], + signal?: AbortSignal, + ): Promise<{ stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + const proc = spawn("docker", args, { shell: true }); + + let stdout = ""; + let stderr = ""; + + proc.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + proc.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + proc.on("close", (code) => { + if (code === 0) { + resolve({ stdout, stderr }); + } else { + reject( + new Error(`Docker command failed with code ${code}: ${stderr}`), + ); + } + }); + + if (signal) { + signal.addEventListener("abort", () => { + proc.kill(); + reject(new Error("Docker command was aborted")); + }); + } + }); + } + + async listModels(): Promise { + try { + // Execute docker model ls and parse the output + const { stdout } = await this.executeDockerCommand([ + "model", + "ls", + "--format", + "{{.Repository}}/{{.Tag}}", + ]); + return stdout + .split("\n") + .map((line) => line.trim()) + .filter(Boolean); + } catch (error) { + console.error("Failed to list Docker models:", error); + return Object.values(this.modelMap); + } + } + + async installModel( + modelName: string, + signal: AbortSignal, + progressReporter?: (task: string, increment: number, total: number) => void, + ): Promise { + const targetModel = this.modelMap[modelName] || modelName; + + try { + // Report starting the installation + progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100); + + // Pull the model + const { stdout, stderr } = await this.executeDockerCommand( + ["model", "pull", targetModel], + signal, + ); + + // Report completion + progressReporter?.( + `Docker model ${targetModel} installed successfully`, + 100, + 100, + ); + + return { success: true, stdout, stderr }; + } catch (error) { + console.error(`Failed to install Docker model ${targetModel}:`, error); + // Fix: Type check the error before accessing message property + const errorMessage = + error instanceof Error ? error.message : String(error); + throw new Error( + `Failed to install Docker model ${targetModel}: ${errorMessage}`, + ); + } + } +} + +export default Docker; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index e6b1c5c70..1c5d24aee 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -4,6 +4,7 @@ import { CompletionOptions, LLMOptions, MessagePart, + TextMessagePart, ToolCallDelta, } from "../../index.js"; import { findLast } from "../../util/findLast.js"; @@ -69,20 +70,84 @@ class Gemini extends BaseLLM { } } + /** + * Removes the system message and merges it with the next user message if present. + * @param messages Array of chat messages + * @returns Modified array with system message merged into user message if applicable + */ public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] { - // should be public for use within VertexAI - const msgs = [...messages]; + // If no messages or first message isn't system, return copy of original messages + if (messages.length === 0 || messages[0]?.role !== "system") { + return [...messages]; + } - if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()?.content; - // @ts-ignore - if (msgs[0]?.role === "user") { - // @ts-ignore - msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; + // Extract system message + const systemMessage: ChatMessage = messages[0]; + + // Extract system content based on its type + let systemContent = ""; + + if (typeof systemMessage.content === "string") { + systemContent = systemMessage.content; + } else if (Array.isArray(systemMessage.content)) { + const contentArray: Array = + systemMessage.content as Array; + + const concatenatedText = contentArray + .filter((part): part is TextMessagePart => part.type === "text") + .map((part) => part.text) + .join(" "); + + systemContent = concatenatedText ? concatenatedText : ""; + } else if ( + systemMessage.content && + typeof systemMessage.content === "object" + ) { + const typedContent = systemMessage.content as TextMessagePart; + systemContent = typedContent?.text || ""; + } + + // Create new array without the system message + const remainingMessages: ChatMessage[] = messages.slice(1); + + // Check if there's a user message to merge with + if (remainingMessages.length > 0 && remainingMessages[0].role === "user") { + const userMessage: ChatMessage = remainingMessages[0]; + const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`; + + // Merge based on user content type + if (typeof userMessage.content === "string") { + userMessage.content = prefix + userMessage.content; + } else if (Array.isArray(userMessage.content)) { + const contentArray: Array = + userMessage.content as Array; + const textPart = contentArray.find((part) => part.type === "text") as + | TextMessagePart + | undefined; + + if (textPart) { + textPart.text = prefix + textPart.text; + } else { + userMessage.content.push({ + type: "text", + text: prefix, + } as TextMessagePart); + } + } else if ( + userMessage.content && + typeof userMessage.content === "object" + ) { + const typedContent = userMessage.content as TextMessagePart; + userMessage.content = [ + { + type: "text", + text: prefix + (typedContent.text || ""), + } as TextMessagePart, + ]; } } - return msgs; + return remainingMessages; } protected async *_streamChat( diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts new file mode 100644 index 000000000..ef204fec1 --- /dev/null +++ b/core/llm/llms/Inception.ts @@ -0,0 +1,70 @@ +import { CompletionOptions, LLMOptions } from "../../index.js"; +import { streamSse } from "../stream.js"; + +import OpenAI from "./OpenAI.js"; + +/** + * Inception Labs provider + * + * Integrates with Inception Labs' OpenAI-compatible API endpoints. + * Provides access to Mercury models for autocomplete and other tasks. + * + * Different models use different API endpoints: + * - mercury-editor-mini-experimental: zaragoza.api.inceptionlabs.ai + * - mercury-editor-small-experimental: copenhagen.api.inceptionlabs.ai + * + * More information at: https://docs.inceptionlabs.ai/ + */ +class Inception extends OpenAI { + static providerName = "inception"; + static defaultOptions: Partial = { + apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/", + model: "mercury-editor-small-experimental", + completionOptions: { + temperature: 0.0, + maxTokens: 150, + presencePenalty: 1.5, + stop: ["\n\n", "\n \n", "<|endoftext|>"], + model: "mercury-editor-small-experimental", // Added model to fix TypeScript error + }, + }; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + prompt: prefix, + suffix, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].text; + } + } +} + +export default Inception; diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index a8b7e08b3..4833405ae 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM { ...this.requestOptions?.headers, }; - const resp = await this.fetch(new URL("completion", this.apiBase), { + const resp = await this.fetch(new URL("completions", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/Relace.ts b/core/llm/llms/Relace.ts index f7a27c9e3..d65a94dc1 100644 --- a/core/llm/llms/Relace.ts +++ b/core/llm/llms/Relace.ts @@ -1,4 +1,5 @@ import { LLMOptions } from "../.."; +import { LLMConfigurationStatuses } from "../constants"; import { LlmApiRequestType } from "../openaiTypeConverters"; import OpenAI from "./OpenAI"; @@ -9,4 +10,12 @@ export class Relace extends OpenAI { apiBase: "https://instantapply.endpoint.relace.run/v1/", }; protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"]; + + getConfigurationStatus() { + if (!this.apiKey) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } } diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts index 6f522f920..cddb22b0d 100644 --- a/core/llm/llms/SiliconFlow.ts +++ b/core/llm/llms/SiliconFlow.ts @@ -1,4 +1,4 @@ -import { CompletionOptions, LLMOptions } from "../../index.js"; +import { Chunk, CompletionOptions, LLMOptions } from "../../index.js"; import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; @@ -52,6 +52,41 @@ class SiliconFlow extends OpenAI { yield chunk.choices[0].text; } } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || query.trim() === "") { + console.warn("[SiliconFlow] rerank: query is empty"); + return []; + } + + if (!chunks || chunks.length === 0) { + console.warn("[SiliconFlow] rerank: chunks is empty"); + return []; + } + + const endpoint = new URL("rerank", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + const results = data.results.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default SiliconFlow; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 561f4f2d9..7f1fe2e0c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -21,7 +21,7 @@ class WatsonX extends BaseLLM { if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( - await fetch( + await this.fetch( `https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", @@ -48,7 +48,7 @@ class WatsonX extends BaseLLM { // Using username/password auth const userPass = this.apiKey?.split(":"); const wxToken = await ( - await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { + await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { method: "POST", headers: { "Content-Type": "application/json", @@ -61,7 +61,7 @@ class WatsonX extends BaseLLM { }) ).json(); const wxTokenExpiry = await ( - await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { + await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { method: "GET", headers: { Accept: "application/json", diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index e6a33a9a8..cef09098c 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -2,6 +2,7 @@ import { BaseCompletionOptions, IdeSettings, ILLM, + ILLMLogger, LLMOptions, ModelDescription, } from "../.."; @@ -18,6 +19,7 @@ import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; import Deepseek from "./Deepseek"; +import Docker from "./Docker"; import Fireworks from "./Fireworks"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; @@ -26,6 +28,7 @@ import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; +import Inception from "./Inception"; import Kindo from "./Kindo"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; @@ -87,6 +90,7 @@ export const LLMClasses = [ ContinueProxy, Cloudflare, Deepseek, + Docker, Msty, Azure, WatsonX, @@ -104,6 +108,7 @@ export const LLMClasses = [ SiliconFlow, Scaleway, Relace, + Inception, ]; export async function llmFromDescription( @@ -111,7 +116,7 @@ export async function llmFromDescription( readFile: (filepath: string) => Promise, uniqueId: string, ideSettings: IdeSettings, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, completionOptions?: BaseCompletionOptions, systemMessage?: string, ): Promise { @@ -141,7 +146,7 @@ export async function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens, }, systemMessage, - writeLog, + logger: llmLogger, uniqueId, }; diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 181db2abd..e43e2bfe2 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,10 +1,15 @@ -import { ContinueProperties } from "@continuedev/config-yaml"; +import { + ContinueProperties, + decodeSecretLocation, + SecretType, +} from "@continuedev/config-yaml"; import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; import type { Chunk, LLMOptions } from "../../../index.js"; +import { LLMConfigurationStatuses } from "../../constants.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { @@ -49,6 +54,19 @@ class ContinueProxy extends OpenAI { }; } + getConfigurationStatus() { + if (!this.apiKeyLocation) { + return LLMConfigurationStatuses.VALID; + } + + const secretLocation = decodeSecretLocation(this.apiKeyLocation); + if (secretLocation.secretType === SecretType.NotFound) { + return LLMConfigurationStatuses.MISSING_API_KEY; + } + + return LLMConfigurationStatuses.VALID; + } + protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; diff --git a/core/llm/logFormatter.test.ts b/core/llm/logFormatter.test.ts new file mode 100644 index 000000000..80aa92068 --- /dev/null +++ b/core/llm/logFormatter.test.ts @@ -0,0 +1,315 @@ +import { Buffer } from "buffer"; +import { Writable } from "stream"; +import { LLMLogFormatter } from "./logFormatter"; +import { LLMLogger } from "./logger"; + +class MemoryWritable extends Writable { + data: Buffer[] = []; + constructor() { + super(); + this.data = []; + } + + _write( + chunk: Buffer, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void { + this.data.push(chunk); + callback(); + } + + getText() { + const decoder = new TextDecoder(); + return decoder.decode(Buffer.concat(this.data as any)); + } +} + +describe("LLMLogFormatter", () => { + it("should format log items correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startChat", + options: { + model: "granite3.2-dense:8b", + }, + messages: [ + { + role: "system", + content: "You are a helpful assistant", + }, + ], + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "world!", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "\nHow can I help you?", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765434100, + kind: "success", + promptTokens: 10, + generatedTokens: 20, + thinkingTokens: 0, + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Chat]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Role: system", + " | You are a helpful assistant", + " +1.0 Role: assistant", + " | Hello, world!", + " +1.2 | How can I help you?", + " +2.0 Success", + " Prompt Tokens: 10", + " Generated Tokens: 20", + "", + ].join("\n"), + ); + }); + + it("should format completion interactions correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startComplete", + options: { + model: "granite3.2-dense:8b", + }, + prompt: "A horse is a horse", + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "chunk", + chunk: ", of course, of course", + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Complete]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Prompt:", + " | A horse is a horse", + " +1.0 Result:", + " | , of course, of course", + ].join("\n"), + ); + }); + + it("should format FIM interactions correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startFim", + options: { + model: "granite3.2-dense:8b", + }, + prefix: "A\nB", + suffix: "D\nE", + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "chunk", + chunk: "C", + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Fim]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Prefix:", + " | A", + " | B", + " Suffix:", + " | D", + " | E", + " +1.0 Result:", + " | C", + ].join("\n"), + ); + }); + + it("should interleave log items correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "2", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "World!", + }, + }); + logger._logItem({ + interactionId: "2", + timestamp: 1698765433400, + kind: "message", + message: { + role: "assistant", + content: "World!", + }, + }); + // Check if we end interaction 2 and start another interaction, + // it gets a different prefix marker. + logger._logItem({ + interactionId: "2", + timestamp: 1698765434000, + kind: "success", + promptTokens: 10, + generatedTokens: 20, + thinkingTokens: 0, + }); + logger._logItem({ + interactionId: "3", + timestamp: 1698765434100, + kind: "message", + message: { + role: "assistant", + content: "Hello, World!", + }, + }); + + expect(output.getText()).toBe( + [ + " 15:17:13.1 Role: assistant", + " | Hello, ", + "|15:17:13.2 Role: assistant", + "| | Hello, ", + " +0.2 | World!", + "| +0.2 | World!", + "| +0.8 Success", + "| Prompt Tokens: 10", + "| Generated Tokens: 20", + "&15:17:14.1 Role: assistant", + "& | Hello, World!", + ].join("\n"), + ); + }); + + it("should wrap long lines", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output, 40); + + // Test a single message long enough to wrap; the input is + // "", not "xxxx" to make sure we are writing the correct + // substrings. + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "<" + "x".repeat(58) + ">", + }, + }); + // Test when a first message doesn't wrap, but another message + // that continues the same line causes a wrap + logger._logItem({ + interactionId: "1", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "\n<" + "y".repeat(29), + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "y".repeat(29) + ">", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433400, + kind: "message", + message: { + role: "assistant", + content: "\n" + "Artichokes and Beans ".repeat(3), + }, + }); + + expect(output.getText()).toBe( + [ + " 15:17:13.1 Role: assistant", + " | <" + "x".repeat(39), + " . " + "x".repeat(19) + ">", + " +0.1 | <" + "y".repeat(39), + " +0.2 . " + "y".repeat(19) + ">", + " +0.3 | Artichokes and Beans Artichokes and", + " . Beans Artichokes and Beans ", + ].join("\n"), + ); + }); +}); diff --git a/core/llm/logFormatter.ts b/core/llm/logFormatter.ts new file mode 100644 index 000000000..cae469f77 --- /dev/null +++ b/core/llm/logFormatter.ts @@ -0,0 +1,426 @@ +import { Writable } from "stream"; +import { + AssistantChatMessage, + ChatMessage, + LLMInteractionCancel, + LLMInteractionError, + LLMInteractionItem, + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, + LLMInteractionSuccess, + ThinkingChatMessage, + ToolCallDelta, + UserChatMessage, +} from ".."; +import { LLMLogger } from "./logger"; + +// Markers for different overlapping interactions. +const LOG_PREFIXES = [" ", "|", "&", "%", "#"]; +// Wrap wide to avoid messing up code +const DEFAULT_WRAP_WIDTH = 100; + +interface InteractionData { + prefix: string; + startItem: LLMInteractionItem; + lastItem: LLMInteractionItem | null; +} + +function formatTimestamp(timestamp: number) { + const date = new Date(timestamp); + + const hours = date.getUTCHours().toString().padStart(2, "0"); + const minutes = date.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date.getUTCSeconds(); + const milliseconds = date.getUTCMilliseconds(); + + // Format seconds with one decimal place + const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`; + + return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`; +} + +/** + * A class that formats LLM log output as a human-readable stream. + * The general appearance of the output is something like: + * + * 01:23:45.6 [Chat] + * Options: { + * "maxTokens": 1000, + * } + * Role: system + * | You are a helpful assistant. + * Role: user + * | Who are you? + * +0.2 Role: assistant + * | How can I help you today? + * +0.3 | I can tell you about the weather or the stock mark + * +0.4 . et. [THIS LINE IS WRAPPED] + * |01:23:46.1 [Complete] + * | Options: { + * | "maxTokens": 1000, + * | } + * | Prefix: + * | | COMPLETE THIS + * +0.6 Success + * PromptTokens: 50 + * GeneratedTokens: 30 + * | +0.2 Result: + * | | COMPLETION + * + * The lines with | are a second interaction that starts while the + * first one is still in progress; every interaction starts with + * an absolute timestamp, and relative timestamps are included for + * separately received results in the same interaction. + */ +export class LLMLogFormatter { + // Current active interactions + private interactions: Record = {}; + private lastItem: LLMInteractionItem | null = null; + // Item that started the current line; we use this to determine + // if the next line needs a timestamp. + private lastLineStartItem: LLMInteractionItem | null = null; + private openLine: boolean = false; + private openLineChars: number = 0; + private lastFreedPrefix: string | null = null; + + /** + * Creates a new LLMLogWriter. + * @param logger - The LLMLogger instance to listen to for log items + * @param output - Stream to write formatted output to + * @param wrapWidth - Maximum width of a line before wrapping + */ + constructor( + private logger: LLMLogger, + private output: Writable, + private wrapWidth: number = DEFAULT_WRAP_WIDTH, + ) { + this.logger.onLogItem((item) => { + this.logItem(item); + }); + } + + private getInteractionData(item: LLMInteractionItem) { + let interaction = this.interactions[item.interactionId]; + if (interaction !== undefined) { + return interaction; + } + + let usedPrefixes = Object.values(this.interactions).map( + (interaction) => interaction.prefix, + ); + + // Select a prefix that is not currently in use, and is + // also not the last retired prefix - but with the + // exception that we can reuse the empty prefix " " + // immediately - this isn't confusing. + let i = 0; + let prefix; + while (true) { + const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`; + if ( + !usedPrefixes.includes(candidate) && + (candidate === " " || candidate !== this.lastFreedPrefix) + ) { + prefix = candidate; + break; + } + i++; + } + + this.interactions[item.interactionId] = { + prefix, + startItem: item, + lastItem: null, + }; + + return this.interactions[item.interactionId]; + } + + private formatTimestamp( + interaction: InteractionData, + item: LLMInteractionItem, + ) { + if (item !== this.lastLineStartItem) { + if (item === interaction.startItem) { + return formatTimestamp(item.timestamp); + } else { + const delta = (item.timestamp - interaction.startItem.timestamp) / 1000; + return ("+" + delta.toFixed(1)).padStart(10, " "); + } + } else { + return " "; + } + } + + // the implementation behind logLines and logMessageText + private logFragment( + item: LLMInteractionItem, + fragment: string, + startAt: number, + marker: string = "", + joinBefore: boolean = false, + joinAfter: boolean = false, + wrap: boolean = false, + ) { + const interaction = this.getInteractionData(item); + + if ( + this.openLine && + (!joinBefore || item.interactionId !== this.lastItem?.interactionId) + ) { + this.openLine = false; + this.openLineChars = 0; + this.output.write("\n"); + } + + let continueAt = null; + if ( + wrap && + fragment.length - startAt > this.wrapWidth - this.openLineChars + ) { + continueAt = startAt + this.wrapWidth - this.openLineChars; + + // Look for a better line-breaking point at whitespace + const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far + for (let i = continueAt; i > searchBackwardLimit; i--) { + if (/\s/.test(fragment.charAt(i))) { + continueAt = i + 1; // Break after the whitespace + break; + } + } + + // When there's whitespace immediately after the wrap width, + // the above will result in breaking *after* that, so we exceed + // the wrap width. The trimEnd() avoids that. + fragment = fragment.substring(startAt, continueAt).trimEnd(); + joinAfter = false; + } else if (startAt > 0) { + fragment = fragment.substring(startAt); + } + + if (!this.openLine || !this.openLine) { + let timestamp = this.formatTimestamp(interaction, item); + this.output.write(`${interaction.prefix}${timestamp} ${marker}`); + this.lastLineStartItem = item; + } + + this.output.write(fragment); + this.openLine = joinAfter; + this.lastItem = item; + if (!this.openLine) { + this.output.write("\n"); + this.openLineChars = 0; + } else { + this.openLineChars += fragment.length; + } + + return continueAt; + } + + // Use for everything but text content; a newline is + // implicitly added at the end of content + private logLines( + item: LLMInteractionItem, + content: string, + marker: string = "", + ) { + for (const line of content.split("\n")) { + this.logFragment(item, line, 0, marker); + } + } + + // This logs text context - as compared to logLines: + // - No newline is appended to the end of content + // - consecutive calls to logMessageText for the same interaction + // will join onto a single line + // - It will wrap text at the wrap width + private logMessageText(item: LLMInteractionItem, content: string) { + const lines = content.split("\n"); + for (let i = 0; i < lines.length; i++) { + let startAt: number | null = 0; + let marker = "| "; + while (startAt !== null) { + // When wrapping, the next start position is turned; + // null means we've written everything + startAt = this.logFragment( + item, + lines[i], + startAt, + marker, + true, + i === lines.length - 1, + true, + ); + marker = ". "; + } + } + } + + private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) { + for (const toolCall of toolsCalls) { + this.logLines( + item, + `Tool call: ${JSON.stringify(toolCall, undefined, 2)}`, + ); + } + } + + private logMessageContent( + item: LLMInteractionItem, + message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage, + ) { + if (typeof message.content === "string") { + this.logMessageText(item, message.content); + } else { + for (const part of message.content) { + if (part.type === "text") { + this.logMessageText(item, part.text); + } else { + this.logLines(item, `Image: ${part.imageUrl.url}`); + } + } + } + } + + private logMessage( + item: LLMInteractionItem, + message: ChatMessage, + forceRole: boolean = false, + ) { + let showRole = true; + if ( + !forceRole && + (message.role === "assistant" || message.role === "thinking") + ) { + const interaction = this.getInteractionData(item); + const lastMessage = + interaction.lastItem?.kind === "message" + ? interaction.lastItem.message + : null; + if (message.role === lastMessage?.role) { + showRole = false; + } + } + + if (showRole) { + this.logLines(item, "Role: " + message.role); + } + + switch (message.role) { + case "assistant": + if (message.toolCalls) { + this.logToolcalls(item, message.toolCalls); + } + this.logMessageContent(item, message); + break; + case "thinking": + if (message.toolCalls) { + this.logToolcalls(item, message.toolCalls); + } + this.logMessageContent(item, message); + if (message.redactedThinking) { + this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`); + } + if (message.signature) { + this.logLines(item, `Signature: ${message.signature}`); + } + break; + case "user": + this.logMessageContent(item, message); + break; + case "system": + this.logMessageText(item, message.content); + break; + case "tool": + this.logLines(item, `Tool Call ID: ${message.toolCallId}`); + this.logMessageText(item, message.content); + break; + } + } + + private logTokens( + item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel, + ) { + this.logLines(item, `Prompt Tokens: ${item.promptTokens}`); + this.logLines(item, `Generated Tokens: ${item.generatedTokens}`); + if (item.thinkingTokens > 0) { + this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`); + } + } + + private logOptions( + item: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim, + ) { + this.logLines( + item, + "Options: " + JSON.stringify(item.options, undefined, 2), + ); + } + + private logItem(item: LLMInteractionItem) { + const interaction = this.getInteractionData(item); + + switch (item.kind) { + case "startChat": + this.logLines(item, "[Chat]"); + this.logOptions(item); + let lastMessage = null; + for (let message of item.messages) { + this.logMessage(item, message, true); + } + break; + case "startComplete": + this.logLines(item, "[Complete]"); + this.logOptions(item); + this.logLines(item, "Prompt:"); + this.logLines(item, item.prompt, "| "); + break; + case "startFim": + this.logLines(item, "[Fim]"); + this.logOptions(item); + this.logLines(item, "Prefix:"); + this.logLines(item, item.prefix, "| "); + this.logLines(item, "Suffix:"); + this.logLines(item, item.suffix, "| "); + break; + case "chunk": + if (interaction.lastItem?.kind !== "chunk") { + this.logLines(item, "Result:"); + } + this.logMessageText(item, item.chunk); + break; + case "message": + this.logMessage(item, item.message); + break; + case "cancel": + this.logLines(item, "Cancelled"); + this.logTokens(item); + break; + case "error": + this.logLines(item, "Error"); + this.logTokens(item); + break; + case "success": + this.logLines(item, "Success"); + this.logTokens(item); + break; + } + + if ( + item.kind === "cancel" || + item.kind === "error" || + item.kind === "success" + ) { + if (interaction.prefix !== " ") { + this.lastFreedPrefix = interaction.prefix; + } + delete this.interactions[item.interactionId]; + } else { + interaction.lastItem = item; + } + } +} diff --git a/core/llm/logger.ts b/core/llm/logger.ts new file mode 100644 index 000000000..ae4699a45 --- /dev/null +++ b/core/llm/logger.ts @@ -0,0 +1,43 @@ +import { + ILLMLogger, + ILLMInteractionLog, + LLMInteractionItem, + LLMInteractionItemDetails, +} from ".."; + +type LLMLogItemFunction = (item: LLMInteractionItem) => void; + +export class LLMLogger implements ILLMLogger { + private nextId = 0; + + public createInteractionLog(): LLMInteractionLog { + return new LLMInteractionLog(this, (this.nextId++).toString()); + } + + private logItemListeners: LLMLogItemFunction[] = []; + + onLogItem(listener: LLMLogItemFunction) { + this.logItemListeners.push(listener); + } + + public _logItem(item: LLMInteractionItem) { + for (const listener of this.logItemListeners) { + listener(item); + } + } +} + +export class LLMInteractionLog implements ILLMInteractionLog { + constructor( + private logger: LLMLogger, + public interactionId: string, + ) {} + + logItem(item: LLMInteractionItemDetails) { + this.logger._logItem({ + ...item, + interactionId: this.interactionId, + timestamp: Date.now(), + }); + } +} diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts new file mode 100644 index 000000000..f50b9972a --- /dev/null +++ b/core/llm/rules/isRuleActive.test.ts @@ -0,0 +1,59 @@ +import { isRuleActive } from "./isRuleActive"; + +describe("isRuleActive", () => { + const rule = { + name: "My Rule", + rule: "Do no harm", + if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', + }; + + it("should return false when activePaths is empty", () => { + expect( + isRuleActive({ + rule, + activePaths: [], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return false when no matching paths exist", () => { + expect( + isRuleActive({ + rule, + activePaths: ["test.py", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return true when both conditions are met", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(true); + }); + + it("should return false when only glob matches but model doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx"], + currentModel: "gpt-4", + }), + ).toBe(false); + }); + + it("should return false when model matches but glob doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.ts"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); +}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts new file mode 100644 index 000000000..47125c644 --- /dev/null +++ b/core/llm/rules/isRuleActive.ts @@ -0,0 +1,68 @@ +import { Rule } from "@continuedev/config-yaml"; +import { compileExpression } from "filtrex"; +import { minimatch } from "minimatch"; + +const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; + +const createGlobFunction = (activePaths: string[]) => { + return (pattern: string) => { + const result = activePaths.some((path) => minimatch(path, pattern)); + return result; + }; +}; + +const contains = (str: string, searchStr: string): boolean => { + return str.includes(searchStr); +}; + +const evaluateIf = ({ + condition, + activePaths, + currentModel, +}: { + condition: string; + activePaths: string[]; + currentModel: string; +}) => { + const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); + if (!expression) { + return true; + } + + try { + const evaluate = compileExpression(expression, { + extraFunctions: { + glob: createGlobFunction(activePaths), + contains, + }, + constants: { + "current.model.model": currentModel, + }, + }); + + return evaluate({}); + } catch (error) { + console.error("Error evaluating rule condition:", error); + return false; + } +}; + +export const isRuleActive = ({ + rule, + activePaths, + currentModel, +}: { + rule: Rule; + activePaths: string[]; + currentModel: string; +}): boolean => { + if (typeof rule === "string") { + return true; + } + + if (rule.if) { + return evaluateIf({ condition: rule.if, activePaths, currentModel }); + } + + return true; +}; diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index 9b1ea87b3..223b5b20e 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -23,19 +23,22 @@ export async function* llmStreamChat( void TTS.kill(); } - const { title, legacySlashCommandData, completionOptions, messages } = - msg.data; + const { legacySlashCommandData, completionOptions, messages } = msg.data; - const model = await configHandler.llmFromTitle(title); + const model = config.selectedModelByRole.chat; + + if (!model) { + throw new Error("No chat model selected"); + } // Log to return in case of error const errorPromptLog = { - modelTitle: model.title ?? model.model, + modelTitle: model?.title ?? model?.model, completion: "", prompt: "", completionOptions: { ...msg.data.completionOptions, - model: model.model, + model: model?.model, }, }; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 7f4975170..3d0d72cc8 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -82,7 +82,7 @@ export const PROVIDER_TOOL_SUPPORT: Record< } else { modelName = model; } - + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( (part) => modelName.toLowerCase().includes(part), @@ -92,6 +92,7 @@ export const PROVIDER_TOOL_SUPPORT: Record< } if ( [ + "cogito", "llama3.3", "qwq", "llama3.2", diff --git a/core/llm/utils/__tests__/getSecureID.test.ts b/core/llm/utils/__tests__/getSecureID.test.ts new file mode 100644 index 000000000..9c4ffd6e7 --- /dev/null +++ b/core/llm/utils/__tests__/getSecureID.test.ts @@ -0,0 +1,49 @@ +import { getSecureID } from '../getSecureID'; + +// Mock the crypto.randomUUID function +const mockRandomUUID = jest.fn(); +global.crypto = { + ...global.crypto, + randomUUID: mockRandomUUID +}; + +describe('getSecureID', () => { + beforeEach(() => { + // Reset the static property before each test + (getSecureID as any).uuid = undefined; + + // Reset the mock implementation + mockRandomUUID.mockReset(); + // Setup a mock implementation that returns a fixed value for testing + mockRandomUUID.mockReturnValue('test-uuid-1234'); + }); + + test('should generate a UUID on first call', () => { + const result = getSecureID(); + expect(mockRandomUUID).toHaveBeenCalledTimes(1); + expect(result).toBe(''); + }); + + test('should reuse the same UUID on subsequent calls', () => { + const firstResult = getSecureID(); + const secondResult = getSecureID(); + + // The UUID generation should only happen once + expect(mockRandomUUID).toHaveBeenCalledTimes(1); + + // Both results should be identical + expect(firstResult).toBe(secondResult); + expect(firstResult).toBe(''); + }); + + test('should maintain the same UUID across different test cases if not reset', () => { + // Don't reset the UUID here to test persistence + (getSecureID as any).uuid = 'persistent-uuid'; + + const result = getSecureID(); + + // No new UUID should be generated + expect(mockRandomUUID).not.toHaveBeenCalled(); + expect(result).toBe(''); + }); +}); \ No newline at end of file diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts new file mode 100644 index 000000000..7573a1f6f --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -0,0 +1,22 @@ +/** + * Extracts file paths from markdown code blocks + */ +export function extractPathsFromCodeBlocks(content: string): string[] { + // Match: + // 1. Starting ``` + // 2. Optional language identifier + // 3. Required whitespace + // 4. File path (captured) that must contain a dot and extension + const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g; + const paths: string[] = []; + let match; + + while ((match = codeBlockRegex.exec(content)) !== null) { + const path = match[1]; + if (path && !path.startsWith("```")) { + paths.push(path); + } + } + + return paths; +} diff --git a/core/llm/utils/getSecureID.ts b/core/llm/utils/getSecureID.ts new file mode 100644 index 000000000..b05fefab6 --- /dev/null +++ b/core/llm/utils/getSecureID.ts @@ -0,0 +1,8 @@ +// Utility function to get or generate UUID for LLM prompts +export function getSecureID(): string { + // Adding a type declaration for the static property + if (!(getSecureID as any).uuid) { + (getSecureID as any).uuid = crypto.randomUUID(); + } + return ``; +} diff --git a/core/package-lock.json b/core/package-lock.json index 50df2a6f3..494992220 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -9,11 +9,11 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.758.0", - "@aws-sdk/client-sagemaker-runtime": "^3.758.0", - "@aws-sdk/credential-providers": "^3.758.0", + "@aws-sdk/client-bedrock-runtime": "^3.779.0", + "@aws-sdk/client-sagemaker-runtime": "^3.777.0", + "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -32,6 +32,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -107,6 +108,27 @@ "node": ">=20.11.0" } }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2" + } + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -289,51 +311,51 @@ } }, "node_modules/@aws-sdk/client-bedrock-runtime": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.758.0.tgz", - "integrity": "sha512-T7s+fULUxN3AcJP+lgoUKLawzVEtyCTi+5Ga+wrHnqEPwAsM/wg7VctsZfow1fCgARLT/lzmP2LTCi8ycRnQWg==", + "version": "3.779.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.779.0.tgz", + "integrity": "sha512-MyzZks8XxWwdsA4VlyPW4IekUjpgDI91VwMvEtOITHD8w+9nTGJtD32HcCKNQQCHWYfSoOj7yIoHRisVatR8yw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/eventstream-serde-browser": "^4.0.1", - "@smithy/eventstream-serde-config-resolver": "^4.0.1", - "@smithy/eventstream-serde-node": "^4.0.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/eventstream-serde-browser": "^4.0.2", + "@smithy/eventstream-serde-config-resolver": "^4.1.0", + "@smithy/eventstream-serde-node": "^4.0.2", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "@types/uuid": "^9.0.1", "tslib": "^2.6.2", @@ -344,47 +366,47 @@ } }, "node_modules/@aws-sdk/client-cognito-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.758.0.tgz", - "integrity": "sha512-8bOXVYtf/0OUN0jXTIHLv3V0TAS6kvvCRAy7nmiL/fDde0O+ChW1WZU7CVPAOtFEpFCdKskDcxFspM7m1k6qyg==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.777.0.tgz", + "integrity": "sha512-VGtFI3SH+jKfPln+9CM16F9zKieIqSxUSZNzQ6WZahPDVC79VmlG6QkXCqgm9Y4qZf4ebcdMhO23+FkR4s9vhA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -393,51 +415,51 @@ } }, "node_modules/@aws-sdk/client-sagemaker-runtime": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.758.0.tgz", - "integrity": "sha512-6pZdZT+Xol56UKcpUDzOlRwLgmVIgv4I2bvCsvq4YI0TnSNhO6/Ob2I8l0GzUTU2qoO2XBkrhO1t+zLuc681ig==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.777.0.tgz", + "integrity": "sha512-b5IE89QOt7pvaImtDiOmUlKVGK7pcb3rW7nIKEqY65pJboIT/RNkehfA/XrlfgDjgGhVebojpUm/paqG+2xlDg==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/eventstream-serde-browser": "^4.0.1", - "@smithy/eventstream-serde-config-resolver": "^4.0.1", - "@smithy/eventstream-serde-node": "^4.0.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/eventstream-serde-browser": "^4.0.2", + "@smithy/eventstream-serde-config-resolver": "^4.1.0", + "@smithy/eventstream-serde-node": "^4.0.2", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -446,46 +468,46 @@ } }, "node_modules/@aws-sdk/client-sso": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.758.0.tgz", - "integrity": "sha512-BoGO6IIWrLyLxQG6txJw6RT2urmbtlwfggapNCrNPyYjlXpzTSJhBYjndg7TpDATFd0SXL0zm8y/tXsUXNkdYQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.777.0.tgz", + "integrity": "sha512-0+z6CiAYIQa7s6FJ+dpBYPi9zr9yY5jBg/4/FGcwYbmqWPXwL9Thdtr0FearYRZgKl7bhL3m3dILCCfWqr3teQ==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -494,19 +516,19 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.758.0.tgz", - "integrity": "sha512-0RswbdR9jt/XKemaLNuxi2gGr4xGlHyGxkTdhSQzCyUe9A9OPCoLl3rIESRguQEech+oJnbHk/wuiwHqTuP9sg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.775.0.tgz", + "integrity": "sha512-8vpW4WihVfz0DX+7WnnLGm3GuQER++b0IwQG35JlQMlgqnc44M//KbJPsIHA0aJUJVwJAEShgfr5dUbY8WUzaA==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/core": "^3.1.5", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/signature-v4": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", + "@aws-sdk/types": "3.775.0", + "@smithy/core": "^3.2.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/signature-v4": "^5.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", "fast-xml-parser": "4.4.1", "tslib": "^2.6.2" }, @@ -515,14 +537,14 @@ } }, "node_modules/@aws-sdk/credential-provider-cognito-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.758.0.tgz", - "integrity": "sha512-y/rHZqyChlEkNRr59gn4hv0gjhJwGmdCdW0JI1K9p3P9p7EurWGjr2M6+goTn3ilOlcAwrl5oFKR5jLt27TkOA==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.777.0.tgz", + "integrity": "sha512-lNvz3v94TvEcBvQqVUyg+c/aL3Max+8wUMXvehWoQPv9y9cJAHciZqvA/G+yFo/JB+1Y4IBpMu09W2lfpT6Euw==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-cognito-identity": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -530,14 +552,14 @@ } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.758.0.tgz", - "integrity": "sha512-N27eFoRrO6MeUNumtNHDW9WOiwfd59LPXPqDrIa3kWL/s+fOKFHb9xIcF++bAwtcZnAxKkgpDCUP+INNZskE+w==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.775.0.tgz", + "integrity": "sha512-6ESVxwCbGm7WZ17kY1fjmxQud43vzJFoLd4bmlR+idQSWdqlzGDYdcfzpjDKTcivdtNrVYmFvcH1JBUwCRAZhw==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -545,19 +567,19 @@ } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.758.0.tgz", - "integrity": "sha512-Xt9/U8qUCiw1hihztWkNeIR+arg6P+yda10OuCHX6kFVx3auTlU7+hCqs3UxqniGU4dguHuftf3mRpi5/GJ33Q==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.775.0.tgz", + "integrity": "sha512-PjDQeDH/J1S0yWV32wCj2k5liRo0ssXMseCBEkCsD3SqsU8o5cU82b0hMX4sAib/RkglCSZqGO0xMiN0/7ndww==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.1.2", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -565,22 +587,22 @@ } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.758.0.tgz", - "integrity": "sha512-cymSKMcP5d+OsgetoIZ5QCe1wnp2Q/tq+uIxVdh9MbfdBBEnl9Ecq6dH6VlYS89sp4QKuxHxkWXVnbXU3Q19Aw==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.777.0.tgz", + "integrity": "sha512-1X9mCuM9JSQPmQ+D2TODt4THy6aJWCNiURkmKmTIPRdno7EIKgAqrr/LLN++K5mBf54DZVKpqcJutXU2jwo01A==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -588,21 +610,21 @@ } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.758.0.tgz", - "integrity": "sha512-+DaMv63wiq7pJrhIQzZYMn4hSarKiizDoJRvyR7WGhnn0oQ/getX9Z0VNCV3i7lIFoLNTb7WMmQ9k7+z/uD5EQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.777.0.tgz", + "integrity": "sha512-ZD66ywx1Q0KyUSuBXZIQzBe3Q7MzX8lNwsrCU43H3Fww+Y+HB3Ncws9grhSdNhKQNeGmZ+MgKybuZYaaeLwJEQ==", "dependencies": { - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-ini": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-ini": "3.777.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -610,15 +632,15 @@ } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.758.0.tgz", - "integrity": "sha512-AzcY74QTPqcbXWVgjpPZ3HOmxQZYPROIBz2YINF0OQk0MhezDWV/O7Xec+K1+MPGQO3qS6EDrUUlnPLjsqieHA==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.775.0.tgz", + "integrity": "sha512-A6k68H9rQp+2+7P7SGO90Csw6nrUEm0Qfjpn9Etc4EboZhhCLs9b66umUsTsSBHus4FDIe5JQxfCUyt1wgNogg==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -626,17 +648,17 @@ } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.758.0.tgz", - "integrity": "sha512-x0FYJqcOLUCv8GLLFDYMXRAQKGjoM+L0BG4BiHYZRDf24yQWFCAZsCQAYKo6XZYh2qznbsW6f//qpyJ5b0QVKQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.777.0.tgz", + "integrity": "sha512-9mPz7vk9uE4PBVprfINv4tlTkyq1OonNevx2DiXC1LY4mCUCNN3RdBwAY0BTLzj0uyc3k5KxFFNbn3/8ZDQP7w==", "dependencies": { - "@aws-sdk/client-sso": "3.758.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/token-providers": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-sso": "3.777.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/token-providers": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -644,15 +666,15 @@ } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.758.0.tgz", - "integrity": "sha512-XGguXhBqiCXMXRxcfCAVPlMbm3VyJTou79r/3mxWddHWF0XbhaQiBIbUz6vobVTD25YQRbWSmSch7VA8kI5Lrw==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.777.0.tgz", + "integrity": "sha512-uGCqr47fnthkqwq5luNl2dksgcpHHjSXz2jUra7TXtFOpqvnhOW8qXjoa1ivlkq8qhqlaZwCzPdbcN0lXpmLzQ==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -660,26 +682,28 @@ } }, "node_modules/@aws-sdk/credential-providers": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.758.0.tgz", - "integrity": "sha512-BaGVBdm9ynsErIc/mLuUwJ1OQcL/pkhCuAm24jpsif3evZ5wgyZnEAZB2yRin+mQnQaQT3L+KvTbdKGfjL8+fQ==", + "version": "3.778.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.778.0.tgz", + "integrity": "sha512-Yy1RSBvoDp/iqGDpmgy5/YnSP2ac9NxTv3wdAjKlqVVStlKWU9nG8MPHZRfy01oPNJ5YWZL9stxHjNKC9hg9eg==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.758.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-cognito-identity": "3.758.0", - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-ini": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/core": "^3.1.5", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-cognito-identity": "3.777.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-cognito-identity": "3.777.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-ini": "3.777.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -687,13 +711,13 @@ } }, "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.734.0.tgz", - "integrity": "sha512-LW7RRgSOHHBzWZnigNsDIzu3AiwtjeI2X66v+Wn1P1u+eXssy1+up4ZY/h+t2sU4LU36UvEf+jrZti9c6vRnFw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.775.0.tgz", + "integrity": "sha512-tkSegM0Z6WMXpLB8oPys/d+umYIocvO298mGvcMCncpRl77L9XkvSLJIFzaHes+o7djAgIduYw8wKIMStFss2w==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -701,12 +725,12 @@ } }, "node_modules/@aws-sdk/middleware-logger": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.734.0.tgz", - "integrity": "sha512-mUMFITpJUW3LcKvFok176eI5zXAUomVtahb9IQBwLzkqFYOrMJvWAvoV4yuxrJ8TlQBG8gyEnkb9SnhZvjg67w==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.775.0.tgz", + "integrity": "sha512-FaxO1xom4MAoUJsldmR92nT1G6uZxTdNYOFYtdHfd6N2wcNaTuxgjIvqzg5y7QIH9kn58XX/dzf1iTjgqUStZw==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -714,13 +738,13 @@ } }, "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.734.0.tgz", - "integrity": "sha512-CUat2d9ITsFc2XsmeiRQO96iWpxSKYFjxvj27Hc7vo87YUHRnfMfnc8jw1EpxEwMcvBD7LsRa6vDNky6AjcrFA==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.775.0.tgz", + "integrity": "sha512-GLCzC8D0A0YDG5u3F5U03Vb9j5tcOEFhr8oc6PDk0k0vm5VwtZOE6LvK7hcCSoAB4HXyOUM0sQuXrbaAh9OwXA==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -728,16 +752,16 @@ } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.758.0.tgz", - "integrity": "sha512-iNyehQXtQlj69JCgfaOssgZD4HeYGOwxcaKeG6F+40cwBjTAi0+Ph1yfDwqk2qiBPIRWJ/9l2LodZbxiBqgrwg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.775.0.tgz", + "integrity": "sha512-7Lffpr1ptOEDE1ZYH1T78pheEY1YmeXWBfFt/amZ6AGsKSLG+JPXvof3ltporTGR2bhH/eJPo7UHCglIuXfzYg==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@smithy/core": "^3.1.5", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@smithy/core": "^3.2.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -745,46 +769,46 @@ } }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.758.0.tgz", - "integrity": "sha512-YZ5s7PSvyF3Mt2h1EQulCG93uybprNGbBkPmVuy/HMMfbFTt4iL3SbKjxqvOZelm86epFfj7pvK7FliI2WOEcg==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.777.0.tgz", + "integrity": "sha512-bmmVRsCjuYlStYPt06hr+f8iEyWg7+AklKCA8ZLDEJujXhXIowgUIqXmqpTkXwkVvDQ9tzU7hxaONjyaQCGybA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -793,15 +817,15 @@ } }, "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.734.0.tgz", - "integrity": "sha512-Lvj1kPRC5IuJBr9DyJ9T9/plkh+EfKLy+12s/mykOy1JaKHDpvj+XGy2YO6YgYVOb8JFtaqloid+5COtje4JTQ==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.775.0.tgz", + "integrity": "sha512-40iH3LJjrQS3LKUJAl7Wj0bln7RFPEvUYKFxtP8a+oKFDO0F65F52xZxIJbPn6sHkxWDAnZlGgdjZXM3p2g5wQ==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -809,15 +833,15 @@ } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.758.0.tgz", - "integrity": "sha512-ckptN1tNrIfQUaGWm/ayW1ddG+imbKN7HHhjFdS4VfItsP0QQOB0+Ov+tpgb4MoNR4JaUghMIVStjIeHN2ks1w==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.777.0.tgz", + "integrity": "sha512-Yc2cDONsHOa4dTSGOev6Ng2QgTKQUEjaUnsyKd13pc/nLLz/WLqHiQ/o7PcnKERJxXGs1g1C6l3sNXiX+kbnFQ==", "dependencies": { - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -825,11 +849,11 @@ } }, "node_modules/@aws-sdk/types": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.734.0.tgz", - "integrity": "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.775.0.tgz", + "integrity": "sha512-ZoGKwa4C9fC9Av6bdfqcW6Ix5ot05F/S4VxWR2nHuMv7hzfmAjTOcUiWT7UR4hM/U0whf84VhDtXN/DWAk52KA==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -837,13 +861,13 @@ } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.743.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.743.0.tgz", - "integrity": "sha512-sN1l559zrixeh5x+pttrnd0A3+r34r0tmPkJ/eaaMaAzXqsmKU/xYre9K3FNnsSS1J1k4PEfk/nHDTVUgFYjnw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.775.0.tgz", + "integrity": "sha512-yjWmUgZC9tUxAo8Uaplqmq0eUh0zrbZJdwxGRKdYxfm4RG6fMw1tj52+KkatH7o+mNZvg1GDcVp/INktxonJLw==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", - "@smithy/util-endpoints": "^3.0.1", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", + "@smithy/util-endpoints": "^3.0.2", "tslib": "^2.6.2" }, "engines": { @@ -862,25 +886,25 @@ } }, "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.734.0.tgz", - "integrity": "sha512-xQTCus6Q9LwUuALW+S76OL0jcWtMOVu14q+GoLnWPUM7QeUw963oQcLhF7oq0CtaLLKyl4GOUfcwc773Zmwwng==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.775.0.tgz", + "integrity": "sha512-txw2wkiJmZKVdDbscK7VBK+u+TJnRtlUjRTLei+elZg2ADhpQxfVAQl436FUeIv6AhB/oRHW6/K/EAGXUSWi0A==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.758.0.tgz", - "integrity": "sha512-A5EZw85V6WhoKMV2hbuFRvb9NPlxEErb4HPO6/SPXYY4QrjprIzScHxikqcWv1w4J3apB1wto9LPU3IMsYtfrw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.775.0.tgz", + "integrity": "sha512-N9yhTevbizTOMo3drH7Eoy6OkJ3iVPxhV7dwb6CMAObbLneS36CSfA6xQXupmHWcRvZPTz8rd1JGG3HzFOau+g==", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -2974,14 +2998,8 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@continuedev/fetch": { "version": "1.0.4", @@ -4533,11 +4551,11 @@ } }, "node_modules/@smithy/abort-controller": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.1.tgz", - "integrity": "sha512-fiUIYgIgRjMWznk6iLJz35K2YxSLHzLBA/RC6lBrKfQ8fHbPfvk7Pk9UvpKoHgJjI18MnbPuEju53zcVy6KF1g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.2.tgz", + "integrity": "sha512-Sl/78VDtgqKxN2+1qduaVE140XF+Xg+TafkncspwM4jFP/LHr76ZHmIY/y3V1M0mMLNk+Je6IGbzxy23RSToMw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4545,14 +4563,14 @@ } }, "node_modules/@smithy/config-resolver": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.0.1.tgz", - "integrity": "sha512-Igfg8lKu3dRVkTSEm98QpZUvKEOa71jDX4vKRcvJVyRc3UgN3j7vFMf0s7xLQhYmKa8kyJGQgUJDOV5V3neVlQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.1.0.tgz", + "integrity": "sha512-8smPlwhga22pwl23fM5ew4T9vfLUCeFXlcqNOCD5M5h8VmNPNUE9j6bQSuRXpDSV11L/E/SwEBQuW8hr6+nS1A==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4560,16 +4578,16 @@ } }, "node_modules/@smithy/core": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.1.5.tgz", - "integrity": "sha512-HLclGWPkCsekQgsyzxLhCQLa8THWXtB5PxyYN+2O6nkyLt550KQKTlbV2D1/j5dNIQapAZM1+qFnpBFxZQkgCA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.2.0.tgz", + "integrity": "sha512-k17bgQhVZ7YmUvA8at4af1TDpl0NDMBuBKJl8Yg0nrefwmValU+CnA5l/AriVdQNthU/33H3nK71HrLgqOPr1Q==", "dependencies": { - "@smithy/middleware-serde": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -4578,14 +4596,14 @@ } }, "node_modules/@smithy/credential-provider-imds": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.1.tgz", - "integrity": "sha512-l/qdInaDq1Zpznpmev/+52QomsJNZ3JkTl5yrTl02V6NBgJOQ4LY0SFw/8zsMwj3tLe8vqiIuwF6nxaEwgf6mg==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.2.tgz", + "integrity": "sha512-32lVig6jCaWBHnY+OEQ6e6Vnt5vDHaLiydGrwYMW9tPqO688hPGTYRamYJ1EptxEC2rAwJrHWmPoKRBl4iTa8w==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4593,12 +4611,12 @@ } }, "node_modules/@smithy/eventstream-codec": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.1.tgz", - "integrity": "sha512-Q2bCAAR6zXNVtJgifsU16ZjKGqdw/DyecKNgIgi7dlqw04fqDu0mnq+JmGphqheypVc64CYq3azSuCpAdFk2+A==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.2.tgz", + "integrity": "sha512-p+f2kLSK7ZrXVfskU/f5dzksKTewZk8pJLPvER3aFHPt76C2MxD9vNatSfLzzQSQB4FNO96RK4PSXfhD1TTeMQ==", "dependencies": { "@aws-crypto/crc32": "5.2.0", - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", "tslib": "^2.6.2" }, @@ -4607,12 +4625,12 @@ } }, "node_modules/@smithy/eventstream-serde-browser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.0.1.tgz", - "integrity": "sha512-HbIybmz5rhNg+zxKiyVAnvdM3vkzjE6ccrJ620iPL8IXcJEntd3hnBl+ktMwIy12Te/kyrSbUb8UCdnUT4QEdA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.0.2.tgz", + "integrity": "sha512-CepZCDs2xgVUtH7ZZ7oDdZFH8e6Y2zOv8iiX6RhndH69nlojCALSKK+OXwZUgOtUZEUaZ5e1hULVCHYbCn7pug==", "dependencies": { - "@smithy/eventstream-serde-universal": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-serde-universal": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4620,11 +4638,11 @@ } }, "node_modules/@smithy/eventstream-serde-config-resolver": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.0.1.tgz", - "integrity": "sha512-lSipaiq3rmHguHa3QFF4YcCM3VJOrY9oq2sow3qlhFY+nBSTF/nrO82MUQRPrxHQXA58J5G1UnU2WuJfi465BA==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.1.0.tgz", + "integrity": "sha512-1PI+WPZ5TWXrfj3CIoKyUycYynYJgZjuQo8U+sphneOtjsgrttYybdqESFReQrdWJ+LKt6NEdbYzmmfDBmjX2A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4632,12 +4650,12 @@ } }, "node_modules/@smithy/eventstream-serde-node": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.0.1.tgz", - "integrity": "sha512-o4CoOI6oYGYJ4zXo34U8X9szDe3oGjmHgsMGiZM0j4vtNoT+h80TLnkUcrLZR3+E6HIxqW+G+9WHAVfl0GXK0Q==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.0.2.tgz", + "integrity": "sha512-C5bJ/C6x9ENPMx2cFOirspnF9ZsBVnBMtP6BdPl/qYSuUawdGQ34Lq0dMcf42QTjUZgWGbUIZnz6+zLxJlb9aw==", "dependencies": { - "@smithy/eventstream-serde-universal": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-serde-universal": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4645,12 +4663,12 @@ } }, "node_modules/@smithy/eventstream-serde-universal": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.1.tgz", - "integrity": "sha512-Z94uZp0tGJuxds3iEAZBqGU2QiaBHP4YytLUjwZWx+oUeohCsLyUm33yp4MMBmhkuPqSbQCXq5hDet6JGUgHWA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.2.tgz", + "integrity": "sha512-St8h9JqzvnbB52FtckiHPN4U/cnXcarMniXRXTKn0r4b4XesZOGiAyUdj1aXbqqn1icSqBlzzUsCl6nPB018ng==", "dependencies": { - "@smithy/eventstream-codec": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-codec": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4658,13 +4676,13 @@ } }, "node_modules/@smithy/fetch-http-handler": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.1.tgz", - "integrity": "sha512-3aS+fP28urrMW2KTjb6z9iFow6jO8n3MFfineGbndvzGZit3taZhKWtTorf+Gp5RpFDDafeHlhfsGlDCXvUnJA==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.2.tgz", + "integrity": "sha512-+9Dz8sakS9pe7f2cBocpJXdeVjMopUDLgZs1yWeu7h++WqSbjUYv/JAJwKwXw1HV6gq1jyWjxuyn24E2GhoEcQ==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "tslib": "^2.6.2" }, @@ -4673,11 +4691,11 @@ } }, "node_modules/@smithy/hash-node": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.1.tgz", - "integrity": "sha512-TJ6oZS+3r2Xu4emVse1YPB3Dq3d8RkZDKcPr71Nj/lJsdAP1c7oFzYqEn1IBc915TsgLl2xIJNuxCz+gLbLE0w==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.2.tgz", + "integrity": "sha512-VnTpYPnRUE7yVhWozFdlxcYknv9UN7CeOqSrMH+V877v4oqtVYuoqhIhtSjmGPvYrYnAkaM61sLMKHvxL138yg==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -4687,11 +4705,11 @@ } }, "node_modules/@smithy/invalid-dependency": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.1.tgz", - "integrity": "sha512-gdudFPf4QRQ5pzj7HEnu6FhKRi61BfH/Gk5Yf6O0KiSbr1LlVhgjThcvjdu658VE6Nve8vaIWB8/fodmS1rBPQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.2.tgz", + "integrity": "sha512-GatB4+2DTpgWPday+mnUkoumP54u/MDM/5u44KF9hIu8jF0uafZtQLcdfIKkIcUNuF/fBojpLEHZS/56JqPeXQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4710,12 +4728,12 @@ } }, "node_modules/@smithy/middleware-content-length": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.1.tgz", - "integrity": "sha512-OGXo7w5EkB5pPiac7KNzVtfCW2vKBTZNuCctn++TTSOMpe6RZO/n6WEC1AxJINn3+vWLKW49uad3lo/u0WJ9oQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.2.tgz", + "integrity": "sha512-hAfEXm1zU+ELvucxqQ7I8SszwQ4znWMbNv6PLMndN83JJN41EPuS93AIyh2N+gJ6x8QFhzSO6b7q2e6oClDI8A==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4723,17 +4741,17 @@ } }, "node_modules/@smithy/middleware-endpoint": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.0.6.tgz", - "integrity": "sha512-ftpmkTHIFqgaFugcjzLZv3kzPEFsBFSnq1JsIkr2mwFzCraZVhQk2gqN51OOeRxqhbPTkRFj39Qd2V91E/mQxg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.1.0.tgz", + "integrity": "sha512-xhLimgNCbCzsUppRTGXWkZywksuTThxaIB0HwbpsVLY5sceac4e1TZ/WKYqufQLaUy+gUSJGNdwD2jo3cXL0iA==", "dependencies": { - "@smithy/core": "^3.1.5", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", - "@smithy/util-middleware": "^4.0.1", + "@smithy/core": "^3.2.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4741,17 +4759,17 @@ } }, "node_modules/@smithy/middleware-retry": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.0.7.tgz", - "integrity": "sha512-58j9XbUPLkqAcV1kHzVX/kAR16GT+j7DUZJqwzsxh1jtz7G82caZiGyyFgUvogVfNTg3TeAOIJepGc8TXF4AVQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.1.0.tgz", + "integrity": "sha512-2zAagd1s6hAaI/ap6SXi5T3dDwBOczOMCSkkYzktqN1+tzbk1GAsHNAdo/1uzxz3Ky02jvZQwbi/vmDA6z4Oyg==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/service-error-classification": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/service-error-classification": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "tslib": "^2.6.2", "uuid": "^9.0.1" }, @@ -4760,11 +4778,11 @@ } }, "node_modules/@smithy/middleware-serde": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.2.tgz", - "integrity": "sha512-Sdr5lOagCn5tt+zKsaW+U2/iwr6bI9p08wOkCp6/eL6iMbgdtc2R5Ety66rf87PeohR0ExI84Txz9GYv5ou3iQ==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.3.tgz", + "integrity": "sha512-rfgDVrgLEVMmMn0BI8O+8OVr6vXzjV7HZj57l0QxslhzbvVfikZbVfBVthjLHqib4BW44QhcIgJpvebHlRaC9A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4772,11 +4790,11 @@ } }, "node_modules/@smithy/middleware-stack": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.1.tgz", - "integrity": "sha512-dHwDmrtR/ln8UTHpaIavRSzeIk5+YZTBtLnKwDW3G2t6nAupCiQUvNzNoHBpik63fwUaJPtlnMzXbQrNFWssIA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.2.tgz", + "integrity": "sha512-eSPVcuJJGVYrFYu2hEq8g8WWdJav3sdrI4o2c6z/rjnYDd3xH9j9E7deZQCzFn4QvGPouLngH3dQ+QVTxv5bOQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4784,13 +4802,13 @@ } }, "node_modules/@smithy/node-config-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.0.1.tgz", - "integrity": "sha512-8mRTjvCtVET8+rxvmzRNRR0hH2JjV0DFOmwXPrISmTIJEfnCBugpYYGAsCj8t41qd+RB5gbheSQ/6aKZCQvFLQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.0.2.tgz", + "integrity": "sha512-WgCkILRZfJwJ4Da92a6t3ozN/zcvYyJGUTmfGbgS/FkCcoCjl7G4FJaCDN1ySdvLvemnQeo25FdkyMSTSwulsw==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4798,14 +4816,14 @@ } }, "node_modules/@smithy/node-http-handler": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.3.tgz", - "integrity": "sha512-dYCLeINNbYdvmMLtW0VdhW1biXt+PPCGazzT5ZjKw46mOtdgToQEwjqZSS9/EN8+tNs/RO0cEWG044+YZs97aA==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.4.tgz", + "integrity": "sha512-/mdqabuAT3o/ihBGjL94PUbTSPSRJ0eeVTdgADzow0wRJ0rN4A27EOrtlK56MYiO1fDvlO3jVTCxQtQmK9dZ1g==", "dependencies": { - "@smithy/abort-controller": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/abort-controller": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4813,11 +4831,11 @@ } }, "node_modules/@smithy/property-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.1.tgz", - "integrity": "sha512-o+VRiwC2cgmk/WFV0jaETGOtX16VNPp2bSQEzu0whbReqE1BMqsP2ami2Vi3cbGVdKu1kq9gQkDAGKbt0WOHAQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.2.tgz", + "integrity": "sha512-wNRoQC1uISOuNc2s4hkOYwYllmiyrvVXWMtq+TysNRVQaHm4yoafYQyjN/goYZS+QbYlPIbb/QRjaUZMuzwQ7A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4825,11 +4843,11 @@ } }, "node_modules/@smithy/protocol-http": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.0.1.tgz", - "integrity": "sha512-TE4cpj49jJNB/oHyh/cRVEgNZaoPaxd4vteJNB0yGidOCVR0jCw/hjPVsT8Q8FRmj8Bd3bFZt8Dh7xGCT+xMBQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.1.0.tgz", + "integrity": "sha512-KxAOL1nUNw2JTYrtviRRjEnykIDhxc84qMBzxvu1MUfQfHTuBlCG7PA6EdVwqpJjH7glw7FqQoFxUJSyBQgu7g==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4837,11 +4855,11 @@ } }, "node_modules/@smithy/querystring-builder": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.1.tgz", - "integrity": "sha512-wU87iWZoCbcqrwszsOewEIuq+SU2mSoBE2CcsLwE0I19m0B2gOJr1MVjxWcDQYOzHbR1xCk7AcOBbGFUYOKvdg==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.2.tgz", + "integrity": "sha512-NTOs0FwHw1vimmQM4ebh+wFQvOwkEf/kQL6bSM1Lock+Bv4I89B3hGYoUEPkmvYPkDKyp5UdXJYu+PoTQ3T31Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-uri-escape": "^4.0.0", "tslib": "^2.6.2" }, @@ -4850,11 +4868,11 @@ } }, "node_modules/@smithy/querystring-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.1.tgz", - "integrity": "sha512-Ma2XC7VS9aV77+clSFylVUnPZRindhB7BbmYiNOdr+CHt/kZNJoPP0cd3QxCnCFyPXC4eybmyE98phEHkqZ5Jw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.2.tgz", + "integrity": "sha512-v6w8wnmZcVXjfVLjxw8qF7OwESD9wnpjp0Dqry/Pod0/5vcEA3qxCr+BhbOHlxS8O+29eLpT3aagxXGwIoEk7Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4862,22 +4880,22 @@ } }, "node_modules/@smithy/service-error-classification": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.1.tgz", - "integrity": "sha512-3JNjBfOWpj/mYfjXJHB4Txc/7E4LVq32bwzE7m28GN79+M1f76XHflUaSUkhOriprPDzev9cX/M+dEB80DNDKA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.2.tgz", + "integrity": "sha512-LA86xeFpTKn270Hbkixqs5n73S+LVM0/VZco8dqd+JT75Dyx3Lcw/MraL7ybjmz786+160K8rPOmhsq0SocoJQ==", "dependencies": { - "@smithy/types": "^4.1.0" + "@smithy/types": "^4.2.0" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/shared-ini-file-loader": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.1.tgz", - "integrity": "sha512-hC8F6qTBbuHRI/uqDgqqi6J0R4GtEZcgrZPhFQnMhfJs3MnUTGSnR1NSJCJs5VWlMydu0kJz15M640fJlRsIOw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.2.tgz", + "integrity": "sha512-J9/gTWBGVuFZ01oVA6vdb4DAjf1XbDhK6sLsu3OS9qmLrS6KB5ygpeHiM3miIbj1qgSJ96GYszXFWv6ErJ8QEw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4885,15 +4903,15 @@ } }, "node_modules/@smithy/signature-v4": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.1.tgz", - "integrity": "sha512-nCe6fQ+ppm1bQuw5iKoeJ0MJfz2os7Ic3GBjOkLOPtavbD1ONoyE3ygjBfz2ythFWm4YnRm6OxW+8p/m9uCoIA==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.2.tgz", + "integrity": "sha512-Mz+mc7okA73Lyz8zQKJNyr7lIcHLiPYp0+oiqiMNc/t7/Kf2BENs5d63pEj7oPqdjaum6g0Fc8wC78dY1TgtXw==", "dependencies": { "@smithy/is-array-buffer": "^4.0.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "@smithy/util-uri-escape": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -4903,16 +4921,16 @@ } }, "node_modules/@smithy/smithy-client": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.1.6.tgz", - "integrity": "sha512-UYDolNg6h2O0L+cJjtgSyKKvEKCOa/8FHYJnBobyeoeWDmNpXjwOAtw16ezyeu1ETuuLEOZbrynK0ZY1Lx9Jbw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.2.0.tgz", + "integrity": "sha512-Qs65/w30pWV7LSFAez9DKy0Koaoh3iHhpcpCCJ4waj/iqwsuSzJna2+vYwq46yBaqO5ZbP9TjUsATUNxrKeBdw==", "dependencies": { - "@smithy/core": "^3.1.5", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.1.2", + "@smithy/core": "^3.2.0", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4920,9 +4938,9 @@ } }, "node_modules/@smithy/types": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.1.0.tgz", - "integrity": "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.2.0.tgz", + "integrity": "sha512-7eMk09zQKCO+E/ivsjQv+fDlOupcFUCSC/L2YUPgwhvowVGWbPQHjEFcmjt7QQ4ra5lyowS92SV53Zc6XD4+fg==", "dependencies": { "tslib": "^2.6.2" }, @@ -4931,12 +4949,12 @@ } }, "node_modules/@smithy/url-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.1.tgz", - "integrity": "sha512-gPXcIEUtw7VlK8f/QcruNXm7q+T5hhvGu9tl63LsJPZ27exB6dtNwvh2HIi0v7JcXJ5emBxB+CJxwaLEdJfA+g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.2.tgz", + "integrity": "sha512-Bm8n3j2ScqnT+kJaClSVCMeiSenK6jVAzZCNewsYWuZtnBehEz4r2qP0riZySZVfzB+03XZHJeqfmJDkeeSLiQ==", "dependencies": { - "@smithy/querystring-parser": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/querystring-parser": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5002,13 +5020,13 @@ } }, "node_modules/@smithy/util-defaults-mode-browser": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.7.tgz", - "integrity": "sha512-CZgDDrYHLv0RUElOsmZtAnp1pIjwDVCSuZWOPhIOBvG36RDfX1Q9+6lS61xBf+qqvHoqRjHxgINeQz47cYFC2Q==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.8.tgz", + "integrity": "sha512-ZTypzBra+lI/LfTYZeop9UjoJhhGRTg3pxrNpfSTQLd3AJ37r2z4AXTKpq1rFXiiUIJsYyFgNJdjWRGP/cbBaQ==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, @@ -5017,16 +5035,16 @@ } }, "node_modules/@smithy/util-defaults-mode-node": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.7.tgz", - "integrity": "sha512-79fQW3hnfCdrfIi1soPbK3zmooRFnLpSx3Vxi6nUlqaaQeC5dm8plt4OTNDNqEEEDkvKghZSaoti684dQFVrGQ==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.8.tgz", + "integrity": "sha512-Rgk0Jc/UDfRTzVthye/k2dDsz5Xxs9LZaKCNPgJTRyoyBoeiNCnHsYGOyu1PKN+sDyPnJzMOz22JbwxzBp9NNA==", "dependencies": { - "@smithy/config-resolver": "^4.0.1", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5034,12 +5052,12 @@ } }, "node_modules/@smithy/util-endpoints": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.1.tgz", - "integrity": "sha512-zVdUENQpdtn9jbpD9SCFK4+aSiavRb9BxEtw9ZGUR1TYo6bBHbIoi7VkrFQ0/RwZlzx0wRBaRmPclj8iAoJCLA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.2.tgz", + "integrity": "sha512-6QSutU5ZyrpNbnd51zRTL7goojlcnuOB55+F9VBD+j8JpRY50IGamsjlycrmpn8PQkmJucFW8A0LSfXj7jjtLQ==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5058,11 +5076,11 @@ } }, "node_modules/@smithy/util-middleware": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.1.tgz", - "integrity": "sha512-HiLAvlcqhbzhuiOa0Lyct5IIlyIz0PQO5dnMlmQ/ubYM46dPInB+3yQGkfxsk6Q24Y0n3/JmcA1v5iEhmOF5mA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.2.tgz", + "integrity": "sha512-6GDamTGLuBQVAEuQ4yDQ+ti/YINf/MEmIegrEeg7DdB/sld8BX1lqt9RRuIcABOhAGTA50bRbPzErez7SlDtDQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5070,12 +5088,12 @@ } }, "node_modules/@smithy/util-retry": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.1.tgz", - "integrity": "sha512-WmRHqNVwn3kI3rKk1LsKcVgPBG6iLTBGC1iYOV3GQegwJ3E8yjzHytPt26VNzOWr1qu0xE03nK0Ug8S7T7oufw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.2.tgz", + "integrity": "sha512-Qryc+QG+7BCpvjloFLQrmlSd0RsVRHejRXd78jNO3+oREueCjwG1CCEH1vduw/ZkM1U9TztwIKVIi3+8MJScGg==", "dependencies": { - "@smithy/service-error-classification": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/service-error-classification": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5083,13 +5101,13 @@ } }, "node_modules/@smithy/util-stream": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.1.2.tgz", - "integrity": "sha512-44PKEqQ303d3rlQuiDpcCcu//hV8sn+u2JBo84dWCE0rvgeiVl0IlLMagbU++o0jCWhYCsHaAt9wZuZqNe05Hw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.2.0.tgz", + "integrity": "sha512-Vj1TtwWnuWqdgQI6YTUF5hQ/0jmFiOYsc51CSMgj7QfyO+RF4EnT2HNjoviNlOOmgzgvf3f5yno+EiC4vrnaWQ==", "dependencies": { - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/types": "^4.1.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-hex-encoding": "^4.0.0", @@ -8585,6 +8603,11 @@ "node": ">=8" } }, + "node_modules/filtrex": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz", + "integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A==" + }, "node_modules/find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", diff --git a/core/package.json b/core/package.json index 205e3b778..296b8834a 100644 --- a/core/package.json +++ b/core/package.json @@ -43,11 +43,11 @@ "typescript": "^5.6.3" }, "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.758.0", - "@aws-sdk/client-sagemaker-runtime": "^3.758.0", - "@aws-sdk/credential-providers": "^3.758.0", + "@aws-sdk/client-bedrock-runtime": "^3.779.0", + "@aws-sdk/client-sagemaker-runtime": "^3.777.0", + "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -66,6 +66,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b9d4e88c8..fd0b48b2c 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -2,10 +2,11 @@ import { ContinueSDK, SlashCommand } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { getLastNPathParts } from "../../util/uri"; import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; +import { renderPromptFileV2 } from "../v2/renderPromptFile"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; -import { updateChatHistory } from "./updateChatHistory"; +import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; export function extractName(preamble: { name?: string }, path: string): string { return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; @@ -67,8 +68,18 @@ export function slashCommandFromPromptFileV1( context.llm.systemMessage = systemMessage; const userInput = extractUserInput(context.input, name); - const renderedPrompt = await renderPromptV1(prompt, context, userInput); - const messages = updateChatHistory( + const [_, renderedPrompt] = await renderPromptFileV2(prompt, { + config: context.config, + fullInput: userInput, + embeddingsProvider: context.config.modelsByRole.embed[0], + reranker: context.config.modelsByRole.rerank[0], + llm: context.llm, + ide: context.ide, + selectedCode: context.selectedCode, + fetch: context.fetch, + }); + + const messages = replaceSlashCommandWithPromptInChatHistory( context.history, name, renderedPrompt, diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 8ebc6f038..04cbcd91b 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,4 +1,4 @@ -export function updateChatHistory( +export function replaceSlashCommandWithPromptInChatHistory( history: any[], commandName: string, renderedPrompt: string, diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 1f08011a8..4d52c7ba1 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -66,7 +66,7 @@ export async function renderPromptFileV2( rawContent: string, extras: ContextProviderExtras, ): Promise<[ContextItem[], string]> { - const [preamble, body] = getPreambleAndBody(rawContent); + const [_, body] = getPreambleAndBody(rawContent); const contextItemsPromises: Promise[] = []; const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { @@ -75,6 +75,10 @@ export async function renderPromptFileV2( }); const contextItems = (await Promise.all(contextItemsPromises)).flat(); + const renderedPrompt = + contextItems.map((item) => item.content).join("\n\n") + + "\n\n" + + renderedBody; - return [contextItems, renderedBody]; + return [contextItems, renderedPrompt]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 03940c283..7f29c2e25 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -5,8 +5,6 @@ import { } from "@continuedev/config-yaml"; import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; -import { OrganizationDescription } from "../config/ProfileLifecycleManager"; import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; @@ -32,6 +30,7 @@ import type { SlashCommandDescription, ToolCall, } from "../"; +import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -66,14 +65,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { { result: ConfigResult; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string; + usingContinueForTeams: boolean; }, ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [ - undefined, - { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, - ]; "config/refreshProfiles": [undefined, void]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; @@ -198,5 +196,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - "controlPlane/listOrganizations": [undefined, OrganizationDescription[]]; + isItemTooBig: [ + { item: ContextItemWithId; selectedModelTitle: string | undefined }, + boolean, + ]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 4dcf74ee5..2e1bd3ff1 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -1,19 +1,8 @@ -import { ProfileDescription } from "../config/ConfigHandler.js"; - import { ToCoreFromIdeOrWebviewProtocol } from "./core.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { - didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [ - { id: string | null; profileId?: string | null }, - void, - ]; -}; -export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [ - { profiles: ProfileDescription[]; selectedProfileId: string | null }, - void, - ]; - didSelectOrganization: [{ orgId: string | null }, void]; + didChangeSelectedProfile: [{ id: string }, void]; + didChangeSelectedOrg: [{ id: string; profileId?: string }, void]; }; +export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5b2a7ab1f..1646d848e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -31,6 +31,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; + getFileResults: [{ pattern: string }, string[]]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; fileExists: [{ filepath: string }, boolean]; @@ -106,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = { { sessionInfo: ControlPlaneSessionInfo | undefined }, void, ]; - didChangeIdeSettings: [{ settings: IdeSettings }, void]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..cc1191d92 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -12,14 +11,12 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB applyToFile: [ { text: string; streamId: string; - curSelectedModelTitle: string; filepath?: string; + toolCallId?: string; }, void, ]; @@ -52,7 +49,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { prompt: MessageContent; range: RangeInFileWithContents; - selectedModelTitle: string; }, void, ]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 4bb78e0ed..5d541225b 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -187,6 +187,10 @@ export class MessageIde implements IDE { return this.request("getSearchResults", { query }); } + getFileResults(pattern: string): Promise { + return this.request("getFileResults", { pattern }); + } + getProblems(fileUri: string): Promise { return this.request("getProblems", { filepath: fileUri }); } diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index 620055a75..8cd1cfbd6 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -166,6 +166,10 @@ export class ReverseMessageIde { return this.ide.getSearchResults(data.query); }); + this.on("getFileResults", (data) => { + return this.ide.getFileResults(data.pattern); + }); + this.on("getProblems", (data) => { return this.ide.getProblems(data.filepath); }); diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index c6ae172f4..1d854f948 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -20,7 +20,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -60,7 +59,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", - "controlPlane/listOrganizations", + "isItemTooBig", ]; // Message types to pass through from core to webview @@ -69,16 +68,13 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 329f71bdc..6b59fa338 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,11 +1,11 @@ import { ConfigResult } from "@continuedev/config-yaml"; +import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, ContextProviderName, IndexingProgressUpdate, IndexingStatus, - PackageDocsResult, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -13,6 +13,9 @@ export type ToWebviewFromIdeOrCoreProtocol = { { result: ConfigResult; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string | null; + usingContinueForTeams: boolean; }, void, ]; diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index ae54b03db..a394273e9 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -1,6 +1,7 @@ import { ConfigHandler } from "../config/ConfigHandler"; import { ControlPlaneClient } from "../control-plane/client"; import Mock from "../llm/llms/Mock"; +import { LLMLogger } from "../llm/logger"; import FileSystemIde from "../util/filesystem"; import { TEST_DIR } from "./testDir"; @@ -17,7 +18,7 @@ export const testControlPlaneClient = new ControlPlaneClient( export const testConfigHandler = new ConfigHandler( testIde, ideSettingsPromise, - async (text) => {}, + new LLMLogger(), Promise.resolve(undefined), ); diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 268cbb9a8..7cff1c70e 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,12 +1,18 @@ export enum BuiltInToolNames { ReadFile = "builtin_read_file", + EditExistingFile = "builtin_edit_existing_file", ReadCurrentlyOpenFile = "builtin_read_currently_open_file", CreateNewFile = "builtin_create_new_file", RunTerminalCommand = "builtin_run_terminal_command", - ViewSubdirectory = "builtin_view_subdirectory", - ViewRepoMap = "builtin_view_repo_map", - ExactSearch = "builtin_exact_search", + GrepSearch = "builtin_grep_search", + FileGlobSearch = "builtin_file_glob_search", SearchWeb = "builtin_search_web", ViewDiff = "builtin_view_diff", + LSTool = "builtin_ls", + + // excluded from allTools for now + ViewRepoMap = "builtin_view_repo_map", + ViewSubdirectory = "builtin_view_subdirectory", } + export const BUILT_IN_GROUP_NAME = "Built-In"; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 8d4b1f1b3..28a8f8c30 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,14 +4,14 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; -import { exactSearchImpl } from "./implementations/exactSearch"; +import { fileGlobSearchImpl } from "./implementations/globSearch"; +import { grepSearchImpl } from "./implementations/grepSearch"; +import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; -import { viewRepoMapImpl } from "./implementations/viewRepoMap"; -import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; async function callHttpTool( url: string, @@ -139,22 +139,27 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + // Note: Custom GUI handling for edit case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); - case BuiltInToolNames.ExactSearch: - return await exactSearchImpl(args, extras); + case BuiltInToolNames.GrepSearch: + return await grepSearchImpl(args, extras); + case BuiltInToolNames.FileGlobSearch: + return await fileGlobSearchImpl(args, extras); case BuiltInToolNames.RunTerminalCommand: return await runTerminalCommandImpl(args, extras); case BuiltInToolNames.SearchWeb: return await searchWebImpl(args, extras); case BuiltInToolNames.ViewDiff: return await viewDiffImpl(args, extras); - case BuiltInToolNames.ViewRepoMap: - return await viewRepoMapImpl(args, extras); - case BuiltInToolNames.ViewSubdirectory: - return await viewSubdirectoryImpl(args, extras); + case BuiltInToolNames.LSTool: + return await lsToolImpl(args, extras); case BuiltInToolNames.ReadCurrentlyOpenFile: return await readCurrentlyOpenFileImpl(args, extras); + // case BuiltInToolNames.ViewRepoMap: + // return await viewRepoMapImpl(args, extras); + // case BuiltInToolNames.ViewSubdirectory: + // return await viewSubdirectoryImpl(args, extras); default: return await callToolFromUri(uri, args, extras); } diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts new file mode 100644 index 000000000..6ee5cee6b --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -0,0 +1,37 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export interface EditToolArgs { + filepath: string; + new_contents: string; +} + +export const editFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + function: { + name: BuiltInToolNames.EditExistingFile, + description: + "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.", + parameters: { + type: "object", + required: ["filepath", "new_contents"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to edit, relative to the root of the workspace.", + }, + new_contents: { + type: "string", + description: "The new file contents", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts new file mode 100644 index 000000000..bff2d454c --- /dev/null +++ b/core/tools/definitions/globSearch.ts @@ -0,0 +1,26 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const globSearchTool: Tool = { + type: "function", + displayTitle: "Glob File Search", + wouldLikeTo: 'find file matches for "{{{ pattern }}}"', + isCurrently: 'finding file matches for "{{{ pattern }}}"', + hasAlready: 'retreived file matches for "{{{ pattern }}}"', + readonly: true, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.FileGlobSearch, + description: "Search for files in the project", + parameters: { + type: "object", + required: ["pattern"], + properties: { + pattern: { + type: "string", + description: "Glob pattern for file path matching", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/grepSearch.ts similarity index 70% rename from core/tools/definitions/exactSearch.ts rename to core/tools/definitions/grepSearch.ts index d20db3cec..42ea92e64 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -1,17 +1,17 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -export const exactSearchTool: Tool = { +export const grepSearchTool: Tool = { type: "function", - displayTitle: "Exact Search", + displayTitle: "Grep Search", wouldLikeTo: 'search for "{{{ query }}}" in the repository', isCurrently: 'getting search results for "{{{ query }}}"', - hasAlready: 'retreived search results for "{{{ query }}}"', + hasAlready: 'retrieved search results for "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { - name: BuiltInToolNames.ExactSearch, - description: "Perform an exact search over the repository using ripgrep.", + name: BuiltInToolNames.GrepSearch, + description: "Perform a search over the repository using ripgrep.", parameters: { type: "object", required: ["query"], diff --git a/core/tools/definitions/lsTool.ts b/core/tools/definitions/lsTool.ts new file mode 100644 index 000000000..6b6e96498 --- /dev/null +++ b/core/tools/definitions/lsTool.ts @@ -0,0 +1,33 @@ +import { Tool } from "../.."; + +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const lsTool: Tool = { + type: "function", + displayTitle: "LS Tool", + wouldLikeTo: "list files and folders in {{{ dirPath }}}", + isCurrently: "listing files and folders in {{{ dirPath }}}", + hasAlready: "listed files and folders in {{{ dirPath }}}", + readonly: true, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.LSTool, + description: "List files and folders in a given directory", + parameters: { + type: "object", + required: ["dirPath", "recursive"], + properties: { + dirPath: { + type: "string", + description: + "The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'", + }, + recursive: { + type: "boolean", + description: + "If true, lists files and folders recursively. To prevent unexpected large results, use this sparingly", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index f4df8e1e5..eacaab70d 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = { displayTitle: "Read Currently Open File", wouldLikeTo: "read the current file", isCurrently: "reading the current file", - hasAlready: "read the current file", + hasAlready: "viewed the current file", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 0133b54b0..ff5d58a31 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -6,7 +6,7 @@ export const readFileTool: Tool = { displayTitle: "Read File", wouldLikeTo: "read {{{ filepath }}}", isCurrently: "reading {{{ filepath }}}", - hasAlready: "read {{{ filepath }}}", + hasAlready: "viewed {{{ filepath }}}", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 0f98f382c..d2ce78efc 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -7,7 +7,7 @@ export const searchWebTool: Tool = { displayTitle: "Search Web", wouldLikeTo: 'search the web for "{{{ query }}}"', isCurrently: 'searching the web for "{{{ query }}}"', - hasAlready: 'searched the web fore "{{{ query }}}"', + hasAlready: 'searched the web for "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..5a89141eb 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -1,6 +1,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const resolvedFileUri = await inferResolvedUriFromRelativePath( @@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { extras.ide, ); if (resolvedFileUri) { + const exists = await extras.ide.fileExists(resolvedFileUri); + if (exists) { + throw new Error( + `File ${args.filepath} already exists. Use the edit tool to edit this file`, + ); + } await extras.ide.writeFile(resolvedFileUri, args.contents); await extras.ide.openFile(resolvedFileUri); + return [ + { + name: getUriPathBasename(resolvedFileUri), + description: getCleanUriPath(resolvedFileUri), + content: "File created successfuly", + uri: { + type: "file", + value: resolvedFileUri, + }, + }, + ]; + } else { + throw new Error("Failed to resolve path"); } - return []; }; diff --git a/core/tools/implementations/exactSearch.ts b/core/tools/implementations/exactSearch.ts deleted file mode 100644 index ae8f6fd02..000000000 --- a/core/tools/implementations/exactSearch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ToolImpl } from "."; - -export const exactSearchImpl: ToolImpl = async (args, extras) => { - const content = await extras.ide.getSearchResults(args.query); - return [ - { - name: "Search results", - description: "Results from exact search", - content, - }, - ]; -}; diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts new file mode 100644 index 000000000..c0b214357 --- /dev/null +++ b/core/tools/implementations/globSearch.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { + const results = await extras.ide.getFileResults(args.pattern); + return [ + { + name: "File results", + description: "Results from file glob search", + content: results.join("\n"), + }, + ]; +}; diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts new file mode 100644 index 000000000..a506be9cd --- /dev/null +++ b/core/tools/implementations/grepSearch.ts @@ -0,0 +1,13 @@ +import { ToolImpl } from "."; +import { formatGrepSearchResults } from "../../util/grepSearch"; + +export const grepSearchImpl: ToolImpl = async (args, extras) => { + const results = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from grep search", + content: formatGrepSearchResults(results), + }, + ]; +}; diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts new file mode 100644 index 000000000..4a7f8bcb5 --- /dev/null +++ b/core/tools/implementations/lsTool.ts @@ -0,0 +1,31 @@ +import { ToolImpl } from "."; +import { walkDir } from "../../indexing/walkDir"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export const lsToolImpl: ToolImpl = async (args, extras) => { + const uri = await resolveRelativePathInDir(args.dirPath, extras.ide); + if (!uri) { + throw new Error( + `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`, + ); + } + + const entries = await walkDir(uri, extras.ide, { + returnRelativeUrisPaths: true, + include: "both", + recursive: args.recursive ?? false, + }); + + const content = + entries.length > 0 + ? entries.join("\n") + : `No files/folders found in ${args.dirPath}`; + + return [ + { + name: "File/folder list", + description: `Files/folders in ${args.dirPath}`, + content, + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index c27860a6f..c9875c5eb 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,21 +1,28 @@ import { createNewFileTool } from "./definitions/createNewFile"; -import { exactSearchTool } from "./definitions/exactSearch"; +import { editFileTool } from "./definitions/editFile"; +import { globSearchTool } from "./definitions/globSearch"; +import { grepSearchTool } from "./definitions/grepSearch"; +import { lsTool } from "./definitions/lsTool"; import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; import { readFileTool } from "./definitions/readFile"; import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; import { searchWebTool } from "./definitions/searchWeb"; import { viewDiffTool } from "./definitions/viewDiff"; -import { viewRepoMapTool } from "./definitions/viewRepoMap"; -import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; export const allTools = [ readFileTool, + editFileTool, createNewFileTool, runTerminalCommandTool, - viewSubdirectoryTool, - viewRepoMapTool, - exactSearchTool, + + grepSearchTool, + globSearchTool, searchWebTool, viewDiffTool, readCurrentlyOpenFileTool, + + lsTool, + // replacing with ls tool for now + // viewSubdirectoryTool, + // viewRepoMapTool, ]; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 3c6963071..c59eb3320 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -238,6 +238,10 @@ class FileSystemIde implements IDE { return ""; } + async getFileResults(pattern: string): Promise { + return []; + } + async getProblems(fileUri?: string | undefined): Promise { return Promise.resolve([]); } diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts new file mode 100644 index 000000000..a30982e77 --- /dev/null +++ b/core/util/grepSearch.ts @@ -0,0 +1,61 @@ +export function formatGrepSearchResults(results: string): string { + const keepLines: string[] = []; + + function countLeadingSpaces(line: string) { + return line?.match(/^ */)?.[0].length ?? 0; + } + + const processResult = (lines: string[]) => { + // Skip results in which only the file path was kept + const resultPath = lines[0]; + const resultContent = lines.slice(1); + if (resultContent.length === 0) { + return; + } + + // Add path + keepLines.push(resultPath); + + // Find the minimum indentation of content lines + let minIndent = Infinity; + for (const line of resultContent) { + const indent = countLeadingSpaces(line); + if (indent < minIndent) { + minIndent = indent; + } + } + + // Make all lines line up to 2-space indent + const changeIndentBy = 2 - minIndent; + if (changeIndentBy === 0) { + keepLines.push(...resultContent); + } else if (changeIndentBy < 0) { + keepLines.push( + ...resultContent.map((line) => line.substring(-changeIndentBy)), + ); + } else { + keepLines.push( + ...resultContent.map((line) => " ".repeat(changeIndentBy) + line), + ); + } + }; + + let resultLines: string[] = []; + for (const line of results.split("\n").filter((l) => !!l)) { + if (line.startsWith("./") || line === "--") { + processResult(resultLines); // process previous result + resultLines = [line]; + continue; + } + + // Exclude leading zero- or single-char lines + if (resultLines.length === 1 && line.trim().length <= 1) { + continue; + } + + resultLines.push(line); + } + processResult(resultLines); + + return keepLines.join("\n"); +} diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index b31deedf4..204f680f0 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -530,10 +530,6 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a You'll then be able to type "@" and see "MCP" in the context providers dropdown. -### Prompt Files - -See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. - ### `@Issue` Reference the conversation in a GitHub issue. @@ -883,7 +879,6 @@ You can override this query by setting the `issueQuery` parameter. You can set the `maxResults` parameter to limit the number of results returned. The default is `50`. - ### `@Discord` Reference the messages in a Discord channel. diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md deleted file mode 100644 index 68995746f..000000000 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Prompt files ---- - -Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub. - -:::info -Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) -::: - -## Quick start - -Below is a quick example of setting up a prompt file: - -1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File"). -2. Add a file called `rails.prompt` to this folder. -3. Write the following contents to `rails.prompt` and save. - -```.prompt -name: Rails Project -description: Information about this project ---- -Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb -``` - -Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. - -Then, type / and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file. - -## Format - -The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. - -:::info -The current state of this format is experimental and subject to change -::: - -### Preamble - -The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: - -- `name` - The display title -- `description` - The description you will see in the dropdown -- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) - -If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. - -### Context - -Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: - -- `@terminal` - The contents of the terminal -- `@currentFile` - The currently active file -- `@open` - All open files -- `@os` - Information about the operating system -- `@problems` - Problems reported by the language server in the active file -- `@repo-map` - A map of files in the repository -- `@tree` - A tree view of the repository structure - -Or you can directly type URLs and file paths: - -- `@https://github.com/continuedev/continue` - The contents of a URL -- `@src/index.ts` - The contents of a file (VS Code only) - -All references will be attached as context items, rather than injected directly inline. - -## Feedback - -If you have ideas about how to improve the `.prompt` file format, please reach out on [Discord](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/customize/deep-dives/prompts.md b/docs/docs/customize/deep-dives/prompts.md new file mode 100644 index 000000000..1cd1c0085 --- /dev/null +++ b/docs/docs/customize/deep-dives/prompts.md @@ -0,0 +1,97 @@ +--- +title: Prompts +--- + +Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. + +:::info +Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) +::: + +## Examples + +Below are some examples to get you started. + +### Security review + +```text title="Security best practices review" +@open - Review these files for the following security best practices: +- Does the architecture follow security-by-design principles? +- Are there potential security vulnerabilities in the system design? +- Is sensitive data handled appropriately throughout the lifecycle? +``` + +### Reference best practice guides + +```text title="Redux best practices review" +@https://redux.js.org/style-guide/ +@currentFile + +Review this code for adherence to Redux best practices. +``` + +### Pull in commonly used files for tasks + +```text title="Generate a new TypeORM entity" +@src/db/dataSource.ts @src/db/entity/SampleEntity.ts + +Use these files to generate a new TypeORM entity based on the following requirements: +``` + +## Including Context Providers in your prompts + +Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: + +- `@terminal` - The contents of the terminal +- `@currentFile` - The currently active file +- `@open` - All open files +- `@os` - Information about the operating system +- `@problems` - Problems reported by the language server in the active file +- `@repo-map` - A map of files in the repository +- `@tree` - A tree view of the repository structure + +Or you can directly type URLs and file paths: + +- `@https://github.com/continuedev/continue` - The contents of a URL +- `@src/index.ts` - The contents of a file (VS Code only) + +All references will be attached as context items, rather than injected directly inline. + +## Local `.prompt` files + +In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub. + +### Quick Start + +Below is a quick example of setting up a prompt file: + +1. Create a folder called `.continue/prompts` at the top level of your workspace +2. Add a file called `test.prompt` to this folder. +3. Write the following contents to `test.prompt` and save. + +```.prompt +name: Current file prompt +description: A test prompt using the current file context provider +--- +@currentFile +``` + +Now to use this prompt, you can open Chat, type /, select the prompt, and add type out some additional text such as "Review the code for any issues". + +### Format + +The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. + +:::info +The current state of this format is experimental and subject to change +::: + +### Preamble + +The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: + +- `name` - The display title +- `description` - The description you will see in the dropdown +- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) + +If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. diff --git a/docs/docs/customize/deep-dives/slash-commands.mdx b/docs/docs/customize/deep-dives/slash-commands.mdx index 0c9796768..059cf8213 100644 --- a/docs/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/docs/customize/deep-dives/slash-commands.mdx @@ -26,7 +26,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/ It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. -Learn more about prompt files [here](./prompt-files.md) +Learn more about prompt files [here](./prompts.md) ### MCP Server prompts diff --git a/docs/docs/customize/deep-dives/vscode-actions.md b/docs/docs/customize/deep-dives/vscode-actions.md index 0c0cdd1f1..d9f1b7b66 100644 --- a/docs/docs/customize/deep-dives/vscode-actions.md +++ b/docs/docs/customize/deep-dives/vscode-actions.md @@ -14,7 +14,7 @@ To make common use cases even more accessible, we provide a handful of other way ## Quick actions -Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompt-files.md) to perform custom actions. +Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions. ![quick-actions](/img/quick-actions.png) diff --git a/docs/docs/customize/model-providers/more/watsonx.mdx b/docs/docs/customize/model-providers/more/watsonx.mdx index f2360788f..1bc247399 100644 --- a/docs/docs/customize/model-providers/more/watsonx.mdx +++ b/docs/docs/customize/model-providers/more/watsonx.mdx @@ -128,8 +128,8 @@ You can also configure generation parameters, such as temperature, topP, topK, f apiBase: watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD template: granite - contextLength: 8000 defaultCompletionOptions: + contextLength: 8000 temperature: 0.1 topP: 0.3 topK: 20 @@ -245,7 +245,6 @@ To view the list of available embeddings models, visit [this page](https://datap - ## Reranker diff --git a/docs/docs/customize/model-providers/top-level/bedrock.mdx b/docs/docs/customize/model-providers/top-level/bedrock.mdx index 9582428a4..45cf5e5eb 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.mdx +++ b/docs/docs/customize/model-providers/top-level/bedrock.mdx @@ -80,7 +80,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ## Autocomplete model -Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. +Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete.md). diff --git a/docs/docs/customize/model-providers/top-level/openai.mdx b/docs/docs/customize/model-providers/top-level/openai.mdx index 8ed706213..7e3870720 100644 --- a/docs/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/docs/customize/model-providers/top-level/openai.mdx @@ -21,7 +21,7 @@ We recommend configuring **GPT-4o** as your chat model. - name: GPT-4o provider: openai model: gpt-4o - apiKey: + apiKey: ``` @@ -32,7 +32,7 @@ We recommend configuring **GPT-4o** as your chat model. "title": "GPT-4o", "provider": "openai", "model": "gpt-4o", - "apiKey": "" + "apiKey": "" } ] } @@ -57,7 +57,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. - name: OpenAI Embeddings provider: openai model: text-embedding-3-large - apiKey: + apiKey: roles: - embed ``` @@ -68,7 +68,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. "embeddingsProvider": { "provider": "openai", "model": "text-embedding-3-large", - "apiKey": "" + "apiKey": "" } } ``` diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 1ecace184..78574b096 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -13,3 +13,27 @@ When editing code, Chat and Edit model output often doesn't clearly align with e Generally speaking, models proficient in chat and edit can also be used for applying code. Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). + +## Prompt templating + +You can customize the prompt template used for applying code changes by setting the `promptTemplates.apply` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the apply template: + +- `{{{original_code}}}` - The original code before changes +- `{{{new_code}}}` - The new code after changes + +Example: + +```yaml +models: + - name: My Custom Apply Template + provider: anthropic + model: claude-3-5-sonnet-latest + promptTemplates: + apply: | + Original: {{{original_code}}} + New: {{{new_code}}} + + Please generate the final code without any markers or explanations. +``` diff --git a/docs/docs/customize/model-roles/edit.mdx b/docs/docs/customize/model-roles/edit.mdx index de817ed42..5e4ad1d5f 100644 --- a/docs/docs/customize/model-roles/edit.mdx +++ b/docs/docs/customize/model-roles/edit.mdx @@ -46,3 +46,37 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. + +## Prompt templating + +You can customize the prompt template used for editing code by setting the `promptTemplates.edit` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the edit template: + +- `{{{userInput}}}` - The user's edit request/instruction +- `{{{language}}}` - The programming language of the code +- `{{{codeToEdit}}}` - The code that's being edited +- `{{{prefix}}}` - Content before the edit area +- `{{{suffix}}}` - Content after the edit area +- `{{{supportsCompletions}}}` - Whether the model supports completions API +- `{{{supportsPrefill}}}` - Whether the model supports prefill capability + +Example: + +```yaml +models: + - name: My Custom Edit Template + provider: openai + model: gpt-4o + promptTemplates: + edit: | + `Here is the code before editing: + \`\`\`{{{language}}} + {{{codeToEdit}}} + \`\`\` + + Here is the edit requested: + "{{{userInput}}}" + + Here is the code after editing:` +``` diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 15ed68ec9..3cd6f2615 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -20,5 +20,5 @@ You can easily access your assistant configuration from the Continue Chat sideba ![configure an assistant](/img/configure-continue.png) -- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hug assistant +- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hub assistant - See the [Config Deep Dive](./deep-dives/configuration.md) for more details on configuring local assistants. diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx index 7710a84c2..1494680c0 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx @@ -50,7 +50,7 @@ Then, create a server that responds to requests as are made from [HttpContextPro The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. :::info -The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompt files](../deep-dives/prompt-files.md) where possible. +The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible. ::: ## Using CustomContextProvider diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md index 27b0517b3..03543a22f 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -3,7 +3,7 @@ title: Build your own slash command --- :::info -Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. +Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompts.md) to achieve similar functionality. ::: There are two ways to add custom slash commands: diff --git a/docs/docs/customize/tutorials/custom-code-rag.mdx b/docs/docs/customize/tutorials/custom-code-rag.mdx index f5e43dc8e..735e45655 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.mdx +++ b/docs/docs/customize/tutorials/custom-code-rag.mdx @@ -51,8 +51,8 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - # 1536 is the embedding dimension of the `voyage-code-3` model. - vector: Vector(1536) = func.VectorField() + # 1024 is the default dimension for `voyage-code-3`: https://docs.voyageai.com/docs/embeddings#model-choices + vector: Vector(1024) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") table.add([ diff --git a/docs/docs/customize/tutorials/set-up-codestral.mdx b/docs/docs/customize/tutorials/set-up-codestral.mdx index 97ec3c981..1ace12f2f 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.mdx +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -45,13 +45,15 @@ import TabItem from "@theme/TabItem"; "apiBase": "https://codestral.mistral.ai/v1" } ], - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "", - "apiBase": "https://codestral.mistral.ai/v1" - } + "tabAutocompleteModel": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "", + "apiBase": "https://codestral.mistral.ai/v1" + } + ] } ``` diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index 0c2698542..b9c5bbd13 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -41,12 +41,7 @@ Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and vi Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. -Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files: - -1. Currently, prompt blocks cannot use context providers -2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and - -The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). +Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). ## Data diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 69f301366..6269a1bb7 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -142,17 +142,16 @@ The `models` section defines the language models used in your configuration. Mod - `name` (**required**): A unique name to identify the model within your configuration. - `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). - `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). +- `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating). +- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: + - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - - `defaultCompletionOptions`: Default completion options for model settings. - - **Properties:** - - `contextLength`: Maximum context length of the model, typically in tokens. - `maxTokens`: Maximum number of tokens to generate in a completion. - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). @@ -160,11 +159,7 @@ The `models` section defines the language models used in your configuration. Mod - `topK`: Maximum number of tokens considered at each step. - `stop`: An array of stop tokens that will terminate the completion. - `n`: Number of completions to generate. - - `requestOptions`: HTTP request options specific to the model. - - **Properties:** - - `timeout`: Timeout for each request to the language model. - `verifySsl`: Whether to verify SSL certificates for requests. - `caBundlePath`: Path to a custom CA bundle for HTTP requests. @@ -177,7 +172,7 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. -#### Example: +#### Example ```yaml title="config.yaml" models: @@ -227,7 +222,7 @@ More information about usage/params for each context provider can be found [here ```yaml title="config.yaml" context: - - provider: files + - provider: file - provider: code - provider: codebase params: @@ -474,7 +469,8 @@ models: - name: qwen2.5-coder-7b <<: *model_defaults model: qwen2.5-coder-7b - useLegacyCompletionsEndpoint: false + env: + useLegacyCompletionsEndpoint: false roles: - autocomplete ``` diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 82df8edd2..c07f99c18 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -114,6 +114,7 @@ models: - name: My Voyage Reranker provider: voyage apiKey: + roles: - rerank - name: My Starcoder diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c74e6a71b..06e717ad7 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -286,7 +286,7 @@ const config = { ], }, { - to: "/customize/deep-dives/prompt-files", + to: "/customize/deep-dives/prompts", from: ["/walkthroughs/prompt-files", "/features/prompt-files"], }, // TODO - actions redirects @@ -489,6 +489,10 @@ const config = { to: "/getting-started/install", from: "/getting-started", }, + { + to: "/customize/deep-dives/prompts", + from: "/customize/deep-dives/prompt-files", + }, ], }, ], diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 2ffc4d0f2..d3c1097e7 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -13,7 +13,7 @@ Continue 有一个大的内置斜杠命令库,但是当你首次安装时, 有两种方法添加定制斜杠命令: -1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。 +1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompts.md) 查看完整参考。 2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数 ### 使用 `config.ts` 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md index f265a9885..a0d4c0023 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md @@ -24,7 +24,7 @@ Actions 是常见用例的快捷方式。例如,你可能想要审查代码, 通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。 -完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。 +完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt.md) 。 :::tip[Prompt 库] 为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求! diff --git a/docs/package-lock.json b/docs/package-lock.json index abd1275c6..deb0071b8 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -8022,9 +8022,10 @@ } }, "node_modules/estree-util-value-to-estree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.2.1.tgz", - "integrity": "sha512-Vt2UOjyPbNQQgT5eJh+K5aATti0OjCIAGc9SgMdOFYbohuifsWclR74l0iZTJwePMgWYdX1hlVS+dedH9XV8kw==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.3.3.tgz", + "integrity": "sha512-Db+m1WSD4+mUO7UgMeKkAwdbfNWwIxLt48XF2oFU9emPfXkIu+k5/nlOj313v7wqtAPo0f9REhUvznFrPkG8CQ==", + "license": "MIT", "dependencies": { "@types/estree": "^1.0.0" }, @@ -9617,9 +9618,10 @@ "license": "ISC" }, "node_modules/image-size": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.0.tgz", - "integrity": "sha512-4S8fwbO6w3GeCVN6OPtA9I5IGKkcDMPcKndtUlpJuCwu7JLjtj7JZpwqLuyY2nrmQT3AWsCJLSKPsc2mPBSl3w==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz", + "integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==", + "license": "MIT", "dependencies": { "queue": "6.0.2" }, diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index dccf4a7f1..45a1f05f0 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -28,11 +28,11 @@ To enable it, simply click the "Continue" button in the status bar at the bottom Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases. +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -For example, you might want to review code, write tests, or add a docstring. +Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index cf4a7e0f1..7c00cb65c 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.8 +pluginVersion=1.0.12 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension 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 9d48705df..031c6b2e9 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 @@ -1,4 +1,5 @@ package com.github.continuedev.continueintellijextension.activities +import IntelliJIDE import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService @@ -152,17 +153,12 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(SettingsListener.TOPIC, object : SettingsListener { override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) { - continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> } - continuePluginService.sendToWebview( - "didChangeIdeSettings", mapOf( - "settings" to mapOf( - "remoteConfigServerUrl" to settings.remoteConfigServerUrl, - "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, - "userToken" to settings.userToken, - "enableControlServerBeta" to settings.enableContinueTeamsBeta - ) - ) - ) + continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf( + "remoteConfigServerUrl" to settings.remoteConfigServerUrl, + "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, + "userToken" to settings.userToken, + "enableControlServerBeta" to settings.enableContinueTeamsBeta + ), null) { _ -> } } }) @@ -185,6 +181,8 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { // Notify core of content changes if (changedURIs.isNotEmpty()) { + continuePluginService.updateLastFileSaveTimestamp() + val data = mapOf("uris" to changedURIs) continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> } } @@ -236,7 +234,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { "sessionInfo" to initialSessionInfo ) continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } connection.subscribe(AuthListener.TOPIC, object : AuthListener { @@ -253,7 +250,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { data, null ) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index b9546aa63..100ee2aad 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -23,6 +23,7 @@ class MessageTypes { "getCurrentFile", "getPinnedFiles", "getSearchResults", + "getFileResults", "getProblems", "subprocess", "getBranch", @@ -59,18 +60,15 @@ class MessageTypes { // core/protocol/passThrough.ts val PASS_THROUGH_TO_WEBVIEW = listOf( "configUpdate", - "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization" ) // Note: If updating these values, make a corresponding update in @@ -87,7 +85,6 @@ class MessageTypes { "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -128,8 +125,7 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", - "controlPlane/listOrganizations" - + "isItemTooBig", ) } } \ No newline at end of file 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 4378d273d..cbcee8e98 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 @@ -65,21 +65,6 @@ class CoreMessenger( // Forward to webview if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { - // TODO: Currently we aren't set up to receive a response back from the webview - // Can circumvent for getDefaultsModelTitle here for now - if (messageType == "getDefaultModelTitle") { - val continueSettingsService = service() - val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel - val message = - gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to defaultModelTitle - ) - ) - write(message) - } val continuePluginService = project.service() continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt new file mode 100644 index 000000000..a378820e8 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt @@ -0,0 +1,94 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.intellij.openapi.project.Project +import com.intellij.openapi.project.guessProjectDir +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.File +import java.io.InputStreamReader +import java.net.URI + +class GitService( + private val project: Project, + private val continuePluginService: ContinuePluginService +) { + // Add a simple cache for diff results + private data class DiffCache( + val timestamp: Long, + val diffs: List + ) + + // Cache the last diff result + private var diffCache: DiffCache? = null + private var lastFileSaveTimestamp: Long = System.currentTimeMillis() + + /** + * Updates the timestamp when a file is saved + */ + fun updateLastFileSaveTimestamp() { + lastFileSaveTimestamp = System.currentTimeMillis() + } + + /** + * Returns the git diff for all workspace directories + */ + suspend fun getDiff(includeUnstaged: Boolean): List { + // Check if we have a valid cache entry + if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) { + return diffCache!!.diffs + } + + // If no cache hit, compute the diff + val workspaceDirs = workspaceDirectories() + val diffs = mutableListOf() + + for (workspaceDir in workspaceDirs) { + val output = StringBuilder() + val builder = if (includeUnstaged) { + ProcessBuilder("git", "diff") + } else { + ProcessBuilder("git", "diff", "--cached") + } + builder.directory(File(URI(workspaceDir))) + val process = withContext(Dispatchers.IO) { + builder.start() + } + + val reader = BufferedReader(InputStreamReader(process.inputStream)) + var line: String? = withContext(Dispatchers.IO) { + reader.readLine() + } + while (line != null) { + output.append(line) + output.append("\n") + line = withContext(Dispatchers.IO) { + reader.readLine() + } + } + + withContext(Dispatchers.IO) { + process.waitFor() + } + + diffs.add(output.toString()) + } + + // Cache the result + diffCache = DiffCache(lastFileSaveTimestamp, diffs) + return diffs + } + + private fun workspaceDirectories(): Array { + val dirs = this.continuePluginService.workspacePaths + + if (dirs?.isNotEmpty() == true) { + return dirs + } + + return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() + } + +} \ No newline at end of file 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 268a7674f..5bdb31cd4 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 @@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager @@ -45,6 +46,10 @@ class IdeProtocolClient( ) } + fun updateLastFileSaveTimestamp() { + (ide as IntelliJIDE).updateLastFileSaveTimestamp() + } + fun handleMessage(msg: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val message = Gson().fromJson(msg, Message::class.java) @@ -110,7 +115,7 @@ class IdeProtocolClient( .handleUpdatedSessionInfo(null) // Tell the webview that session info changed - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", null, uuid()) + continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", null, null) { _ -> } respond(null) } @@ -343,6 +348,15 @@ class IdeProtocolClient( respond(results) } + "getFileResults" -> { + val params = Gson().fromJson( + dataElement.toString(), + GetFileResultsParams::class.java + ) + val results = ide.getFileResults(params.pattern) + respond(results) + } + "getOpenFiles" -> { val openFiles = ide.getOpenFiles() respond(openFiles) @@ -419,11 +433,43 @@ class IdeProtocolClient( dataElement.toString(), ApplyToFileParams::class.java ) + val filepath = params.filepath - val editor = FileEditorManager.getInstance(project).selectedTextEditor + continuePluginService.sendToWebview("updateApplyState", mapOf( + "streamId" to params.streamId, + "status" to "streaming", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + + + fun closeStream () { + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to 0, + "streamId" to params.streamId, + "status" to "closed", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + } + + var editor: Editor? = null; + + if (!filepath.isNullOrEmpty()) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + } + } + } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -432,6 +478,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -450,21 +497,18 @@ class IdeProtocolClient( val config = result["config"] as Map<*, *> val selectedModels = config["selectedModelByRole"] as? Map<*, *> - val applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *> + + // If "apply" role model is not found, try "chat" role + if (applyCodeBlockModel == null) { + applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *> + } if (applyCodeBlockModel != null) { continuation.resume(applyCodeBlockModel) } else { - val models = - config["models"] as List> - val curSelectedModel = - models.find { it["title"] == params.curSelectedModelTitle } - - if (curSelectedModel == null) { - continuation.resumeWithException(IllegalStateException("Model '${params.curSelectedModelTitle}' not found in config.")) - } else { - continuation.resume(curSelectedModel) - } + // If neither "apply" nor "chat" models are available, return with exception + continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration.")) } } catch (e: Exception) { continuation.resumeWithException(e) @@ -477,6 +521,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -515,7 +560,11 @@ class IdeProtocolClient( editor, rif?.range?.start?.line ?: 0, rif?.range?.end?.line ?: (editor.document.lineCount - 1), - {}, {}) + {}, + {}, + params.streamId, + params.toolCallId + ) diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index e903e1238..a23f2d716 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -1,13 +1,9 @@ import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.`continue`.GitService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.OS -import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID -import com.github.continuedev.continueintellijextension.utils.getOS -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.Desktop -import com.google.gson.Gson +import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil @@ -31,12 +27,7 @@ import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile -import com.intellij.util.containers.toArray import kotlinx.coroutines.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.RequestBody.Companion.toRequestBody import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -44,7 +35,6 @@ import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.net.URI -import java.net.URL import java.nio.charset.Charset import java.nio.file.Paths @@ -52,7 +42,10 @@ class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, - ) : IDE { +) : IDE { + + private val gitService = GitService(project, continuePluginService) + private val ripgrep: String init { @@ -66,6 +59,13 @@ class IntelliJIDE( Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString() } + /** + * Updates the timestamp when a file is saved + */ + override fun updateLastFileSaveTimestamp() { + gitService.updateLastFileSaveTimestamp() + } + override suspend fun getIdeInfo(): IdeInfo { val applicationInfo = ApplicationInfo.getInstance() val ideName: String = applicationInfo.fullApplicationName @@ -110,41 +110,7 @@ class IntelliJIDE( } override suspend fun getDiff(includeUnstaged: Boolean): List { - val workspaceDirs = workspaceDirectories() - val diffs = mutableListOf() - - for (workspaceDir in workspaceDirs) { - val output = StringBuilder() - val builder = if (includeUnstaged) { - ProcessBuilder("git", "diff") - } else { - ProcessBuilder("git", "diff", "--cached") - } - builder.directory(File(URI(workspaceDir))) - val process = withContext(Dispatchers.IO) { - builder.start() - } - - val reader = BufferedReader(InputStreamReader(process.inputStream)) - var line: String? = withContext(Dispatchers.IO) { - reader.readLine() - } - while (line != null) { - output.append(line) - output.append("\n") - line = withContext(Dispatchers.IO) { - reader.readLine() - } - } - - withContext(Dispatchers.IO) { - process.waitFor() - } - - diffs.add(output.toString()) - } - - return diffs + return gitService.getDiff(includeUnstaged) } override suspend fun getClipboardContent(): Map { @@ -185,7 +151,7 @@ class IntelliJIDE( } override suspend fun getWorkspaceConfigs(): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = this.getWorkspaceDirs() val configs = mutableListOf() @@ -342,12 +308,116 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getSearchResults(query: String): String { - val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout + override suspend fun getFileResults(pattern: String): List { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ) + + command.setWorkDirectory(project.basePath) + val results = ExecUtil.execAndGetOutput(command).stdout + return results.split("\n") + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } + } } + override suspend fun getSearchResults(query: String): String { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "-i", + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, + "." + ) + + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // For remote workspaces, use JetBrains search functionality + // val searchResults = StringBuilder() + // ApplicationManager.getApplication().invokeAndWait { + // val options = FindModel().apply { + // stringToFind = query + // isCaseSensitive = false + // isRegularExpressions = false + // isWholeWordsOnly = false + // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. + // isMultiline = true // Allow matching across multiple lines + // } + // + // val progressIndicator = EmptyProgressIndicator() + // val presentation = FindUsagesProcessPresentation( + // UsageViewPresentation() + // ) + // val filesToSearch = ProjectFileIndex.getInstance(project) + // .iterateContent(::ArrayList) + // .filterNot { it.isDirectory } + // .toSet() + // + // + // FindInProjectUtil.findUsages( + // options, + // project, + // progressIndicator, + // presentation, + // filesToSearch + // ) { result -> + // val virtualFile = result.virtualFile + // searchResults.append(virtualFile.path).append("\n") + // searchResults.append("${result..trim()}\n") + // true // continue searching + // } + // } + // return searchResults.toString() + } + } + + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") val builder = ProcessBuilder(commandList) @@ -434,7 +504,7 @@ class IntelliJIDE( } override suspend fun getTags(artifactId: String): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = this.getWorkspaceDirs() // Collect branches concurrently using Kotlin coroutines val branches = withContext(Dispatchers.IO) { @@ -577,4 +647,5 @@ class IntelliJIDE( return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() } + } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 55df303a8..f6cf5972f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -27,14 +27,15 @@ class DiffStreamHandler( private val startLine: Int, private val endLine: Int, private val onClose: () -> Unit, - private val onFinish: () -> Unit + private val onFinish: () -> Unit, + private val streamId: String?, + private val toolCallId: String? ) { private data class CurLineState( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) private var curLine = CurLineState(startLine) - private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false @@ -48,8 +49,26 @@ class DiffStreamHandler( initUnfinishedRangeHighlights() } + private fun sendUpdate(status: String) { + if(this.streamId == null) { + return + } + val virtualFile = getVirtualFile() + val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to this.diffBlocks.size, + "streamId" to this.streamId, + "status" to status, + "fileContent" to "not implemented", + "toolCallId" to this.toolCallId, + "filepath" to virtualFile?.url + )) + } + fun acceptAll() { - editor.markupModel.removeAllHighlighters() + editor.markupModel.removeAllHighlighters(); + sendUpdate("closed") + resetState() } @@ -62,6 +81,7 @@ class DiffStreamHandler( } else { undoChanges() } + sendUpdate("closed") resetState() } @@ -70,6 +90,7 @@ class DiffStreamHandler( input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String ) { isRunning = true + this.sendUpdate("streaming") val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) val virtualFile = getVirtualFile() @@ -83,6 +104,7 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() + sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } @@ -133,7 +155,10 @@ class DiffStreamHandler( } if (diffBlocks.isEmpty()) { + sendUpdate("closed") onClose() + } else { + sendUpdate("done") } } @@ -144,6 +169,7 @@ class DiffStreamHandler( ) diffBlocks.add(diffBlock) + sendUpdate("streaming") return diffBlock } @@ -234,6 +260,7 @@ class DiffStreamHandler( undoManager.undo(fileEditor) } } + sendUpdate("done") } } 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 faaf7d058..fd910308d 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 @@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) { textArea.document.insertString(textArea.caretPosition, ", ", null) textArea.requestFocus() customPanelRef.get().finish() - }) + }, + null, + null + ) val diffStreamService = project.service() diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 5ce49e80a..4c66fcc0c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,6 +23,7 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) +data class GetFileResultsParams(val pattern: String) data class SaveFileParams(val filepath: String) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 07988ad0e..718755a99 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -11,8 +11,8 @@ data class SetGitHubAuthTokenParams( data class ApplyToFileParams( val text: String, val streamId: String, - val curSelectedModelTitle: String, - val filepath: String? + val filepath: String?, + val toolCallId: String? ) data class InsertAtCursorParams( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..d3b8ea68a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -41,4 +41,8 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + fun updateLastFileSaveTimestamp() { + ideProtocolClient?.updateLastFileSaveTimestamp() + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 5d8335220..d0d44655c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -11,7 +11,7 @@ import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory import javax.swing.* -const val JS_QUERY_POOL_SIZE = 200 +const val JS_QUERY_POOL_SIZE = "200" class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { @@ -43,6 +43,11 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(project: Project) { private val defaultGUIUrl = "http://continue/index.html" + init { + System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) + System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") + } + val browser: ContinueBrowser by lazy { val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 7dfa83da4..2970ca84a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -159,6 +159,8 @@ interface IDE { suspend fun getSearchResults(query: String): String + suspend fun getFileResults(pattern: String): List + // Note: This should be a `Pair` but we use `List` because the keys of `Pair` // will serialize to `first and `second` rather than `0` and `1` like in JavaScript suspend fun subprocess(command: String, cwd: String? = null): List @@ -192,6 +194,10 @@ interface IDE { // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) + + fun updateLastFileSaveTimestamp() { + // Default implementation does nothing + } } data class GetGhTokenArgs( diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index 29ad0b023..aa99f752c 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -3,6 +3,7 @@ node_modules/ out/ .vscode-test/ data/ +src/.buildTimestamp.ts src/client .continue diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index 9470b2d5e..1bc087276 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## Actions +## Agent -[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases. +[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 2a908c045..801bba5ea 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -956,7 +956,10 @@ "gemini-2.0-flash", "gemini-2.0-flash-thinking-exp-01-21", "gemini-2.0-pro-exp-02-05", - "gemini-2.0-flash-lite-preview-02-05" + "gemini-2.0-flash-lite-preview-02-05", + "gemini-2.0-flash-lite", + "gemini-2.0-flash-exp-image-generation", + "gemini-2.5-pro-exp-03-25" ] } } @@ -2886,7 +2889,8 @@ "watsonx", "llm", "free-trial", - "huggingface-tei" + "huggingface-tei", + "siliconflow" ] }, "params": { @@ -3053,6 +3057,40 @@ "required": ["truncation_direction"] } } + }, + { + "if": { + "properties": { + "name": { + "enum": ["siliconflow"] + } + }, + "required": ["name"] + }, + "then": { + "properties": { + "params": { + "type": "object", + "properties": { + "model": { + "enum": [ + "BAAI/bge-reranker-v2-m3", + "netease-youdao/bce-reranker-base_v1", + "Pro/BAAI/bge-reranker-v2-m3" + ], + "default": "BAAI/bge-reranker-v2-m3" + }, + "apiBase": { + "type": "string" + }, + "apiKey": { + "type": "string" + } + }, + "required": ["apiKey"] + } + } + } } ] }, @@ -3063,7 +3101,7 @@ "default": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "deepseek-coder:1.3b-base" + "model": "qwen2.5-coder:1.5b-base" }, "oneOf": [ { diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index ace296ca3..ef2bf0c16 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -16,8 +16,12 @@ export class GUIActions { await GUIActions.toggleGui(); await TestUtils.waitForSuccess(async () => { await new Workbench().executeCommand("View: Move View"); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(4); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(14); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("Continue"); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("New Secondary Side Bar Entry"); }); // first call focuses the input diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 1170be786..ac76f456e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.17", + "version": "1.1.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.17", + "version": "1.1.23", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -88,7 +88,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.3.9", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, @@ -102,11 +102,11 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.758.0", - "@aws-sdk/client-sagemaker-runtime": "^3.758.0", - "@aws-sdk/credential-providers": "^3.758.0", + "@aws-sdk/client-bedrock-runtime": "^3.779.0", + "@aws-sdk/client-sagemaker-runtime": "^3.777.0", + "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -125,6 +125,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -12293,9 +12294,10 @@ } }, "node_modules/tar-fs": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", - "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", + "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", + "license": "MIT", "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", @@ -12392,10 +12394,11 @@ } }, "node_modules/targz/node_modules/tar-fs": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.3.tgz", - "integrity": "sha512-NvCeXpYx7OsmOh8zIOP/ebG55zZmxLE0etfWRbWok+q2Qo8x/vOR/IJT1taADXPe+jsiu9axDb3X4B+iIgNlKw==", + "version": "1.16.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.4.tgz", + "integrity": "sha512-u3XczWoYAIVXe5GOKK6+VeWaHjtc47W7hyuTo3+4cNakcCcuDmlkYiiHEsECwTkcI3h1VUgtwBQ54+RvY6cM4w==", "dev": true, + "license": "MIT", "dependencies": { "chownr": "^1.0.1", "mkdirp": "^0.5.1", @@ -13319,9 +13322,9 @@ } }, "node_modules/vite": { - "version": "4.5.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", - "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", + "version": "4.5.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz", + "integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 142f9f95d..df19a2e5e 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.17", + "version": "1.1.23", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -127,6 +127,11 @@ "default": false, "markdownDescription": "Pause Continue's codebase index on start." }, + "continue.enableConsole": { + "type": "boolean", + "default": false, + "markdownDescription": "Enable a console to log and explore model inputs and outputs. It can be found in the bottom panel." + }, "continue.remoteConfigServerUrl": { "type": "string", "default": null, @@ -252,6 +257,13 @@ "title": "View History", "group": "Continue" }, + { + "command": "continue.clearConsole", + "category": "Continue", + "title": "Clear Console", + "icon": "$(clear-all)", + "group": "Continue" + }, { "command": "continue.navigateTo", "category": "Continue", @@ -505,6 +517,11 @@ "command": "continue.openConfigPage", "group": "navigation@4", "when": "view == continue.continueGUIView" + }, + { + "command": "continue.clearConsole", + "group": "navigation@1", + "when": "view == continue.continueConsoleView" } ], "editor/title": [ @@ -533,6 +550,13 @@ "title": "Continue", "icon": "media/sidebar-icon.png" } + ], + "panel": [ + { + "id": "continueConsole", + "title": "Continue Console", + "icon": "$(window)" + } ] }, "views": { @@ -544,6 +568,16 @@ "icon": "media/sidebar-icon.png", "visibility": "visible" } + ], + "continueConsole": [ + { + "type": "webview", + "id": "continue.continueConsoleView", + "name": "Continue Console", + "icon": "$(window)", + "visibility": "visible", + "when": "config.continue.enableConsole" + } ] }, "jsonValidation": [ @@ -573,6 +607,7 @@ "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", "package": "node scripts/package.js", "package-all": "node scripts/package-all.js", @@ -625,7 +660,7 @@ "ovsx": "^0.8.3", "rimraf": "^5.0.5", "typescript": "^5.6.3", - "vite": "^4.3.9", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index d8a9d4e68..9382e2b7a 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -1,4 +1,5 @@ const fs = require("fs"); +const { writeBuildTimestamp } = require("./utils"); const esbuild = require("esbuild"); @@ -49,6 +50,8 @@ const esbuildConfig = { }; (async () => { + // Create .buildTimestamp.js before starting the first build + writeBuildTimestamp(); // Bundles the extension into one file if (flags.includes("--watch")) { const ctx = await esbuild.context(esbuildConfig); @@ -74,7 +77,7 @@ const esbuildConfig = { }); console.log("Triggering VS Code Extension esbuild rebuild..."); - fs.utimesSync(inFile, new Date(), new Date()); + writeBuildTimestamp(); } else { await esbuild.build(esbuildConfig); } diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 35ad7d24f..2fd5177eb 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -1,6 +1,10 @@ const { exec } = require("child_process"); const fs = require("fs"); +const version = JSON.parse( + fs.readFileSync("./package.json", { encoding: "utf-8" }), +).version; + const args = process.argv.slice(2); let target; @@ -27,6 +31,6 @@ exec(command, (error) => { throw error; } console.log( - "vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix", + `vsce package completed - extension created at extensions/vscode/build/continue-${version}.vsix`, ); }); diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index aeab677ca..fbec94f6c 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,7 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema } = require("./utils"); +const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -71,6 +71,9 @@ const isMacTarget = target?.startsWith("darwin"); process.chdir("extensions/vscode"); } + // Make sure we have an initial timestamp file + writeBuildTimestamp(); + // Install node_modules // execCmdSync("npm install"); console.log("[info] npm install in extensions/vscode completed"); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index c4d392cfa..8a144731f 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -511,6 +511,20 @@ async function copyScripts() { console.log("[info] Copied script files"); } +// We can't simply touch one of our files to trigger a rebuild, because +// esbuild doesn't always use modifications times to detect changes - +// for example, if it finds a file changed within the last 3 seconds, +// it will fall back to full-contents-comparison for that file +// +// So to facilitate development workflows, we always include a timestamp string +// in the build +function writeBuildTimestamp() { + fs.writeFileSync( + "src/.buildTimestamp.ts", + `export default "${new Date().toISOString()}";\n`, + ); +} + module.exports = { copyConfigSchema, installNodeModules, @@ -526,4 +540,5 @@ module.exports = { downloadRipgrepBinary, copyTokenizers, copyScripts, + writeBuildTimestamp, }; diff --git a/extensions/vscode/scripts/write-build-timestamp.js b/extensions/vscode/scripts/write-build-timestamp.js new file mode 100644 index 000000000..a26f9b8d3 --- /dev/null +++ b/extensions/vscode/scripts/write-build-timestamp.js @@ -0,0 +1,3 @@ +const { writeBuildTimestamp } = require("./utils"); + +writeBuildTimestamp(); diff --git a/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts new file mode 100644 index 000000000..6427091ff --- /dev/null +++ b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts @@ -0,0 +1,221 @@ +import { LLMInteractionItem } from "core"; +import { EXTENSION_NAME } from "core/control-plane/env"; +import { LLMLogger } from "core/llm/logger"; +import * as vscode from "vscode"; + +import { getExtensionUri, getNonce } from "./util/vscode"; + +interface FromConsoleView { + type: "start" | "stop"; + uuid: string; +} + +// Maximum interactions we retain; when we exceed this, we drop the +// oldest and also send a message to the view to do the same. +const MAX_INTERACTIONS = 50; + +export class ContinueConsoleWebviewViewProvider + implements vscode.WebviewViewProvider +{ + public static readonly viewType = "continue.continueConsoleView"; + + resolveWebviewView( + webviewView: vscode.WebviewView, + _context: vscode.WebviewViewResolveContext, + _token: vscode.CancellationToken, + ): void | Thenable { + this._webviewView = webviewView; + this._webview = webviewView.webview; + this._webviewView.onDidDispose(() => { + this._webviewView = undefined; + this._webview = undefined; + }); + webviewView.webview.html = this.getSidebarContent( + this.extensionContext, + webviewView, + ); + this._webview.onDidReceiveMessage((message: FromConsoleView) => { + if (message.type === "start") { + this._currentUuid = message.uuid; + this._webview?.postMessage({ + type: "init", + uuid: this._currentUuid, + items: this.getAllItems(), + }); + } + }); + this._webviewView.onDidDispose(() => { + this._webview = undefined; + this._webviewView = undefined; + this._currentUuid = undefined; + }); + } + + private _webview?: vscode.Webview; + private _webviewView?: vscode.WebviewView; + private _currentUuid?: string; + private _currentInteractions = new Map(); + private _completedInteractions: LLMInteractionItem[][] = []; + private _saveLog; + + constructor( + private readonly windowId: string, + private readonly extensionContext: vscode.ExtensionContext, + private readonly llmLogger: LLMLogger, + ) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration(`${EXTENSION_NAME}.enableConsole`)) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + if (!this._saveLog) { + this.clearLog(); + } + } + }); + + llmLogger.onLogItem((item) => this.addItem(item)); + } + + private addItem(item: LLMInteractionItem) { + if (!this._saveLog) { + return; + } + + let iteractionItems = this._currentInteractions.get(item.interactionId); + if (iteractionItems === undefined) { + iteractionItems = []; + this._currentInteractions.set(item.interactionId, iteractionItems); + } + + iteractionItems.push(item); + switch (item.kind) { + case "success": + case "cancel": + case "error": + this._completedInteractions.push(iteractionItems); + this._currentInteractions.delete(item.interactionId); + break; + default: + break; + } + + if (this._currentUuid) { + this._webview?.postMessage({ + type: "item", + uuid: this._currentUuid, + item, + }); + } + + while ( + this._completedInteractions.length > 0 && + this._completedInteractions.length + this._currentInteractions.size > + MAX_INTERACTIONS + ) { + let toRemove = this._completedInteractions.shift(); + this._webview?.postMessage({ + type: "remove", + uuid: this._currentUuid, + interactionId: toRemove![0].interactionId, + }); + } + } + + private getAllItems() { + let items = this._completedInteractions.flat(); + + for (const interactionItems of this._currentInteractions.values()) { + items.push(...interactionItems); + } + + return items; + } + + clearLog() { + this._completedInteractions = []; + this._currentInteractions = new Map(); + + if (this._currentUuid) { + this._webview?.postMessage({ + type: "clear", + uuid: this._currentUuid, + }); + } + } + + private getSidebarContent( + context: vscode.ExtensionContext | undefined, + panel: vscode.WebviewPanel | vscode.WebviewView, + page: string | undefined = undefined, + ): string { + const extensionUri = getExtensionUri(); + let scriptUri: string; + let styleMainUri: string; + + const inDevelopmentMode = + context?.extensionMode === vscode.ExtensionMode.Development; + if (!inDevelopmentMode) { + scriptUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.js"), + ) + .toString(); + styleMainUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.css"), + ) + .toString(); + } else { + scriptUri = "http://localhost:5173/src/console.tsx"; + styleMainUri = "http://localhost:5173/src/indexConsole.css"; + } + + panel.webview.options = { + enableScripts: true, + localResourceRoots: [ + vscode.Uri.joinPath(extensionUri, "gui"), + vscode.Uri.joinPath(extensionUri, "assets"), + ], + enableCommandUris: true, + portMapping: [ + { + webviewPort: 65433, + extensionHostPort: 65433, + }, + ], + }; + + const nonce = getNonce(); + + return ` + + + + + + + + Continue + + +
+ + ${ + inDevelopmentMode + ? `` + : "" + } + + + `; + } +} diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 883039263..3c8b66dcd 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -555,25 +555,15 @@ class VsCodeIde implements IDE { .map((t) => (t.input as vscode.TabInputText).uri.toString()); } - private async _searchDir(query: string, dir: string): Promise { - const relativeDir = vscode.Uri.parse(dir).fsPath; + runRipgrepQuery(dirUri: string, args: string[]) { + const relativeDir = vscode.Uri.parse(dirUri).fsPath; const ripGrepUri = vscode.Uri.joinPath( getExtensionUri(), "out/node_modules/@vscode/ripgrep/bin/rg", ); - const p = child_process.spawn( - ripGrepUri.fsPath, - [ - "-i", // Case-insensitive search - "-C", - "2", // Show 2 lines of context - "--heading", // Only show filepath once per result - "-e", - query, // Pattern to search for - ".", // Directory to search in - ], - { cwd: relativeDir }, - ); + const p = child_process.spawn(ripGrepUri.fsPath, args, { + cwd: relativeDir, + }); let output = ""; p.stdout.on("data", (data) => { @@ -595,55 +585,118 @@ class VsCodeIde implements IDE { }); } + async getFileResults(pattern: string): Promise { + const MAX_FILE_RESULTS = 200; + if (vscode.env.remoteName) { + // TODO better tests for this remote search implementation + // throw new Error("Ripgrep not supported, this workspace is remote"); + + // IMPORTANT: findFiles automatically accounts for .gitignore + const ignoreFiles = await vscode.workspace.findFiles( + "**/.continueignore", + null, + ); + + const ignoreGlobs: Set = new Set(); + for (const file of ignoreFiles) { + const content = await vscode.workspace.fs.readFile(file); + const filePath = vscode.workspace.asRelativePath(file); + const fileDir = filePath + .replace(/\\/g, "/") + .replace(/\/$/, "") + .split("/") + .slice(0, -1) + .join("/"); + + const patterns = Buffer.from(content) + .toString() + .split("\n") + .map((line) => line.trim()) + .filter( + (line) => line && !line.startsWith("#") && !pattern.startsWith("!"), + ); + // VSCode does not support negations + + patterns + // Handle prefix + .map((pattern) => { + const normalizedPattern = pattern.replace(/\\/g, "/"); + + if (normalizedPattern.startsWith("/")) { + if (fileDir) { + return `{/,}${normalizedPattern}`; + } else { + return `${fileDir}/${normalizedPattern.substring(1)}`; + } + } else { + if (fileDir) { + return `${fileDir}/${normalizedPattern}`; + } else { + return `**/${normalizedPattern}`; + } + } + }) + // Handle suffix + .map((pattern) => { + return pattern.endsWith("/") ? `${pattern}**/*` : pattern; + }) + .forEach((pattern) => { + ignoreGlobs.add(pattern); + }); + } + + const ignoreGlobsArray = Array.from(ignoreGlobs); + + const results = await vscode.workspace.findFiles( + pattern, + ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null, + MAX_FILE_RESULTS, + ); + return results.map((result) => vscode.workspace.asRelativePath(result)); + } else { + const results: string[] = []; + for (const dir of await this.getWorkspaceDirs()) { + const dirResults = await this.runRipgrepQuery(dir, [ + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ]); + + results.push(dirResults); + } + + return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS); + } + } + async getSearchResults(query: string): Promise { + if (vscode.env.remoteName) { + throw new Error("Ripgrep not supported, this workspace is remote"); + } const results: string[] = []; for (const dir of await this.getWorkspaceDirs()) { - const dirResults = await this._searchDir(query, dir); + const dirResults = await this.runRipgrepQuery(dir, [ + "-i", // Case-insensitive search + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", // Show 2 lines of context + "--heading", // Only show filepath once per result + "-e", + query, // Pattern to search for + ".", // Directory to search in + ]); - const keepLines: string[] = []; - - function countLeadingSpaces(line: string) { - return line?.match(/^ */)?.[0].length ?? 0; - } - - // function formatLine(line: string, sectionIndent: number): string { - // return line.replace(new RegExp(`^[ ]{0,${sectionIndent}}`), ""); - // } - - let leading = false; - let sectionIndent = 0; - // let sectionTrim = 0; - for (const line of dirResults.split("\n").filter((l) => !!l)) { - if (line.startsWith("./") || line === "--") { - leading = true; - keepLines.push(line); - continue; - } - - if (leading) { - // Exclude leading single-char lines - if (line.trim().length > 1) { - // Record spacing at first non-single char line - leading = false; - sectionIndent = countLeadingSpaces(line); - keepLines.push(line); - } - continue; - } - // Exclude trailing - // TODO may exclude wanted results for lines that look like - // ./filename - // thisThing - // relevantThing - // - if (countLeadingSpaces(line) >= sectionIndent) { - keepLines.push(line); - } - } - results.push(keepLines.join("\n")); + results.push(dirResults); } - return results.join("\n\n"); + return results.join("\n"); } async getProblems(fileUri?: string | undefined): Promise { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6a1e35424..719c1a5d1 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -12,7 +12,10 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { EXTENSION_NAME } from "core/control-plane/env"; import { Core } from "core/core"; +import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; import { walkDirAsync } from "core/indexing/walkDir"; +import { isModelInstaller } from "core/llm"; +import { startLocalOllama } from "core/util/ollamaHelper"; import { getDevDataFilePath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import readLastLines from "read-last-lines"; @@ -27,8 +30,8 @@ import { setupStatusBar, StatusBarStatus, } from "./autocomplete/statusBar"; +import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; - import { VerticalDiffManager } from "./diff/vertical/manager"; import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; @@ -36,9 +39,6 @@ import { Battery } from "./util/battery"; import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; -import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; -import { isModelInstaller } from "core/llm"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -247,6 +247,7 @@ async function processDiff( verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, + toolCallId?: string, ) { captureCommandTelemetry(`${action}Diff`); @@ -280,6 +281,7 @@ async function processDiff( streamId, status: "closed", numDiffs: 0, + toolCallId, }); } @@ -316,6 +318,7 @@ const getCommandsMap: ( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -327,6 +330,7 @@ const getCommandsMap: ( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, @@ -359,18 +363,18 @@ const getCommandsMap: ( throw new Error("Config not loaded"); } - const modelTitle = - config.selectedModelByRole.edit?.title ?? - (await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - )); + const llm = + config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No edit or chat model selected"); + } void sidebar.webviewProtocol.request("incrementFtc", undefined); await verticalDiffManager.streamEdit( config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, + llm, undefined, onlyOneInsertion, undefined, @@ -634,16 +638,6 @@ const getCommandsMap: ( editDecorationManager.clear(); void sidebar.webviewProtocol?.request("exitEditMode", undefined); }, - // "continue.quickEdit": async (args: QuickEditShowParams) => { - // let linesOfCode = undefined; - // if (args.range) { - // linesOfCode = args.range.end.line - args.range.start.line; - // } - // captureCommandTelemetry("quickEdit", { - // linesOfCode, - // }); - // quickEdit.show(args); - // }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); @@ -680,6 +674,9 @@ const getCommandsMap: ( "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", ); }, + "continue.clearConsole": async () => { + consoleView.clearLog(); + }, "continue.viewLogs": async () => { captureCommandTelemetry("viewLogs"); vscode.commands.executeCommand("workbench.action.toggleDevTools"); @@ -708,37 +705,6 @@ const getCommandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); sidebar.webviewProtocol?.request("addModel", undefined); }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, "continue.newSession": () => { sidebar.webviewProtocol?.request("newSession", undefined); }, @@ -1127,6 +1093,7 @@ export function registerAllCommands( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -1142,6 +1109,7 @@ export function registerAllCommands( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 34c3345ac..48741a142 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { ChatMessage, DiffLine } from "core"; +import { ChatMessage, DiffLine, ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; @@ -7,9 +7,9 @@ import * as URI from "uri-js"; import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; +import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; -import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -190,6 +190,7 @@ export class VerticalDiffManager { diffStream: AsyncGenerator, instant: boolean, streamId: string, + toolCallId?: string, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -226,6 +227,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); @@ -270,12 +272,13 @@ export class VerticalDiffManager { async streamEdit( input: string, - modelTitle: string | undefined, + llm: ILLM, streamId?: string, onlyOneInsertion?: boolean, quickEdit?: string, range?: vscode.Range, newCode?: string, + toolCallId?: string, ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -305,13 +308,13 @@ export class VerticalDiffManager { // Previous diff was a quickEdit // Check if user has highlighted a range let rangeBool = - startLine != endLine || - editor.selection.start.character != editor.selection.end.character; + startLine !== endLine || + editor.selection.start.character !== editor.selection.end.character; // Check if the range is different from the previous range let newRangeBool = - startLine != existingHandler.range.start.line || - endLine != existingHandler.range.end.line; + startLine !== existingHandler.range.start.line || + endLine !== existingHandler.range.end.line; if (!rangeBool || !newRangeBool) { // User did not highlight a new range -> use start/end from the previous quickEdit @@ -351,6 +354,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); @@ -370,7 +374,6 @@ export class VerticalDiffManager { ); } - const llm = await this.configHandler.llmFromTitle(modelTitle); const rangeContent = editor.document.getText(selectedRange); const prefix = pruneLinesFromTop( editor.document.getText( diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index f1aa3f3e4..be2b12487 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -8,6 +8,7 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { getExtensionVersion } from "./util/util"; +export { default as buildTimestamp } from "./.buildTimestamp"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { await setupCa(); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 9441d70cd..c955f8d51 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -21,6 +21,7 @@ import { StatusBarStatus, } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; +import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; @@ -48,6 +49,7 @@ export class VsCodeExtension { private configHandler: ConfigHandler; private extensionContext: vscode.ExtensionContext; private ide: VsCodeIde; + private consoleView: ContinueConsoleWebviewViewProvider; private sidebar: ContinueGUIWebviewViewProvider; private windowId: string; private editDecorationManager: EditDecorationManager; @@ -106,10 +108,6 @@ export class VsCodeExtension { ); resolveWebviewProtocol(this.sidebar.webviewProtocol); - // Config Handler with output channel - const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion", - ); const inProcessMessenger = new InProcessMessenger< ToCoreProtocol, FromCoreProtocol @@ -125,19 +123,12 @@ export class VsCodeExtension { this.editDecorationManager, ); - this.core = new Core(inProcessMessenger, this.ide, async (log: string) => { - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.append(log); - }); + this.core = new Core(inProcessMessenger, this.ide); this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); this.configHandler.loadConfig(); + this.verticalDiffManager = new VerticalDiffManager( this.configHandler, this.sidebar.webviewProtocol, @@ -202,16 +193,10 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId) { - if (orgId === "null") { - orgId = null; - } + if (orgId && orgId !== "null") { // In case org id is passed with profile id // Make sure org is updated before profile is set - if (profileId) { - if (profileId === "null") { - profileId = null; - } + if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedOrg", { id: orgId, profileId, @@ -221,10 +206,7 @@ export class VsCodeExtension { id: orgId, }); } - } else if (profileId) { - if (profileId === "null") { - profileId = null; - } + } else if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedProfile", { id: profileId, }); @@ -253,12 +235,27 @@ export class VsCodeExtension { this.fileSearch, ); + // LLM Log view + this.consoleView = new ContinueConsoleWebviewViewProvider( + this.windowId, + this.extensionContext, + this.core.llmLogger, + ); + + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueConsoleView", + this.consoleView, + ), + ); + // Commands registerAllCommands( context, this.ide, context, this.sidebar, + this.consoleView, this.configHandler, this.verticalDiffManager, this.core.continueServerClientPromise, @@ -334,14 +331,6 @@ export class VsCodeExtension { ); const sessionInfo = await getControlPlaneSessionInfo(true, false); - this.webviewProtocolPromise.then(async (webviewProtocol) => { - void webviewProtocol.request("didChangeControlPlaneSessionInfo", { - sessionInfo, - }); - - // To make sure continue-proxy models and anything else requiring it get updated access token - this.configHandler.reloadConfig(); - }); void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo, }); @@ -415,10 +404,7 @@ export class VsCodeExtension { vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings(); - const webviewProtocol = await this.webviewProtocolPromise; - void webviewProtocol.request("didChangeIdeSettings", { - settings, - }); + void this.core.invoke("config/ideSettingsUpdate", settings); } }); } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..591c82454 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -28,7 +28,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -133,6 +132,7 @@ export class VsCodeMessenger { streamId: data.streamId, status: "streaming", fileContent: data.text, + toolCallId: data.toolCallId, }); if (data.filepath) { @@ -164,6 +164,7 @@ export class VsCodeMessenger { status: "closed", numDiffs: 0, fileContent: data.text, + toolCallId: data.toolCallId, }); return; @@ -178,19 +179,14 @@ export class VsCodeMessenger { return; } - let llm: ILLM | null | undefined = config.selectedModelByRole.apply; + let llm = + config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; if (!llm) { - llm = config.models.find( - (model) => model.title === data.curSelectedModelTitle, + vscode.window.showErrorMessage( + `No model with roles "apply" or "chat" found in config.`, ); - - if (!llm) { - vscode.window.showErrorMessage( - `Model ${data.curSelectedModelTitle} not found in config.`, - ); - return; - } + return; } const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm; @@ -211,6 +207,7 @@ export class VsCodeMessenger { diffLines, instant, data.streamId, + data.toolCallId, ); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; @@ -226,12 +223,13 @@ export class VsCodeMessenger { await verticalDiffManager.streamEdit( prompt, - llm.title, + llm, data.streamId, undefined, undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); @@ -288,9 +286,19 @@ export class VsCodeMessenger { const { start, end } = msg.data.range.range; const verticalDiffManager = await verticalDiffManagerPromise; + const configHandler = await configHandlerPromise; + const { config } = await configHandler.loadConfig(); + + const model = + config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat; + + if (!model) { + throw new Error("No Edit or Chat model selected"); + } + const fileAfterEdit = await verticalDiffManager.streamEdit( stripImages(prompt), - msg.data.selectedModelTitle, + model, "edit", undefined, undefined, @@ -391,6 +399,9 @@ export class VsCodeMessenger { this.onWebviewOrCore("getSearchResults", async (msg) => { return ide.getSearchResults(msg.data.query); }); + this.onWebviewOrCore("getFileResults", async (msg) => { + return ide.getFileResults(msg.data.pattern); + }); this.onWebviewOrCore("subprocess", async (msg) => { return ide.subprocess(msg.data.command, msg.data.cwd); }); diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index 074ec4d86..f982c5c55 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -34,7 +34,7 @@ export async function getContextProvidersString( provider.description.displayTitle === selectedProvider.label, ); - if (!provider) { + if (!provider || !config.selectedModelByRole.chat) { return []; } @@ -43,7 +43,7 @@ export async function getContextProvidersString( ide, embeddingsProvider: config.selectedModelByRole.embed, reranker: config.selectedModelByRole.rerank, - llm: config.models[0], + llm: config.selectedModelByRole.chat, fullInput: "", selectedCode: [], fetch: (url, init) => diff --git a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts b/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts deleted file mode 100644 index d46ed6d43..000000000 --- a/extensions/vscode/src/quickEdit/ModelSelectionQuickPick.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ContinueConfig } from "core"; -import { QuickPickItem, window } from "vscode"; - -export async function getModelQuickPickVal( - curModelTitle: string, - config: ContinueConfig, -) { - const modelItems: QuickPickItem[] = config.models.map((model) => { - const isCurModel = curModelTitle === model.title; - - return { - label: model.title - ? `${isCurModel ? "$(check)" : " "} ${model.title}` - : "Model title not set", - }; - }); - - const selectedItem = await window.showQuickPick(modelItems, { - title: "Models", - placeHolder: "Select a model", - }); - - if (!selectedItem) { - return undefined; - } - - const selectedModelTitle = config.models.find( - (model) => model.title && selectedItem.label.includes(model.title), - )?.title; - - return selectedModelTitle; -} diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index ec84eb81b..e0c826fb1 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { IDE } from "core"; +import { IDE, ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { DataLogger } from "core/data/log"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -8,10 +9,8 @@ import { VerticalDiffManager } from "../diff/vertical/manager"; import { FileSearch } from "../util/FileSearch"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { DataLogger } from "core/data/log"; import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick"; import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; -import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; // @ts-ignore - error finding typings // @ts-ignore @@ -23,7 +22,6 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; enum QuickEditInitialItemLabels { History = "History", ContextProviders = "Context providers", - Model = "Model", Submit = "Submit", } @@ -100,11 +98,6 @@ export class QuickEdit { */ private contextProviderStr?: string; - /** - * Stores the current model title for potential changes - */ - private _curModelTitle?: string; - constructor( private readonly verticalDiffManager: VerticalDiffManager, private readonly configHandler: ConfigHandler, @@ -224,7 +217,7 @@ export class QuickEdit { default: break; } - let model = await this.getCurModelTitle(); + let model = await this.getCurModel(); void DataLogger.getInstance().logDevData({ name: "quickEdit", @@ -233,7 +226,7 @@ export class QuickEdit { path, label, diffs: this.verticalDiffManager.logDiffs, - model, + model: model?.title, }, }); @@ -245,12 +238,12 @@ export class QuickEdit { prompt: string, path: string | undefined, ) => { - const modelTitle = await this.getCurModelTitle(); - if (!modelTitle) { + const model = await this.getCurModel(); + if (!model) { throw new Error("No model selected"); } - await this._streamEditWithInputAndContext(prompt, modelTitle); + await this._streamEditWithInputAndContext(prompt, model); this.openAcceptRejectMenu(prompt, path); }; @@ -266,25 +259,13 @@ export class QuickEdit { /** * Gets the model title the user has chosen, or their default model */ - private async getCurModelTitle(): Promise { - if (this._curModelTitle) { - return this._curModelTitle; - } - + private async getCurModel(): Promise { const { config } = await this.configHandler.loadConfig(); if (!config) { - return undefined; + return null; } - return ( - config.selectedModelByRole.edit?.title ?? - (await this.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - false, - )) ?? - config.models[0]?.title - ); + return config.selectedModelByRole.edit ?? config.selectedModelByRole.chat; } /** @@ -314,10 +295,7 @@ export class QuickEdit { }`; }; - private async _streamEditWithInputAndContext( - prompt: string, - modelTitle: string, - ) { + private async _streamEditWithInputAndContext(prompt: string, model: ILLM) { // Extracts all file references from the prompt string, // which are denoted by an '@' symbol followed by // one or more non-whitespace characters. @@ -343,7 +321,7 @@ export class QuickEdit { await this.verticalDiffManager.streamEdit( prompt, - modelTitle, + model, undefined, undefined, this.previousInput, @@ -351,7 +329,7 @@ export class QuickEdit { ); } - private getInitialItems(modelTitle: string): vscode.QuickPickItem[] { + private getInitialItems(): vscode.QuickPickItem[] { return [ { label: QuickEditInitialItemLabels.History, @@ -361,10 +339,6 @@ export class QuickEdit { label: QuickEditInitialItemLabels.ContextProviders, detail: "$(add) Add context to your prompt", }, - { - label: QuickEditInitialItemLabels.Model, - detail: `$(chevron-down) ${modelTitle}`, - }, ]; } @@ -372,7 +346,7 @@ export class QuickEdit { label: QuickEditInitialItemLabels | undefined; value: string | undefined; }> { - const modelTitle = await this.getCurModelTitle(); + const modelTitle = await this.getCurModel(); if (!modelTitle) { this.ide.showToast("error", "Please configure a model to use Quick Edit"); @@ -381,7 +355,7 @@ export class QuickEdit { const quickPick = vscode.window.createQuickPick(); - const initialItems = this.getInitialItems(modelTitle); + const initialItems = this.getInitialItems(); quickPick.items = initialItems; quickPick.placeholder = "Enter a prompt to edit your code (@ to search files, ⏎ to submit)"; @@ -552,27 +526,6 @@ export class QuickEdit { break; - case QuickEditInitialItemLabels.Model: - const curModelTitle = await this.getCurModelTitle(); - - if (!curModelTitle) { - break; - } - - const selectedModelTitle = await getModelQuickPickVal( - curModelTitle, - config, - ); - - if (selectedModelTitle) { - this._curModelTitle = selectedModelTitle; - } - - // Recurse back to let the user write their prompt - this.initiateNewQuickPick(editor, params); - - break; - case QuickEditInitialItemLabels.Submit: if (selectedValue) { prompt = selectedValue; diff --git a/extensions/vscode/src/test/test-suites/main.test.ts b/extensions/vscode/src/test/test-suites/main.test.ts deleted file mode 100644 index 2cd1945fa..000000000 --- a/extensions/vscode/src/test/test-suites/main.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from "node:assert"; - -import { describe, test } from "mocha"; -import * as vscode from "vscode"; - -import { VsCodeExtension } from "../../extension/VsCodeExtension"; - -describe("Extension Test Suite", () => { - vscode.window.showInformationMessage("Start all tests."); - - // test("Make sure that nothing breaks after 10 seconds", async () => { - // await new Promise((resolve) => setTimeout(resolve, 10_000)); - // }); - - test("Get the default model from webview", async () => { - const continueExtensionApi = - vscode.extensions.getExtension("continue.continue"); - const extension: VsCodeExtension = continueExtensionApi?.exports.extension; - await new Promise((resolve) => setTimeout(resolve, 400)); - await vscode.commands.executeCommand("continue.focusContinueInput"); - await new Promise((resolve) => setTimeout(resolve, 400)); - const title = await ( - await extension.webviewProtocolPromise - ).request("getDefaultModelTitle", undefined); - assert.strictEqual(typeof title, "string"); - assert.strictEqual(title, "Test Model"); - }); -}); diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..a7a58f894 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -9,6 +9,7 @@ "strict": true, "esModuleInterop": true, "resolveJsonModule": true, + "skipLibCheck": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], diff --git a/gui/indexConsole.html b/gui/indexConsole.html new file mode 100644 index 000000000..aaa69903b --- /dev/null +++ b/gui/indexConsole.html @@ -0,0 +1,13 @@ + + + + + + + Continue + + +
+ + + diff --git a/gui/package-lock.json b/gui/package-lock.json index 389343794..2105fc59b 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -25,7 +25,6 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", @@ -63,8 +62,7 @@ "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", @@ -95,7 +93,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.1.0", + "vite": "^4.5.11", "vitest": "^2.1.3" }, "engines": { @@ -107,11 +105,11 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.758.0", - "@aws-sdk/client-sagemaker-runtime": "^3.758.0", - "@aws-sdk/credential-providers": "^3.758.0", + "@aws-sdk/client-bedrock-runtime": "^3.779.0", + "@aws-sdk/client-sagemaker-runtime": "^3.777.0", + "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -130,6 +128,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -205,6 +204,27 @@ "node": ">=20.11.0" } }, + "../packages/config-yaml": { + "name": "@continuedev/config-yaml", + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -545,23 +565,9 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, - "node_modules/@continuedev/config-types": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", - "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", - "dependencies": { - "zod": "^3.23.8" - } - }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - } + "resolved": "../packages/config-yaml", + "link": true }, "node_modules/@emotion/is-prop-valid": { "version": "1.3.1", @@ -3236,11 +3242,6 @@ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==" }, - "node_modules/@types/vscode-webview": { - "version": "1.57.5", - "resolved": "https://registry.npmjs.org/@types/vscode-webview/-/vscode-webview-1.57.5.tgz", - "integrity": "sha512-iBAUYNYkz+uk1kdsq05fEcoh8gJmwT3lqqFPN7MGyjQ3HVloViMdo7ZJ8DFIP8WOK74PjOEilosqAyxV2iUFUw==" - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.16.0.tgz", @@ -5959,19 +5960,6 @@ "url": "https://github.com/sponsors/rawify" } }, - "node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -6175,11 +6163,6 @@ "url": "https://github.com/sindresorhus/got?sponsor=1" } }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" - }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -7666,17 +7649,6 @@ "node": ">=6" } }, - "node_modules/jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -12179,14 +12151,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "engines": { - "node": ">= 10.0.0" - } - }, "node_modules/update-browserslist-db": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", @@ -12291,9 +12255,9 @@ } }, "node_modules/vite": { - "version": "4.5.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", - "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", + "version": "4.5.11", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz", + "integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==", "dev": true, "license": "MIT", "dependencies": { @@ -13428,14 +13392,6 @@ } } }, - "node_modules/vscode-webview": { - "version": "1.0.1-beta.1", - "resolved": "https://registry.npmjs.org/vscode-webview/-/vscode-webview-1.0.1-beta.1.tgz", - "integrity": "sha512-8H2icqlb93qIvZs7Me/0sALMqJrX2e2W7JVE0mfK8exUPETP9Bmg+feivaByd1Xbg78lcKaNF9ZRrIFSenUVxQ==", - "dependencies": { - "fs-extra": "^10.0.0" - } - }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", @@ -13824,6 +13780,7 @@ "version": "2.6.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz", "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", + "dev": true, "bin": { "yaml": "bin.mjs" }, @@ -13843,14 +13800,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/zod": { - "version": "3.24.2", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", - "integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/gui/package.json b/gui/package.json index 33f326de3..1a46aa97e 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -33,7 +33,6 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", @@ -71,8 +70,7 @@ "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", @@ -103,7 +101,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.1.0", + "vite": "^4.5.11", "vitest": "^2.1.3" }, "engine-strict": true, diff --git a/gui/public/logos/docker.png b/gui/public/logos/docker.png new file mode 100644 index 000000000..600476cfe Binary files /dev/null and b/gui/public/logos/docker.png differ diff --git a/gui/public/logos/inception.png b/gui/public/logos/inception.png new file mode 100644 index 000000000..4ef5ad6a0 Binary files /dev/null and b/gui/public/logos/inception.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index deb1e376f..15082d35b 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,11 +1,10 @@ import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; +import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; -import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigPage from "./pages/config"; -import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; @@ -34,18 +33,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: "/addModel", - element: , - }, - { - path: "/addModel/provider/:providerName", - element: , - }, - { - path: ROUTES.CONFIG_ERROR, - element: , - }, { path: ROUTES.CONFIG, element: , @@ -66,9 +53,11 @@ function SetupListeners() { function App() { return ( - - - + + + + + ); diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 7e0e2e183..776c0721b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -2,14 +2,17 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice"; -import { getParagraphNodeFromString } from "../mainInput/utils"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; const NUM_CARDS_TO_RENDER = 5; +/** + * Displays a grid of conversation starter cards for bookmarked slash commands + */ export function ConversationStarterCards() { const dispatch = useAppDispatch(); + const { mainEditor } = useMainEditor(); const [showAll, setShowAll] = useState(false); const { isCommandBookmarked } = useBookmarkedSlashCommands(); const slashCommands = useAppSelector( @@ -21,11 +24,7 @@ export function ConversationStarterCards() { ); function onClick(command: SlashCommandDescription) { - if (command.prompt) { - dispatch( - setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)), - ); - } + mainEditor?.commands.insertPrompt(command); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 6f96e498d..839f7ed7c 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -4,10 +4,11 @@ import { useMemo } from "react"; import { themeIcons } from "seti-file-icons"; export interface FileIconProps { + height: `${number}px`; + width: `${number}px`; filename: string; - height: string; - width: string; } + export default function FileIcon({ filename, height, width }: FileIconProps) { const file = useMemo(() => { if (filename.includes(" (")) { @@ -45,7 +46,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { height: height, fill: color, flexShrink: 0, - display: "block", + display: "flex", }} /> ); diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index b2efd221c..d6e79651c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -1,11 +1,11 @@ import { useAppSelector } from "../redux/hooks"; -import { selectDefaultModel } from "../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../redux/slices/configSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; import { getLocalStorage } from "../util/localStorage"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; function Footer() { - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); if (defaultModel?.provider === "free-trial") { return ( diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index d2d91f1ea..0f52d3d0b 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -6,14 +6,12 @@ import { AuthProvider } from "../context/Auth"; import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { selectUseHub } from "../redux/selectors"; import { focusEdit, setEditStatus } from "../redux/slices/editModeState"; import { addCodeToEdit, newSession, selectIsInEditMode, setMode, - updateApplyState, } from "../redux/slices/sessionSlice"; import { setShowDialog } from "../redux/slices/uiSlice"; import { exitEditMode } from "../redux/thunks"; @@ -126,20 +124,6 @@ const Layout = () => { [], ); - useWebviewListener( - "updateApplyState", - async (state) => { - // dispatch( - // updateCurCheckpoint({ - // filepath: state.filepath, - // content: state.fileContent, - // }), - // ); - dispatch(updateApplyState(state)); - }, - [], - ); - useWebviewListener( "openOnboardingCard", async () => { @@ -250,21 +234,6 @@ const Layout = () => { } }, [location]); - const useHub = useAppSelector(selectUseHub); - - // Existing users that have already seen the onboarding card - // should be shown an intro card for hub.continue.dev - // useEffect(() => { - // if (useHub !== true) { - // return; - // } - // const seenHubIntro = getLocalStorage("seenHubIntro"); - // if (!onboardingCard.show && !seenHubIntro) { - // onboardingCard.setActiveTab("ExistingUserHubIntro"); - // } - // setLocalStorage("seenHubIntro", true); - // }, [onboardingCard.show, useHub]); - return ( diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index a4baa9a1e..aa8be2a29 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -37,7 +37,7 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { return ( onboardingCard.close()} testId="onboarding-card" > diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 389ed72dd..d739a8434 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -1,11 +1,12 @@ import { CubeIcon } from "@heroicons/react/24/outline"; import { FormEventHandler, useContext, useState } from "react"; -import { useDispatch } from "react-redux"; import { Button, Input, InputSubtext, lightGray } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { models } from "../../../pages/AddNewModel/configs/models"; import { providers } from "../../../pages/AddNewModel/configs/providers"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; +import { useAppDispatch } from "../../../redux/hooks"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; const { anthropic, mistral } = providers; @@ -25,7 +26,8 @@ interface BestExperienceConfigFormProps { function BestExperienceConfigForm({ onComplete, }: BestExperienceConfigFormProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); @@ -61,7 +63,14 @@ function BestExperienceConfigForm({ model: repoMapConfig, role: "repoMapFileSelection", }); - dispatch(setDefaultModel({ title: chatModelConfig.title, force: true })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: chatModelConfig.title, + }), + ); if (!!autocompleteApiKey) { await ideMessenger.request("addAutocompleteModel", { diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index 4c0deda74..daa064ea2 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -28,7 +28,7 @@ export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { return ( onboardingCard.close()} >
diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index 8ca75b1e3..ab197b3d4 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -3,6 +3,8 @@ import { useContext } from "react"; import { Button, ButtonSubtext } from "../../.."; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { selectCurrentOrg } from "../../../../redux"; +import { useAppSelector } from "../../../../redux/hooks"; import { hasPassedFTL } from "../../../../util/freeTrial"; import ContinueLogo from "../../../gui/ContinueLogo"; import { useOnboardingCard } from "../../hooks"; @@ -17,6 +19,7 @@ export default function MainTab({ const ideMessenger = useContext(IdeMessengerContext); const onboardingCard = useOnboardingCard(); const auth = useAuth(); + const currentOrg = useAppSelector(selectCurrentOrg); function onGetStarted() { auth.login(true).then((success) => { @@ -29,7 +32,7 @@ export default function MainTab({ function openPastFreeTrialOnboarding() { ideMessenger.post("controlPlane/openUrl", { path: "setup-models", - orgSlug: auth.selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); onboardingCard.close(isDialog); } diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 81b0a7a6b..0f1e05da0 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -6,15 +6,16 @@ import { LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; import { Button } from "../.."; +import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../../redux/thunks"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; -import { setDefaultModel } from "../../../redux/slices/configSlice"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; const OLLAMA_CHECK_INTERVAL_MS = 3000; @@ -23,13 +24,14 @@ interface OnboardingLocalTabProps { } function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const { submitOnboarding } = useSubmitOnboarding("Local", isDialog); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< string[] >([]); + const { selectedProfile } = useAuth(); const [isOllamaConnected, setIsOllamaConnected] = useState(false); @@ -135,11 +137,11 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { dispatch(setShowDialog(false)); } - // Set the selected model to the local chat model dispatch( - setDefaultModel({ - title: LOCAL_ONBOARDING_CHAT_TITLE, - force: true, // Because it doesn't exist in the webview's config object yet + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: LOCAL_ONBOARDING_CHAT_TITLE, }), ); }} diff --git a/gui/src/components/StepContainer/ThinkingIndicator.tsx b/gui/src/components/StepContainer/ThinkingIndicator.tsx index 862351872..3dcbf9491 100644 --- a/gui/src/components/StepContainer/ThinkingIndicator.tsx +++ b/gui/src/components/StepContainer/ThinkingIndicator.tsx @@ -1,7 +1,7 @@ import { ChatHistoryItem } from "core"; import { useEffect, useState } from "react"; import { useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; interface ThinkingIndicatorProps { historyItem: ChatHistoryItem; @@ -22,7 +22,7 @@ const ThinkingIndicator = ({ historyItem }: ThinkingIndicatorProps) => { }; }, []); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const hasContent = Array.isArray(historyItem.message.content) diff --git a/gui/src/components/console/Details.tsx b/gui/src/components/console/Details.tsx new file mode 100644 index 000000000..a9edfa8a6 --- /dev/null +++ b/gui/src/components/console/Details.tsx @@ -0,0 +1,116 @@ +import { useEffect, useRef } from "react"; +import { LLMInteraction } from "../../hooks/useLLMLog"; +import useLLMSummary from "../../hooks/useLLMSummary"; +import End from "./End"; +import ResultGroup from "./ResultGroup"; +import Start from "./Start"; +import StatusIcon from "./StatusIcon"; + +export interface DetailsProps { + interaction: LLMInteraction; +} + +function renderCell(children: React.ReactNode) { + return ( +
+ {children} +
+ ); +} + +/** + * A cell of statistics at the top of the details view + */ +function Cell({ + label, + value, + format, +}: { + label: string; + value: any; + format?: (value: any) => string; +}) { + return renderCell( + value != undefined ? `${label}: ${format ? format(value) : value}` : "", + ); +} + +/** + * A cell of statistics at the top of the details view with custom content + */ +function CustomCell({ children }: { children: React.ReactNode }) { + return renderCell(children); +} + +function formatSeconds(milliseconds: number) { + return (milliseconds / 1000).toFixed(2) + "s"; +} + +export default function Details({ interaction }: DetailsProps) { + const scrollTop = useRef(null); + const lastResult = useRef(null); + const summary = useLLMSummary(interaction); + + useEffect(() => { + if (interaction.end) { + return; + } + + const last = interaction.results[interaction.results.length - 1]; + if (last != lastResult.current) { + lastResult.current = last; + const lastChild = scrollTop.current?.lastChild; + if (lastChild) { + (lastChild as HTMLElement).scrollIntoView({ + behavior: "auto", + block: "end", + }); + } + } + }); + + return ( +
+
+
+ + + Result: + {summary.result} + +
+
+ + + +
+
+ + + v.toFixed(1)} + > +
+
+
+ {interaction.start ? : ""} +
+ {interaction.results.map((group, i) => { + return ; + })} +
+ {interaction.end ? : ""} +
+
+ ); +} diff --git a/gui/src/components/console/End.tsx b/gui/src/components/console/End.tsx new file mode 100644 index 000000000..382ac4bda --- /dev/null +++ b/gui/src/components/console/End.tsx @@ -0,0 +1,37 @@ +import { + LLMInteractionCancel, + LLMInteractionError, + LLMInteractionSuccess, +} from "core"; +import Expander from "./Expander"; +import Message from "./Message"; + +export interface StartProps { + item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel; +} + +export default function Start({ item }: StartProps) { + //
+ switch (item.kind) { + case "success": + return <>; + case "error": + return ( +
+ + Error + + {item.message} +
+ ); + break; + case "cancel": + return ( +
+ + Cancelled + +
+ ); + } +} diff --git a/gui/src/components/console/Expander.tsx b/gui/src/components/console/Expander.tsx new file mode 100644 index 000000000..f7d958463 --- /dev/null +++ b/gui/src/components/console/Expander.tsx @@ -0,0 +1,25 @@ +import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { ReactNode, useState } from "react"; + +export interface ExpanderProps { + label: string; + children: ReactNode; +} + +export default function Expander({ label, children }: ExpanderProps) { + const [expanded, setExpanded] = useState(false); + + return ( +
+
setExpanded(!expanded)}> + {expanded ? ( + + ) : ( + + )}{" "} + {label} +
+ {expanded &&
{children}
} +
+ ); +} diff --git a/gui/src/components/console/Layout.tsx b/gui/src/components/console/Layout.tsx new file mode 100644 index 000000000..d1dcd9266 --- /dev/null +++ b/gui/src/components/console/Layout.tsx @@ -0,0 +1,30 @@ +import { useState } from "react"; +import useLLMLog from "../../hooks/useLLMLog"; +import Details from "./Details"; +import List from "./List"; + +export default function Layout() { + const llmLog = useLLMLog(); + + const [selectedId, setSelectedId] = useState(undefined); + + const interaction = selectedId + ? llmLog.interactions.get(selectedId) + : undefined; + + return llmLog.loading ? ( +
Loading...
+ ) : ( +
+ { + setSelectedId(interactionId); + }} + > + {interaction && ( +
+ )} +
+ ); +} diff --git a/gui/src/components/console/List.tsx b/gui/src/components/console/List.tsx new file mode 100644 index 000000000..b10a15684 --- /dev/null +++ b/gui/src/components/console/List.tsx @@ -0,0 +1,53 @@ +import { useEffect, useRef, useState } from "react"; +import { LLMLog } from "../../hooks/useLLMLog"; +import ListItem from "./ListItem"; + +export interface ListProps { + llmLog: LLMLog; + onClickInteraction: (interactionId: string) => void; +} + +export default function List({ llmLog, onClickInteraction }: ListProps) { + const topRef = useRef(null); + const [selectedId, setSelectedId] = useState(undefined); + + const lastSize = useRef(0); + + useEffect(() => { + if (llmLog.order.length != lastSize.current) { + setSelectedId(llmLog.order[llmLog.order.length - 1]); + onClickInteraction(llmLog.order[llmLog.order.length - 1]); + + lastSize.current = llmLog.order.length; + const lastChild = topRef.current?.lastChild; + if (lastChild) { + (lastChild as HTMLElement).scrollIntoView({ + behavior: "smooth", + block: "end", + }); + } + } + }); + + return ( +
    + {llmLog.order.map((id) => ( + { + topRef.current?.focus(); + setSelectedId(interactionId); + onClickInteraction(interactionId); + }} + selected={id == selectedId} + > + ))} +
+ ); +} diff --git a/gui/src/components/console/ListItem.tsx b/gui/src/components/console/ListItem.tsx new file mode 100644 index 000000000..bbd4a4be3 --- /dev/null +++ b/gui/src/components/console/ListItem.tsx @@ -0,0 +1,55 @@ +import { LLMInteraction } from "../../hooks/useLLMLog"; +import useLLMSummary from "../../hooks/useLLMSummary"; +import StatusIcon from "./StatusIcon"; + +export interface ListItemProps { + interactionId: string; + interaction: LLMInteraction; + selected: boolean; + onClickInteraction: (interactionId: string) => void; +} + +function formatTimestamp(timestamp: number) { + const date = new Date(timestamp); + + const hours = date.getHours().toString().padStart(2, "0"); + const minutes = date.getMinutes().toString().padStart(2, "0"); + const seconds = date.getSeconds(); + const milliseconds = date.getMilliseconds(); + + // Format seconds with one decimal place + const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`; + + return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`; +} + +export default function ListItem({ + interactionId, + interaction, + onClickInteraction, + selected, +}: ListItemProps) { + const summary = useLLMSummary(interaction); + + return ( +
  • onClickInteraction(interactionId)} + > + {" "} + + {interaction.start ? formatTimestamp(interaction.start.timestamp) : ""} + + {summary.type} +
  • + ); +} diff --git a/gui/src/components/console/Message.tsx b/gui/src/components/console/Message.tsx new file mode 100644 index 000000000..8c5c35bc6 --- /dev/null +++ b/gui/src/components/console/Message.tsx @@ -0,0 +1,106 @@ +import { + AssistantChatMessage, + ChatMessage, + ThinkingChatMessage, + UserChatMessage, +} from "core"; +import { memo } from "react"; + +export interface MessageProps { + message: ChatMessage; +} + +function renderMessageText(text: string) { + return {text}; +} + +export function renderMessageRole(role: ChatMessage["role"]) { + return ( +
    + + {role} + +
    + ); +} + +function renderMessageContent( + message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage, +) { + if (typeof message.content == "string") { + return renderMessageText(message.content); + } else { + return message.content.map((part) => { + if (part.type == "text") { + return renderMessageText(part.text); + } else { + return
    Image: {part.imageUrl.url}
    ; + } + }); + } +} + +export function renderMessage(message: ChatMessage, includeRole: boolean) { + switch (message.role) { + case "assistant": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {message.toolCalls + ? message.toolCalls.map((toolCall) => ( +
    Tool call: {JSON.stringify(toolCall, undefined, 2)}
    + )) + : ""} + {renderMessageContent(message)} + + ); + break; + case "thinking": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {message.toolCalls + ? message.toolCalls.map((toolCall) => ( +
    Tool call: {JSON.stringify(toolCall, undefined, 2)}
    + )) + : ""} + {renderMessageContent(message)} + {message.redactedThinking && ( +
    Redacted Thinking: {message.redactedThinking}
    + )} + {message.signature &&
    Signature: {message.signature}
    } + + ); + break; + case "user": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {renderMessageContent(message)} + + ); + break; + case "system": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {renderMessageText(message.content)} + + ); + case "tool": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} +
    Tool Call ID: {message.toolCallId}
    + {renderMessageText(message.content)} + + ); + break; + } +} + +const Message = memo(function Message({ message }: MessageProps) { + return renderMessage(message, true); +}); + +export default Message; diff --git a/gui/src/components/console/Result.tsx b/gui/src/components/console/Result.tsx new file mode 100644 index 000000000..6122fa2a8 --- /dev/null +++ b/gui/src/components/console/Result.tsx @@ -0,0 +1,37 @@ +import { memo } from "react"; +import { LLMResult } from "../../hooks/useLLMLog"; +import { renderMessage } from "./Message"; + +interface ResultProps { + result: LLMResult; + prevResult: LLMResult | undefined; +} + +const Result = memo(function Result({ result, prevResult }: ResultProps) { + switch (result.kind) { + case "chunk": + return {result.chunk}; + break; + case "message": + switch (result.message.role) { + case "assistant": + case "thinking": + const includeRole = !( + prevResult?.kind === "message" && + prevResult.message.role === result.message.role + ); + return renderMessage(result.message, includeRole); + default: + // We don't expect anything but AssistantChatMessages and ThinkingChatMessages in the reply + // from the LLM output, but log them if they do occur. + return ( +
    + {renderMessage(result.message, true)} +
    + ); + } + break; + } +}); + +export default Result; diff --git a/gui/src/components/console/ResultGroup.tsx b/gui/src/components/console/ResultGroup.tsx new file mode 100644 index 000000000..b7ed2933c --- /dev/null +++ b/gui/src/components/console/ResultGroup.tsx @@ -0,0 +1,19 @@ +import { memo } from "react"; +import { LLMResult } from "../../hooks/useLLMLog"; +import Result from "./Result"; + +interface ResultGroupProps { + group: LLMResult[]; +} + +const ResultGroup = memo(function ResultGroup({ group }: ResultGroupProps) { + return ( + <> + {group.map((result, i) => ( + + ))} + + ); +}); + +export default ResultGroup; diff --git a/gui/src/components/console/Start.tsx b/gui/src/components/console/Start.tsx new file mode 100644 index 000000000..a28601aaa --- /dev/null +++ b/gui/src/components/console/Start.tsx @@ -0,0 +1,73 @@ +import { + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, +} from "core"; +import Expander from "./Expander"; +import Message from "./Message"; + +export interface StartProps { + item: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim; +} + +export default function Start({ item }: StartProps) { + return ( +
    + {(() => { + switch (item.kind) { + case "startChat": + return ( + <> + +
    + {item.messages.map((message, i) => ( + + ))} +
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + break; + case "startComplete": + return ( + <> + +
    {item.prompt}
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + break; + case "startFim": + return ( + <> + +
    {item.prefix}
    +
    + +
    {item.suffix}
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + } + })()} +
    + ); +} diff --git a/gui/src/components/console/StatusIcon.tsx b/gui/src/components/console/StatusIcon.tsx new file mode 100644 index 000000000..51cbe7a91 --- /dev/null +++ b/gui/src/components/console/StatusIcon.tsx @@ -0,0 +1,34 @@ +import { + CheckIcon, + EllipsisHorizontalIcon, + StopCircleIcon, + XCircleIcon, +} from "@heroicons/react/24/outline"; +import { LLMInteraction } from "../../hooks/useLLMLog"; + +export interface StatusIconProps { + interaction: LLMInteraction; +} + +export default function StatusIcon({ interaction }: StatusIconProps) { + if (interaction.end) { + switch (interaction.end.kind) { + case "success": + return ( + + ); + case "cancel": + return ( + + ); + case "error": + return ( + + ); + } + } else { + return ( + + ); + } +} diff --git a/gui/src/components/gui/HeaderButtonWithToolTip.tsx b/gui/src/components/gui/HeaderButtonWithToolTip.tsx index 8c357d5ea..2ee4496fe 100644 --- a/gui/src/components/gui/HeaderButtonWithToolTip.tsx +++ b/gui/src/components/gui/HeaderButtonWithToolTip.tsx @@ -48,7 +48,7 @@ const HeaderButtonWithToolTip = React.forwardRef< - {props.text} + {props.text} ); diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index beeb37070..9d5a10bec 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -5,6 +5,7 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; +import { RangeInFile } from "core"; import { forwardRef, useContext, @@ -24,6 +25,8 @@ import { vscQuickInputBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -138,11 +141,29 @@ interface AtMentionDropdownProps { onClose: () => void; } +const formatFileSize = (fileSize: number) => { + const KB = 1000; + const MB = 1000_000; + const GB = 1000_000_000; + + if (fileSize > GB) { + return `${(fileSize / GB).toFixed(1)} GB`; + } else if (fileSize > MB) { + return `${(fileSize / MB).toFixed(1)} MB`; + } else if (fileSize > KB) { + return `${(fileSize / KB).toFixed(1)} KB`; + } + + return `${fileSize} byte${fileSize > 1 ? "s" : ""}`; +}; + const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); + const selectedModelTitle = useAppSelector(selectSelectedChatModel); + const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -157,6 +178,88 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const [allItems, setAllItems] = useState([]); + async function isItemTooBig( + name: string, + query: string, + ): Promise<[boolean, number]> { + const selectedCode: RangeInFile[] = []; + // Get context item from core + const contextResult = await ideMessenger.request( + "context/getContextItems", + { + name, + query, + fullInput: "", + selectedCode, + selectedModelTitle: selectedModelTitle?.title ?? "", + }, + ); + + if (contextResult.status === "error") { + return [false, -1]; + } + + const item = contextResult.content[0]; + + // Check if the context item exceeds the context length of the selected model + const result = await ideMessenger.request("isItemTooBig", { + item, + selectedModelTitle: selectedModelTitle?.title, + }); + + if (result.status === "error") { + return [false, -1]; + } + + const size = new Blob([item.content]).size; + + return [result.content, size]; + } + + function handleItemTooBig( + fileExceeds: boolean, + fileSize: number, + item: ComboBoxItem, + ) { + if (fileExceeds) { + props.editor + .chain() + .focus() + .command(({ tr, state }) => { + const text = state.doc.textBetween( + 0, + state.selection.from, + "\n", + "\n", + ); // Get the text before the cursor + const lastAtIndex = text.lastIndexOf("@"); + + if (lastAtIndex !== -1) { + // Delete text after the last "@" + tr.delete(lastAtIndex + 1, state.selection.from); + return true; + } + return false; + }) + .run(); + + // Trigger warning message + ideMessenger.ide.showToast( + "warning", + fileSize > 0 ? "File exceeds context length" : "Can't load the file", + { + modal: true, + detail: + fileSize > 0 + ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model` + : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, + }, + ); + } else { + props.command({ ...item, itemType: item.type }); + } + } + useEffect(() => { const items = [...props.items]; if (subMenuTitle === "Type to search docs") { @@ -243,7 +346,13 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { } if (item) { - props.command({ ...item, itemType: item.type }); + if (item.type === "file" && item.query) { + isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) => + handleItemTooBig(fileExceeds, fileSize, item), + ); + } else { + props.command({ ...item, itemType: item.type }); + } } }; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 2b91b707b..14777acb6 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,6 +1,6 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useMemo, useState } from "react"; +import { useMemo } from "react"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; import { useAppSelector } from "../../redux/hooks"; @@ -8,7 +8,7 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; -import TipTapEditor from "./tiptap/TipTapEditor"; +import { TipTapEditor } from "./TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; @@ -113,12 +113,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) { } : {}; - const [lumpOpen, setLumpOpen] = useState(true); - return (
    - {props.isMainInput && } + {props.isMainInput && } diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index de2c410f7..252126425 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -14,7 +14,7 @@ import { import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { selectHasCodeToEdit, selectIsInEditMode, @@ -31,7 +31,7 @@ import { ToolTip } from "../gui/Tooltip"; import ModelSelect from "../modelSelection/ModelSelect"; import ModeSelect from "../modelSelection/ModeSelect"; import { useFontSize } from "../ui/font"; -import HoverItem from "./InputToolbar/bottom/HoverItem"; +import HoverItem from "./InputToolbar/HoverItem"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -87,24 +87,27 @@ interface InputToolbarProps { toolbarOptions?: ToolbarOptions; disabled?: boolean; isMainInput?: boolean; - lumpOpen: boolean; - setLumpOpen: (open: boolean) => void; } function InputToolbar(props: InputToolbarProps) { const dispatch = useAppDispatch(); const fileInputRef = useRef(null); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + const activeToolCallStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit || - toolCallState?.status === "generated"; + toolCallState?.status === "generated" || + !!activeToolCallStreamId; + const toolsSupported = defaultModel && modelSupportsTools(defaultModel); const supportsImages = diff --git a/gui/src/components/mainInput/InputToolbar/bottom/HoverItem.tsx b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx similarity index 100% rename from gui/src/components/mainInput/InputToolbar/bottom/HoverItem.tsx rename to gui/src/components/mainInput/InputToolbar/HoverItem.tsx diff --git a/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx b/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx deleted file mode 100644 index f82ea9860..000000000 --- a/gui/src/components/mainInput/InputToolbar/top/TopInputToolbar.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline"; -import { ToolbarOptions } from "../../InputToolbar"; -import HoverItem from "../bottom/HoverItem"; - -interface TopInputToolbarProps { - toolbarOptions?: ToolbarOptions; - onAddContextItem?: () => void; - lumpOpen: boolean; - setLumpOpen: (open: boolean) => void; -} -export function TopInputToolbar(props: TopInputToolbarProps) { - return ( -
    - props.setLumpOpen(!props.lumpOpen)} - className="ml-auto" - > - - -
    - ); -} diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 5a6a27ae2..4ecf299b7 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -4,16 +4,17 @@ import { ChevronLeftIcon, CubeIcon, EllipsisHorizontalIcon, + ExclamationTriangleIcon, PencilIcon, Squares2X2Icon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; -import { vscBadgeBackground, vscBadgeForeground } from "../.."; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice"; +import { vscBadgeForeground } from "../.."; +import { useAppSelector } from "../../../redux/hooks"; import { fontSize } from "../../../util"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; -import HoverItem from "../InputToolbar/bottom/HoverItem"; +import HoverItem from "../InputToolbar/HoverItem"; +import { useLump } from "./LumpContext"; interface BlockSettingsToolbarIcon { tooltip: string; @@ -37,9 +38,14 @@ const sections: Section[] = [ { id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon }, { id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon }, { id: "mcp", tooltip: "MCP", icon: Squares2X2Icon }, + { id: "error", tooltip: "Errors", icon: ExclamationTriangleIcon }, ]; -function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { +function BlockSettingsToolbarIcon( + props: BlockSettingsToolbarIcon & { sectionId?: string }, +) { + const isErrorSection = props.sectionId === "error"; + return (
    void; -} +export function BlockSettingsTopToolbar() { + const { + isToolbarExpanded, + toggleToolbar, + selectedSection, + setSelectedSection, + } = useLump(); + + const configError = useAppSelector((store) => store.config.configError); -export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { - const isExpanded = useAppSelector( - (state) => state.ui.isBlockSettingsToolbarExpanded, - ); - const dispatch = useAppDispatch(); const handleEllipsisClick = () => { - if (isExpanded) { - props.setSelectedSection(null); + if (isToolbarExpanded) { + setSelectedSection(null); } - dispatch(toggleBlockSettingsToolbar()); + toggleToolbar(); }; + const visibleSections = sections.filter( + (section) => + section.id !== "error" || + (section.id === "error" && configError && configError?.length > 0), + ); + return (
    -
    - -
    -
    - {sections.map((section) => ( - - props.setSelectedSection( - props.selectedSection === section.id ? null : section.id, - ) - } - /> - ))} +
    +
    + +
    +
    + {visibleSections.map((section) => ( + + setSelectedSection( + selectedSection === section.id ? null : section.id, + ) + } + /> + ))} +
    -
    +
    diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx index 53cd82cfb..6cdcac4b0 100644 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -4,7 +4,10 @@ import { useContext } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -type SectionKey = Exclude; +type SectionKey = Exclude< + keyof ConfigYaml, + "name" | "version" | "schema" | "metadata" +>; interface EditBlockButtonProps { blockType: T; diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx new file mode 100644 index 000000000..92c5dbd6c --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -0,0 +1,115 @@ +/** + * Provides context for controlling the Lump component's visibility state + */ +import { + createContext, + ReactNode, + useCallback, + useContext, + useEffect, + useState, +} from "react"; +import { useAppSelector } from "../../../redux/hooks"; + +interface LumpContextType { + isLumpVisible: boolean; + selectedSection: string | null; + displayedSection: string | null; + isToolbarExpanded: boolean; + hideLump: () => void; + setSelectedSection: (section: string | null) => void; + toggleToolbar: () => void; +} + +const LumpContext = createContext(undefined); + +interface LumpProviderProps { + children: ReactNode; +} + +/** + * Provider component that makes Lump state available to any child component + */ +export function LumpProvider({ children }: LumpProviderProps) { + const [selectedSection, setSelectedSection] = useState(null); + const [displayedSection, setDisplayedSection] = useState(null); + const [isVisible, setIsVisible] = useState(false); + const [isToolbarExpanded, setIsToolbarExpanded] = useState(true); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + + // Handle keyboard escape + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === "Escape" && selectedSection) { + setSelectedSection(null); + } + }, + [selectedSection], + ); + + // Function to hide the lump + const hideLump = useCallback(() => { + setSelectedSection(null); + }, []); + + // Function to toggle toolbar expanded state + const toggleToolbar = useCallback(() => { + setIsToolbarExpanded((prev) => !prev); + }, []); + + // Update displayedSection and visibility when selectedSection changes + useEffect(() => { + if (selectedSection) { + setDisplayedSection(selectedSection); + setIsVisible(true); + } else { + setIsVisible(false); + const timeout = setTimeout(() => { + setDisplayedSection(null); + }, 300); + return () => clearTimeout(timeout); + } + }, [selectedSection]); + + // Reset when streaming starts + useEffect(() => { + if (isStreaming && selectedSection) { + setSelectedSection(null); + } + }, [isStreaming, selectedSection]); + + // Set up keyboard listener + useEffect(() => { + if (selectedSection) { + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); + } + }, [selectedSection, handleKeyDown]); + + return ( + + {children} + + ); +} + +/** + * Hook that lets any component access the Lump context + */ +export function useLump() { + const context = useContext(LumpContext); + if (context === undefined) { + throw new Error("useLump must be used within a LumpProvider"); + } + return context; +} diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index cca7885d3..2cac02cbb 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -1,17 +1,16 @@ import { useContext } from "react"; import styled from "styled-components"; +import { AnimatedEllipsis } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - clearLastEmptyResponse, - setInactive, -} from "../../../redux/slices/sessionSlice"; +import { cancelStream } from "../../../redux/thunks/cancelStream"; import { getFontSize, getMetaKeyLabel } from "../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; const Container = styled.div` display: flex; - justify-content: flex-end; + justify-content: space-between; + align-items: center; width: 100%; `; @@ -22,12 +21,16 @@ const StopButton = styled.div` cursor: pointer; `; -interface TopToolbarProps { - selectedSection: string | null; - setSelectedSection: (value: string | null) => void; +function GeneratingIndicator() { + return ( +
    + Generating + +
    + ); } -export function LumpToolbar(props: TopToolbarProps) { +export function LumpToolbar() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const ttsActive = useAppSelector((state) => state.ui.ttsActive); @@ -36,6 +39,7 @@ export function LumpToolbar(props: TopToolbarProps) { if (ttsActive) { return ( + { @@ -51,11 +55,11 @@ export function LumpToolbar(props: TopToolbarProps) { if (isStreaming) { return ( + { - dispatch(setInactive()); - dispatch(clearLastEmptyResponse()); + dispatch(cancelStream()); }} > {getMetaKeyLabel()} ⌫ Cancel @@ -64,10 +68,5 @@ export function LumpToolbar(props: TopToolbarProps) { ); } - return ( - - ); + return ; } diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index a642136b4..de432f1d1 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -1,20 +1,14 @@ -import { useEffect, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, vscInputBackground, } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; +import { LumpProvider, useLump } from "./LumpContext"; import { LumpToolbar } from "./LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; -interface LumpProps { - open: boolean; - setOpen: (open: boolean) => void; -} - -const LumpDiv = styled.div<{ open: boolean }>` +const LumpDiv = styled.div` background-color: ${vscInputBackground}; margin-left: 4px; margin-right: 4px; @@ -35,47 +29,34 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>` overflow-y: auto; `; -export function Lump(props: LumpProps) { - const { open, setOpen } = props; - const [selectedSection, setSelectedSection] = useState(null); - const [displayedSection, setDisplayedSection] = useState(null); - const [isVisible, setIsVisible] = useState(false); - const isStreaming = useAppSelector((state) => state.session.isStreaming); +/** + * Main component that displays the toolbar and selected content section + */ +export function Lump() { + return ( + + + + ); +} - useEffect(() => { - if (selectedSection) { - setDisplayedSection(selectedSection); - setIsVisible(true); - } else { - setIsVisible(false); - // Delay clearing the displayed section until after the fade-out - const timeout = setTimeout(() => { - setDisplayedSection(null); - }, 300); // Match the transition duration - return () => clearTimeout(timeout); - } - }, [selectedSection]); - - if (!open) { - return null; - } +/** + * Internal component that consumes the LumpContext + */ +function LumpContent() { + const { isLumpVisible, selectedSection } = useLump(); return ( - +
    - + - {!isStreaming && ( - - )} +
    diff --git a/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx new file mode 100644 index 000000000..d4d01141c --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx @@ -0,0 +1,40 @@ +import { + ExclamationCircleIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../../../redux/hooks"; + +export function ErrorSection() { + const configError = useAppSelector((state) => state.config.configError); + + const sortedErrors = configError + ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) + : []; + + return ( +
    +
      + {sortedErrors.map((error, index) => ( +
    • + {error.fatal ? ( + + ) : ( + + )} +

      + {error.fatal ? "Fatal Error:" : "Warning:"}{" "} + {error.message} +

      +
    • + ))} +
    +
    + ); +} diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index ad2212ac7..6885870df 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -50,7 +50,7 @@ export function ExploreBlocksButton(props: { blockType: string }) { return (
    - {text} + + {text}
    ); diff --git a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx index 05e9352f0..b128db0a2 100644 --- a/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/ModelsSection.tsx @@ -1,54 +1,31 @@ import { ModelRole } from "@continuedev/config-yaml"; import { ModelDescription } from "core"; -import { useContext } from "react"; import { useAuth } from "../../../../context/Auth"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, - updateConfig, -} from "../../../../redux/slices/configSlice"; +import { updateSelectedModelByRole } from "../../../../redux/thunks"; import { isJetBrains } from "../../../../util"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; export function ModelsSection() { const { selectedProfile } = useAuth(); const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); const jetbrains = isJetBrains(); - const selectedChatModel = useAppSelector(selectDefaultModel); function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) { - if (!selectedProfile) { - return; - } - // Optimistic update - dispatch( - updateConfig({ - ...config, - selectedModelByRole: { - ...config.selectedModelByRole, - [role]: model, - }, - }), - ); - ideMessenger.post("config/updateSelectedModel", { - profileId: selectedProfile.id, - role, - title: model?.title ?? null, - }); - } - - // TODO use handleRoleUpdate for chat - function handleChatModelSelection(model: ModelDescription | null) { if (!model) { return; } - dispatch(setDefaultModel({ title: model.title })); + + dispatch( + updateSelectedModelByRole({ + role, + selectedProfile, + modelTitle: model.title, + }), + ); } return ( @@ -58,16 +35,8 @@ export function ModelsSection() { displayName="Chat" description="Used in the chat interface" models={config.modelsByRole.chat} - selectedModel={ - selectedChatModel - ? { - title: selectedChatModel.title, - provider: selectedChatModel.provider, - model: selectedChatModel.model, - } - : null - } - onSelect={(model) => handleChatModelSelection(model)} + selectedModel={config.selectedModelByRole.chat} + onSelect={(model) => handleRoleUpdate("chat", model)} /> void; onEdit?: () => void; } +/** + * Displays a single prompt row with bookmark and edit controls + */ function PromptRow({ - command, - description, + prompt, isBookmarked, setIsBookmarked, onEdit, }: PromptRowProps) { + const { mainEditor } = useMainEditor(); + const { hideLump } = useLump(); + + const handlePromptClick = (e: React.MouseEvent) => { + e.stopPropagation(); + mainEditor?.commands.insertPrompt(prompt); + hideLump(); + }; + + const handleBookmarkClick = (e: React.MouseEvent) => { + e.stopPropagation(); + setIsBookmarked(!isBookmarked); + }; + + const handleEditClick = (e: React.MouseEvent) => { + e.stopPropagation(); + if (onEdit) { + onEdit(); + } + }; + return (
    -
    - {command} - {description} +
    + + {prompt.name} + + + {prompt.description} +
    setIsBookmarked(!isBookmarked)} + onClick={handleBookmarkClick} className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125" > {isBookmarked ? ( @@ -54,8 +84,12 @@ function PromptRow({ ); } +/** + * Section that displays all available prompts with bookmarking functionality + */ export function PromptsSection() { const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands(); + const slashCommands = useAppSelector( (state) => state.config.config.slashCommands ?? [], ); @@ -74,12 +108,11 @@ export function PromptsSection() { }); return ( -
    +
    {sortedCommands.map((prompt) => ( toggleBookmark(prompt)} onEdit={() => handleEdit(prompt)} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 4cb7b0051..cd9e94d91 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -1,4 +1,4 @@ -import { parseConfigYaml } from "@continuedev/config-yaml"; +import { parseConfigYaml, type Rule } from "@continuedev/config-yaml"; import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline"; import { useContext, useMemo } from "react"; import { useSelector } from "react-redux"; @@ -13,11 +13,12 @@ import { import { RootState } from "../../../../redux/store"; import { fontSize } from "../../../../util"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; +import { useLump } from "../LumpContext"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface RuleCardProps { index: number; - rule: string; + rule: Rule; onClick: () => void; title: string; } @@ -31,12 +32,32 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { setDialogMessage(

    {title}

    -
    {rule}
    +
    +            {/** TODO: Render the rule in a more readable way */}
    +            {JSON.stringify(rule)}
    +          
    , ), ); } + const renderRuleContent = () => { + if (typeof rule === "string") { + return
    {rule}
    ; + } + + if (rule.rule) { + return ( +
    +
    {rule.rule}
    + {rule.if &&
    if: {rule.if}
    } +
    + ); + } + + return
    {JSON.stringify(rule)}
    ; + }; + return (
    = ({ index, rule, onClick, title }) => { }} className="line-clamp-3 text-gray-400" > - {rule} + {renderRuleContent()}
    @@ -82,6 +103,7 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { export function RulesSection() { const ideMessenger = useContext(IdeMessengerContext); const { selectedProfile } = useAuth(); + const { hideLump } = useLump(); const rules = useSelector( (state: RootState) => state.config.config.rules ?? [], @@ -97,11 +119,13 @@ export function RulesSection() { })); }, [rules]); - const openUrl = (path: string) => + const openUrl = (path: string) => { ideMessenger.request("controlPlane/openUrl", { path, orgSlug: undefined, }); + hideLump(); + }; return (
    @@ -113,11 +137,12 @@ export function RulesSection() { key={index} index={index} rule={rule.unrolledRule} - onClick={() => + onClick={() => { ideMessenger.post("config/openProfile", { profileId: undefined, - }) - } + }); + hideLump(); + }} title="Locally Defined Rule" /> ); @@ -137,27 +162,25 @@ export function RulesSection() { ); } - if (!rule.ruleFromYaml?.uses) { - return null; + if ("uses" in rule.ruleFromYaml) { + const ruleSlug = rule.ruleFromYaml?.uses; + + return ( + openUrl(`${ruleSlug}/new-version`)} + title={ruleSlug} + /> + ); } - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); + // TODO: Handle rules as object with 'if' + return null; })}
    ); } -function useTypedDispatch() { - throw new Error("Function not implemented."); -} diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 28dc37c28..85f72078f 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,17 +1,20 @@ +import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; import DocsSection from "./docs/DocsSection"; +import { ErrorSection } from "./ErrorSection"; import { MCPSection } from "./MCPSection"; import { ModelsSection } from "./ModelsSection"; import { PromptsSection } from "./PromptsSection"; import { RulesSection } from "./RulesSection"; -import { ToolsSection } from "./ToolsSection"; +import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection"; -interface SelectedSectionProps { - selectedSection: string | null; -} +/** + * Renders the appropriate section based on the selected section in the Lump context + */ +export function SelectedSection() { + const { displayedSection } = useLump(); -export function SelectedSection(props: SelectedSectionProps) { - switch (props.selectedSection) { + switch (displayedSection) { case "models": return ; case "rules": @@ -23,9 +26,11 @@ export function SelectedSection(props: SelectedSectionProps) { case "context": return ; case "tools": - return ; + return ; case "mcp": return ; + case "error": + return ; default: return null; } diff --git a/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx b/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx deleted file mode 100644 index af03f7220..000000000 --- a/gui/src/components/mainInput/Lump/sections/ToolsSection.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { ToolPermissionsDialog } from "../../InputToolbar/bottom/ToolPermissionsDialog"; - -interface ToolsSectionProps {} - -export function ToolsSection({}: ToolsSectionProps) { - return ; -} diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx index 51b9d35c3..9189a794c 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx @@ -12,6 +12,7 @@ import { import { fontSize } from "../../../../../util"; import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog"; import EditBlockButton from "../../EditBlockButton"; +import { useLump } from "../../LumpContext"; import { StatusIndicator } from "./StatusIndicator"; interface IndexingStatusViewerProps { docConfig: SiteIndexingConfig; @@ -24,6 +25,7 @@ function DocsIndexingStatus({ }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useAppDispatch(); + const { hideLump } = useLump(); const status = useAppSelector( (store) => store.indexing.indexing.statuses[docConfig.startUrl], @@ -78,7 +80,7 @@ function DocsIndexingStatus({ if (hasDeleted) return null; return ( -
    +
    @@ -87,16 +89,10 @@ function DocsIndexingStatus({ onClick={() => { if (status?.url) { ideMessenger.post("openUrl", status.url); + hideLump(); } }} > - {docConfig.faviconUrl ? ( - doc icon - ) : null}

    store.config.config); const indexingStatuses = useAppSelector( (store) => store.indexing.indexing.statuses, ); const { selectedProfile } = useAuth(); - const mergedDocs = useMemo(() => { const parsed = selectedProfile?.rawYaml ? parseConfigYaml(selectedProfile?.rawYaml ?? "") diff --git a/gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx similarity index 85% rename from gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx rename to gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx index 5ab7bfa45..7ad61abd0 100644 --- a/gui/src/components/mainInput/InputToolbar/bottom/ToolPermissionsDialog.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx @@ -1,12 +1,12 @@ import { Tool } from "core"; import { useMemo } from "react"; -import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; -import { toggleToolGroupSetting } from "../../../../redux/slices/uiSlice"; -import { fontSize } from "../../../../util"; -import ToggleSwitch from "../../../gui/Switch"; -import ToolDropdownItem from "./ToolDropdownItem"; +import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; +import { toggleToolGroupSetting } from "../../../../../redux/slices/uiSlice"; +import { fontSize } from "../../../../../util"; +import ToggleSwitch from "../../../../gui/Switch"; +import ToolPolicyItem from "./ToolPolicyItem"; -export const ToolPermissionsDialog = () => { +export const ToolPoliciesSection = () => { const availableTools = useAppSelector((state) => state.config.config.tools); const toolGroupSettings = useAppSelector( (store) => store.ui.toolGroupSettings, @@ -61,7 +61,7 @@ export const ToolPermissionsDialog = () => {

    {tools.map((tool) => ( - state.ui.toolSettings[props.tool.function.name], ); useEffect(() => { - if (!settings) { + if (!policy) { dispatch(addTool(props.tool)); } - }, [props.tool.function.name, settings]); + }, [props.tool.function.name, policy]); - if (!settings) { + if (!policy) { return null; } @@ -81,13 +84,13 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { Excluded ) : (
    - {(settings === "allowedWithPermission" || settings === undefined) && ( + {(policy === "allowedWithPermission" || policy === undefined) && ( Ask First )} - {settings === "allowedWithoutPermission" && ( + {policy === "allowedWithoutPermission" && ( Automatic )} - {settings === "disabled" && ( + {policy === "disabled" && ( Excluded )}
    @@ -96,4 +99,4 @@ function ToolDropdownItem(props: ToolDropdownItemProps) { ); } -export default ToolDropdownItem; +export default ToolPolicyItem; diff --git a/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx new file mode 100644 index 000000000..874640aa5 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx @@ -0,0 +1,117 @@ +import { Editor } from "@tiptap/react"; +import { InputModifiers } from "core"; +import React, { + createContext, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { setMainEditorContentTrigger } from "../../../redux/slices/sessionSlice"; +import { useMainEditorWebviewListeners } from "./useMainEditorWebviewListeners"; + +/** + * Context for accessing the main editor instance + */ +interface MainEditorContextType { + /** The current main editor instance */ + mainEditor: Editor | null; + /** Set the current main editor instance */ + setMainEditor: (editor: Editor | null) => void; + /** The current input ID */ + inputId: string | null; + /** Set the current input ID */ + setInputId: (id: string) => void; + /** Reference to the execute content function */ + onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>; +} + +const MainEditorContext = createContext( + undefined, +); + +/** + * Provider component that maintains a reference to the main editor + */ +export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + const dispatch = useAppDispatch(); + const [mainEditor, setMainEditorInternal] = useState(null); + const [inputId, setInputId] = useState(null); + const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {}); + const editorFocusedRef = useRef(false); + const historyLength = useAppSelector((store) => store.session.history.length); + + // Listen for changes to mainEditorContentTrigger in Redux + const mainEditorContentTrigger = useAppSelector( + (store) => store.session.mainEditorContentTrigger, + ); + + useEffect(() => { + if (mainEditor && mainEditorContentTrigger) { + queueMicrotask(() => { + mainEditor.commands.setContent(mainEditorContentTrigger); + }); + // Clear the trigger after using it + dispatch(setMainEditorContentTrigger(undefined)); + } + }, [mainEditor, mainEditorContentTrigger, dispatch]); + + // Update focused ref when editor focus state changes + useEffect(() => { + if (mainEditor) { + const updateFocus = () => { + editorFocusedRef.current = mainEditor.isFocused || false; + }; + + mainEditor.on("focus", updateFocus); + mainEditor.on("blur", updateFocus); + + return () => { + mainEditor.off("focus", updateFocus); + mainEditor.off("blur", updateFocus); + }; + } + }, [mainEditor]); + + // Set up main editor webview listeners when we have a valid editor and input ID + useMainEditorWebviewListeners({ + editor: mainEditor, + onEnterRef, + dispatch, + historyLength, + inputId: inputId || "", + editorFocusedRef, + }); + + const setMainEditor = (newEditor: Editor | null) => { + setMainEditorInternal(newEditor); + }; + + const value: MainEditorContextType = { + mainEditor, + setMainEditor, + inputId, + setInputId, + onEnterRef, + }; + + return ( + + {children} + + ); +}; + +/** + * Hook to access the main editor context + */ +export const useMainEditor = (): MainEditorContextType => { + const context = useContext(MainEditorContext); + if (context === undefined) { + throw new Error("useMainEditor must be used within a MainEditorProvider"); + } + return context; +}; diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.css b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.css similarity index 100% rename from gui/src/components/mainInput/tiptap/TipTapEditor.css rename to gui/src/components/mainInput/TipTapEditor/TipTapEditor.css diff --git a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx similarity index 83% rename from gui/src/components/mainInput/tiptap/TipTapEditor.tsx rename to gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 47323e4ee..f5d172dc2 100644 --- a/gui/src/components/mainInput/tiptap/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -6,20 +6,16 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; -import { - selectIsInEditMode, - setMainEditorContentTrigger, -} from "../../../redux/slices/sessionSlice"; +import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; +import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; -import { DragOverlay } from "./DragOverlay"; -import { createEditorConfig, getPlaceholderText } from "./editorConfig"; -import { handleImageFile } from "./imageUtils"; -import { useEditorEventHandlers } from "./keyHandlers"; -import { InputBoxDiv } from "./StyledComponents"; +import { DragOverlay, InputBoxDiv } from "./components"; +import { useMainEditor } from "./MainEditorProvider"; import "./TipTapEditor.css"; -import { useWebviewListeners } from "./useWebviewListeners"; +import { handleImageFile } from "./utils"; +import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig"; +import { useEditorEventHandlers } from "./utils/keyHandlers"; export interface TipTapEditorProps { availableContextProviders: ContextProviderDescription[]; @@ -32,23 +28,25 @@ export interface TipTapEditorProps { ) => void; editorState?: JSONContent; toolbarOptions?: ToolbarOptions; - lumpOpen: boolean; - setLumpOpen: (open: boolean) => void; placeholder?: string; historyKey: string; + + // TODO: This isn't actually used anywhere in this component, but it appears + // to be pulled into some of our TipTap extensions. inputId: string; } export const TIPPY_DIV_ID = "tippy-js-div"; -function TipTapEditor(props: TipTapEditorProps) { +export function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); + const mainEditorContext = useMainEditor(); const ideMessenger = useContext(IdeMessengerContext); const isOSREnabled = useIsOSREnabled(); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const isInEditMode = useAppSelector(selectIsInEditMode); const historyLength = useAppSelector((store) => store.session.history.length); @@ -59,6 +57,15 @@ function TipTapEditor(props: TipTapEditorProps) { dispatch, }); + // Register the main editor with the provider + useEffect(() => { + if (props.isMainInput && editor) { + mainEditorContext.setMainEditor(editor); + mainEditorContext.setInputId(props.inputId); + mainEditorContext.onEnterRef.current = onEnterRef.current; + } + }, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]); + const [shouldHideToolbar, setShouldHideToolbar] = useState(true); useEffect(() => { @@ -103,30 +110,6 @@ function TipTapEditor(props: TipTapEditorProps) { } }, [props.isMainInput, isStreaming, editor]); - // This allows anywhere in the app to set the content of the main input - const mainInputContentTrigger = useAppSelector( - (store) => store.session.mainEditorContentTrigger, - ); - useEffect(() => { - if (!props.isMainInput || !mainInputContentTrigger) { - return; - } - queueMicrotask(() => { - editor?.commands.setContent(mainInputContentTrigger); - }); - dispatch(setMainEditorContentTrigger(undefined)); - }, [editor, props.isMainInput, mainInputContentTrigger]); - - // IDE event listeners - useWebviewListeners({ - editor, - onEnterRef, - dispatch, - historyLength, - props, - editorFocusedRef, - }); - const [showDragOverMsg, setShowDragOverMsg] = useState(false); const [activeKey, setActiveKey] = useState(null); @@ -152,7 +135,6 @@ function TipTapEditor(props: TipTapEditorProps) { editor, isOSREnabled: isOSREnabled, editorFocusedRef, - isInEditMode, setActiveKey, }); @@ -189,9 +171,6 @@ function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(false); }, [cancelBlurTimeout]); - // TODO pass clear blur timeout to model and mode selectors - // Seems like unnecessary for now? - return ( ); } - -export default TipTapEditor; diff --git a/gui/src/components/mainInput/tiptap/DragOverlay.tsx b/gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx similarity index 100% rename from gui/src/components/mainInput/tiptap/DragOverlay.tsx rename to gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx new file mode 100644 index 000000000..b7f3d724c --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -0,0 +1,231 @@ +import { + ChevronDownIcon, + EyeSlashIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { EyeIcon } from "@heroicons/react/24/solid"; +import { useEffect, useMemo, useRef, useState } from "react"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscBadgeBackground, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from "../../.."; +import { useAppSelector } from "../../../../redux/hooks"; +import { getFontSize } from "../../../../util"; +import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; + +const MAX_PREVIEW_HEIGHT = 100; +const MAX_EXPANED_PREVIEW_HEIGHT = MAX_PREVIEW_HEIGHT * 3; + +const PreviewDiv = styled.div<{ + borderColor?: string; +}>` + background-color: ${vscEditorBackground}; + border-radius: ${defaultBorderRadius}; + border: 0.5px solid ${(props) => props.borderColor || lightGray}; + margin-top: 4px; + margin-bottom: 4px; + overflow: hidden; + position: relative; + + & div { + background-color: ${vscEditorBackground}; + } +`; + +const ContentContainer = styled.div<{ expanded: boolean }>` + position: relative; + max-height: ${(props) => + props.expanded + ? `${MAX_EXPANED_PREVIEW_HEIGHT}px` + : `${MAX_PREVIEW_HEIGHT}px`}; + overflow: hidden; + display: flex; + flex-direction: column; +`; + +const ScrollableContent = styled.div<{ shouldShowChevron: boolean }>` + overflow-y: auto; + padding-bottom: ${(props) => (props.shouldShowChevron ? "24px" : "0px")}; +`; + +const ChevronContainer = styled.div` + position: sticky; + bottom: 0; + left: 0; + right: 0; + display: flex; + justify-content: center; + background: ${vscEditorBackground}; + padding: 4px 0; + z-index: 10; +`; + +/** + * Props for the ExpandableToolbarPreview component + */ +interface ExpandableToolbarPreviewProps { + /** Title to display in the header */ + title: string; + /** Optional icon to display next to the title */ + icon?: React.ReactNode; + /** ID of the input this preview is associated with (for toolbar hiding logic) */ + inputId?: string; + /** ID of the item being displayed (for toolbar hiding logic) */ + itemId?: string; + /** Whether the preview is initially hidden (overridden if inputId and itemId are provided) */ + initiallyHidden?: boolean; + /** Callback when the delete button is clicked */ + onDelete?: () => void; + /** Callback when the title is clicked */ + onTitleClick?: (e: React.MouseEvent) => void; + /** Border color of the preview */ + borderColor?: string; + /* Whether the preview is selected */ + isSelected?: boolean; + /** Content to display in the preview */ + children: React.ReactNode; +} + +/** + * A generalized expandable preview component for displaying content with a header and expandable body + */ +export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { + // Get toolbar visibility state from Redux if inputId and itemId are provided + const newestCodeblockForInputId = useAppSelector((store) => + props.inputId + ? store.session.newestToolbarPreviewForInput[props.inputId] + : undefined, + ); + + const calculatedInitiallyHidden = useMemo(() => { + // If initiallyHidden is explicitly set to false, always start visible + if (props.initiallyHidden === false) { + return false; + } + + // Otherwise, use the inputId/itemId logic + if (props.inputId && props.itemId) { + return newestCodeblockForInputId !== props.itemId; + } + return props.initiallyHidden ?? false; + }, [ + newestCodeblockForInputId, + props.inputId, + props.itemId, + props.initiallyHidden, + ]); + + const [hidden, setHidden] = useState(calculatedInitiallyHidden); + const [isExpanded, setIsExpanded] = useState(false); + + const contentRef = useRef(null); + const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); + + useEffect(() => { + // Only update hidden state from props if initiallyHidden isn't explicitly set to false + if (props.initiallyHidden !== false) { + setHidden(calculatedInitiallyHidden); + } + }, [calculatedInitiallyHidden, props.initiallyHidden]); + + useEffect(() => { + const resizeObserver = new ResizeObserver(() => { + setContentDims(prevValue => ({ + width: contentRef.current?.scrollWidth ?? prevValue.width, + height: contentRef.current?.scrollHeight ?? prevValue.height, + })); + }); + + if (contentRef.current) { + resizeObserver.observe(contentRef.current); + } + + return () => { + resizeObserver.disconnect(); + }; + }, [contentRef]); + + return ( + +
    { + setHidden(!hidden); + }} + > +
    { + e.stopPropagation(); + if (props.onTitleClick) { + props.onTitleClick(e); + } + }} + > + {props.icon} + {props.title} +
    +
    + + {hidden ? ( + + ) : ( + + )} + + {props.onDelete && ( + { + e.stopPropagation(); + props.onDelete?.(); + }} + > + + + )} +
    +
    + + {!hidden && ( + + MAX_PREVIEW_HEIGHT} + > + {props.children} + + + {contentDims.height > MAX_PREVIEW_HEIGHT && ( + + + setIsExpanded((v) => !v)} + /> + + + )} + + )} +
    + ); +} diff --git a/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx new file mode 100644 index 000000000..ac1a67836 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx @@ -0,0 +1,23 @@ +import { + NodeViewWrapper as TiptapNodeViewWrapper, + NodeViewWrapperProps as TiptapNodeViewWrapperProps, +} from "@tiptap/react"; +import React from "react"; + +interface NodeViewWrapperProps { + children: React.ReactNode; +} + +export const NodeViewWrapper: React.FC = ({ + children, +}) => { + // Not setting this as a "p" will cause issues with foreign keyboards + // See https://github.com/continuedev/continue/issues/3199 + const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p"; + + return ( + + {children} + + ); +}; diff --git a/gui/src/components/mainInput/tiptap/StyledComponents.ts b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts similarity index 95% rename from gui/src/components/mainInput/tiptap/StyledComponents.ts rename to gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts index 2aca4f1be..f994b53d6 100644 --- a/gui/src/components/mainInput/tiptap/StyledComponents.ts +++ b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts @@ -8,8 +8,8 @@ import { vscForeground, vscInputBackground, vscInputBorderFocus, -} from "../.."; -import { getFontSize } from "../../../util"; +} from "../../.."; +import { getFontSize } from "../../../../util"; export const InputBoxDiv = styled.div<{}>` resize: none; diff --git a/gui/src/components/mainInput/TipTapEditor/components/index.ts b/gui/src/components/mainInput/TipTapEditor/components/index.ts new file mode 100644 index 000000000..ddcf5dd94 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/index.ts @@ -0,0 +1,3 @@ +export * from "./DragOverlay"; +export * from "./ExpandableToolbarPreview"; +export * from "./StyledComponents"; diff --git a/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts similarity index 88% rename from gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts index f633c342b..87b524435 100644 --- a/gui/src/components/mainInput/tiptap/extensions/AddCodeToEditExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts @@ -1,25 +1,16 @@ import { mergeAttributes, Node } from "@tiptap/core"; -import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type MentionOptions = { - HTMLAttributes: Record; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; - -export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit"); +import Suggestion from "@tiptap/suggestion"; +import { MentionOptions } from "./types"; export const AddCodeToEdit = Node.create({ name: "add-code-to-edit", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "add-code-to-edit", + }, renderHTML({ options, node }) { return [ "span", @@ -29,7 +20,7 @@ export const AddCodeToEdit = Node.create({ }, suggestion: { char: "#", - pluginKey: AddCodeToEditPluginKey, + pluginKey: new PluginKey(this.name), allow: ({ state, range }) => { const $from = state.doc.resolve(range.from); const type = state.schema.nodes[this.name]; diff --git a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx similarity index 74% rename from gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx index aea6e18af..386593e28 100644 --- a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx @@ -1,9 +1,9 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeBlockComponent } from "../CodeBlockComponent"; +import { CodeBlockPreview } from "./CodeBlockPreview"; -export const CodeBlockExtension = Node.create({ - name: "codeBlock", +export const CodeBlock = Node.create({ + name: "code-block", group: "block", @@ -37,6 +37,6 @@ export const CodeBlockExtension = Node.create({ }, addNodeView() { - return ReactNodeViewRenderer(CodeBlockComponent); + return ReactNodeViewRenderer(CodeBlockPreview); }, }); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx new file mode 100644 index 000000000..c414d7f1c --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -0,0 +1,76 @@ +import { NodeViewProps } from "@tiptap/react"; +import { ContextItemWithId } from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; +import { dedent, getMarkdownLanguageTagForFile } from "core/util"; +import { useContext, useMemo } from "react"; +import { vscBadgeBackground } from "../../../.."; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import FileIcon from "../../../../FileIcon"; +import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; + +const backticksRegex = /`{3,}/gm; + +/** + * Component for displaying a code block in the TipTap editor + */ +export const CodeBlockPreview = ({ + node, + deleteNode, + selected, +}: NodeViewProps) => { + const item: ContextItemWithId = node.attrs.item; + const inputId = node.attrs.inputId; + const ideMessenger = useContext(IdeMessengerContext); + + const content = useMemo(() => { + return dedent`${item.content}`; + }, [item.content]); + + const fence = useMemo(() => { + const backticks = content.match(backticksRegex); + return backticks ? backticks.sort().at(-1) + "`" : "```"; + }, [content]); + + const handleTitleClick = (e: React.MouseEvent) => { + e.stopPropagation(); + + if (item.id.providerTitle === "file" && item.uri?.value) { + ideMessenger.post("showFile", { + filepath: item.uri.value, + }); + } else if (item.id.providerTitle === "code") { + const rif = ctxItemToRifWithContents(item, true); + ideMessenger.ide.showLines( + rif.filepath, + rif.range.start.line, + rif.range.end.line, + ); + } else { + ideMessenger.post("showVirtualFile", { + content: item.content, + name: item.name, + }); + } + }; + + return ( + + } + inputId={inputId} + itemId={item.id.itemId} + onDelete={() => deleteNode()} + borderColor={selected ? vscBadgeBackground : undefined} + onTitleClick={handleTitleClick} + > + + + + ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts new file mode 100644 index 000000000..ca111193d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts @@ -0,0 +1 @@ +export * from "./CodeBlock"; diff --git a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts index 364b241ee..bfd48b0f6 100644 --- a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts @@ -1,25 +1,17 @@ import { mergeAttributes, Node } from "@tiptap/core"; -import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type MentionOptions = { - HTMLAttributes: Record; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; - -export const MentionPluginKey = new PluginKey("mention"); +import Suggestion from "@tiptap/suggestion"; +import { MentionOptions } from "./types"; export const Mention = Node.create({ name: "mention", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "mention", + }, + renderHTML({ options, node }) { return [ "span", @@ -29,7 +21,7 @@ export const Mention = Node.create({ }, suggestion: { char: "@", - pluginKey: MentionPluginKey, + pluginKey: new PluginKey(this.name), command: ({ editor, range, props }) => { // increase range.to by one when the next node is of type "text" // and starts with a space character diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts new file mode 100644 index 000000000..b35a637ea --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts @@ -0,0 +1,130 @@ +import { mergeAttributes, Node } from "@tiptap/core"; +import { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { ReactNodeViewRenderer } from "@tiptap/react"; +import { ContextItemWithId, SlashCommandDescription } from "core"; +import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat"; +import { PromptBlockPreview } from "./PromptBlockPreview"; + +export interface PromptBlockOptions { + HTMLAttributes: Record; +} + +export interface PromptBlockAttributes { + item: ContextItemWithId; + inputId: string; +} + +declare module "@tiptap/core" { + interface Commands { + promptBlock: { + /** + * Insert a prompt block into the editor + */ + insertPrompt: (item: SlashCommandDescription) => ReturnType; + + /** + * Clear all prompt blocks from the editor + */ + clearPrompt: () => ReturnType; + }; + } +} + +/** + * Extension for adding prompt blocks to the TipTap editor + */ +export const PromptBlock = Node.create({ + name: "prompt-block", + group: "block", + content: "inline*", + + addOptions() { + return { + HTMLAttributes: { + class: "prompt-block", + }, + }; + }, + + addAttributes() { + return { + item: { + default: null, + }, + inputId: { + default: null, + }, + }; + }, + + parseHTML() { + return [ + { + tag: "prompt-block", + }, + ]; + }, + + renderHTML({ HTMLAttributes }) { + return ["prompt-block", mergeAttributes(HTMLAttributes), 0]; + }, + + addNodeView() { + return ReactNodeViewRenderer(PromptBlockPreview); + }, + + addCommands() { + return { + insertPrompt: + (prompt: SlashCommandDescription) => + ({ chain }) => { + const item: ContextItemWithId = { + content: prompt.prompt ?? "", + name: prompt.name, + description: prompt.description, + id: { + providerTitle: "prompt", + itemId: prompt.name, + }, + }; + + return chain() + .insertContentAt(0, { + type: this.name, + attrs: { + item, + inputId: MAIN_EDITOR_INPUT_ID, + }, + }) + .focus("end") + .run(); + }, + + // TODO: This could probably be greatly simplified with something along the lines of + // `editor.commands.deleteNode(this.name)`, but was unable to get it working + clearPrompt: + () => + ({ state, commands }) => { + // Find all prompt-block nodes in the document + const promptNodes: { pos: number; node: ProseMirrorNode }[] = []; + state.doc.descendants((node, pos) => { + if (node.type.name === this.name) { + promptNodes.push({ pos, node }); + return false; // Don't descend into this node + } + return true; + }); + + // Delete all found prompt blocks + // We process them in reverse order so that deleting one doesn't affect the position of others + for (let i = promptNodes.length - 1; i >= 0; i--) { + const { pos, node } = promptNodes[i]; + commands.deleteRange({ from: pos, to: pos + node.nodeSize }); + } + + // Return true if we deleted any nodes + return promptNodes.length > 0; + }, + }; + }, +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx new file mode 100644 index 000000000..8a1095d80 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -0,0 +1,51 @@ +import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; +import { NodeViewProps } from "@tiptap/react"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; +import { PromptBlockAttributes } from "./PromptBlock"; + +/** + * Component for prompt blocks in the Tiptap editor + */ +export const PromptBlockPreview = ({ + node, + selected, + editor, +}: NodeViewProps) => { + const { item, inputId } = node.attrs as PromptBlockAttributes; + + const ideMessenger = useContext(IdeMessengerContext); + + const handleTitleClick = (e: React.MouseEvent) => { + e.stopPropagation(); + ideMessenger.post("showVirtualFile", { + content: item.content, + name: item.name, + }); + }; + + const handleDelete = () => { + editor.commands.clearPrompt(); + }; + + return ( + + } + inputId={inputId} + itemId={item.id.itemId} + onDelete={handleDelete} + onTitleClick={handleTitleClick} + > +
    + {item.content} +
    +
    +
    + ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts new file mode 100644 index 000000000..3a72d7bd3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts @@ -0,0 +1 @@ +export * from "./PromptBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts new file mode 100644 index 000000000..892d80355 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts @@ -0,0 +1,58 @@ +// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) + +import { Node } from "@tiptap/core"; +import { PluginKey } from "@tiptap/pm/state"; +import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; +import { ComboBoxItem } from "../../types"; + +export type SlashCommandOptions = { + suggestion: Omit, "editor">; +}; + +export const SlashCommand = Node.create({ + name: "slash-command", + + addOptions() { + return { + suggestion: { + char: "/", + pluginKey: new PluginKey(this.name), + startOfLine: true, + command: ({ editor, range, props }) => { + // First delete the slash character and any text after it + editor.chain().focus().deleteRange(range).run(); + + editor.commands.insertPrompt({ + name: props.title, + description: props.description, + prompt: props.content, + }); + }, + }, + }; + }, + + group: "inline", + inline: true, + selectable: false, + atom: true, + + // We don't need attributes since we won't be rendering any node + addAttributes() { + return {}; + }, + + // No need to parse HTML since we're not rendering anything + parseHTML() { + return []; + }, + + addProseMirrorPlugins() { + return [ + Suggestion({ + editor: this.editor, + ...this.options.suggestion, + }), + ]; + }, +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts new file mode 100644 index 000000000..06426b9c3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -0,0 +1,5 @@ +export * from "./AddCodeToEdit"; +export * from "./CodeBlock"; +export * from "./Mention"; +export * from "./Prompt"; +export * from "./SlashCommand"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/types.ts b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts new file mode 100644 index 000000000..318b1062d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts @@ -0,0 +1,11 @@ +import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { SuggestionOptions } from "@tiptap/suggestion"; + +export type MentionOptions = { + HTMLAttributes: Record; + renderHTML: (props: { + options: MentionOptions; + node: ProseMirrorNode; + }) => DOMOutputSpec; + suggestion: Omit; +}; diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts new file mode 100644 index 000000000..b2d446398 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -0,0 +1,4 @@ +export * from "./extensions"; +export * from "./MainEditorProvider"; +export * from "./TipTapEditor"; +export * from "./utils"; diff --git a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts similarity index 68% rename from gui/src/components/mainInput/tiptap/useWebviewListeners.ts rename to gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 3a4694939..400f08019 100644 --- a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -1,43 +1,50 @@ -import { Editor } from "@tiptap/core"; +import { Editor } from "@tiptap/react"; import { InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { MutableRefObject } from "react"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { clearCodeToEdit, - setNewestCodeblocksForInput, + setNewestToolbarPreviewForInput, } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { TipTapEditorProps } from "./TipTapEditor"; +import { CodeBlock, PromptBlock } from "./extensions"; -export function useWebviewListeners(options: { +/** + * Hook for setting up main editor specific webview listeners + */ +export function useMainEditorWebviewListeners({ + editor, + onEnterRef, + dispatch, + historyLength, + inputId, + editorFocusedRef, +}: { editor: Editor | null; onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>; dispatch: AppDispatch; historyLength: number; - props: TipTapEditorProps; + inputId: string; editorFocusedRef: MutableRefObject; }) { - const { - editor, - onEnterRef, - dispatch, - historyLength, - props, - editorFocusedRef, - } = options; + useWebviewListener( + "isContinueInputFocused", + async () => { + return !!editorFocusedRef.current; + }, + [editorFocusedRef], + ); useWebviewListener( "userInput", async (data) => { - if (!props.isMainInput) { - return; - } - editor?.commands.insertContent(data.input); + if (!editor) return; + editor.commands.insertContent(data.input); onEnterRef.current({ useCodebase: false, noContext: true }); }, - [editor, onEnterRef.current, props.isMainInput], + [editor, onEnterRef.current], ); useWebviewListener("jetbrains/editorInsetRefresh", async () => { @@ -46,11 +53,7 @@ export function useWebviewListeners(options: { useWebviewListener( "focusContinueInput", - async (data) => { - if (!props.isMainInput) { - return; - } - + async () => { dispatch(clearCodeToEdit()); if (historyLength > 0) { @@ -61,52 +64,46 @@ export function useWebviewListeners(options: { }), ); } + setTimeout(() => { editor?.commands.blur(); editor?.commands.focus("end"); }, 20); }, - [historyLength, editor, props.isMainInput], + [historyLength, editor, dispatch], ); useWebviewListener( "focusContinueInputWithoutClear", async () => { - if (!props.isMainInput) { - return; - } setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "focusContinueInputWithNewSession", async () => { - if (!props.isMainInput) { - return; - } await dispatch( saveCurrentSession({ openNewSession: true, generateTitle: true, }), ); + setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor, dispatch], ); useWebviewListener( "highlightedCode", async (data) => { - if (!props.isMainInput || !editor) { - return; - } + if (!editor) return; const contextItem = rifWithContentsToContextItem( data.rangeInFileWithContents, @@ -114,31 +111,36 @@ export function useWebviewListeners(options: { let index = 0; for (const el of editor.getJSON()?.content ?? []) { + // Prevent exact duplicate code blocks if (el.attrs?.item?.name === contextItem.name) { - return; // Prevent exact duplicate code blocks + return; } - if (el.type === "codeBlock") { + + if (el.type === CodeBlock.name || el.type === PromptBlock.name) { index += 2; } else { break; } } + editor .chain() .insertContentAt(index, { - type: "codeBlock", + type: CodeBlock.name, attrs: { item: contextItem, - inputId: props.inputId, + inputId, }, }) .run(); + dispatch( - setNewestCodeblocksForInput({ - inputId: props.inputId, + setNewestToolbarPreviewForInput({ + inputId, contextItemId: contextItem.id.itemId, }), ); + if (data.prompt) { editor.commands.focus("end"); editor.commands.insertContent(data.prompt); @@ -153,52 +155,42 @@ export function useWebviewListeners(options: { editor.commands.focus("end"); }, 20); }, - [editor, props.isMainInput, historyLength, onEnterRef.current], + [editor, inputId, onEnterRef.current], ); useWebviewListener( "focusEdit", async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "focusEditWithoutClear", async () => { - if (!props.isMainInput) { - return; - } - setTimeout(() => { editor?.commands.focus("end"); }, 2000); }, - [editor, props.isMainInput], + [editor], ); useWebviewListener( "isContinueInputFocused", async () => { - return props.isMainInput && !!editorFocusedRef.current; + return !!editorFocusedRef.current; }, - [editorFocusedRef, props.isMainInput], - !props.isMainInput, + [editorFocusedRef], ); useWebviewListener( "focusContinueSessionId", async (data) => { - if (!props.isMainInput || !data.sessionId) { - return; - } + if (!data.sessionId) return; + await dispatch( loadSession({ sessionId: data.sessionId, @@ -206,6 +198,6 @@ export function useWebviewListeners(options: { }), ); }, - [props.isMainInput], + [], ); } diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts similarity index 82% rename from gui/src/components/mainInput/tiptap/editorConfig.ts rename to gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index d79981d39..9c56819e3 100644 --- a/gui/src/components/mainInput/tiptap/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -1,4 +1,4 @@ -import { Editor } from "@tiptap/core"; +import { Editor, JSONContent } from "@tiptap/core"; import Document from "@tiptap/extension-document"; import History from "@tiptap/extension-history"; import Image from "@tiptap/extension-image"; @@ -11,33 +11,29 @@ import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { usePostHog } from "posthog-js/react"; import { useRef } from "react"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders"; -import { useInputHistory } from "../../../hooks/useInputHistory"; -import useUpdatingRef from "../../../hooks/useUpdatingRef"; -import { useAppSelector } from "../../../redux/hooks"; -import { selectUseActiveFile } from "../../../redux/selectors"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + getContextProviderDropdownOptions, + getSlashCommandDropdownOptions, +} from "."; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders"; +import { useInputHistory } from "../../../../hooks/useInputHistory"; +import useUpdatingRef from "../../../../hooks/useUpdatingRef"; +import { useAppSelector } from "../../../../redux/hooks"; +import { selectUseActiveFile } from "../../../../redux/selectors"; +import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; import { addCodeToEdit, selectHasCodeToEdit, selectIsInEditMode, -} from "../../../redux/slices/sessionSlice"; -import { AppDispatch } from "../../../redux/store"; -import { exitEditMode } from "../../../redux/thunks"; -import { loadLastSession } from "../../../redux/thunks/session"; -import { getFontSize } from "../../../util"; -import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension"; -import { CodeBlockExtension } from "./extensions/CodeBlockExtension"; -import { SlashCommand } from "./extensions/CommandsExtension"; -import { MockExtension } from "./extensions/FillerExtension"; -import { Mention } from "./extensions/MentionExtension"; -import { - getContextProviderDropdownOptions, - getSlashCommandDropdownOptions, -} from "./getSuggestion"; +} from "../../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../../redux/store"; +import { exitEditMode } from "../../../../redux/thunks"; +import { loadLastSession } from "../../../../redux/thunks/session"; +import { getFontSize } from "../../../../util"; +import * as ContinueExtensions from "../extensions"; +import { TipTapEditorProps } from "../TipTapEditor"; import { handleImageFile } from "./imageUtils"; -import { TipTapEditorProps } from "./TipTapEditor"; export function getPlaceholderText( placeholder: TipTapEditorProps["placeholder"], @@ -52,6 +48,28 @@ export function getPlaceholderText( : "Ask a follow-up"; } +/** + * Checks if the editor content is valid for submission. + * A valid submission can contain either text content or prompt/code blocks + * + * @param json The editor JSON content + * @returns true if the content is valid for submission, false otherwise + */ +export function hasValidEditorContent(json: JSONContent): boolean { + // Check for prompt or code blocks + const hasPromptOrCodeBlock = json.content?.some( + (c) => + c.type === ContinueExtensions.PromptBlock.name || + c.type === ContinueExtensions.CodeBlock.name, + ); + + // Check for text content + const hasTextContent = json.content?.some((c) => c.content); + + // Content is valid if it has either text or special blocks + return hasTextContent || hasPromptOrCodeBlock || false; +} + /** * This function is called only once, so we need to use refs to pass in the latest values */ @@ -64,18 +82,15 @@ export function createEditorConfig(options: { const posthog = usePostHog(); - // #region Selectors const { getSubmenuContextItems } = useSubmenuContextProviders(); - const defaultModel = useAppSelector(selectDefaultModel); + const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const useActiveFile = useAppSelector(selectUseActiveFile); const historyLength = useAppSelector((store) => store.session.history.length); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - // #endregion - // #region Refs const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); const defaultModelRef = useUpdatingRef(defaultModel); @@ -91,8 +106,6 @@ export function createEditorConfig(options: { ); const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); - // #endregion - const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); @@ -295,10 +308,7 @@ export function createEditorConfig(options: { }, }), Text, - Mention.configure({ - HTMLAttributes: { - class: "mention", - }, + ContinueExtensions.Mention.configure({ suggestion: getContextProviderDropdownOptions( availableContextProvidersRef, getSubmenuContextItemsRef, @@ -308,15 +318,8 @@ export function createEditorConfig(options: { inSubmenuRef, ideMessenger, ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, }), - - AddCodeToEdit.configure({ - HTMLAttributes: { - class: "add-code-to-edit", - }, + ContinueExtensions.AddCodeToEdit.configure({ suggestion: { ...getContextProviderDropdownOptions( availableContextProvidersRef, @@ -352,27 +355,22 @@ export function createEditorConfig(options: { }, }, }), - props.availableSlashCommands.length - ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) - : MockExtension, - CodeBlockExtension, + ContinueExtensions.SlashCommand.configure({ + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + dispatch, + props.inputId, + ), + }), + ContinueExtensions.PromptBlock, + ContinueExtensions.CodeBlock, ], editorProps: { attributes: { - class: "outline-none -mt-1 overflow-hidden", + class: "outline-none overflow-hidden", style: `font-size: ${getFontSize()}px;`, }, }, @@ -391,8 +389,8 @@ export function createEditorConfig(options: { const json = editor.getJSON(); - // Don't do anything if input box is empty - if (!json.content?.some((c) => c.content)) { + // Don't do anything if input box doesn't have valid content + if (!hasValidEditorContent(json)) { return; } diff --git a/gui/src/components/mainInput/tiptap/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts similarity index 91% rename from gui/src/components/mainInput/tiptap/getSuggestion.ts rename to gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index 264258dd5..8c0613a4a 100644 --- a/gui/src/components/mainInput/tiptap/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -6,10 +6,12 @@ import { } from "core"; import { MutableRefObject } from "react"; import tippy from "tippy.js"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import AtMentionDropdown from "../AtMentionDropdown"; -import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types"; -import { TIPPY_DIV_ID } from "./TipTapEditor"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { AppDispatch } from "../../../../redux/store"; +import AtMentionDropdown from "../../AtMentionDropdown"; +import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; +import { TIPPY_DIV_ID } from "../TipTapEditor"; +import { SlashCommand } from "../extensions"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -196,6 +198,8 @@ export function getSlashCommandDropdownOptions( onClose: () => void, onOpen: () => void, ideMessenger: IIdeMessenger, + dispatch: AppDispatch, + inputId: string, ) { const items = async ({ query }: { query: string }) => { const options = [...availableSlashCommandsRef.current]; @@ -203,7 +207,7 @@ export function getSlashCommandDropdownOptions( const filteredCommands = query.length > 0 ? options.filter((slashCommand) => { - const sc = slashCommand.title.substring(1).toLowerCase(); + const sc = slashCommand.title.toLowerCase(); const iv = query.toLowerCase(); return sc.startsWith(iv); }) @@ -215,11 +219,12 @@ export function getSlashCommandDropdownOptions( id: provider.title, title: provider.title, label: provider.title, - type: (provider.type ?? "slashCommand") as ComboBoxItemType, + type: (provider.type ?? SlashCommand.name) as ComboBoxItemType, + content: provider.content, action: provider.action, })); - if (query.length === 0 && commandItems.length > 0) { + if (query.length === 0 && commandItems.length === 0) { commandItems.push({ title: "Explore prompts", type: "action", @@ -232,6 +237,7 @@ export function getSlashCommandDropdownOptions( name: "", id: "", label: "", + content: "", }); } diff --git a/gui/src/components/mainInput/tiptap/imageUtils.ts b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts similarity index 96% rename from gui/src/components/mainInput/tiptap/imageUtils.ts rename to gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts index 0803e5ab8..23de2dda1 100644 --- a/gui/src/components/mainInput/tiptap/imageUtils.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts @@ -1,4 +1,4 @@ -import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; const IMAGE_RESOLUTION = 1024; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/index.ts b/gui/src/components/mainInput/TipTapEditor/utils/index.ts new file mode 100644 index 000000000..5ce05a866 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/index.ts @@ -0,0 +1,5 @@ +export * from "./editorConfig"; +export * from "./getSuggestion"; +export * from "./imageUtils"; +export * from "./keyHandlers"; +export * from "./resolveEditorContent"; diff --git a/gui/src/components/mainInput/tiptap/keyHandlers.ts b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/keyHandlers.ts rename to gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts index c25a53271..a102ba2f0 100644 --- a/gui/src/components/mainInput/tiptap/keyHandlers.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts @@ -1,20 +1,18 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; -import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util"; import { handleJetBrainsOSRMetaKeyIssues, handleVSCMetaKeyIssues, -} from "../util/handleMetaKeyIssues"; +} from "../../util/handleMetaKeyIssues"; export function useEditorEventHandlers(options: { editor: Editor | null; isOSREnabled: boolean; editorFocusedRef: React.MutableRefObject; - isInEditMode: boolean; setActiveKey: (key: string | null) => void; }) { - const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } = - options; + const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options; /** * This handles various issues with meta key actions diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts new file mode 100644 index 000000000..ad7858a0a --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -0,0 +1,339 @@ +import { Dispatch } from "@reduxjs/toolkit"; +import Image from "@tiptap/extension-image"; +import { Paragraph } from "@tiptap/extension-paragraph"; +import { Text } from "@tiptap/extension-text"; +import { JSONContent } from "@tiptap/react"; +import { + ContextItemWithId, + DefaultContextProvider, + InputModifiers, + MessageContent, + MessagePart, + RangeInFile, + SlashCommandDescription, + TextMessagePart, +} from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; +import { renderChatMessage, stripImages } from "core/util/messageContent"; +import { getUriFileExtension } from "core/util/uri"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; +import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; +import { CodeBlock, Mention, PromptBlock } from "../extensions"; + +interface MentionAttrs { + label: string; + id: string; + itemType?: string; + query?: string; +} + +interface ResolveEditorContentInput { + editorState: JSONContent; + modifiers: InputModifiers; + ideMessenger: IIdeMessenger; + defaultContextProviders: DefaultContextProvider[]; + availableSlashCommands: SlashCommandDescription[]; + selectedModelTitle: string; + dispatch: Dispatch; +} + +type ResolveEditorContentOutput = [ + ContextItemWithId[], + RangeInFile[], + MessageContent, + ( + | { + command: SlashCommandDescription; + input: string; + } + | undefined + ), +]; + +/** + * This function converts the input from the editor to a string, resolving any context items + * Context items are appended to the top of the prompt and then referenced within the input + */ +export async function resolveEditorContent({ + editorState, + modifiers, + ideMessenger, + defaultContextProviders, + availableSlashCommands, + selectedModelTitle, + dispatch, +}: ResolveEditorContentInput): Promise { + const { parts, contextItemAttrs, selectedCode, slashCommandName } = + processEditorContent(editorState); + + const slashCommandWithInput = processSlashCommand( + slashCommandName, + availableSlashCommands, + parts, + ); + + const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput; + if (shouldGatherContext) { + dispatch(setIsGatheringContext(true)); + } + + const contextItems = await gatherContextItems({ + contextItemAttrs, + modifiers, + ideMessenger, + defaultContextProviders, + parts, + selectedCode, + selectedModelTitle, + }); + + if (shouldGatherContext) { + dispatch(setIsGatheringContext(false)); + } + + return [contextItems, selectedCode, parts, slashCommandWithInput]; +} + +/** + * Processes editor content and extracts parts, context items, code, and slash commands + */ +function processEditorContent(editorState: JSONContent) { + const contextItemAttrs: MentionAttrs[] = []; + const selectedCode: RangeInFile[] = []; + let slashCommandName: string | undefined; + + const parts = (editorState?.content || []).reduce( + (parts, p) => { + switch (p.type) { + case PromptBlock.name: { + slashCommandName = resvolePromptBlock(p); + } + + case Paragraph.name: { + const [text, ctxItems] = resolveParagraph(p); + + contextItemAttrs.push(...ctxItems); + + if (!text) return parts; + + // Merge with previous text part if possible + if (parts[parts.length - 1]?.type === "text") { + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; + return parts; + } + + return [...parts, { type: "text", text }]; + } + + case CodeBlock.name: { + if (!p.attrs?.item) { + console.warn("codeBlock has no item attribute"); + return parts; + } + + const contextItem = p.attrs.item as ContextItemWithId; + const rif = ctxItemToRifWithContents(contextItem, true); + selectedCode.push(rif); + + // If editing, only include in selectedCode + if (contextItem.editing) { + return parts; + } + + const fileExtension = getUriFileExtension(rif.filepath); + const codeText = [ + "\n\n```", + fileExtension, + " ", + contextItem.description, + "\n", + contextItem.content, + "\n```", + ].join(""); + + if (parts[parts.length - 1]?.type === "text") { + (parts[parts.length - 1] as TextMessagePart).text += + "\n" + codeText; + return parts; + } + + return [...parts, { type: "text", text: codeText }]; + } + + case Image.name: { + return [ + ...parts, + { + type: "imageUrl", + imageUrl: { url: p.attrs?.src }, + }, + ]; + } + + default: { + console.warn("Unexpected content type", p.type); + return parts; + } + } + }, + [], + ); + + return { parts, contextItemAttrs, selectedCode, slashCommandName }; +} + +/** + * Processes slash commands and prepares the command with input + */ +function processSlashCommand( + slashCommandName: string | undefined, + availableSlashCommands: SlashCommandDescription[], + parts: MessagePart[], +): { command: SlashCommandDescription; input: string } | undefined { + if (!slashCommandName) return; + + const command = availableSlashCommands.find( + (c) => c.name === slashCommandName, + ); + + if (!command) return; + + const lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); + const lastTextPart = parts[lastTextIndex] as TextMessagePart; + + let input: string; + + /** + * Although we no longer render slash command tags from the editor, + * we are inserting a slash command style text back into the text here. + * This is a a hack, but there's a number of assumptions in `core` that there + * is slash command text at the beginning of the text in order to process slash commands. + */ + if (lastTextPart) { + input = renderChatMessage({ + role: "user", + content: lastTextPart.text, + }).trimStart(); + lastTextPart.text = `/${command.name} ${lastTextPart.text}`; + } else { + input = ""; + parts.push({ type: "text", text: `/${command.name}` }); + } + + return { + command, + input, + }; +} + +/** + * Gathers context items from various sources + */ +async function gatherContextItems({ + contextItemAttrs, + modifiers, + ideMessenger, + defaultContextProviders, + parts, + selectedCode, + selectedModelTitle, +}: { + contextItemAttrs: MentionAttrs[]; + modifiers: InputModifiers; + ideMessenger: IIdeMessenger; + defaultContextProviders: DefaultContextProvider[]; + parts: MessagePart[]; + selectedCode: RangeInFile[]; + selectedModelTitle: string; +}): Promise { + let contextItems: ContextItemWithId[] = []; + + // Process context item attributes + for (const item of contextItemAttrs) { + const result = await ideMessenger.request("context/getContextItems", { + name: item.itemType === "contextProvider" ? item.id : item.itemType!, + query: item.query ?? "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + if (result.status === "success") { + contextItems.push(...result.content); + } + } + + // cmd+enter to use codebase + if (modifiers.useCodebase) { + const result = await ideMessenger.request("context/getContextItems", { + name: "codebase", + query: "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + + if (result.status === "success") { + contextItems.push(...result.content); + } + } + + // Include default context providers + const defaultContextItems = await Promise.all( + defaultContextProviders.map(async (provider) => { + const result = await ideMessenger.request("context/getContextItems", { + name: provider.name, + query: provider.query ?? "", + fullInput: stripImages(parts), + selectedCode, + selectedModelTitle, + }); + if (result.status === "success") { + return result.content; + } else { + return []; + } + }), + ); + contextItems.push(...defaultContextItems.flat()); + + return contextItems; +} + +function findLastIndex( + array: T[], + predicate: (value: T, index: number, obj: T[]) => boolean, +): number { + for (let i = array.length - 1; i >= 0; i--) { + if (predicate(array[i], i, array)) { + return i; + } + } + return -1; // if no element satisfies the predicate +} + +function resvolePromptBlock(p: JSONContent): string | undefined { + return p.attrs?.item.name; +} + +function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] { + const contextItems: MentionAttrs[] = []; + + const text = (p.content || []) + .map((child) => { + switch (child.type) { + case Text.name: + return child.text; + case Mention.name: + contextItems.push(child.attrs as MentionAttrs); + return child.attrs?.renderInlineAs ?? child.attrs?.label; + + default: + console.warn("Unexpected child type", child.type); + return ""; + } + }) + .join("") + .trimStart(); + + return [text, contextItems]; +} diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index eb63e0ee9..bb153f62a 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -42,7 +42,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { const isRangeInFile = name.includes(" (") && name.endsWith(")"); if (isRangeInFile) { - const rif = ctxItemToRifWithContents(contextItem); + const rif = ctxItemToRifWithContents(contextItem, true); ideMessenger.ide.showLines( rif.filepath, rif.range.start.line, diff --git a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx deleted file mode 100644 index e63e273ad..000000000 --- a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; -import { ContextItemWithId } from "core"; -import { vscBadgeBackground } from "../.."; -import CodeSnippetPreview from "../../markdown/CodeSnippetPreview"; - -export const CodeBlockComponent = (props: any) => { - const { node, deleteNode, selected, editor, updateAttributes } = props; - const item: ContextItemWithId = node.attrs.item; - const inputId = node.attrs.inputId; - // const contextItems = useSelector( - // (store: RootState) => - // store.session.messages[store.session.messages.length - 1].contextItems, - // ); - // const isFirstContextItem = item.id === contextItems[0]?.id; - const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now - - // Not setting this as a "p" will cause issues with foreign keyboards - // See https://github.com/continuedev/continue/issues/3199 - const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p"; - - return ( - - { - deleteNode(); - }} - /> - - ); -}; diff --git a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts b/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts deleted file mode 100644 index 0c25d7cca..000000000 --- a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts +++ /dev/null @@ -1,178 +0,0 @@ -// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) - -import { mergeAttributes, Node } from "@tiptap/core"; -import { Node as ProseMirrorNode } from "@tiptap/pm/model"; -import { PluginKey } from "@tiptap/pm/state"; -import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; - -export type SlashCommandOptions = { - HTMLAttributes: Record; - renderText: (props: { - options: SlashCommandOptions; - node: ProseMirrorNode; - }) => string; - suggestion: Omit; -}; - -export const SlashCommandPluginKey = new PluginKey("slashcommand"); - -export const SlashCommand = Node.create({ - name: "slashcommand", - - addOptions() { - return { - HTMLAttributes: {}, - renderText({ options, node }) { - return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`; - }, - suggestion: { - char: "/", - pluginKey: SlashCommandPluginKey, - startOfLine: true, - command: ({ editor, range, props }) => { - // increase range.to by one when the next node is of type "text" - // and starts with a space character - const nodeAfter = editor.view.state.selection.$to.nodeAfter; - const overrideSpace = nodeAfter?.text?.startsWith(" "); - - if (overrideSpace) { - range.to += 1; - } - - editor - .chain() - .focus() - .insertContentAt(range, [ - { - type: this.name, - attrs: props, - }, - { - type: "text", - text: " ", - }, - ]) - .run(); - - window.getSelection()?.collapseToEnd(); - }, - allow: ({ state, range }) => { - const $from = state.doc.resolve(range.from); - const type = state.schema.nodes[this.name]; - const allow = !!$from.parent.type.contentMatch.matchType(type); - - return allow; - }, - }, - }; - }, - - group: "inline", - - inline: true, - - selectable: false, - - atom: true, - - addAttributes() { - return { - id: { - default: null, - parseHTML: (element) => element.getAttribute("data-id"), - renderHTML: (attributes) => { - if (!attributes.id) { - return {}; - } - - return { - "data-id": attributes.id, - }; - }, - }, - - label: { - default: null, - parseHTML: (element) => element.getAttribute("data-label"), - renderHTML: (attributes) => { - if (!attributes.label) { - return {}; - } - - return { - "data-label": attributes.label, - }; - }, - }, - }; - }, - - parseHTML() { - return [ - { - tag: `span[data-type="${this.name}"]`, - }, - ]; - }, - - renderHTML({ node, HTMLAttributes }) { - return [ - "span", - mergeAttributes( - { "data-type": this.name }, - this.options.HTMLAttributes, - HTMLAttributes, - ), - this.options.renderText({ - options: this.options, - node, - }), - ]; - }, - - renderText({ node }) { - return this.options.renderText({ - options: this.options, - node, - }); - }, - - addKeyboardShortcuts() { - return { - Backspace: () => - this.editor.commands.command(({ tr, state }) => { - let isSlashCommand = false; - const { selection } = state; - const { empty, anchor } = selection; - - if (!empty) { - return false; - } - - state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { - if (node.type.name === this.name) { - isSlashCommand = true; - tr.insertText( - this.options.suggestion.char || "", - pos, - pos + node.nodeSize, - ); - - return false; - } - }); - - return isSlashCommand; - }), - }; - }, - - addProseMirrorPlugins() { - return [ - Suggestion({ - editor: this.editor, - ...this.options.suggestion, - }), - ]; - }, -}); diff --git a/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx b/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx deleted file mode 100644 index 9b8baac86..000000000 --- a/gui/src/components/mainInput/tiptap/extensions/FillerExtension.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { Node } from "@tiptap/core"; - -export const MockExtension = Node.create({ - name: "mockExtension", - - addOptions() { - return { - enabled: false, - }; - }, - addCommands() { - return {}; - }, - addKeyboardShortcuts() { - return {}; - }, - addProseMirrorPlugins() { - return []; - }, -}); diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts deleted file mode 100644 index d9eb47b6c..000000000 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { JSONContent } from "@tiptap/react"; -import { - ContextItemWithId, - DefaultContextProvider, - InputModifiers, - MessageContent, - MessagePart, - RangeInFile, - TextMessagePart, -} from "core"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import { stripImages } from "core/util/messageContent"; -import { getUriFileExtension } from "core/util/uri"; -import { IIdeMessenger } from "../../../context/IdeMessenger"; -import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; - -interface MentionAttrs { - label: string; - id: string; - itemType?: string; - query?: string; -} - -interface ResolveEditorContentInput { - editorState: JSONContent; - modifiers: InputModifiers; - ideMessenger: IIdeMessenger; - defaultContextProviders: DefaultContextProvider[]; - selectedModelTitle: string; - dispatch: Dispatch; -} - -/** - * This function converts the input from the editor to a string, resolving any context items - * Context items are appended to the top of the prompt and then referenced within the input - */ -async function resolveEditorContent({ - editorState, - modifiers, - ideMessenger, - defaultContextProviders, - selectedModelTitle, - dispatch, -}: ResolveEditorContentInput): Promise< - [ContextItemWithId[], RangeInFile[], MessageContent] -> { - let parts: MessagePart[] = []; - let contextItemAttrs: MentionAttrs[] = []; - const selectedCode: RangeInFile[] = []; - let slashCommand: string | undefined = undefined; - if (editorState?.content) { - for (const p of editorState.content) { - if (p.type === "paragraph") { - const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - // Only take the first slash command\ - if (foundSlashCommand && typeof slashCommand === "undefined") { - slashCommand = foundSlashCommand; - } - - contextItemAttrs.push(...ctxItems); - - if (text === "") { - continue; - } - - if (parts[parts.length - 1]?.type === "text") { - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; - } else { - parts.push({ type: "text", text }); - } - } else if (p.type === "codeBlock") { - if (p.attrs?.item) { - const contextItem = p.attrs.item as ContextItemWithId; - const rif = ctxItemToRifWithContents(contextItem, true); - // If not editing, include codeblocks in the prompt - // If editing is handled by selectedCode below - if (!contextItem.editing) { - const fileExtension = getUriFileExtension(rif.filepath); - // let extName = relativeFilepath.split(".").slice(-1)[0]; - const text = - "\n\n" + - "```" + - fileExtension + - " " + - contextItem.description + - "\n" + - contextItem.content + - "\n```"; - if (parts[parts.length - 1]?.type === "text") { - (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; - } else { - parts.push({ - type: "text", - text, - }); - } - } - selectedCode.push(rif); - } else { - console.warn("codeBlock has no item attribute"); - } - } else if (p.type === "image") { - parts.push({ - type: "imageUrl", - imageUrl: { - url: p.attrs?.src, - }, - }); - } else { - console.warn("Unexpected content type", p.type); - } - } - } - - const shouldGatherContext = modifiers.useCodebase || slashCommand; - if (shouldGatherContext) { - dispatch(setIsGatheringContext(true)); - } - - let contextItemsText = ""; - let contextItems: ContextItemWithId[] = []; - for (const item of contextItemAttrs) { - const result = await ideMessenger.request("context/getContextItems", { - name: item.itemType === "contextProvider" ? item.id : item.itemType!, - query: item.query ?? "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - if (result.status === "success") { - const resolvedItems = result.content; - contextItems.push(...resolvedItems); - for (const resolvedItem of resolvedItems) { - contextItemsText += resolvedItem.content + "\n\n"; - } - } - } - - // cmd+enter to use codebase - if (modifiers.useCodebase) { - const result = await ideMessenger.request("context/getContextItems", { - name: "codebase", - query: "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - - if (result.status === "success") { - const codebaseItems = result.content; - contextItems.push(...codebaseItems); - for (const codebaseItem of codebaseItems) { - contextItemsText += codebaseItem.content + "\n\n"; - } - } - } - - // Include default context providers - const defaultContextItems = await Promise.all( - defaultContextProviders.map(async (provider) => { - const result = await ideMessenger.request("context/getContextItems", { - name: provider.name, - query: provider.query ?? "", - fullInput: stripImages(parts), - selectedCode, - selectedModelTitle, - }); - if (result.status === "success") { - return result.content; - } else { - return []; - } - }), - ); - contextItems.push(...defaultContextItems.flat()); - - if (contextItemsText !== "") { - contextItemsText += "\n"; - } - - if (slashCommand) { - let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); - const lastTextPart = parts[lastTextIndex] as TextMessagePart; - const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`; - if (parts.length > 0) { - lastTextPart.text = lastPart; - } else { - parts = [{ type: "text", text: lastPart }]; - } - } - if (shouldGatherContext) { - dispatch(setIsGatheringContext(false)); - } - - return [contextItems, selectedCode, parts]; -} - -function findLastIndex( - array: T[], - predicate: (value: T, index: number, obj: T[]) => boolean, -): number { - for (let i = array.length - 1; i >= 0; i--) { - if (predicate(array[i], i, array)) { - return i; - } - } - return -1; // if no element satisfies the predicate -} - -function resolveParagraph( - p: JSONContent, -): [string, MentionAttrs[], string | undefined] { - let text = ""; - const contextItems: MentionAttrs[] = []; - let slashCommand: string | undefined = undefined; - for (const child of p.content || []) { - if (child.type === "text") { - text += text === "" ? child.text?.trimStart() : child.text; - } else if (child.type === "mention") { - text += - typeof child.attrs?.renderInlineAs === "string" - ? child.attrs.renderInlineAs - : child.attrs?.label; - contextItems.push(child.attrs as MentionAttrs); - } else if (child.type === "slashcommand") { - if (typeof slashCommand === "undefined") { - slashCommand = child.attrs?.id; - } else { - text += child.attrs?.label; - } - } else { - console.warn("Unexpected child type", child.type); - } - } - return [text, contextItems, slashCommand]; -} - -export function hasSlashCommandOrContextProvider( - editorState: JSONContent, -): boolean { - if (!editorState?.content) { - return false; - } - - for (const p of editorState.content) { - if (p.type === "paragraph" && p.content) { - for (const child of p.content) { - if (child.type === "slashcommand") { - return true; - } - if ( - child.type === "mention" && - child.attrs?.itemType === "contextProvider" - ) { - return true; - } - } - } - } - - return false; -} - -export default resolveEditorContent; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 9f9078303..bc45d19f1 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,6 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; +import { CodeBlock } from "../TipTapEditor"; const isWebEnv = isWebEnvironment(); @@ -103,7 +104,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => { for (let i = doc.content.childCount - 1; i >= 0; i--) { const node = doc.content.child(i); - if (node.type.name === "codeBlock") { + if (node.type.name === CodeBlock.name) { continue; } diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx deleted file mode 100644 index 06717c5ee..000000000 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import { - ChevronDownIcon, - EyeSlashIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { ContextItemWithId } from "core"; -import { dedent, getMarkdownLanguageTagForFile } from "core/util"; -import { useContext, useEffect, useMemo, useRef, useState } from "react"; -import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { getFontSize } from "../../util"; -import FileIcon from "../FileIcon"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import StyledMarkdownPreview from "./StyledMarkdownPreview"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import { EyeIcon } from "@heroicons/react/24/solid"; -import { useAppSelector } from "../../redux/hooks"; - -const PreviewMarkdownDiv = styled.div<{ - borderColor?: string; -}>` - background-color: ${vscEditorBackground}; - border-radius: ${defaultBorderRadius}; - border: 0.5px solid ${(props) => props.borderColor || lightGray}; - margin-top: 4px; - margin-bottom: 4px; - overflow: hidden; - position: relative; - - & div { - background-color: ${vscEditorBackground}; - } -`; - -interface CodeSnippetPreviewProps { - item: ContextItemWithId; - onDelete?: () => void; - borderColor?: string; - inputId: string; -} - -const MAX_PREVIEW_HEIGHT = 100; - -const backticksRegex = /`{3,}/gm; - -function CodeSnippetPreview(props: CodeSnippetPreviewProps) { - const ideMessenger = useContext(IdeMessengerContext); - - const [localHidden, setLocalHidden] = useState(); - const [isSizeLimited, setIsSizeLimited] = useState(true); - - const newestCodeblockForInputId = useAppSelector( - (store) => store.session.newestCodeblockForInput[props.inputId], - ); - - const hidden = useMemo(() => { - return localHidden ?? newestCodeblockForInputId !== props.item.id.itemId; - }, [localHidden, newestCodeblockForInputId, props.item]); - - const content = useMemo(() => { - return dedent`${props.item.content}`; - }, [props.item.content]); - - const fence = useMemo(() => { - const backticks = content.match(backticksRegex); - return backticks ? backticks.sort().at(-1) + "`" : "```"; - }, [content]); - - const codeBlockRef = useRef(null); - - const [codeblockDims, setCodeblockDims] = useState({ width: 0, height: 0 }); - useEffect(() => { - const resizeObserver = new ResizeObserver(() => { - setCodeblockDims({ - width: codeBlockRef.current?.scrollWidth ?? 0, - height: codeBlockRef.current?.scrollHeight ?? 0, - }); - }); - - if (codeBlockRef.current) { - resizeObserver.observe(codeBlockRef.current); - } - - return () => { - resizeObserver.disconnect(); - }; - }, [codeBlockRef]); - - return ( - -
    { - setLocalHidden(!hidden); - }} - > -
    { - e.stopPropagation(); - if ( - props.item.id.providerTitle === "file" && - props.item.uri?.value - ) { - ideMessenger.post("showFile", { - filepath: props.item.uri.value, - }); - } else if (props.item.id.providerTitle === "code") { - const rif = ctxItemToRifWithContents(props.item, true); - ideMessenger.ide.showLines( - rif.filepath, - rif.range.start.line, - rif.range.end.line, - ); - } else { - ideMessenger.post("showVirtualFile", { - content, - name: props.item.name, - }); - } - }} - > - - {props.item.name} -
    -
    - - {hidden ? ( - - ) : ( - - )} - - { - e.stopPropagation(); - props.onDelete?.(); - }} - > - - -
    -
    -
    - -
    - - {codeblockDims.height > MAX_PREVIEW_HEIGHT && ( - - setIsSizeLimited((v) => !v)} - /> - - )} -
    - ); -} - -export default CodeSnippetPreview; diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx deleted file mode 100644 index 85ece0990..000000000 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { - ArrowLeftEndOnRectangleIcon, - CommandLineIcon, - PlayIcon, -} from "@heroicons/react/24/outline"; -import { useContext, useRef, useState } from "react"; -import { v4 as uuidv4 } from "uuid"; -import { - defaultBorderRadius, - vscCommandCenterInactiveBorder, - vscEditorBackground, -} from ".."; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - selectUIConfig, -} from "../../redux/slices/configSlice"; -import { isJetBrains } from "../../util"; -import { CopyIconButton } from "../gui/CopyIconButton"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { getTerminalCommand, isTerminalCodeBlock } from "./utils"; - -interface StepContainerPreActionButtonsProps { - language: string | null; - codeBlockContent: string; - codeBlockIndex: number; - children: any; -} - -export default function StepContainerPreActionButtons({ - language, - codeBlockContent, - codeBlockIndex, - children, -}: StepContainerPreActionButtonsProps) { - const [hovering, setHovering] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const uiConfig = useAppSelector(selectUIConfig); - const streamIdRef = useRef(null); - const nextCodeBlockIndex = useAppSelector( - (state) => state.session.codeBlockApplyStates.curIndex, - ); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isBottomToolbarPosition = - uiConfig?.codeBlockToolbarPosition == "bottom"; - - const toolTipPlacement = isBottomToolbarPosition ? "top" : "bottom"; - - const shouldRunTerminalCmd = - !isJetBrains() && isTerminalCodeBlock(language, codeBlockContent); - const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; - - if (streamIdRef.current === null) { - streamIdRef.current = uuidv4(); - } - - const defaultModel = useAppSelector(selectDefaultModel); - - function onClickApply() { - if (!defaultModel || !streamIdRef.current) { - return; - } - ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, - text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, - }); - } - - async function onClickRunTerminal(): Promise { - if (shouldRunTerminalCmd) { - return ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent)); - } - } - - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - - return ( -
    setHovering(true)} - onMouseLeave={() => setHovering(false)} - className="bg-vsc-editor-background relative my-2.5" - style={{ - border: `1px solid ${vscCommandCenterInactiveBorder}`, - borderRadius: defaultBorderRadius, - }} - > -
    {children}
    - {hovering && !isStreaming && ( -
    - {shouldRunTerminalCmd && ( - - - - )} - - - - - ideMessenger.post("insertAtCursor", { text: codeBlockContent }) - } - tooltipPlacement={toolTipPlacement} - > - - - -
    - )} -
    - ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 71e7ca9cf..6a775c16b 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { + disableManualApply?: boolean; applyState?: ApplyState; onClickAccept: () => void; onClickReject: () => void; @@ -36,12 +37,12 @@ export default function ApplyActions(props: ApplyActionsProps) { const applyButton = (text: string) => ( @@ -51,33 +52,35 @@ export default function ApplyActions(props: ApplyActionsProps) { case "streaming": return (
    - - Applying changes + + Applying
    ); case "done": return ( -
    - +
    + {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} {` remaining`} - - - +
    + + + - - - + + + +
    ); case "closed": @@ -86,14 +89,19 @@ export default function ApplyActions(props: ApplyActionsProps) { return ( Applied - + ); } - + if (props.disableManualApply) { + return null; + } return applyButton("Reapply"); } default: + if (props.disableManualApply) { + return null; + } return applyButton("Apply"); } } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx index 195615380..2167afc41 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/CopyButton.tsx @@ -1,6 +1,6 @@ import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; +import { lightGray } from "../.."; import useCopy from "../../../hooks/useCopy"; -import { lightGray, vscForeground } from "../.."; interface CopyButtonProps { text: string; @@ -11,23 +11,17 @@ export default function CopyButton({ text }: CopyButtonProps) { return (
    {copied ? ( - <> - - Copied - + ) : ( - <> - - Copy - + )}
    diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c2f09a24a..7b204190b 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -1,41 +1,25 @@ +import { getLastNPathParts } from "core/util/uri"; import FileIcon from "../../FileIcon"; -import { useContext } from "react"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; export interface FileInfoProps { - relativeFilepath: string; + filepath: string; + onClick: () => void; range?: string; } -const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { - const ideMessenger = useContext(IdeMessengerContext); - - async function onClickFileName() { - const fileUri = await inferResolvedUriFromRelativePath( - relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("showFile", { - filepath: fileUri, - }); - } - +export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { return ( -
    -
    - - - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} - +
    +
    +
    + + {getLastNPathParts(filepath, 1)} + {range && ` ${range}`} +
    ); }; - -export default FileInfo; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx new file mode 100644 index 000000000..7d56e012b --- /dev/null +++ b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx @@ -0,0 +1,25 @@ +import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; +import { lightGray } from "../.."; + +/** + * Button that inserts code at the current cursor position + */ +interface InsertButtonProps { + onInsert: () => void; +} + +export default function InsertButton({ onInsert }: InsertButtonProps) { + return ( +
    +
    + +
    +
    + ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 46fa90d68..0397603f3 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -1,9 +1,7 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { debounce } from "lodash"; -import { useContext, useEffect, useRef, useState } from "react"; +import { useContext, useState } from "react"; import styled from "styled-components"; -import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, @@ -12,24 +10,27 @@ import { import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; -import { selectDefaultModel } from "../../../redux/slices/configSlice"; import { selectApplyStateByStreamId, selectIsInEditMode, } from "../../../redux/slices/sessionSlice"; import { getFontSize } from "../../../util"; -import { childrenToText, isTerminalCodeBlock } from "../utils"; +import { isTerminalCodeBlock } from "../utils"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; -import FileInfo from "./FileInfo"; +import { FileInfo } from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; +import InsertButton from "./InsertButton"; import RunInTerminalButton from "./RunInTerminalButton"; const TopDiv = styled.div` + display: flex; + flex-direction: column; outline: 1px solid ${vscCommandCenterInactiveBorder}; outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; + margin-top: 8px !important; background-color: ${vscEditorBackground}; min-width: 0; `; @@ -38,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` display: flex; justify-content: space-between; align-items: center; - background: inherit; font-size: ${getFontSize() - 2}px; padding: 4px 6px; margin: 0; @@ -49,68 +49,101 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` export interface StepContainerPreToolbarProps { codeBlockContent: string; language: string | null; - relativeFilepath: string; + relativeFilepath?: string; isGeneratingCodeBlock: boolean; codeBlockIndex: number; // To track which codeblock we are applying + codeBlockStreamId: string; range?: string; children: any; expanded?: boolean; - hideApply?: boolean; + disableManualApply?: boolean; } -export default function StepContainerPreToolbar( - props: StepContainerPreToolbarProps, -) { +export default function StepContainerPreToolbar({ + codeBlockContent, + language, + relativeFilepath, + isGeneratingCodeBlock, + codeBlockIndex, + codeBlockStreamId, + range, + children, + expanded, + disableManualApply, +}: StepContainerPreToolbarProps) { const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(uuidv4()); - const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isInEditMode = useAppSelector(selectIsInEditMode); const [isExpanded, setIsExpanded] = useState( - props.expanded ?? (isInEditMode ? false : true), + expanded ?? (isInEditMode ? false : true), ); - const [codeBlockContent, setCodeBlockContent] = useState(""); - const isStreaming = useAppSelector((state) => state.session.isStreaming); + // We store the resolved file URI to ensure we use the same file when + // accepting/rejecting diffs, even if no `relativeFilepath` is provided + const [resolvedFileUri, setResolvedFileUri] = useState( + undefined, + ); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, streamIdRef.current), + selectApplyStateByStreamId(state, codeBlockStreamId), ); - // This handles an edge case when the last node in the markdown syntax tree is a codeblock. - // In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if - // we are done generating based on whether the next node in the tree is not a codeblock. - // The tree parsing logic for Remark is defined on page load, so we can't access state - // during the actual tree parsing. - const isGeneratingCodeBlock = !isStreaming - ? false - : props.isGeneratingCodeBlock; + const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; + const hasFileExtension = + relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); - const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; - const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); + const displayFilepath = relativeFilepath ?? resolvedFileUri; - const defaultModel = useAppSelector(selectDefaultModel); + async function getFileUri() { + // If we've already resolved a file URI (from clicking apply), use that + if (resolvedFileUri) { + return resolvedFileUri; + } + + // If a relative filepath was provided, try to resolve it + if (relativeFilepath) { + return await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + } + + // If no filepath was provided, get the current file + const currentFile = await ideMessenger.ide.getCurrentFile(); + if (currentFile) { + return currentFile.path; + } + + return undefined; + } async function onClickApply() { - if (!defaultModel) { + const fileUri = await getFileUri(); + if (!fileUri) { + ideMessenger.ide.showToast( + "error", + "Could not resolve filepath to apply changes", + ); + return; } - let fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); + setResolvedFileUri(fileUri); ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, + streamId: codeBlockStreamId, filepath: fileUri, text: codeBlockContent, - curSelectedModelTitle: defaultModel.title, }); } + function onClickInsertAtCursor() { + ideMessenger.post("insertAtCursor", { text: codeBlockContent }); + } + + // TODO: This logic should be moved to a thunk // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", @@ -119,121 +152,94 @@ export default function StepContainerPreToolbar( !isNextCodeBlock, ); - useEffect(() => { - if (codeBlockContent === "") { - setCodeBlockContent(childrenToText(props.children.props.children)); - } else { - const debouncedEffect = debounce(() => { - setCodeBlockContent(childrenToText(props.children.props.children)); - }, 100); - - debouncedEffect(); - - return () => { - debouncedEffect.cancel(); - }; + async function handleDiffAction(action: "accept" | "reject") { + const filepath = await getFileUri(); + if (!filepath) { + ideMessenger.ide.showToast( + "error", + `Could not resolve filepath to ${action} changes`, + ); + return; } - }, [props.children, codeBlockContent]); - // Temporarily disabling auto apply for Edit mode - // useEffect(() => { - // const hasCompletedGenerating = - // wasGeneratingRef.current && !isGeneratingCodeBlock; - - // const shouldAutoApply = hasCompletedGenerating && isInEditMode; - - // if (shouldAutoApply) { - // onClickApply(); - // } - - // wasGeneratingRef.current = isGeneratingCodeBlock; - // }, [isGeneratingCodeBlock]); - - async function onClickAcceptApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("acceptDiff", { - filepath: fileUri, - streamId: streamIdRef.current, + ideMessenger.post(`${action}Diff`, { + filepath, + streamId: codeBlockStreamId, }); + + setResolvedFileUri(undefined); } - async function onClickRejectApply() { - const fileUri = await inferResolvedUriFromRelativePath( - props.relativeFilepath, - ideMessenger.ide, - ); - ideMessenger.post("rejectDiff", { - filepath: fileUri, - streamId: streamIdRef.current, - }); - } + function onClickFilename() { + if (resolvedFileUri) { + ideMessenger.post("showFile", { + filepath: resolvedFileUri, + }); + } - function onClickExpand() { - setIsExpanded(!isExpanded); + if (relativeFilepath) { + ideMessenger.post("showFile", { + filepath: relativeFilepath, + }); + } } // We want until there is an extension in the filepath to avoid rendering - // an incomplete filepath - if (!hasFileExtension) { - return props.children; + // an incomplete filepath + if (relativeFilepath && !hasFileExtension) { + return children; } return ( - -
    + +
    setIsExpanded(!isExpanded)} + className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${ isExpanded ? "rotate-0" : "-rotate-90" }`} /> -
    + {displayFilepath ? ( -
    + ) : ( + {language} + )}
    -
    - {isGeneratingCodeBlock && ( +
    + {isGeneratingCodeBlock ? ( - )} - - {!isGeneratingCodeBlock && ( + ) : ( <> - - {props.hideApply || - (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - ))} + + + + {isTerminalCodeBlock(language, codeBlockContent) ? ( + + ) : ( + handleDiffAction("accept")} + onClickReject={() => handleDiffAction("reject")} + /> + )} )}
    {isExpanded && ( -
    - {props.children} -
    +
    {children}
    )} ); diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index d968101d0..3f7c82bca 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,5 +1,5 @@ import { ctxItemToRifWithContents } from "core/commands/util"; -import { memo, useEffect, useMemo } from "react"; +import { memo, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -17,12 +17,11 @@ import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols"; -import { getFontSize, isJetBrains } from "../../util"; +import { getFontSize } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; import StepContainerPreToolbar from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; @@ -69,7 +68,7 @@ const StyledMarkdown = styled.div<{ overflow-x: scroll; overflow-y: hidden; - padding: 16px 8px; + padding: 8px; } code { @@ -114,10 +113,6 @@ const StyledMarkdown = styled.div<{ line-height: 1.5; } - > *:first-child { - margin-top: 8px; - } - > *:last-child { margin-bottom: 0; } @@ -130,6 +125,9 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; + disableManualApply?: boolean; + singleCodeblockStreamId?: string; + expandCodeblocks?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -196,6 +194,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.itemIndex, history, allSymbols]); const pastFileInfoRef = useUpdatingRef(pastFileInfo); + const isLastItem = useMemo(() => { + return props.itemIndex && props.itemIndex === history.length - 1; + }, [history.length, props.itemIndex]); + const isLastItemRef = useUpdatingRef(isLastItem); + + const isStreaming = useAppSelector((store) => store.session.isStreaming); + const isStreamingRef = useUpdatingRef(isStreaming); + + const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( + [], + ); + + useEffect(() => { + if (props.singleCodeblockStreamId) { + codeblockState.current = [ + { + streamId: props.singleCodeblockStreamId, + isGenerating: false, + }, + ]; + } + }, [props.singleCodeblockStreamId]); + const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ remarkTables, @@ -219,8 +240,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( node.data = node.data || {}; node.data.hProperties = node.data.hProperties || {}; - node.data.hProperties["data-isgeneratingcodeblock"] = - lastCodeNode === node; + node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node; node.data.hProperties["data-codeblockcontent"] = node.value; if (node.meta) { @@ -280,10 +300,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const preChildProps = preProps?.children?.[0]?.props ?? {}; const { className, range } = preChildProps; + const relativeFilePath = preChildProps["data-relativefilepath"]; const codeBlockContent = preChildProps["data-codeblockcontent"]; - const isGeneratingCodeBlock = - preChildProps["data-isgeneratingcodeblock"]; if (!props.isRenderingInStepContainer) { return ; @@ -291,23 +310,21 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - // If we don't have a filepath show the more basic toolbar - // that is just action buttons on hover. - // We also use this in JB since we haven't yet implemented - // the logic forfileUri lazy apply. - if (!relativeFilePath || isJetBrains()) { - return ( - - - - ); + const isGeneratingCodeBlock = + preChildProps["data-islastcodeblock"] && + isLastItemRef.current && + isStreamingRef.current; + + if (codeblockState.current[codeBlockIndex] === undefined) { + codeblockState.current[codeBlockIndex] = { + streamId: uuidv4(), + isGenerating: isGeneratingCodeBlock, + }; + } else { + codeblockState.current[codeBlockIndex].isGenerating = + isGeneratingCodeBlock; } - // We use a custom toolbar for codeblocks in the step container return ( diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx index 0e14adfad..92395f545 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -12,7 +12,7 @@ import { useEffect, useMemo } from "react"; import styled from "styled-components"; import { lightGray } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { cycleMode, selectCurrentMode, @@ -40,7 +40,7 @@ const ShortcutText = styled.span` function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector(selectCurrentMode); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); const jetbrains = useMemo(() => { diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 4c2e31387..8191af54b 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -6,18 +6,15 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray } from ".."; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; -import { useAppSelector } from "../../redux/hooks"; -import { - selectDefaultModel, - setDefaultModel, -} from "../../redux/slices/configSlice"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; @@ -122,9 +119,11 @@ function ModelOption({ } function ModelSelect() { - const dispatch = useDispatch(); - const defaultModel = useAppSelector(selectDefaultModel); - const allModels = useAppSelector((state) => state.config.config.models); + const dispatch = useAppDispatch(); + const selectedChatModel = useAppSelector(selectSelectedChatModel); + const allChatModels = useAppSelector( + (state) => state.config.config.modelsByRole.chat, + ); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -142,7 +141,7 @@ function ModelSelect() { useEffect(() => { setOptions( - allModels + allChatModels .filter((m) => !m.roles || m.roles.includes("chat")) .map((model) => { return { @@ -152,19 +151,30 @@ function ModelSelect() { }; }), ); - }, [allModels]); + }, [allChatModels]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { + if (!selectedProfile) { + return; + } + const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === defaultModel?.title, + (option) => option.value === selectedChatModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; const newModelTitle = options[nextIndex].value; - dispatch(setDefaultModel({ title: newModelTitle })); + + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: newModelTitle, + }), + ); } }; @@ -172,7 +182,7 @@ function ModelSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [options, defaultModel]); + }, [options, selectedChatModel]); function onClickAddModel(e: MouseEvent) { e.stopPropagation(); @@ -195,11 +205,16 @@ function ModelSelect() { } return ( - // Hiad sfasdfasdf asdfasdf { - if (val === defaultModel?.title) return; - dispatch(setDefaultModel({ title: val })); + if (val === selectedChatModel?.title) return; + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: val, + }), + ); }} >
    @@ -208,8 +223,8 @@ function ModelSelect() { ref={buttonRef} className="h-[18px] gap-1 border-none text-gray-400" > - - {modelSelectTitle(defaultModel) || "Select model"} + + {modelSelectTitle(selectedChatModel) || "Select model"} ))}
    diff --git a/gui/src/components/modelSelection/platform/AssistantIcon.tsx b/gui/src/components/modelSelection/platform/AssistantIcon.tsx index 9f4bfcd0b..c901bfdf4 100644 --- a/gui/src/components/modelSelection/platform/AssistantIcon.tsx +++ b/gui/src/components/modelSelection/platform/AssistantIcon.tsx @@ -10,7 +10,15 @@ export interface AssistantIconProps { export default function AssistantIcon({ assistant, size }: AssistantIconProps) { const sizeTw = size ?? 4; if (isLocalProfile(assistant)) { - return ; + return ( +
    + +
    + ); } else if (assistant.iconUrl) { return ( void; } + const AssistantSelectOption = ({ profile, + selected, onClick, }: AssistantSelectOptionProps) => { + const tinyFont = useFontSize(-4); + const navigate = useNavigate(); - const [hovered, setHovered] = useState(false); const hasFatalErrors = useMemo(() => { return !!profile.errors?.find((error) => error.fatal); @@ -52,7 +62,12 @@ const AssistantSelectOption = ({ const ideMessenger = useContext(IdeMessengerContext); function handleOptionClick() { - dispatch(selectProfileThunk(profile.id)); + // optimistic update + dispatch(setSelectedProfile(profile.id)); + // notify core which will handle actual update + ideMessenger.post("didChangeSelectedProfile", { + id: profile.id, + }); onClick(); } @@ -72,29 +87,34 @@ const AssistantSelectOption = ({ return ( setHovered(true)} - onMouseLeave={() => setHovered(false)} value={profile.id} disabled={hasFatalErrors} onClick={!hasFatalErrors ? handleOptionClick : undefined} fontSizeModifier={-2} + className={selected ? "bg-list-active text-list-active-foreground" : ""} > -
    -
    -
    -
    - +
    +
    +
    +
    +
    - {profile.title} + + {profile.title} +
    -
    +
    {!profile.errors?.length ? ( isLocalProfile(profile) ? ( { e.stopPropagation(); e.preventDefault(); @@ -103,10 +123,7 @@ const AssistantSelectOption = ({ /> ) : ( { e.stopPropagation(); e.preventDefault(); @@ -141,11 +158,11 @@ const AssistantSelectOption = ({ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile, selectedOrganization } = useAuth(); + const { selectedProfile, refreshProfiles } = useAuth(); + const currentOrg = useAppSelector(selectCurrentOrg); + const orgs = useAppSelector((store) => store.profiles.organizations); const ideMessenger = useContext(IdeMessengerContext); - const isLumpToolbarExpanded = useAppSelector( - (state) => state.ui.isBlockSettingsToolbarExpanded, - ); + const { isToolbarExpanded } = useLump(); const { profiles, session, login } = useAuth(); const navigate = useNavigate(); @@ -158,14 +175,14 @@ export default function AssistantSelect() { function onNewAssistant() { ideMessenger.post("controlPlane/openUrl", { path: "new", - orgSlug: selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); close(); } useEffect(() => { let lastToggleTime = 0; - const DEBOUNCE_MS = 500; + const DEBOUNCE_MS = 800; const handleKeyDown = (event: KeyboardEvent) => { if ( @@ -176,8 +193,24 @@ export default function AssistantSelect() { const now = Date.now(); if (now - lastToggleTime >= DEBOUNCE_MS) { - dispatch(cycleProfile()); lastToggleTime = now; + + const profileIds = profiles?.map((profile) => profile.id) ?? []; + // In case of 1 or 0 profiles just does nothing + if (profileIds.length < 2) { + return; + } + let nextId = profileIds[0]; + if (selectedProfile) { + const curIndex = profileIds.indexOf(selectedProfile.id); + const nextIndex = (curIndex + 1) % profileIds.length; + nextId = profileIds[nextIndex]; + } + // Optimistic update + dispatch(setSelectedProfile(nextId)); + ideMessenger.post("didChangeSelectedProfile", { + id: nextId, + }); } } }; @@ -186,7 +219,25 @@ export default function AssistantSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, []); + }, [currentOrg, selectedProfile]); + + const cycleOrgs = () => { + const orgIds = orgs.map((org) => org.id); + if (orgIds.length < 2) { + return; + } + let nextId = orgIds[0]; + if (currentOrg) { + const curIndex = orgIds.indexOf(currentOrg.id); + const nextIndex = (curIndex + 1) % orgIds.length; + nextId = orgIds[nextIndex]; + } + // Optimistic update + dispatch(setSelectedOrgId(nextId)); + ideMessenger.post("didChangeSelectedOrg", { + id: nextId, + }); + }; const tinyFont = useFontSize(-4); const smallFont = useFontSize(-3); @@ -197,7 +248,7 @@ export default function AssistantSelect() { onClick={() => { ideMessenger.request("controlPlane/openUrl", { path: "/new?type=assistant", - orgSlug: selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); }} className="flex cursor-pointer select-none items-center gap-1 text-gray-400" @@ -205,7 +256,7 @@ export default function AssistantSelect() { > Create your first assistant @@ -215,7 +266,7 @@ export default function AssistantSelect() { return ( -
    +
    {selectedProfile.title} @@ -240,8 +291,22 @@ export default function AssistantSelect() { +
    + Assistants +
    { + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); + }} + > + +
    +
    +
    {profiles?.map((profile, idx) => { return ( @@ -249,6 +314,7 @@ export default function AssistantSelect() { key={idx} profile={profile} onClick={close} + selected={profile.id === selectedProfile.id} /> ); })} @@ -262,16 +328,24 @@ export default function AssistantSelect() { }} /> - login(false)} - > -
    - - New Assistant -
    -
    +
    + login(false)} + > +
    + + New Assistant +
    +
    +
    - + {getMetaKeyLabel()} ⇧ ' to toggle
    navigate(ROUTES.CONFIG)} + className="ml-auto flex items-center gap-1" + onClick={cycleOrgs} > - {selectedOrganization?.iconUrl ? ( + {currentOrg?.iconUrl ? ( ) : ( )} - - {selectedOrganization?.name || "Personal"} + + {currentOrg?.name || "Personal"}
    diff --git a/gui/src/components/ui/Listbox.tsx b/gui/src/components/ui/Listbox.tsx index 5bb235563..ed2e077bf 100644 --- a/gui/src/components/ui/Listbox.tsx +++ b/gui/src/components/ui/Listbox.tsx @@ -46,7 +46,7 @@ const ListboxOptions = React.forwardRef( anchor={"bottom start"} {...props} className={cn( - "bg-vsc-input-background flex flex-col overflow-auto px-0 shadow-md", + "bg-vsc-input-background flex w-max min-w-[160px] max-w-[400px] flex-col overflow-auto px-0 shadow-md", props.className, )} style={{ diff --git a/gui/src/console.tsx b/gui/src/console.tsx new file mode 100644 index 000000000..beb7c4e53 --- /dev/null +++ b/gui/src/console.tsx @@ -0,0 +1,12 @@ +import React from "react"; +import ReactDOM from "react-dom/client"; +import Layout from "./components/console/Layout"; +import "./indexConsole.css"; + +(async () => { + ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( + + + , + ); +})(); diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index a049e8adc..329a1ee38 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -5,17 +5,20 @@ import { import { ControlPlaneSessionInfo } from "core/control-plane/client"; import React, { createContext, + useCallback, useContext, useEffect, - useMemo, useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { updateOrgsThunk, updateProfilesThunk } from "../redux"; -import { selectSelectedProfile } from "../redux/"; +import { + selectCurrentOrg, + selectSelectedProfile, + setOrganizations, + setSelectedOrgId, +} from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; @@ -28,7 +31,6 @@ interface AuthContextType { refreshProfiles: () => void; controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; - selectedOrganization: OrganizationDescription | null; } const AuthContext = createContext(undefined); @@ -38,26 +40,16 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - // Session const [session, setSession] = useState( undefined, ); // Orgs - const orgs = useAppSelector((store) => store.organizations.organizations); - const selectedOrgId = useAppSelector( - (store) => store.organizations.selectedOrganizationId, - ); - const selectedOrganization = useMemo(() => { - if (!selectedOrgId) { - return null; - } - return orgs.find((p) => p.id === selectedOrgId) ?? null; - }, [orgs, selectedOrgId]); + const orgs = useAppSelector((store) => store.profiles.organizations); // Profiles - const profiles = useAppSelector((store) => store.profiles.availableProfiles); + const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); const login: AuthContextType["login"] = (useOnboarding: boolean) => { @@ -90,6 +82,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ text="Are you sure you want to log out of Continue?" onConfirm={() => { ideMessenger.post("logoutOfControlPlane", undefined); + dispatch( + setOrganizations(orgs.filter((org) => org.id === "personal")), + ); + dispatch(setSelectedOrgId("personal")); }} onCancel={() => { dispatch(setDialogMessage(undefined)); @@ -100,79 +96,40 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ); }; - useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => { - setSession(data.sessionInfo); - // On logout, clear the list of orgs - if (!data.sessionInfo) { - dispatch(updateOrgsThunk([])); - } - }); - useEffect(() => { - ideMessenger - .request("getControlPlaneSessionInfo", { + async function init() { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { silent: true, useOnboarding: false, - }) - .then( - (result) => result.status === "success" && setSession(result.content), - ); - }, []); - - const [controlServerBetaEnabled, setControlServerBetaEnabled] = - useState(false); - - useEffect(() => { - ideMessenger.ide - .getIdeSettings() - .then(({ enableControlServerBeta, continueTestEnvironment }) => { - setControlServerBetaEnabled(enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(enableControlServerBeta), - ); }); - }, []); - - useEffect(() => { - if (session) { - ideMessenger - .request("controlPlane/listOrganizations", undefined) - .then((result) => { - if (result.status === "success") { - dispatch(updateOrgsThunk(result.content)); - } else { - dispatch(updateOrgsThunk([])); - } - }); + if (result.status === "success") { + setSession(result.content); + } } - }, [session]); + void init(); + }, []); useWebviewListener( - "didChangeIdeSettings", - async (msg) => { - const { settings } = msg; - setControlServerBetaEnabled(settings.enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), - ); + "didChangeControlPlaneSessionInfo", + async (data) => { + setSession(data.sessionInfo); }, [], ); - useEffect(() => { - ideMessenger.request("config/listProfiles", undefined).then((result) => { - if (result.status === "success") { - dispatch( - updateProfilesThunk({ - profiles: result.content.profiles, - selectedProfileId: result.content.selectedProfileId, - }), - ); - } - }); - }, []); + const [controlServerBetaEnabled, setControlServerBetaEnabled] = + useState(false); - const refreshProfiles = async () => { + // Hacky, remove once continue for teams is deprecated + useWebviewListener( + "configUpdate", + async (msg) => { + setControlServerBetaEnabled(msg.usingContinueForTeams); + }, + [], + ); + + const refreshProfiles = useCallback(async () => { try { await ideMessenger.request("config/refreshProfiles", undefined); ideMessenger.post("showToast", ["info", "Config refreshed"]); @@ -180,20 +137,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ console.error("Failed to refresh profiles", e); ideMessenger.post("showToast", ["error", "Failed to refresh config"]); } - }; - - useWebviewListener( - "didChangeAvailableProfiles", - async (data) => { - dispatch( - updateProfilesThunk({ - profiles: data.profiles, - selectedProfileId: data.selectedProfileId, - }), - ); - }, - [], - ); + }, [ideMessenger]); return ( = ({ logout, login, selectedProfile, - profiles, + profiles: currentOrg?.profiles ?? [], refreshProfiles, - selectedOrganization, organizations: orgs, controlServerBetaEnabled, }} diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index c2e848446..4d0258efd 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -15,7 +15,6 @@ import { } from "core/protocol/util"; import { createContext } from "react"; import { v4 as uuidv4 } from "uuid"; -import "vscode-webview"; import { isJetBrains } from "../util"; interface vscode { diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index c89a67972..8268377de 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -50,6 +50,7 @@ export const SubmenuContextProvidersProvider = ({ }) => { const ideMessenger = useContext(IdeMessengerContext); const submenuContextProviders = useAppSelector(selectSubmenuContextProviders); + const lastProviders = useRef(submenuContextProviders); const disableIndexing = useAppSelector( (store) => store.config.config.disableIndexing, ); @@ -356,15 +357,22 @@ export const SubmenuContextProvidersProvider = ({ ); // Reload all submenu items on the initial config load - // TODO - could refresh on any change - const initialLoad = useRef(false); useEffect(() => { - if (!submenuContextProviders.length || initialLoad.current) { + if (!submenuContextProviders.length) { return; } - void loadSubmenuItems("all"); - initialLoad.current = true; - }, [loadSubmenuItems, submenuContextProviders, initialLoad]); + // Refresh submenu items when new titles detected + const newTitles = submenuContextProviders + .filter( + (provider) => + !lastProviders.current.find((p) => p.title === provider.title), + ) + .map((provider) => provider.title); + if (newTitles.length > 0) { + loadSubmenuItems(newTitles); + } + lastProviders.current = submenuContextProviders; + }, [loadSubmenuItems, submenuContextProviders]); return ( void; @@ -33,13 +34,14 @@ function AddModelForm({ const [selectedProvider, setSelectedProvider] = useState( providers["openai"]!, ); + const dispatch = useAppDispatch(); + const { selectedProfile } = useAuth(); const [selectedModel, setSelectedModel] = useState( selectedProvider.packages[0], ); const formMethods = useForm(); - const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const popularProviderTitles = [ @@ -115,7 +117,13 @@ function AddModelForm({ profileId: "local", }); - dispatch(setDefaultModel({ title: model.title, force: true })); + dispatch( + updateSelectedModelByRole({ + selectedProfile, + role: "chat", + modelTitle: model.title, + }), + ); onDone(); } diff --git a/gui/src/hooks/useLLMLog.ts b/gui/src/hooks/useLLMLog.ts new file mode 100644 index 000000000..3b20d1628 --- /dev/null +++ b/gui/src/hooks/useLLMLog.ts @@ -0,0 +1,252 @@ +import { + LLMInteractionCancel, + LLMInteractionChunk, + LLMInteractionError, + LLMInteractionItem, + LLMInteractionMessage, + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, + LLMInteractionSuccess, +} from "core"; +import { useEffect, useReducer } from "react"; + +declare const vscode: any; + +export type LLMResult = LLMInteractionMessage | LLMInteractionChunk; + +const MAX_GROUP_LENGTH = 32; + +interface ToConsoleViewInit { + type: "init"; + uuid: string; + items: LLMInteractionItem[]; +} + +interface ToConsoleViewItem { + type: "item"; + uuid: string; + item: LLMInteractionItem; +} + +interface ToConsoleViewRemove { + type: "remove"; + uuid: string; + interactionId: string; +} + +interface ToConsoleViewClear { + type: "clear"; + uuid: string; +} + +type ToConsoleView = + | ToConsoleViewInit + | ToConsoleViewItem + | ToConsoleViewRemove + | ToConsoleViewClear; + +/** + * Represents a linear list of LLMInteractionItem, transformed into + * a form that is more convenient for rendering. + */ +export interface LLMInteraction { + start?: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim; + + // We use an array-of-arrays for efficiency when rendering a streamed result + // with lots and lots of separate tokens; instead of having a linear list + // of 1024 Result components, we have 32 ResultGroup components each rendering + // 32 Results. + // + // Inline content can split between one group and the next - we'll let the + // browser engine sort that out. + results: LLMResult[][]; + + end?: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel; +} + +export interface LLMLog { + loading: boolean; + interactions: Map; + order: string[]; +} + +/** + * Appends a new result item (chunk or message) to an interaction, + * existing iteractions must already have been copied with + * copyInteractionForMutation(). + */ +function appendItemToInteractionResult( + interaction: LLMInteraction, + item: LLMInteractionMessage | LLMInteractionChunk, +) { + let lastGroup = interaction.results[interaction.results.length - 1]; + + if (lastGroup == undefined || lastGroup.length == MAX_GROUP_LENGTH) { + interaction.results.push([item]); + } else { + lastGroup.push(item); + } +} + +/** + * Makes a copy of an interaction that can be mutated without changing + * any objects/arrays that are part of the old state. We always make + * a copy of the last (open) result group, so that we can simply append + * to it; this is very slightly inefficient for the case where we're + * handling a single end item with no results, but makes things simpler. + */ +function copyInteractionForMutation(oldInteraction: LLMInteraction) { + const oldResults = oldInteraction.results; + let oldLastGroup = oldInteraction.results[oldInteraction.results.length - 1]; + let newResults; + + if (oldLastGroup == undefined || oldLastGroup.length == MAX_GROUP_LENGTH) { + newResults = [...oldInteraction.results]; + } else { + newResults = oldInteraction.results.slice(0, -1); + newResults.push([...oldLastGroup]); + } + + return { ...oldInteraction, results: newResults }; +} + +function appendItemsToLLMLog( + oldLog: LLMLog, + items: LLMInteractionItem[], +): LLMLog { + const oldInteractions = oldLog.interactions; + const newInteractions: Map = new Map(); + let order = oldLog.order; + let interactionsAdded = false; + + // Add the new items to the log, making mutable copies of old + // LLMInteraction as necessary + for (const item of items) { + let interaction = newInteractions.get(item.interactionId); + if (interaction === undefined) { + const oldInteraction = oldInteractions.get(item.interactionId); + if (oldInteraction) { + interaction = copyInteractionForMutation(oldInteraction); + } else { + interaction = { + results: [], + }; + + if (interactionsAdded) { + order.push(item.interactionId); + } else { + order = [...order, item.interactionId]; + interactionsAdded = true; + } + } + newInteractions.set(item.interactionId, interaction); + } + + switch (item.kind) { + case "startChat": + case "startComplete": + case "startFim": + interaction.start = item; + break; + case "chunk": + case "message": + appendItemToInteractionResult(interaction, item); + break; + case "success": + case "error": + case "cancel": + interaction.end = item; + break; + } + } + + // Copy over unchanged interactions + for (const interactionId of oldInteractions.keys()) { + if (!newInteractions.has(interactionId)) { + newInteractions.set(interactionId, oldInteractions.get(interactionId)!); + } + } + + return { + loading: false, + interactions: newInteractions, + order, + }; +} + +function removeInteractionFromLLMLog( + llmLog: LLMLog, + interactionId: string, +): LLMLog { + const newInteractions = new Map(llmLog.interactions); + newInteractions.delete(interactionId); + const newOrder = llmLog.order.filter((id) => id !== interactionId); + + return { + loading: false, + interactions: newInteractions, + order: newOrder, + }; +} + +/** + * Hook to accumulate log data structures based on messages passed + * from the core. Note that each call site will create an independent + * data structure, so this should be only used once at a toplevel + * component. + * @returns currently log datastructure. + */ +export default function useLLMLog() { + const [llmLog, dispatchLlmLog] = useReducer( + (llmLog: LLMLog, message: ToConsoleView) => { + switch (message.type) { + case "init": + return appendItemsToLLMLog(llmLog, message.items); + case "item": + return appendItemsToLLMLog(llmLog, [message.item]); + case "remove": + return removeInteractionFromLLMLog(llmLog, message.interactionId); + case "clear": + return { + loading: false, + interactions: new Map(), + order: [], + }; + } + }, + { + loading: true, + interactions: new Map(), + order: [], + }, + ); + + useEffect(function () { + // The uuid here marks the "generation" when the webview is + // reloaded, so we don't get confused if there are inflight + // messages from the previous generation. In particular, this + // avoids problems when React.StrictMode runs this effect + // twice - we don't want to process two "init" messages. + const uuid = crypto.randomUUID(); + const onMessage = (event: MessageEvent) => { + if (event.data.uuid !== uuid) { + return; + } + + dispatchLlmLog(event.data); + }; + window.addEventListener("message", onMessage); + vscode.postMessage({ type: "start", uuid }); + + return () => { + vscode.postMessage({ type: "stop", uuid }); + window.removeEventListener("message", onMessage); + }; + }, []); + + return llmLog; +} diff --git a/gui/src/hooks/useLLMSummary.ts b/gui/src/hooks/useLLMSummary.ts new file mode 100644 index 000000000..b5016e767 --- /dev/null +++ b/gui/src/hooks/useLLMSummary.ts @@ -0,0 +1,76 @@ +import { useMemo } from "react"; +import { LLMInteraction } from "./useLLMLog"; + +/** + * Hook returning memoized information about single logged prompt/response + * query to the LLM. + */ +export default function useLLMSummary(interaction: LLMInteraction) { + return useMemo(() => { + if (interaction.start == undefined) { + return { + result: "", + type: "", + }; + } + + const type = interaction.start.kind.slice(5); + + let result; + switch (interaction.end?.kind) { + case "cancel": + result = "Cancelled"; + break; + case "error": + result = "Error"; + break; + case "success": + result = "Success"; + break; + case undefined: + result = ""; + } + + let totalTime, + toFirstToken, + tokensPerSecond, + promptTokens, + generatedTokens, + thinkingTokens; + if (interaction.start != undefined && interaction.results.length > 0) { + const firstGroup = interaction.results[0]; + const firstItem = firstGroup ? firstGroup[0] : undefined; + toFirstToken = firstItem + ? firstItem.timestamp - interaction.start.timestamp + : undefined; + } + if (interaction.end != undefined) { + totalTime = interaction.end.timestamp - interaction.start.timestamp; + promptTokens = interaction.end.promptTokens; + generatedTokens = interaction.end.generatedTokens; + thinkingTokens = interaction.end.thinkingTokens; + if (toFirstToken != undefined) { + tokensPerSecond = + (generatedTokens + thinkingTokens) / + ((totalTime - toFirstToken) / 1000); + } + } else { + const lastGroup = interaction.results[interaction.results.length - 1]; + const lastItem = lastGroup ? lastGroup[lastGroup.length - 1] : undefined; + totalTime = lastItem + ? lastItem.timestamp - interaction.start.timestamp + : undefined; + } + + return { + result, + type, + totalTime, + toFirstToken, + tokensPerSecond, + promptTokens, + generatedTokens, + thinkingTokens, + }; + }, [interaction]); +} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index d90259a9b..e9d9223a8 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -2,24 +2,28 @@ import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from "core"; +import { FromCoreProtocol } from "core/protocol"; import { - initializeProfilePreferencesThunk, - selectProfileThunk, - selectSelectedProfileId, + initializeProfilePreferences, + setOrganizations, + setSelectedOrgId, + setSelectedProfile, } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { - selectDefaultModel, + selectSelectedChatModel, setConfigResult, } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { + acceptToolCall, addContextItemsAtIndex, setInactive, + setToolCallOutput, + updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { streamResponseAfterToolCall } from "../redux/thunks"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -31,31 +35,40 @@ function useSetup() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); - const defaultModel = useAppSelector(selectDefaultModel); - const selectedProfileId = useAppSelector(selectSelectedProfileId); + const defaultModel = useAppSelector(selectSelectedChatModel); + const selectedProfileId = useAppSelector( + (store) => store.profiles.selectedProfileId, + ); - const hasLoadedConfig = useRef(false); + const hasDoneInitialConfigLoad = useRef(false); const handleConfigUpdate = useCallback( - async ( - initial: boolean, - result: { - result: ConfigResult; - profileId: string | null; - }, - ) => { - const { result: configResult, profileId } = result; - if (initial && hasLoadedConfig.current) { + async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { + const { + result: configResult, + profileId, + organizations, + selectedOrgId, + } = result; + + if (isInitial && hasDoneInitialConfigLoad.current) { return; } - hasLoadedConfig.current = true; + hasDoneInitialConfigLoad.current = true; + dispatch(setOrganizations(organizations)); + dispatch(setSelectedOrgId(selectedOrgId)); + dispatch(setSelectedProfile(profileId)); dispatch(setConfigResult(configResult)); - dispatch(selectProfileThunk(profileId)); const isNewProfileId = profileId && profileId !== selectedProfileId; if (isNewProfileId) { - dispatch(initializeProfilePreferencesThunk({ profileId })); + dispatch( + initializeProfilePreferences({ + defaultSlashCommands: [], + profileId, + }), + ); } // Perform any actions needed with the config @@ -64,28 +77,31 @@ function useSetup() { document.body.style.fontSize = `${configResult.config.ui.fontSize}px`; } }, - [dispatch, hasLoadedConfig], + [dispatch, hasDoneInitialConfigLoad], ); - const loadConfig = useCallback( + const initialLoadAuthAndConfig = useCallback( async (initial: boolean) => { + // const authResult = await ideMessenger.request( + // "auth/getState", + // undefined + // ) const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, ); - if (result.status === "error") { - return; + if (result.status === "success") { + await handleConfigUpdate(initial, result.content); } - await handleConfigUpdate(initial, result.content); }, [ideMessenger, handleConfigUpdate], ); // Load config from the IDE useEffect(() => { - loadConfig(true); + initialLoadAuthAndConfig(true); const interval = setInterval(() => { - if (hasLoadedConfig.current) { + if (hasDoneInitialConfigLoad.current) { // Init to run on initial config load ideMessenger.post("docs/initStatuses", undefined); dispatch(updateFileSymbolsFromHistory()); @@ -93,13 +109,13 @@ function useSetup() { // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); - return; + } else { + initialLoadAuthAndConfig(true); } - loadConfig(true); }, 2_000); return () => clearInterval(interval); - }, [hasLoadedConfig, loadConfig, ideMessenger]); + }, [hasDoneInitialConfigLoad, initialLoadAuthAndConfig, ideMessenger]); useWebviewListener( "configUpdate", @@ -109,7 +125,7 @@ function useSetup() { } await handleConfigUpdate(false, update); }, - [loadConfig], + [handleConfigUpdate], ); // Load symbols for chat on any session change @@ -238,12 +254,34 @@ function useSetup() { dispatch(updateIndexingStatus(data)); }); + const activeToolStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); useWebviewListener( - "getDefaultModelTitle", - async () => { - return defaultModel?.title; + "updateApplyState", + async (state) => { + dispatch(updateApplyState(state)); + if ( + activeToolStreamId && + state.streamId === activeToolStreamId[0] && + state.status === "closed" + ) { + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; + dispatch(acceptToolCall()); + dispatch(setToolCallOutput([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolStreamId[1], + toolOutput: [], + }), + ); + } }, - [defaultModel], + [activeToolStreamId], ); } diff --git a/gui/src/indexConsole.css b/gui/src/indexConsole.css new file mode 100644 index 000000000..c5e41252f --- /dev/null +++ b/gui/src/indexConsole.css @@ -0,0 +1,9 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +html, +body, +#root { + height: 100%; +} diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx deleted file mode 100644 index e2fa104ea..000000000 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ /dev/null @@ -1,238 +0,0 @@ -import { ArrowLeftIcon, Cog6ToothIcon } from "@heroicons/react/24/outline"; -import _ from "lodash"; -import React, { useContext } from "react"; -import { useDispatch } from "react-redux"; -import { Link, useNavigate } from "react-router-dom"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscBackground, -} from "../../components"; -import ModelCard from "../../components/modelSelection/ModelCard"; -import Toggle from "../../components/modelSelection/Toggle"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { setDefaultModel } from "../../redux/slices/configSlice"; -import { ModelPackage, models } from "./configs/models"; -import { providers } from "./configs/providers"; -import { CustomModelButton } from "./ConfigureProvider"; - -const IntroDiv = styled.div` - padding: 8px 12px; - border-radius: ${defaultBorderRadius}; - border: 1px solid ${lightGray}; - margin-top: 1rem; - margin-bottom: 1rem; -`; - -const GridDiv = styled.div` - display: grid; - grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); - grid-gap: 1.25rem; - justify-items: center; - align-items: center; -`; - -/** - * Used to display groupings in the Models tab - */ -const modelsByProvider: Record = { - "Open AI": [models.gpt4turbo, models.gpt4o, models.gpt35turbo], - Anthropic: [models.claude3Opus, models.claude3Sonnet, models.claude35Haiku], - Mistral: [ - models.codestral, - models.mistral7b, - models.mistral8x7b, - models.mistral8x22b, - models.mistralSmall, - models.mistralLarge, - ], - Cohere: [models.commandR, models.commandRPlus], - DeepSeek: [ - models.deepseekCoderApi, - models.deepseekChatApi, - models.deepseekReasonerApi, - ], - Gemini: [models.geminiPro, models.gemini15Pro, models.gemini15Flash], - "Open Source": [models.llama3Chat, models.mistralOs, models.deepseek], -}; - -function AddNewModel() { - const navigate = useNavigate(); - const dispatch = useDispatch(); - useNavigationListener(); - const ideMessenger = useContext(IdeMessengerContext); - - const [providersSelected, setProvidersSelected] = React.useState(true); - - return ( -
    -
    - navigate("/")} - className="ml-4 inline-block cursor-pointer" - /> -

    Add a new model

    -
    -
    -
    - - To add a new model you can either: -
      -
    • - Start by selecting and configuring a provider, then choosing your - model -
    • -
    • Select a specific model directly
    • -
    - - Visit our setup overview docs - {" "} - to learn more. -
    - -
    - { - setProvidersSelected((prev) => !prev); - }} - > -
    - - {providersSelected ? ( - <> -
    -

    Providers

    -

    - Select a provider below, or configure your own in{" "} - config.json -

    -
    - - - {Object.entries(providers).map(([providerName, modelInfo], i) => - modelInfo ? ( - { - console.log(`/addModel/provider/${providerName}`); - navigate(`/addModel/provider/${providerName}`); - }} - /> - ) : null, - )} - - - ) : ( - <> -
    -

    Models

    -

    - Select a model from the most popular options below, or configure - your own in config.json -

    -
    - - {Object.entries(modelsByProvider).map( - ([providerTitle, modelConfigsByProviderTitle]) => ( -
    -
    -

    {providerTitle}

    -
    -
    - - - {modelConfigsByProviderTitle.map((config) => ( - { - if (!selectedProvider) { - return; - } - const model = { - ...config.params, - ..._.merge( - {}, - ...(config.dimensions?.map((dimension, i) => { - if (!dimensionChoices?.[i]) return {}; - return { - ...dimension.options[dimensionChoices[i]], - }; - }) || []), - ), - provider: providers[selectedProvider]?.provider, - }; - ideMessenger.post("config/addModel", { model }); - dispatch( - setDefaultModel({ - title: model.title, - force: true, - }), - ); - navigate("/"); - }} - /> - ))} - -
    - ), - )} - - )} - - { - ideMessenger.post("config/openProfile", { - profileId: undefined, - }); - }} - > -

    - - Open Assistant configuration -

    -
    -
    -
    - ); -} - -export default AddNewModel; diff --git a/gui/src/pages/AddNewModel/ConfigureProvider.tsx b/gui/src/pages/AddNewModel/ConfigureProvider.tsx deleted file mode 100644 index 33a3366d6..000000000 --- a/gui/src/pages/AddNewModel/ConfigureProvider.tsx +++ /dev/null @@ -1,245 +0,0 @@ -import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import _ from "lodash"; -import { useCallback, useContext, useEffect, useState } from "react"; -import { FormProvider, useForm } from "react-hook-form"; -import { useDispatch } from "react-redux"; -import { useNavigate, useParams } from "react-router-dom"; -import styled from "styled-components"; -import { - Input, - defaultBorderRadius, - lightGray, - vscBackground, -} from "../../components"; -import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; -import ModelCard from "../../components/modelSelection/ModelCard"; -import { ModelProviderTag } from "../../components/modelSelection/ModelProviderTag"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { updatedObj } from "../../util"; -import type { ProviderInfo } from "./configs/providers"; -import { providers } from "./configs/providers"; -import { setDefaultModel } from "../../redux/slices/configSlice"; - -const GridDiv = styled.div` - display: grid; - grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); - grid-gap: 2rem; - padding: 1rem; - justify-items: center; - align-items: center; -`; - -export const CustomModelButton = styled.div<{ disabled: boolean }>` - border: 1px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 4px 8px; - display: flex; - justify-content: center; - align-items: center; - transition: all 0.5s; - - ${(props) => - props.disabled - ? ` - opacity: 0.5; - ` - : ` - &:hover { - border: 1px solid #be1b55; - background-color: #be1b5522; - cursor: pointer; - } - `} -`; - -function ConfigureProvider() { - useNavigationListener(); - const formMethods = useForm(); - const { providerName } = useParams(); - const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); - const navigate = useNavigate(); - const [modelInfo, setModelInfo] = useState( - undefined, - ); - - useEffect(() => { - if (providerName) { - setModelInfo(providers[providerName]); - } - }, [providerName]); - - const disableModelCards = useCallback(() => { - return ( - modelInfo?.collectInputFor?.some((d) => { - if (!d.required) return false; - const val = formMethods.watch(d.key); - return ( - typeof val === "undefined" || (typeof val === "string" && val === "") - ); - }) || false - ); - }, [modelInfo, formMethods]); - - return ( - -
    -
    - navigate("/addModel")} - className="ml-4 inline-block cursor-pointer" - /> -

    - Configure provider -

    -
    - -
    -
    - {window.vscMediaUrl && modelInfo?.icon && ( - - )} -

    {modelInfo?.title}

    -
    - - {modelInfo?.tags?.map((tag, i) => ( - - ))} - - -
    - - {(modelInfo?.collectInputFor?.filter((d) => d.required).length || 0) > - 0 && ( - <> -

    Enter required parameters

    - - {modelInfo?.collectInputFor - ?.filter((d) => d.required) - .map((d, idx) => ( -
    - - -
    - ))} - - )} - - {(modelInfo?.collectInputFor?.filter((d) => !d.required).length || - 0) > 0 && ( -
    - - Advanced (optional) - - - {modelInfo?.collectInputFor?.map((d, idx) => { - if (d.required) return null; - return ( -
    - - -
    - ); - })} -
    - )} - -

    Select a model preset

    -
    - - {modelInfo?.packages.map((pkg, idx) => { - return ( - { - if (disableModelCards()) return; - let formParams: any = {}; - for (const d of modelInfo.collectInputFor || []) { - const val = formMethods.watch(d.key); - if (val === "" || val === undefined || val === null) { - continue; - } - formParams = updatedObj(formParams, { - [d.key]: d.inputType === "text" ? val : parseFloat(val), - }); - } - - const model = { - ...pkg.params, - ...modelInfo.params, - ..._.merge( - {}, - ...(pkg.dimensions?.map((dimension, i) => { - if (!dimensionChoices?.[i]) return {}; - return { - ...dimension.options[dimensionChoices[i]], - }; - }) || []), - ), - ...formParams, - provider: modelInfo.provider, - }; - ideMessenger.post("config/addModel", { model }); - dispatch( - setDefaultModel({ title: model.title, force: true }), - ); - navigate("/"); - }} - /> - ); - })} - -
    -
    - ); -} - -export default ConfigureProvider; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index fafdc53b7..d21a7d66f 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -887,6 +887,48 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["gemini"], isOpenSource: false, }, + gemini20FlashLite: { + title: "Gemini 2.0 Flash Lite", + description: + "A more efficient version of Gemini 2.0 Flash optimized for faster responses and lower resource usage.", + params: { + title: "Gemini 2.0 Flash Lite", + model: "gemini-2.0-flash-lite", + contextLength: 1_048_576, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["gemini"], + isOpenSource: false, + }, + gemini20FlashImageGeneration: { + title: "Gemini 2.0 Flash Image Generation", + description: + "A version of Gemini 2.0 Flash optimized for image generation capabilities.", + params: { + title: "Gemini 2.0 Flash Image Generation", + model: "gemini-2.0-flash-exp-image-generation", + contextLength: 32_768, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["gemini"], + isOpenSource: false, + }, + gemini25ProExp: { + title: "Gemini 2.5 Pro Experimental", + description: + "Experimental version of Gemini 2.5 Pro with enhanced capabilities and larger output limits.", + params: { + title: "Gemini 2.5 Pro Experimental", + model: "gemini-2.5-pro-exp-03-25", + contextLength: 1_048_576, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["gemini"], + isOpenSource: false, + }, commandR: { title: "Command R", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 089ba74f9..43a3bbe4c 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -495,6 +495,9 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n ], packages: [ models.gemini20Flash, + models.gemini20FlashLite, + models.gemini20FlashImageGeneration, + models.gemini25ProExp, models.gemini15Pro, models.geminiPro, models.gemini15Flash, diff --git a/gui/src/pages/AddNewModel/index.ts b/gui/src/pages/AddNewModel/index.ts deleted file mode 100644 index fa5775f14..000000000 --- a/gui/src/pages/AddNewModel/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { default as AddNewModel } from "./AddNewModel"; -export { default as ConfigureProvider } from "./ConfigureProvider"; diff --git a/gui/src/pages/config-error/index.tsx b/gui/src/pages/config-error/index.tsx deleted file mode 100644 index 7bd3a3050..000000000 --- a/gui/src/pages/config-error/index.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { - ArrowLeftIcon, - ExclamationCircleIcon, - ExclamationTriangleIcon, -} from "@heroicons/react/24/outline"; -import { useNavigate } from "react-router-dom"; -import { vscBackground } from "../../components"; -import { useAppSelector } from "../../redux/hooks"; -import { ROUTES } from "../../util/navigation"; - -export default function ConfigErrorPage() { - const navigate = useNavigate(); - const configError = useAppSelector((state) => state.config.configError); - - const sortedErrors = configError - ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) - : []; - - return ( -
    -
    navigate(ROUTES.HOME)} - className="sticky top-0 m-0 flex cursor-pointer items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" - style={{ - backgroundColor: vscBackground, - }} - > - - Chat -
    - -
    -
    -

    Config Errors

    -

    - Please resolve the following errors in your assistant configuration. -

    -
    - {sortedErrors.length > 0 ? ( -
      - {sortedErrors.map((error, index) => ( -
    • - {error.fatal ? ( - - ) : ( - - )} -

      - - {error.fatal ? "Fatal Error:" : "Warning:"} - {" "} - {error.message} -

      -
    • - ))} -
    - ) : ( -

    - No configuration errors found. -

    - )} -
    -
    -
    -
    - ); -} diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 34dfe2f29..5c3d2e44f 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,5 +1,6 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; +import { useState } from "react"; import { SecondaryButton } from "../../components"; import { Popover, @@ -8,13 +9,14 @@ import { Transition, } from "../../components/ui"; import { useAuth } from "../../context/Auth"; -import { selectSelectedOrganization } from "../../redux"; +import { selectCurrentOrg } from "../../redux"; import { useAppSelector } from "../../redux/hooks"; import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { + const [open, setOpen] = useState(false); const { session, logout, login, organizations } = useAuth(); - const selectedOrg = useAppSelector(selectSelectedOrganization); + const selectedOrg = useAppSelector(selectCurrentOrg); if (!session) { return ( @@ -29,40 +31,44 @@ export function AccountButton() { return ( - -
    - - {selectedOrg === null ? "Personal" : selectedOrg.name} - - {" "} -
    -
    - - - -
    -
    - {session.account.label} - - {session.account.id} + {({ close }) => ( + <> + +
    + + {selectedOrg === null ? "Personal" : selectedOrg.name} + {" "}
    +
    - {organizations.length > 0 && ( -
    - - + + +
    +
    + {session.account.label} + + {session.account.id} + +
    + + {organizations.length > 0 && ( +
    + + +
    + )} + + + Sign out +
    - )} - - - Sign out - -
    - - + + + + )} ); } diff --git a/gui/src/pages/config/KeyboardShortcuts.tsx b/gui/src/pages/config/KeyboardShortcuts.tsx index 4ac0919c5..4456bf45c 100644 --- a/gui/src/pages/config/KeyboardShortcuts.tsx +++ b/gui/src/pages/config/KeyboardShortcuts.tsx @@ -1,192 +1,130 @@ import { useMemo } from "react"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscForeground, -} from "../../components"; -import { ToolTip } from "../../components/gui/Tooltip"; -import { getPlatform, isJetBrains } from "../../util"; - -const StyledKeyDiv = styled.div` - border: 0.5px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 2px; - color: ${vscForeground}; - - width: 16px; - height: 16px; - - display: flex; - justify-content: center; - align-items: center; -`; - -const keyToName: { [key: string]: string } = { - "⌘": "Cmd", - "⌃": "Ctrl", - "⇧": "Shift", - "⏎": "Enter", - "⌫": "Backspace", - "⌥": "Option", - "⎇": "Alt", -}; - -function KeyDiv({ text }: { text: string }) { - return ( - <> - - {text} - - - - {keyToName[text]} - - - ); -} +import Shortcut from "../../components/gui/Shortcut"; +import { isJetBrains } from "../../util"; interface KeyboardShortcutProps { - mac: string; - windows: string; + shortcut: string; description: string; + isEven: boolean; } function KeyboardShortcut(props: KeyboardShortcutProps) { - const shortcut = getPlatform() === "mac" ? props.mac : props.windows; return ( -
    - {props.description}: -
    - {shortcut.split(" ").map((key, i) => { - return ; - })} +
    +
    + {props.description}: +
    +
    + {props.shortcut}
    ); } -const vscodeShortcuts: KeyboardShortcutProps[] = [ +// Shortcut strings will be rendered correctly based on the platform by the Shortcut component +const vscodeShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ L", - windows: "⌃ L", + shortcut: "cmd L", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ L", - windows: "⌃ ⇧ L", + shortcut: "cmd shift L", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ R", - windows: "⌃ ⇧ R", + shortcut: "cmd shift R", description: "Debug Terminal", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⌘ N", - windows: "Alt ⌃ N", + shortcut: "alt cmd N", description: "Reject Top Change in Diff", }, { - mac: "⌥ ⌘ Y", - windows: "Alt ⌃ Y", + shortcut: "alt cmd Y", description: "Accept Top Change in Diff", }, { - mac: "⌘ K ⌘ A", - windows: "⌃ K ⌃ A", + shortcut: "cmd K cmd A", description: "Toggle Autocomplete Enabled", }, { - mac: "⌘ K ⌘ M", - windows: "⌃ K ⌃ M", + shortcut: "cmd K cmd M", description: "Toggle Full Screen", }, ]; -const jetbrainsShortcuts: KeyboardShortcutProps[] = [ +const jetbrainsShortcuts: Omit[] = [ { - mac: "⌘ '", - windows: "⌃ '", + shortcut: "cmd '", description: "Toggle Selected Model", }, { - mac: "⌘ I", - windows: "⌃ I", + shortcut: "cmd I", description: "Edit highlighted code", }, { - mac: "⌘ J", - windows: "⌃ J", + shortcut: "cmd J", description: "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⌫", - windows: "⌃ ⌫", + shortcut: "cmd backspace", description: "Cancel response", }, { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", + shortcut: "cmd shift I", description: "Toggle inline edit focus", }, { - mac: "⌘ ⇧ J", - windows: "⌃ ⇧ J", + shortcut: "cmd shift J", description: "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", + shortcut: "cmd shift backspace", description: "Reject Diff", }, { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", + shortcut: "cmd shift enter", description: "Accept Diff", }, { - mac: "⌥ ⇧ J", - windows: "Alt ⇧ J", + shortcut: "alt shift J", description: "Quick Input", }, { - mac: "⌥ ⌘ J", - windows: "Alt ⌃ J", + shortcut: "alt cmd J", description: "Toggle Sidebar", }, ]; @@ -197,16 +135,16 @@ function KeyboardShortcuts() { }, []); return ( -
    -

    Keyboard shortcuts

    -
    +
    +

    Keyboard shortcuts

    +
    {shortcuts.map((shortcut, i) => { return ( ); })} @@ -216,3 +154,4 @@ function KeyboardShortcuts() { } export default KeyboardShortcuts; + diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index cdc0d16d1..e3464a6f2 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -1,5 +1,12 @@ -import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/24/outline"; -import { type ModelDescription } from "core"; +import { + CheckIcon, + ChevronUpDownIcon, + Cog6ToothIcon, + CubeIcon, +} from "@heroicons/react/24/outline"; +import { ModelDescription } from "core"; +import { LLMConfigurationStatuses } from "core/llm/constants"; +import { MouseEvent, useContext, useState } from "react"; import { defaultBorderRadius } from "../../components"; import { ToolTip } from "../../components/gui/Tooltip"; import InfoHover from "../../components/InfoHover"; @@ -10,6 +17,7 @@ import { ListboxOptions, Transition, } from "../../components/ui"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { fontSize } from "../../util"; interface ModelRoleSelectorProps { @@ -27,10 +35,33 @@ const ModelRoleSelector = ({ displayName, description, }: ModelRoleSelectorProps) => { + const ideMessenger = useContext(IdeMessengerContext); + const [hoveredIdx, setHoveredIdx] = useState(null); + + const noConfiguredModels = models.every( + (model) => model.configurationStatus !== LLMConfigurationStatuses.VALID, + ); + function handleSelect(title: string | null) { onSelect(models.find((m) => m.title === title) ?? null); } + function onClickGear(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + ideMessenger.post("config/openProfile", { profileId: undefined }); + } + + function handleOptionClick( + showMissingApiKeyMsg: boolean, + e: MouseEvent, + ) { + if (showMissingApiKeyMsg) { + e.preventDefault(); + e.stopPropagation(); + } + } + return ( <>
    @@ -52,8 +83,14 @@ const ModelRoleSelector = ({ disabled={models.length === 0} className={`bg-vsc-editor-background hover:bg-list-active hover:text-list-active-foreground w-full justify-between`} > - {models.length === 0 ? ( - {`No ${displayName} models${["Chat", "Apply", "Edit"].includes(displayName) ? ". Using chat model" : ""}`} + {models.length === 0 || noConfiguredModels ? ( + + {`No ${models.length === 0 ? "" : "valid "}${displayName} models${ + ["Chat", "Apply", "Edit"].includes(displayName) + ? ". Using Chat model" + : "" + }`} + ) : ( {selectedModel?.title ?? `Select ${displayName} model`} @@ -71,19 +108,55 @@ const ModelRoleSelector = ({ style={{ borderRadius: defaultBorderRadius }} className="min-w-40" > - {models.map((option, idx) => ( - - { + const showMissingApiKeyMsg = + option.configurationStatus === + LLMConfigurationStatuses.MISSING_API_KEY; + + return ( + setHoveredIdx(idx)} + onMouseLeave={() => setHoveredIdx(null)} + onClick={(e: any) => + handleOptionClick(showMissingApiKeyMsg, e) + } + className={""} > - {option.title} - - {option.title === selectedModel?.title && ( - - ))} +
    +
    +
    + + + {option.title} + {showMissingApiKeyMsg && ( + + (Missing API key) + + )} + +
    +
    + {hoveredIdx === idx && ( + + )} + {option.title === selectedModel?.title && ( + + )} +
    +
    +
    + + ); + })}
    diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 311f78d98..ee3bdd42f 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -3,6 +3,7 @@ import { ChevronUpDownIcon, } from "@heroicons/react/24/outline"; import { UserCircleIcon } from "@heroicons/react/24/solid"; +import { useContext } from "react"; import { Listbox, ListboxButton, @@ -10,30 +11,39 @@ import { ListboxOptions, } from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { selectOrgThunk } from "../../redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + selectCurrentOrg, + setSelectedOrgId, +} from "../../redux/slices/profiles/slice"; -export function ScopeSelect() { - const { organizations, selectedOrganization } = useAuth(); +interface ScopeSelectProps { + onSelect?: () => void; +} +export function ScopeSelect({ onSelect }: ScopeSelectProps) { + const { organizations } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( - (state) => state.organizations.selectedOrganizationId, + (state) => state.profiles.selectedOrganizationId, ); + const currentOrg = useAppSelector(selectCurrentOrg); const dispatch = useAppDispatch(); - const handleChange = (newValue: string | null) => { - dispatch(selectOrgThunk(newValue)); + const handleChange = (newValue: string) => { + // optimisitic update + dispatch(setSelectedOrgId(newValue)); + ideMessenger.post("didChangeSelectedOrg", { + id: newValue, + }); + onSelect?.(); }; - useWebviewListener("didSelectOrganization", async (data) => { - handleChange(data.orgId); - }); - const CurScopeEntityFallBackIcon = selectedOrgId ? BuildingOfficeIcon : UserCircleIcon; - const selectedDisplay = selectedOrganization ?? { + const selectedDisplay = currentOrg ?? { name: "Personal", iconUrl: null, }; @@ -68,17 +78,6 @@ export function ScopeSelect() {
    ))} - - {!!organizations.length && ( -
    - )} - - -
    - - Personal -
    -
    diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index d9efc4c49..152d701ae 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -17,7 +17,7 @@ import { getFontSize } from "../../util"; export function UserSettingsForm() { /////// User settings section ////// const dispatch = useAppDispatch(); - const { selectedProfile, controlServerBetaEnabled } = useAuth(); + const { controlServerBetaEnabled } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); @@ -101,55 +101,69 @@ export function UserSettingsForm() { }, [ideMessenger]); return ( -
    +
    + {/* {selectedProfile && isLocalProfile(selectedProfile) ? ( +
    + { + ideMessenger.post("config/openProfile", { + profileId: selectedProfile.id, + }); + }} + > + Open + Config + File + +
    + ) : null} */} {!controlServerBetaEnabled || hubEnabled ? ( -
    -
    -
    -
    -

    User settings

    -
    +
    +
    +

    User settings

    +
    -
    - - handleUpdate({ - showSessionTabs: !showSessionTabs, - }) - } - text="Show Session Tabs" - /> - - handleUpdate({ - codeWrap: !codeWrap, - }) - } - text="Wrap Codeblocks" - /> +
    + + handleUpdate({ + showSessionTabs: !showSessionTabs, + }) + } + text="Show Session Tabs" + /> + + handleUpdate({ + codeWrap: !codeWrap, + }) + } + text="Wrap Codeblocks" + /> - - handleUpdate({ - showChatScrollbar: !showChatScrollbar, - }) - } - text="Show Chat Scrollbar" - /> - - handleUpdate({ - readResponseTTS: !readResponseTTS, - }) - } - text="Text-to-Speech Output" - /> + + handleUpdate({ + showChatScrollbar: !showChatScrollbar, + }) + } + text="Show Chat Scrollbar" + /> + + handleUpdate({ + readResponseTTS: !readResponseTTS, + }) + } + text="Text-to-Speech Output" + /> - {/* handleUpdate({ @@ -158,46 +172,46 @@ export function UserSettingsForm() { } text="Use Chromium for Docs Crawling" /> */} - - handleUpdate({ - disableSessionTitles: !disableSessionTitles, - }) - } - text="Enable Session Titles" - /> - - handleUpdate({ - displayRawMarkdown: !displayRawMarkdown, - }) - } - text="Format Markdown" - /> + + handleUpdate({ + disableSessionTitles: !disableSessionTitles, + }) + } + text="Enable Session Titles" + /> + + handleUpdate({ + displayRawMarkdown: !displayRawMarkdown, + }) + } + text="Format Markdown" + /> - - handleUpdate({ - allowAnonymousTelemetry: !allowAnonymousTelemetry, - }) - } - text="Allow Anonymous Telemetry" - /> + + handleUpdate({ + allowAnonymousTelemetry: !allowAnonymousTelemetry, + }) + } + text="Allow Anonymous Telemetry" + /> - - handleUpdate({ - disableIndexing: !disableIndexing, - }) - } - text="Enable Indexing" - /> + + handleUpdate({ + disableIndexing: !disableIndexing, + }) + } + text="Enable Indexing" + /> - {/* handleUpdate({ @@ -207,89 +221,86 @@ export function UserSettingsForm() { text="Use Autocomplete Cache" /> */} -
    ) : null} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 05c1f2c47..40db6fd8c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -21,7 +21,7 @@ import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; @@ -31,7 +31,7 @@ import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { submitEdit } from "../../redux/slices/editModeState"; import { newSession, @@ -54,7 +54,6 @@ import { } from "../../util/freeTrial"; import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; -import ConfigErrorIndicator from "./ConfigError"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; @@ -75,6 +74,8 @@ const StepsDiv = styled.div` } `; +export const MAIN_EDITOR_INPUT_ID = "main-editor-input"; + function fallbackRender({ error, resetErrorBoundary }: any) { // Call resetErrorBoundary() to reset the error boundary and retry the render. @@ -103,7 +104,7 @@ export function Chat() { const showSessionTabs = useAppSelector( (store) => store.config.config.ui?.showSessionTabs, ); - const defaultModel = useAppSelector(selectDefaultModel); + const selectedChatModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); @@ -163,7 +164,7 @@ export function Chat() { "Cannot submit message while awaiting tool confirmation", ); } - if (defaultModel?.provider === "free-trial") { + if (selectedChatModel?.provider === "free-trial") { const newCount = incrementFreeTrialCount(); if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { @@ -222,7 +223,7 @@ export function Chat() { }, [ history, - defaultModel, + selectedChatModel, streamResponse, isSingleRangeEditOrInsertion, codeToEdit, @@ -231,11 +232,12 @@ export function Chat() { ); async function handleSingleRangeEditOrInsertion(editorState: JSONContent) { - if (!defaultModel) { + if (!selectedChatModel) { console.error("No selected chat model"); return; } - const [contextItems, __, userInstructions] = await resolveEditorContent({ + + const [contextItems, __, userInstructions, _] = await resolveEditorContent({ editorState, modifiers: { noContext: true, @@ -243,8 +245,9 @@ export function Chat() { }, ideMessenger, defaultContextProviders: [], + availableSlashCommands: [], dispatch, - selectedModelTitle: defaultModel.title, + selectedModelTitle: selectedChatModel.title, }); const prompt = [ @@ -255,7 +258,6 @@ export function Chat() { ideMessenger.post("edit/sendPrompt", { prompt, range: codeToEdit[0] as RangeInFileWithContents, - selectedModelTitle: defaultModel.title, }); dispatch(submitEdit(prompt)); @@ -293,7 +295,7 @@ export function Chat() { 0 ? "flex-1" : ""}`} + className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} > {highlights} {history.map((item, index: number) => ( @@ -404,7 +406,7 @@ export function Chat() { onEnter={(editorState, modifiers, editor) => sendInput(editorState, modifiers, undefined, editor) } - inputId={"main-editor"} + inputId={MAIN_EDITOR_INPUT_ID} /> )} @@ -433,7 +435,6 @@ export function Chat() {
    )}
    -
    {hasPendingApplies && isSingleRangeEditOrInsertion && ( diff --git a/gui/src/pages/gui/ConfigError.tsx b/gui/src/pages/gui/ConfigError.tsx index 8bab2c3c9..ee85046f1 100644 --- a/gui/src/pages/gui/ConfigError.tsx +++ b/gui/src/pages/gui/ConfigError.tsx @@ -1,8 +1,8 @@ +import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; import { useLocation, useNavigate } from "react-router-dom"; import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; -import { ROUTES } from "../../util/navigation"; -import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; +import { ROUTES } from "../../util/navigation"; const ConfigErrorIndicator = () => { const configError = useAppSelector((store) => store.config.configError); @@ -25,7 +25,7 @@ const ConfigErrorIndicator = () => { text="Config error" onClick={onClickError} > - + ); }; diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 389528cd0..35fe3dc91 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -9,7 +9,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; -import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { isLocalProfile } from "../../util"; import { providers } from "../AddNewModel/configs/providers"; @@ -20,7 +20,7 @@ interface StreamErrorProps { const StreamErrorDialog = ({ error }: StreamErrorProps) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const selectedModel = useAppSelector(selectDefaultModel); + const selectedModel = useAppSelector(selectSelectedChatModel); const hubEnabled = useAppSelector(selectUseHub); const selectedProfile = useAppSelector(selectSelectedProfile); const { session, refreshProfiles } = useAuth(); diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index bca805f45..e3b0002e1 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -7,9 +7,13 @@ interface CreateFileToolCallProps { } export function CreateFile(props: CreateFileToolCallProps) { - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "test.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; return props.relativeFilepath ? ( - + ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx new file mode 100644 index 000000000..f1592a7fe --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -0,0 +1,54 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import { useMemo } from "react"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import { useAppSelector } from "../../../redux/hooks"; + +type EditToolCallProps = { + relativeFilePath: string; + newContents: string; + toolCallId?: string; +}; + +export function EditFile(props: EditToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const states = useAppSelector((store) => store.session.codeBlockApplyStates); + + const applyState = useMemo(() => { + return states.states.find( + (state) => state.toolCallId && state.toolCallId === props.toolCallId, + ); + }, [states, props.toolCallId]); + + if (!props.relativeFilePath) { + return null; + } + + return ( + <> + + {/* TODO better indicator of generation at bottom */} + {/* {isStreaming && applyState?.status === "streaming" && ( +
    + Generating... +
    + )} */} + {!isStreaming && applyState?.status === "done" && ( +
    + {}} + /> +
    + )} + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 52b41f505..55ed79e2a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,5 +1,7 @@ -import { ToolCall, ToolCallDelta, ToolCallState } from "core"; +import { ToolCallDelta, ToolCallState } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { CreateFile } from "./CreateFile"; +import { EditFile } from "./EditFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -12,14 +14,22 @@ function FunctionSpecificToolCallDiv({ const args = toolCallState.parsedArgs; switch (toolCall.function?.name) { - case "builtin_create_new_file": + case BuiltInToolNames.CreateNewFile: return ( ); - case "builtin_run_terminal_command": + case BuiltInToolNames.EditExistingFile: + return ( + + ); + case BuiltInToolNames.RunTerminalCommand: return ( ); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 47868cfc8..3fc0fb206 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -54,7 +54,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) { Mustache.render(tool.isCurrently, props.toolCallState.parsedArgs) ) : ( <> - using the {defaultToolDescription} + calling the {defaultToolDescription} ); } else if (props.toolCallState.status === "done") { @@ -130,7 +130,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) { {args.map(([key, value]) => (
    {key}: - {value} + {value.toString()}
    ))}
    diff --git a/gui/src/pages/gui/index.tsx b/gui/src/pages/gui/index.tsx index 788d88b23..0550d27f2 100644 --- a/gui/src/pages/gui/index.tsx +++ b/gui/src/pages/gui/index.tsx @@ -3,8 +3,8 @@ import { Chat } from "./Chat"; export default function GUI() { return ( -
    -