diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index a52daa05b..192ebb612 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -110,6 +110,6 @@ jobs: # Create GitHub release gh release create "v${{ steps.get_version.outputs.beta_version }}" \ - --title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \ + --title "CLI Beta Release v${{ steps.get_version.outputs.beta_version }}" \ --notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \ --prerelease diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 2a1819fa5..7e44fff65 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -119,12 +119,12 @@ jobs: run: npm audit --audit-level=moderate - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: javascript - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 # Use this for any files that we want to be certain exist # Basically creates a forcing function to discuss were anyone to want to remove them diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 0d5e317c3..7efead1fb 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -1,6 +1,9 @@ name: Continue General Review on: + push: + branches: + - nate/fix-wf pull_request: types: [opened, ready_for_review] issue_comment: diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 6ed9292b7..9c33c822c 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -116,7 +116,7 @@ jobs: # Validate wrapper - name: Gradle Wrapper Validation - uses: gradle/actions/wrapper-validation@v3 + uses: gradle/actions/wrapper-validation@v5 # # Set up Java environment for the next steps - name: Setup Java @@ -127,7 +127,7 @@ jobs: # # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true @@ -444,7 +444,7 @@ jobs: # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true @@ -522,7 +522,7 @@ jobs: # Setup Gradle - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v5 with: gradle-home-cache-cleanup: true diff --git a/.github/workflows/run-continue-agent.yml b/.github/workflows/run-continue-agent.yml new file mode 100644 index 000000000..fcc49903b --- /dev/null +++ b/.github/workflows/run-continue-agent.yml @@ -0,0 +1,41 @@ +name: Run Continue Agent + +on: + workflow_call: + inputs: + prompt: + description: "The prompt to send to the Continue agent" + required: true + type: string + agent: + description: "The agent to use (e.g., continuedev/default-background-agent)" + required: false + type: string + default: "continuedev/default-background-agent" + branch_name: + description: "The base branch name to work from" + required: false + type: string + default: "main" + secrets: + CONTINUE_API_KEY: + required: true + +jobs: + run-agent: + runs-on: ubuntu-latest + + steps: + - name: Call agents endpoint + run: | + response=$(curl -f -X POST https://api.continue.dev/agents \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer ${{ secrets.CONTINUE_API_KEY }}" \ + -d '{ + "prompt": "${{ inputs.prompt }}", + "agent": "${{ inputs.agent }}", + "branchName": "${{ inputs.branch_name }}", + "repoUrl": "https://github.com/${{ github.repository }}" + }') + id=$(echo $response | jq -r '.id') + echo "https://hub.continue.dev/agents/$id" diff --git a/.github/workflows/runloop-blueprint-template.json b/.github/workflows/runloop-blueprint-template.json index d0fcf57c1..d1626d81f 100644 --- a/.github/workflows/runloop-blueprint-template.json +++ b/.github/workflows/runloop-blueprint-template.json @@ -3,6 +3,8 @@ "system_setup_commands": [ "npm i -g @continuedev/cli@latest", "sudo apt update", - "sudo apt install -y ripgrep" + "sudo apt install -y ripgrep", + "sudo apt install asciinema", + "sudo apt install expect" ] } diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index 6c02f1f17..c24abf8f8 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -208,7 +208,7 @@ jobs: # Create GitHub release gh release create "v${{ steps.final_version.outputs.stable_version }}" \ - --title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \ + --title "CLI Stable Release v${{ steps.final_version.outputs.stable_version }}" \ --notes "${{ steps.final_version.outputs.release_notes }}" \ --latest diff --git a/.github/workflows/submit-github-dependency-graph.yml b/.github/workflows/submit-github-dependency-graph.yml index 08373c66a..b647c6557 100644 --- a/.github/workflows/submit-github-dependency-graph.yml +++ b/.github/workflows/submit-github-dependency-graph.yml @@ -19,7 +19,7 @@ jobs: distribution: "temurin" java-version: 17 - name: Generate and submit dependency graph - uses: gradle/actions/dependency-submission@v4 + uses: gradle/actions/dependency-submission@v5 with: # The gradle project is not in the root of the repository. build-root-directory: extensions/intellij diff --git a/.github/workflows/tidy-up-codebase.yml b/.github/workflows/tidy-up-codebase.yml new file mode 100644 index 000000000..a6fa6c688 --- /dev/null +++ b/.github/workflows/tidy-up-codebase.yml @@ -0,0 +1,17 @@ +name: Weekly CN Task + +on: + schedule: + # Runs at 8/9:30 AM PST (16:30 UTC) every Monday so PR shows up at beginning of week + - cron: "30 16 * * 1" + workflow_dispatch: # Allows manual triggering + +jobs: + run-cn-task: + uses: ./.github/workflows/run-continue-agent.yml + with: + prompt: "Review every Markdown documentation file and verify that descriptions, examples, or behavior outlines accurately reflect the current code. Only update documentation; do not modify code. Check the corresponding code to confirm behavior before making changes. Correct any inaccuracies or outdated information in descriptions, examples, or behavior outlines. Preserve existing Markdown formatting, style, and structure. Do not add new sections, speculative explanations, or details not present in the code. Only update statements that are clearly incorrect or misleading; do not rewrite text for style or preference. Keep edits minimal and focused, ensuring that the Markdown matches what the code actually does. If verification against the code is ambiguous, leave the documentation unchanged. Use branch name bot/cleanup--" + agent: continuedev/default-background-agent + branch_name: main + secrets: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} diff --git a/.github/workflows/vscode-prerelease.yml b/.github/workflows/vscode-prerelease.yml new file mode 100644 index 000000000..a2c4b8208 --- /dev/null +++ b/.github/workflows/vscode-prerelease.yml @@ -0,0 +1,231 @@ +name: VSCode Pre-release + +on: + workflow_dispatch: + inputs: + main_commit_sha: + description: "Main branch commit SHA to create pre-release from - leave empty to use HEAD of main" + required: false + type: string + prerelease_version: + description: "New pre-release version (e.g., 1.3.15) - leave empty to auto-increment" + required: false + type: string + +permissions: + contents: write + pull-requests: write + +jobs: + create-prerelease: + name: Create VSCode Pre-release + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + ref: ${{ inputs.main_commit_sha || 'main' }} + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: 20 + + - name: Determine version numbers + id: version + working-directory: extensions/vscode + run: | + # Get current version from package.json + CURRENT_VERSION=$(node -p "require('./package.json').version") + echo "Current version in package.json: $CURRENT_VERSION" + + # Determine new pre-release version + if [[ -n "${{ inputs.prerelease_version }}" ]]; then + NEW_VERSION="${{ inputs.prerelease_version }}" + echo "Using manually specified new version: $NEW_VERSION" + else + # Auto-increment patch version + IFS='.' read -r major minor patch <<< "$CURRENT_VERSION" + NEW_PATCH=$((patch + 1)) + NEW_VERSION="${major}.${minor}.${NEW_PATCH}" + echo "Auto-incremented version: $NEW_VERSION" + fi + + TAG_NAME="v${NEW_VERSION}-vscode" + + echo "previous_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT + echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT + echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT + + echo "Summary:" + echo " Previous version: $CURRENT_VERSION" + echo " New version: $NEW_VERSION" + echo " Tag name: $TAG_NAME" + + - name: Create pre-release branch + id: branch + run: | + BRANCH_NAME="prerelease/vscode-${{ steps.version.outputs.new_version }}" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT + + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git checkout -b "$BRANCH_NAME" + echo "Created branch: $BRANCH_NAME" + + - name: Update package.json version + working-directory: extensions/vscode + run: | + # Update version in package.json + npm version ${{ steps.version.outputs.new_version }} --no-git-tag-version + + echo "Updated package.json to version ${{ steps.version.outputs.new_version }}" + + - name: Commit version bump + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git add extensions/vscode/package.json + git commit -m "chore: bump VSCode extension version to ${{ steps.version.outputs.new_version }}" + + echo "Committed version bump" + + - name: Push branch and create PR + id: pr + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git push origin "${{ steps.branch.outputs.branch_name }}" + echo "Pushed branch: ${{ steps.branch.outputs.branch_name }}" + + # Create pull request + PR_URL=$(gh pr create \ + --base main \ + --head "${{ steps.branch.outputs.branch_name }}" \ + --title "chore: VSCode pre-release ${{ steps.version.outputs.new_version }}" \ + --body "$(cat <<'EOF' + ## VSCode Pre-release ${{ steps.version.outputs.new_version }} + + This PR bumps the VSCode extension version for pre-release. + + ### Changes + - Version bumped from ${{ steps.version.outputs.previous_version }} to ${{ steps.version.outputs.new_version }} + - Based on commit: ${{ inputs.main_commit_sha }} + + ### Release Process + After merging this PR: + 1. The tag \`${{ steps.version.outputs.tag_name }}\` will be created automatically + 2. A GitHub pre-release will be created with auto-generated release notes + + 🤖 This PR was created automatically by the VSCode Pre-release workflow. + EOF + )") + + echo "pr_url=$PR_URL" >> $GITHUB_OUTPUT + echo "Created PR: $PR_URL" + + - name: Auto-merge PR + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Get PR number from URL + PR_NUMBER=$(echo "${{ steps.pr.outputs.pr_url }}" | grep -oE '[0-9]+$') + + # Merge the PR + gh pr merge "$PR_NUMBER" --squash --auto + + echo "PR #$PR_NUMBER set to auto-merge" + + # Wait for merge to complete (with timeout) + echo "Waiting for PR to be merged..." + TIMEOUT=300 # 5 minutes + ELAPSED=0 + INTERVAL=10 + + while [ $ELAPSED -lt $TIMEOUT ]; do + PR_STATE=$(gh pr view "$PR_NUMBER" --json state --jq '.state') + if [ "$PR_STATE" = "MERGED" ]; then + echo "PR successfully merged!" + break + fi + sleep $INTERVAL + ELAPSED=$((ELAPSED + INTERVAL)) + echo "Still waiting... ($ELAPSED seconds elapsed)" + done + + if [ $ELAPSED -ge $TIMEOUT ]; then + echo "Warning: Timed out waiting for PR merge. Please check manually." && exit 1 + fi + + - name: Checkout main branch + run: | + git fetch origin main + git checkout main + git pull origin main + + - name: Create and push tag + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + git tag "${{ steps.version.outputs.tag_name }}" + git push origin "${{ steps.version.outputs.tag_name }}" + + echo "Created and pushed tag: ${{ steps.version.outputs.tag_name }}" + + - name: Get previous tag for release notes + id: prev_tag + run: | + # Find the previous vscode pre-release tag + PREV_TAG=$(git tag -l "v*-vscode" --sort=-version:refname | head -n 2 | tail -n 1) + + if [ -z "$PREV_TAG" ]; then + echo "No previous tag found, using first commit" + PREV_TAG=$(git rev-list --max-parents=0 HEAD) + fi + + echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT + echo "Previous tag for release notes: $PREV_TAG" + + - name: Create GitHub pre-release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Generate release notes between previous tag and current tag + RELEASE_NOTES=$(gh api \ + --method POST \ + -H "Accept: application/vnd.github+json" \ + /repos/${{ github.repository }}/releases/generate-notes \ + -f tag_name="${{ steps.version.outputs.tag_name }}" \ + -f target_commitish="main" \ + -f previous_tag_name="${{ steps.prev_tag.outputs.prev_tag }}" \ + --jq '.body') + + # Create the pre-release + gh release create "${{ steps.version.outputs.tag_name }}" \ + --title "VSCode Pre-release ${{ steps.version.outputs.new_version }}" \ + --notes "$RELEASE_NOTES" \ + --prerelease \ + --target main + + echo "Created pre-release: ${{ steps.version.outputs.tag_name }}" + + - name: Summary + run: | + echo "## VSCode Pre-release Created Successfully! 🚀" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Version Information" >> $GITHUB_STEP_SUMMARY + echo "- **Previous Version:** ${{ steps.version.outputs.previous_version }}" >> $GITHUB_STEP_SUMMARY + echo "- **New Version:** ${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY + echo "- **Tag:** \`${{ steps.version.outputs.tag_name }}\`" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Links" >> $GITHUB_STEP_SUMMARY + echo "- **PR:** ${{ steps.pr.outputs.pr_url }}" >> $GITHUB_STEP_SUMMARY + echo "- **Release:** https://github.com/${{ github.repository }}/releases/tag/${{ steps.version.outputs.tag_name }}" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Commit" >> $GITHUB_STEP_SUMMARY + echo "- **Base Commit:** \`${{ inputs.main_commit_sha }}\`" >> $GITHUB_STEP_SUMMARY diff --git a/.vscode/settings.json b/.vscode/settings.json index 9f3f17f98..0e2cdfd7e 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -23,6 +23,7 @@ "binary/build/**": true, "binary/out/**": true, "binary/tmp/**": true, + "core/dist/**": true, "core/edit/lazy/test-examples/**": true, "core/llm/llamaTokenizer.js": true, "core/llm/llamaTokenizer.mjs": true, diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index 3fdb433c3..0e0387c6f 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -170,62 +170,11 @@ runs: PR_NUMBER="${{ github.event.issue.number }}" fi - # Get PR diff - gh pr diff $PR_NUMBER > pr_diff.txt - - # Get PR details - PR_TITLE=$(gh pr view $PR_NUMBER --json title -q .title) - PR_AUTHOR=$(gh pr view $PR_NUMBER --json author -q .author.login) - PR_BODY=$(gh pr view $PR_NUMBER --json body -q .body) - FILES_CHANGED=$(gh pr view $PR_NUMBER --json files -q '.files | length') - - # Create review prompt - cat > review_prompt.txt << EOF - You are reviewing a pull request. Please provide helpful, context-aware feedback. - - CONTEXT: - - Repository: ${{ github.repository }} - - PR #$PR_NUMBER: $PR_TITLE - - Files Changed: $FILES_CHANGED - - Author: $PR_AUTHOR - - REVIEW APPROACH: - 1. First, understand what this PR is trying to accomplish - 2. Check if similar patterns exist elsewhere in the codebase - 3. Focus on actual issues that affect functionality - 4. Be constructive and suggest solutions when possible - - FOCUS ON: - - Bugs that will cause failures or incorrect behavior - - Security vulnerabilities (exposed secrets, injection risks) - - Breaking changes that affect other parts of the system - - Performance issues with real impact (memory leaks, O(n²) algorithms) - - Missing tests for new features or bug fixes - - Missing documentation for APIs or complex logic - - SKIP COMMENTING ON: - - Style and formatting (handled by linters) - - Alternative approaches unless current is broken - - Minor naming unless genuinely confusing - - Trivial documentation for self-explanatory code - - Be specific with line numbers and explain why something is an issue. - - PR Description: ${PR_BODY:-No description provided} - - Code Changes: - EOF - - # Add the diff - cat pr_diff.txt >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' - - Your Review: - Please provide constructive feedback on the code changes. - Focus on issues that matter for functionality, security, and maintainability. - If the code looks good overall, acknowledge that while noting any minor suggestions. - EOF + # Gather PR context and build prompt without heredocs + gh pr diff "$PR_NUMBER" > pr_diff.txt + gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json + node actions/general-review/scripts/buildPrompt.js "$PR_NUMBER" + rm -f pr_data.json - name: Run Continue CLI Review if: env.SHOULD_RUN == 'true' @@ -247,15 +196,7 @@ runs: if [ -z "$CONTINUE_API_KEY" ]; then echo "Warning: CONTINUE_API_KEY environment variable is not set" # Create fallback review and continue - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: CONTINUE_API_KEY not configured. - - ### Configuration Required - - Please set the CONTINUE_API_KEY secret in repository settings - - Verify that the organization and config path are valid - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md missing_api_key echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "SKIP_CLI=false" >> $GITHUB_ENV @@ -277,15 +218,7 @@ runs: echo "Testing Continue CLI..." if ! which cn > /dev/null 2>&1; then echo "Warning: Continue CLI not found or not working" - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: Continue CLI installation failed. - - ### Troubleshooting - - Check that npm installation succeeded - - Verify @continuedev/cli package is available - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md cli_install_failed echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "Continue CLI found at: $(which cn)" @@ -321,11 +254,7 @@ runs: # Check if output is empty if [ ! -s code_review.md ]; then echo "Warning: Continue CLI returned empty output" - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue CLI returned an empty response. Please check the configuration. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md empty_output fi else echo "Error: Continue CLI command failed with exit code $?" @@ -334,34 +263,13 @@ runs: # Check for specific error patterns if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md cli_not_found elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md config_error elif grep -q "api\|auth" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error else - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review failed. Please check the Continue API key and configuration. - - ### Troubleshooting - - Verify the CONTINUE_API_KEY secret is set correctly - - Check that the organization and config path are valid - - Ensure the Continue service is accessible - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure fi fi diff --git a/actions/general-review/scripts/buildPrompt.js b/actions/general-review/scripts/buildPrompt.js new file mode 100644 index 000000000..2f454d144 --- /dev/null +++ b/actions/general-review/scripts/buildPrompt.js @@ -0,0 +1,94 @@ +const fs = require("fs"); +const path = require("path"); + +function main() { + const prNumber = process.argv[2]; + if (!prNumber) { + console.error( + "buildPrompt.js requires the PR number as the first argument", + ); + process.exit(1); + } + + const prDataPath = path.resolve(process.cwd(), "pr_data.json"); + const prDiffPath = path.resolve(process.cwd(), "pr_diff.txt"); + const outputPath = path.resolve(process.cwd(), "review_prompt.txt"); + + if (!fs.existsSync(prDataPath)) { + console.error(`Missing PR metadata file: ${prDataPath}`); + process.exit(1); + } + + if (!fs.existsSync(prDiffPath)) { + console.error(`Missing PR diff file: ${prDiffPath}`); + process.exit(1); + } + + const repo = process.env.GITHUB_REPOSITORY || "unknown-repo"; + let prData; + + try { + prData = JSON.parse(fs.readFileSync(prDataPath, "utf8")); + } catch (error) { + console.error("Failed to parse PR metadata JSON:", error); + process.exit(1); + } + + const filesChanged = Array.isArray(prData.files) ? prData.files.length : 0; + const authorLogin = prData.author?.login || "unknown-author"; + const title = prData.title || "Untitled"; + const prBody = + prData.body && prData.body.trim() + ? prData.body.trim() + : "No description provided"; + const diff = fs.readFileSync(prDiffPath, "utf8"); + + const promptSections = [ + "You are reviewing a pull request. Please provide helpful, context-aware feedback.", + "", + "CONTEXT:", + `- Repository: ${repo}`, + `- PR #${prNumber}: ${title}`, + `- Files Changed: ${filesChanged}`, + `- Author: ${authorLogin}`, + "", + "REVIEW APPROACH:", + "1. First, understand what this PR is trying to accomplish", + "2. Check if similar patterns exist elsewhere in the codebase", + "3. Focus on actual issues that affect functionality", + "4. Be constructive and suggest solutions when possible", + "", + "FOCUS ON:", + "- Bugs that will cause failures or incorrect behavior", + "- Security vulnerabilities (exposed secrets, injection risks)", + "- Breaking changes that affect other parts of the system", + "- Performance issues with real impact (memory leaks, O(n²) algorithms)", + "- Missing tests for new features or bug fixes", + "- Missing documentation for APIs or complex logic", + "", + "SKIP COMMENTING ON:", + "- Style and formatting (handled by linters)", + "- Alternative approaches unless current is broken", + "- Minor naming unless genuinely confusing", + "- Trivial documentation for self-explanatory code", + "", + "Be specific with line numbers and explain why something is an issue.", + "", + `PR Description: ${prBody}`, + "", + "Code Changes:", + diff.trimEnd(), + "", + "Your Review:", + "Please provide constructive feedback on the code changes.", + "Focus on issues that matter for functionality, security, and maintainability.", + "If the code looks good overall, acknowledge that while noting any minor suggestions.", + ]; + + const prompt = `${promptSections.join("\n")}\n`; + + fs.writeFileSync(outputPath, prompt, "utf8"); + console.log(`Wrote review prompt to ${outputPath}`); +} + +main(); diff --git a/actions/general-review/scripts/writeMarkdown.js b/actions/general-review/scripts/writeMarkdown.js new file mode 100644 index 000000000..8ada50bbd --- /dev/null +++ b/actions/general-review/scripts/writeMarkdown.js @@ -0,0 +1,68 @@ +const fs = require("fs"); +const path = require("path"); + +const messages = { + missing_api_key: `## Code Review Summary + +⚠️ AI review skipped: CONTINUE_API_KEY not configured. + +### Configuration Required +- Please set the CONTINUE_API_KEY secret in repository settings +- Verify that the organization and config path are valid +`, + cli_install_failed: `## Code Review Summary + +⚠️ AI review skipped: Continue CLI installation failed. + +### Troubleshooting +- Check that npm installation succeeded +- Verify @continuedev/cli package is available +`, + empty_output: `## Code Review Summary + +⚠️ Continue CLI returned an empty response. Please check the configuration. +`, + cli_not_found: `## Code Review Summary + +⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally. +`, + config_error: `## Code Review Summary + +⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub. +`, + auth_error: `## Code Review Summary + +⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY. +`, + generic_failure: `## Code Review Summary + +⚠️ AI review failed. Please check the Continue API key and configuration. + +### Troubleshooting +- Verify the CONTINUE_API_KEY secret is set correctly +- Check that the organization and config path are valid +- Ensure the Continue service is accessible +`, +}; + +function main() { + const [outputPath, messageKey] = process.argv.slice(2); + + if (!outputPath || !messageKey) { + console.error("Usage: node writeMarkdown.js "); + process.exit(1); + } + + const message = messages[messageKey]; + + if (!message) { + console.error(`Unknown message key: ${messageKey}`); + process.exit(1); + } + + const absolutePath = path.resolve(process.cwd(), outputPath); + fs.writeFileSync(absolutePath, message, "utf8"); + console.log(`Wrote ${messageKey} message to ${absolutePath}`); +} + +main(); diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 6deb9d132..5001a6203 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -268,6 +268,8 @@ export class CompletionProvider { gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), timestamp: new Date().toISOString(), + profileType: + this.configHandler.currentProfile?.profileDescription.profileType, ...helper.options, }; diff --git a/core/autocomplete/postprocessing/index.test.ts b/core/autocomplete/postprocessing/index.test.ts new file mode 100644 index 000000000..e0314b5d1 --- /dev/null +++ b/core/autocomplete/postprocessing/index.test.ts @@ -0,0 +1,118 @@ +import { postprocessCompletion } from "./index"; + +describe("postprocessCompletion - removeBackticks", () => { + const mockLLM = { model: "test-model" } as any; + + it("should remove first line starting with ``` and last line that is ```", () => { + const completion = + "```typescript\nfunction hello() {\n return 'world';\n}\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("function hello() {\n return 'world';\n}"); + }); + + it("should remove only first line if it starts with ```", () => { + const completion = "```javascript\nconst x = 5;\nconsole.log(x);"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5;\nconsole.log(x);"); + }); + + it("should remove only last line if it is ```", () => { + const completion = "const y = 10;\nconsole.log(y);\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const y = 10;\nconsole.log(y);"); + }); + + it("should not modify completion without backticks", () => { + const completion = "function test() {\n return true;\n}"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("function test() {\n return true;\n}"); + }); + + it("should handle completion with backticks in the middle", () => { + const completion = "const str = `template ${literal}`;\nconsole.log(str);"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe( + "const str = `template ${literal}`;\nconsole.log(str);", + ); + }); + + it("should handle first line with leading whitespace before ```", () => { + const completion = " ```python\ndef hello():\n pass\n```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("def hello():\n pass"); + }); + + it("should handle last line with whitespace around ```", () => { + const completion = "```\ncode here\n ``` "; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("code here"); + }); + + it("should handle single line completion", () => { + const completion = "const x = 5;"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5;"); + }); + + it("should handle empty completion", () => { + const completion = ""; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBeUndefined(); + }); + + it("should not remove ``` if it's not on its own line at the end", () => { + const completion = "```typescript\nconst x = 5; // end```"; + const result = postprocessCompletion({ + completion, + llm: mockLLM, + prefix: "", + suffix: "", + }); + expect(result).toBe("const x = 5; // end```"); + }); +}); diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index b78d32009..11cdf88d4 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -52,6 +52,43 @@ function isBlank(completion: string): boolean { return completion.trim().length === 0; } +/** + * Removes markdown code block delimiters from completion. + * Removes the first line if it starts with backticks (with optional language name). + * Removes the last line if it contains only backticks. + */ +function removeBackticks(completion: string): string { + const lines = completion.split("\n"); + + if (lines.length === 0) { + return completion; + } + + let startIdx = 0; + let endIdx = lines.length; + + // Remove first line if it starts with backticks (``` or ```language) + const firstLineTrimmed = lines[0].trim(); + if (firstLineTrimmed.startsWith("```")) { + startIdx = 1; + } + + // Remove last line if it contains only backticks (one or more) + if (lines.length > startIdx) { + const lastLineTrimmed = lines[lines.length - 1].trim(); + if (lastLineTrimmed.length > 0 && /^`+$/.test(lastLineTrimmed)) { + endIdx = lines.length - 1; + } + } + + // If we removed lines, return the modified completion + if (startIdx > 0 || endIdx < lines.length) { + return lines.slice(startIdx, endIdx).join("\n"); + } + + return completion; +} + export function postprocessCompletion({ completion, llm, @@ -156,5 +193,8 @@ export function postprocessCompletion({ completion = completion.slice(1); } + // Remove markdown code block delimiters + completion = removeBackticks(completion); + return completion; } diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 58b3d2d0d..b84aaf156 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -119,6 +119,7 @@ export class AutocompleteLoggingService { time: restOfOutcome.time, useRecentlyEdited: restOfOutcome.useRecentlyEdited, numLines: restOfOutcome.numLines, + profileType: restOfOutcome.profileType, }; outcome.enabledStaticContextualization diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 4f669fc63..eb9a75fa1 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -43,4 +43,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { uniqueId: string; timestamp: string; enabledStaticContextualization?: boolean; + profileType?: "local" | "platform" | "control-plane"; } diff --git a/core/commands/slash/customSlashCommand.ts b/core/commands/slash/customSlashCommand.ts index 9526cbca8..43f535d4d 100644 --- a/core/commands/slash/customSlashCommand.ts +++ b/core/commands/slash/customSlashCommand.ts @@ -11,6 +11,6 @@ export function convertCustomCommandToSlashCommand( description: customCommand.description ?? "", prompt: customCommand.prompt, source: "json-custom-command", - promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile + sourceFile: customCommand.sourceFile, }; } diff --git a/core/commands/slash/promptBlockSlashCommand.ts b/core/commands/slash/promptBlockSlashCommand.ts index 4f3446a21..284a499ab 100644 --- a/core/commands/slash/promptBlockSlashCommand.ts +++ b/core/commands/slash/promptBlockSlashCommand.ts @@ -9,6 +9,6 @@ export function convertPromptBlockToSlashCommand( description: prompt.description ?? "", prompt: prompt.prompt, source: "yaml-prompt-block", - promptFile: prompt.sourceFile, // Align with the sourceFile property + sourceFile: prompt.sourceFile, }; } diff --git a/core/commands/slash/promptFileSlashCommand.ts b/core/commands/slash/promptFileSlashCommand.ts index e076086c0..693d2f856 100644 --- a/core/commands/slash/promptFileSlashCommand.ts +++ b/core/commands/slash/promptFileSlashCommand.ts @@ -15,7 +15,7 @@ export function slashCommandFromPromptFile( description, prompt, source: version === 1 ? "prompt-file-v1" : "prompt-file-v2", - promptFile: path, + sourceFile: path, overrideSystemMessage: systemMessage, }; } diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts index d907768cb..dd9b999cb 100644 --- a/core/commands/slash/ruleBlockSlashCommand.ts +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -10,6 +10,7 @@ export function convertRuleBlockToSlashCommand( description: rule.description ?? "", prompt: rule.rule, source: "invokable-rule", - promptFile: rule.ruleFile, + sourceFile: rule.sourceFile, + slug: rule.slug, }; } diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts index ccbc2df4f..e4f7c087c 100644 --- a/core/commands/slash/ruleBlockSlashCommand.vitest.ts +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -9,7 +9,7 @@ describe("convertRuleBlockToSlashCommand", () => { rule: "Review this code for best practices", description: "Performs a code review", source: "rules-block", - ruleFile: "/path/to/rules.yaml", + sourceFile: "file:///path/to/rules.yaml", invokable: true, }; @@ -20,7 +20,7 @@ describe("convertRuleBlockToSlashCommand", () => { description: "Performs a code review", prompt: "Review this code for best practices", source: "invokable-rule", - promptFile: "/path/to/rules.yaml", + sourceFile: "file:///path/to/rules.yaml", }); }); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 4127f2097..6eaabea60 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -537,12 +537,19 @@ export class ConfigHandler { // Track config loading telemetry const endTime = performance.now(); const duration = endTime - startTime; - void Telemetry.capture("config_reload", { + + const profileDescription = this.currentProfile.profileDescription; + const telemetryData: Record = { duration, reason, totalConfigLoads: this.totalConfigReloads, configLoadInterrupted, - }); + profileType: profileDescription.profileType, + isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id, + errorCount: errors.length, + }; + + void Telemetry.capture("config_reload", telemetryData); return { config, diff --git a/core/config/getWorkspaceContinueRuleDotFiles.ts b/core/config/getWorkspaceContinueRuleDotFiles.ts index 8a14d2405..52733e9d7 100644 --- a/core/config/getWorkspaceContinueRuleDotFiles.ts +++ b/core/config/getWorkspaceContinueRuleDotFiles.ts @@ -16,7 +16,7 @@ export async function getWorkspaceContinueRuleDotFiles(ide: IDE) { const content = await ide.readFile(dotFile); rules.push({ rule: content, - ruleFile: dotFile, + sourceFile: dotFile, source: ".continuerules", }); } diff --git a/core/config/load.ts b/core/config/load.ts index 6a97316d2..35d12d421 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -61,7 +61,7 @@ import { localPathToUri } from "../util/pathToUri"; import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import { PolicySingleton } from "../control-plane/PolicySingleton"; -import { getBaseToolDefinitions } from "../tools"; +import { getBaseToolDefinitions, serializeTool } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; import { getWorkspaceRcConfigs } from "./json/loadRcConfigs"; import { loadConfigContextProviders } from "./loadContextProviders"; @@ -671,7 +671,7 @@ async function finalToBrowserConfig( experimental: final.experimental, rules: final.rules, docs: final.docs, - tools: final.tools, + tools: final.tools.map(serializeTool), mcpServerStatuses: final.mcpServerStatuses, tabAutocompleteOptions: final.tabAutocompleteOptions, usePlatform: await useHub(ide.getIdeSettings()), diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index b05c50729..f0d96cbf4 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -12,13 +12,12 @@ import { getGlobalFolderWithName } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; import { getUriPathBasename, joinPathsToUri } from "../util/uri"; import { SYSTEM_PROMPT_DOT_FILE } from "./getWorkspaceContinueRuleDotFiles"; +import { SUPPORTED_AGENT_FILES } from "./markdown"; export function isContinueConfigRelatedUri(uri: string): boolean { return ( uri.endsWith(".continuerc.json") || uri.endsWith(".prompt") || - uri.endsWith("AGENTS.md") || - uri.endsWith("AGENT.md") || - uri.endsWith("CLAUDE.md") || + !!SUPPORTED_AGENT_FILES.find((file) => uri.endsWith(`/${file}`)) || uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || (uri.includes(".continue") && (uri.endsWith(".yaml") || diff --git a/core/config/markdown/loadCodebaseRules.ts b/core/config/markdown/loadCodebaseRules.ts index dc6696576..386bb0527 100644 --- a/core/config/markdown/loadCodebaseRules.ts +++ b/core/config/markdown/loadCodebaseRules.ts @@ -26,20 +26,30 @@ export class CodebaseRulesCache { } async update(ide: IDE, uri: string) { const content = await ide.readFile(uri); - const { relativePathOrBasename } = findUriInDirs( + const workspaceDirs = await ide.getWorkspaceDirs(); + const { relativePathOrBasename, foundInDir } = findUriInDirs( uri, - await ide.getWorkspaceDirs(), + workspaceDirs, + ); + if (!foundInDir) { + console.warn( + `Failed to load codebase rule ${uri}: URI not found in workspace`, + ); + } + const rule = markdownToRule( + content, + { + uriType: "file", + fileUri: uri, + }, + relativePathOrBasename, ); - const rule = markdownToRule(content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); const ruleWithSource: RuleWithSource = { ...rule, source: "colocated-markdown", - ruleFile: uri, + sourceFile: uri, }; - const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri); + const matchIdx = this.rules.findIndex((r) => r.sourceFile === uri); if (matchIdx === -1) { this.rules.push(ruleWithSource); } else { @@ -47,7 +57,7 @@ export class CodebaseRulesCache { } } remove(uri: string) { - this.rules = this.rules.filter((r) => r.ruleFile !== uri); + this.rules = this.rules.filter((r) => r.sourceFile !== uri); } } @@ -75,20 +85,32 @@ export async function loadCodebaseRules(ide: IDE): Promise<{ for (const filePath of rulesMdFiles) { try { const content = await ide.readFile(filePath); - const { relativePathOrBasename } = findUriInDirs( + const { relativePathOrBasename, foundInDir, uri } = findUriInDirs( filePath, await ide.getWorkspaceDirs(), ); - const rule = markdownToRule(content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); + if (foundInDir) { + const lastSlashIndex = relativePathOrBasename.lastIndexOf("/"); + const parentDir = relativePathOrBasename.substring(0, lastSlashIndex); + const rule = markdownToRule( + content, + { + uriType: "file", + fileUri: uri, + }, + parentDir, + ); - rules.push({ - ...rule, - source: "colocated-markdown", - ruleFile: filePath, - }); + rules.push({ + ...rule, + source: "colocated-markdown", + sourceFile: filePath, + }); + } else { + console.warn( + `Failed to load codebase rule ${uri}: URI not found in workspace dirs`, + ); + } } catch (e) { errors.push({ fatal: false, diff --git a/core/config/markdown/loadCodebaseRules.vitest.ts b/core/config/markdown/loadCodebaseRules.vitest.ts index 74da02684..81364830a 100644 --- a/core/config/markdown/loadCodebaseRules.vitest.ts +++ b/core/config/markdown/loadCodebaseRules.vitest.ts @@ -2,7 +2,6 @@ import { markdownToRule } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { IDE } from "../.."; import { walkDirs } from "../../indexing/walkDir"; -import { findUriInDirs, getUriPathBasename } from "../../util/uri"; import { loadCodebaseRules } from "./loadCodebaseRules"; // Mock dependencies @@ -14,14 +13,10 @@ vi.mock("@continuedev/config-yaml", () => ({ markdownToRule: vi.fn(), })); -vi.mock("../../util/uri", () => ({ - findUriInDirs: vi.fn(), - getUriPathBasename: vi.fn(), -})); - describe("loadCodebaseRules", () => { // Mock IDE with properly typed mock functions const mockIde = { + fileExists: vi.fn().mockImplementation(() => true), readFile: vi.fn() as unknown as IDE["readFile"] & { mockImplementation: Function; }, @@ -30,52 +25,45 @@ describe("loadCodebaseRules", () => { }, } as unknown as IDE; - // Setup test files - const mockFiles = [ - "src/rules.md", - "src/redux/rules.md", - "src/components/rules.md", - "src/utils/helper.ts", // Non-rules file - ".continue/rules.md", // This should also be loaded - ]; - // Mock rule content const mockRuleContent: Record = { - "src/rules.md": "# General Rules\nFollow coding standards", - "src/redux/rules.md": + "file:///workspace/src/rules.md": + "# General Rules\nFollow coding standards", + "file:///workspace/src/redux/rules.md": '---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit', - "src/components/rules.md": + "file:///workspace/src/components/rules.md": '---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components', - ".continue/rules.md": "# Global Rules\nFollow project guidelines", + "file:///workspace/.continue/rules.md": + "# Global Rules\nFollow project guidelines", }; // Mock converted rules const mockConvertedRules: Record = { - "src/rules.md": { + "file:///workspace/src/rules.md": { name: "General Rules", rule: "Follow coding standards", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "file:///workspace/src/rules.md", }, - "src/redux/rules.md": { + "file:///workspace/src/redux/rules.md": { name: "Redux Rules", rule: "Use Redux Toolkit", globs: "**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "file:///workspace/src/redux/rules.md", }, - "src/components/rules.md": { + "file:///workspace/src/components/rules.md": { name: "Component Rules", rule: "Use functional components", globs: ["**/*.tsx", "**/*.jsx"], source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "file:///workspace/src/components/rules.md", }, - ".continue/rules.md": { + "file:///workspace/.continue/rules.md": { name: "Global Rules", rule: "Follow project guidelines", source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: "file:///workspace/.continue/rules.md", }, }; @@ -84,20 +72,13 @@ describe("loadCodebaseRules", () => { vi.resetAllMocks(); // Mock walkDirs to return our test files - (walkDirs as any).mockResolvedValue(mockFiles); + (walkDirs as any).mockResolvedValue([ + ...Object.keys(mockRuleContent), + "file:///workspace/src/utils/helper.ts", // Non-rules file + ]); // Mock getWorkspaceDirs to return a workspace directory - (mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]); - - // Mock getUriPathBasename to return just the filename - (getUriPathBasename as any).mockImplementation((path: string) => { - return path.split("/").pop() || ""; - }); - - // Mock findUriInDirs to return relative path - (findUriInDirs as any).mockImplementation((uri: string) => { - return { relativePathOrBasename: uri }; - }); + (mockIde.getWorkspaceDirs as any).mockResolvedValue(["file:///workspace"]); // Mock readFile to return content based on path (mockIde.readFile as any).mockImplementation((path: string) => { @@ -123,20 +104,36 @@ describe("loadCodebaseRules", () => { // Should read all rules.md files expect(mockIde.readFile).toHaveBeenCalledTimes(4); - expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md"); - expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md"); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/redux/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/src/components/rules.md", + ); + expect(mockIde.readFile).toHaveBeenCalledWith( + "file:///workspace/.continue/rules.md", + ); // Should convert all rules expect(markdownToRule).toHaveBeenCalledTimes(4); // Should return all rules expect(rules).toHaveLength(4); - expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/redux/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/components/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/.continue/rules.md"], + ); // Should not have errors expect(errors).toHaveLength(0); @@ -145,7 +142,7 @@ describe("loadCodebaseRules", () => { it("should handle errors when reading a rule file", async () => { // Setup mock to throw for a specific file (mockIde.readFile as any).mockImplementation((path: string) => { - if (path === "src/redux/rules.md") { + if (path === "file:///workspace/src/redux/rules.md") { return Promise.reject(new Error("Failed to read file")); } return Promise.resolve(mockRuleContent[path] || ""); @@ -155,14 +152,20 @@ describe("loadCodebaseRules", () => { // Should still return other rules expect(rules).toHaveLength(3); - expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]); - expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/src/components/rules.md"], + ); + expect(rules).toContainEqual( + mockConvertedRules["file:///workspace/.continue/rules.md"], + ); // Should have one error expect(errors).toHaveLength(1); expect(errors[0].message).toContain( - "Failed to parse colocated rule file src/redux/rules.md", + "Failed to parse colocated rule file file:///workspace/src/redux/rules.md: Failed to read file", ); }); diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 42bfcd21d..bdeddedaa 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -3,12 +3,13 @@ import { markdownToRule, } from "@continuedev/config-yaml"; import { IDE, RuleWithSource } from "../.."; -import { findUriInDirs, joinPathsToUri } from "../../util/uri"; +import { PROMPTS_DIR_NAME, RULES_DIR_NAME } from "../../promptFiles"; +import { joinPathsToUri } from "../../util/uri"; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"]; /** - * Loads rules from markdown files in the .continue/rules directory + * Loads rules from markdown files in the .continue/rules and .continue/prompts directories * and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root */ export async function loadMarkdownRules(ide: IDE): Promise<{ @@ -25,66 +26,73 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ let agentFileFound = false; for (const fileName of SUPPORTED_AGENT_FILES) { try { - const agentFilePath = joinPathsToUri(workspaceDir, fileName); - const agentContent = await ide.readFile(agentFilePath); + const agentFileUri = joinPathsToUri(workspaceDir, fileName); + const exists = await ide.fileExists(agentFileUri); + if (exists) { + const agentContent = await ide.readFile(agentFileUri); + + const rule = markdownToRule(agentContent, { + uriType: "file", + fileUri: agentFileUri, + }); + rules.push({ + ...rule, + source: "agent-file", + sourceFile: agentFileUri, + alwaysApply: true, + }); + agentFileFound = true; + } - const rule = markdownToRule(agentContent, { - uriType: "file", - fileUri: agentFilePath, - }); - rules.push({ - ...rule, - source: "agent-file", - ruleFile: agentFilePath, - alwaysApply: true, - }); - agentFileFound = true; break; // Use the first found agent file in this workspace } catch (e) { // File doesn't exist or can't be read, continue to next file } } - if (agentFileFound) { break; // Use agent file from first workspace that has one } } - try { - // Get all .md files from .continue/rules - const markdownFiles = await getAllDotContinueDefinitionFiles( - ide, - { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, - "rules", - ); + // Load markdown files from both .continue/rules and .continue/prompts + const dirsToCheck = [RULES_DIR_NAME, PROMPTS_DIR_NAME]; - // Filter to just .md files - const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + for (const dirName of dirsToCheck) { + try { + const markdownFiles = await getAllDotContinueDefinitionFiles( + ide, + { + includeGlobal: true, + includeWorkspace: true, + fileExtType: "markdown", + }, + dirName, + ); - // Process each markdown file - for (const file of mdFiles) { - try { - const { relativePathOrBasename } = findUriInDirs( - file.path, - await ide.getWorkspaceDirs(), - ); - const rule = markdownToRule(file.content, { - uriType: "file", - fileUri: relativePathOrBasename, - }); - rules.push({ ...rule, source: "rules-block", ruleFile: file.path }); - } catch (e) { - errors.push({ - fatal: false, - message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, - }); + // Filter to just .md files + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + + // Process each markdown file + for (const file of mdFiles) { + try { + const rule = markdownToRule(file.content, { + uriType: "file", + fileUri: file.path, + }); + rules.push({ ...rule, source: "rules-block", sourceFile: file.path }); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, + }); + } } + } catch (e) { + errors.push({ + fatal: false, + message: `Error loading markdown rule files from ${dirName}: ${e instanceof Error ? e.message : e}`, + }); } - } catch (e) { - errors.push({ - fatal: false, - message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, - }); } return { rules, errors }; diff --git a/core/config/markdown/ruleCollocationApplication.vitest.ts b/core/config/markdown/ruleCollocationApplication.vitest.ts index 120e2d6a1..439d337ca 100644 --- a/core/config/markdown/ruleCollocationApplication.vitest.ts +++ b/core/config/markdown/ruleCollocationApplication.vitest.ts @@ -17,7 +17,7 @@ describe("Rule Colocation Application", () => { name: "Root Rule", rule: "Follow project standards", source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Nested directory rule without globs - should only apply to files in that directory @@ -25,7 +25,7 @@ describe("Rule Colocation Application", () => { name: "React Components Rule", rule: "Use functional components with hooks", source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should implicitly only apply to files in that directory }, @@ -35,7 +35,7 @@ describe("Rule Colocation Application", () => { rule: "Use Redux Toolkit for state management", globs: "src/redux/**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "src/redux/rules.md", }, // Directory rule with specific file extension glob @@ -44,7 +44,7 @@ describe("Rule Colocation Application", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only apply to .tsx files source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }, // Rule for a specific subdirectory with its own glob @@ -53,7 +53,7 @@ describe("Rule Colocation Application", () => { rule: "Follow API utility conventions", globs: "**/*.ts", // Only TypeScript files in this directory source: "colocated-markdown", - ruleFile: "src/utils/api/rules.md", + sourceFile: "src/utils/api/rules.md", }, ]; @@ -184,7 +184,7 @@ describe("Rule Colocation Application", () => { name: "Implied Components Rule", rule: "Use React component best practices", source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should infer from directory }; @@ -234,7 +234,7 @@ describe("Rule Colocation Application", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only apply to .tsx files source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; // Test with TSX component file - should apply @@ -281,7 +281,7 @@ describe("Rule Colocation Application", () => { rule: "Follow API utility conventions", globs: "**/*.ts", // Only TypeScript files in this directory source: "colocated-markdown", - ruleFile: "src/utils/api/rules.md", + sourceFile: "src/utils/api/rules.md", }; // Test with file in the API utils directory - should apply @@ -314,9 +314,9 @@ describe("Rule Colocation Application", () => { // it should automatically create an implicit glob pattern for that directory. function createRuleWithAutomaticGlobInference( - ruleFilePath: string, + sourceFilePath: string, ): RuleWithSource { - const directory = path.dirname(ruleFilePath); + const directory = path.dirname(sourceFilePath); // The expected behavior would be to create an implicit glob like this: const expectedGlob = `${directory}/**/*`; @@ -324,7 +324,7 @@ describe("Rule Colocation Application", () => { name: `Inferred Rule for ${directory}`, rule: `Follow standards for ${directory}`, source: "colocated-markdown", - ruleFile: ruleFilePath, + sourceFile: sourceFilePath, // In a fixed implementation, these globs would be automatically inferred // globs: expectedGlob, }; diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index c213bcb66..97011a77c 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -28,6 +28,7 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { initSlashCommand } from "../../promptFiles/initPrompt"; import { getConfigDependentToolDefinitions } from "../../tools"; import { encodeMCPToolUri } from "../../tools/callTool"; import { getMCPToolName } from "../../tools/mcpToolName"; @@ -171,6 +172,8 @@ export default async function doLoadConfig(options: { } } + newConfig.slashCommands.push(initSlashCommand); + const proxyContextProvider = newConfig.contextProviders?.find( (cp) => cp.description.title === "continue-proxy", ); @@ -210,6 +213,13 @@ export default async function doLoadConfig(options: { newConfig.mcpServerStatuses = serializableStatuses; for (const server of mcpServerStatuses) { + server.errors.forEach((error) => { + // MCP errors will also show as config loading errors + errors.push({ + fatal: false, + message: error, + }); + }); if (server.status === "connected") { const serverTools: Tool[] = server.tools.map((tool) => ({ displayTitle: server.name + " " + tool.name, diff --git a/core/config/types.ts b/core/config/types.ts index c6441f626..d9f58aca6 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -78,8 +78,9 @@ declare global { export interface ILLM extends LLMOptions { get providerName(): string; - + uniqueId: string; + lastRequestId?: string; model: string; title?: string; diff --git a/core/config/workspace/workspaceBlocks.ts b/core/config/workspace/workspaceBlocks.ts index f96ba112f..9ba16b400 100644 --- a/core/config/workspace/workspaceBlocks.ts +++ b/core/config/workspace/workspaceBlocks.ts @@ -7,6 +7,7 @@ import { } from "@continuedev/config-yaml"; import * as YAML from "yaml"; import { IDE } from "../.."; +import { getContinueGlobalPath } from "../../util/paths"; import { joinPathsToUri } from "../../util/uri"; const BLOCK_TYPE_CONFIG: Record< @@ -114,8 +115,13 @@ export async function findAvailableFilename( blockType: BlockType, fileExists: (uri: string) => Promise, extension?: string, + isGlobal?: boolean, ): Promise { - const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`; + // Differentiate filename based on whether its a global rule or a workspace rule + const baseFilename = + blockType === "rules" && isGlobal + ? "global-rule" + : `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`; const fileExtension = extension ?? getFileExtension(blockType); let counter = 0; let fileUri: string; @@ -156,3 +162,28 @@ export async function createNewWorkspaceBlockFile( await ide.writeFile(fileUri, fileContent); await ide.openFile(fileUri); } + +export async function createNewGlobalRuleFile(ide: IDE): Promise { + try { + const globalDir = getContinueGlobalPath(); + + // Create the rules subdirectory within the global directory + const rulesDir = joinPathsToUri(globalDir, "rules"); + + const fileUri = await findAvailableFilename( + rulesDir, + "rules", + ide.fileExists.bind(ide), + undefined, + true, // isGlobal = true for global rules + ); + + const fileContent = getFileContent("rules"); + + await ide.writeFile(fileUri, fileContent); + + await ide.openFile(fileUri); + } catch (error) { + throw error; + } +} diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts index ad435aea8..d639e4515 100644 --- a/core/config/yaml/yamlToContinueConfig.ts +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -25,7 +25,7 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { globs: rule.globs, name: rule.name, description: rule.description, - ruleFile: rule.sourceFile, + sourceFile: rule.sourceFile, alwaysApply: rule.alwaysApply, invokable: rule.invokable ?? false, }; @@ -48,27 +48,28 @@ export function convertYamlMcpConfigToInternalMcpOptions( if ("command" in config) { const { args, command, cwd, env, type } = config; const stdioOptions: InternalStdioMcpOptions = { + ...shared, type, command, args, cwd, env, - ...shared, }; return stdioOptions; } // HTTP/SSE - const { type, url, requestOptions } = config; + const { type, url, apiKey, requestOptions } = config; const httpSseConfig: | InternalStreamableHttpMcpOptions | InternalSseMcpOptions = { + ...shared, type, url, + apiKey, requestOptions: mergeConfigYamlRequestOptions( requestOptions, globalRequestOptions, ), - ...shared, }; return httpSseConfig; } diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index b79647c57..4090e92c5 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -1,4 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { fileURLToPath } from "url"; + import { SSEClientTransport, SseError, @@ -6,7 +9,6 @@ import { import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; -import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { Agent as HttpsAgent } from "https"; import { IDE, @@ -22,6 +24,7 @@ import { MCPServerStatus, MCPTool, } from "../.."; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getEnvPathFromUserShell } from "../../util/shellPath"; import { getOauthToken } from "./MCPOauth"; @@ -38,6 +41,8 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +const COMMONS_ENV_VARS = ["HOME", "USER", "USERPROFILE", "LOGNAME", "USERNAME"]; + function is401Error(error: unknown) { return ( (error instanceof SseError && error.code === 401) || @@ -88,11 +93,11 @@ class MCPConnection { this.abortController = new AbortController(); } - async disconnect() { - this.status = "not-connected"; + async disconnect(disable = false) { this.abortController.abort(); await this.client.close(); await this.transport.close(); + this.status = disable ? "disabled" : "not-connected"; } getStatus(): MCPServerStatus { @@ -110,6 +115,9 @@ class MCPConnection { } async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) { + if (this.status === "disabled") { + return; + } if (!forceRefresh) { // Already connected if (this.status === "connected") { @@ -408,6 +416,44 @@ class MCPConnection { }; } + /** + * Resolves the current working directory of the current workspace. + * @param cwd The cwd parameter provided by user. + * @returns Current working directory (user-provided cwd or workspace root). + */ + private async resolveCwd(cwd?: string) { + if (!cwd) { + return this.resolveWorkspaceCwd(undefined); + } + + if (cwd.startsWith("file://")) { + return fileURLToPath(cwd); + } + + // Return cwd if cwd is an absolute path. + if (cwd.charAt(0) === "/") { + return cwd; + } + + return this.resolveWorkspaceCwd(cwd); + } + + private async resolveWorkspaceCwd(cwd: string | undefined) { + const IDE = this.extras?.ide; + if (IDE) { + const target = cwd ?? "."; + const resolved = await resolveRelativePathInDir(target, IDE); + if (resolved) { + if (resolved.startsWith("file://")) { + return fileURLToPath(resolved); + } + return resolved; + } + return resolved; + } + return cwd; + } + private constructWebsocketTransport( options: InternalWebsocketMcpOptions, ): WebSocketClientTransport { @@ -422,6 +468,12 @@ class MCPConnection { ? new HttpsAgent({ rejectUnauthorized: false }) : undefined; + // Merge apiKey into headers if provided + const headers = { + ...options.requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + return new SSEClientTransport(new URL(options.url), { eventSourceInit: { fetch: (input, init) => @@ -429,13 +481,13 @@ class MCPConnection { ...init, headers: { ...init?.headers, - ...options.requestOptions?.headers, + ...headers, }, ...(sseAgent && { agent: sseAgent }), }), }, requestInit: { - headers: options.requestOptions?.headers, + headers, ...(sseAgent && { agent: sseAgent }), }, }); @@ -450,9 +502,15 @@ class MCPConnection { ? new HttpsAgent({ rejectUnauthorized: false }) : undefined; + // Merge apiKey into headers if provided + const headers = { + ...requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + return new StreamableHTTPClientTransport(new URL(url), { requestInit: { - headers: requestOptions?.headers, + headers, ...(streamableAgent && { agent: streamableAgent }), }, }); @@ -461,7 +519,16 @@ class MCPConnection { private async constructStdioTransport( options: InternalStdioMcpOptions, ): Promise { - const env: Record = options.env ? { ...options.env } : {}; + const commonEnvVars: Record = Object.fromEntries( + COMMONS_ENV_VARS.filter((key) => process.env[key] !== undefined).map( + (key) => [key, process.env[key] as string], + ), + ); + + const env = { + ...commonEnvVars, + ...(options.env ?? {}), + }; if (process.env.PATH !== undefined) { // Set the initial PATH from process.env @@ -485,11 +552,13 @@ class MCPConnection { options.args || [], ); + const cwd = await this.resolveCwd(options.cwd); + const transport = new StdioClientTransport({ command, args, env, - cwd: options.cwd, + cwd, stderr: "pipe", }); diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index af1a2d17a..2df63cb32 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -5,6 +5,7 @@ import { InternalStdioMcpOptions, InternalWebsocketMcpOptions, } from "../.."; +import * as ideUtils from "../../util/ideUtils"; import MCPConnection from "./MCPConnection"; // Mock the shell path utility @@ -145,6 +146,37 @@ describe("MCPConnection", () => { }); }); + describe("resolveCwd", () => { + const baseOptions = { + name: "test-mcp", + id: "test-id", + type: "stdio" as const, + command: "test-cmd", + args: [], + }; + + it("should return absolute cwd unchanged", async () => { + const conn = new MCPConnection(baseOptions); + + await expect((conn as any).resolveCwd("/tmp/project")).resolves.toBe( + "/tmp/project", + ); + }); + + it("should resolve relative cwd using IDE workspace", async () => { + const ide = {} as any; + const mockResolve = vi + .spyOn(ideUtils, "resolveRelativePathInDir") + .mockResolvedValue("file:///workspace/src"); + const conn = new MCPConnection(baseOptions, { ide }); + + await expect((conn as any).resolveCwd("src")).resolves.toBe( + "/workspace/src", + ); + expect(mockResolve).toHaveBeenCalledWith("src", ide); + }); + }); + describe("connectClient", () => { const options: InternalStdioMcpOptions = { name: "test-mcp", diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index f9e6ff29c..cac57e1e6 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -8,7 +8,6 @@ export class MCPManagerSingleton { public onConnectionsRefreshed?: () => void; public connections: Map = new Map(); - private disconnectedServers: string[] = []; private abortController: AbortController = new AbortController(); @@ -21,16 +20,20 @@ export class MCPManagerSingleton { return MCPManagerSingleton.instance; } - addDisconnectedServer(serverId: string) { - this.disconnectedServers.push(serverId); - } - removeDisconnectedServer(serverId: string) { - this.disconnectedServers = this.disconnectedServers.filter( - (server) => server !== serverId, - ); - } - getDisconnectedServers() { - return this.disconnectedServers; + async setEnabled(serverId: string, enabled: boolean) { + const conn = this.connections.get(serverId); + if (conn) { + if (enabled) { + conn.status = "not-connected"; + await this.refreshConnection(serverId); + } else { + try { + await conn.disconnect(true); + } catch (e) { + console.error(`Error disconnecting from MCP server ${serverId}`, e); + } + } + } } createConnection(id: string, options: InternalMcpOptions): MCPConnection { @@ -47,15 +50,6 @@ export class MCPManagerSingleton { return this.connections.get(id); } - async removeConnection(id: string) { - const connection = this.connections.get(id); - if (connection) { - await connection.client.close(); - } - - this.connections.delete(id); - } - async shutdown() { if (this.connections.size > 0) { await Promise.allSettled( @@ -169,19 +163,9 @@ export class MCPManagerSingleton { }), (async () => { await Promise.all( - Array.from(this.connections.values()) - .filter( - (connection) => - !this.disconnectedServers.some( - (s) => s === connection.options.id, - ), - ) - .map(async (connection) => { - await connection.connectClient( - force, - this.abortController.signal, - ); - }), + Array.from(this.connections.values()).map(async (connection) => { + await connection.connectClient(force, this.abortController.signal); + }), ); if (this.onConnectionsRefreshed) { this.onConnectionsRefreshed(); diff --git a/core/context/mcp/MCPManagerSingleton.vitest.ts b/core/context/mcp/MCPManagerSingleton.vitest.ts index 6a6fc3842..96d4c78e5 100644 --- a/core/context/mcp/MCPManagerSingleton.vitest.ts +++ b/core/context/mcp/MCPManagerSingleton.vitest.ts @@ -94,28 +94,6 @@ describe("MCPManagerSingleton", () => { }); }); - describe("removeConnection", () => { - it("should remove connection and close client", async () => { - // Create a spy on the close method - const connection = manager.createConnection( - "test-id", - testOptions, - ) as TestMCPConnection; - const closeSpy = vi.spyOn(connection.client, "close"); - - await manager.removeConnection("test-id"); - - expect(closeSpy).toHaveBeenCalled(); - expect(manager.getConnection("test-id")).toBeUndefined(); - }); - - it("should handle non-existent connection", async () => { - await expect( - manager.removeConnection("non-existent"), - ).resolves.toBeUndefined(); - }); - }); - describe("setConnections", () => { it("should add new connections", () => { const servers = [testOptions]; diff --git a/core/context/providers/RulesContextProvider.ts b/core/context/providers/RulesContextProvider.ts index 3a4cfbcdb..dd543b88d 100644 --- a/core/context/providers/RulesContextProvider.ts +++ b/core/context/providers/RulesContextProvider.ts @@ -22,11 +22,11 @@ class RulesContextProvider extends BaseContextProvider { // This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case // Can eventually pull in more metadata, but this is experimental private getIdFromRule(rule: RuleWithSource): string { - return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule; + return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.rule; } private getNameFromRule(rule: RuleWithSource): string { - return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source; + return rule.name ?? rule.slug ?? rule.sourceFile ?? rule.source; } private getDescriptionFromRule(rule: RuleWithSource): string { @@ -37,10 +37,10 @@ class RulesContextProvider extends BaseContextProvider { rule: RuleWithSource, appUrl: string, ): ContextItemUri | undefined { - if (rule.ruleFile) { + if (rule.sourceFile) { return { type: "file", - value: rule.ruleFile, + value: rule.sourceFile, }; } diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 094c25b27..9a0b88e5e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -8,7 +8,7 @@ const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", "llama3.1", "llama3.2", - "gemini-1.5", + "gemini-2.5", "gpt-4", ]; diff --git a/core/core.ts b/core/core.ts index dd66dae44..0d1b5ffba 100644 --- a/core/core.ts +++ b/core/core.ts @@ -63,7 +63,10 @@ import { setupProviderConfig, setupQuickstartConfig, } from "./config/onboarding"; -import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; +import { + createNewGlobalRuleFile, + createNewWorkspaceBlockFile, +} from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; @@ -80,6 +83,7 @@ import { NextEditProvider } from "./nextEdit/NextEditProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; +import { ContinueError, ContinueErrorReason } from "./util/errors"; import { shareSession } from "./util/historyUtils"; import { Logger } from "./util/Logger.js"; @@ -410,11 +414,19 @@ export class Core { ); }); + on("config/addGlobalRule", async (msg) => { + try { + await createNewGlobalRuleFile(this.ide); + await this.configHandler.reloadConfig( + "Global rule created (config/addGlobalRule message)", + ); + } catch (error) { + throw error; + } + }); + on("config/openProfile", async (msg) => { - await this.configHandler.openConfigProfile( - msg.data.profileId, - msg.data?.element, - ); + await this.configHandler.openConfigProfile(msg.data.profileId); }); on("config/ideSettingsUpdate", async (msg) => { @@ -483,20 +495,10 @@ export class Core { on("mcp/reloadServer", async (msg) => { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); - MCPManagerSingleton.getInstance().removeDisconnectedServer(msg.data.id); }); - on("mcp/disconnectServer", async (msg) => { - const mcpConnection = MCPManagerSingleton.getInstance().getConnection( - msg.data.id, - ); - if (!mcpConnection) - throw new Error(`MCP connection with id ${msg.data.id} not found`); - MCPManagerSingleton.getInstance().addDisconnectedServer(msg.data.id); - await mcpConnection.disconnect(); - await this.configHandler.refreshAll("MCP Servers disconnected"); - }); - on("mcp/getDisconnectedServers", async (_msg) => { - return MCPManagerSingleton.getInstance().getDisconnectedServers(); + on("mcp/setServerEnabled", async (msg) => { + const { id, enabled } = msg.data; + await MCPManagerSingleton.getInstance().setEnabled(id, enabled); }); on("mcp/getPrompt", async (msg) => { const { serverName, promptName, args } = msg.data; @@ -825,7 +827,6 @@ export class Core { if (data?.shouldClearIndexes) { await this.codeBaseIndexer.clearIndexes(); } - const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.codeBaseIndexer.refreshCodebaseIndex(dirs); }); @@ -929,7 +930,7 @@ export class Core { }); on("files/closed", async ({ data }) => { - console.log("deleteChain called from files/closed"); + console.debug("deleteChain called from files/closed"); await NextEditProvider.getInstance().deleteChain(); try { @@ -1104,7 +1105,6 @@ export class Core { const tool = config.tools.find((t) => t.function.name === toolName); if (!tool) { - // Tool not found, return base policy return { policy: basePolicy }; } @@ -1114,17 +1114,47 @@ export class Core { displayValue = args.command as string; } - // If tool has evaluateToolCallPolicy function, use it if (tool.evaluateToolCallPolicy) { const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); return { policy: evaluatedPolicy, displayValue }; } - - // Otherwise return base policy unchanged return { policy: basePolicy, displayValue }; }, ); + on("tools/preprocessArgs", async ({ data: { toolName, args } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config?.tools.find((t) => t.function.name === toolName); + if (!tool) { + throw new Error(`Tool ${toolName} not found`); + } + + try { + const preprocessedArgs = await tool.preprocessArgs?.(args, { + ide: this.ide, + }); + return { + preprocessedArgs, + }; + } catch (e) { + let errorReason = + e instanceof ContinueError ? e.reason : ContinueErrorReason.Unknown; + let errorMessage = + e instanceof Error + ? e.message + : `Error preprocessing tool call args for ${toolName}\n${JSON.stringify(args)}`; + return { + preprocessedArgs: undefined, + errorReason, + errorMessage, + }; + } + }); + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.ts b/core/edit/searchAndReplace/findAndReplaceUtils.ts index b85dcdfb9..e3185374e 100644 --- a/core/edit/searchAndReplace/findAndReplaceUtils.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.ts @@ -7,22 +7,23 @@ export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = * Validates a single edit operation */ export function validateSingleEdit( - oldString: string, - newString: string, + oldString: unknown, + newString: unknown, + replaceAll: unknown, index?: number, -): void { +): { oldString: string; newString: string; replaceAll?: boolean } { const context = index !== undefined ? `edit at index ${index}: ` : ""; - if (!oldString && oldString !== "") { + if (oldString === undefined || typeof oldString !== "string") { throw new ContinueError( ContinueErrorReason.FindAndReplaceMissingOldString, - `${context}old_string is required`, + `${context}string old_string is required`, ); } - if (newString === undefined) { + if (newString === undefined || typeof newString !== "string") { throw new ContinueError( ContinueErrorReason.FindAndReplaceMissingNewString, - `${context}new_string is required`, + `${context}string new_string is required`, ); } if (oldString === newString) { @@ -31,6 +32,13 @@ export function validateSingleEdit( `${context}old_string and new_string must be different`, ); } + if (replaceAll !== undefined && typeof replaceAll !== "boolean") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + `${context}replace_all must be a valid boolean`, + ); + } + return { oldString, newString, replaceAll }; } export function trimEmptyLines({ diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts index b08413a9d..1489de7ac 100644 --- a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts +++ b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts @@ -6,39 +6,69 @@ describe("validateSingleEdit", () => { describe("valid inputs", () => { it("should not throw for valid non-empty strings", () => { expect(() => { - validateSingleEdit("old", "new"); + validateSingleEdit("old", "new", undefined); }).not.toThrow(); }); it("should allow empty old_string for file creation", () => { expect(() => { - validateSingleEdit("", "new content"); + validateSingleEdit("", "new content", undefined); }).not.toThrow(); }); it("should allow empty new_string for deletion", () => { expect(() => { - validateSingleEdit("delete me", ""); + validateSingleEdit("delete me", "", undefined); }).not.toThrow(); }); it("should allow multiline strings", () => { expect(() => { - validateSingleEdit("line1\nline2", "newline1\nnewline2"); + validateSingleEdit("line1\nline2", "newline1\nnewline2", undefined); }).not.toThrow(); }); it("should allow special characters", () => { expect(() => { - validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g"); + validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g", undefined); }).not.toThrow(); }); + + it("should allow replaceAll as true", () => { + expect(() => { + validateSingleEdit("old", "new", true); + }).not.toThrow(); + }); + + it("should allow replaceAll as false", () => { + expect(() => { + validateSingleEdit("old", "new", false); + }).not.toThrow(); + }); + + it("should return validated values including replaceAll", () => { + const result = validateSingleEdit("old", "new", true); + expect(result).toEqual({ + oldString: "old", + newString: "new", + replaceAll: true, + }); + }); + + it("should return validated values with replaceAll undefined", () => { + const result = validateSingleEdit("old", "new", undefined); + expect(result).toEqual({ + oldString: "old", + newString: "new", + replaceAll: undefined, + }); + }); }); describe("invalid inputs", () => { it("should throw error when old_string is null", () => { expect(() => { - validateSingleEdit(null as any, "new"); + validateSingleEdit(null as any, "new", undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceMissingOldString, @@ -48,7 +78,7 @@ describe("validateSingleEdit", () => { it("should throw error when old_string is undefined", () => { expect(() => { - validateSingleEdit(undefined as any, "new"); + validateSingleEdit(undefined as any, "new", undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceMissingOldString, @@ -58,7 +88,7 @@ describe("validateSingleEdit", () => { it("should throw error when new_string is undefined", () => { expect(() => { - validateSingleEdit("old", undefined as any); + validateSingleEdit("old", undefined as any, undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceMissingNewString, @@ -68,7 +98,7 @@ describe("validateSingleEdit", () => { it("should throw error when old_string and new_string are identical", () => { expect(() => { - validateSingleEdit("same", "same"); + validateSingleEdit("same", "same", undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, @@ -78,19 +108,49 @@ describe("validateSingleEdit", () => { it("should throw error when both are empty strings", () => { expect(() => { - validateSingleEdit("", ""); + validateSingleEdit("", "", undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, }), ); }); + + it("should throw error when replaceAll is not a boolean", () => { + expect(() => { + validateSingleEdit("old", "new", "invalid" as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + + it("should throw error when replaceAll is null", () => { + expect(() => { + validateSingleEdit("old", "new", null as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + + it("should throw error when replaceAll is a number", () => { + expect(() => { + validateSingleEdit("old", "new", 1 as any); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); }); describe("error messages with context", () => { it("should include edit number in error messages when index provided", () => { expect(() => { - validateSingleEdit(null as any, "new", 2); + validateSingleEdit(null as any, "new", undefined, 2); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceMissingOldString, @@ -100,7 +160,7 @@ describe("validateSingleEdit", () => { it("should include edit number for new_string errors", () => { expect(() => { - validateSingleEdit("old", undefined as any, 0); + validateSingleEdit("old", undefined as any, undefined, 0); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceMissingNewString, @@ -110,7 +170,7 @@ describe("validateSingleEdit", () => { it("should include edit number for identical strings error", () => { expect(() => { - validateSingleEdit("same", "same", 4); + validateSingleEdit("same", "same", undefined, 4); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, @@ -118,9 +178,19 @@ describe("validateSingleEdit", () => { ); }); + it("should include edit number for replaceAll validation error", () => { + expect(() => { + validateSingleEdit("old", "new", "invalid" as any, 3); + }).toThrowError( + expect.objectContaining({ + reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll, + }), + ); + }); + it("should not include context when index not provided", () => { expect(() => { - validateSingleEdit("same", "same"); + validateSingleEdit("same", "same", undefined); }).toThrowError( expect.objectContaining({ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, diff --git a/core/edit/searchAndReplace/multiEditValidation.ts b/core/edit/searchAndReplace/multiEditValidation.ts index b103884fb..3600eeebc 100644 --- a/core/edit/searchAndReplace/multiEditValidation.ts +++ b/core/edit/searchAndReplace/multiEditValidation.ts @@ -2,26 +2,30 @@ import { EditOperation } from "../../tools/definitions/multiEdit"; import { ContinueError, ContinueErrorReason } from "../../util/errors"; import { validateSingleEdit } from "./findAndReplaceUtils"; -export interface MultiEditValidationResult { - edits: EditOperation[]; -} - /** * Validates multi-edit arguments and all edits in a single pass * @param args - The arguments object containing the edits array * @returns Validated edits array * @throws ContinueError if validation fails */ -export function validateMultiEdit(args: any): MultiEditValidationResult { - const { edits } = args; +export function validateMultiEdit(args: unknown): { + edits: EditOperation[]; +} { + if (typeof args !== "object" || !args || !("edits" in args)) { + throw new ContinueError( + ContinueErrorReason.MultiEditEditsArrayRequired, + "invalid multi-edit args", + ); + } // Validate that edits is a non-empty array - if (!edits || !Array.isArray(edits)) { + if (!Array.isArray(args.edits)) { throw new ContinueError( ContinueErrorReason.MultiEditEditsArrayRequired, "edits array is required", ); } + const { edits } = args; if (edits.length === 0) { throw new ContinueError( @@ -35,7 +39,7 @@ export function validateMultiEdit(args: any): MultiEditValidationResult { const edit = edits[i]; // Use existing single edit validation - validateSingleEdit(edit.old_string, edit.new_string, i); + validateSingleEdit(edit.old_string, edit.new_string, edit.replace_all, i); // Only the first edit can have empty old_string (for insertion at beginning) if (i > 0 && edit.old_string === "") { diff --git a/core/edit/searchAndReplace/validateArgs.ts b/core/edit/searchAndReplace/validateArgs.ts new file mode 100644 index 000000000..623503515 --- /dev/null +++ b/core/edit/searchAndReplace/validateArgs.ts @@ -0,0 +1,23 @@ +import { IDE } from "../.."; +import { ContinueError, ContinueErrorReason } from "../../util/errors"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export async function validateSearchAndReplaceFilepath( + filepath: unknown, + ide: IDE, +) { + if (!filepath || typeof filepath !== "string") { + throw new ContinueError( + ContinueErrorReason.FindAndReplaceMissingFilepath, + "filepath (string) is required", + ); + } + const resolvedFilepath = await resolveRelativePathInDir(filepath, ide); + if (!resolvedFilepath) { + throw new ContinueError( + ContinueErrorReason.FileNotFound, + `File ${filepath} does not exist`, + ); + } + return resolvedFilepath; +} diff --git a/core/index.d.ts b/core/index.d.ts index 8650c6ae2..fb59d97bd 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -99,6 +99,8 @@ export interface ILLM autocompleteOptions?: Partial; + lastRequestId?: string; + complete( prompt: string, signal: AbortSignal, @@ -476,6 +478,7 @@ interface ToolCallState { toolCall: ToolCall; status: ToolStatus; parsedArgs: any; + processedArgs?: Record; // Added in preprocesing step output?: ContextItem[]; tool?: Tool; } @@ -918,7 +921,8 @@ export interface SlashCommand extends SlashCommandDescription { export interface SlashCommandWithSource extends SlashCommandDescription { run?: (sdk: ContinueSDK) => AsyncGenerator; // Optional - only needed for legacy source: SlashCommandSource; - promptFile?: string; + sourceFile?: string; + slug?: string; overrideSystemMessage?: string; } @@ -936,7 +940,8 @@ export type SlashCommandSource = export interface SlashCommandDescWithSource extends SlashCommandDescription { isLegacy: boolean; // Maps to if slashcommand.run exists source: SlashCommandSource; - promptFile?: string; + sourceFile?: string; + slug?: string; mcpServerName?: string; mcpArgs?: MCPPromptArgs; } @@ -1080,7 +1085,6 @@ export interface Tool { parameters?: Record; strict?: boolean | null; }; - displayTitle: string; wouldLikeTo?: string; isCurrently?: string; @@ -1097,6 +1101,12 @@ export interface Tool { }; defaultToolPolicy?: ToolPolicy; toolCallIcon?: string; + preprocessArgs?: ( + args: Record, + extras: { + ide: IDE; + }, + ) => Promise>; evaluateToolCallPolicy?: ( basePolicy: ToolPolicy, parsedArgs: Record, @@ -1273,6 +1283,7 @@ export type TransportOptions = | StreamableHTTPOptions; export type MCPConnectionStatus = + | "disabled" | "connecting" | "connected" | "error" @@ -1339,11 +1350,13 @@ export type InternalStdioMcpOptions = BaseInternalMCPOptions & { export type InternalStreamableHttpMcpOptions = BaseInternalMCPOptions & { type?: "streamable-http"; url: string; + apiKey?: string; }; export type InternalSseMcpOptions = BaseInternalMCPOptions & { type?: "sse"; url: string; + apiKey?: string; }; export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & { @@ -1776,7 +1789,7 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; - tools: Tool[]; + tools: Omit[]; mcpServerStatuses: MCPServerStatus[]; rules: RuleWithSource[]; usePlatform: boolean; @@ -1849,7 +1862,7 @@ export interface RuleWithSource { regex?: string | string[]; rule: string; description?: string; - ruleFile?: string; + sourceFile?: string; alwaysApply?: boolean; invokable?: boolean; } @@ -1865,6 +1878,16 @@ export interface CompiledMessagesResult { contextPercentage: number; } +export interface AddToChatPayload { + data: AddToChatPayloadItem[]; +} + +interface AddToChatPayloadItem { + type: "file" | "folder"; + fullPath: string; + name: string; +} + export interface MessageOption { precompiled: boolean; } diff --git a/core/indexing/README.md b/core/indexing/README.md index 94bf196aa..eaf137167 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -20,7 +20,7 @@ The indexing process does the following: All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used. -`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file +`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 `ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex` `LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. diff --git a/core/llm/index.ts b/core/llm/index.ts index ecb43bfca..39b6b127b 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -193,12 +193,15 @@ export abstract class BaseLLM implements ILLM { isFromAutoDetect?: boolean; + lastRequestId: string | undefined; + private _llmOptions: LLMOptions; protected openaiAdapter?: BaseLlmApi; constructor(_options: LLMOptions) { this._llmOptions = _options; + this.lastRequestId = undefined; // Set default options const options = { @@ -594,6 +597,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { + this.lastRequestId = undefined; const { completionOptions, logEnabled } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -623,6 +627,9 @@ export abstract class BaseLLM implements ILLM { signal, ); for await (const chunk of stream) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } const result = fromChatCompletionChunk(chunk); if (result) { const content = renderChatMessage(result); @@ -706,6 +713,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { + this.lastRequestId = undefined; const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -745,6 +753,7 @@ export abstract class BaseLLM implements ILLM { { ...toCompleteBody(prompt, completionOptions), stream: false }, signal, ); + this.lastRequestId = response.id ?? this.lastRequestId; completion = response.choices[0]?.text ?? ""; yield completion; } else { @@ -756,6 +765,9 @@ export abstract class BaseLLM implements ILLM { }, signal, )) { + if (!this.lastRequestId && typeof (chunk as any).id === "string") { + this.lastRequestId = (chunk as any).id; + } const content = chunk.choices[0]?.text ?? ""; completion += content; interaction?.logItem({ @@ -835,6 +847,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { + this.lastRequestId = undefined; const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -876,6 +889,7 @@ export abstract class BaseLLM implements ILLM { }, signal, ); + this.lastRequestId = result.id ?? this.lastRequestId; completion = result.choices[0].text; } else { completion = await this._complete(prompt, signal, completionOptions); @@ -985,6 +999,7 @@ export abstract class BaseLLM implements ILLM { options: LLMFullCompletionOptions = {}, messageOptions?: MessageOption, ): AsyncGenerator { + this.lastRequestId = undefined; let { completionOptions, logEnabled } = this._parseCompletionOptions(options); const interaction = logEnabled @@ -1054,6 +1069,7 @@ export abstract class BaseLLM implements ILLM { { ...body, stream: false }, signal, ); + this.lastRequestId = response.id ?? this.lastRequestId; const msg = fromChatResponse(response); yield msg; completion = this._formatChatMessage(msg); @@ -1071,6 +1087,12 @@ export abstract class BaseLLM implements ILLM { signal, ); for await (const chunk of stream) { + if ( + !this.lastRequestId && + typeof (chunk as any).id === "string" + ) { + this.lastRequestId = (chunk as any).id; + } const result = fromChatCompletionChunk(chunk); if (result) { completion += this._formatChatMessage(result); diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 988c57ac6..93d2016c3 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,3 +1,4 @@ +import FormData from "form-data"; import { ChatMessage, CompletionOptions, @@ -6,48 +7,169 @@ import { } from "../../index.js"; import { BaseLLM } from "../index.js"; +// Extended options for AskSage +interface AskSageCompletionOptions extends CompletionOptions { + mode?: "chat" | "deep_agent"; + limitReferences?: 0 | 1; + persona?: number; + systemPrompt?: string; + askSageTools?: AskSageTool[]; + enabledMcpTools?: string[]; + toolsToExecute?: string[]; + askSageToolChoice?: ToolChoice; + reasoningEffort?: "low" | "medium" | "high"; + deepAgentId?: number; + streaming?: boolean; + file?: unknown; +} + +const DEFAULT_API_URL = "https://api.asksage.ai/server"; +const DEFAULT_USER_API_URL = "https://api.asksage.ai/user"; +const TOKEN_TTL = 3600000; // 1 hour in milliseconds + +interface AskSageTool { + type: string; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +type ToolChoice = + | "auto" + | "none" + | { type: "function"; function: { name: string } }; + +interface AskSageRequestArgs { + model?: string; + temperature?: number; + mode?: "chat" | "deep_agent"; + message?: string | { user: string; message: string }[]; + live?: 0 | 1 | 2; + dataset?: string | string[]; + limit_references?: 0 | 1; + persona?: number; + system_prompt?: string; + tools?: AskSageTool[]; + enabled_mcp_tools?: string[]; + tools_to_execute?: string[]; + tool_choice?: ToolChoice; + reasoning_effort?: "low" | "medium" | "high"; + deep_agent_id?: number; + streaming?: boolean; + file?: unknown; +} + +interface AskSageResponse { + text?: string; + answer?: string; + message?: string; + status?: number | string; + response?: unknown; + choices?: Array<{ + message?: { + content?: string; + }; + }>; +} + +interface TokenResponse { + status: number | string; + response: { + access_token: string; + }; +} + class Asksage extends BaseLLM { static providerName = "askSage"; static defaultOptions: Partial = { - apiBase: "https://api.asksage.ai/server/", + apiBase: DEFAULT_API_URL, model: "gpt-4o", }; - private static modelConversion: { [key: string]: string } = { - "gpt-4o-gov": "gpt-4o-gov", // Works - "gpt-4o-mini-gov": "gpt-4o-mini-gov", - "gpt4-gov": "gpt4-gov", // Works - "gpt-gov": "gpt-gov", // Works - "gpt-4o": "gpt-4o", // Works - "gpt-4o-mini": "gpt-4o-mini", // Works - gpt4: "gpt4", // Works - "gpt4-32k": "gpt4-32k", - "gpt-o1": "gpt-o1", // Works - "gpt-o1-mini": "gpt-o1-mini", // Works - "gpt-o3-mini": "gpt-o3-mini", // Stub - "gpt-3.5-turbo": "gpt35-16k", // Works - "aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works - "claude-3-5-sonnet-latest": "claude-35-sonnet", // Works - "claude-3-opus-20240229": "claude-3-opus", // Works - "claude-3-sonnet-20240229": "claude-3-sonnet", // Works - "grok-beta": "xai-grok", - "groq-llama33": "groq-llama33", - "groq-70b": "groq-70b", - "mistral-large-latest": "mistral-large", // Works - "llama3-70b": "llma3", // Works - "gemini-1.5-pro-latest": "google-gemini-pro", // Works - }; + private sessionTokenPromise: Promise | null = null; + private tokenTimestamp: number = 0; + private email?: string; + private userApiUrl: string; constructor(options: LLMOptions) { super(options); this.apiVersion = options.apiVersion ?? "v1.2.4"; + this.email = process.env.ASKSAGE_EMAIL; + this.userApiUrl = process.env.ASKSAGE_USER_API_URL || DEFAULT_USER_API_URL; } - protected _convertModelName(model: string): string { - console.log("Converting model:", model); - const convertedModel = Asksage.modelConversion[model] ?? model; - console.log("Converted model:", convertedModel); - return convertedModel; + private async getSessionToken(): Promise { + if (!this.apiKey) { + throw new Error( + "AskSage adapter: missing ASKSAGE_API_KEY. Provide it in your environment variables or .env file.", + ); + } + + // If no email, use API key directly + if (!this.email || this.email.length === 0) { + return this.apiKey; + } + + const url = this.userApiUrl.replace(/\/$/, "") + "/get-token-with-api-key"; + const res = await this.fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: this.email, api_key: this.apiKey }), + }); + + const data = (await res.json()) as TokenResponse; + if (parseInt(String(data.status)) !== 200) { + throw new Error("Error getting access token: " + JSON.stringify(data)); + } + return data.response.access_token; + } + + private async getToken(): Promise { + // Check if token needs refresh + if ( + !this.sessionTokenPromise || + Date.now() - this.tokenTimestamp > TOKEN_TTL + ) { + this.sessionTokenPromise = this.getSessionToken(); + this.tokenTimestamp = Date.now(); + } + return this.sessionTokenPromise; + } + + private isFileLike(val: unknown): boolean { + return ( + val !== null && + val !== undefined && + ((typeof File !== "undefined" && val instanceof File) || + (typeof Buffer !== "undefined" && val instanceof Buffer) || + (typeof val === "object" && + ("path" in val || "name" in val || "type" in val))) + ); + } + + private toFormData(args: AskSageRequestArgs): FormData { + const form = new FormData(); + + for (const [key, value] of Object.entries(args)) { + if (value === undefined || value === null) continue; + + if (key === "file" && value) { + if (Buffer.isBuffer(value)) { + form.append("file", value, "file"); + } else if (typeof value === "string") { + form.append("file", value); + } else { + form.append("file", value as Buffer); + } + } else if (Array.isArray(value) || typeof value === "object") { + form.append(key, JSON.stringify(value)); + } else { + form.append(key, String(value)); + } + } + return form; } protected _convertMessage(message: ChatMessage) { @@ -63,43 +185,63 @@ class Asksage extends BaseLLM { }; } - protected _convertArgs(options: any, messages: ChatMessage[]) { - let formattedMessage: any; + protected _convertArgs( + options: AskSageCompletionOptions, + messages: ChatMessage[], + ): AskSageRequestArgs { + let formattedMessage: string | { user: string; message: string }[]; if (messages.length === 1) { - formattedMessage = messages[0].content; + formattedMessage = messages[0].content as string; } else { formattedMessage = messages.map(this._convertMessage); } - const args: any = { + const args: AskSageRequestArgs = { message: formattedMessage, - persona: options.persona ?? "default", - dataset: options.dataset ?? "none", - limit_references: options.limitReferences ?? 0, + model: options.model, temperature: options.temperature ?? 0.0, - live: options.live ?? 0, - model: this._convertModelName(options.model), + mode: "chat", // Always use chat mode + limit_references: 0, // Always use 0 + persona: options.persona as number | undefined, system_prompt: options.systemPrompt ?? + process.env.ASKSAGE_SYSTEM_PROMPT ?? "You are an expert software developer. You give helpful and concise responses.", - tools: options.tools, - tool_choice: options.toolChoice, + tools: options.askSageTools, + // enabled_mcp_tools: options.enabledMcpTools as string[] | undefined, + // tools_to_execute: options.toolsToExecute as string[] | undefined, + tool_choice: options.askSageToolChoice, + reasoning_effort: options.reasoningEffort as + | "low" + | "medium" + | "high" + | undefined, + deep_agent_id: options.deepAgentId as number | undefined, + streaming: options.streaming as boolean | undefined, + file: options.file, }; + // Remove undefined values Object.keys(args).forEach( - (key) => args[key] === undefined && delete args[key], + (key) => + args[key as keyof AskSageRequestArgs] === undefined && + delete args[key as keyof AskSageRequestArgs], ); return args; } - protected _getHeaders() { + protected async _getHeaders( + hasFile: boolean = false, + ): Promise> { + const token = await this.getToken(); const headers: Record = { - "Content-Type": "application/json", + accept: "application/json", + "x-access-tokens": token, }; - if (this.apiKey) { - headers["x-access-tokens"] = this.apiKey; + if (!hasFile) { + headers["Content-Type"] = "application/json"; } return headers; @@ -125,21 +267,66 @@ class Asksage extends BaseLLM { } const messages: ChatMessage[] = [{ role: "user", content: prompt }]; - const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return ""; // Aborted by user + if (response.status === 499) { + return ""; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + return ( + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "" + ); + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - return data.message; } protected async *_streamComplete( @@ -157,30 +344,74 @@ class Asksage extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - signal, - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return; // Aborted by user + if (response.status === 499) { + return; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + + const assistantMessage: ChatMessage = { + role: "assistant", + content: + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "", + }; + + yield assistantMessage; + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - - const assistantMessage: ChatMessage = { - role: "assistant", - content: data.message, - }; - - yield assistantMessage; } async listModels(): Promise { - return Object.keys(Asksage.modelConversion); + return []; } } diff --git a/core/llm/rules/alwaysApply.vitest.ts b/core/llm/rules/alwaysApply.vitest.ts index f8d6e1160..f586ff87d 100644 --- a/core/llm/rules/alwaysApply.vitest.ts +++ b/core/llm/rules/alwaysApply.vitest.ts @@ -44,7 +44,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: true, globs: "**/*.tsx", // Should be ignored since alwaysApply is true source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Test with no file context @@ -83,7 +83,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: false, globs: "**/*.tsx", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Rule with alwaysApply: false and no globs @@ -93,7 +93,7 @@ describe("alwaysApply Behavior", () => { alwaysApply: false, // No globs source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; // Test with no file context @@ -131,7 +131,7 @@ describe("alwaysApply Behavior", () => { name: "Default No Globs Rule", rule: "Default rule with no globs", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs }; @@ -141,7 +141,7 @@ describe("alwaysApply Behavior", () => { rule: "Default rule with globs", globs: "**/*.tsx", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, with globs }; diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 538ab03cf..b6073bf7d 100644 --- a/core/llm/rules/alwaysApplyRules.vitest.ts +++ b/core/llm/rules/alwaysApplyRules.vitest.ts @@ -15,7 +15,7 @@ describe("Rule application with alwaysApply", () => { rule: "This rule should always be applied", alwaysApply: true, source: "rules-block", - ruleFile: ".continue/always-apply.md", + sourceFile: ".continue/always-apply.md", }; // Create a colocated rule in a nested directory @@ -23,7 +23,7 @@ describe("Rule application with alwaysApply", () => { name: "Nested Directory Rule", rule: "This rule applies to files in the nested directory", source: "rules-block", - ruleFile: "nested-folder/rules.md", + sourceFile: "nested-folder/rules.md", }; it("should apply alwaysApply rules even with no file references", () => { @@ -145,7 +145,7 @@ describe("Rule application with alwaysApply", () => { rule: "This rule has alwaysApply: true but is blocked by rulePolicies", alwaysApply: true, source: "rules-block", - ruleFile: "src/some/path.md", + sourceFile: "src/some/path.md", }; // Message with no code blocks or file references diff --git a/core/llm/rules/fileProtocolMatching.vitest.ts b/core/llm/rules/fileProtocolMatching.vitest.ts index 075ca0472..310e868c5 100644 --- a/core/llm/rules/fileProtocolMatching.vitest.ts +++ b/core/llm/rules/fileProtocolMatching.vitest.ts @@ -8,7 +8,7 @@ describe("File Path Protocol Matching", () => { name: "Rule with file:// protocol", rule: "This is a test rule", source: "rules-block", - ruleFile: "file:///Users/user/project/nested-folder/rules.md", + sourceFile: "file:///Users/user/project/nested-folder/rules.md", }; it("should match relative paths with file:// protocol paths", () => { diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index dc03ad43f..078a2dcdf 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -132,7 +132,7 @@ const isFileInDirectory = ( * Checks if a rule is a root-level rule (.continue directory or no file path) */ const isRootLevelRule = (rule: RuleWithSource): boolean => { - return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between + return !rule.sourceFile || rule.sourceFile.includes(".continue/"); // sourceFile path is absolute - hence we need to check for it in between }; /** @@ -230,8 +230,8 @@ export const shouldApplyRule = ( const isRootRule = isRootLevelRule(rule); // For non-root rules, we need to check if any files are in the rule's directory - if (!isRootRule && rule.ruleFile) { - const ruleDirectory = getCleanUriPath(rule.ruleFile); + if (!isRootRule && rule.sourceFile) { + const ruleDirectory = getCleanUriPath(rule.sourceFile); const lastSlashIndex = ruleDirectory.lastIndexOf("/"); const ruleDirPath = lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : ""; @@ -325,7 +325,7 @@ export const getApplicableRules = ( }; export function getRuleId(rule: RuleWithSource): string { - return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source; + return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source; } export const getSystemMessageWithRules = ({ diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 9f350197d..104ceecf8 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -20,7 +20,7 @@ describe("Rule colocation glob matching", () => { name: "Components Rule", rule: "Use functional components with hooks", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // No explicit globs - should only apply to files in src/components/ directory }; @@ -43,7 +43,7 @@ describe("Rule colocation glob matching", () => { rule: "Use TypeScript with React components", globs: "**/*.tsx", // Only .tsx files source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", // Should only apply to .tsx files in src/components/ directory }; @@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => { name: "Root Rule", rule: "Follow project standards", source: "rules-block", - ruleFile: "/path/to/repo/.continue/rules.md", + sourceFile: "/path/to/repo/.continue/rules.md", // No restriction, should apply to all files }; @@ -89,7 +89,7 @@ describe("Rule colocation glob matching", () => { rule: "Follow these guidelines always", alwaysApply: true, source: "rules-block", - ruleFile: "src/specific/rules.md", + sourceFile: "src/specific/rules.md", // Should apply to all files regardless of directory }; @@ -107,7 +107,7 @@ describe("Rule colocation glob matching", () => { rule: "This rule should never apply", alwaysApply: false, source: "rules-block", - ruleFile: "src/specific/rules.md", + sourceFile: "src/specific/rules.md", // Should never apply since alwaysApply is false and there are no globs }; @@ -121,7 +121,7 @@ describe("Rule colocation glob matching", () => { rule: "Apply to TS files but not test files", globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"], source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", // Should only apply to non-test TS files in src/utils/ }; @@ -147,7 +147,7 @@ describe("Rule policies", () => { name: "Components Rule", rule: "Use functional components with hooks", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; const testFiles = ["src/components/Button.tsx"]; @@ -167,7 +167,7 @@ describe("Rule policies", () => { rule: "This rule would normally always apply", alwaysApply: true, source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; const offPolicies: RulePolicies = { @@ -212,7 +212,7 @@ describe("Rule policies", () => { name: "Root Rule", rule: "Follow project standards", source: "rules-block", - ruleFile: "/my/project/.continue/rules.md", + sourceFile: "/my/project/.continue/rules.md", }; // Off policy should override even global rules @@ -238,7 +238,7 @@ describe("Rule policies", () => { alwaysApply: true, globs: "**/*.ts", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; // Off policy should win over everything @@ -261,7 +261,7 @@ describe("Content pattern matching", () => { rule: "Follow React component standards", regex: "export (function|const) \\w+.*\\(", source: "rules-block", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }; // File that matches the pattern @@ -293,7 +293,7 @@ describe("Content pattern matching", () => { rule: "Apply to functions or classes", regex: ["function\\s+\\w+", "class\\s+\\w+"], source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; const filePath = "src/utils/helper.ts"; @@ -332,7 +332,7 @@ describe("Content pattern matching", () => { globs: "**/*.ts", regex: "class\\s+\\w+", source: "rules-block", - ruleFile: "src/models/rules.md", + sourceFile: "src/models/rules.md", }; const tsFilePath = "src/models/User.ts"; @@ -371,7 +371,7 @@ describe("Content pattern matching", () => { rule: "Use arrow functions for better this binding", regex: "const\\s+\\w+\\s*=\\s*\\(", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; // Message with code block containing a matching pattern @@ -433,7 +433,7 @@ describe("Content pattern matching", () => { rule: "This rule has an invalid regex pattern", regex: "([unclosed parenthesis", source: "rules-block", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }; const filePath = "src/utils/helper.ts"; @@ -454,7 +454,7 @@ describe("Content pattern matching", () => { rule: "Apply only to model files with interfaces", regex: "interface\\s+\\w+", source: "rules-block", - ruleFile: "src/models/rules.md", + sourceFile: "src/models/rules.md", }; // File in the correct directory with matching content diff --git a/core/llm/rules/implicitGlobalRules.vitest.ts b/core/llm/rules/implicitGlobalRules.vitest.ts index 3d9d62004..baa13745f 100644 --- a/core/llm/rules/implicitGlobalRules.vitest.ts +++ b/core/llm/rules/implicitGlobalRules.vitest.ts @@ -8,7 +8,7 @@ describe("Implicit global rules application", () => { name: "Implicit Global Rule", rule: "This rule should be applied to all messages (implicit global)", source: "rules-block", - ruleFile: ".continue/global-rule.md", + sourceFile: ".continue/global-rule.md", // No alwaysApply specified // No globs specified }; @@ -19,7 +19,7 @@ describe("Implicit global rules application", () => { rule: "This rule should always be applied (explicit global)", alwaysApply: true, source: "rules-block", - ruleFile: ".continue/explicit-global.md", + sourceFile: ".continue/explicit-global.md", }; // Create a colocated rule in a nested directory @@ -27,7 +27,7 @@ describe("Implicit global rules application", () => { name: "Nested Directory Rule", rule: "This rule applies to files in the nested directory", source: "rules-block", - ruleFile: "nested-folder/rules.md", + sourceFile: "nested-folder/rules.md", }; it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => { @@ -63,7 +63,7 @@ describe("Implicit global rules application", () => { name: "Root No Globs Rule", rule: "This is a root-level rule with no globs", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs }; @@ -119,7 +119,7 @@ describe("Implicit global rules application", () => { name: "Assistant Guidelines", rule: "SOLID Design Principles - Coding Assistant Guidelines", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", // No alwaysApply, no globs - should still apply }; diff --git a/core/llm/rules/nestedDirectoryRules.vitest.ts b/core/llm/rules/nestedDirectoryRules.vitest.ts index 7f55bc7c3..97f8f8238 100644 --- a/core/llm/rules/nestedDirectoryRules.vitest.ts +++ b/core/llm/rules/nestedDirectoryRules.vitest.ts @@ -13,7 +13,7 @@ describe("Nested directory rules application", () => { name: "Nested Folder Rule", rule: "HELLO WORLD THIS IS A RULE", source: "rules-block", - ruleFile: "manual-testing-sandbox/nested-folder/rules.md", + sourceFile: "manual-testing-sandbox/nested-folder/rules.md", // No globs specified }; @@ -22,7 +22,7 @@ describe("Nested directory rules application", () => { name: "Global Rule", rule: "SOLID Design Principles - Coding Agent Guidelines", source: "rules-block", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }; it("should apply nested directory rules to files in that directory", () => { @@ -103,7 +103,7 @@ describe("Nested directory rules application", () => { rule: "Follow Python best practices for src directory", globs: "**/*.py", // This should only match .py files in src/ and subdirectories source: "rules-block", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; // A rule in utils/ that targets *.py files @@ -112,7 +112,7 @@ describe("Nested directory rules application", () => { rule: "Follow Python best practices for utils directory", globs: "**/*.py", // This should only match .py files in utils/ and subdirectories source: "rules-block", - ruleFile: "utils/rules.md", + sourceFile: "utils/rules.md", }; // A file in src/ diff --git a/core/llm/rules/ruleColocation.vitest.ts b/core/llm/rules/ruleColocation.vitest.ts index 6bee635b0..644bfb957 100644 --- a/core/llm/rules/ruleColocation.vitest.ts +++ b/core/llm/rules/ruleColocation.vitest.ts @@ -10,7 +10,7 @@ describe("Rule colocation - glob pattern matching", () => { name: "General Rule", rule: "Follow coding standards", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }, // Redux-specific rule with specific directory/file type pattern @@ -19,7 +19,7 @@ describe("Rule colocation - glob pattern matching", () => { rule: "Use Redux Toolkit", globs: "src/redux/**/*.{ts,tsx}", source: "colocated-markdown", - ruleFile: "src/redux/rules.md", + sourceFile: "src/redux/rules.md", }, // Component-specific rule with array of globs @@ -28,7 +28,7 @@ describe("Rule colocation - glob pattern matching", () => { rule: "Use functional components", globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"], source: "colocated-markdown", - ruleFile: "src/components/rules.md", + sourceFile: "src/components/rules.md", }, // Rule with explicit alwaysApply: true @@ -38,7 +38,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: true, globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Rule with explicit alwaysApply: false @@ -48,7 +48,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: false, // No globs, so should never apply source: "colocated-markdown", - ruleFile: ".continue/rules.md", + sourceFile: ".continue/rules.md", }, // Rule with explicit alwaysApply: false but with globs @@ -58,7 +58,7 @@ describe("Rule colocation - glob pattern matching", () => { alwaysApply: false, globs: "src/utils/**/*.ts", source: "colocated-markdown", - ruleFile: "src/utils/rules.md", + sourceFile: "src/utils/rules.md", }, }; @@ -128,7 +128,7 @@ describe("Rule colocation - glob pattern matching", () => { // Fix: Specify the exact path prefix to restrict to this directory structure globs: "src/features/auth/utils/**/*.ts", source: "colocated-markdown", - ruleFile: "src/features/auth/utils/rules.md", + sourceFile: "src/features/auth/utils/rules.md", }; it("should apply nested rules to files in the same directory and subdirectories", () => { @@ -158,7 +158,7 @@ describe("Rule colocation - glob pattern matching", () => { // Testing with standard pattern instead globs: "src/**/[!.]*.ts", source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; it("should apply to matching files that are not excluded", () => { @@ -175,7 +175,7 @@ describe("Rule colocation - glob pattern matching", () => { globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"], alwaysApply: false, source: "colocated-markdown", - ruleFile: "src/rules.md", + sourceFile: "src/rules.md", }; // Using alwaysApply:false with a more specific test diff --git a/core/llm/rules/rules-utils.ts b/core/llm/rules/rules-utils.ts index 3645576ed..41afc7cc0 100644 --- a/core/llm/rules/rules-utils.ts +++ b/core/llm/rules/rules-utils.ts @@ -27,14 +27,14 @@ export function getRuleSourceDisplayName(rule: RuleWithSource): string { case "model-options-chat": return "Base System Chat Message"; case "agent-file": - if (rule.ruleFile) { - return getLastNPathParts(rule.ruleFile, 2); + if (rule.sourceFile) { + return getLastNPathParts(rule.sourceFile, 2); } else { return "Agent file"; } case "colocated-markdown": - if (rule.ruleFile) { - return getLastNPathParts(rule.ruleFile, 2); + if (rule.sourceFile) { + return getLastNPathParts(rule.sourceFile, 2); } else { return "rules.md"; } diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index 5f368a9be..ad883e4cb 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -41,7 +41,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should return true for Gemini models", () => { expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true); - expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe( + expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe( true, ); }); @@ -139,7 +139,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should return true for all Gemini models", () => { expect(supportsFn("gemini-pro")).toBe(true); - expect(supportsFn("gemini-1.5-pro")).toBe(true); expect(supportsFn("gemini-ultra")).toBe(true); }); @@ -150,7 +149,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { it("should handle case insensitivity", () => { expect(supportsFn("GEMINI-pro")).toBe(true); - expect(supportsFn("Gemini-1.5-Pro")).toBe(true); + expect(supportsFn("Gemini-2.5-Pro")).toBe(true); }); }); diff --git a/core/nextEdit/NextEditLoggingService.ts b/core/nextEdit/NextEditLoggingService.ts index 4ed9ed4e9..430cb576a 100644 --- a/core/nextEdit/NextEditLoggingService.ts +++ b/core/nextEdit/NextEditLoggingService.ts @@ -1,5 +1,7 @@ import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; +import { fetchwithRequestOptions } from "@continuedev/fetch"; +import { getControlPlaneEnvSync } from "../control-plane/env"; import { DataLogger } from "../data/log"; import { Telemetry } from "../util/posthog"; import { NextEditOutcome } from "./types"; @@ -121,6 +123,7 @@ export class NextEditLoggingService { clearTimeout(this._logRejectionTimeouts.get(completionId)!); this._logRejectionTimeouts.delete(completionId); } + if (this._outcomes.has(completionId)) { this._outcomes.delete(completionId); } @@ -185,44 +188,15 @@ export class NextEditLoggingService { this._logRejectionTimeouts.delete(completionId); } - // If we have the full outcome, log it as aborted. + // Only log if the completion was displayed to the user. + // This aligns with Autocomplete behavior and prevents logging + // of cancelled requests that never reached the user. if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - outcome.accepted = false; + // outcome.accepted = false; outcome.aborted = true; this.logNextEditOutcome(outcome); this._outcomes.delete(completionId); - } else { - // Log minimal abort event for requests that never got displayed. - const pendingData = this._pendingCompletions.get(completionId); - - const minimalAbortOutcome: Partial = { - completionId, - accepted: false, - aborted: true, - timestamp: Date.now(), - uniqueId: completionId, - elapsed: pendingData ? Date.now() - pendingData.startTime : 0, - modelName: pendingData?.modelName || "unknown", - modelProvider: pendingData?.modelProvider || "unknown", - fileUri: pendingData?.filepath || "unknown", - - // Empty/default values for fields we don't have. - completion: "", - prompt: "", - userEdits: "", - userExcerpts: "", - originalEditableRange: "", - workspaceDirUri: "", - cursorPosition: { line: -1, character: -1 }, - finalCursorPosition: { line: -1, character: -1 }, - editableRegionStartLine: -1, - editableRegionEndLine: -1, - diffLines: [], - completionOptions: {}, - }; - - this.logNextEditOutcome(minimalAbortOutcome as NextEditOutcome); } // Clean up. @@ -243,6 +217,35 @@ export class NextEditLoggingService { }); // const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; + if (outcome.requestId && outcome.accepted !== undefined) { + void this.logAcceptReject(outcome.requestId, outcome.accepted); + } void Telemetry.capture("nextEditOutcome", outcome, true); } + + private async logAcceptReject( + requestId: string, + accepted: boolean, + ): Promise { + try { + if (!Telemetry.client) { + return; + } + + const controlPlaneEnv = getControlPlaneEnvSync("production"); + const resp = await fetchwithRequestOptions( + new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL), + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + requestId, + accepted, + }), + }, + ); + } catch (error) {} + } } diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index ad35db3b9..d6af3598d 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -140,7 +140,7 @@ export class PrefetchQueue { const count = Math.min(3, this.processedQueue.length); const firstThree = this.processedQueue.slice(0, count); firstThree.forEach((item, index) => { - console.log( + console.debug( `Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`, ); }); diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 4d9216914..1150f5545 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -8,6 +8,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; +import { postprocessCompletion } from "../autocomplete/postprocessing/index.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; @@ -415,6 +416,7 @@ export class NextEditProvider { filePath: helper.filepath, diffType: DiffFormatType.Unified, contextLines: 3, + workspaceDir: workspaceDirs[0], // Use first workspace directory }), }; @@ -468,33 +470,53 @@ export class NextEditProvider { } // Extract completion using model-specific logic. - const nextCompletion = this.modelProvider.extractCompletion(msg.content); + let nextCompletion = this.modelProvider.extractCompletion(msg.content); + + // Postprocess the completion (same as autocomplete). + const postprocessed = postprocessCompletion({ + completion: nextCompletion, + llm, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, + }); + + // Return early if postprocessing filtered out the completion. + if (!postprocessed) { + return undefined; + } + + nextCompletion = postprocessed; let outcome: NextEditOutcome | undefined; // Handle based on diff type. + const profileType = + this.configHandler.currentProfile?.profileDescription.profileType; + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { - outcome = await this.modelProvider.handlePartialFileDiff( + outcome = await this.modelProvider.handlePartialFileDiff({ helper, editableRegionStartLine, editableRegionEndLine, startTime, llm, nextCompletion, - this.promptMetadata!, - this.ide, - ); + promptMetadata: this.promptMetadata!, + ide: this.ide, + profileType, + }); } else { - outcome = await this.modelProvider.handleFullFileDiff( + outcome = await this.modelProvider.handleFullFileDiff({ helper, editableRegionStartLine, editableRegionEndLine, startTime, llm, nextCompletion, - this.promptMetadata!, - this.ide, - ); + promptMetadata: this.promptMetadata!, + ide: this.ide, + profileType, + }); } if (outcome) { diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 38a76b051..773b05805 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -1,4 +1,5 @@ import { createPatch } from "diff"; +import { getUriPathBasename } from "../../util/uri"; export enum DiffFormatType { Unified = "unified", @@ -18,6 +19,7 @@ export interface CreateDiffArgs { filePath: string; diffType: DiffFormatType; contextLines: number; + workspaceDir?: string; } export const createDiff = ({ @@ -26,6 +28,7 @@ export const createDiff = ({ filePath, diffType, contextLines, + workspaceDir, }: CreateDiffArgs) => { switch (diffType) { case DiffFormatType.Unified: @@ -34,6 +37,7 @@ export const createDiff = ({ afterContent, filePath, contextLines, + workspaceDir, ); case DiffFormatType.TokenLineDiff: return createTokenLineDiff(beforeContent, afterContent, filePath); @@ -46,6 +50,7 @@ const createUnifiedDiff = ( afterContent: string, filePath: string, contextLines: number, + workspaceDir?: string, ) => { const normalizedBefore = beforeContent.endsWith("\n") ? beforeContent @@ -54,12 +59,21 @@ const createUnifiedDiff = ( ? afterContent : afterContent + "\n"; + // Use relative path if workspace directory is provided + let displayPath = filePath; + if (workspaceDir && filePath.startsWith(workspaceDir)) { + displayPath = filePath.slice(workspaceDir.length).replace(/^[\/]/, ""); + } else if (workspaceDir) { + // Fallback to just the basename if we can't determine relative path + displayPath = getUriPathBasename(filePath); + } + const patch = createPatch( - filePath, + displayPath, normalizedBefore, normalizedAfter, - "before", - "after", + undefined, + undefined, { context: contextLines }, ); diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts index b010f7837..889059037 100644 --- a/core/nextEdit/context/diffFormatting.vitest.ts +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -127,6 +127,72 @@ describe("diffFormatting", () => { expect(result).toContain("@@ -4,5 +4,5 @@"); }); + + it("should use relative path when workspaceDir is provided", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///workspace/project/src/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project", + }; + + const result = createDiff(args); + + expect(result).toContain("--- src/test.js"); + expect(result).toContain("+++ src/test.js"); + expect(result).not.toContain("file://"); + expect(result).not.toContain("/workspace/project"); + }); + + it("should handle workspaceDir with trailing slash", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///workspace/project/src/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project/", + }; + + const result = createDiff(args); + + expect(result).toContain("--- src/test.js"); + expect(result).toContain("+++ src/test.js"); + }); + + it("should fallback to basename when path not in workspace", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: "file:///other/location/test.js", + diffType: DiffFormatType.Unified, + contextLines: 3, + workspaceDir: "file:///workspace/project", + }; + + const result = createDiff(args); + + expect(result).toContain("--- test.js"); + expect(result).toContain("+++ test.js"); + }); + + it("should use full path when no workspaceDir provided", () => { + const fullPath = "file:///workspace/project/src/test.js"; + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: fullPath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain(`--- ${fullPath}`); + expect(result).toContain(`+++ ${fullPath}`); + }); }); describe("createBeforeAfterDiff", () => { diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index 2aa4adb79..8b6e41a82 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -140,6 +140,7 @@ export const processNextEditData = async ({ filePath: filePath, diffType: DiffFormatType.Unified, contextLines: 25, // storing many context lines for downstream trimming + workspaceDir: workspaceDir, }), fileUri: filePath, workspaceUri: workspaceDir, diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index a98233cfe..c2fc85786 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -14,16 +14,6 @@ export const processSmallEdit = async ( getDefsFromLspFunction: GetLspDefinitionsFunction, ide: IDE, ) => { - NextEditProvider.getInstance().addDiffToContext( - createDiff({ - beforeContent: beforeAfterdiff.beforeContent, - afterContent: beforeAfterdiff.afterContent, - filePath: beforeAfterdiff.filePath, - diffType: DiffFormatType.Unified, - contextLines: 5, // NOTE: This can change depending on experiments! - }), - ); - // Get the current context data from the most recent message const currentData = (EditAggregator.getInstance() as any) .latestContextData || { @@ -33,6 +23,17 @@ export const processSmallEdit = async ( recentlyVisitedRanges: [], }; + NextEditProvider.getInstance().addDiffToContext( + createDiff({ + beforeContent: beforeAfterdiff.beforeContent, + afterContent: beforeAfterdiff.afterContent, + filePath: beforeAfterdiff.filePath, + diffType: DiffFormatType.Unified, + contextLines: 3, // NOTE: This can change depending on experiments! + workspaceDir: currentData.workspaceDir, + }), + ); + void processNextEditData({ filePath: beforeAfterdiff.filePath, beforeContent: beforeAfterdiff.beforeContent, diff --git a/core/nextEdit/providers/BaseNextEditProvider.ts b/core/nextEdit/providers/BaseNextEditProvider.ts index 2a0bea8ed..0c8fa2f62 100644 --- a/core/nextEdit/providers/BaseNextEditProvider.ts +++ b/core/nextEdit/providers/BaseNextEditProvider.ts @@ -47,16 +47,28 @@ export abstract class BaseNextEditModelProvider { }; // Methods that can be used as default fallback. - public async handlePartialFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + public async handlePartialFileDiff(params: { + helper: HelperVars; + editableRegionStartLine: number; + editableRegionEndLine: number; + startTime: number; + llm: ILLM; + nextCompletion: string; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + promptMetadata, + ide, + profileType, + } = params; const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) @@ -83,21 +95,34 @@ export abstract class BaseNextEditModelProvider { originalEditableRange: oldEditRangeSlice, diffLines: [], ide, + profileType, }); return outcome; } - public async handleFullFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + public async handleFullFileDiff(params: { + helper: HelperVars; + editableRegionStartLine: number; + editableRegionEndLine: number; + startTime: number; + llm: ILLM; + nextCompletion: string; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + promptMetadata, + ide, + profileType, + } = params; const fileSlice = helper.fileLines .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); @@ -111,7 +136,7 @@ export abstract class BaseNextEditModelProvider { const currentLine = helper.pos.line; const prefetchQueue = PrefetchQueue.getInstance(); - const cursorLocalDiffGroup = await this.processDiffGroups( + const cursorLocalDiffGroup = await this.processDiffGroups({ diffGroups, currentLine, helper, @@ -120,19 +145,21 @@ export abstract class BaseNextEditModelProvider { prefetchQueue, promptMetadata, ide, - ); + profileType, + }); if (cursorLocalDiffGroup) { - return await this.createOutcomeFromDiffGroup( - cursorLocalDiffGroup, + return await this.createOutcomeFromDiffGroup({ + diffGroup: cursorLocalDiffGroup, helper, startTime, llm, - helper.input.completionId, - true, + completionId: helper.input.completionId, + isCurrentCursorGroup: true, promptMetadata, ide, - ); + profileType, + }); } return undefined; @@ -141,23 +168,35 @@ export abstract class BaseNextEditModelProvider { /** * Process diff groups and find the one containing the cursor. */ - private async processDiffGroups( - diffGroups: DiffGroup[], - currentLine: number, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async processDiffGroups(params: { + diffGroups: DiffGroup[]; + currentLine: number; + helper: HelperVars; + startTime: number; + llm: ILLM; + prefetchQueue: PrefetchQueue; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + diffGroups, + currentLine, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + profileType, + } = params; let cursorGroup: DiffGroup | undefined; for (const group of diffGroups) { if (currentLine >= group.startLine && currentLine <= group.endLine) { cursorGroup = group; } else { - await this.addDiffGroupToPrefetchQueue( + await this.addDiffGroupToPrefetchQueue({ group, helper, startTime, @@ -165,22 +204,34 @@ export abstract class BaseNextEditModelProvider { prefetchQueue, promptMetadata, ide, - ); + profileType, + }); } } return cursorGroup; } - private async addDiffGroupToPrefetchQueue( - group: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async addDiffGroupToPrefetchQueue(params: { + group: DiffGroup; + helper: HelperVars; + startTime: number; + llm: ILLM; + prefetchQueue: PrefetchQueue; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + group, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + profileType, + } = params; // Extract lines that are not old. const groupContent = group.lines .filter((l) => l.type !== "old") @@ -223,6 +274,7 @@ export abstract class BaseNextEditModelProvider { completionId: uuidv4(), // Generate a new ID for this prefetched item. diffLines: group.lines, ide, + profileType, }); prefetchQueue.enqueueProcessed({ @@ -231,16 +283,28 @@ export abstract class BaseNextEditModelProvider { }); } - private async createOutcomeFromDiffGroup( - diffGroup: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - completionId: string, - isCurrentCursorGroup: boolean, - promptMetadata: PromptMetadata, - ide: IDE, - ): Promise { + private async createOutcomeFromDiffGroup(params: { + diffGroup: DiffGroup; + helper: HelperVars; + startTime: number; + llm: ILLM; + completionId: string; + isCurrentCursorGroup: boolean; + promptMetadata: PromptMetadata; + ide: IDE; + profileType?: "local" | "platform" | "control-plane"; + }): Promise { + const { + diffGroup, + helper, + startTime, + llm, + completionId, + isCurrentCursorGroup, + promptMetadata, + ide, + profileType, + } = params; const groupContent = diffGroup.lines .filter((l) => l.type !== "old") .map((l) => l.line) @@ -278,6 +342,7 @@ export abstract class BaseNextEditModelProvider { completionId, diffLines: diffGroup.lines, ide, + profileType, }); return outcomeNext; @@ -299,6 +364,7 @@ export abstract class BaseNextEditModelProvider { completionId?: string; diffLines: DiffLine[]; ide: IDE; + profileType?: "local" | "platform" | "control-plane"; }): Promise { return { elapsed: Date.now() - outcomeCtx.startTime, @@ -309,6 +375,7 @@ export abstract class BaseNextEditModelProvider { outcomeCtx.completionId || outcomeCtx.helper.input.completionId, gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), uniqueId: await outcomeCtx.ide.getUniqueId(), + requestId: outcomeCtx.llm.lastRequestId, timestamp: Date.now(), fileUri: outcomeCtx.helper.filepath, workspaceDirUri: @@ -324,6 +391,7 @@ export abstract class BaseNextEditModelProvider { editableRegionStartLine: outcomeCtx.editableRegionStartLine, editableRegionEndLine: outcomeCtx.editableRegionEndLine, diffLines: outcomeCtx.diffLines, + profileType: outcomeCtx.profileType, ...outcomeCtx.helper.options, }; } diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 8d08f8216..2d742c697 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions { completionId: string; gitRepo?: string; uniqueId: string; + requestId?: string; timestamp: number; // New for Next Edit. @@ -67,6 +68,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions { editableRegionStartLine: number; editableRegionEndLine: number; diffLines: DiffLine[]; + profileType?: "local" | "platform" | "control-plane"; } export interface PromptMetadata { diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index 8ca4f1966..6a3837e3a 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -1,86 +1,15 @@ -import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; +import path from "path"; +import { + DEFAULT_PROMPTS_FOLDER_V1, + DEFAULT_PROMPTS_FOLDER_V2, + DEFAULT_RULES_FOLDER, + RULES_DIR_NAME, +} from "."; import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; -import { readAllGlobalPromptFiles } from "../util/paths"; +import { getContinueGlobalPath, readAllGlobalPromptFiles } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; -// The hardcoded init prompt content -const INIT_PROMPT_CONTENT = `name: Init -description: Initialize Codebase ---- -You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project. - -## Step 1: Check Required Tools -First, verify that you have access to the necessary tools: -- builtin_file_glob_search: To discover project files -- builtin_read_file: To analyze file contents -- builtin_ls: To explore directory structure -- builtin_create_new_file: To generate the CONTINUE.md file - -If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. - -## Step 2: Project Analysis -Analyze the project structure and key files to understand: -- The programming languages and frameworks used -- The overall architecture and organization -- Key components and their responsibilities -- Important configuration files -- Build/deployment system - -## Step 3: Generate CONTINUE.md -Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections: - -1. **Project Overview** - - Brief description of the project's purpose - - Key technologies used - - High-level architecture - -2. **Getting Started** - - Prerequisites (required software, dependencies) - - Installation instructions - - Basic usage examples - - Running tests - -3. **Project Structure** - - Overview of main directories and their purpose - - Key files and their roles - - Important configuration files - -4. **Development Workflow** - - Coding standards or conventions - - Testing approach - - Build and deployment process - - Contribution guidelines - -5. **Key Concepts** - - Domain-specific terminology - - Core abstractions - - Design patterns used - -6. **Common Tasks** - - Step-by-step guides for frequent development tasks - - Examples of common operations - -7. **Troubleshooting** - - Common issues and their solutions - - Debugging tips - -8. **References** - - Links to relevant documentation - - Important resources - -Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. - -## Step 4: Finalize -After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to: -1. Review and edit the file as needed -2. Commit it to their repository to share with their team -3. Explain that Continue will automatically load this file into context when working with the project - -Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`; - -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; - export async function getPromptFilesFromDir( ide: IDE, dir: string, @@ -115,7 +44,7 @@ export async function getAllPromptFiles( const workspaceDirs = await ide.getWorkspaceDirs(); let promptFiles: { path: string; content: string }[] = []; - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, DEFAULT_RULES_FOLDER]; if (checkV1DefaultFolder) { dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); } @@ -131,20 +60,16 @@ export async function getAllPromptFiles( await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) ).flat(); - // Also read from ~/.continue/.prompts + // Also read from ~/.continue/prompts and ~/.continue/rules promptFiles.push(...readAllGlobalPromptFiles()); - // Add hardcoded init prompt - promptFiles.push({ - path: "builtin:/init.prompt", - content: INIT_PROMPT_CONTENT, - }); + const promptFilesFromRulesDirectory = readAllGlobalPromptFiles( + path.join(getContinueGlobalPath(), RULES_DIR_NAME), + ); + promptFiles.push(...promptFilesFromRulesDirectory); return await Promise.all( promptFiles.map(async (file) => { - if (file.path.startsWith("builtin:")) { - return file; - } const content = await ide.readFile(file.path); return { path: file.path, content }; }), diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts index ee5fb6b84..58be45fe8 100644 --- a/core/promptFiles/index.ts +++ b/core/promptFiles/index.ts @@ -2,6 +2,11 @@ import { ContextProviderName } from ".."; export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; +export const DEFAULT_RULES_FOLDER = ".continue/rules"; + +// Subdirectory names (without .continue/ prefix) +export const RULES_DIR_NAME = "rules"; +export const PROMPTS_DIR_NAME = "prompts"; export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ "file", diff --git a/core/promptFiles/initPrompt.ts b/core/promptFiles/initPrompt.ts new file mode 100644 index 000000000..f436d6e43 --- /dev/null +++ b/core/promptFiles/initPrompt.ts @@ -0,0 +1,86 @@ +import { SlashCommandWithSource } from ".."; +import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants"; +import { BuiltInToolNames } from "../tools/builtIn"; + +const initFilename = "CONTINUE.md"; + +// Prompt for init slash command +export const INIT_PROMPT_CONTENT = ` +You are an expert development assistant. Your task is to create a comprehensive ${initFilename} project guide for the user's codebase to help them and their team better understand and work with the project. + +## Step 1: Check Required Tools +First, verify that you have access to the necessary tools: +- ${BuiltInToolNames.FileGlobSearch}: To discover project files +- ${BuiltInToolNames.ReadFile}: To analyze file contents +- ${BuiltInToolNames.LSTool}: To explore directory structure +- ${BuiltInToolNames.CreateNewFile}: To generate the ${initFilename} file + +If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding. + +## Step 2: Project Analysis +Analyze the project structure and key files to understand: +- The programming languages and frameworks used +- The overall architecture and organization +- Key components and their responsibilities +- Important configuration files +- Build/deployment system + +## Step 3: Generate ${initFilename} +Create a comprehensive ${initFilename} file in the .continue/rules/ directory with the following sections: + +1. **Project Overview** + - Brief description of the project's purpose + - Key technologies used + - High-level architecture + +2. **Getting Started** + - Prerequisites (required software, dependencies) + - Installation instructions + - Basic usage examples + - Running tests + +3. **Project Structure** + - Overview of main directories and their purpose + - Key files and their roles + - Important configuration files + +4. **Development Workflow** + - Coding standards or conventions + - Testing approach + - Build and deployment process + - Contribution guidelines + +5. **Key Concepts** + - Domain-specific terminology + - Core abstractions + - Design patterns used + +6. **Common Tasks** + - Step-by-step guides for frequent development tasks + - Examples of common operations + +7. **Troubleshooting** + - Common issues and their solutions + - Debugging tips + +8. **References** + - Links to relevant documentation + - Important resources + +Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification. + +## Step 4: Finalize +After creating the .continue/rules/${initFilename} file, provide a summary of what you've created and remind the user to: +1. Review and edit the file as needed +2. Commit it to their repository to share with their team +3. Explain that Continue will automatically load this file into context when working with the project + +Also inform the user that they can create additional ${RULES_MARKDOWN_FILENAME} files in subdirectories for more specific documentation related to those components. +`.trim(); + +export const initSlashCommand: SlashCommandWithSource = { + name: "Init", + description: "Initialize Codebase", + source: "built-in", + prompt: INIT_PROMPT_CONTENT, +}; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index c92945888..c559d9f64 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -54,6 +54,7 @@ import { } from "../control-plane/client"; import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; import { NextEditOutcome } from "../nextEdit/types"; +import { ContinueErrorReason } from "../util/errors"; export enum OnboardingModes { API_KEY = "API Key", @@ -93,6 +94,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { void, ]; "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; + "config/addGlobalRule": [undefined, void]; "config/newPromptFile": [undefined, void]; "config/newAssistantFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; @@ -117,10 +119,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { ), void, ]; - "config/openProfile": [ - { profileId: string | undefined; element?: { sourceFile?: string } }, - void, - ]; + "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ { @@ -147,8 +146,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; - "mcp/disconnectServer": [{ id: string }, void]; - "mcp/getDisconnectedServers": [undefined, string[]]; + "mcp/setServerEnabled": [{ id: string; enabled: boolean }, void]; "mcp/getPrompt": [ { serverName: string; @@ -318,6 +316,14 @@ export type ToCoreFromIdeOrWebviewProtocol = { { toolName: string; basePolicy: ToolPolicy; args: Record }, { policy: ToolPolicy; displayValue?: string }, ]; + "tools/preprocessArgs": [ + { toolName: string; args: Record }, + { + preprocessedArgs?: Record; + errorReason?: ContinueErrorReason; + errorMessage?: string; + }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 21eab1f7f..79e7de10b 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -3,6 +3,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, + AddToChatPayload, ApplyState, ApplyToFilePayload, HighlightedCodePayload, @@ -78,4 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; + addToChat: [AddToChatPayload, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f02727a37..5a6f45eba 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/newAssistantFile", "config/ideSettingsUpdate", "config/addLocalWorkspaceBlock", + "config/addGlobalRule", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", @@ -32,8 +33,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "mcp/getPrompt", "mcp/startAuthentication", "mcp/removeAuthentication", - "mcp/disconnectServer", - "mcp/getDisconnectedServers", + "mcp/setServerEnabled", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -82,6 +82,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "tools/evaluatePolicy", + "tools/preprocessArgs", "controlPlane/getEnvironment", "controlPlane/getFreeTrialStatus", "controlPlane/getModelsAddOnUpgradeUrl", diff --git a/core/tools/constants.ts b/core/tools/constants.ts index 0b5278209..332a270ef 100644 --- a/core/tools/constants.ts +++ b/core/tools/constants.ts @@ -1,2 +1,4 @@ export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; +export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE = + "There was an error calling the tool."; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts index 1fb045b22..e526b90e5 100644 --- a/core/tools/definitions/multiEdit.ts +++ b/core/tools/definitions/multiEdit.ts @@ -1,4 +1,7 @@ import { Tool } from "../.."; +import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation"; +import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; @@ -107,4 +110,24 @@ WARNINGS: ], }, defaultToolPolicy: "allowedWithPermission", + preprocessArgs: async (args, extras) => { + const { edits } = validateMultiEdit(args); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, + extras.ide, + ); + + const editingFileContents = await extras.ide.readFile(fileUri); + const newFileContents = executeMultiFindAndReplace( + editingFileContents, + edits, + ); + + return { + ...args, + fileUri, + editingFileContents, + newFileContents, + }; + }, }; diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts index 0fd7b5de8..b2d924ec9 100644 --- a/core/tools/definitions/requestRule.test.ts +++ b/core/tools/definitions/requestRule.test.ts @@ -10,7 +10,7 @@ describe("getRequestRuleDescription", () => { source: "default-chat", rule: "Always use semicolons", alwaysApply: true, - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with Globs", @@ -18,7 +18,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use TypeScript", globs: "**/*.ts", - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, ]; @@ -38,7 +38,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use consistent formatting", alwaysApply: false, - ruleFile: "/path/to/agent-rule1.md", + sourceFile: "/path/to/agent-rule1.md", }, { name: "Agent Rule 2", @@ -46,7 +46,7 @@ describe("getRequestRuleDescription", () => { source: "default-agent", rule: "Follow naming conventions", alwaysApply: false, - ruleFile: "/path/to/agent-rule2.md", + sourceFile: "/path/to/agent-rule2.md", }, // These should be filtered out { @@ -55,7 +55,7 @@ describe("getRequestRuleDescription", () => { source: "default-chat", rule: "Always use semicolons", alwaysApply: true, - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with Globs", @@ -63,7 +63,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Use TypeScript", globs: "**/*.ts", - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, ]; @@ -84,7 +84,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule content", alwaysApply: false, - ruleFile: "/path/to/no-desc-rule.md", + sourceFile: "/path/to/no-desc-rule.md", }, ]; @@ -104,7 +104,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule content", alwaysApply: false, - ruleFile: "/path/to/no-name-rule.md", + sourceFile: "/path/to/no-name-rule.md", }, ]; @@ -117,7 +117,7 @@ describe("getRequestRuleDescription", () => { expect(result).toBe(expected); }); - it("should handle rules with missing ruleFile", () => { + it("should handle rules with missing sourceFile", () => { const rules: RuleWithSource[] = [ { name: "Rule Without File", @@ -144,7 +144,7 @@ describe("getRequestRuleDescription", () => { description: "This should be filtered out", source: "rules-block", rule: "Some rule", - ruleFile: "/path/to/rule.md", + sourceFile: "/path/to/rule.md", // alwaysApply is undefined, which is truthy in the filter condition }, { @@ -153,7 +153,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule", alwaysApply: false, - ruleFile: "/path/to/valid-rule.md", + sourceFile: "/path/to/valid-rule.md", }, ]; @@ -175,7 +175,7 @@ describe("getRequestRuleDescription", () => { rule: "Some rule", alwaysApply: false, globs: "**/*.ts", - ruleFile: "/path/to/rule1.md", + sourceFile: "/path/to/rule1.md", }, { name: "Rule with array globs", @@ -184,7 +184,7 @@ describe("getRequestRuleDescription", () => { rule: "Some rule", alwaysApply: false, globs: ["**/*.ts", "**/*.js"], - ruleFile: "/path/to/rule2.md", + sourceFile: "/path/to/rule2.md", }, { name: "Valid Agent Rule", @@ -192,7 +192,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Some rule", alwaysApply: false, - ruleFile: "/path/to/valid-rule.md", + sourceFile: "/path/to/valid-rule.md", }, ]; @@ -224,7 +224,7 @@ describe("getRequestRuleDescription", () => { source: "rules-block", rule: "Follow this guideline", alwaysApply: false, - ruleFile: "/path/to/single-rule.md", + sourceFile: "/path/to/single-rule.md", }, ]; diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts index 653fba584..c5b2995e1 100644 --- a/core/tools/definitions/singleFindAndReplace.ts +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -1,4 +1,7 @@ import { Tool } from "../.."; +import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils"; +import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace"; +import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile"; @@ -70,4 +73,31 @@ WARNINGS: ], }, defaultToolPolicy: "allowedWithPermission", + preprocessArgs: async (args, extras) => { + const { oldString, newString, replaceAll } = validateSingleEdit( + args.old_string, + args.new_string, + args.replace_all, + ); + const fileUri = await validateSearchAndReplaceFilepath( + args.filepath, + extras.ide, + ); + + const editingFileContents = await extras.ide.readFile(fileUri); + const newFileContents = executeFindAndReplace( + editingFileContents, + oldString, + newString, + replaceAll ?? false, + 0, + ); + + return { + ...args, + fileUri, + editingFileContents, + newFileContents, + }; + }, }; diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index 61467e429..c5c312e70 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -7,7 +7,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { // Find the rule by name in the config const rule = extras.config.rules.find((r) => r.name === name); - if (!rule || !rule.ruleFile) { + if (!rule || !rule.sourceFile) { throw new Error(`Rule with name "${name}" not found or has no file path`); } @@ -18,7 +18,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { content: rule.rule, uri: { type: "file", - value: rule.ruleFile, + value: rule.sourceFile, }, }, ]; diff --git a/core/tools/index.ts b/core/tools/index.ts index e021a601c..bdc519dc9 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = ( return tools; }; + +export function serializeTool(tool: Tool) { + const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool; + return rest; +} diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 0a1778395..44b9b5f11 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -30,6 +30,7 @@ export type GlobalContextType = { selectedModelsByProfileId: { [profileId: string]: GlobalContextModelSelections; }; + cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users /** * This is needed to handle the case where a JetBrains user has created diff --git a/core/util/errors.ts b/core/util/errors.ts index 9a5c07443..4c6cfb16d 100644 --- a/core/util/errors.ts +++ b/core/util/errors.ts @@ -27,6 +27,7 @@ export enum ContinueErrorReason { FindAndReplaceMissingOldString = "find_and_replace_missing_old_string", FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string", FindAndReplaceMissingNewString = "find_and_replace_missing_new_string", + FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all", FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found", FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences", FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath", @@ -48,6 +49,6 @@ export enum ContinueErrorReason { ParentDirectoryNotFound = "parent_directory_not_found", // Other - Unspecified = "unspecified", - Unknown = "unknown", + Unspecified = "unspecified", // I.e. a known error but no specific code for it + Unknown = "unknown", // I.e. an unexpected error } diff --git a/docs/CONTRIBUTING.mdx b/docs/CONTRIBUTING.mdx new file mode 100644 index 000000000..33cd1ac17 --- /dev/null +++ b/docs/CONTRIBUTING.mdx @@ -0,0 +1,318 @@ +--- +title: "Contributing to Continue Documentation" +sidebarTitle: "Docs Contributions" +description: "Welcome to the Continue documentation! We're excited that you want to contribute. This guide will help you get started with our documentation workflow and tools." +--- + +## 🚀 Quick Start + +### Prerequisites + +1. **Node.js** (v20 or higher) +2. **Git** for version control +3. **GitHub CLI** - Install from [cli.github.com](https://cli.github.com/) + +### Setup Steps + +1. **Fork and clone the repository** + + ```bash + # Fork the repository (this will also clone it locally) + gh repo fork continuedev/continue + cd continue/docs + ``` + +2. **Install dependencies** + + ```bash + npm install + ``` + +3. **Start the local development server** + ```bash + npm run dev + ``` + Your docs will be available at `http://localhost:3000` + +## 💬 Creating Discussions and Issues + +Before creating any issues, we ask that you start with a GitHub Discussion. This helps us organize feedback and determine the best path forward. + +### Starting a Discussion + + + + Visit the [Continue GitHub Discussions](https://github.com/continuedev/continue/discussions) page. + + + + Select the **Docs** category for documentation improvements, corrections, or suggestions. + + + + + Include the following in your discussion: + - Clear description of the issue or suggestion + - Steps to reproduce (if applicable) + - Expected vs. actual behavior + - Screenshots or code examples when helpful + - Your environment (OS, IDE, Continue version) + + + +### Issue Escalation Process + + + + **Important**: All issues should start as discussions. The Continue team will determine if and when a discussion should be escalated to a GitHub issue. + + + +The Continue team will review discussions and may: +- Provide a solution or clarification directly in the discussion +- Ask for additional information or testing +- Convert the discussion to an issue if it requires code changes or is a confirmed bug +- Close the discussion if it's resolved or not actionable + +### When Discussions Become Issues + +A discussion will typically be converted to an issue when: +- A bug in the documentation is confirmed +- A new feature or significant documentation change is approved +- Community consensus supports the proposed change +- Technical implementation is required + +## 🤖 AI-Powered Documentation with Continue + +We strongly encourage using Continue's AI assistance to maintain consistency and quality in our documentation. Here are three ways to set this up: + +### Option 1: Use the Pre-Built Documentation Agent (Recommended) + +The easiest way to get started is using our pre-configured documentation agent: + + + + Visit [the Docs Assistant - Mintlify in the Hub](https://hub.continue.dev/continuedev/docs-mintlify) and click "Install" to add it to your Continue setup. This agent comes pre-configured with all our documentation standards. + + + Learn more about Continue Agents in our [agent documentation](/guides/understanding-agents). + + + + + + + ```bash + # Install the Continue CLI if you haven't already + npm install -g @continuedev/cli + + # Use the agent from the command line + cn "Create a new guide for using the Continue CLI with Linear" --config continuedev/docs-mintlify + ``` + + + + 1. Open Continue in your IDE + 2. Select the "Docs Assistant - Mintlify" agent from the model dropdown + 3. Ask it to help you create or edit documentation + + Example prompts: + - "Create a new guide for using the Continue CLI with Linear" + - "Update the getting-started guide with the new installation process" + - "Format this documentation according to Mintlify standards" + + + + + + +You can also remix this agent to customize it for your specific needs. Learn how to create your own remix in our [remix agent documentation](/hub/agents/create-an-agent#how-to-remix-an-agent). + + +### Option 2: Create Your Own Custom Agent + +If you want more control or customization, you can create your own documentation agent: + + + + Follow our [agent creation guide](/hub/agents/create-an-agent) to set up your own agent. + + + + Install from Continue Hub: https://hub.continue.dev/continuedev/continue-docs-mcp + + This MCP provides context about Continue's documentation structure and standards. + + + + Install from Continue Hub: https://hub.continue.dev/mintlify/technical-writing-rule + + This rule ensures proper Mintlify component formatting. + + + + + + ```bash + # Install the Continue CLI if you haven't already + npm install -g @continuedev/cli + + # Use your agent from the command line + cn --config your-org/your-agent-name "Create a new guide for API authentication" + ``` + + + + 1. Open Continue in your IDE + 2. Select your custom agent from the model dropdown + 3. Ask it to help you create or edit documentation + + Example prompts: + - "Help me format this documentation according to Mintlify standards" + - "Create a troubleshooting section for this feature" + + + + + +## 📝 Documentation Standards + +### Mintlify Component Guidelines + +When using Mintlify components, follow these formatting rules: + +#### Cards and Info Boxes + +```mdx + + +Always include blank lines and proper indentation: + +- Use 2-space indentation +- Add blank lines after opening tags +- Format lists as bullet points + + +``` + +#### Warning and Note Components + +```mdx + + +Important information should be formatted clearly: + +- Each point on its own line +- Consistent indentation +- Clear, concise language + + +``` + +### Writing Style + +1. **Be concise**: Get to the point quickly +2. **Use examples**: Show, don't just tell +3. **Include code blocks**: Provide working examples +4. **Add visuals**: Screenshots and diagrams help understanding +5. **Test your changes**: Ensure all links and code examples work + + +If you are creating a new guide, please test the steps yourself to ensure accuracy. + + +## 🔧 Common Tasks + +### Adding a New Guide + +1. Create a new `.mdx` file in the guides directory +2. Add frontmatter: + ```mdx + --- + title: "Your Guide Title" + description: "Brief description of what this guide covers" + --- + ``` +3. Use the Continue agent to help format your content +4. Update `docs.json` to include your new page in the navigation + + +We have both guides and cookbooks. Use guides for step-by-step instructions and cookbooks for creating agents for the CLI. + + +### Updating Existing Documentation + +1. Use the Continue agent with prompts like: + - "Update the installation guide with the new npm package" + - "Add a troubleshooting section for connection issues" +2. The agent will maintain consistent formatting automatically + +### Adding Code Examples + +Use language-specific code blocks: + +````mdx +```typescript +// Your TypeScript code here +const example = "Hello, Continue!"; +``` +```` + +## 🐛 Testing Your Changes + +1. **Local preview**: In the docs directory, run `npm run dev` and check your changes +2. **Link validation**: Ensure all internal and external links work +3. **Format check**: Use the Continue agent to validate Mintlify formatting +4. **Build test**: Run `npm run build` to ensure no build errors + +## 📤 Submitting Your Contribution + +1. **Create a feature branch** + + ```bash + git checkout -b docs/your-feature-name + ``` + +2. **Commit your changes** + + ```bash + git add . + git commit -m "docs: describe your changes" + ``` + +3. **Push and create a Pull Request** + + ```bash + # Push to your fork and create a PR + git push origin docs/your-feature-name + gh pr create --web + ``` + + + + The `gh pr create` command will automatically: + - Push your branch to your fork + - Create a pull request to the main repository + - Allow you to add a title, description, and reference issues + - Open the PR in your browser if using `--web` + + + +## 💡 Tips for Success + +- **Use the Continue agent**: It knows our documentation standards and will save you time +- **Preview frequently**: Check your changes in the local dev server +- **Ask questions**: Open an issue or discussion if you need clarification +- **Small PRs are better**: Focus on one topic or fix per PR +- **Update examples**: Ensure code examples reflect the latest API + + +## 🆘 Getting Help + +- **Start a Discussion**: Use [GitHub Discussions](https://github.com/continuedev/continue/discussions) for documentation issues, suggestions, or questions +- **Continue agent questions**: Check the [Continue Hub page](https://hub.continue.dev/continuedev/docs-mintlify) +- **Discord community**: Join our Discord for real-time help +- **Existing docs**: Review similar pages for formatting examples +--- + +Thank you for contributing to Continue! Your efforts help make our documentation better for everyone. To learn more about contibuting to other parts of the project, check out our [main CONTRIBUTING guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md) 🎉 diff --git a/docs/cli/guides.mdx b/docs/cli/guides.mdx new file mode 100644 index 000000000..89e96b566 --- /dev/null +++ b/docs/cli/guides.mdx @@ -0,0 +1,4 @@ +--- +title: "Guides" +url: "/guides/overview#mcp-integration-cookbooks" +--- \ No newline at end of file diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx index 75dbfc811..e685e8303 100644 --- a/docs/customization/rules.mdx +++ b/docs/customization/rules.mdx @@ -15,4 +15,28 @@ By implementing rules, you transform the AI from a generic coding agent into a k Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes. +## Where to Manage Rules + + + +- Create files in `.continue/rules` folder +- Automatically appear with Hub assistants +- Edit directly in your file system +- Version controlled alongside your code +- Best for project-specific rules (e.g., "remember to generate migrations after modifying the db") + + + +- Manage on [Continue Hub](https://hub.continue.dev) +- Reference in config.yaml with `uses:` +- Share with team and community +- Easy to include in multiple agents +- Best for organization-wide rules (e.g., "always use X library for Y task") + + + + +**Quick Setup**: Start with local rules for immediate use, then promote commonly used rules to the Hub for sharing and reuse. + + Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details. \ No newline at end of file diff --git a/docs/customization/settings.mdx b/docs/customization/settings.mdx new file mode 100644 index 000000000..4ff298c34 --- /dev/null +++ b/docs/customization/settings.mdx @@ -0,0 +1,190 @@ +--- +title: Settings +description: Configure Continue through VS Code's streamlined settings interface +--- + +Continue Settings Panel - Card-based Layout + +The new settings experience introduces a **card-based layout** that reduces visual clutter while maintaining powerful functionality. Every setting is more discoverable and easier to modify, whether you're on an ultrawide monitor or a small laptop screen. + +## Quick Access + + + + Click the gear in the Continue sidebar + + + File → Preferences → Settings → Extensions → Continue + + + Edit `config.yml` directly for advanced options + + + + + Use the toolbar buttons for quick access to specific settings: - **Rules** + (pencil icon) - Custom coding preferences - **Tools** (wrench icon) - Manage + integrations - **Models** (cube icon) - Configure AI providers + + +## Core Settings + + + + + + | Setting | Description | + |---------|-------------| + | Session Tabs | Manage multiple chat sessions | + | Code Wrapping | Auto-wrap long code lines | + | Markdown Display | Show raw markdown vs rendered | + | Chat Scrollbar | Toggle scrollbar visibility | + + + + | Setting | Description | + |---------|-------------| + | Auto-accept Diffs | Apply code changes automatically | + | Tool Rejection | Continue after tool rejection | + | Auto-naming | Generate session titles automatically | + + + + + + Configure code completions: + + Continue Autocomplete Settings + + + Autocomplete models need to be added to your agent to enable selecting an autocomplete model. If none is available, you will be linked to the docs showing recommended models. See our [model recommendations](/customize/model-roles/autocomplete) for the best autocomplete models. + + + Autocomplete Model Selection + + + To better understand how to set up agents and models, see our [Understanding Agents guide](/guides/understanding-agents). + + + + + + Control how Continue understands your codebase: + + Continue Indexing Settings + + + + Toggle codebase indexing in the settings panel + + + Watch real-time status in the UI + + + Check which files are indexed via the status indicator + + + + + Indexing enables Continue to understand your entire codebase structure, significantly improving context awareness and suggestions. + + + + + + + These features are in beta and may change or have stability issues. + + + | Feature | Purpose | + |---------|---------| + | Add Current File by Default | The currently open file is added as context in every new conversation | + | Enable experimental tools | Enables access to experimental tools that are still in development | + | Only use system message tools | Continue will not attempt to use native tool calling and will only use system message tools | + | @Codebase: use tool calling only | @codebase context provider will only use tool calling for code retrieval | + | Stream after tool rejection | Streaming will continue after the tool call is rejected | + + + + +## Model & Assistant Selection + +New assistant dropdown with cleaner icons and improved organization display + +The refined assistant selector features: + +- **Organization badges** for easy provider identification +- **Smart error handling** that sorts problematic configurations while keeping them selectable +- **Keyboard navigation** for quick model switching + +## Privacy & Data + + + + All code analysis happens locally unless explicitly shared + + + Opt in/out of anonymous usage statistics + + + Sessions auto-save and restore between IDE restarts + + + +## Troubleshooting + + + + - Verify API keys in `config.yml` - Check network connectivity - Confirm + endpoint URLs are correct + + + + - Review MCP server configurations - Check tool permissions - Verify tool + dependencies are installed + + + + - Check file permissions + - Review `.gitignore` patterns + - Verify sufficient disk space + + + + + + Still having issues? Check our comprehensive [troubleshooting + guide](/troubleshooting) or visit the [FAQs](/faqs) for more solutions. + + +## Next Steps + + + + Set up your AI providers + + + Extend Continue with MCP tools + + + Define coding preferences + + + Customize AI behavior + + diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 074448104..6ad5414bc 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -30,8 +30,8 @@ explore available MCP server blocks Below is a quick example of setting up a new MCP server for use in your agent: 1. Create a folder called `.continue/mcpServers` at the top level of your workspace -2. Add a file called `playwright-mcp.yaml` to this folder. -3. Write the following contents to `playwright-mcp.yaml` and save. +2. Add a file called `playwright-mcp.yaml` to this folder +3. Write the following contents and save ```yaml title=".continue/mcpServers/playwright-mcp.yaml" name: Playwright mcpServer @@ -60,6 +60,14 @@ You can set up an MCP server to search the Continue documentation directly from For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). +## Using JSON MCP Format from Claude, Cursor, Cline, etc + + +If you're coming from another tool that uses JSON MCP format configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up. + +For example, place your JSON MCP config file at `.continue/mcpServers/mcp.json` in your workspace. + + ## How to Configure MCP Servers To set up your own MCP server, read the [MCP @@ -68,38 +76,21 @@ quickstart](https://modelcontextprotocol.io/quickstart) and then [create an block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP server block to your [config file](./configuration.md): - - - ```yaml title="config.yaml" - mcpServers: - - name: SQLite MCP - command: npx - args: - - "-y" - - "mcp-sqlite" - - "/path/to/your/database.db" +```yaml title="config.yaml" +# ... +mcpServers: + - name: SQLite MCP + command: npx + args: + - "-y" + - "mcp-sqlite" + - "/path/to/your/database.db" +# ... +``` -```` - - -```json title="config.json" -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"] - } - } - ] - } -} -```` - - - + +When creating a standalone block file in `.continue/mcpServers/`, remember to include the required metadata fields (`name`, `version`, `schema`) as shown in the Quick Start example above. + ### How to Configure MCP Server Properties @@ -120,10 +111,12 @@ MCP now supports remote server connections through HTTP-based transports, expand For real-time streaming communication, use the SSE transport: ```yaml +# ... mcpServers: - name: Name type: sse url: https://.... +# ... ``` #### How to Use Standard Input/Output (`stdio`) @@ -131,6 +124,7 @@ mcpServers: For local MCP servers that communicate via standard input and output: ```yaml +# ... mcpServers: - name: Name type: stdio @@ -138,6 +132,7 @@ mcpServers: args: - "@modelcontextprotocol/server-sqlite" - "/path/to/your/database.db" +# ... ``` #### How to Use Streamable HTTP Transport @@ -145,10 +140,12 @@ mcpServers: For standard HTTP-based communication with streaming capabilities: ```yaml +# ... mcpServers: - name: Name type: streamable-http url: https://.... +# ... ``` These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients. @@ -161,6 +158,7 @@ With some MCP servers you will need to use API keys or other secrets. You can le as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`. ```yaml +# ... mcpServers: - name: Supabase MCP command: npx @@ -178,4 +176,5 @@ mcpServers: - "@modelcontextprotocol/server-github" env: GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }} +# ... ``` diff --git a/docs/customize/deep-dives/rules.mdx b/docs/customize/deep-dives/rules.mdx index 93631f3ab..449fc272d 100644 --- a/docs/customize/deep-dives/rules.mdx +++ b/docs/customize/deep-dives/rules.mdx @@ -20,6 +20,42 @@ You can view the current rules by clicking the pen icon above the main toolbar: To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#how-to-customize-chat-system-message)). +## Understanding Hub vs Local Rules Integration + + +**Important:** Rules created in different locations behave differently and have different synchronization patterns. + + +Continue supports two types of rules with different behaviors: + + + +- **Location**: `.continue/rules` folder in your workspace +- **Visibility**: Automatically visible when using Hub assistants +- **Creation**: Add rules button in VSCode or manual file creation +- **File Management**: Creates actual `.md` files you can edit directly + + + +- **Location**: Stored on Continue Hub, referenced in config.yaml +- **Visibility**: Only appear when referenced in assistant configuration +- **Creation**: Created directly on Hub or copied from local rules +- **File Management**: No local files created, managed through Hub interface + + + +### How Rules Are Applied + +When using Continue, rules are loaded in this order: +1. **Hub assistant rules** (if using a Hub-based assistant) +2. **Referenced Hub rules** (via `uses:` in config.yaml) +3. **Local workspace rules** (from `.continue/rules` folder) +4. **Global rules** (from `~/.continue/rules` folder) + + +**TL;DR**: Local rules show up automatically when using Hub assistants. Hub rules show up automatically when referenced in your config. + + ## Quick Start: How to Create Your First Rule File Below is a quick example of setting up a new rule file: @@ -42,6 +78,8 @@ Now test your rules by asking a question about a file in chat. ## How to Create Rules Blocks +### Creating Local Rules + Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules. ![add local rules button](/images/add-local-rules.png) @@ -50,12 +88,44 @@ Rules can be added locally using the "Add Rules" button while viewing the Local **Automatically create local rule blocks**: When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled. For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. - -Rules can also be added to an Agent on the Continue Hub. +### Creating Hub Rules -Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. +Rules can also be created and managed on the Continue Hub: + +1. **Browse existing rules**: [Explore available rules](https://hub.continue.dev) +2. **Create new rules**: [Create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub +3. **Copy from local rules**: Copy/paste content from your `.continue/rules` files to create Hub rules + +### Working Between Hub and Local Rules + + + +To use Hub rules in your local setup: + +1. Reference them in your `config.yaml`: + ```yaml + rules: + - uses: username/my-hub-rule + ``` +2. The rule will automatically appear in your rules toolbar +3. **Note**: No local file is created - the rule exists only on the Hub + + + +To move local rules to the Hub: + +1. Copy the content from your `.continue/rules/rule-name.md` file +2. Go to [Create new rule](https://hub.continue.dev/new?type=block&blockType=rules) +3. Paste the content and configure the rule +4. Optionally, remove the local file and reference the Hub rule in your config + + +**Current Limitation**: There's no automatic sync from local to Hub. You must manually copy/paste rule content. + + + ### How to Configure Rule Properties and Syntax @@ -150,6 +220,42 @@ globs: ["**/*.ts", "**/*.tsx"] - modularize components into smaller, reusable pieces ``` +## Troubleshooting Rules + +### Issue: Rules Created in Different Places Don't Sync + +**Problem**: You created rules in the Hub but don't see them in VSCode, or vice versa. + +**Solution**: +- **Hub rules** only appear when referenced in your config.yaml using the `uses:` syntax +- **Local rules** automatically appear when using Hub assistants +- There's currently no automatic bidirectional sync + +### Issue: "Edit" Links Point to Wrong Location + +**Problem**: When you click "Edit" on a rule in VSCode, it tries to open the Hub even though the rule is local, or shows an incorrect URL. + +**Root Cause**: This happens when you have a mix of local and Hub rules, and Continue can't properly determine where each rule originates. + +**Workaround**: +1. **For local rules**: Navigate directly to `.continue/rules/` folder and edit the `.md` file +2. **For Hub rules**: Go directly to your assistant page on [Continue Hub](https://hub.continue.dev) and edit from there +3. Keep track of which rules are local vs Hub-based to avoid confusion + + +**Known Issue**: This link accuracy problem is tracked in [Linear issue CON-3084](https://linear.app/continue/issue/CON-3084) and will be fixed in a future update. + + +### Issue: Rules Don't Appear in Assistant + +**Problem**: Your rules exist but don't show up in the rules toolbar. + +**Check These**: +1. **File location**: Ensure local rules are in `.continue/rules/` (not `.continue/rule/`) +2. **File format**: Rules should be `.md` files with proper YAML frontmatter +3. **Config reference**: Hub rules must be referenced in `config.yaml` +4. **Assistant type**: Ensure you're using the correct assistant (local vs Hub) + ### How to Customize Chat System Message Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output. diff --git a/docs/customize/model-providers/more/asksage.mdx b/docs/customize/model-providers/more/asksage.mdx index 03ad0e3ca..c7dd81391 100644 --- a/docs/customize/model-providers/more/asksage.mdx +++ b/docs/customize/model-providers/more/asksage.mdx @@ -1,18 +1,34 @@ --- -title: "AskSage" -description: "Configure AskSage with Continue to access a wide range of models including government-compliant versions of GPT and Claude models, supporting chat and edit functionalities" +title: "Ask Sage" +slug: ../asksage --- + + **Discover Ask Sage models [here](https://hub.continue.dev/?q=Ask%20Sage)** + + - To get an Ask Sage API key login to the Ask Sage platform (If you don't have - an account, you can create one [here](https://chat.asksage.ai/)) and follow - the instructions in the Ask Sage Docs: [Ask Sage API - Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) + You can get an API key from the [Ask Sage](https://www.asksage.ai/). -## Configuration -To use the Ask Sage models, you can use the following +## Overview + +Ask Sage provides secure, government-compliant access to LLMs. This guide explains how to set up and configure Ask Sage models, including support for DoD certificates. + +## 1. Prerequisites + +- **Ask Sage Account:** + Sign up or log in at [Ask Sage Platform](https://chat.asksage.ai/). + +- **API Key:** + Follow the [API Key Documentation](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) to generate your key. + + +## 2. Configuration + +Add your Ask Sage model to your Continue configuration file. + @@ -42,53 +58,66 @@ To use the Ask Sage models, you can use the following -The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below: +## 3. Using DoD Certificates -> Server API for query/training etc.: -> -> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0 -> - URL for this API is: https://api.asksage.ai/server/ +For secure environments, specify your DoD CA bundle path: -## Usage -Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev: + + + ```yaml title="config.yaml" + models: + - name: GPT-4 gov + provider: askSage + model: gpt4-gov + apiBase: https://api.asksage.ai/server/ + apiKey: + requestOptions: + caBundlePath: /path/to/dod/certificates + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4 gov", + "provider": "askSage", + "model": "gpt4-gov", + "apiBase": "https://api.asksage.ai/server/", + "apiKey": "", + "requestOptions": { + "caBundlePath": "/path/to/dod/certificates" + } + } + ] + } + ``` + + -- `Chat` to understand and iterate on code in the sidebar -- `Edit` to modify code without leaving your current file +Replace `/path/to/dod/certificates` with your actual CA bundle file path. -More models, functionalities and documentation will be added in the future for Ask Sage Integration. +--- -> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. +## 4. Final Steps -## Ask Sage Documentation +- Save your configuration file. +- Restart Continue to apply changes. -Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage. +Your Ask Sage model will now be available in Continue. -## Current Models From Ask Sage Supported +## 5. Usage -The current Models available provided by Ask Sage are: +Supported features: + +- **Chat:** Interact and iterate on code in the sidebar. +- **Edit:** Modify code in place. + +## 6. Support + +- Refer to [Ask Sage Docs](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) for more details. +- Email the Ask Sage support team for assistance at support@asksage.ai. + +--- -| Index | Model | Added | -| ----- | --------------------- | ----- | -| 1 | GPT-4 Gov | ✅ | -| 2 | GPT-4o Gov | ✅ | -| 3 | GPT-4o-mini Gov | ✅ | -| 4 | GPT-3.5-Turbo Gov | ✅ | -| 5 | GPT-4o | ✅ | -| 6 | GPT-4o-mini | ✅ | -| 7 | GPT-4 | ✅ | -| 8 | GPT-4-32K | ✅ | -| 9 | GPT-o1 | ✅ | -| 10 | GPT-o1-mini | ✅ | -| 10 | GPT-o3-mini | ✅ | -| 11 | GPT-3.5-turbo | ✅ | -| 12 | Claude 3.5 Sonnet Gov | ✅ | -| 13 | Claude 3 Opus | ✅ | -| 14 | Claude 3 Sonet | ✅ | -| 15 | Claude 3.5 Sonnet | ✅ | -| 16 | Grok (xAI) | ✅ | -| 17 | Groq Llama 3.3 | ✅ | -| 18 | Groq 70B | ✅ | -| 19 | Gemini Pro | ✅ | -| 20 | llama 3 | ✅ | -| 21 | Mistral Large | ✅ | diff --git a/docs/customize/model-providers/top-level/openai.mdx b/docs/customize/model-providers/top-level/openai.mdx index 9537ac133..3249e27c9 100644 --- a/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/customize/model-providers/top-level/openai.mdx @@ -90,7 +90,7 @@ If you are using an OpenAI API compatible providers, you can change the `apiBase ### How to Force Legacy Completions Endpoint Usage -To force usage of `chat/completions` instead of `completions` endpoint you can set: +To force usage of `completions` instead of `chat/completions` endpoint you can set: diff --git a/docs/docs.json b/docs/docs.json index 2c67802e0..7b1d5e1ba 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -2,6 +2,10 @@ "$schema": "https://mintlify.com/docs.json", "theme": "mint", "name": "Continue", + "banner": { + "content": "Continue CLI v1.4.49 is live 🚀 Learn how you can [leverage the CLI with our MCP Cookbooks](/guides/overview#mcp-integration-cookbooks)", + "dismissable": true + }, "colors": { "primary": "#6b7280", "light": "#ffffff", @@ -26,7 +30,12 @@ { "group": "CLI", "icon": "terminal", - "pages": ["cli/overview", "cli/install", "cli/quick-start"] + "pages": [ + "cli/overview", + "cli/install", + "cli/quick-start", + "cli/guides" + ] }, { "group": "Features", @@ -88,13 +97,14 @@ "customization/models", "customization/mcp-tools", "customization/rules", - "customization/prompts" + "customization/prompts", + "customization/settings" ] }, { "group": "Help", "icon": "book-open", - "pages": ["faqs", "troubleshooting"] + "pages": ["faqs", "troubleshooting", "CONTRIBUTING"] } ] }, @@ -129,6 +139,7 @@ { "group": "More Providers", "pages": [ + "customize/model-providers/more/asksage", "customize/model-providers/more/deepseek", "customize/model-providers/more/deepinfra", "customize/model-providers/more/groq", @@ -185,7 +196,7 @@ "pages": [ "hub/introduction", { - "group": "agents", + "group": "Agents", "icon": "robot", "pages": [ "hub/agents/intro", @@ -221,6 +232,11 @@ "hub/secrets/secret-resolution" ] }, + { + "group": "Workflows", + "icon": "cloud", + "pages": ["hub/workflows/intro"] + }, "hub/sharing", "hub/source-control" ] @@ -246,7 +262,8 @@ "guides/instinct", "guides/running-continue-without-internet", "guides/custom-code-rag", - "guides/how-to-self-host-a-model" + "guides/how-to-self-host-a-model", + "guides/notion-continue-guide" ] }, { @@ -254,8 +271,14 @@ "icon": "book-open-cover", "pages": [ "guides/posthog-github-continuous-ai", + "guides/continue-docs-mcp-cookbook", + "guides/github-mcp-continue-cookbook", + "guides/sanity-mcp-continue-cookbook", + "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", - "guides/netlify-mcp-continuous-deployment" + "guides/dlt-mcp-continue-cookbook", + "guides/netlify-mcp-continuous-deployment", + "guides/chrome-devtools-mcp-performance" ] } ] @@ -317,7 +340,7 @@ "navbar": { "links": [ { - "label": "Explore", + "label": "🚀 Get Started", "href": "https://hub.continue.dev/" } ], diff --git a/docs/guides/chrome-devtools-mcp-performance.mdx b/docs/guides/chrome-devtools-mcp-performance.mdx new file mode 100644 index 000000000..02a24edd3 --- /dev/null +++ b/docs/guides/chrome-devtools-mcp-performance.mdx @@ -0,0 +1,798 @@ +--- +title: "Chrome DevTools Performance Optimization Cookbook" +description: "Measure and optimize web performance with Chrome DevTools MCP, automated performance traces, and Core Web Vitals monitoring using Continue." +sidebarTitle: "Chrome DevTools MCP for Performance" +--- + + + Use AI to automatically trace performance, analyze Core Web Vitals, diagnose bottlenecks, and get actionable optimization suggestions directly from Chrome DevTools + + + + **Did You Know?** Chrome DevTools MCP brings the full power of browser debugging to your AI workflow: + - [Performance Traces](https://developer.chrome.com/docs/devtools/performance) with automated analysis + - [Network Request Monitoring](https://developer.chrome.com/docs/devtools/network) for bottleneck detection + - [Console Debugging](https://developer.chrome.com/docs/devtools/console) with error pattern recognition + - [CPU & Network Throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) to simulate real-world conditions + - [Performance Insights](https://developer.chrome.com/docs/devtools/performance-insights) with AI-powered analysis + - [Screenshot Debugging](https://developer.chrome.com/docs/devtools/device-mode) for visual regression detection + +This guide shows you how to leverage these features through natural language with Continue CLI! + + + +## What You'll Learn + +This cookbook teaches you to: + +- Run automated [performance traces](https://developer.chrome.com/docs/devtools/performance) to capture runtime metrics +- Analyze [Core Web Vitals](https://web.dev/vitals/) (LCP, FID, CLS, INP) and performance insights +- Diagnose performance bottlenecks using network and console analysis +- Test performance under different network and CPU conditions with [throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) +- Automate visual regression testing with [screenshots](https://developer.chrome.com/docs/devtools/device-mode) + +## Prerequisites + +- Chrome browser installed +- Web project with a running development server (or deployed URL) +- Node.js 20+ installed +- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`) +- [Chrome DevTools MCP](https://hub.continue.dev) configured + +## Quick Setup + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + +## Chrome DevTools MCP Workflow Options + + + Skip the manual setup and use our pre-built Chrome DevTools agent that includes + optimized prompts, rules, and the Chrome DevTools MCP for more consistent results. + + +After completing **Quick Setup** above, you have two paths to get started: + + + + **Perfect for:** Immediate results with optimized prompts and built-in performance analysis + + + + Visit the [Chrome DevTools Continuous Agent](https://hub.continue.dev/continuedev/chrome-dev-continuous) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/chrome-dev-continuous + ``` + + This agent includes: + - **Optimized prompts** for performance analysis and debugging + - **Built-in rules** for consistent formatting and error handling + - **[Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp)** for reliable browser automation + + + + In the TUI that opens, type: + ``` + Analyze performance of http://localhost:3000 and provide optimization recommendations + ``` + + That's it! The agent handles Chrome automation automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Chrome DevTools MCP integration and pre-tested prompts. + + + + + + + + Visit the [Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp) on Continue Hub and add it to your assistant, or add this to your configuration: + + ```yaml + name: Chrome DevTools MCP + version: 0.0.1 + schema: v1 + mcpServers: + - name: Chrome DevTools MCP + command: npx + args: + - chrome-devtools-mcp@latest + ``` + + The MCP will automatically launch Chrome and connect to DevTools when needed. + + + + Test the connection: + + **TUI Mode Prompt:** + ``` + Open web.dev and take a screenshot + ``` + + + + Navigate to your project directory: + + **TUI Mode Prompt:** + ``` + Navigate to http://localhost:3000 and record a performance trace. Analyze LCP, FID, and CLS. + ``` + + + + + **Manual Setup**: While you can configure the MCP manually, the pre-built agent provides optimized prompts and better error handling for performance analysis workflows. + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + - **Chrome browser** installed on your system + - **Node.js 20+** to run the MCP via npx + + The agent will automatically detect and use your configuration. + + +--- + +## Performance Measurement Workflows + +The Chrome DevTools MCP enables natural language performance analysis. Here are workflows adapted from real-world use cases: + +### Quick Performance Checks + + +**TUI Mode Prompt:** +``` +Verify in the browser that your change works as expected. +``` + + + +**TUI Mode Prompt:** +``` +A few images on localhost:8080 are not loading. What's happening? +``` + + + +**TUI Mode Prompt:** +``` +Why does submitting the form fail after entering an email address? +``` + + + +**TUI Mode Prompt:** +``` +The page on localhost:8080 looks strange and off. Check what's happening there. +``` + + + +**TUI Mode Prompt:** +``` +Localhost:8080 is loading slowly. Make it load faster. +``` + + + +**TUI Mode Prompt:** +``` +Please check the LCP of web.dev. +``` + + +--- + +## Performance Analysis Recipes + +Now you can use natural language prompts to analyze web performance. The Continue agent automatically calls the appropriate Chrome DevTools MCP tools. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running performance measurements, test your prompts in plan mode (see the [Plan Mode Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This shows you what the agent will do without executing it. + + +### Step 1: Baseline Performance Trace + +Establish your current performance baseline: + +**TUI Mode Prompt:** +``` +Navigate to http://localhost:3000 and record a performance trace with page reload. Analyze the trace and show me the LCP, FID, CLS, and total blocking time. +``` + + + + + Chrome DevTools Performance Panel automatically tracks: + - **Core Web Vitals**: LCP, FID, CLS, INP + - **Loading Performance**: DOMContentLoaded, Load events, First Paint + - **Runtime Performance**: JavaScript execution time, layout shifts, paint events + - **Resource Usage**: Memory consumption, CPU utilization + + + +### Step 2: Analyze Performance Insights + +Deep dive into specific performance issues: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and analyze all Performance Insights. For each insight found, provide detailed information about: +- The specific issue (e.g., DocumentLatency, SlowCSS) +- Root cause analysis +- Affected resources or code +- Recommended optimizations +- Expected impact on Core Web Vitals +``` + + + **Performance Insights**: Chrome DevTools automatically detects common performance issues like: + - **Render Blocking Resources**: CSS and JavaScript that delay first paint + - **Layout Shifts**: Elements that move during page load + - **Long Tasks**: JavaScript execution blocking the main thread + - **Slow Network Requests**: Resources taking too long to load + - **Unused CSS/JavaScript**: Dead code increasing bundle size + + +### Step 3: Network Performance Analysis + +Identify slow network requests and optimization opportunities: + +**TUI Mode Prompt:** +``` +Navigate to https://my-site.com and: +1. List all network requests made during page load +2. Identify the 5 slowest requests and their sizes +3. Find any requests over 1MB +4. Detect render-blocking resources +5. Check for inefficient caching (missing cache headers) +6. Suggest specific optimizations for each issue found +``` + +### Step 4: Throttling Performance Tests + +Test performance under real-world network and CPU conditions: + +**TUI Mode Prompt:** +``` +Test my site's performance under different conditions: + +1. Navigate to http://localhost:3000 +2. Emulate 4x CPU slowdown and Fast 3G network +3. Record a performance trace with reload +4. Analyze LCP and Total Blocking Time +5. Take a screenshot when page is fully loaded + +Then repeat the test with: +- Slow 3G network + 6x CPU slowdown +- Offline network (to test service worker) + +Compare results and identify which conditions cause the worst performance degradation." +``` + + + **Available Network Presets**: + - No throttling + - Fast 3G (1.6 Mbps down, 0.75 Mbps up) + - Slow 3G (400 Kbps down, 400 Kbps up) + - Offline + + **CPU Throttling**: 4x, 6x, or custom slowdown to simulate low-end devices + + +### Step 5: JavaScript Performance Analysis + +Identify expensive JavaScript operations: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and: +1. Identify all long tasks (>50ms) blocking the main thread +2. Find the specific JavaScript functions causing these tasks +3. Measure total JavaScript execution time +4. Detect unused JavaScript being loaded +5. Show the call stack for the longest task +6. Recommend code splitting or lazy loading opportunities" +``` + +## Automated Performance Monitoring + +### Step 6: Core Web Vitals Dashboard + +Create automated monitoring for Core Web Vitals: + +**TUI Mode Prompt:** +``` +Create a performance monitoring script that: +1. Opens my site at http://localhost:3000 +2. Records a performance trace with reload +3. Extracts Core Web Vitals (LCP, FID, CLS, INP) +4. Checks console for JavaScript errors +5. Takes a screenshot +6. Saves results to performance-report.json with format: + { + 'timestamp': 'ISO date', + 'lcp': number, + 'fid': number, + 'cls': number, + 'inp': number, + 'errors': array, + 'screenshot': 'path' + } + +Save this as scripts/performance-monitor.js that I can run regularly" +``` + +### Step 7: Visual Regression Detection + +Detect unintended visual changes: + +**TUI Mode Prompt:** +``` +Set up visual regression testing: +1. Navigate to http://localhost:3000 +2. Take full-page screenshots at: + - Desktop viewport (1920x1080) + - Tablet viewport (768x1024) + - Mobile viewport (375x667) +3. Save screenshots to screenshots/baseline/ +4. Create a script to compare future screenshots against baseline +5. Highlight any pixel differences over 5% +6. Generate a visual diff report" +``` + +### Step 8: Performance Budget Enforcement + +Set and enforce performance budgets: + +**TUI Mode Prompt:** +``` +Create a performance budget checker that: + +Requirements: +- LCP must be < 2.5 seconds +- FID must be < 100ms +- CLS must be < 0.1 +- Total JavaScript < 300KB +- Total page size < 1MB +- No console errors + +Implementation: +1. Navigate to http://localhost:3000 +2. Record performance trace with reload +3. List all network requests and calculate total sizes +4. Check console messages for errors +5. Validate all metrics against budgets +6. Exit with code 1 if any budget is exceeded +7. Generate a detailed report showing pass/fail for each metric + +Save as scripts/performance-budget.js for CI/CD integration" +``` + +## Continuous Performance Testing with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where performance validation runs automatically in your CI/CD pipeline using Chrome DevTools MCP in headless mode. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + +### Create Workflow File + +This workflow automatically validates web performance on pull requests using the Continue CLI in headless mode. It records performance traces, extracts Core Web Vitals, and posts a summary report as a PR comment. + +Create `.github/workflows/performance-check.yml` in your repository: + +```yaml +name: Performance Check + +on: + pull_request: + +jobs: + performance: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Dependencies + run: | + npm install -g @continuedev/cli + npm ci + + - name: Build Project + run: npm run build + + - name: Start Dev Server + run: | + npm run dev & + npx wait-on http://localhost:3000 + + - name: Run Performance Tests + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + cn --config continuedev/chrome-dev-continuous \ + -p "Navigate to http://localhost:3000 and: + 1. Record performance trace with reload + 2. Extract LCP, FID, CLS values + 3. List network requests and calculate total bundle size + 4. Output results as JSON to performance.json" \ + --auto + + - name: Check Performance Budgets + run: | + node << 'EOF' + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const budgets = { + lcp: 2.5, + fid: 100, + cls: 0.1, + bundleSize: 300000 + }; + + let failed = false; + const results = []; + + if (perf.lcp > budgets.lcp) { + results.push(`❌ LCP: ${perf.lcp}s (budget: ${budgets.lcp}s)`); + failed = true; + } else { + results.push(`✅ LCP: ${perf.lcp}s`); + } + + if (perf.fid > budgets.fid) { + results.push(`❌ FID: ${perf.fid}ms (budget: ${budgets.fid}ms)`); + failed = true; + } else { + results.push(`✅ FID: ${perf.fid}ms`); + } + + if (perf.cls > budgets.cls) { + results.push(`❌ CLS: ${perf.cls} (budget: ${budgets.cls})`); + failed = true; + } else { + results.push(`✅ CLS: ${perf.cls}`); + } + + if (perf.bundleSize > budgets.bundleSize) { + results.push(`❌ Bundle: ${perf.bundleSize}KB (budget: ${budgets.bundleSize}KB)`); + failed = true; + } else { + results.push(`✅ Bundle: ${perf.bundleSize}KB`); + } + + console.log(results.join('\n')); + + if (failed) { + process.exit(1); + } + EOF + + - name: Comment Performance Results + if: always() + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const comment = `## 📊 Performance Report + + | Metric | Value | Budget | Status | + |--------|-------|--------|--------| + | LCP | ${perf.lcp}s | 2.5s | ${perf.lcp <= 2.5 ? '✅' : '❌'} | + | FID | ${perf.fid}ms | 100ms | ${perf.fid <= 100 ? '✅' : '❌'} | + | CLS | ${perf.cls} | 0.1 | ${perf.cls <= 0.1 ? '✅' : '❌'} | + | Bundle Size | ${perf.bundleSize}KB | 300KB | ${perf.bundleSize <= 300 ? '✅' : '❌'} | + + ${perf.lcp > 2.5 || perf.fid > 100 || perf.cls > 0.1 || perf.bundleSize > 300 + ? '⚠️ **Performance budgets exceeded. Please optimize before merging.**' + : '✅ **All performance budgets met!**'}`; + + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: comment + }); +``` + + + The Chrome DevTools MCP works in headless Chrome environments. Make sure your CI environment has Chrome installed (it's pre-installed on GitHub Actions ubuntu-latest runners). + + +## Advanced Performance Workflows + +### Step 9: Competitor Comparison + +Compare your site's performance with competitors: + +**TUI Mode Prompt:** +``` +Compare performance between my site and competitors: + +Sites to test: +- http://localhost:3000 (my site) +- https://competitor1.com +- https://competitor2.com + +For each site: +1. Navigate to homepage +2. Record performance trace with reload +3. Extract LCP, FID, CLS, Total Blocking Time +4. List network requests and calculate total page size +5. Count JavaScript and CSS files + +Create a comparison table showing: +- Site name +- All Core Web Vitals +- Total page size +- Number of requests +- Which site performs best for each metric + +Provide specific recommendations for how my site can improve based on what competitors do better." +``` + +### Step 10: Performance Testing Across Routes + +Test performance consistency across your entire site: + +**TUI Mode Prompt:** +``` +Test performance across all major routes: + +Routes to test: +- / (homepage) +- /products +- /products/[id] (pick a sample product) +- /checkout +- /blog + +For each route: +1. Navigate to the URL +2. Record performance trace +3. Extract LCP, Total Blocking Time, bundle size +4. Check console for errors +5. Take a screenshot + +Generate a report showing: +- Which routes have the worst LCP +- Routes with the most JavaScript errors +- Bundle size variations across routes +- Recommendations for route-specific optimizations" +``` + +### Step 11: Mobile Performance Analysis + +Focus on mobile-specific performance issues: + +**TUI Mode Prompt:** +``` +Analyze mobile performance for http://localhost:3000: + +1. Resize viewport to mobile (375x667) +2. Emulate Slow 3G network + 4x CPU slowdown +3. Record performance trace with reload +4. Analyze Performance Insights for mobile-specific issues +5. Check for: + - Touch target sizes too small + - Horizontal scrolling issues + - Oversized images not optimized for mobile + - Excessive JavaScript on mobile +6. Take mobile screenshot +7. Provide mobile-specific optimization recommendations" +``` + +## Performance Troubleshooting + +### Debug Performance Regressions + +Quickly identify what caused a performance regression: + +**TUI Mode Prompt:** +``` +Debug performance regression on http://localhost:3000: + +1. Record performance trace +2. Analyze all Performance Insights +3. List console errors and warnings +4. Check network requests for: + - Failed requests + - Slow requests (>1s) + - Large requests (>500KB) +5. Identify the top 3 performance bottlenecks +6. For each bottleneck, suggest: + - Root cause + - Specific code or resource causing it + - Step-by-step fix + - Expected performance improvement" +``` + +### Performance Issue Quick Reference + +| Issue | Quick Fix Command (in cn TUI) | +| :---- | :---------------------------- | +| Slow LCP | `"Find render-blocking resources and suggest preloading or deferring"` | +| High CLS | `"Detect layout shifts and identify unsized images or dynamic content"` | +| Long Tasks | `"Find JavaScript tasks over 50ms and suggest code splitting"` | +| Large Bundles | `"List all JavaScript files, identify largest ones, suggest lazy loading"` | +| Slow Network | `"Find requests over 500KB and suggest compression or optimization"` | +| Console Errors | `"List all console errors and suggest fixes"` | + +## What You've Built + +After completing this guide, you have a complete **AI-powered performance analysis system** that: + +- ✅ **Uses natural language** — Simple prompts instead of complex DevTools commands +- ✅ **Analyzes automatically** — AI interprets performance traces and suggests fixes +- ✅ **Runs continuously** — Automated validation in CI/CD pipelines +- ✅ **Ensures quality** — Performance checks prevent regressions from shipping + + + Your performance workflow now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine performance analysis and debugging with human oversight through review and approval of changes. + + +## Chrome DevTools MCP Capabilities + + + + + **Tools Available** + - `performance_start_trace`: Start recording with auto-reload + - `performance_stop_trace`: Stop and analyze trace + - `performance_analyze_insight`: Deep dive into specific issues + + + + + + **Tools Available** + - `list_network_requests`: See all requests and sizes + - `get_network_request`: Inspect specific request details + - `emulate_network`: Test under various network conditions + + + + + + **Tools Available** + - `list_console_messages`: Get all console logs and errors + - `evaluate_script`: Run JavaScript in page context + - Automatic error pattern detection + + + + + + **Tools Available** + - `take_screenshot`: Capture full or partial page + - `take_snapshot`: Get accessibility tree snapshot + - `resize_page`: Test responsive layouts + + + + +## Performance Best Practices + +Key metrics to monitor for optimal web performance: + + + + - LCP < 2.5s (good) + - FID < 100ms (good) + - CLS < 0.1 (good) + - INP < 200ms (good) + + + + - Total page size < 1MB + - JavaScript < 300KB + - Time to Interactive < 3.8s + - First Contentful Paint < 1.8s + + + + - No long tasks > 50ms + - 60 FPS during interactions + - No memory leaks + - Efficient event listeners + + + +## Advanced Testing Scenarios + +### A/B Test Performance Impact + +**TUI Mode Prompt:** +``` +Compare performance of two implementations: +1. Test variant A at http://localhost:3000?variant=A +2. Test variant B at http://localhost:3000?variant=B +Run each test 5 times and calculate average LCP, FID, CLS +Determine which variant has better performance and by how much +``` + +### Lighthouse Score Tracking + +**TUI Mode Prompt:** +``` +Create a script that runs daily performance audits: +1. Navigate to production site +2. Record performance trace +3. Calculate Lighthouse-style performance score based on: + - FCP (10%) + - SI (10%) + - LCP (25%) + - TTI (10%) + - TBT (30%) + - CLS (15%) +4. Track score over time in performance-history.json +5. Alert if score drops below 90 +``` + +### Performance Regression Detection + +**TUI Mode Prompt:** +``` +Set up automated regression detection: +1. Record baseline performance for main branch +2. Save baseline metrics to baseline-perf.json +3. On each PR, run performance tests +4. Compare PR metrics with baseline +5. Flag regressions over 10% for any metric +6. Generate visual diff report with screenshots +``` + +## Next Steps + +1. **Analyze your first site** - Try the baseline performance trace on your current project +2. **Debug bottlenecks** - Use the network analysis prompt to fix slow requests +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Test throttling** - Measure performance under real-world network conditions +5. **Monitor trends** - Track Core Web Vitals over time + +## Additional Resources + + + + Official Chrome DevTools MCP repository + + + Explore more MCP integrations + + + Complete Chrome DevTools documentation + + + Learn about Core Web Vitals + + diff --git a/docs/guides/continue-docs-mcp-cookbook.mdx b/docs/guides/continue-docs-mcp-cookbook.mdx new file mode 100644 index 000000000..76c4637dd --- /dev/null +++ b/docs/guides/continue-docs-mcp-cookbook.mdx @@ -0,0 +1,542 @@ +--- +title: "Contributing to Continue with Model Context Protocol (MCP)" +description: "Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows." +sidebarTitle: "Continue Docs MCP Cookbook" +--- + + + Master using the Continue Docs MCP to contribute documentation, create cookbooks, and maintain consistency across Continue's docs - all through natural language prompts. + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Contributing to Continue Documentation](/CONTRIBUTING) for setup instructions +- Forked the [continuedev/continue](https://github.com/continuedev/continue) repository +- Node.js 20+ and Continue CLI installed + + + This cookbook assumes you've read the setup in the [CONTRIBUTING guide](/CONTRIBUTING). If you haven't, start there first. + + +## Continue Docs MCP Setup + + + Use the pre-built [Docs Assistant - Mintlify agent](https://hub.continue.dev/continuedev/docs-mintlify) that includes the Continue Docs MCP and is ready to use immediately. + + + + + ```bash + # From your Continue docs directory + cn --config continuedev/docs-mintlify + ``` + + This agent includes: + - **Continue Docs MCP** for searching Continue documentation + - **Mintlify formatting rules** for proper component usage + - **Documentation-focused prompts** for common tasks + + + + If you want to customize, create your own agent and add: + 1. [Continue Docs MCP](https://hub.continue.dev/continuedev/continue-docs-mcp) + 2. [Mintlify Technical Writing Rule](https://hub.continue.dev/mintlify/technical-writing-rule) + + See the [CONTRIBUTING guide](/CONTRIBUTING#option-2-create-your-own-custom-agent) for details. + + + +--- + +## What is the Continue Docs MCP? + + + A Model Context Protocol server built with [Mintlify's MCP generation](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) that enables semantic search across Continue documentation. [Learn more →](/reference/continue-mcp) + + +The MCP helps you: +- **Find examples** from existing documentation +- **Maintain consistency** with established patterns +- **Source accurate information** about Continue features +- **Write better documentation** faster + +--- + +## Documentation Workflows with Prompts + +### 🆕 Creating a New Cookbook + +Cookbooks show how to use Continue CLI with specific tools or services. Here's how to create one using the Continue Docs MCP: + + + + ```bash + cn --config continuedev/docs-mintlify + ``` + + **Prompt:** + ``` + "Show me the structure of existing MCP cookbooks in the Continue docs. + I want to create a cookbook for GitHub MCP." + ``` + + The agent will find examples like the dlt, Snyk, and Sanity cookbooks. + + + + **Prompt:** + ``` + "Using the Continue Docs MCP, find information about how GitHub MCP works. + Then search the web for the official GitHub MCP documentation and combine + both sources to create a cookbook following the same structure as the + dlt cookbook." + ``` + + The agent will: + - Search Continue docs for MCP patterns + - Fetch GitHub MCP official documentation + - Combine both sources + - Generate a cookbook with consistent formatting + + + + **Prompt:** + ``` + "Add my new github-mcp-continue-cookbook.mdx to the docs.json navigation + under the Cookbooks section." + ``` + + + + ```bash + npm run dev + # Visit http://localhost:3000 + ``` + + **Refine with prompts:** + ``` + "Add more examples to the troubleshooting section" + "Include a CI/CD workflow example using GitHub Actions" + "Add authentication setup using environment variables" + ``` + + + + + **Pro Tip:** The agent uses the Continue Docs MCP to maintain consistency with existing cookbooks automatically. + + +--- + +### ✏️ Updating Existing Documentation + + + + **Prompt:** + ``` + "Where is the MCP tools documentation located? Show me the file path." + ``` + + + + **Prompt:** + ``` + "Update the MCP tools documentation at docs/customization/mcp-tools.mdx + to include information about the new Slack MCP server. Use the Continue + Docs MCP to find examples of how other MCP servers are documented, then + add a similar section for Slack." + ``` + + + +--- + +### 📝 Adding New Guides + + + + **Prompt:** + ``` + "I want to create a guide for setting up Continue with Amazon Bedrock. + Search the Continue docs for similar model provider setup guides and + show me the common structure they follow." + ``` + + + + **Prompt:** + ``` + "Create a new guide at docs/guides/amazon-bedrock-setup.mdx following + the structure you found. Include: + - Prerequisites + - Step-by-step setup with code examples + - Configuration options + - Troubleshooting common issues + + Use the Continue Docs MCP to find accurate information about Continue's + model provider configuration." + ``` + + + + **Prompt:** + ``` + "Add this guide to docs.json under the Model Providers section" + ``` + + + +--- + +## Real-World Cookbook Examples + +### Example 1: PostgreSQL MCP Cookbook + +**Prompt:** +``` +"Create a cookbook for using Continue with PostgreSQL MCP. Follow the same +structure as the dlt cookbook, but customize it for database operations. + +Include these sections: +1. Quick start with pre-built agent +2. Manual setup with MCP configuration +3. Common database tasks (schema exploration, query writing, migrations) +4. Troubleshooting database connection issues + +Use the Continue Docs MCP to find MCP configuration patterns and search the +web for PostgreSQL MCP documentation." +``` + +### Example 2: Sentry Error Tracking Cookbook + +**Prompt:** +``` +"Create a cookbook showing how to use Continue to analyze Sentry errors. + +The cookbook should demonstrate: +1. Setting up Sentry MCP integration +2. Querying recent errors +3. Analyzing error patterns with AI +4. Generating fixes for common errors +5. CI/CD integration for automated error analysis + +Research the Snyk cookbook structure since it's also about error detection, +and adapt it for Sentry." +``` + +### Example 3: OpenAPI Documentation Cookbook + +**Prompt:** +``` +"I want to create a cookbook for using Continue to work with OpenAPI specs. + +Show how to: +1. Load OpenAPI specs into Continue's context +2. Generate API client code from specs +3. Create tests based on API endpoints +4. Update documentation when APIs change + +Use the Continue Docs MCP to find how context providers work, then combine +that with OpenAPI MCP information." +``` + +--- + +## Advanced Prompt Patterns + + + + ```bash + "Use the Continue Docs MCP to understand how agents + work in Continue, then search the web for Anthropic's + Computer Use MCP. Create a cookbook showing how to + combine Continue agents with Computer Use for + automated testing." + ``` + + + + ```bash + "Find all mentions of MCP servers across Continue + documentation. Then create a comprehensive reference + page that links to all MCP-related guides and + configurations." + ``` + + + + ```bash + "Review all cookbook files in docs/guides/ and check + if they follow the same structure. List any + inconsistencies and suggest updates to make them + uniform." + ``` + + + + ```bash + "Extract all code examples showing MCP server + configuration from the Continue docs. Format them + as a single reference page with explanations for + each pattern." + ``` + + + +--- + +## Testing Your Documentation + +### Local Preview + +```bash +cd docs +npm run dev +# Visit http://localhost:3000 +``` + +### Validation Prompts + +```bash +# Check formatting +"Review this documentation for Mintlify formatting issues and fix any problems" + +# Verify links +"Check all links in this file and ensure they point to existing documentation" + +# Test code examples +"Verify that all code examples in this cookbook are syntactically correct" +``` + +--- + +## Submitting Your Contribution + +**Prompt:** +```bash +"Create a pull request with my documentation changes and use the repo's +PR template to write the description" +``` + +The agent will: +- Create a feature branch +- Stage and commit your changes +- Push to your fork +- Generate a PR description following the template +- Open the PR for review + + + See the full [Contributing Guide](/CONTRIBUTING#submitting-your-contribution) for manual PR submission details. + + +--- + +## Automated Documentation Checks with GitHub Actions + +Add automated documentation checks to your PR workflow using the Continue Docs MCP agent: + +```yaml title=".github/workflows/docs-check.yml" +name: Documentation Check + +on: + pull_request: + types: [opened, synchronize] + paths: + - 'core/**' + - 'extensions/**' + - 'packages/**' + - 'gui/**' + +jobs: + check-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Analyze Changes for Documentation Needs + id: analyze + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + echo "🔍 Analyzing code changes for documentation needs..." + + # Get changed files + git diff origin/${{ github.base_ref }}..HEAD --name-only > changed_files.txt + + # Create detailed diff + git diff origin/${{ github.base_ref }}..HEAD > changes.diff + + # Use Continue agent to check if docs need updates + PROMPT="Review these code changes and determine if documentation updates are needed. + + Changed files: $(cat changed_files.txt | tr '\n' ' ') + + Consider: + - New features or APIs + - Breaking changes + - New configuration options + - Modified CLI commands + - New MCP integrations + + If docs updates are needed, specify which files in docs/ should be updated. + If no updates needed, respond with 'NO_DOCS_NEEDED'. + Be specific and concise." + + cn --config continuedev/docs-mintlify -p "$PROMPT" --auto > analysis.md || { + echo "⚠️ Analysis failed" + echo "needs_docs=false" >> $GITHUB_OUTPUT + exit 0 + } + + if grep -q "NO_DOCS_NEEDED" analysis.md; then + echo "needs_docs=false" >> $GITHUB_OUTPUT + else + echo "needs_docs=true" >> $GITHUB_OUTPUT + fi + + - name: Post Documentation Recommendation + if: steps.analyze.outputs.needs_docs == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + echo "📝 Creating PR comment with documentation recommendations..." + + cat > pr-comment.md <<'EOF' +## 📚 Documentation Update Recommended + +Based on the code changes in this PR, documentation updates may be needed: + +EOF + + cat analysis.md >> pr-comment.md + + cat >> pr-comment.md <<'EOF' + +--- + +### Next Steps + +1. Review the suggested documentation areas above +2. Update relevant files in the `/docs` folder +3. Consider updating: + - API references for interface changes + - Guides for workflow changes + - Configuration docs for new settings + - MCP cookbooks for new integrations + +### Resources +- [Contributing to Docs](/CONTRIBUTING) +- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) + +*This analysis was generated using the Continue Docs MCP agent.* +EOF + + gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md + + - name: Add Label + if: steps.analyze.outputs.needs_docs == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh pr edit ${{ github.event.pull_request.number }} --add-label "docs-needed" +``` + + + This workflow uses the Continue Docs MCP agent to analyze code changes and automatically comment on PRs when documentation updates are recommended. + + +--- + +## Documentation MCP for Other Projects + +Want to create documentation MCPs for your own projects? Mintlify makes it easy: + + + + ```bash + npm i -g mintlify + mintlify init + ``` + + + + Mintlify automatically generates an MCP server for your documentation, enabling semantic search. + + [Learn more about Mintlify MCP generation →](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) + + + + Share your docs MCP on [Continue Hub](https://hub.continue.dev/new?type=mcp) so others can use it with Continue agents. + + + + + The [Continue Docs MCP](/reference/continue-mcp) itself was built this way! + + +--- + +## Key Prompts Cheat Sheet + +| Task | Prompt | +|:-----|:-------| +| **Find structure** | "Show me the structure of existing cookbooks in Continue docs" | +| **Create cookbook** | "Create a cookbook for [tool] MCP following the dlt cookbook structure" | +| **Update docs** | "Update [file] to include information about [feature], using Continue Docs MCP to find examples" | +| **Add navigation** | "Add [file] to docs.json under the [section] section" | +| **Check consistency** | "Review this file for consistency with other Continue documentation" | +| **Fix formatting** | "Review for Mintlify formatting issues and fix any problems" | +| **Extract examples** | "Find all examples of [topic] in Continue docs" | +| **Research feature** | "Use Continue Docs MCP to explain how [feature] works in Continue" | + +--- + +## Resources + +### Continue Documentation +- [Contributing Guide](/CONTRIBUTING) - Setup and submission process +- [Continue Docs MCP Reference](/reference/continue-mcp) - MCP server details +- [Understanding Agents](/guides/understanding-agents) - How agents work + +### Mintlify +- [MCP Generation Guide](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) +- [Mintlify Documentation](https://mintlify.com/docs) + +### Community +- [Continue Discord](https://discord.gg/continue) - #documentation channel +- [GitHub Discussions](https://github.com/continuedev/continue/discussions) + +--- + +## Next Steps + + + + Set up your environment + + + + Install pre-built agent + + + + See cookbook examples + + + + Get help from community + + diff --git a/docs/guides/dlt-mcp-continue-cookbook.mdx b/docs/guides/dlt-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..c3460ed24 --- /dev/null +++ b/docs/guides/dlt-mcp-continue-cookbook.mdx @@ -0,0 +1,484 @@ +--- +title: "Building Data Pipelines with dlt MCP and Continue" +description: "Set up an AI-powered data engineering workflow that helps you develop, debug, and inspect dlt data pipelines using natural language commands." +sidebarTitle: "dlt Data Pipelines with Continue" +--- + + + An AI-powered data pipeline development system that uses Continue's AI agent with dlt + MCP to inspect pipeline execution, retrieve schemas, analyze datasets, and debug load errors - all through simple natural language prompts + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents) +- Python 3.8+ installed locally +- A dlt pipeline project (or create one during this guide) +- Basic understanding of data pipelines + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + ```bash + pip install dlt + ``` + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + + +## dlt MCP Workflow Options + + + Skip the manual setup and use our pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) that includes + the dlt MCP and optimized data pipeline workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Navigate to your pipeline project directory and run: + ```bash + cn --config dlthub/dlt-assistant + ``` + + This agent includes: + - **dlt MCP** pre-configured and ready to use + - **Pipeline-focused rules** for data engineering best practices + + + + Start with a comprehensive pipeline check: + ```bash + # TUI mode + Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes. + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** The pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) provides consistent pipeline development workflows and handles MCP configuration automatically, making it easier to get started with AI-powered data engineering. You can [remix and customize this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) later to fit your team's specific workflow. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Visit the [dlt MCP on Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) and click **Install** to add it to the agent you created in the step above. + + This will add dlt MCP to your agent's available tools. The Hub listing automatically configures the MCP command. + + + **Alternative installation methods:** + 1. **Quick CLI install**: `cn --mcp dlthub/dlt-mcp` + 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section + + Once installed, dlt MCP tools become available to your Continue agent for all prompts. + + + + The MCP will work with your existing dlt pipelines in your current directory. + + + + + + Start with a comprehensive pipeline check: + ```bash + # TUI mode + cn + # Then type: Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes. + ``` + + + + + + + + To use the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant), you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as manual setup) + + The agent will automatically detect and use your configuration along with the pre-configured dlt MCP for pipeline operations. + + + +--- + +## dlt MCP vs dlt+ MCP + + + **dlt MCP** is focused on local pipeline development and inspection. It provides tools to: + - Inspect pipeline execution and load information + - Retrieve schema metadata from your local pipelines + - Query dataset records from destination databases + - Analyze load errors, timings, and file sizes + + **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** extends these capabilities with cloud-based features for production deployments: + - Connect to dlt+ Projects and manage deployments + - Monitor pipeline runs across multiple environments + - Access centralized logging and observability + - Collaborate with team members on pipeline development + + For local development and getting started, **[dlt MCP](https://hub.continue.dev/dlthub/dlt-mcp)** is the right choice. Consider **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** when you need production deployment features and team collaboration. + + +--- + +## Pipeline Development Recipes + +Now you can use natural language prompts to develop and debug your dlt pipelines. The Continue agent automatically calls the appropriate dlt MCP tools. + + +You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section. + + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running pipeline operations that might make + changes, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This + shows you what the agent will do without executing it. + + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like pipeline inspection, schema retrieval, and error analysis. + + + +### Pipeline Inspection + + + Review pipeline execution details including load timing and file sizes. + +**TUI Mode Prompt:** +``` +Inspect my dlt pipeline execution and provide a summary of the load info. +Show me the timing breakdown and file sizes for each table. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Inspect my dlt pipeline execution and provide a summary of the load info. Show me the timing breakdown and file sizes for each table." --auto +``` + + + +### Schema Management + + + Get detailed schema information for your pipeline's tables. + +**TUI Mode Prompt:** +``` +Show me the schema for my users table including all columns, +data types, and any constraints. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Show me the schema for my users table including all columns, data types, and any constraints." --auto +``` + + + +### Data Exploration + + + Retrieve and analyze records from your destination database. + +**TUI Mode Prompt:** +``` +Get the last 10 records from my orders table and show me +the distribution of order statuses. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Get the last 10 records from my orders table and show me the distribution of order statuses." --auto +``` + + + +### Error Debugging + + + Investigate and understand pipeline load errors. + +**TUI Mode Prompt:** +``` +Check for any load errors in my last pipeline run. If there are errors, +explain what went wrong and suggest fixes. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Check for any load errors in my last pipeline run. If there are errors, explain what went wrong and suggest fixes." --auto +``` + + + +### Pipeline Creation + + + Create a new dlt pipeline from an API or data source. + +**TUI Mode Prompt:** +``` +Help me create a new dlt pipeline that loads data from the +JSONPlaceholder API users endpoint into DuckDB. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Help me create a new dlt pipeline that loads data from the JSONPlaceholder API users endpoint into DuckDB." --auto +``` + + + +### Schema Evolution + + + Review and manage schema evolution in your pipelines. + +**TUI Mode Prompt:** +``` +Check if my pipeline schema has evolved since the last run. +Show me what columns were added or modified. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Check if my pipeline schema has evolved since the last run. Show me what columns were added or modified." --auto +``` + + + +## Continuous Data Pipelines with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where data pipeline validation runs automatically in your CI/CD pipeline in headless mode using the [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant). Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific validation rules. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- Any required database credentials for your destination + + + The workflow uses the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) with `--config dlthub/dlt-assistant`. This agent comes pre-configured with the dlt MCP and optimized rules for pipeline operations. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize the validation rules and prompts for your specific pipeline requirements. + + +### Create Workflow File + +This workflow automatically validates your dlt data pipelines on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It inspects pipeline schemas, checks for errors, and posts a summary report as a PR comment. The workflow can also be triggered manually via `workflow_dispatch`. + +Create `.github/workflows/dlt-pipeline-validation.yml` in your repository: + +```yaml +name: Data Pipeline Validation with dlt MCP + +on: + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + validate-pipeline: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + + - name: Install dlt + run: | + pip install dlt + echo "✅ dlt installed" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Validate Pipeline Schema + run: | + echo "🔍 Validating pipeline schema..." + cn --config dlthub/dlt-assistant \ + -p "Inspect the pipeline schema and verify all required tables + and columns are present. Flag any missing or unexpected changes." \ + --auto + + - name: Check Pipeline Health + run: | + echo "📊 Checking pipeline health..." + cn --config dlthub/dlt-assistant \ + -p "Analyze the last pipeline run for errors or warnings. + Report any issues that need attention." \ + --auto + + - name: Comment Pipeline Report on PR + if: always() && github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPORT=$(cn --config dlthub/dlt-assistant \ + -p "Generate a concise summary (200 words or less) of: + - Pipeline schemas and row counts + - Any load errors or warnings + - Performance metrics (timing, file sizes) + - Recommended improvements" \ + --auto) + + gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT" +``` + + + The dlt MCP works with your local pipeline state. Make sure your CI environment + has access to the necessary pipeline configuration and credentials. + + +## Pipeline Development Best Practices + +Implement automated pipeline quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips. + + + ```bash + "Before committing pipeline changes, verify the schema + matches expectations and flag any unexpected modifications." + ``` + + + + ```bash + "When load errors occur, analyze the error details and + suggest specific code fixes to handle the data issues." + ``` + + + + ```bash + "Track pipeline execution times and file sizes. Alert if + performance degrades significantly from baseline." + ``` + + + + ```bash + "After each pipeline run, validate row counts and check for + null values in critical columns." + ``` + + +## Troubleshooting + +### Pipeline Not Found + +```bash +"Check if there's a dlt pipeline in the current directory. +If not, help me initialize a new pipeline." +``` + +### Destination Connection Issues + +```bash +"Verify the destination connection and credentials for my pipeline. +Test the connection and report any issues." +``` + +### Schema Inference Problems + + + **Verification Steps:** + - dlt MCP is installed via [Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) + - Pipeline directory is accessible + - Destination database credentials are configured + - Pipeline has been run at least once + + +## What You've Built + +After completing this guide, you have a complete **AI-powered data pipeline development system** that: + +✅ Uses natural language — Simple prompts instead of complex pipeline commands +✅ Debugs automatically — AI analyzes errors and suggests fixes +✅ Runs continuously — Automated validation in CI/CD pipelines +✅ Ensures quality — Pipeline checks prevent bad data from shipping + + + Your data pipeline workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine pipeline inspection and debugging with human oversight + through review and approval of changes. + + +## Next Steps + +1. **Inspect your first pipeline** - Try the pipeline inspection prompt on your current project +2. **Debug load errors** - Use the error analysis prompt to fix any issues +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Create new pipelines** - Use AI to scaffold new data sources +5. **Monitor performance** - Track pipeline execution metrics over time + +## Additional Resources + + + + Complete dlt platform documentation + + + Explore more MCP integrations and agents + + + Learn about AI assistants, MCP, and Continue integration + + + Deep dive into dlt MCP integration + + \ No newline at end of file diff --git a/docs/guides/github-mcp-continue-cookbook.mdx b/docs/guides/github-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..65ea7a3ef --- /dev/null +++ b/docs/guides/github-mcp-continue-cookbook.mdx @@ -0,0 +1,376 @@ +--- +title: "GitHub Issues and PRs with GitHub MCP and Continue" +description: "Use Continue and the GitHub MCP to list, summarize, and act on open issues and recently merged pull requests with natural language prompts." +sidebarTitle: "GitHub Issues with Continue" +--- + + + A GitHub workflow assistant that uses Continue with the GitHub MCP to: + - List, filter, and summarize open issues + - Review and summarize recently merged PRs + - Post comments with AI-generated summaries or checklists + - Automate routine GitHub maintenance with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents) +- Node.js 22+ installed locally +- A GitHub account and a repository to work with +- A GitHub token with the appropriate scopes: + - For read-only: `repo:read` + - To comment on issues/PRs: `public_repo` for public repos or `repo` for private repos + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + Add your `GITHUB_TOKEN` to your [Continue Hub agent's environment variables](https://hub.continue.dev/settings). + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + For write actions (e.g., posting comments), your token must include the relevant GitHub scopes. + + +## GitHub MCP Workflow Options + + + Use the GitHub MCP from Continue Hub for one-click setup, or add it via CLI. + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Visit the [Anthropic GitHub MCP](https://hub.continue.dev/anthropic/github-mcp) on Continue Hub and click **Install** to add it to your agent. + + The listing provides a pre-configured MCP block; add your `GITHUB_TOKEN` in Hub. + + + + From your repo root: + ```bash + cn --config continuedev/github-manager-ai + ``` + Now try: "List my open issues labeled bug and summarize priorities." + + + + + You can also attach an MCP to a one-off session: `cn --mcp anthropic/github-mcp`. + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: GitHub MCP + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_TOKEN: ${env:GITHUB_TOKEN} + connectionTimeout: 30 + ``` + + Notes: + - The exact `command`/`args` may differ based on the MCP you choose on Hub. Hub templates prefill these for you. + - Provide `GITHUB_TOKEN` via environment or Hub secrets. + + + + Launch Continue and ask: + ``` + List the 5 most recently updated open issues in this repository. + ``` + + + + + + + To use GitHub MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the GitHub MCP for issue and PR operations. + + + +--- + +## Issue Workflows + +Use natural language to explore, triage, and act on open issues. The agent calls GitHub MCP tools under the hood. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for automation + + +### Triage and Summaries + + + Get a prioritized overview of current open issues. + +**TUI Mode Prompt:** +``` +List the 20 most recently updated open issues in this repo. +Cluster by label and severity. Summarize top priorities. +``` + +**Headless Mode Prompt:** +```bash +cn -p "List the 20 most recently updated open issues in this repo. Cluster by label and severity. Summarize top priorities." --auto +``` + + + + Narrow by label or assignee. + +**TUI Mode Prompt:** +``` +Show open issues labeled bug or security, assigned to @me. +Summarize blockers and suggest next steps. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Show open issues labeled bug or security, assigned to @me. Summarize blockers and suggest next steps." --auto +``` + + +### Taking Action + + + Post an AI-generated status update or checklist. + +**TUI Mode Prompt:** +``` +Find the issue with the most engagement (comments, reactions) in the last 30 days. +Come up with a triage plan and draft a comment with: +- current hypothesis +- next 2 steps +- owner and ETA +Then post the comment. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find the issue with the most engagement in the last 30 days. Come up with a triage plan and draft a comment (hypothesis, next 2 steps, owner, ETA) and post it." --auto +``` + + + Requires a token with permission to comment (`public_repo` or `repo`). The agent will confirm before posting unless `--auto` is used. + + + + + Identify issues that need attention. + +**TUI Mode Prompt:** +``` +Find open issues with no activity in the last 30 days. +Suggest action (close, needs-repro, or prioritize) and draft comments. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find open issues with no activity in the last 30 days. Suggest action and draft comments for each." --auto +``` + + +--- + +## Merged PR Workflows + +Analyze recently merged PRs for change awareness, release notes, and quality signals. + +### Recently Merged Overview + + + Summarize merged PRs over a time window. + +**TUI Mode Prompt:** +``` +List PRs merged in the last 7 days. +Group by area (label or path). Summarize impact and notable changes. +``` + +**Headless Mode Prompt:** +```bash +cn -p "List PRs merged in the last 7 days. Group by area (label or path). Summarize impact and notable changes." --auto +``` + + +### Release Notes + + + Turn merged PRs into crisp release notes. + +**TUI Mode Prompt:** +``` +Generate release notes for PRs merged since tag v1.2.0. +Use keep-a-changelog sections and include PR numbers/authors. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Generate release notes for PRs merged since tag v1.2.0. Use keep-a-changelog sections and include PR numbers/authors." --auto +``` + + +### Deep Dives + + + Get a human-readable summary of a recently merged PR with active discussion. + +**TUI Mode Prompt:** +``` +Find the last merged PR with a significant amount of comments. +Summarize the conversation, including goal, key changes, +risk areas, and any follow-ups. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find the last merged PR with a significant amount of comments. Summarize the conversation including goal, key changes, risk areas, and follow-ups." --auto +``` + + +--- + +## Automate with GitHub Actions + +Run headless commands on a schedule or in PRs to keep teams informed. + +### Add GitHub Secrets + +Repository Settings → Secrets and variables → Actions: + +- `CONTINUE_API_KEY`: From [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `GITHUB_TOKEN`: A token with permissions to read issues/PRs and post comments + +### Example Workflow + +Create `.github/workflows/github-mcp-reports.yml`: + +```yaml +name: GitHub MCP Reports + +on: + schedule: + - cron: "0 13 * * 1" # Mondays 13:00 UTC + workflow_dispatch: + pull_request: + types: [opened, synchronize] + +jobs: + report: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "18" + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Weekly Issue Triage Summary + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + run: | + cn --config continuedev/github-manager-ai \ + -p "List open issues updated in the last 14 days. Group by label and priority. Propose top 5 actions and include issue links." \ + --auto > issue_summary.txt + + - name: Post PR Context Comment + if: github.event_name == 'pull_request' + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + REPORT=$(cn --config continuedev/github-manager-ai \ + -p "Summarize the context for PR #${PR_NUMBER}: related open issues, risk areas, and test suggestions. Keep under 200 words." \ + --auto) + gh pr comment ${PR_NUMBER} --body "$REPORT" +``` + + + Use `continuedev/github-manager-ai` consistently throughout your automation as the recommended agent configuration. + + +--- + +## Troubleshooting + +- **Missing or invalid token:** Ensure `GITHUB_TOKEN` is set and has the required scopes. Try a minimal test: “List 3 open issues in this repo”. +- **Permissions errors on comment:** Your token must include `public_repo` (public) or `repo` (private) to write comments. +- **Rate limiting:** Reduce frequency or filter queries; consider using a PAT distinct from the default Actions token when running in CI. +- **MCP connection timeout:** If using custom YAML, increase `connectionTimeout` or verify the `command`/`args` from the Hub listing. + +## What You've Built + +After completing this guide, you have a complete **AI-powered GitHub workflow system** that: + +- ✅ Uses natural language — Simple prompts for complex GitHub operations +- ✅ Automates issue triage — AI analyzes and summarizes open issues +- ✅ Generates release notes — Automatic PR digests and changelogs +- ✅ Runs continuously — Automated reports via GitHub Actions + + + Your GitHub workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine issue triage and PR summaries with human oversight + through review and approval. + + +## Next Steps + +1. **Explore your issues** - Try the issue triage prompts on your repository +2. **Generate release notes** - Use the merged PR prompts to create changelogs +3. **Set up automation** - Add the GitHub Actions workflow to your repo +4. **Customize prompts** - Tailor the prompts to your team's workflow +5. **Monitor progress** - Track issue resolution metrics over time + +## Additional Resources + + + + Anthropic GitHub MCP on Continue Hub + + + How MCP works with Continue agents + + + Pre-configured agent on Continue Hub + + + Official GitHub MCP server README + + + diff --git a/docs/guides/netlify-mcp-continuous-deployment.mdx b/docs/guides/netlify-mcp-continuous-deployment.mdx index c852de1de..a6e53a6ef 100644 --- a/docs/guides/netlify-mcp-continuous-deployment.mdx +++ b/docs/guides/netlify-mcp-continuous-deployment.mdx @@ -95,7 +95,7 @@ After completing **Quick Setup** above, you have two paths to get started: - Navigate to your project directory and run: + From your project directory, run: ```bash cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals." ``` diff --git a/docs/guides/notion-continue-guide.mdx b/docs/guides/notion-continue-guide.mdx new file mode 100644 index 000000000..b1dc4227b --- /dev/null +++ b/docs/guides/notion-continue-guide.mdx @@ -0,0 +1,377 @@ +--- +title: "Developer & Team Workflows with Notion + Continue CLI" +description: "Use Continue CLI with Notion to generate docs, manage tasks, and automate project workflows – all through natural-language prompts." +sidebarTitle: "Notion with Continue" +--- + + + + A workflow that lets you query, update, and create Notion pages or database + entries from natural-language prompts. Generate PRDs, sprint tasks, meeting + notes, or status reports automatically – perfect for individual developers + and cross-functional teams. + + + +## What You'll Learn + +This guide teaches you to: +- Use natural language to connect to the Notion API directly with Continue CLI for powerful automation +- Configure Notion API access with proper permissions and security +- Run prompts in both TUI (interactive) and headless modes +- Create automated workflows that generate docs, manage tasks, and sync data + +## Prerequisites + +Before starting, ensure you have: + +- [Continue CLI](https://docs.continue.dev/cli/overview) installed (`npm i -g @continuedev/cli`) +- A [Notion workspace](https://notion.so) with Editor (or higher) access +- Node.js 18+ installed locally +- [Continue account](https://hub.continue.dev) with **Hub access** + + + + **Agent usage requires credits** – create a Continue API key at + [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + and store it as a secret. + + + + + + ```bash + npm i -g @continuedev/cli + ``` + Verify installation: + ```bash + cn --version + ``` + + + + 1. Go to **[Notion Integrations](https://www.notion.so/my-integrations)** + 2. Click **+ New integration** → give it a name (e.g. "Continue Integration") + 3. Select your workspace + 4. Under **Content Capabilities**, enable: + - ✅ Read content + - ✅ Update content + - ✅ Insert content + 5. Under **Comment Capabilities**, enable: + - ✅ Read comments + - ✅ Insert comments + 6. Under **User Capabilities**, select: + - ✅ Read user information including email addresses + 7. Click **Submit** and copy the **Internal Integration Secret** (starts with `secret_`) + + + + This token is your `NOTION_API_KEY`. + Keep it safe – you won't be able to view it again. + + + + 8. In Notion, open each database or top-level page you want accessible → **Share** → **Invite** your new integration → **Full access**. + + + + Set your Notion API key as an environment variable in your terminal: + + ```bash + export NOTION_API_KEY="secret_xxx" + ``` + + + + Running this command sets your API key for the current terminal session only. + When you close the terminal, the variable won't persist. To test your API key, run the curl command below in the same session. + + ```bash + curl -H "Authorization: Bearer $NOTION_API_KEY" \ + -H "Notion-Version: 2022-06-28" \ + https://api.notion.com/v1/databases + ``` + + + + + Depending on what you want `cn` to accomplish, you'll need to add your Notion workspace keys to the terminal session. The workspace key is your Notion database ID. Run the following command: + + ```bash + export NOTION_DATABASE_ID="your_database_id" + ``` + + + You can find your database ID by: + 1. Opening your Notion changelog database + 2. Looking at the URL - it will be something like: + https://www.notion.so/your-workspace/DATABASE_ID?v=... + 3. The DATABASE_ID is the long string of characters between the last / and the ? + + + + + +## Running Continue AI Agent with Notion API + + + + Continue CLI offers two powerful modes for Notion automation: + **TUI mode** for interactive workflows and **Headless mode** for automated scripts. + + + + + + + + + Navigate to your project directory and run: + ```bash + cn + ``` + + + + In the TUI interface, enter: + ``` + 1. Fetch my Notion databases using the Notion API key + and Database ID stored in this terminal session. + 2. Look at the last week of Merged GitHub PRs, and create + a changelog entry in Notion summarizing the features and breaking changes. + ``` + + + + TUI mode lets you review and approve each action before execution, + perfect for learning and debugging. + + + + + + + + + + Execute prompts directly from the command line: + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the Notion API key + and Database ID stored in this terminal session. + 2. Analyze all merged GitHub PRs from the past week. + 3. Extract feature descriptions and breaking changes. + 4. Create a technical changelog in Notion with PR links." + ``` + + **Flags explained:** + - `-p`: Run without TUI interface + - `--auto`: Execute without manual approval + + + + Always test prompts in TUI mode first before running + them with `--auto` in production. + + + + + + + + + + - Environment variable `NOTION_API_KEY` must be set before running Continue CLI + - Continue automatically uses the API key to authenticate with Notion + - No need for manual curl commands - just reference "the API key stored in this session" + - For complex workflows, Continue maintains the API connection throughout + - Consider creating aliases or scripts for frequently used prompts + + + +--- + +## Quick Start Example + +Working example that demonstrates the power of Continue with Notion API: + + + + **This exact command has been tested and works:** + + ```bash + # Weekly Sprint Summary + cn -p --auto " + 1. Fetch Notion Sprint database + 2. Analyze completed tasks vs planned + 3. Generate sprint retrospective page + 4. Add velocity metrics and burndown chart" + ``` + + **What this does:** + 1. Connects to your Notion workspace using the API key + 2. Analyzes your sprint data + 3. Calculates completion metrics + 4. Creates a comprehensive retrospective with visualizations + + + + +## Example Prompts & Workflows + +With the Notion API configured, you can use natural language prompts to automate your workspace. Here are examples for both TUI and headless modes: + + + + **TUI Mode:** + ```bash + cn " + 1. Fetch my Notion databases using the API key and secrets stored in this session + 2. Generate API documentation for all endpoints + in src/api/routes with request/response schemas + 3. Create a page in Technical Docs database + " + ``` + + **Headless Mode:** + ```bash + cn -p --auto "Fetch my Notion databases using the API key and secrets stored in this session. Generate API docs + for src/api/routes and save to Notion in Technical Docs database" + ``` + + + + **Headless Mode (Automated):** + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the API key stored in this session + 2. Scan codebase for TODO and FIXME comments + 3. Create tasks in my Notion Engineering Backlog database + 4. Include file paths and complexity estimates" + ``` + + + + ```bash + cn -p --auto " + 1. Fetch my Notion databases using the API key stored in this session + 2. Analyze all merged GitHub PRs from past month + 3. In my Notion Launch Database, review the Launch Template. + 4. Create an October Launch doc in Notion with a week of launches and materials based on the Launch documents based on the PR analysis and launch documents." + ``` + + + + + ```bash + cn -p --auto " + 1. Fetch my Tasks database from Notion using the API key + 2. Find tasks completed yesterday + 3. Find tasks in progress + 4. Create standup note with: completed, + in-progress, and blockers sections" + ``` + + + +## Advanced Workflows + + + + ```bash + cn -p --auto " + 1. Connect to Notion using the API key in this session + 2. Get merged PRs from last 7 days using GitHub + 3. Extract feature descriptions and changes + 4. Create formatted changelog in Notion + 5. Add links back to GitHub PRs" + ``` + + + + Requires GitHub repository access. To add GitHub access, update your [integration settings](https://hub.continue.dev/settings/integrations). + + + + + + ```bash + cn -p --auto " + 1. Connect to Notion using the API key in this session + 2. Run test coverage report (npm test -- --coverage) + 3. Parse coverage metrics + 4. Update Test Metrics database in Notion + 5. Flag files with coverage below 80%" + ``` + + + + ```bash + cn " + 1. Connect to Notion using the API key in this session + 2. In my Blog Posts Database, find drafts tagged 'Review' + 3. Review all blog posts for grammar and clarity and suggest improvements through comments. + ``` + + + + ```bash + cn -p --auto " + 1. Connect to Notion databases using API key + 2. Aggregate completed tasks from the week + 3. Calculate velocity and burndown metrics + 4. Generate weekly report with charts + 5. Share link in Slack #team-updates" + ``` + + + +## Security Best Practices + + + + **Protect Your API Keys:** + - Never commit `NOTION_API_KEY` to version control + - Use environment variables or secure secret managers + - Rotate API keys every 90 days + - Grant integration access only to required databases/pages + - Monitor API usage through Notion's integration dashboard + - Use `.env` files with `.gitignore` for local development + + + + +## Next Steps + +- Create a **GitHub Actions** workflow to automate changelog generation on releases +- Build a **daily standup bot** that runs every morning and posts to Slack +- Set up **database templates** in Notion for consistent formatting +- Explore **batch operations** to update multiple pages efficiently +- Implement **error handling** for API rate limits and network issues + +--- + +## Troubleshooting + + + + **API Key Not Found:** + - Ensure `NOTION_API_KEY` is exported in your current shell session + - Check for typos in the environment variable name + - Verify the key starts with `secret_` + + **Database Access Denied:** + - Share the specific database with your integration in Notion + - Ensure the integration has the correct permissions (Read, Write, Insert) + + **Connection Issues:** + - Verify Continue CLI has internet access + - Check network connectivity to api.notion.com + - Ensure your Notion workspace allows API access + + **Rate Limiting:** + - Notion API has rate limits (3 requests per second) + - Implement exponential backoff for automated scripts + - Consider batching operations when possible + + diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index 3ca80dae0..e4eb77ccf 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -14,14 +14,21 @@ description: "Comprehensive collection of practical guides for Continue includin - [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows - [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue - [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption +- [Notion + Continue Guide](/guides/notion-continue-guide) - Automate docs, tasks, and release workflows ## MCP Integration Cookbooks Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue: +- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows +- [GitHub MCP Cookbook](/guides/github-mcp-continue-cookbook) - Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments - [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation - [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP +- [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets +- [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP +- [Sentry Error Monitoring Cookbook](/guides/sentry-mcp-error-monitoring) - Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues - [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers +- [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging ## What Advanced Tutorials Are Available diff --git a/docs/guides/posthog-github-continuous-ai.mdx b/docs/guides/posthog-github-continuous-ai.mdx index a84b64e1e..e4421f7ed 100644 --- a/docs/guides/posthog-github-continuous-ai.mdx +++ b/docs/guides/posthog-github-continuous-ai.mdx @@ -67,6 +67,7 @@ First, you'll need to gather your PostHog and GitHub API credentials and add the 3. Name it "Continue CLI Session Analysis" 4. Select these scopes: - `session_recording:read` - **Required** for accessing session data + - `feature_flag:read` - **Required** for feature flag auditing - `insight:read` - `query:read` - `session_recording_playlist:read` @@ -146,7 +147,7 @@ You only need to configure the PostHog MCP credential - it automatically handles - Navigate to your project directory and run: + From your project directory, run: ```bash cn "Give me my PostHog Session data and create GitHub issues based on the problems." ``` @@ -212,227 +213,24 @@ You only need to configure the PostHog MCP credential - it automatically handles **Repository Labels Required**: Make sure your GitHub repository has these labels: -- `bug`, `enhancement` +- `bug`, `enhancement`, `technical-debt` - `high-priority`, `medium-priority`, `low-priority` -- `user-experience`, `automated` +- `user-experience`, `automated`, `feature-flag`, `cleanup` Create missing labels in your repo at: **Settings → Labels → New label** - **What Continue CLI Does:** - Parses your analysis results automatically - - Makes authenticated GitHub API calls using your stored token - Creates - properly formatted issues with appropriate labels - Checks for duplicate - issues to avoid spam - Provides confirmation with issue URLs + **What Continue CLI Does:** + - Parses your analysis results automatically + - Makes authenticated GitHub API calls using your stored token + - Creates properly formatted issues with appropriate labels + - Checks for duplicate issues to avoid spam + - Provides confirmation with issue URLs + -## Setting Up Automated GitHub Actions Workflow - -Create a GitHub Actions workflow that runs your Continue CLI analysis automatically on a schedule. - -### Add GitHub Secrets - -First, add these secrets to your GitHub repository: - -1. Go to **Repository Settings → Secrets and variables → Actions** -2. Click **"New repository secret"** and add: - - `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev - -### Create GitHub Actions Workflow - -Create `.github/workflows/posthog-analysis.yml` in your repository: - - - -```yaml -name: PostHog Session Analysis with Continue CLI Agent - -on: -schedule: - cron: "0 6 \* \* \*" # Run at 6 AM UTC daily -workflow_dispatch: # Allow manual triggering - -jobs: -analyze: -runs-on: ubuntu-latest - - permissions: - contents: read - issues: write - - steps: - - uses: actions/checkout@v4 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: "18" - - - name: Install Continue CLI - run: | - npm install -g @continuedev/cli - echo "✅ Continue CLI installed" - cn --version - - - name: Authenticate with Continue CLI - run: | - # Set Continue API key - export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}" - # Login to Continue CLI - if ! cn auth login --api-key "$CONTINUE_API_KEY"; then - echo "❌ Failed to authenticate with Continue CLI" - exit 1 - fi - echo "✅ Continue CLI authenticated" - - - name: Load PostHog GitHub Agent - run: | - echo "🤖 Loading PostHog GitHub Continuous AI Agent..." - cn --config continuedev/awesome-models-posthog-gh - echo "✅ Agent loaded successfully" - - - name: Run PostHog Analysis and Create GitHub Issues - run: | - echo "🎬 Starting automated PostHog session analysis..." - - # Run the agent with the simple prompt - cn -p "Tell me about my PostHog session recordings and create GitHub issues based on the problems." - - echo "✅ Analysis and issue creation completed" - - - name: Summary - run: | - echo "✅ PostHog analysis workflow completed!" - echo "📊 Check the artifacts for detailed analysis results" - echo "🐛 Check your repository issues for newly created UX issues" - echo "🤖 Agent automatically handled both analysis and issue creation" - ``` - - - - - -```yaml -name: PostHog Session Analysis with Continue CLI Manual - -on: -schedule: - cron: "0 6 \* \* \*" # Run at 6 AM UTC daily -workflow_dispatch: # Allow manual triggering - -jobs: -analyze: -runs-on: ubuntu-latest - - permissions: - contents: read - issues: write - - steps: - - uses: actions/checkout@v4 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: "18" - - - name: Install Continue CLI - run: | - npm install -g @continuedev/cli - echo "✅ Continue CLI installed" - cn --version - - - name: Authenticate with Continue CLI - run: | - # Set Continue API key - export CONTINUE_API_KEY="${{ secrets.CONTINUE_API_KEY }}" - # Login to Continue CLI - if ! cn auth login --api-key "$CONTINUE_API_KEY"; then - echo "❌ Failed to authenticate with Continue CLI" - exit 1 - fi - echo "✅ Continue CLI authenticated" - - - name: Run PostHog Session Analysis - run: | - echo "🎬 Starting PostHog session analysis..." - # Create the analysis prompt - I need you to help me analyze PostHog session recordings to identify UX issues. Please: - - 1. First, fetch session recordings from PostHog using these details: - - Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets - - API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20 - - Include Authorization header: 'Bearer {POSTHOG_API_KEY}' - - 2. Filter the sessions to find problematic ones with either: - - console_error_count > 0 (JavaScript errors) - - recording_duration > 300 (sessions longer than 5 minutes) - - 3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems. - - 4. Format each issue like this: - ### 1. **Issue Title Here** - **Problem**: One sentence describing the user problem - **Technical Causes**: Brief technical explanation - **Affected Pages**: List the URLs - **Recommended Fix**: - - Specific action item 1 - - Specific action item 2 - **Priority**: **HIGH** or **MEDIUM** or **LOW** - **Impact**: Quantify the impact (e.g., 'Affects 80% of sessions') - - Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data. - EOF - - echo "✅ Analysis completed" - - - - name: Create GitHub Issues from Analysis - run: | - echo "📝 Creating GitHub issues from analysis..." - # Create the issue creation prompt - I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API. - - For each issue in my analysis: - 1. Parse the issue title, body content, and priority level - 2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues - 3. Use these headers: - - Authorization: token {GITHUB_PAT} - - Accept: application/vnd.github.v3+json - - Content-Type: application/json - 4. Set labels based on priority: - - HIGH: ["bug", "high-priority", "user-experience", "automated"] - - MEDIUM: ["enhancement", "medium-priority", "user-experience", "automated"] - - LOW: ["low-priority", "user-experience", "automated"] - 5. Format the issue title as: "🔍 UX Issue: {original title}" - - Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs. - - echo "✅ Issue creation completed" - - - name: Summary - run: | - echo "✅ PostHog analysis workflow completed!" - echo "🐛 Check your repository issues for newly created UX issues" - ``` - - - - -### Test the GitHub Actions Workflow - -1. **Manual Trigger**: Go to **Actions** tab in your repository and manually trigger the workflow -2. **Check Artifacts**: Download the analysis results from the workflow run -3. **Verify Issues**: Check that GitHub issues were created in your repository - - - - **Success Indicators:** - - PostHog API returns session data (not empty) - - Continue CLI generates analysis with identified issues - - GitHub issues are created with proper labels and formatting - - Workflow completes without errors - - ## What You've Built @@ -469,7 +267,57 @@ After completing this guide, you have a complete **Continuous AI system** that: -## Advanced Prompts +## Example Use Cases + +Here are practical examples of what you can build with PostHog MCP and Continue CLI: + +### Session Recording Analysis (Current Implementation) + +The main workflow above focuses on analyzing session recordings to identify UX issues and create GitHub issues automatically. + +### Feature Flag Audit and Cleanup + + + Automatically audit your feature flags to identify unused, outdated, or problematic flags that need attention. + + +**What this workflow does:** +- Fetches all feature flags from your PostHog project +- Analyzes flag usage, rollout status, and configuration +- Identifies flags that may be candidates for removal or updates +- Creates GitHub issues for flag cleanup tasks + +**Example Continue CLI prompts:** + +```bash +# Get all feature flags and analyze them +cn "Use PostHog MCP to fetch all feature flags with mcp__posthog__feature-flag-get-all. Then analyze each flag to identify: 1) Flags that are 100% rolled out and could be removed, 2) Flags that haven't been updated in 90+ days, 3) Flags with complex targeting that might need simplification, 4) Experimental flags that should be cleaned up." + +# Create cleanup issues for identified flags +cn "For each problematic feature flag identified, create a GitHub issue using gh CLI: +- Title: '🏁 Feature Flag Cleanup: [flag_name]' +- Include flag details: rollout percentage, last modified date, targeting rules +- Add labels: 'technical-debt', 'feature-flag', 'cleanup' +- Set priority based on risk level (high for 100% rollouts, medium for stale flags) +- Include specific recommendations for each flag" + +# Audit flag performance impact +cn "Cross-reference feature flags with PostHog performance metrics to identify flags that may be impacting user experience or site performance. Create performance-focused GitHub issues for flags showing negative impact." +``` + +**Required PostHog MCP Tools:** +- `feature-flag-get-all` - Retrieve all feature flags +- `feature-flag-get-definition` - Get detailed flag configuration +- `query-run` - Run analytics queries to check flag usage +- `insights-get-all` - Get insights related to flag performance + +**Sample Output:** +This workflow creates GitHub issues like: +- "🏁 Feature Flag Cleanup: dark-mode-toggle" (100% rollout, safe to remove) +- "🏁 Feature Flag Review: experimental-checkout" (unused for 120 days) +- "🏁 Feature Flag Simplify: complex-user-targeting" (overly complex rules) + +### Advanced Prompts Consider enhancing your workflow with these advanced Continue CLI prompts: @@ -483,13 +331,12 @@ Consider enhancing your workflow with these advanced Continue CLI prompts: "Cross-reference JavaScript console errors with user actions to identify the root cause of UX issues" - - "Analyze how [PostHog feature flags](https://posthog.com/docs/feature-flags) - impact user behavior in session recordings" + + "Use PostHog MCP to correlate feature flag rollouts with performance metrics and user behavior changes to identify flags causing issues" "Create Slack alerts when critical UX issues are detected in PostHog - sessions" + sessions or when feature flags need attention" diff --git a/docs/guides/sanity-mcp-continue-cookbook.mdx b/docs/guides/sanity-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..8af21df8d --- /dev/null +++ b/docs/guides/sanity-mcp-continue-cookbook.mdx @@ -0,0 +1,610 @@ +--- +title: "Content Management with Sanity MCP and Continue" +description: "Set up an AI-powered content management workflow that helps you manage schemas, run GROQ queries, handle documentation, and perform migrations using natural language commands." +sidebarTitle: "Sanity CMS with Continue" +--- + + + An AI-powered content management system workflow that uses Continue's AI agent with Sanity + MCP to manage schemas, execute GROQ queries, handle migrations, and maintain documentation - all through simple natural language prompts + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents) +- Node.js 20+ installed locally +- A [Sanity account](https://www.sanity.io/) and project (free tier works) +- Basic understanding of content management systems + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + ```bash + npm install -g @sanity/cli + ``` + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys) and proper environment variable configuration. + + +## Getting Started with Sanity + + + +New to Sanity? Follow the [Sanity Getting Started Guide](https://www.sanity.io/docs/getting-started) to set up your first project. + +**Quick setup:** +```bash +npm create sanity@latest +cd your-project-name +npm run dev +``` + +**Key resources:** +- [Sanity Studio](https://www.sanity.io/docs/sanity-studio) - Content editing interface +- [Schema Types](https://www.sanity.io/docs/schema-types) - Define content structure +- [GROQ](https://www.sanity.io/docs/groq) - Query language for fetching content +- [Content Lake](https://www.sanity.io/docs/datastore) - Real-time data store + + + +## Sanity MCP Workflow Options + + + Skip the manual setup and use our pre-built Sanity Assistant agent that includes + the Sanity MCP and optimized content management workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs. + + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Visit the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/sanity-agent-config + ``` + + This agent includes: + - **[Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp)** pre-configured and ready to use + - **Content management rules** for best practices + - **Schema optimization** guidelines + + + + Start with these beginner-friendly prompts to explore your content: + + ```bash + # Content exploration + "Show me all blog posts published in the last month" + + # Schema understanding + "Show me all the document types in my Sanity schema and explain their relationships" + + # Content management + "Create a new product page for our upcoming feature" + ``` + + That's it! The agent handles everything automatically. For more starter prompts and examples, see the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + + + + **Why Use the Agent?** The pre-built Sanity Assistant agent provides consistent content management workflows and handles MCP configuration automatically, making it easier to get started with AI-powered CMS operations. Results are more consistent and debugging is easier thanks to the [Sanity MCP](https://hub.continue.dev/sanity/sanity-mcp) integration and pre-tested prompts. + + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Visit the [Sanity MCP on Continue Hub](https://hub.continue.dev/sanity/sanity-mcp) and click **"Install"** to add it to the agent you created in the step above. + + This will add Sanity MCP to your agent's available tools. The Hub listing automatically configures the MCP connection. + + + **Alternative installation methods:** + 1. **Quick CLI install**: `cn --mcp sanity/sanity-mcp` + 2. **With config**: Use [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup + 3. **Manual configuration**: Add the MCP to your agent configuration + + Once installed, Sanity MCP tools become available to your Continue agent for all prompts. + + + + **Authentication Options:** + - **Interactive mode**: OAuth authentication via browser (expires after 7 days) + - **Headless/CI mode**: Uses environment variables (SANITY_API_TOKEN, SANITY_PROJECT_ID, etc.) + + See [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) for environment variable setup. + + + + + + Start with these beginner-friendly prompts: + ```bash + cn + # Try these starter prompts: + # "Show me all blog posts published in the last month" + # "Show me all the document types in my Sanity schema and explain their relationships" + # "Create a new product page for our upcoming feature" + ``` + + For more examples, see the [Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + + + + + + + To use the pre-built Sanity Assistant agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the pre-configured Sanity MCP for content operations. Note that OAuth authentication will be required on first use. + + + +--- + +## Sanity MCP Capabilities + + + **Sanity MCP** provides comprehensive tools for content management: + - Execute [GROQ queries](https://www.sanity.io/docs/groq) to fetch and analyze content + - Explore and modify [document schemas](https://www.sanity.io/docs/schema-types) + - Manage [content releases](https://www.sanity.io/docs/release-schedules) and versions + - Handle content [migrations](https://www.sanity.io/docs/migrating-data) between environments + - Automate documentation generation + - Perform bulk content operations + - Manage [localization](https://www.sanity.io/docs/localization) and translations + + The MCP integrates seamlessly with your existing Sanity workspace, providing AI-powered assistance for both development and content operations. + + +--- + +## Your First MCP Conversation + +With everything set up, you're ready for your first AI-powered content conversation! Try these beginner-friendly starter prompts: + + + + ``` + "Show me all blog posts published in the last month" + ``` + + + ``` + "Create a new product page for our upcoming feature" + ``` + + + ``` + "Update our pricing information across all service pages" + ``` + + + ``` + "Schedule the Easter marketing campaign content release for next Tuesday" + ``` + + + + +**New to MCP?** These prompts demonstrate the power of natural language content management. For more examples and detailed explanations, check out the [official Sanity MCP blog post](https://www.sanity.io/blog/model-context-protocol). + + +## Content Management Recipes + +Now you can use natural language prompts to manage your Sanity content and schemas. The Continue agent automatically calls the appropriate Sanity MCP tools. + + +You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section. + + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running operations that might make + changes, test your prompts in plan mode (see the [Plan Mode + Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This + shows you what the agent will do without executing it. + + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like schema exploration, GROQ execution, and content migration. + + + +### Schema Management + + + Review and understand your content schema structure. + +**TUI Mode Prompt:** +``` +Show me all document types in my Sanity schema with their fields, +validation rules, and relationships to other types. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Show me all document types in my Sanity schema with their fields, validation rules, and relationships to other types." --auto +``` + + + +### GROQ Queries + + + Run GROQ queries to fetch and analyze content. + +**TUI Mode Prompt:** +``` +Run a GROQ query to fetch all articles published in the last 30 days, +including their titles, authors, categories, and view counts. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Run a GROQ query to fetch all articles published in the last 30 days, including their titles, authors, categories, and view counts." --auto +``` + + + +### Content Operations + + + Perform bulk operations on your content. + +**TUI Mode Prompt:** +``` +Find all blog posts with the category "News" and update their +status to "archived" if they are older than 6 months. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find all blog posts with the category 'News' and update their status to 'archived' if they are older than 6 months." --auto +``` + + + +### Localization + + + Set up and manage content translations. + +**TUI Mode Prompt:** +``` +Add localization support to my article document type for +Spanish and French languages with appropriate field configurations. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Add localization support to my article document type for Spanish and French languages with appropriate field configurations." --auto +``` + + + +### Content Migration + + + Migrate content between different schemas or environments. + +**TUI Mode Prompt:** +``` +Help me migrate my blog posts from the old schema structure +to the new one, mapping the deprecated fields to the new format. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Help me migrate my blog posts from the old schema structure to the new one, mapping the deprecated fields to the new format." --auto +``` + + + +### Documentation Generation + + + Automatically generate documentation for your content model. + +**TUI Mode Prompt:** +``` +Generate comprehensive documentation for my Sanity schema including +all document types, their purposes, field descriptions, and usage examples. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Generate comprehensive documentation for my Sanity schema including all document types, their purposes, field descriptions, and usage examples." --auto +``` + + + +### Content Releases + + + Work with Sanity's content release feature. + +**TUI Mode Prompt:** +``` +List all active releases in my dataset and show me the content +changes scheduled for each release. +``` + +**Headless Mode Prompt:** +```bash +cn -p "List all active releases in my dataset and show me the content changes scheduled for each release." --auto +``` + + + +### Performance Analysis + + + Optimize GROQ queries for better performance. + +**TUI Mode Prompt:** +``` +Analyze the performance of my most frequent GROQ queries and +suggest optimizations to improve response times. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Analyze the performance of my most frequent GROQ queries and suggest optimizations to improve response times." --auto +``` + + + +## Continuous Content Management with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where content validation and schema checks run automatically in your CI/CD pipeline in headless mode using the Sanity agent config. Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific content governance rules. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `SANITY_PROJECT_ID`: Your Sanity project ID +- `SANITY_DATASET`: Your Sanity dataset name (usually "production") +- `SANITY_API_TOKEN`: Your Sanity API token with appropriate permissions +- `MCP_USER_ROLE`: Your MCP user role (typically "admin" or "editor") + + + The workflow uses the [Sanity Agent Config](https://hub.continue.dev/continuedev/sanity-agent-config) with environment variable authentication via [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config). This enables headless mode operation without OAuth browser authentication. + + +### Create Workflow File + +This workflow automatically validates your Sanity schemas and content on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It checks schema integrity, validates content relationships, and posts a summary report as a PR comment. + +Create `.github/workflows/sanity-content-validation.yml` in your repository: + +```yaml +name: Sanity Content Validation with MCP + +on: + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + validate-content: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SANITY_PROJECT_ID: ${{ secrets.SANITY_PROJECT_ID }} + SANITY_DATASET: ${{ secrets.SANITY_DATASET }} + SANITY_API_TOKEN: ${{ secrets.SANITY_API_TOKEN }} + MCP_USER_ROLE: ${{ secrets.MCP_USER_ROLE }} + + steps: + - uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + + - name: Install Sanity CLI + run: | + npm install -g @sanity/cli + echo "✅ Sanity CLI installed" + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Validate Schema Structure + run: | + echo "🔍 Validating schema structure..." + cn --config continuedev/sanity-agent-config \ + -p "Analyze the Sanity schema for any structural issues, + missing required fields, or broken references between document types." \ + --auto + + - name: Check Content Integrity + run: | + echo "📊 Checking content integrity..." + cn --config continuedev/sanity-agent-config \ + -p "Run GROQ queries to identify any orphaned documents, + broken references, or missing required fields in the content." \ + --auto + + - name: Generate Schema Documentation + run: | + echo "📝 Generating schema documentation..." + cn --config continuedev/sanity-agent-config \ + -p "Generate a markdown summary of all schema changes + in this PR and their potential impact on existing content." \ + --auto > schema-changes.md + + - name: Comment Report on PR + if: always() && github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPORT=$(cn --config continuedev/sanity-agent-config \ + -p "Generate a concise summary (200 words or less) of: + - Schema validation results + - Content integrity checks + - Any breaking changes detected + - Recommended actions before merging" \ + --auto) + + gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT" +``` + + + Environment variables enable the MCP to authenticate without OAuth browser prompts. The [Sanity MCP Config](https://hub.continue.dev/sanity/sanity-mcp-config) documentation provides detailed setup instructions for all required variables. + + +## Content Management Best Practices + +Implement automated content quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips. + + + ```bash + "Before deploying schema changes, validate that all required fields + are present and that no breaking changes affect existing content." + ``` + + + + ```bash + "When creating new content types, ensure they follow the existing + naming conventions and field patterns established in the schema." + ``` + + + + ```bash + "Review GROQ queries for performance issues and suggest indexes + or query restructuring to improve response times." + ``` + + + + ```bash + "Ensure all user-facing content fields have proper localization + support configured for the required languages." + ``` + + +## Troubleshooting + +### Authentication Issues + +```bash +"Check if I'm properly authenticated with Sanity. +If not, help me set up OAuth or API token authentication." +``` + +### Schema Not Found + +```bash +"Verify that the Sanity project is properly configured +and that the schema files are accessible in the current directory." +``` + +### GROQ Query Errors + +```bash +"Debug this GROQ query and explain why it's failing, +then provide a corrected version that achieves the intended result." +``` + +### Migration Conflicts + + + **Verification Steps:** + - Sanity MCP is installed via [Continue Hub](https://hub.continue.dev/sanity/sanity-mcp) + - Project is authenticated with Sanity + - Schema files are present and valid + - Dataset permissions are correctly configured + + +## What You've Built + +After completing this guide, you have a complete **AI-powered content management system** that: + +- ✅ Uses natural language — Simple prompts instead of complex CMS commands +- ✅ Manages schemas automatically — AI handles schema evolution and migrations +- ✅ Runs continuously — Automated validation in CI/CD pipelines +- ✅ Ensures quality — Content checks prevent broken references and invalid data + + + Your content management workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine content operations and schema management with human oversight + through review and approval of changes. + + +## Next Steps + +1. **Explore your schema** - Try the schema exploration prompt on your current project +2. **Run GROQ queries** - Use natural language to query your content +3. **Set up CI validation** - Add the GitHub Actions workflow to your repo +4. **Create documentation** - Generate comprehensive docs for your content model +5. **Optimize performance** - Analyze and improve query performance + +## Additional Resources + + + + Complete Sanity platform documentation + + + Explore more MCP integrations and agents + + + Learn GROQ query language + + + Official Sanity MCP introduction with examples + + + Official Sanity MCP documentation + + \ No newline at end of file diff --git a/docs/guides/sentry-mcp-error-monitoring.mdx b/docs/guides/sentry-mcp-error-monitoring.mdx new file mode 100644 index 000000000..bcbe81f9c --- /dev/null +++ b/docs/guides/sentry-mcp-error-monitoring.mdx @@ -0,0 +1,534 @@ +--- +title: "Automated Error Analysis with Sentry MCP" +description: "Build an AI-powered error monitoring workflow that analyzes Sentry issues, identifies patterns, and creates actionable GitHub issues automatically." +sidebarTitle: "Sentry Automated Error Analysis with MCP" +--- + + + An automated error monitoring system that uses Continue CLI with Sentry MCP to analyze production errors, identify root causes with AI, and create detailed GitHub issues with suggested fixes. + + +## What You'll Learn + +This cookbook teaches you to: + +- Use [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) to access [issues](https://docs.sentry.io/product/issues/) +- Analyze error patterns and stack traces with AI + +- Automatically create GitHub issues with root cause analysis +- Set up continuous error monitoring with GitHub Actions + +## Prerequisites + +Before starting, ensure you have: + +- GitHub repository where you want to create issues +- [Sentry account](https://sentry.io) with an active project collecting errors +- Node.js 18+ installed locally +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- [GitHub CLI](https://cli.github.com/) installed (`gh` command) + + + + ```bash + npm i -g @continuedev/cli + ``` + + + + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) + 2. Sign up or log in to your Continue account + 3. Navigate to your organization settings + 4. Click **"API Keys"** and then **"+ New API Key"** + 5. Copy the API key immediately (you won't see it again!) + 6. Login to the CLI: `cn login` + + + + + Continue CLI handles complex error analysis and API interactions - you just need to provide the right prompts! + + +## Step 1: Set Up Your Credentials + +First, you'll need to gather your Sentry and GitHub API credentials. + + + + + + See [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) for detailed configuration options + + + The Sentry MCP supports multiple configuration methods. For Continue CLI, OAuth is recommended: + + **Option 1: OAuth Configuration (Recommended)** + + The Sentry MCP will prompt for OAuth authentication when first used. Simply follow the authorization flow. + + **Option 2: STDIO Mode with Auth Token** + + For local development or self-hosted Sentry installations, you can use STDIO mode: + ```bash + npx @sentry/mcp-server@latest --access-token=YOUR_SENTRY_TOKEN --host=sentry.io + ``` + + Or use environment variables: + ```bash + SENTRY_ACCESS_TOKEN=your-token SENTRY_HOST=sentry.io + ``` + + + The `--host` parameter is required and should point to your Sentry instance (e.g., `sentry.io` or `sentry.example.com` for self-hosted). + + + + + You'll need a **Sentry User Auth Token** to access issues and error data: + + 1. Go to [User Auth Tokens](https://sentry.io/settings/account/api/auth-tokens/) in Sentry + - For self-hosted Sentry, use: `https://YOUR-SENTRY-DOMAIN/settings/account/api/auth-tokens/` + 2. Click **Create New Token** + 3. Name it "Continue CLI Error Analysis" + 4. **Select these permission scopes** (required for full functionality): + - `org:read` - **Required** - Access organization information + - `project:read` - **Required** - Read project configurations + - `project:releases` - **Required** - Access release information for deployment tracking + - `event:read` - **Required** - Read detailed error event data and stack traces + - `event:write` - Optional - Update error events (for marking as resolved) + - `member:read` - Recommended - Read team member information for auto-assignment + - `team:read` - Recommended - Access team data for routing issues + 5. Copy the token immediately (you won't see it again!) + 6. Note your organization slug (found in your Sentry URL: `https://sentry.io/organizations/YOUR-ORG-SLUG`) + 7. Note your Sentry host URL (typically `https://sentry.io` or your self-hosted domain) + + + **Sentry MCP Connection**: The MCP server connects via OAuth to `https://mcp.sentry.dev/mcp` and handles authentication securely. For local development, you can use STDIO mode with your auth token. + + + + + GitHub CLI handles authentication automatically - no manual PAT needed: + + 1. Install GitHub CLI if not already installed + 2. Run `gh auth login` and follow the prompts + 3. Choose authentication method (browser or token) + 4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues) + + + +## Sentry Error Monitoring Workflow Options + + + Skip the manual setup and use our pre-built Sentry Continuous AI agent that includes + optimized prompts, rules, and the Sentry MCP for more consistent results. + + + + **How Sentry MCP Works**: + - Connects to your Sentry organization via OAuth + - Provides tools for accessing issues, projects, teams, and DSNs + - Supports both hosted (`https://mcp.sentry.dev`) and self-hosted Sentry instances + - Automatically handles authentication and API interactions + + + + + **Perfect for:** Immediate error analysis with AI-powered root cause detection and built-in debugging + + + + Visit the [Sentry Continuous AI Agent](https://hub.continue.dev/continuedev/sentry-continuous-ai) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/sentry-continuous-ai + ``` + + This agent includes: + - **Optimized prompts** for Sentry error analysis and GitHub issue creation + - **Built-in rules** for consistent formatting and error handling + - **[Sentry MCP](https://docs.sentry.io/product/sentry-mcp/)** for more reliable API interactions + - **Automatic authentication** via OAuth flow + + + + Navigate to your project directory and enter this prompt in the Continue CLI TUI: + + ``` + Analyze recent Sentry errors and create GitHub issues for critical bugs with suggested fixes + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Sentry MCP integration and pre-tested prompts. + + + + + + + + Configure the [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) using OAuth: + + The MCP server will automatically prompt for OAuth authentication when you first use it. + + + + Test your Sentry MCP connection with this prompt: + + ``` + List my Sentry organizations and projects + ``` + + + + Use this prompt template with Continue CLI to analyze Sentry errors: + + ``` + Analyze Sentry errors from the past 24 hours: + - Group errors by root cause + - Identify the top 5 most critical issues by frequency and impact + - For each critical issue, provide: + * Stack trace analysis + * Affected user count + * First seen and last seen timestamps + * Suggested fix based on error context + - Create GitHub issues using gh CLI with: + * Title format: '🐛 [Sentry] [Error Type]: Brief description' + * Labels: 'bug', 'sentry', 'production' + * Priority labels based on severity + * Full error context and suggested fix in the body + Execute the commands and confirm each issue was created. + ``` + + + + + + + + **Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be + token-expensive to run. The `gh` CLI is more efficient, requires no API tokens + (authenticated via `gh auth login`), and provides a cleaner command-line + experience. GitHub MCP remains an option if you prefer full MCP integration. + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as Step 1) + + The agent will automatically detect and use your configuration. For Sentry MCP: + - **Sentry account** with at least one project + - **User Auth Token** with appropriate scopes (or OAuth flow) + - The MCP works with both Sentry's hosted service (`sentry.io`) and self-hosted instances + + +--- + + + **Repository Labels Required**: Make sure your GitHub repository has these labels: + - `bug`, `sentry`, `production` + - `critical`, `high-priority`, `medium-priority`, `low-priority` + - `needs-investigation`, `has-fix` + + Create missing labels in your repo at: **Settings → Labels → New label** + + +## Step 2: Analyze Sentry Errors with AI + +Use Continue CLI to perform intelligent error analysis. Enter these prompts in the Continue CLI TUI: + + + + **Prompt:** + ``` + Show me Sentry errors from the past 7 days, grouped by error type, with frequency counts + ``` + + + + **Prompt:** + ``` + Find the most critical Sentry error affecting the most users in production and provide: + - Full stack trace analysis + - Affected user count and browser/OS breakdown + - Timeline of when the error started occurring + - Similar historical issues from Sentry + - Root cause hypothesis based on code context + - Suggested fix with code examples + ``` + + + + **Prompt:** + ``` + Analyze Sentry performance data to identify: + - Slowest transactions in the past 24 hours + - Database queries with high latency + - API endpoints with degraded performance + - Suggested optimizations for each issue + ``` + + + + + **Available Sentry MCP Tools**: + - **Organizations**: Access org-level data and settings + - **Projects**: Query projects and their configurations + - **Issues**: Search and analyze error issues + - **Teams**: Manage team assignments + - **DSNs**: Retrieve project DSN configurations + + + +## Step 3: Automate GitHub Issue Creation + +Create actionable GitHub issues from Sentry errors. Enter this prompt in the Continue CLI TUI: + +**Prompt:** +``` +For each unresolved Sentry error with 'critical' or 'high' severity: +1. Analyze the error using Sentry MCP +2. Create a GitHub issue with gh CLI: + - Title: '🐛 [Sentry] [Error Type]: Brief description' + - Body with: + * Error summary and impact (affected users, frequency) + * Full stack trace + * Environment details (browser, OS, release version) + * Link to Sentry issue + * Root cause analysis from AI + * Suggested fix with code snippets + * Related Sentry issues + - Labels: 'bug', 'sentry', 'production', and severity label + - Assignees: Team member based on code ownership +3. Update Sentry issue with GitHub issue link +4. Confirm creation with GitHub issue URL +``` + + + **Best Practice**: Link GitHub issues back to Sentry for full traceability. This creates a bidirectional connection between your error monitoring and issue tracking. + + +## Step 4: Set Up Continuous Monitoring with GitHub Actions + +Automate error monitoring with the [Sentry Release GitHub Action](https://docs.sentry.io/product/releases/setup/release-automation/github-actions/) and Continue CLI to create comprehensive, AI-powered issue descriptions: + + + **Why Combine Sentry Releases with Continue CLI?** + - **Release Tracking**: Associate errors with specific deployments + - **AI-Powered Analysis**: Continue CLI generates detailed issue descriptions with root cause analysis + - **Better Context**: Link errors to commits and pull requests + - **Automated Workflows**: Create issues with full stack traces and suggested fixes + + +```yaml +name: Sentry Error Monitoring + +on: + push: + branches: + - main + schedule: + # Run every 6 hours + - cron: "0 */6 * * *" + workflow_dispatch: # Allow manual triggers + +jobs: + monitor-errors: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + # Create Sentry release for better error tracking + - name: Create Sentry release + uses: getsentry/action-release@v1 + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + with: + environment: production + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Authenticate GitHub CLI + run: | + echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token + echo "✅ GitHub CLI authenticated" + + - name: Analyze Sentry Errors and Create Issues + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + run: | + echo "🔍 Analyzing Sentry errors..." + + # Use Continue CLI to analyze errors and generate comprehensive issue descriptions + cn -p "Using Sentry MCP, analyze errors from the past 6 hours for project $SENTRY_PROJECT: + 1. Filter for unresolved errors with high or critical severity + 2. Group similar errors to avoid duplicates + 3. For each unique critical error: + - Generate a comprehensive issue description including: + * Error summary with frequency and user impact metrics + * Full stack trace with highlighted problem areas + * Environment details (browser, OS, release version) + * Link to Sentry issue dashboard + * Root cause analysis using AI + * Step-by-step reproduction if available + * Suggested fix with code examples + * Related errors or patterns + - Check if a GitHub issue already exists for this error + - If not, create a new issue with the generated description + - Use gh CLI: gh issue create --title '[Sentry] [Error Type]: Brief description' --body 'AI-generated comprehensive analysis' --label 'bug,sentry,critical,needs-investigation' + - Link the GitHub issue back to Sentry + 4. Generate a summary report with: + - Total errors analyzed + - New issues created with URLs + - Errors skipped (already tracked) + - Release correlation if available + + Sentry Organization: $SENTRY_ORG + Project: $SENTRY_PROJECT + Only process errors not already tracked in GitHub." + + - name: Post workflow summary + if: always() + run: | + echo "## 📊 Sentry Error Monitoring Summary" >> $GITHUB_STEP_SUMMARY + echo "✅ Workflow completed at $(date)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Check the 'Analyze Sentry Errors' step above for:" >> $GITHUB_STEP_SUMMARY + echo "- Number of errors analyzed" >> $GITHUB_STEP_SUMMARY + echo "- GitHub issues created" >> $GITHUB_STEP_SUMMARY + echo "- Errors already tracked" >> $GITHUB_STEP_SUMMARY +``` + + + **Required GitHub Secrets**: + - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + - `SENTRY_AUTH_TOKEN`: Your Sentry User Auth Token (needs scopes: `org:read`, `project:read`, `project:releases`, `event:read`) + - `SENTRY_ORG`: Your Sentry organization slug + - `SENTRY_PROJECT`: Your Sentry project slug + - `GITHUB_TOKEN`: Automatically provided by GitHub Actions + + Add these at: **Repository Settings → Secrets and variables → Actions** + + + + **Workflow Best Practices**: + - Run every 6 hours to catch critical errors quickly + - Create Sentry releases on push to track error-to-deployment correlation + - Use Continue CLI to generate comprehensive, AI-powered issue descriptions + - Use duplicate detection to avoid creating multiple issues for the same error + - Filter by severity to focus on high-impact issues + - Include full error context and suggested fixes in issues + - Tag issues with appropriate labels for team routing + - Link GitHub issues back to Sentry for bidirectional tracking + + +## What You've Built + +After completing this guide, you have a complete **Sentry-powered error monitoring system** that: + +- **Monitors production errors** - Automatically fetches and analyzes Sentry issues every 6 hours + +- **Identifies critical bugs** - Uses AI to spot high-impact errors + +- **Creates actionable tasks** - Generates GitHub issues with root cause analysis and suggested fixes + +- **Runs autonomously** - Operates continuously without manual intervention using GitHub Actions + +- **Scales with your app** - Handles growing error volumes and complexity automatically + + + Your system now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine error analysis with human oversight through GitHub issue review and resolution. + + +## Advanced Error Analysis Prompts + +Enhance your workflow with these advanced Continue CLI prompts: + + + + Compare error rates before and after the latest [Sentry release](https://docs.sentry.io/product/releases/) to identify regressions introduced in the deployment + + + Analyze Sentry error trends over the past 30 days and identify emerging issues before they become critical + + + Identify which errors are affecting the most unique users and prioritize fixes based on user impact + + + Cross-reference Sentry [performance issues](https://docs.sentry.io/product/performance/) with error spikes to identify root causes + + + +## Security Best Practices + + + **Protect Your API Keys**: + - Store all credentials as GitHub Secrets, never in code + - Use Continue CLI's secure secret storage + - Limit Sentry token scopes to minimum required permissions + - Rotate API keys regularly (every 90 days recommended) + - Monitor token usage for unusual activity + - Use OAuth when possible for better security + + +## Troubleshooting + +### Sentry MCP Connection Issues + +If you encounter connection issues: + +1. Verify OAuth authentication is complete +2. Check your Sentry organization access +3. Ensure the MCP server URL is correct (`https://mcp.sentry.dev/mcp`) +4. For self-hosted Sentry, verify your host URL is configured correctly + +See the [Sentry MCP GitHub Issues](https://github.com/getsentry/sentry-mcp/issues) for known issues and solutions. + +### Common Error Analysis Issues + +| Issue | Solution | +|:------|:---------| +| No errors returned | Verify your Sentry project has collected errors recently | +| OAuth prompt not appearing | Check that Continue CLI has proper MCP configuration | +| Duplicate GitHub issues | Implement duplicate detection in your prompts | +| Missing error context | Ensure your Sentry token has `event:read` scope | + +## Next Steps + + +- Set up [Sentry performance monitoring](https://docs.sentry.io/product/performance/) +- Configure [Sentry release tracking](https://docs.sentry.io/product/releases/) for deployment correlation +- Integrate [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for error alerts +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) +- [Sentry API Documentation](https://docs.sentry.io/api/) +- [Sentry Issues Guide](https://docs.sentry.io/product/issues/) +- [Sentry Performance Monitoring](https://docs.sentry.io/product/performance/) +- [Sentry Release Tracking](https://docs.sentry.io/product/releases/) + +- [Sentry MCP GitHub Repository](https://github.com/getsentry/sentry-mcp) +- [GitHub CLI Documentation](https://cli.github.com/) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx index 709cfd604..cd45ac71e 100644 --- a/docs/guides/snyk-mcp-continue-cookbook.mdx +++ b/docs/guides/snyk-mcp-continue-cookbook.mdx @@ -33,8 +33,18 @@ For all options, first: 1. Sign up for a Snyk account at [snyk.io](https://snyk.io/) 2. Create a new project in Snyk by importing your code repository (Git provider or manual upload) + 3. Install and authenticate the Snyk CLI locally: + ```bash + npm install -g snyk + snyk auth + ``` + This will open your browser to authenticate with your Snyk account. + + + **Important**: The Snyk MCP requires the Snyk CLI to be authenticated locally. Run `snyk auth` to authenticate before using the Continue agent with Snyk MCP. + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). @@ -64,10 +74,10 @@ After ensuring you meet the **Prerequisites** above, you have two paths to get s - Start with a comprehensive security scan: + From your project directory, start with a comprehensive security scan: ```bash - # TUI mode - cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." + # Headless mode + cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto ``` That's it! The agent handles everything automatically. @@ -159,7 +169,7 @@ You can add prompts to your agent's configuration for easy access in future sess **Where to run these workflows:** - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts - - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for headless commands **Test in Plan Mode First**: Before running security scans that might make changes, test your prompts in plan mode (see the [Plan Mode @@ -182,7 +192,7 @@ and rerun to verify. **Headless Mode Prompt:** ```bash -cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." +cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify." --auto ``` @@ -201,7 +211,7 @@ Re-test after the plan (dry run). **Headless Mode Prompt:** ```bash -cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." +cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)." --auto ``` @@ -219,7 +229,7 @@ with exact files/lines. Provide code changes and re-scan to confirm. **Headless Mode Prompt:** ```bash -cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." +cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm." --auto ``` @@ -238,7 +248,7 @@ Re-test after the change (dry run). **Headless Mode Prompt:** ```bash -cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." +cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)." --auto ``` @@ -256,7 +266,7 @@ Block if new high issues would be introduced. Show deltas. **Headless Mode Prompt:** ```bash -cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." +cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas." --auto ``` @@ -273,35 +283,38 @@ Open Snyk Learn lessons related to the top CWE(s) from this scan. **Headless Mode Prompt:** ```bash -cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." +cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto ``` ## Continuous Security with GitHub Actions -This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline Headless Mode Prompt in headless mode (`cn -p`) with Snyk MCP. +This example demonstrates a **Continuous AI workflow** where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments. + + + + **About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like security scanning, vulnerability analysis, and fix validation. + + ### Add GitHub Secrets Navigate to **Repository Settings → Secrets and variables → Actions** and add: - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `SNYK_TOKEN`: Your Snyk authentication token from [app.snyk.io/account](https://app.snyk.io/account) ### Create Workflow File Create `.github/workflows/snyk-security.yml` in your repository: ```yaml -name: Security Scanning with Snyk MCP +name: Snyk Security Scanning on: pull_request: branches: [main] - push: - branches: [main] - schedule: - - cron: "0 8 * * *" # Daily at 8 AM UTC jobs: security-scan: @@ -309,55 +322,259 @@ jobs: steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetch all history for git diff + + - name: Get Changed Files + id: changed-files + run: | + echo "📝 Getting changed files since main branch..." + CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ') + echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT + echo "Changed files: $CHANGED_FILES" - name: Set up Node.js uses: actions/setup-node@v4 with: - node-version: "18" + node-version: '18' + + - name: Install Snyk CLI + run: | + npm install -g snyk + echo "✅ Snyk CLI installed" - name: Install Continue CLI run: | npm install -g @continuedev/cli echo "✅ Continue CLI installed" - - name: Authenticate Continue CLI - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + - name: Validate Secrets run: | - cn auth login --api-key "$CONTINUE_API_KEY" - echo "✅ Continue CLI authenticated" + if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then + echo "❌ Error: SNYK_TOKEN secret is not set" + exit 1 + fi + if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then + echo "⚠️ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped" + fi + echo "✅ Required secrets validated" + + - name: Authenticate Snyk + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + run: | + snyk auth "$SNYK_TOKEN" + echo "✅ Snyk authenticated" - name: Run Security Scans + id: security-scan + continue-on-error: true + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }} run: | - echo "🔍 Running code vulnerability scan..." - cn -p "Run Snyk Code scan with severity high on this repo. - Fail if any high issues are present." + SCAN_FAILED=0 + + if [ -n "$CHANGED_FILES" ]; then + echo "🔍 Running targeted scan on changed files..." + echo "Changed files: $CHANGED_FILES" + FILE_ARGS="" + for file in $CHANGED_FILES; do + if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then + FILE_ARGS="$FILE_ARGS --file=$file" + fi + done + + if [ -n "$FILE_ARGS" ]; then + echo "🔍 Running Snyk Code scan on changed files..." + snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || { + echo "❌ Snyk Code found high severity issues in changed files" + SCAN_FAILED=1 + } + else + echo "⚠️ No scannable code files changed, skipping Snyk Code scan" + echo '{"runs": [{"results": []}]}' > snyk-code-results.json + fi + else + echo "⚠️ No changed files detected, creating empty results" + echo '{"runs": [{"results": []}]}' > snyk-code-results.json + fi echo "📦 Checking dependencies..." - cn -p "Run Snyk Open Source on this repo. - Fail on fixable high issues." + snyk test --severity-threshold=high --json > snyk-oss-results.json || { + echo "❌ Snyk Open Source found high severity issues" + SCAN_FAILED=1 + } + + if [ $SCAN_FAILED -eq 1 ]; then + echo "scan_status=failed" >> $GITHUB_OUTPUT + echo "⚠️ Scans completed with issues - continuing to generate mitigation suggestions" + else + echo "scan_status=passed" >> $GITHUB_OUTPUT + echo "✅ All security scans passed" + fi + + - name: Generate AI Mitigation Suggestions + if: always() && steps.security-scan.outputs.scan_status == 'failed' + continue-on-error: true + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + run: | + echo "🤖 Generating AI-powered mitigation suggestions..." + + # Create a summary of findings for Continue CLI + FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r ' + if .runs then + .runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))" + elif .vulnerabilities then + .vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))" + else + empty + end + ' | head -20) + + if [ -n "$FINDINGS_SUMMARY" ]; then + echo "📋 Security findings to analyze:" + echo "$FINDINGS_SUMMARY" + echo "" + + # Use Continue CLI to generate mitigation suggestions + PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations." + + cn --config continuedev/snyk-continuous-ai -p "$PROMPT" --auto > mitigation-suggestions.md || { + echo "⚠️ Warning: Could not generate AI suggestions" + exit 0 + } + + if [ -f mitigation-suggestions.md ]; then + echo "✅ AI mitigation suggestions generated" + echo "" + echo "--- Mitigation Suggestions ---" + cat mitigation-suggestions.md + fi + else + echo "⚠️ No findings to analyze" + fi + + - name: Post Mitigation Summary to PR + if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != '' + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + run: | + if [ -f mitigation-suggestions.md ]; then + echo "💬 Posting mitigation summary to PR..." + + # Create PR comment with mitigation suggestions + cat > pr-comment.md <<'EOF' + ## 🛡️ Snyk Mitigation Summary + + Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations: + + EOF + + cat mitigation-suggestions.md >> pr-comment.md + + cat >> pr-comment.md < scan-results.md + + if [ -f scan-results.md ]; then + echo "✅ Security report generated successfully" + cat scan-results.md + else + echo "⚠️ Warning: scan-results.md was not created" + fi - name: Upload Security Report - uses: actions/upload-artifact@v4 if: always() + continue-on-error: true + uses: actions/upload-artifact@v4 with: - name: security-report-${{ github.run_number }} - path: security-report.md - retention-days: 30 + name: security-scan-results + path: | + scan-results.md + snyk-code-results.json + snyk-oss-results.json + mitigation-suggestions.md + if-no-files-found: warn + + - name: Fail if Security Issues Found + if: steps.security-scan.outputs.scan_status == 'failed' + run: | + echo "❌ Security scan failed - high severity issues found" + echo "📋 Review the security report artifact for details and mitigation suggestions" + exit 1 ``` - The Snyk MCP authentication is handled through Continue Hub. No need to manage - Snyk tokens directly in CI - the agent manages authentication. + **About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways: + 1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans + 2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions + + The `cn` agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations. + + + + This workflow demonstrates several advanced features: + - **Changed Files Detection**: Only scans files modified in the PR + - **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps + - **PR Comments**: Automatically posts mitigation suggestions as PR comments + - **Comprehensive Reporting**: Generates detailed security reports with artifacts ## Security Guardrails @@ -432,10 +649,10 @@ then rerun the same Snyk scan to confirm resolution." After completing this guide, you have a complete **AI-powered security system** that: -✅ Uses natural language — Simple prompts instead of complex CLI commands -✅ Fixes automatically — AI suggests and validates security fixes -✅ Runs continuously — Automated scanning in CI/CD pipelines -✅ Enforces guardrails — Security rules prevent vulnerable code from shipping +- ✅ Uses natural language — Simple prompts instead of complex CLI commands +- ✅ Fixes automatically — AI suggests and validates security fixes +- ✅ Runs continuously — Automated scanning in CI/CD pipelines +- ✅ Enforces guardrails — Security rules prevent vulnerable code from shipping Your security workflow now operates at **[Level 2 Continuous diff --git a/docs/hub/workflows/intro.mdx b/docs/hub/workflows/intro.mdx new file mode 100644 index 000000000..1c5fd3d5b --- /dev/null +++ b/docs/hub/workflows/intro.mdx @@ -0,0 +1,97 @@ +--- +title: "Introduction" +description: "Run Continuous AI workflows in the background" +--- + + + Workflows are in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051). + + +Workflows are a way to run and manage background agents in Continue. You can use them for: +- Addressing small nitpicks and bugs +- Building boilerplate-heavy features +- Investigating an issue to kickstart your work +- [Automated security scanning](../../guides/snyk-mcp-continue-cookbook) +- Running repeatable tasks with your own rules, prompts, and MCP servers +- Much more! + +## Quickstart + +To run your first workflow + +1. Go to [hub.continue.dev/agents](https://hub.continue.dev/agents) + +![Agent Setup](/images/hub/workflows/images/workflows-setup.png) + +2. Connect with your GitHub account +3. Enter the prompt for your agent + +## Example Workflow Tasks + +Here are some example tasks you can try with your workflows: + + + + + - "Fix the TypeError in api/users.ts where the user object might be undefined" + - "Add null checks to all database query results in the services/ directory" + - "Fix all ESLint warnings in the components folder" + - "Update deprecated React lifecycle methods to hooks in legacy components" + + + + + + - "Create a new REST endpoint for user profile updates with validation and error handling" + - "Add pagination to the products list page with previous/next buttons" + - "Implement dark mode toggle using Tailwind CSS classes across all pages" + - "Add unit tests for the authentication service using Jest" + + + + + + - "Scan the codebase for hardcoded API keys and move them to environment variables" + - "Add input sanitization to all user-facing form fields" + - "Update all npm packages with known security vulnerabilities" + - "Implement rate limiting on the /api/login endpoint" + + + + + + - "Add JSDoc comments to all exported functions in the utils/ directory" + - "Create a README.md for the new payment-processing module with setup instructions" + - "Generate TypeScript interfaces for all API response schemas" + - "Add error handling boilerplate to all async functions missing try-catch blocks" + + + + + + - "Investigate why the login API is returning 500 errors intermittently and suggest fixes" + - "Analyze the performance bottleneck in the data processing pipeline" + - "Review the database schema for the orders table and suggest optimizations" + - "Find all TODO comments related to authentication and create a summary" + + + + + + - "Extract the repeated validation logic in controllers into a shared utility function" + - "Convert all class components in src/legacy to functional components with hooks" + - "Rename all instances of 'userId' to 'accountId' across the codebase" + - "Split the 500-line UserService.ts into smaller, single-responsibility services" + + + + +## How to use background agents + +The practice of using background agents, which we call Continuous AI, requires practice and forethought to set up the right guiderails and habits to fit your development workflow, much like learning to work with a larger engineering team. We are constantly sharing our learnings on the [Continuous AI Blog](https://blog.continue.dev), but these few high-level tips are a great way to quickly become successful with workflows: + +- Practice first with the [Continue CLI](../../guides/cli) in "TUI mode". The same agent that powers our CLI is used for workflows, so you can easily test your prompts locally. +- Identify and begin with tasks that you are confident can be accomplished by Continue. For example, ask Continue to fix a small bug where you already know the solution is simple. +- Once you have merged a PR created by Continue, be increasingly ambitious with your tasks. By being willing to start tasks that might not succeed on the first try, you will learn about prompting best practices and limitations of current language models. +- Use thorough prompts. Workflows can run for a long time to complete their task, so it is worthwhile to invest in sharing all of the important details. +- Discuss the use of workflows with your team. Truly embracing Continuous AI likely means acknowledging that a higher volume of PRs will be created and adjusting your code review habits. diff --git a/docs/images/assistant-selector-dropdown.png b/docs/images/assistant-selector-dropdown.png new file mode 100644 index 000000000..9b4b69f3e Binary files /dev/null and b/docs/images/assistant-selector-dropdown.png differ diff --git a/docs/images/autocomplete-model-selection.png b/docs/images/autocomplete-model-selection.png new file mode 100644 index 000000000..530b30a63 Binary files /dev/null and b/docs/images/autocomplete-model-selection.png differ diff --git a/docs/images/autocomplete-settings.png b/docs/images/autocomplete-settings.png new file mode 100644 index 000000000..fa3fe2fd6 Binary files /dev/null and b/docs/images/autocomplete-settings.png differ diff --git a/docs/images/continue-settings-card-layout.png b/docs/images/continue-settings-card-layout.png new file mode 100644 index 000000000..4fc8c6d8b Binary files /dev/null and b/docs/images/continue-settings-card-layout.png differ diff --git a/docs/images/hub/workflows/images/workflows-setup.png b/docs/images/hub/workflows/images/workflows-setup.png new file mode 100644 index 000000000..05419e84d Binary files /dev/null and b/docs/images/hub/workflows/images/workflows-setup.png differ diff --git a/docs/images/indexing-settings.png b/docs/images/indexing-settings.png new file mode 100644 index 000000000..1b4cb9be6 Binary files /dev/null and b/docs/images/indexing-settings.png differ diff --git a/docs/telemetry.mdx b/docs/telemetry.mdx index dba2dc6d5..f71255f0d 100644 --- a/docs/telemetry.mdx +++ b/docs/telemetry.mdx @@ -26,6 +26,25 @@ The following usage information is collected and reported: ## How to Opt Out +### IDE extensions + You can disable anonymous telemetry by toggling "Allow Anonymous Telemetry" off in the user settings. +#### VS Code + Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut `ctrl` + `,` on Windows/Linux or `cmd` + `,` on macOS). + +### CLI + +For `cn`, the Continue CLI, set the environment variable `CONTINUE_CLI_ENABLE_TELEMETRY=0` before running commands: + +```bash +export CONTINUE_CLI_ENABLE_TELEMETRY=0 +cn +``` + +Or run it inline: + +```bash +CONTINUE_CLI_ENABLE_TELEMETRY=0 cn +``` diff --git a/extensions/cli/.gitignore b/extensions/cli/.gitignore index dc3410527..f3e655274 100644 --- a/extensions/cli/.gitignore +++ b/extensions/cli/.gitignore @@ -11,3 +11,6 @@ chat.log config.yaml .continue-debug/ + +*.expect +!demo.expect \ No newline at end of file diff --git a/extensions/cli/BUILD.md b/extensions/cli/BUILD.md index 553660f94..ae805a800 100644 --- a/extensions/cli/BUILD.md +++ b/extensions/cli/BUILD.md @@ -6,8 +6,9 @@ The Continue CLI uses esbuild to bundle the application along with local package ## Build Steps -1. **Install dependencies**: `npm install` -2. **Build**: `npm run build` +1. **Build packages**: `cd ../../ && node ./scripts/build-packages.js` +2. **Install dependencies**: `npm install` +3. **Build**: `npm run build` - This first builds the local packages - Then bundles everything with esbuild diff --git a/extensions/cli/demo.expect b/extensions/cli/demo.expect new file mode 100644 index 000000000..e762df796 --- /dev/null +++ b/extensions/cli/demo.expect @@ -0,0 +1,36 @@ +#!/usr/bin/expect -f +# Automated demo script for Continue TUI + +set timeout 30 +log_user 1 + +# Set terminal environment for better TUI rendering +set env(TERM) "xterm-256color" + +# Spawn cn directly inside an asciinema recording session +spawn bash -c "asciinema rec --overwrite demo.cast -c 'npm run start'" + +# Wait for TUI to load +sleep 5 + +# Demo interaction 1: Show help +send "?" +sleep 3 + +# Demo interaction 2: Close help +send "?" +sleep 2 + +# Demo interaction 3: Type a message +send "Hello, this is a demo!" +sleep 1 + +# Submit the message +send "\r" +sleep 3 + +# Exit the application with Ctrl+C +send "\x03" +sleep 1 + +expect eof diff --git a/extensions/cli/spec/modes.md b/extensions/cli/spec/modes.md index 7296a19eb..49838a3b3 100644 --- a/extensions/cli/spec/modes.md +++ b/extensions/cli/spec/modes.md @@ -57,8 +57,7 @@ Users can switch modes during chat sessions using: Modes are implemented through the permission system: -- **ModeService**: Singleton service managing the current mode and initialization -- **ToolPermissionService**: Extended to support mode-specific policies with highest priority +- **ToolPermissionService**: Rectifies current mode and tool policies - **ModeIndicator**: UI component showing current mode (hidden for normal mode) - **Keyboard shortcuts**: Shift+Tab cycles through modes instantly - **Backward compatibility**: Existing `--readonly` flag maps to plan mode diff --git a/extensions/cli/spec/shell-mode.md b/extensions/cli/spec/shell-mode.md index a3bdd6cf4..06ad477e9 100644 --- a/extensions/cli/spec/shell-mode.md +++ b/extensions/cli/spec/shell-mode.md @@ -1,73 +1,4 @@ -shell Mode (CLI TUI) - -Overview - -- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!). -- It is intended for quick terminal command execution without leaving the TUI. - -Activation - -- shell mode is activated when the current input (trimmed) starts with ! - - Example: "!git status" or " !ls -la" both activate shell mode. -- Visual indicator: - - Input border color changes to yellow. - - The input prompt indicator changes to a yellow "$". - - The input placeholder includes "! for shell mode". - -Deactivation / Exiting shell Mode - -- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result. -- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode. -- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior. - -Interaction with other input helpers - -- When in shell mode (input starts with !): - - "@" file search suggestions are disabled. - - "/" slash command UI is disabled. -- When in slash command mode (input starts with /): - - "@" file search suggestions are disabled. - -Submission behavior - -- On submit (Enter) with a shell-mode input: - - The leading ! is removed and the remainder is treated as the shell command to run. - - The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress. - - The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated. - -Execution semantics - -- The command is executed in the same way as terminal tool commands, minus permissions - -Output handling - -- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success. -- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown. -- Output is truncated to the first 5000 lines if exceeded. -- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like: - "[Command timed out after 30 seconds of no output]". - -Keyboard behaviors (summary) - -- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately. -- Shift+Enter: new line. -- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual. -- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context. - -Scope / Modes - -- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing. - -Error handling - -- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available). - -Examples - -- "!git status" → shows a shell tool call immediately, then populates with the git status output. -- "!echo hello" → shows a shell tool call immediately, then output "hello". -- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message. - Shell Mode (CLI TUI) +Shell Mode (CLI TUI) Overview diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts deleted file mode 100644 index f982bdd09..000000000 --- a/extensions/cli/src/__mocks__/args.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { vi } from "vitest"; - -export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); - -export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts index 7ea28d99b..a062ef2a4 100644 --- a/extensions/cli/src/__mocks__/services/index.ts +++ b/extensions/cli/src/__mocks__/services/index.ts @@ -1,3 +1,4 @@ +import { ToolPermissionService } from "src/services/ToolPermissionService.js"; import { vi } from "vitest"; export const services = { @@ -7,14 +8,23 @@ export const services = { switchOrganization: vi.fn(() => Promise.resolve({})), getAvailableOrganizations: vi.fn(() => Promise.resolve([])), }, + toolPermissions: vi.mocked(new ToolPermissionService()), }; export const reloadService = vi.fn(() => Promise.resolve(undefined)); export const SERVICE_NAMES = { AUTH: "auth", - API_CLIENT: "apiClient", CONFIG: "config", MODEL: "model", MCP: "mcp", -}; + API_CLIENT: "apiClient", + TOOL_PERMISSIONS: "toolPermissions", + FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", + UPDATE: "update", + STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", +} as const; diff --git a/extensions/cli/src/args-mcp.test.ts b/extensions/cli/src/args-mcp.test.ts deleted file mode 100644 index 95f77cc7d..000000000 --- a/extensions/cli/src/args-mcp.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { beforeEach, describe, expect, it } from "vitest"; - -import { parseArgs } from "./args.js"; - -describe("parseArgs --mcp flag", () => { - beforeEach(() => { - // Clear process.argv before each test - process.argv = ["node", "test"]; - }); - - it("should parse single MCP from --mcp flag", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should parse multiple MCPs from multiple --mcp flags", () => { - process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]); - }); - - it("should handle MCP flag with other flags", () => { - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "my-org/my-mcp", - "--org", - "test-org", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("my-config.yaml"); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.organizationSlug).toBe("test-org"); - }); - - it("should handle MCP flag with prompt", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.prompt).toBe("hello world"); - }); - - it("should ignore MCP and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "test", - "actual prompt", - "--rule", - "my-rule", - "--mcp", - "my-org/my-mcp", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual prompt"); - expect(result.rules).toEqual(["my-rule"]); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should handle MCP flag without value", () => { - process.argv = ["node", "test", "--mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual([]); - }); - - it("should handle MCP flag at the end without value", () => { - process.argv = ["node", "test", "my prompt", "--mcp"]; - const result = parseArgs(); - expect(result.prompt).toBe("my prompt"); - expect(result.mcps).toEqual([]); - }); -}); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts deleted file mode 100644 index 46b70b4db..000000000 --- a/extensions/cli/src/args.prompt.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, it, expect, beforeEach, afterAll } from "vitest"; - -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("args --prompt flag", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv for each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original process.argv after all tests - process.argv = originalArgv; - }); - - it("should parse single prompt from --prompt flag", () => { - process.argv = ["node", "script.js", "--prompt", "my-prompt"]; - const result = parseArgs(); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should parse multiple prompts from multiple --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt1", - "--prompt", - "prompt2", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt1", "prompt2"]); - }); - - it("should handle mixed flags including --prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "myconfig", - "--prompt", - "myprompt", - "--resume", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("myconfig"); - expect(result.prompts).toEqual(["myprompt"]); - expect(result.resume).toBe(true); - }); - - it("should not include --prompt value in non-flag arguments", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt-value", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt-value"]); - expect(result.prompt).toBe("actual-prompt"); - }); - - it("should handle both --rule and --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "my-rule", - "--prompt", - "my-prompt", - ]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should process direct string content", async () => { - const result = await processPromptOrRule("This is a direct prompt"); - expect(result).toBe("This is a direct prompt"); - }); -}); diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index d22333c05..1b345971c 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,222 +1,6 @@ import { vi } from "vitest"; -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("parseArgs", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv before each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original argv - process.argv = originalArgv; - }); - - it("should return default values when no arguments provided", () => { - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should set resume to true when --resume flag is present", () => { - process.argv = ["node", "script.js", "--resume"]; - const result = parseArgs(); - expect(result.resume).toBe(true); - }); - - it("should set readonly to true when --readonly flag is present", () => { - process.argv = ["node", "script.js", "--readonly"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - }); - - it("should parse config path from --config flag", () => { - process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"]; - const result = parseArgs(); - expect(result.configPath).toBe("/path/to/config.yaml"); - }); - - it("should parse single rule from --rule flag", () => { - process.argv = ["node", "script.js", "--rule", "my-rule"]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should parse multiple rules from multiple --rule flags", () => { - process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"]; - const result = parseArgs(); - expect(result.rules).toEqual(["rule1", "rule2"]); - }); - - it("should parse prompt from last non-flag argument", () => { - process.argv = ["node", "script.js", "Hello world"]; - const result = parseArgs(); - expect(result.prompt).toBe("Hello world"); - }); - - it("should handle multiple flags together", () => { - process.argv = ["node", "script.js", "--print", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result).toEqual({ - readonly: true, - resume: true, - }); - }); - - it("should handle config flag with other flags", () => { - process.argv = ["node", "script.js", "--config", "config.yaml", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - }); - }); - - it("should handle rule flag with other flags", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - }); - }); - - it("should handle prompt with flags", () => { - process.argv = ["node", "script.js", "--print", "What is the weather?"]; - const result = parseArgs(); - expect(result).toEqual({ - prompt: "What is the weather?", - }); - }); - - it("should handle config flag with prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "Test prompt", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - prompt: "Test prompt", - }); - }); - - it("should handle rule flag with prompt", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - prompt: "Test prompt", - }); - }); - - it("should ignore config and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "--rule", - "my-rule", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual-prompt"); - expect(result.configPath).toBe("config.yaml"); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should handle multiple non-flag arguments and use the last one as prompt", () => { - process.argv = ["node", "script.js", "first", "second", "third"]; - const result = parseArgs(); - expect(result.prompt).toBe("third"); - }); - - it("should handle complex argument combinations", () => { - process.argv = [ - "node", - "script.js", - "--print", - "--config", - "my-config.yaml", - "--rule", - "rule1", - "--rule", - "rule2", - "--readonly", - "--resume", - "Complex prompt with spaces", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "my-config.yaml", - rules: ["rule1", "rule2"], - readonly: true, - resume: true, - prompt: "Complex prompt with spaces", - }); - }); - - it("should handle config flag without value", () => { - process.argv = ["node", "script.js", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag without value", () => { - process.argv = ["node", "script.js", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle config flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle empty arguments array", () => { - process.argv = ["node", "script.js"]; - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should handle multiple boolean flags", () => { - process.argv = ["node", "script.js", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - expect(result.resume).toBe(true); - }); - - it("should handle multiple rules with complex combinations", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "file.txt", - "--rule", - "owner/package", - "--rule", - "direct string rule", - ]; - const result = parseArgs(); - expect(result.rules).toEqual([ - "file.txt", - "owner/package", - "direct string rule", - ]); - }); -}); - +import { processRule as processPromptOrRule } from "./hubLoader.js"; describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests const originalFetch = global.fetch; diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts deleted file mode 100644 index b8a452213..000000000 --- a/extensions/cli/src/args.ts +++ /dev/null @@ -1,147 +0,0 @@ -export interface CommandLineArgs { - configPath?: string; - organizationSlug?: string; // Organization slug to use for this session - prompt?: string; // Optional prompt argument - resume?: boolean; // Resume from last session - fork?: string; // Fork from an existing session ID - readonly?: boolean; // Start in plan mode (backward compatibility) - rules?: string[]; // Array of rule specifications - mcps?: string[]; // Array of MCP server slugs from the hub - models?: string[]; // Array of model slugs from the hub - prompts?: string[]; // Array of prompt slugs from the hub - format?: "json"; // Output format for headless mode -} - -// Re-export hub loader functions for backward compatibility -export { loadMcpFromHub, processRule } from "./hubLoader.js"; -// Alias processRule as processPromptOrRule for backward compatibility -export { processRule as processPromptOrRule } from "./hubLoader.js"; - -/** - * Extract values for a specific flag that can appear multiple times - */ -function extractMultipleFlags(args: string[], flagName: string): string[] { - const indices: number[] = []; - for (let i = 0; i < args.length; i++) { - if (args[i] === flagName) { - indices.push(i); - } - } - - const values: string[] = []; - for (const index of indices) { - if (index + 1 < args.length && !args[index + 1].startsWith("--")) { - values.push(args[index + 1]); - } - } - return values; -} - -/** - * Extract value for a single-value flag - */ -function extractSingleFlag( - args: string[], - flagName: string, -): string | undefined { - const index = args.indexOf(flagName); - if ( - index !== -1 && - index + 1 < args.length && - !args[index + 1].startsWith("--") - ) { - return args[index + 1]; - } - return undefined; -} - -/** - * Parse command line arguments for non-permission related flags - * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility. - * @returns Parsed command line arguments - */ -export function parseArgs(): CommandLineArgs { - const args = process.argv.slice(2); - const result: CommandLineArgs = {}; - - // Parse boolean flags - if (args.includes("--resume")) { - result.resume = true; - } - if (args.includes("--readonly")) { - result.readonly = true; - } - - // Parse fork flag - const forkValue = extractSingleFlag(args, "--fork"); - if (forkValue) { - result.fork = forkValue; - } - - // Parse single-value flags - const formatValue = extractSingleFlag(args, "--format"); - if (formatValue === "json") { - result.format = "json"; - } - - result.configPath = extractSingleFlag(args, "--config"); - - const orgValue = extractSingleFlag(args, "--org"); - if (orgValue) { - result.organizationSlug = - orgValue.toLowerCase() === "personal" ? undefined : orgValue; - } - - // Parse multi-value flags - const rules = extractMultipleFlags(args, "--rule"); - if (rules.length > 0) { - result.rules = rules; - } else if (args.includes("--rule")) { - result.rules = []; - } - - const mcps = extractMultipleFlags(args, "--mcp"); - if (mcps.length > 0) { - result.mcps = mcps; - } else if (args.includes("--mcp")) { - // Ensure we have an empty array if --mcp flag is present but has no values - result.mcps = []; - } - - const models = extractMultipleFlags(args, "--model"); - if (models.length > 0) { - result.models = models; - } else if (args.includes("--model")) { - result.models = []; - } - - const prompts = extractMultipleFlags(args, "--prompt"); - if (prompts.length > 0) { - result.prompts = prompts; - } else if (args.includes("--prompt")) { - result.prompts = []; - } - - // Extract prompt from non-flag arguments - const flagsWithValues = [ - "--config", - "--org", - "--rule", - "--mcp", - "--model", - "--prompt", - "--format", - "--fork", - ]; - const nonFlagArgs = args.filter((arg, index) => { - if (arg.startsWith("--") || arg === "-p") return false; - const prevArg = index > 0 ? args[index - 1] : ""; - return !flagsWithValues.includes(prevArg); - }); - - if (nonFlagArgs.length > 0) { - result.prompt = nonFlagArgs[nonFlagArgs.length - 1]; - } - - return result; -} diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts index d110ea161..a005eb56a 100644 --- a/extensions/cli/src/auth/workos.ts +++ b/extensions/cli/src/auth/workos.ts @@ -8,6 +8,7 @@ import nodeFetch from "node-fetch"; import open from "open"; import { getApiClient } from "../config.js"; +// eslint-disable-next-line import/order import { env } from "../env.js"; if (!globalThis.fetch) { globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; @@ -96,13 +97,24 @@ export function getConfigUri(config: AuthConfig): string | null { /** * Gets the model name from any auth config type + * For unauthenticated users or when auth config has no modelName, checks GlobalContext */ export function getModelName(config: AuthConfig): string | null { - if (config === null) return null; - return config.modelName || null; + // Priority 1: Logged-in users with modelName in auth config + if (config !== null && config.modelName) { + return config.modelName; + } + + // Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName) + return getPersistedModelName(); } // URI utility functions have been moved to ./uriUtils.ts +import { + getPersistedModelName, + persistModelName, +} from "../util/modelPersistence.js"; + import { autoSelectOrganizationAndConfig } from "./orgSelection.js"; import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js"; import { @@ -214,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void { /** * Updates the model name in the authentication configuration + * Returns the updated config so the caller can update in-memory state + * For unauthenticated users, saves to GlobalContext */ -export function updateModelName(modelName: string | null): void { +export function updateModelName(modelName: string | null): AuthConfig { // If using CONTINUE_API_KEY environment variable, don't save anything if (process.env.CONTINUE_API_KEY) { - return; + return loadAuthConfig(); } const config = loadAuthConfig(); + + // If logged in, save to auth.json if (config && isAuthenticatedConfig(config)) { const updatedConfig: AuthenticatedConfig = { ...config, modelName: modelName || undefined, }; saveAuthConfig(updatedConfig); + return updatedConfig; } + + // If logged out, save to GlobalContext + persistModelName(modelName); + return config; } /** diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 0d0808ea3..bb32e9a90 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -21,6 +21,8 @@ export interface BaseCommandOptions { ask?: string[]; /** Array of tools to exclude from use (--exclude) */ exclude?: string[]; + /** Workflow slug from the hub (--workflow) */ + workflow?: string; } /** diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index a954e8b34..05332d80e 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -12,7 +12,11 @@ import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; import { initializeServices, services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; -import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + ModelServiceState, + SERVICE_NAMES, + WorkflowServiceState, +} from "../services/types.js"; import { loadSession, updateSessionHistory, @@ -474,9 +478,15 @@ async function runHeadlessMode( const { processAndCombinePrompts } = await import( "../util/promptProcessor.js" ); + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + const initialPrompt = + `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || + undefined; const initialUserInput = await processAndCombinePrompts( options.prompt, - prompt, + initialPrompt, ); let isFirstMessage = true; @@ -532,7 +542,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { if (!options.headless) { // Process flags for TUI mode const { permissionOverrides } = processCommandFlags(options); - // Initialize services with onboarding handled internally await initializeServices({ options, @@ -540,9 +549,17 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { toolPermissionOverrides: permissionOverrides, }); + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + const initialPrompt = + `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || + undefined; + // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { - initialPrompt: prompt, + initialPrompt, resume: options.resume, fork: options.fork, config: options.config, diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index bf19c099f..d9886273e 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -146,7 +146,10 @@ export function getAllSlashCommands( category: "assistant" as const, })) || []; - return [...systemCommands, ...assistantCommands]; + // Get invokable rule commands + const invokableRuleCommands = getInvokableRuleSlashCommands(assistant); + + return [...systemCommands, ...assistantCommands, ...invokableRuleCommands]; } /** @@ -163,3 +166,33 @@ export function getAssistantSlashCommands( })) || [] ); } + +/** + * Get invokable rule commands from assistant config + */ +export function getInvokableRuleSlashCommands( + assistant: AssistantConfig, +): SlashCommand[] { + if (!assistant?.rules) { + return []; + } + + return assistant.rules + .filter((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + // Only include rules with invokable: true + return rule.invokable === true; + }) + .map((rule) => { + // TypeScript now knows rule is an object with invokable: true + const ruleObj = rule as any; + return { + name: ruleObj.name || "", + description: ruleObj.description || "", + category: "assistant" as const, + }; + }); +} diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts index a1c6cc4f8..e5abf3136 100644 --- a/extensions/cli/src/commands/login.ts +++ b/extensions/cli/src/commands/login.ts @@ -3,12 +3,18 @@ import chalk from "chalk"; import { login as workosLogin } from "../auth/workos.js"; import { gracefulExit } from "../util/exit.js"; +import { chat } from "./chat.js"; + export async function login() { console.info(chalk.yellow("Logging in to Continue...")); try { await workosLogin(); console.info(chalk.green("Successfully logged in!")); + + // Start the CLI session after successful login + console.info(chalk.blue("Starting Continue CLI...")); + await chat(); } catch (error: any) { console.error(chalk.red(`Login failed: ${error.message}`)); await gracefulExit(1); diff --git a/extensions/cli/src/commands/ls.ts b/extensions/cli/src/commands/ls.ts index d78ae162d..529c711b8 100644 --- a/extensions/cli/src/commands/ls.ts +++ b/extensions/cli/src/commands/ls.ts @@ -1,10 +1,9 @@ import { render } from "ink"; import React from "react"; -import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; -import { env } from "../env.js"; import { listSessions, loadSessionById } from "../session.js"; import { SessionSelector } from "../ui/SessionSelector.js"; +import { ApiRequestError, post } from "../util/apiClient.js"; import { logger } from "../util/logger.js"; import { chat } from "./chat.js"; @@ -27,26 +26,19 @@ function setSessionId(sessionId: string): void { } export async function getTunnelForAgent(agentId: string): Promise { - const authConfig = loadAuthConfig(); - const accessToken = getAccessToken(authConfig); - - const resp = await fetch( - new URL(`agents/${encodeURIComponent(agentId)}/tunnel`, env.apiBase), - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${accessToken}`, - }, - }, - ); - if (!resp.ok) { - throw new Error( - `Failed to get tunnel for agent ${agentId}: ${await resp.text()}`, + try { + const response = await post<{ url: string }>( + `agents/${encodeURIComponent(agentId)}/tunnel`, ); + return response.data.url; + } catch (error) { + if (error instanceof ApiRequestError) { + throw new Error( + `Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`, + ); + } + throw error; } - const data = await resp.json(); - return data.url; } /** diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts index 625ac18a8..a8025a4d7 100644 --- a/extensions/cli/src/commands/remote.test.ts +++ b/extensions/cli/src/commands/remote.test.ts @@ -8,11 +8,13 @@ vi.mock("../env.js"); vi.mock("../telemetry/telemetryService.js"); vi.mock("../ui/index.js"); vi.mock("../util/git.js"); +vi.mock("../util/exit.js"); const mockWorkos = vi.mocked(await import("../auth/workos.js")); const mockEnv = vi.mocked(await import("../env.js")); const mockGit = vi.mocked(await import("../util/git.js")); const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js")); +const mockExit = vi.mocked(await import("../util/exit.js")); // Mock fetch globally const mockFetch = vi.fn(); @@ -62,6 +64,10 @@ describe("remote command", () => { mockFetch.mockResolvedValue({ ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, json: async () => ({ id: "test-agent-id", url: "ws://test-url.com", @@ -70,6 +76,9 @@ describe("remote command", () => { }); mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any); + + // Mock gracefulExit to prevent process.exit during tests + mockExit.gracefulExit.mockResolvedValue(undefined); }); it("should include idempotency key in request body when provided", async () => { @@ -151,10 +160,18 @@ describe("remote command", () => { mockFetch .mockResolvedValueOnce({ ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }), }) .mockResolvedValue({ ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, json: async () => ({ id: "test-agent-id", url: "ws://test-url.com", @@ -187,6 +204,10 @@ describe("remote command", () => { mockFetch.mockResolvedValueOnce({ ok: true, + headers: { + get: (name: string) => + name === "content-type" ? "application/json" : null, + }, json: async () => tunnelResponse, }); diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts index 61110f2e1..919c720fd 100644 --- a/extensions/cli/src/commands/remote.ts +++ b/extensions/cli/src/commands/remote.ts @@ -1,9 +1,13 @@ import chalk from "chalk"; -import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; import { env } from "../env.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; +import { + ApiRequestError, + AuthenticationRequiredError, + post, +} from "../util/apiClient.js"; import { gracefulExit } from "../util/exit.js"; import { getRepoUrl } from "../util/git.js"; import { logger } from "../util/logger.js"; @@ -28,12 +32,6 @@ type AgentCreationResponse = TunnelResponse & { id: string; }; -class AuthenticationRequiredError extends Error { - constructor() { - super("Not authenticated. Please run 'cn login' first."); - } -} - export async function remote( prompt: string | undefined, options: RemoteCommandOptions = {}, @@ -46,19 +44,12 @@ export async function remote( return; } - const accessToken = requireAccessToken(); - if (options.id) { - await connectExistingAgent( - options.id, - accessToken, - actualPrompt, - options.start, - ); + await connectExistingAgent(options.id, actualPrompt, options.start); return; } - await createAndConnectRemoteEnvironment(accessToken, actualPrompt, options); + await createAndConnectRemoteEnvironment(actualPrompt, options); } catch (error) { await handleRemoteError(error); } @@ -99,29 +90,12 @@ async function connectToRemoteUrl( await launchRemoteTUI(remoteUrl, prompt); } -function requireAccessToken(): string { - const authConfig = loadAuthConfig(); - - if (!authConfig) { - throw new AuthenticationRequiredError(); - } - - const accessToken = getAccessToken(authConfig); - - if (!accessToken) { - throw new AuthenticationRequiredError(); - } - - return accessToken; -} - async function connectExistingAgent( agentId: string, - accessToken: string, prompt: string | undefined, startOnly?: boolean, ) { - const tunnel = await fetchAgentTunnel(agentId, accessToken); + const tunnel = await fetchAgentTunnel(agentId); if (startOnly) { printStartJson({ @@ -142,30 +116,24 @@ async function connectExistingAgent( } async function createAndConnectRemoteEnvironment( - accessToken: string, prompt: string | undefined, options: RemoteCommandOptions, ) { const requestBody = buildAgentRequestBody(options, prompt); - const response = await fetch(new URL("agents", env.apiBase), { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${accessToken}`, - }, - body: JSON.stringify(requestBody), - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `Failed to create remote environment: ${response.status} ${errorText}`, - ); + let result: AgentCreationResponse; + try { + const response = await post("agents", requestBody); + result = response.data; + } catch (error) { + if (error instanceof ApiRequestError) { + throw new Error( + `Failed to create remote environment: ${error.status} ${error.response || error.statusText}`, + ); + } + throw error; } - const result = (await response.json()) as AgentCreationResponse; - if (options.start) { printStartJson({ status: "success", @@ -216,26 +184,18 @@ function buildAgentRequestBody( return body; } -async function fetchAgentTunnel(agentId: string, accessToken: string) { - const response = await fetch( - new URL(`agents/${agentId}/tunnel`, env.apiBase), - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${accessToken}`, - }, - }, - ); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `Failed to create tunnel for agent ${agentId}: ${response.status} ${errorText}`, - ); +async function fetchAgentTunnel(agentId: string) { + try { + const response = await post(`agents/${agentId}/tunnel`); + return response.data; + } catch (error) { + if (error instanceof ApiRequestError) { + throw new Error( + `Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`, + ); + } + throw error; } - - return (await response.json()) as TunnelResponse; } async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) { diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 2aee9e23a..bba7efa00 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -2,6 +2,7 @@ import chalk from "chalk"; import type { ChatHistoryItem } from "core/index.js"; import express, { Request, Response } from "express"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { posthogService } from "src/telemetry/posthogService.js"; import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; @@ -72,9 +73,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); // Get initialized services from the service container - const [configState, modelState] = await Promise.all([ + const [configState, modelState, permissionsState] = await Promise.all([ getService(SERVICE_NAMES.CONFIG), getService(SERVICE_NAMES.MODEL), + getService(SERVICE_NAMES.TOOL_PERMISSIONS), ]); if (!configState.config || !modelState.llmApi || !modelState.model) { @@ -117,6 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Initialize session with system message const systemMessage = await constructSystemMessage( + permissionsState.currentMode, options.rule, undefined, true, @@ -259,6 +262,32 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); }); + // POST /pause - Pause the current agent run (like pressing escape in TUI) + app.post("/pause", async (_req: Request, res: Response) => { + state.lastActivity = Date.now(); + + // Check if there's anything to pause + if (!state.isProcessing) { + return res.json({ + success: false, + message: "No active processing to pause", + }); + } + + // Abort the current processing + if (state.currentAbortController) { + state.currentAbortController.abort(); + } + + // Set isProcessing to false + state.isProcessing = false; + + res.json({ + success: true, + message: "Agent run paused", + }); + }); + // GET /diff - Return git diff against main branch app.get("/diff", async (_req: Request, res: Response) => { state.lastActivity = Date.now(); @@ -343,6 +372,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { " POST /permission - Approve/reject tool (body: { requestId, approved })", ), ); + console.log(chalk.dim(" POST /pause - Pause the current agent run")); console.log( chalk.dim(" GET /diff - Get git diff against main branch"), ); diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts index 6c97767bc..90734d835 100644 --- a/extensions/cli/src/config.ts +++ b/extensions/cli/src/config.ts @@ -7,7 +7,6 @@ import { import { Configuration, DefaultApi, - DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; import { @@ -15,9 +14,7 @@ import { getAccessToken, getOrganizationId, } from "./auth/workos.js"; -import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { MCPService } from "./services/MCPService.js"; /** * Creates an LLM API instance from a ModelConfig and auth configuration @@ -96,23 +93,3 @@ export function getApiClient( }), ); } - -export async function initialize( - authConfig: AuthConfig, - configPath: string | undefined, -): Promise<{ - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; -}> { - const apiClient = getApiClient(authConfig?.accessToken); - const result = await loadConfiguration(authConfig, configPath, apiClient); - const config = result.config; - const [llmApi, model] = getLlmApi(config, authConfig); - const mcpService = new MCPService(); - await mcpService.initialize(config, false); - - return { config, llmApi, model, mcpService, apiClient }; -} diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts index bbee50c0b..4b37951d5 100644 --- a/extensions/cli/src/configEnhancer.test.ts +++ b/extensions/cli/src/configEnhancer.test.ts @@ -13,11 +13,34 @@ vi.mock("./hubLoader.js", () => ({ // Return as-is for direct content return Promise.resolve(rule); }), + loadPackageFromHub: vi.fn(() => + Promise.resolve({ name: "test", provider: "test" }), + ), loadPackagesFromHub: vi.fn(() => Promise.resolve([])), mcpProcessor: {}, modelProcessor: {}, })); +// Mock the service container to provide empty workflow state +vi.mock("./services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(() => + Promise.resolve({ + workflowService: null, + workflowModelName: null, + workflowFile: null, + workflow: null, + }), + ), + }, +})); + +vi.mock("./services/types.js", () => ({ + SERVICE_NAMES: { + WORKFLOW: "workflow", + }, +})); + describe("ConfigEnhancer", () => { let enhancer: ConfigEnhancer; let mockConfig: any; @@ -173,11 +196,12 @@ describe("ConfigEnhancer", () => { }); it("should prepend MCPs from --mcp flag", async () => { - // Mock loadPackagesFromHub to return test MCPs - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "New-MCP", command: "new-mcp" }, - ]); + // Mock loadPackageFromHub to return test MCP (singular call for each MCP) + const { loadPackageFromHub } = await import("./hubLoader.js"); + (loadPackageFromHub as any).mockResolvedValueOnce({ + name: "New-MCP", + command: "new-mcp", + }); // Set up existing MCPs in config mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; @@ -199,4 +223,106 @@ describe("ConfigEnhancer", () => { command: "existing-mcp", }); }); + + it("should handle URLs in --mcp flag as streamable-http servers", async () => { + // Set up existing MCPs in config + mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; + + const options: BaseCommandOptions = { + mcp: ["https://docs.continue.dev/mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // URL should be converted to streamable-http MCP configuration + expect(config.mcpServers).toHaveLength(2); + expect(config.mcpServers?.[0]).toEqual({ + name: "docs.continue.dev", + type: "streamable-http", + url: "https://docs.continue.dev/mcp", + }); + expect(config.mcpServers?.[1]).toEqual({ + name: "Existing-MCP", + command: "existing-mcp", + }); + }); + + it("should handle mix of URLs and hub slugs in --mcp flag", async () => { + // Mock loadPackageFromHub to return test MCP for hub slug + const { loadPackageFromHub } = await import("./hubLoader.js"); + (loadPackageFromHub as any).mockResolvedValueOnce({ + name: "Hub-MCP", + command: "hub-mcp", + }); + + const options: BaseCommandOptions = { + mcp: ["https://example.com/mcp", "test/hub-mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.mcpServers).toHaveLength(2); + expect(config.mcpServers?.[0]).toEqual({ + name: "example.com", + type: "streamable-http", + url: "https://example.com/mcp", + }); + expect(config.mcpServers?.[1]).toEqual({ + name: "Hub-MCP", + command: "hub-mcp", + }); + }); + + it("should handle http:// URLs in --mcp flag", async () => { + const options: BaseCommandOptions = { + mcp: ["http://localhost:8080/mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.mcpServers).toHaveLength(1); + expect(config.mcpServers?.[0]).toEqual({ + name: "localhost", + type: "streamable-http", + url: "http://localhost:8080/mcp", + }); + }); + + it("should handle workflow integration gracefully when no workflow", async () => { + // The mocked service container returns null workflow state + const options: BaseCommandOptions = { + rule: ["test-rule"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // Should work normally when no workflow is active + expect(config.rules).toEqual(["test-rule"]); + }); + + it("should handle workflow integration when workflow is active", async () => { + // Mock service container to return active workflow + const options: BaseCommandOptions = { + rule: ["user-rule"], + prompt: ["user-prompt"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options, { + workflowFile: { + name: "Test Workflow", + prompt: "You are a test assistant", + rules: "Always be helpful", + model: "gpt-4", + tools: "bash,read", + }, + slug: "owner/test-workflow", + workflowModelName: null, + workflowService: null, + }); + + // Should have both workflow and user rules + expect(config.rules).toHaveLength(2); + expect(config.rules?.[0]).toBe("Always be helpful"); // Workflow rule first + expect(config.rules?.[1]).toBe("user-rule"); // User rule second + }); }); diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index ee1c9b254..b299e871b 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -1,43 +1,115 @@ -import { AssistantUnrolled, Rule } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + parseWorkflowTools, + Rule, +} from "@continuedev/config-yaml"; import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; import { + loadPackageFromHub, loadPackagesFromHub, mcpProcessor, modelProcessor, processRule, } from "./hubLoader.js"; +import { WorkflowServiceState } from "./services/types.js"; import { logger } from "./util/logger.js"; /** * Enhances a configuration by injecting additional components from CLI flags */ export class ConfigEnhancer { + // added this for lint complexity rule + private async enhanceConfigFromWorkflow( + config: AssistantUnrolled, + _options: BaseCommandOptions | undefined, + workflowState?: WorkflowServiceState, + ) { + const enhancedConfig = { ...config }; + const options = { ..._options }; + + if (workflowState?.workflowFile) { + const { rules, model, tools, prompt } = workflowState?.workflowFile; + if (rules) { + options.rule = [ + ...rules + .split(",") + .filter(Boolean) + .map((r) => r.trim()), + ...(options.rule || []), + ]; + } + + if (tools) { + try { + const parsedTools = parseWorkflowTools(tools); + if (parsedTools.mcpServers.length > 0) { + options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; + } + } catch (e) { + logger.error("Failed to parse workflow tools", e); + } + } + + // --model takes precedence over workflow model + if (model) { + try { + const workflowModel = await loadPackageFromHub(model, modelProcessor); + enhancedConfig.models = [ + workflowModel, + ...(enhancedConfig.models ?? []), + ]; + workflowState?.workflowService?.setWorkflowModelName( + workflowModel.name, + ); + } catch (e) { + logger.error("Failed to load workflow model", e); + } + } + + // Workflow prompt is included as a slash command, initial kickoff is handled elsewhere + if (prompt) { + enhancedConfig.prompts = [ + { + name: `Workflow prompt (${workflowState.workflowFile.name})`, + prompt, + description: workflowState.workflowFile.description, + }, + ...(enhancedConfig.prompts ?? []), + ]; + } + } + return { options, enhancedConfig }; + } /** * Apply all enhancements to a configuration */ async enhanceConfig( config: AssistantUnrolled, - options: BaseCommandOptions, + _options?: BaseCommandOptions, + workflowState?: WorkflowServiceState, ): Promise { - let enhancedConfig = { ...config }; + const enhanced = await this.enhanceConfigFromWorkflow( + config, + _options, + workflowState, + ); + let { enhancedConfig } = enhanced; + const { options } = enhanced; - // Apply rules + // Inject resolved items into config if (options.rule && options.rule.length > 0) { enhancedConfig = await this.injectRules(enhancedConfig, options.rule); } - // Apply MCPs if (options.mcp && options.mcp.length > 0) { enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); } - // Apply models if (options.model && options.model.length > 0) { enhancedConfig = await this.injectModels(enhancedConfig, options.model); } - // Apply prompts if (options.prompt && options.prompt.length > 0) { enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); } @@ -99,17 +171,35 @@ export class ConfigEnhancer { config: AssistantUnrolled, mcps: string[], ): Promise { - const processedMcps = await loadPackagesFromHub(mcps, mcpProcessor); + const processedMcps: any[] = []; + + // Process each MCP spec - check if it's a URL or hub slug + for (const mcpSpec of mcps) { + try { + // Check if it's a URL (starts with http:// or https://) + if (mcpSpec.startsWith("http://") || mcpSpec.startsWith("https://")) { + // Create a streamable-http MCP configuration + processedMcps.push({ + name: new URL(mcpSpec).hostname, + type: "streamable-http", + url: mcpSpec, + }); + } else { + // Otherwise, treat it as a hub slug + const hubMcp = await loadPackageFromHub(mcpSpec, mcpProcessor); + processedMcps.push(hubMcp); + } + } catch (error: any) { + logger.warn(`Failed to load MCP "${mcpSpec}": ${error.message}`); + } + } // Clone the config to avoid mutating the original const modifiedConfig = { ...config }; // Prepend processed MCPs to existing mcpServers array for consistency - const existingMcpServers = (modifiedConfig as any).mcpServers || []; - (modifiedConfig as any).mcpServers = [ - ...processedMcps, - ...existingMcpServers, - ]; + const existingMcpServers = modifiedConfig.mcpServers || []; + modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers]; return modifiedConfig; } @@ -123,26 +213,28 @@ export class ConfigEnhancer { ): Promise { const processedModels = await loadPackagesFromHub(models, modelProcessor); - // Clone the config to avoid mutating the original const modifiedConfig = { ...config }; // Prepend processed models to existing models array so they become the default - const existingModels = (modifiedConfig as any).models || []; - (modifiedConfig as any).models = [...processedModels, ...existingModels]; + const existingModels = modifiedConfig.models || []; + modifiedConfig.models = [...processedModels, ...existingModels]; return modifiedConfig; } /** * Inject prompts into the configuration + * Note: Prompts are processed at runtime via processAndCombinePrompts(), + * not injected into the config. This method exists for consistency with + * other injection methods but doesn't modify the config. */ private async injectPrompts( config: AssistantUnrolled, prompts: string[], ): Promise { - // For prompts, we'll need a different approach since they become slash commands - // This is a placeholder implementation - logger.debug("Prompt injection not yet implemented", { prompts }); + // Prompts are handled at runtime by processAndCombinePrompts in chat.ts + // They don't need to be injected into the configuration + logger.debug("Prompts will be processed at runtime", { prompts }); return config; } } diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts index a5ccf0970..ccb2437c9 100644 --- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts @@ -115,7 +115,7 @@ models: if (configExists) { const configContent = await fs.readFile(configPath, "utf-8"); - expect(configContent).toContain("anthropic/claude-4-sonnet"); + expect(configContent).toContain("anthropic/claude-sonnet-4-5"); expect(configContent).toContain( "ANTHROPIC_API_KEY: TEST-test-invalid-key-format", ); diff --git a/extensions/cli/src/e2e/headless-permission-error.test.ts b/extensions/cli/src/e2e/headless-permission-error.test.ts new file mode 100644 index 000000000..60a10d16f --- /dev/null +++ b/extensions/cli/src/e2e/headless-permission-error.test.ts @@ -0,0 +1,209 @@ +/** + * E2E test for headless mode permission errors + * Verifies that when a tool requires permission in headless mode, + * an appropriate error message is displayed suggesting the --auto flag + */ +import * as http from "http"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + cleanupMockLLMServer, + setupMockLLMTest, + type MockLLMServer, +} from "../test-helpers/mock-llm-server.js"; + +describe("E2E: Headless Mode Permission Errors", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + if (mockServer) { + await cleanupMockLLMServer(mockServer); + } + await cleanupTestContext(context); + }); + it("should display error message with --auto suggestion when tool requires permission", async () => { + // Set up mock LLM to return a tool call that requires permission (Write tool) + mockServer = await setupMockLLMTest(context, { + customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send a Write tool call (requires permission by default) + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); + }, + }); + + // Run CLI in headless mode without permission flags + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath, "Create a file test.txt"], + timeout: 15000, + }); + + // Expect non-zero exit code + expect(result.exitCode).toBe(1); + + // Verify the error message contains the expected information + expect(result.stderr).toContain("requires permission"); + expect(result.stderr).toContain("headless mode"); + expect(result.stderr).toContain("--auto"); + expect(result.stderr).toContain("--allow"); + expect(result.stderr).toContain("--exclude"); + }, 20000); + + it("should succeed with --auto flag when tool requires permission", async () => { + // Set up mock LLM to return a Write tool call + mockServer = await setupMockLLMTest(context, { + customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send a Write tool call + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); + }, + }); + + // Run CLI with --auto flag + const result = await runCLI(context, { + args: [ + "-p", + "--auto", + "--config", + context.configPath, + "Create a file test.txt", + ], + timeout: 15000, + }); + + // Should succeed + expect(result.exitCode).toBe(0); + expect(result.stderr).not.toContain("requires permission"); + }, 20000); + + it("should succeed with --allow flag for specific tool", async () => { + // Set up mock LLM to return a Write tool call + mockServer = await setupMockLLMTest(context, { + customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send a Write tool call + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`, + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`, + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`, + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); + }, + }); + + // Run CLI with --allow Write flag + const result = await runCLI(context, { + args: [ + "-p", + "--allow", + "Write", + "--config", + context.configPath, + "Create a file test.txt", + ], + timeout: 15000, + }); + + // Should succeed + expect(result.exitCode).toBe(0); + expect(result.stderr).not.toContain("requires permission"); + }, 20000); +}); diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts index dcbbd57b8..d659652f4 100644 --- a/extensions/cli/src/hooks/useService.ts +++ b/extensions/cli/src/hooks/useService.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useServiceContainer } from "../services/ServiceContainerContext.js"; import { ServiceResult } from "../services/types.js"; @@ -96,47 +96,54 @@ export function useServices>( allReady: boolean; } { const container = useServiceContainer(); - const [services, setServices] = useState>({}); + + const getServiceStates = useCallback(() => { + const services: Partial = {}; + let hasLoading = false; + let hasError: Error | null = null; + + for (const serviceName of serviceNames) { + const result = container.getSync(serviceName as string); + + if (result.state === "loading") { + hasLoading = true; + } else if (result.state === "error") { + hasError = result.error; + } else if (result.state === "idle") { + // Auto-load idle services + container.load(serviceName as string).catch(() => {}); + } else if (result.state === "ready" && result.value !== null) { + services[serviceName] = result.value as T[keyof T]; + } else { + } + } + + return { + hasLoading, + hasError, + services, + }; + }, [serviceNames, container]); + const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [services, setServices] = useState>( + getServiceStates().services, + ); useEffect(() => { - const updateState = () => { - const newServices: Partial = {}; - let hasLoading = false; - let hasError: Error | null = null; - - for (const serviceName of serviceNames) { - const result = container.getSync(serviceName as string); - - if (result.state === "loading") { - hasLoading = true; - } else if (result.state === "error") { - hasError = result.error; - } else if (result.state === "idle") { - // Auto-load idle services - container.load(serviceName as string).catch(() => {}); - } else if (result.state === "ready" && result.value !== null) { - newServices[serviceName] = result.value as T[keyof T]; - } else { - } - } - - setServices(newServices); - setLoading(hasLoading); - setError(hasError); - }; - - // Initial state - updateState(); - // Set up listeners for all services const listeners: Array<() => void> = []; for (const serviceName of serviceNames) { const name = serviceName as string; - const onAnyChange = () => updateState(); + const onAnyChange = () => { + const { hasLoading, hasError, services } = getServiceStates(); + setLoading(hasLoading); + setError(hasError); + setServices(services); + }; container.on(`${name}:loading`, onAnyChange); container.on(`${name}:ready`, onAnyChange); @@ -155,7 +162,7 @@ export function useServices>( return () => { listeners.forEach((cleanup) => cleanup()); }; - }, [serviceNames.join(","), container]); + }, [serviceNames.join(","), container, getServiceStates]); const allReady = serviceNames.every((name) => container.isReady(name as string), diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index 533980541..006cda7a8 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,3 +1,4 @@ +import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; import JSZip from "jszip"; import { env } from "./env.js"; @@ -11,7 +12,7 @@ const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; /** * Hub package type definitions */ -export type HubPackageType = "rule" | "mcp" | "model" | "prompt"; +export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "workflow"; /** * Hub package processor interface @@ -99,6 +100,15 @@ export const promptProcessor: HubPackageProcessor = { parseContent: (content: string) => content, }; +export const workflowProcessor: HubPackageProcessor = { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: (content: string) => parseWorkflowFile(content), + validateContent: (workflowFile: WorkflowFile) => { + return !!workflowFile.name; + }, +}; + /** * Generic hub package loader */ diff --git a/extensions/cli/src/integration/model-persistence-e2e.test.ts b/extensions/cli/src/integration/model-persistence-e2e.test.ts new file mode 100644 index 000000000..22354c989 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-e2e.test.ts @@ -0,0 +1,205 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; +import { persistModelName } from "../util/modelPersistence.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence End-to-End", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthenticatedConfig; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, // 1 hour from now + organizationId: "test-org", + }; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should restore model selection after restart", async () => { + // Step 1: Initial session - user starts with default model (GPT-4) + saveAuthConfig(mockAuthConfig); + let service = new ModelService(); + let state = await service.initialize(mockAssistant, mockAuthConfig); + + console.log("Initial model:", state.model?.name); + expect(state.model?.name).toBe("GPT-4"); + + // Step 2: User switches to Claude 3.5 Sonnet (index 1) + await service.switchModel(1); + state = service.getState(); + + console.log("After switch:", state.model?.name); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + + // Step 3: Persist the model choice (this should happen in useModelSelector) + updateModelName("Claude 3.5 Sonnet"); + + // Verify it was saved to auth.json + const savedConfig = loadAuthConfig(); + console.log("Saved model name:", getModelName(savedConfig)); + expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet"); + + // Step 4: Simulate restart - create new service instance + // Load fresh auth config from disk (this is what the real code does) + const freshAuthConfig = loadAuthConfig(); + console.log("Fresh auth config model name:", getModelName(freshAuthConfig)); + + service = new ModelService(); + state = await service.initialize(mockAssistant, freshAuthConfig); + + // Step 5: Verify the persisted model is restored + console.log("After restart:", state.model?.name); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + expect(state.model?.provider).toBe("anthropic"); + }); + + test("should handle model name mismatch gracefully", async () => { + // Save auth config with a model that doesn't exist + mockAuthConfig.modelName = "Non-existent Model"; + saveAuthConfig(mockAuthConfig); + + const service = new ModelService(); + const state = await service.initialize(mockAssistant, mockAuthConfig); + + // Should fall back to first available model (GPT-4) + expect(state.model?.name).toBe("GPT-4"); + }); + + test("should check both name and model fields when matching", async () => { + // Some configs might have model field instead of name + const assistantWithModelField = { + ...mockAssistant, + models: [ + { + provider: "openai", + model: "gpt-4", + // No name field, just model + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + // No name field, just model + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig.modelName = "claude-3-5-sonnet-20241022"; + saveAuthConfig(mockAuthConfig); + + const service = new ModelService(); + const state = await service.initialize( + assistantWithModelField, + mockAuthConfig, + ); + + // Should match by model field + expect(state.model?.model).toBe("claude-3-5-sonnet-20241022"); + }); + + test("should persist model through multiple switches", async () => { + saveAuthConfig(mockAuthConfig); + const service = new ModelService(); + await service.initialize(mockAssistant, mockAuthConfig); + + // Switch to Claude 3.5 Sonnet + await service.switchModel(1); + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet"); + + // Switch to Claude 3 Opus + await service.switchModel(2); + updateModelName("Claude 3 Opus"); + expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus"); + + // Restart and verify last selection + const freshAuthConfig = loadAuthConfig(); + console.log("Fresh auth config model name:", getModelName(freshAuthConfig)); + + const newService = new ModelService(); + const state = await newService.initialize(mockAssistant, freshAuthConfig); + expect(state.model?.name).toBe("Claude 3 Opus"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts new file mode 100644 index 000000000..db4b30ee4 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-unauthenticated.test.ts @@ -0,0 +1,245 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + getModelName, + loadAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; +import { + getPersistedModelName, + persistModelName, +} from "../util/modelPersistence.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence for Unauthenticated Users", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model selection for logged-out users", () => { + // User is logged out (no auth config) + const authConfig = loadAuthConfig(); + expect(authConfig).toBeNull(); + + // User switches model + updateModelName("Claude 3.5 Sonnet"); + + // Verify it was saved to GlobalContext + const persistedModel = getPersistedModelName(); + expect(persistedModel).toBe("Claude 3.5 Sonnet"); + + // Verify getModelName returns it for null config + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + }); + + test("should restore model selection on next session for logged-out users", async () => { + // Session 1: User is logged out and switches model + const authConfig = loadAuthConfig(); + expect(authConfig).toBeNull(); + + const modelService = new ModelService(); + await modelService.initialize(mockAssistant, authConfig); + + await modelService.switchModel(1); + updateModelName("Claude 3.5 Sonnet"); + + // Session 2: User reopens CLI (still logged out) + const newAuthConfig = loadAuthConfig(); + expect(newAuthConfig).toBeNull(); + + const newModelService = new ModelService(); + const state = await newModelService.initialize( + mockAssistant, + newAuthConfig, + ); + + // Should restore Claude 3.5 Sonnet + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + }); + + test("should handle multiple model switches for logged-out users", () => { + updateModelName("GPT-4"); + expect(getModelName(null)).toBe("GPT-4"); + + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + + updateModelName("Claude 3 Opus"); + expect(getModelName(null)).toBe("Claude 3 Opus"); + }); + + test("should clear model selection when set to null", () => { + updateModelName("Claude 3.5 Sonnet"); + expect(getModelName(null)).toBe("Claude 3.5 Sonnet"); + + updateModelName(null); + expect(getModelName(null)).toBeNull(); + }); + + test("should preserve GlobalContext model when user logs in", () => { + // User is logged out with a persisted model + updateModelName("Claude 3.5 Sonnet"); + expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet"); + + // User logs in (simulated by having auth.json) + const authPath = path.join(testDir, "auth.json"); + fs.writeFileSync( + authPath, + JSON.stringify({ + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }), + ); + + const authConfig = loadAuthConfig(); + expect(authConfig).not.toBeNull(); + + // GlobalContext model should still exist + expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet"); + + // When auth config has no modelName, it should fall back to GlobalContext + expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should use auth config model when both exist", () => { + // Clear previous state + updateModelName(null); + + // Set GlobalContext model + updateModelName("GPT-4"); + expect(getPersistedModelName()).toBe("GPT-4"); + + // Create auth config with different model + const authPath = path.join(testDir, "auth.json"); + fs.writeFileSync( + authPath, + JSON.stringify({ + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "Claude 3.5 Sonnet", + }), + ); + + const authConfig = loadAuthConfig(); + + // Auth config should take precedence + expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should not save to GlobalContext when using CONTINUE_API_KEY", () => { + // Clear any existing model + updateModelName(null); + expect(getPersistedModelName()).toBeNull(); + + // Capture original value to restore after test + const originalApiKey = process.env.CONTINUE_API_KEY; + process.env.CONTINUE_API_KEY = "test-api-key"; + + updateModelName("Claude 3.5 Sonnet"); + + // Should not be saved to GlobalContext + expect(getPersistedModelName()).toBeNull(); + + // Restore original value + if (originalApiKey === undefined) { + delete process.env.CONTINUE_API_KEY; + } else { + process.env.CONTINUE_API_KEY = originalApiKey; + } + }); + + test("should work across config changes for logged-out users", async () => { + // User switches model with one config + updateModelName("Claude 3.5 Sonnet"); + + const modelService = new ModelService(); + let state = await modelService.initialize(mockAssistant, null); + expect(state.model?.name).toBe("Claude 3.5 Sonnet"); + + // User switches to a different model + await modelService.switchModel(2); + updateModelName("Claude 3 Opus"); + + // Create new service (simulating restart) + const newModelService = new ModelService(); + state = await newModelService.initialize(mockAssistant, null); + expect(state.model?.name).toBe("Claude 3 Opus"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts new file mode 100644 index 000000000..3aef05071 --- /dev/null +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -0,0 +1,155 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { AuthService } from "src/services/AuthService.js"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, +} from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "../services/ModelService.js"; + +// Mock the config module +vi.mock("../config.js"); + +describe("Model Persistence User Flow", () => { + let testDir: string; + let originalContinueHome: string | undefined; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthenticatedConfig; + const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + mockAssistant = { + name: "test-assistant", + version: "1.0.0", + models: [ + { + provider: "openai", + model: "gpt-4", + name: "GPT-4", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + name: "Claude 3.5 Sonnet", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + { + provider: "anthropic", + model: "claude-3-opus-20240229", + name: "Claude 3 Opus", + apiKey: "test-key", + roles: ["chat"], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, // 1 hour from now + organizationId: "test-org", + modelName: "GPT-4", + }; + + // Setup default mock behavior + vi.mocked(config.getLlmApi).mockReturnValue([ + mockLlmApi as any, + mockAssistant.models![0] as ModelConfig, + ]); + vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model choice exactly as user experiences it", async () => { + console.log("\n=== SESSION 1: User opens cn and switches model ==="); + + // Session 1: User starts CLI + // Save initial auth config (what happens after login) + saveAuthConfig(mockAuthConfig); + console.log("1. Initial auth.json saved"); + + // Initialize ModelService (what happens on CLI start) + const modelService = new ModelService(); + const state = await modelService.initialize(mockAssistant, mockAuthConfig); + console.log("2. Initial model:", state.model?.name); + expect(state.model?.name).toBe("GPT-4"); + + // User switches to Claude 3.5 Sonnet via UI + await modelService.switchModel(1); + const modelInfo = modelService.getModelInfo(); + console.log("3. User switched to:", modelInfo?.name); + expect(modelInfo?.name).toBe("Claude 3.5 Sonnet"); + + // useModelSelector calls updateModelName + const { updateModelName } = await import("../auth/workos.js"); + const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet"); + console.log("4. Model name persisted to disk"); + + // Verify it was saved + const savedConfig = loadAuthConfig(); + console.log("5. Read back from disk:", getModelName(savedConfig)); + expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet"); + + // User closes CLI + console.log("6. User exits CLI\n"); + + console.log("=== SESSION 2: User reopens cn ==="); + + // Session 2: User restarts CLI + // Initialize AuthService (loads from disk) + const authService = new AuthService(); + const authState = await authService.initialize(); + console.log( + "7. AuthService loaded, modelName in auth:", + getModelName(authState.authConfig), + ); + + // Initialize ModelService with fresh auth state + const newModelService = new ModelService(); + const newState = await newModelService.initialize( + mockAssistant, + authState.authConfig, + ); + console.log( + "8. ModelService initialized with model:", + newState.model?.name, + ); + + // EXPECTATION: Should restore Claude 3.5 Sonnet + expect(newState.model?.name).toBe("Claude 3.5 Sonnet"); + expect(newState.model?.provider).toBe("anthropic"); + console.log("✅ Model persisted correctly!\n"); + }); +}); diff --git a/extensions/cli/src/integration/model-persistence.test.ts b/extensions/cli/src/integration/model-persistence.test.ts new file mode 100644 index 000000000..9e352143d --- /dev/null +++ b/extensions/cli/src/integration/model-persistence.test.ts @@ -0,0 +1,194 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { + AuthenticatedConfig, + getModelName, + loadAuthConfig, + saveAuthConfig, + updateModelName, +} from "../auth/workos.js"; +import { persistModelName } from "../util/modelPersistence.js"; + +describe("Model Persistence Integration", () => { + let testDir: string; + let originalContinueHome: string | undefined; + + beforeEach(() => { + // Create a temporary directory for testing + testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-")); + originalContinueHome = process.env.CONTINUE_GLOBAL_DIR; + process.env.CONTINUE_GLOBAL_DIR = testDir; + + // Clear GlobalContext for clean test state + persistModelName(null); + }); + + afterEach(() => { + // Cleanup + if (fs.existsSync(testDir)) { + fs.rmSync(testDir, { recursive: true }); + } + if (originalContinueHome) { + process.env.CONTINUE_GLOBAL_DIR = originalContinueHome; + } else { + delete process.env.CONTINUE_GLOBAL_DIR; + } + }); + + test("should persist model name when user selects a model", () => { + // Create initial auth config without model name + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }; + + saveAuthConfig(authConfig); + + // User selects a model + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify model name is persisted + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should update model name when user switches models", () => { + // Create initial auth config with a model + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "GPT-4", + }; + + saveAuthConfig(authConfig); + + // User switches to a different model + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify new model name + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet"); + }); + + test("should preserve other auth config fields when updating model", () => { + // Create initial auth config + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + configUri: "slug://owner/my-config", + }; + + saveAuthConfig(authConfig); + + // Update model name + updateModelName("Claude 3.5 Sonnet"); + + // Load config and verify all fields are preserved + const loadedConfig = loadAuthConfig(); + expect(loadedConfig).toMatchObject({ + userId: "test-user", + userEmail: "test@example.com", + organizationId: "test-org", + configUri: "slug://owner/my-config", + modelName: "Claude 3.5 Sonnet", + }); + }); + + test("should clear model name when set to null", () => { + // Create initial auth config with a model + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + modelName: "GPT-4", + }; + + saveAuthConfig(authConfig); + + // Clear model name + updateModelName(null); + + // Load config and verify model name is cleared + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + }); + + test("should return null for model name when not authenticated and no GlobalContext", () => { + // No auth config exists and no GlobalContext model + persistModelName(null); // Ensure GlobalContext is clear + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + }); + + test("should not persist model name when using CONTINUE_API_KEY", () => { + // Clear GlobalContext first + persistModelName(null); + + // Capture original value to restore after test + const originalApiKey = process.env.CONTINUE_API_KEY; + // Set environment variable + process.env.CONTINUE_API_KEY = "test-api-key"; + + // Try to update model name + updateModelName("Claude 3.5 Sonnet"); + + // Load config - should be environment auth config without model name + const loadedConfig = loadAuthConfig(); + expect(getModelName(loadedConfig)).toBeNull(); + + // Restore original value + if (originalApiKey === undefined) { + delete process.env.CONTINUE_API_KEY; + } else { + process.env.CONTINUE_API_KEY = originalApiKey; + } + }); + + test("should persist model name in auth.json file with correct format", () => { + // Create and save auth config + const authConfig: AuthenticatedConfig = { + userId: "test-user", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh", + expiresAt: Date.now() + 3600000, + organizationId: "test-org", + }; + + saveAuthConfig(authConfig); + updateModelName("Claude 3.5 Sonnet"); + + // Read the raw file content + const authPath = path.join(testDir, "auth.json"); + const rawContent = fs.readFileSync(authPath, "utf8"); + const parsedContent = JSON.parse(rawContent); + + // Verify the file structure + expect(parsedContent).toHaveProperty("userId", "test-user"); + expect(parsedContent).toHaveProperty("userEmail", "test@example.com"); + expect(parsedContent).toHaveProperty("organizationId", "test-org"); + expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet"); + + // Verify it's pretty-printed (has indentation) + expect(rawContent).toContain("\n "); + }); +}); diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index e68a3eff9..83143dede 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -19,6 +19,24 @@ vi.mock("../hubLoader.js", () => ({ modelProcessor: {}, })); +// Mock the service container to provide empty workflow state +vi.mock("../services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(() => + Promise.resolve({ + workflowFile: null, + slug: null, + }), + ), + }, +})); + +vi.mock("../services/types.js", () => ({ + SERVICE_NAMES: { + WORKFLOW: "workflow", + }, +})); + describe("Rule duplication integration test", () => { it("should not duplicate rules when using --rule flag", async () => { const enhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/loadMcpFromHub.test.ts b/extensions/cli/src/loadMcpFromHub.test.ts index 92dd69cf8..cbd49a53a 100644 --- a/extensions/cli/src/loadMcpFromHub.test.ts +++ b/extensions/cli/src/loadMcpFromHub.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Store original fetch to restore later const originalFetch = global.fetch; diff --git a/extensions/cli/src/mcp-flag.integration.test.ts b/extensions/cli/src/mcp-flag.integration.test.ts index a040c45b4..863e1ea32 100644 --- a/extensions/cli/src/mcp-flag.integration.test.ts +++ b/extensions/cli/src/mcp-flag.integration.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { parseArgs, loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Integration test to demonstrate the --mcp flag functionality describe("--mcp flag integration", () => { @@ -10,35 +10,6 @@ describe("--mcp flag integration", () => { vi.clearAllMocks(); }); - it("should demonstrate the complete --mcp flag functionality", () => { - // Test command line parsing - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "continuedev/filesystem", - "--mcp", - "continuedev/github", - "hello world", - ]; - - const args = parseArgs(); - - // Verify the parsed command line arguments - expect(args).toEqual({ - configPath: "my-config.yaml", - mcps: ["continuedev/filesystem", "continuedev/github"], - prompt: "hello world", - }); - - // Verify MCP slugs are properly captured - expect(args.mcps).toHaveLength(2); - expect(args.mcps).toContain("continuedev/filesystem"); - expect(args.mcps).toContain("continuedev/github"); - }); - it("should validate MCP slug format", async () => { // Test that invalid slug formats are rejected await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow( @@ -58,35 +29,4 @@ describe("--mcp flag integration", () => { 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found', ); }); - - it("should demonstrate MCP flag with other command line options", () => { - process.argv = [ - "node", - "test", - "--config", - "test-config.yaml", - "--org", - "my-org", - "--rule", - "my-rule", - "--mcp", - "continuedev/filesystem", - "--allow", - "readFile", - "--readonly", - "analyze this code", - ]; - - const args = parseArgs(); - - // Verify all flags are parsed correctly together - expect(args).toEqual({ - configPath: "test-config.yaml", - organizationSlug: "my-org", - rules: ["my-rule"], - mcps: ["continuedev/filesystem"], - readonly: true, - prompt: "analyze this code", - }); - }); }); diff --git a/extensions/cli/src/onboarding.test.ts b/extensions/cli/src/onboarding.test.ts index 1864e6368..1dee85c8d 100644 --- a/extensions/cli/src/onboarding.test.ts +++ b/extensions/cli/src/onboarding.test.ts @@ -5,7 +5,7 @@ import * as path from "path"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import type { AuthConfig } from "./auth/workos.js"; -import { runNormalFlow } from "./onboarding.js"; +import { initializeWithOnboarding } from "./onboarding.js"; describe("onboarding config flag handling", () => { let tempDir: string; @@ -40,7 +40,9 @@ describe("onboarding config flag handling", () => { expect(fs.existsSync(configPath)).toBe(false); // Should throw an error that mentions both the path and the failure - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow( /Failed to load config from ".*non-existent\.yaml": .*ENOENT/, ); }); @@ -64,9 +66,9 @@ models: expect(fs.existsSync(configPath)).toBe(true); // Should throw an error mentioning the path and failure to load - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*malformed\.yaml": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*malformed\.yaml": .+/); }); test("should fail loudly when --config points to file with missing required fields", async () => { @@ -85,9 +87,9 @@ name: "Incomplete Config" expect(fs.existsSync(configPath)).toBe(true); // Should throw with our specific error format and include path - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /^Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/^Failed to load config from ".*": .+/); }); test("should handle different config path formats with proper error messages", async () => { @@ -99,16 +101,18 @@ name: "Incomplete Config" ]; for (const configPath of testPaths) { - await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( - /Failed to load config from ".*": .+/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, configPath), + ).rejects.toThrow(/Failed to load config from ".*": .+/); } }); test("should handle empty string config path", async () => { // Empty string should be treated differently from undefined // Note: empty string triggers onboarding flow, but should still fail in our error format - await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow(); + await expect( + initializeWithOnboarding(mockAuthConfig, ""), + ).rejects.toThrow(); }); test("should not fall back to default config when explicit config fails", async () => { @@ -117,7 +121,7 @@ name: "Incomplete Config" // Create a bad config file fs.writeFileSync(configPath, "invalid: yaml: content: ["); - const promise = runNormalFlow(mockAuthConfig, configPath); + const promise = initializeWithOnboarding(mockAuthConfig, configPath); await expect(promise).rejects.toThrow(); @@ -144,13 +148,13 @@ name: "Incomplete Config" fs.writeFileSync(badConfigPath, "invalid yaml ["); // Case 1: Explicit --config that fails should throw our specific error - await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow( - /^Failed to load config from "/, - ); + await expect( + initializeWithOnboarding(mockAuthConfig, badConfigPath), + ).rejects.toThrow(/^Failed to load config from "/); // Case 2: No explicit config should follow different logic try { - await runNormalFlow(mockAuthConfig, undefined); + await initializeWithOnboarding(mockAuthConfig, undefined); // If it succeeds, that's fine - the point is it's different behavior } catch (error) { const errorMessage = @@ -213,9 +217,9 @@ describe("CONTINUE_USE_BEDROCK environment variable", () => { vi.resetModules(); const { runOnboardingFlow } = await import("./onboarding.js"); - const result = await runOnboardingFlow(undefined, mockAuthConfig); + const result = await runOnboardingFlow(undefined); - expect(result.wasOnboarded).toBe(true); + expect(result).toBe(true); expect(mockConsoleLog).toHaveBeenCalledWith( expect.stringContaining( "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)", @@ -235,7 +239,7 @@ describe("CONTINUE_USE_BEDROCK environment variable", () => { process.stdin.isTTY = false; try { - await runOnboardingFlow(undefined, mockAuthConfig); + await runOnboardingFlow(undefined); // Verify the Bedrock message was NOT called by checking all calls const allCalls = mockConsoleLog.mock.calls.flat(); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 57ed8155f..a8f780591 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -1,16 +1,12 @@ import * as fs from "fs"; import * as path from "path"; -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import { processPromptOrRule } from "./args.js"; -import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; -import { initialize } from "./config.js"; +import { AuthConfig, login } from "./auth/workos.js"; +import { getApiClient } from "./config.js"; +import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; -import { MCPService } from "./services/MCPService.js"; import { getApiKeyValidationError, isValidAnthropicApiKey, @@ -20,15 +16,6 @@ import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); -export interface OnboardingResult { - config: AssistantUnrolled; - llmApi: BaseLlmApi; - model: ModelConfig; - mcpService: MCPService; - apiClient: DefaultApiInterface; - wasOnboarded: boolean; -} - export async function checkHasAcceptableModel( configPath: string, ): Promise { @@ -61,12 +48,10 @@ export async function createOrUpdateConfig(apiKey: string): Promise { export async function runOnboardingFlow( configPath: string | undefined, - authConfig: AuthConfig, -): Promise { +): Promise { // Step 1: Check if --config flag is provided if (configPath !== undefined) { - const result = await initialize(authConfig, configPath); - return { ...result, wasOnboarded: false }; + return false; } // Step 2: Check for CONTINUE_USE_BEDROCK environment variable first (before test env check) @@ -74,8 +59,7 @@ export async function runOnboardingFlow( console.log( chalk.blue("✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"), ); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return true; } // Step 3: Check if we're in a test/CI environment - if so, skip interactive prompts @@ -92,13 +76,11 @@ export async function runOnboardingFlow( console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: false }; + return false; } // Otherwise return a minimal working configuration - const result = await initialize(authConfig, undefined); - return { ...result, wasOnboarded: false }; + return false; } // Step 4: Present user with two options @@ -114,13 +96,8 @@ export async function runOnboardingFlow( ); if (choice === "1" || choice === "") { - const newAuthConfig = await login(); - - const { ensureOrganization } = await import("./auth/workos.js"); - const finalAuthConfig = await ensureOrganization(newAuthConfig); - - const result = await initialize(finalAuthConfig, undefined); - return { ...result, wasOnboarded: true }; + await login(); + return true; } else if (choice === "2") { const apiKey = await question( chalk.white("\nEnter your Anthropic API key: "), @@ -135,89 +112,12 @@ export async function runOnboardingFlow( chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`), ); - const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return true; } else { throw new Error(`Invalid choice. Please select "1" or "2"`); } } -export async function runNormalFlow( - authConfig: AuthConfig, - configPath?: string, - rules?: string[], -): Promise { - // Step 1: Check if --config flag is provided - if (configPath !== undefined) { - // Empty string is invalid and should be treated as an error - if (configPath === "") { - throw new Error( - `Failed to load config from "": Config path cannot be empty`, - ); - } - - try { - const result = await initialize(authConfig, configPath); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch (error) { - // If user explicitly provided --config flag, fail loudly instead of falling back - const errorMessage = - error instanceof Error ? error.message : String(error); - throw new Error( - `Failed to load config from "${configPath}": ${errorMessage}`, - ); - } - } - - // Step 2: If user is logged in, look for first assistant in selected org - if (isAuthenticated()) { - try { - const result = await initialize(authConfig, undefined); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - // Silently ignore errors when loading default assistant - } - } - - // Step 3: Look for local ~/.continue/config.yaml - if (fs.existsSync(CONFIG_PATH)) { - try { - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } catch { - console.log(chalk.yellow("⚠ Invalid config file found")); - } - } - - // Step 4: Look for ANTHROPIC_API_KEY in environment - if (process.env.ANTHROPIC_API_KEY) { - console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); - await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); - console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); - // Inject rules into the config if provided - if (rules && rules.length > 0) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - return { ...result, wasOnboarded: false }; - } - - // Step 5: Fall back to onboarding flow - return runOnboardingFlow(configPath, authConfig); -} - export async function isFirstTime(): Promise { return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete")); } @@ -233,71 +133,31 @@ export async function markOnboardingComplete(): Promise { fs.writeFileSync(flagPath, new Date().toISOString()); } -/** - * Process rules and inject them into the assistant config - * @param config - The assistant config to modify - * @param rules - Array of rule specifications to process and inject - * @returns The modified config with injected rules - */ -async function injectRulesIntoConfig( - config: AssistantUnrolled, - rules: string[], -): Promise { - if (!rules || rules.length === 0) { - return config; - } +export async function initializeWithOnboarding( + authConfig: AuthConfig, + configPath: string | undefined, +) { + const firstTime = await isFirstTime(); - const processedRules: string[] = []; - for (const ruleSpec of rules) { + if (configPath !== undefined) { + // throw an early error is configPath is invalid or has errors try { - const processedRule = await processPromptOrRule(ruleSpec); - processedRules.push(processedRule); - } catch (error: any) { - console.warn( - chalk.yellow( - `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, - ), + await loadConfiguration( + authConfig, + configPath, + getApiClient(authConfig?.accessToken), + ); + } catch (errorMessage) { + throw new Error( + `Failed to load config from "${configPath}": ${errorMessage}`, ); } } - if (processedRules.length === 0) { - return config; + if (!firstTime) return; + + const wasOnboarded = await runOnboardingFlow(configPath); + if (wasOnboarded) { + await markOnboardingComplete(); } - - // Clone the config to avoid mutating the original - const modifiedConfig = { ...config }; - - // Add processed rules to the config's rules array - // Each processed rule is a string, which is a valid Rule type - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [...existingRules, ...processedRules]; - - return modifiedConfig; -} - -export async function initializeWithOnboarding( - authConfig: AuthConfig, - configPath: string | undefined, - rules?: string[], -): Promise { - const firstTime = await isFirstTime(); - - let result: OnboardingResult; - - if (firstTime) { - result = await runOnboardingFlow(configPath, authConfig); - if (result.wasOnboarded) { - await markOnboardingComplete(); - } - } else { - result = await runNormalFlow(authConfig, configPath, rules); - } - - // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) - if (rules && rules.length > 0 && !result.wasOnboarded) { - result.config = await injectRulesIntoConfig(result.config, rules); - } - - return result; } diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 55a4fbfab..738de9a56 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,7 +1,8 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + import { getServiceSync } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/types.js"; import { SERVICE_NAMES } from "../services/types.js"; import { getAllBuiltinTools } from "../tools/index.js"; diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts index 0a3a79653..c79d563d2 100644 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ b/extensions/cli/src/services/AuthService.refactored.ts @@ -1,205 +1,206 @@ -import { - AuthenticatedConfig, - login as doLogin, - logout as doLogout, - ensureOrganization, - isAuthenticated, - listUserOrganizations, - loadAuthConfig, - saveAuthConfig, -} from "../auth/workos.js"; -import { logger } from "../util/logger.js"; +// import { +// AuthenticatedConfig, +// login as doLogin, +// logout as doLogout, +// ensureOrganization, +// isAuthenticated, +// listUserOrganizations, +// loadAuthConfig, +// saveAuthConfig, +// } from "../auth/workos.js"; +// import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; -import { AuthServiceState } from "./types.js"; +// import { BaseService } from "./BaseService.js"; +// import { AuthServiceState } from "./types.js"; -/** - * Service for managing authentication state and operations - * Now extends BaseService for common functionality - */ -export class AuthService extends BaseService { - constructor() { - super("AuthService", { - authConfig: null, - isAuthenticated: false, - }); - } +// /** +// * Service for managing authentication state and operations +// * Now extends BaseService for common functionality +// */ +// export class AuthService extends BaseService { +// constructor() { +// super("AuthService", { +// authConfig: null, +// isAuthenticated: false, +// }); +// } - /** - * Initialize the auth service by loading current config - */ - async doInitialize(): Promise { - const authConfig = loadAuthConfig(); - const authenticated = isAuthenticated(); +// /** +// * Initialize the auth service by loading current config +// */ +// async doInitialize(): Promise { +// const authConfig = loadAuthConfig(); +// const authenticated = isAuthenticated(); - const state: AuthServiceState = { - authConfig, - isAuthenticated: authenticated, - organizationId: authConfig?.organizationId || undefined, - }; +// const state: AuthServiceState = { +// authConfig, +// isAuthenticated: authenticated, +// organizationId: authConfig?.organizationId || undefined, +// }; - logger.debug("AuthService initialized", { - authenticated, - hasConfig: !!authConfig, - orgId: state.organizationId, - }); +// logger.debug("AuthService initialized", { +// authenticated, +// hasConfig: !!authConfig, +// orgId: state.organizationId, +// }); - return state; - } +// return state; +// } - /** - * Perform login flow - */ - async login(): Promise { - logger.debug("Starting login flow"); +// /** +// * Perform login flow +// */ +// async login(): Promise { +// logger.debug("Starting login flow"); - try { - const newAuthConfig = await doLogin(); +// try { +// const newAuthConfig = await doLogin(); - this.setState({ - authConfig: newAuthConfig, - isAuthenticated: true, - organizationId: newAuthConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: newAuthConfig, +// isAuthenticated: true, +// organizationId: newAuthConfig?.organizationId || undefined, +// }); - logger.debug("Login successful", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Login successful", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } catch (error: any) { - logger.error("Login failed:", error); - this.emit("error", error); - throw error; - } - } +// return this.getState(); +// } catch (error: any) { +// logger.error("Login failed:", error); +// this.emit("error", error); +// throw error; +// } +// } - /** - * Perform logout - */ - async logout(): Promise { - logger.debug("Logging out"); +// /** +// * Perform logout +// */ +// async logout(): Promise { +// logger.debug("Logging out"); - doLogout(); +// doLogout(); - this.setState({ - authConfig: null, - isAuthenticated: false, - organizationId: undefined, - }); +// this.setState({ +// authConfig: null, +// isAuthenticated: false, +// organizationId: undefined, +// }); - logger.debug("Logout complete"); - return this.getState(); - } +// logger.debug("Logout complete"); +// return this.getState(); +// } - /** - * Ensure organization is selected, prompting if necessary - */ - async ensureOrganization( - isHeadless: boolean = false, - ): Promise { - if (!this.currentState.authConfig) { - throw new Error("Not authenticated - cannot ensure organization"); - } +// /** +// * Ensure organization is selected, prompting if necessary +// */ +// async ensureOrganization( +// isHeadless: boolean = false, +// ): Promise { +// if (!this.currentState.authConfig) { +// throw new Error("Not authenticated - cannot ensure organization"); +// } - logger.debug("Ensuring organization is selected", { - currentOrgId: this.currentState.organizationId, - isHeadless, - }); +// logger.debug("Ensuring organization is selected", { +// currentOrgId: this.currentState.organizationId, +// isHeadless, +// }); - const updatedConfig = await ensureOrganization( - this.currentState.authConfig, - isHeadless, - ); +// const updatedConfig = await ensureOrganization( +// this.currentState.authConfig, +// isHeadless, +// ); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: updatedConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: updatedConfig?.organizationId || undefined, +// }); - logger.debug("Organization ensured", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Organization ensured", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Switch to a different organization - */ - async switchOrganization( - organizationId: string | null, - ): Promise { - if ( - !this.currentState.authConfig || - !("userId" in this.currentState.authConfig) - ) { - throw new Error( - "Not authenticated with file-based auth - cannot switch organizations", - ); - } +// /** +// * Switch to a different organization +// */ +// async switchOrganization( +// organizationId: string | null, +// ): Promise { +// if ( +// !this.currentState.authConfig || +// !("userId" in this.currentState.authConfig) +// ) { +// throw new Error( +// "Not authenticated with file-based auth - cannot switch organizations", +// ); +// } - logger.debug("Switching organization", { - from: this.currentState.organizationId, - to: organizationId, - }); +// logger.debug("Switching organization", { +// from: this.currentState.organizationId, +// to: organizationId, +// }); - const authenticatedConfig = this.currentState - .authConfig as AuthenticatedConfig; +// const authenticatedConfig = this.currentState +// .authConfig as AuthenticatedConfig; - const updatedConfig: AuthenticatedConfig = { - ...authenticatedConfig, - organizationId, - }; +// const updatedConfig: AuthenticatedConfig = { +// ...authenticatedConfig, +// organizationId, +// }; - saveAuthConfig(updatedConfig); +// saveAuthConfig(updatedConfig); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: organizationId || undefined, +// }); - logger.debug("Organization switched", { - newOrgId: this.currentState.organizationId, - }); +// logger.debug("Organization switched", { +// newOrgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Get available organizations for the current user - */ - async getAvailableOrganizations(): Promise< - { id: string; name: string }[] | null - > { - if (!this.currentState.isAuthenticated) { - return null; - } +// /** +// * Get available organizations for the current user +// */ +// async getAvailableOrganizations(): Promise< +// { id: string; name: string }[] | null +// > { +// if (!this.currentState.isAuthenticated) { +// return null; +// } - try { - return await listUserOrganizations(); - } catch (error: any) { - logger.error("Failed to list organizations:", error); - this.emit("error", error); - return null; - } - } +// try { +// return await listUserOrganizations(); +// } catch (error: any) { +// logger.error("Failed to list organizations:", error); +// this.emit("error", error); +// return null; +// } +// } - /** - * Check if the current user has multiple organizations available - */ - async hasMultipleOrganizations(): Promise { - const orgs = await this.getAvailableOrganizations(); - return orgs !== null && orgs.length > 0; - } +// /** +// * Check if the current user has multiple organizations available +// */ +// async hasMultipleOrganizations(): Promise { +// const orgs = await this.getAvailableOrganizations(); +// return orgs !== null && orgs.length > 0; +// } - /** - * Refresh auth state from disk (useful after external changes) - */ - async refresh(): Promise { - logger.debug("Refreshing auth state from disk"); - return this.reload(); - } -} +// /** +// * Refresh auth state from disk (useful after external changes) +// */ +// async refresh(): Promise { +// logger.debug("Refreshing auth state from disk"); +// return this.reload(); +// } +// } +export {}; diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 84d2ba5ae..dbb313fb7 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -12,7 +12,7 @@ import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { SERVICE_NAMES } from "./types.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; describe("ConfigService", () => { let service: ConfigService; @@ -23,7 +23,12 @@ describe("ConfigService", () => { systemMessage: "Test system message", } as any; const mockApiClient = { get: vi.fn(), post: vi.fn() }; - + const mockWorkflowState: WorkflowServiceState = { + slug: null, + workflowFile: null, + workflowModelName: null, + workflowService: null, + }; beforeEach(() => { vi.clearAllMocks(); service = new ConfigService(); @@ -36,12 +41,13 @@ describe("ConfigService", () => { source: { type: "cli-flag", path: "/path/to/config.yaml" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - "/path/to/config.yaml", - "org-123", - mockApiClient as any, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/path/to/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); expect(state).toEqual({ config: mockConfig as any, @@ -55,12 +61,13 @@ describe("ConfigService", () => { source: { type: "default-agent" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockApiClient as any, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); expect(state).toEqual({ config: mockConfig as any, @@ -82,18 +89,20 @@ describe("ConfigService", () => { vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); - const state = await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockApiClient as any, - { rule: ["rule1", "rule2"] }, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + injectedConfigOptions: { rule: ["rule1", "rule2"] }, + }); // Verify configEnhancer was called with the right parameters expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( mockConfig, { rule: ["rule1", "rule2"] }, + mockWorkflowState, ); expect(state.config).toEqual(expectedConfig); @@ -107,12 +116,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Switch to new config const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -136,12 +146,13 @@ describe("ConfigService", () => { }); test("should handle switch config errors", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); vi.mocked(configLoader.loadConfiguration).mockRejectedValue( new Error("Config not found"), @@ -165,12 +176,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Modify mock to return updated config const updatedConfig = { ...mockConfig, name: "updated-assistant" } as any; @@ -197,12 +209,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "default-agent" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); await expect( service.reload( @@ -221,12 +234,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Mock service container vi.mocked(workos.loadAuthConfig).mockReturnValue({ @@ -263,12 +277,13 @@ describe("ConfigService", () => { }); test("should handle missing API client", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); vi.mocked(workos.loadAuthConfig).mockReturnValue({ accessToken: "token", @@ -286,7 +301,11 @@ describe("ConfigService", () => { describe("getDependencies()", () => { test("should declare auth and apiClient dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "apiClient"]); + expect(service.getDependencies()).toEqual([ + "auth", + "apiClient", + "workflow", + ]); }); }); @@ -296,12 +315,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); const listener = vi.fn(); service.on("stateChanged", listener); @@ -329,12 +349,13 @@ describe("ConfigService", () => { }); test("should emit error on switch failure", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); const errorListener = vi.fn(); service.on("error", errorListener); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 149977edb..72f88540f 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -11,8 +11,17 @@ import { ApiClientServiceState, ConfigServiceState, SERVICE_NAMES, + WorkflowServiceState, } from "./types.js"; +interface ConfigServiceInit { + authConfig: AuthConfig; + configPath: string | undefined; + _organizationId: string | null; + apiClient: DefaultApiInterface; + workflowState: WorkflowServiceState; + injectedConfigOptions?: BaseCommandOptions; +} /** * Service for managing configuration state and operations * Handles loading configs from files or assistant slugs @@ -32,19 +41,23 @@ export class ConfigService * Declare dependencies on other services */ getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + return [ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.WORKFLOW, + ]; } /** * Initialize the config service */ - async doInitialize( - authConfig: AuthConfig, - configPath: string | undefined, - _organizationId: string | null, - apiClient: DefaultApiInterface, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { + async doInitialize({ + apiClient, + authConfig, + configPath, + workflowState, + injectedConfigOptions, + }: ConfigServiceInit): Promise { // Use the new streamlined config loader const { loadConfiguration } = await import("../configLoader.js"); const result = await loadConfiguration(authConfig, configPath, apiClient); @@ -53,12 +66,13 @@ export class ConfigService // Apply injected config if provided if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) + workflowState?.workflowFile || + (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) ) { config = await configEnhancer.enhanceConfig( config, injectedConfigOptions, + workflowState, ); logger.debug("Applied injected configuration"); diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts index 518ffe9c4..9482699e2 100644 --- a/extensions/cli/src/services/FileIndexService.ts +++ b/extensions/cli/src/services/FileIndexService.ts @@ -2,6 +2,7 @@ import { fdir } from "fdir"; import { AsyncFzf, FzfResultItem } from "fzf"; import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; +import { isGitRepo } from "../util/git.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; @@ -131,10 +132,15 @@ export class FileIndexService extends BaseService { const currentDir = process.cwd(); logger.debug(`Starting file index in directory: ${currentDir}`); + // Determine max depth based on git repository status + const inGitRepo = isGitRepo(); + const maxDepth = inGitRepo ? 10 : 3; + // Create file indexing promise const fileIndexPromise = new fdir() .withFullPaths() .withRelativePaths() + .withMaxDepth(maxDepth) .filter((path) => { // Use the helper function that implements original FILE_PATTERNS logic return this.shouldIncludeFile(path); diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 069171fef..08190e267 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -1,6 +1,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { + SSEClientTransport, + SseError, +} from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { @@ -21,6 +24,14 @@ import { SERVICE_NAMES, } from "./types.js"; +function is401Error(error: unknown) { + return ( + (error instanceof SseError && error.code === 401) || + (error instanceof Error && error.message.includes("401")) || + (error instanceof Error && error.message.includes("Unauthorized")) + ); +} + interface ServerConnection extends MCPConnectionInfo { client: Client | null; } @@ -366,15 +377,29 @@ export class MCPService url: serverConfig.url, }); - if (serverConfig.type === "sse") { - const transport = this.constructSseTransport(serverConfig); - await client.connect(transport, {}); - } else if (serverConfig.type === "streamable-http") { - const transport = this.constructHttpTransport(serverConfig); - await client.connect(transport, {}); - } else if (serverConfig.type) { - throw new Error(`Unsupported transport type: ${serverConfig.type}`); - } else { + try { + if (serverConfig.type === "sse") { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } else if (serverConfig.type === "streamable-http") { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } + } catch (error: unknown) { + // on authorization error, use "mcp-remote" with stdio transport to connect + if (is401Error(error)) { + const transport = this.constructStdioTransport({ + name: serverConfig.name, + command: "npx", + args: ["-y", "mcp-remote", serverConfig.url], + }); + await client.connect(transport, {}); + } else { + throw error; + } + } + + if (typeof serverConfig.type === "undefined") { try { const transport = this.constructHttpTransport(serverConfig); await client.connect(transport, {}); @@ -394,6 +419,10 @@ export class MCPService ); } } + } else if ( + !["streamable-http", "sse", "stdio"].includes(serverConfig.type) + ) { + throw new Error(`Unsupported transport type: ${serverConfig.type}`); } } @@ -403,6 +432,14 @@ export class MCPService private constructSseTransport( serverConfig: SseMcpServer, ): SSEClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + return new SSEClientTransport(new URL(serverConfig.url), { eventSourceInit: { fetch: (input, init) => @@ -410,18 +447,26 @@ export class MCPService ...init, headers: { ...init?.headers, - ...serverConfig.requestOptions?.headers, + ...headers, }, }), }, - requestInit: { headers: serverConfig.requestOptions?.headers }, + requestInit: { headers }, }); } private constructHttpTransport( serverConfig: HttpMcpServer, ): StreamableHTTPClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { - requestInit: { headers: serverConfig.requestOptions?.headers }, + requestInit: { headers }, }); } private constructStdioTransport( diff --git a/extensions/cli/src/services/ModeService.test.ts b/extensions/cli/src/services/ModeService.test.ts deleted file mode 100644 index 974826377..000000000 --- a/extensions/cli/src/services/ModeService.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { beforeEach, afterEach, describe, expect, vi, test } from "vitest"; - -import { ModeService } from "./ModeService.js"; - -describe("ModeService", () => { - let modeService: ModeService; - - beforeEach(() => { - // Reset singleton instance for each test - (ModeService as any).instance = undefined; - modeService = ModeService.getInstance(); - }); - - afterEach(() => { - // Clean up singleton instance - (ModeService as any).instance = undefined; - }); - - describe("State Management", () => { - test("should initialize with normal mode by default", async () => { - const state = await modeService.initialize({}); - - expect(state).toEqual({ - mode: "normal", - toolPermissionService: expect.any(Object), - }); - expect(modeService.getCurrentMode()).toBe("normal"); - }); - - test("should convert readonly flag to plan mode", async () => { - const state = await modeService.initialize({ readonly: true }); - - expect(state.mode).toBe("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - }); - - test("should convert auto flag to auto mode", async () => { - const state = await modeService.initialize({ auto: true }); - - expect(state.mode).toBe("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); - }); - - test("should initialize tool permission service with flags", async () => { - const state = await modeService.initialize({ - allow: ["testTool"], - exclude: ["badTool"], - }); - - const toolPermissionService = state.toolPermissionService; - expect(toolPermissionService).toBeDefined(); - expect(toolPermissionService.getState()).toBeDefined(); - expect(toolPermissionService.getCurrentMode()).toBe("normal"); - }); - }); - - describe("switchMode()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should switch from normal to plan mode", () => { - expect(modeService.getCurrentMode()).toBe("normal"); - - modeService.switchMode("plan"); - - expect(modeService.getCurrentMode()).toBe("plan"); - expect(modeService.getState().mode).toBe("plan"); - }); - - test("should switch from plan to auto mode", () => { - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - - modeService.switchMode("auto"); - - expect(modeService.getCurrentMode()).toBe("auto"); - expect(modeService.getState().mode).toBe("auto"); - }); - - test("should switch back to normal mode", () => { - modeService.switchMode("plan"); - modeService.switchMode("normal"); - - expect(modeService.getCurrentMode()).toBe("normal"); - expect(modeService.getState().mode).toBe("normal"); - }); - - test("should update tool permission service when switching modes", () => { - const toolPermissionService = modeService.getToolPermissionService(); - const initialState = toolPermissionService.getState(); - - modeService.switchMode("auto"); - const newState = toolPermissionService.getState(); - - expect(newState.currentMode).toBe("auto"); - expect(newState.permissions.policies.length).toBeGreaterThan(0); - expect(newState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - }); - - test("should handle multiple mode switches correctly", () => { - // Start in normal - expect(modeService.getCurrentMode()).toBe("normal"); - - // Switch to plan - modeService.switchMode("plan"); - const planState = modeService.getToolPermissionService().getState(); - expect(planState.permissions.policies).toContainEqual({ - tool: "Write", - permission: "exclude", - }); - - // Switch to auto - modeService.switchMode("auto"); - const autoState = modeService.getToolPermissionService().getState(); - expect(autoState.permissions.policies).toHaveLength(1); - expect(autoState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - - // Back to normal - modeService.switchMode("normal"); - const normalState = modeService.getToolPermissionService().getState(); - expect(normalState.currentMode).toBe("normal"); - }); - }); - - describe("getAvailableModes()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should return all available modes with descriptions", () => { - const modes = modeService.getAvailableModes(); - expect(modes).toHaveLength(3); - - const modeNames = modes.map((m) => m.mode); - expect(modeNames).toContain("normal"); - expect(modeNames).toContain("plan"); - expect(modeNames).toContain("auto"); - - // Check that all modes have descriptions - modes.forEach((mode) => { - expect(mode.description).toBeDefined(); - expect(mode.description.length).toBeGreaterThan(0); - }); - }); - }); - - describe("Singleton Behavior", () => { - test("should return the same instance", () => { - const instance1 = ModeService.getInstance(); - const instance2 = ModeService.getInstance(); - expect(instance1).toBe(instance2); - }); - - test("should maintain state across getInstance calls", async () => { - const instance1 = ModeService.getInstance(); - await instance1.initialize({}); - instance1.switchMode("plan"); - - const instance2 = ModeService.getInstance(); - expect(instance2.getCurrentMode()).toBe("plan"); - }); - }); - - describe("isReady()", () => { - test("should always return true for ModeService", () => { - // ModeService is always ready since it's a singleton - expect(modeService.isReady()).toBe(true); - }); - }); - - describe("Event Emission", () => { - let modeChangeListener: ReturnType; - let stateChangeListener: ReturnType; - - beforeEach(async () => { - await modeService.initialize({}); - modeChangeListener = vi.fn(); - stateChangeListener = vi.fn(); - modeService.on("modeChanged", modeChangeListener); - modeService.on("stateChanged", stateChangeListener); - }); - - afterEach(() => { - modeService.off("modeChanged", modeChangeListener); - modeService.off("stateChanged", stateChangeListener); - }); - - test("should emit modeChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should emit stateChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(stateChangeListener).toHaveBeenCalledWith( - expect.objectContaining({ mode: "plan" }), - expect.objectContaining({ mode: "normal" }), - ); - }); - - test("should emit event with correct previous and new modes", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("auto"); - - expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - expect(stateChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should not emit event when switching to same mode", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("plan"); - - expect(modeChangeListener).not.toHaveBeenCalled(); - // stateChanged might still be called due to setState, but modeChanged should not - }); - }); - - describe("Integration with ToolPermissionService", () => { - beforeEach(async () => { - await modeService.initialize({ - allow: ["Read"], - exclude: ["dangerous_tool"], - }); - }); - - test("should pass initialization args to ToolPermissionService", () => { - const toolService = modeService.getToolPermissionService(); - const state = toolService.getState(); - - // The state should have processed the allow/exclude rules - expect(state.permissions.policies).toBeDefined(); - expect(state.currentMode).toBe("normal"); - }); - - test("should maintain ToolPermissionService reference", () => { - const toolService1 = modeService.getToolPermissionService(); - const toolService2 = modeService.getToolPermissionService(); - - expect(toolService1).toBe(toolService2); - }); - }); -}); diff --git a/extensions/cli/src/services/ModeService.ts b/extensions/cli/src/services/ModeService.ts deleted file mode 100644 index b066af870..000000000 --- a/extensions/cli/src/services/ModeService.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { PermissionMode } from "../permissions/types.js"; -import { logger } from "../util/logger.js"; - -import { BaseService } from "./BaseService.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; - -export interface ModeServiceState { - mode: PermissionMode; - toolPermissionService: ToolPermissionService; -} - -/** - * Global service for managing permission modes - * Provides a singleton interface for mode switching - */ -export class ModeService extends BaseService { - private static instance: ModeService; - - private constructor() { - const toolPermissionService = new ToolPermissionService(); - super("ModeService", { - mode: "normal", - toolPermissionService, - }); - - // Increase max listeners since ModeService is a singleton that can have - // multiple subscribers (UI components, tests, etc.) - this.setMaxListeners(100); - } - - public static getInstance(): ModeService { - if (!ModeService.instance) { - ModeService.instance = new ModeService(); - } - return ModeService.instance; - } - - /** - * Initialize the mode service with command line arguments - */ - async doInitialize(args: { - readonly?: boolean; - auto?: boolean; - allow?: string[]; - ask?: string[]; - exclude?: string[]; - isHeadless?: boolean; - }): Promise { - // Convert legacy flags to mode - let mode: PermissionMode = "normal"; - if (args.readonly) { - mode = "plan"; // Legacy flag maps directly to plan mode - } else if (args.auto) { - mode = "auto"; // Auto flag maps to auto mode - } - - this.currentState.toolPermissionService.initializeSync({ - allow: args.allow, - ask: args.ask, - exclude: args.exclude, - mode, - isHeadless: args.isHeadless, - }); - - logger.debug(`ModeService initialized with mode: ${mode}`); - - return { - mode, - toolPermissionService: this.currentState.toolPermissionService, - }; - } - - /** - * Switch to a different mode - */ - public switchMode(mode: PermissionMode): void { - const previousMode = this.currentState.mode; - this.currentState.toolPermissionService.switchMode(mode); - - this.setState({ mode }); - - logger.info(`Switched to ${mode} mode`); - - // Emit mode change event for immediate UI updates - if (previousMode !== mode) { - this.emit("modeChanged", mode, previousMode); - } - } - - /** - * Get the current mode - */ - public getCurrentMode(): PermissionMode { - return this.currentState.mode; - } - - /** - * Get the tool permission service instance - */ - public getToolPermissionService(): ToolPermissionService { - return this.currentState.toolPermissionService; - } - - /** - * Get available modes with descriptions - */ - public getAvailableModes(): Array<{ - mode: PermissionMode; - description: string; - }> { - return [ - { - mode: "normal", - description: "Default mode - follows configured permission policies", - }, - { - mode: "plan", - description: "Planning mode - only allow read-only tools for analysis", - }, - { - mode: "auto", - description: "Automatically allow all tools without asking", - }, - ]; - } - - /** - * Override cleanup to properly clean up nested ToolPermissionService - */ - override async cleanup(): Promise { - await this.currentState.toolPermissionService.cleanup(); - await super.cleanup(); - } - - /** - * Override isReady since this is a singleton with immediate availability - */ - override isReady(): boolean { - return true; - } -} - -// Export singleton instance -export const modeService = ModeService.getInstance(); diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index 9dff62d2f..b52414558 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -1,12 +1,12 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { describe, expect, beforeEach, vi, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock dependencies before imports vi.mock("../config.js"); vi.mock("../auth/workos.js"); -import { AuthConfig } from "../auth/workos.js"; import * as workos from "../auth/workos.js"; +import { AuthConfig } from "../auth/workos.js"; import * as config from "../config.js"; import { ModelService } from "./ModelService.js"; @@ -357,8 +357,8 @@ describe("ModelService", () => { }); describe("getDependencies()", () => { - test("should declare auth and config dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "config"]); + test("should declare auth, config, and workflow dependencies", () => { + expect(service.getDependencies()).toEqual(["auth", "config", "workflow"]); }); }); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 313f2afc1..e09c65d49 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,7 +5,7 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; +import { ModelServiceState, WorkflowServiceState } from "./types.js"; /** * Service for managing LLM and model state @@ -32,7 +32,7 @@ export class ModelService * Declare dependencies on other services */ getDependencies(): string[] { - return ["auth", "config"]; + return ["auth", "config", "workflow"]; } /** @@ -41,6 +41,7 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, + workflowServiceState?: WorkflowServiceState, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -55,16 +56,29 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - // Check if we have a persisted model name and use it if valid - const persistedModelName = getModelName(authConfig); - if (persistedModelName) { + let preferredModelName: string | null | undefined = null; + let modelSource = "default"; + + // Priority = workflow -> last selected model + if (workflowServiceState?.workflowModelName) { + preferredModelName = workflowServiceState.workflowModelName; + modelSource = "workflow"; + } else { + preferredModelName = getModelName(authConfig); + if (preferredModelName) { + modelSource = "persisted"; + } + } + + // Try to use the preferred model (workflow or persisted) + if (preferredModelName) { // During initialization, we need to check against availableModels directly const modelIndex = this.availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; - return name === persistedModelName; + return name === preferredModelName; }); if (modelIndex === -1) { - // Model name not found, use default model selection + // Preferred model not found, use default model selection const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, @@ -73,20 +87,20 @@ export class ModelService authConfig, }; } else { - // Use the persisted model - but we need to handle initialization specially + // Use the preferred model - but we need to handle initialization specially // During init, currentState isn't set yet, so switchModel would fail // Instead, we'll manually switch here const selectedModel = this.availableModels[modelIndex]; - logger.debug("Using persisted model during initialization", { + logger.debug(`Using ${modelSource} model during initialization`, { modelIndex, provider: selectedModel.provider, name: (selectedModel as any).name || "unnamed", + modelSource, }); const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { - throw new Error("Failed to initialize LLM with persisted model"); + throw new Error(`Failed to initialize LLM with ${modelSource} model`); } return { diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts new file mode 100644 index 000000000..2d04c58ab --- /dev/null +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -0,0 +1,254 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { AuthConfig } from "../auth/workos.js"; +import * as config from "../config.js"; + +import { ModelService } from "./ModelService.js"; +import { WorkflowServiceState } from "./types.js"; + +// Mock the dependencies +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(() => null), +})); + +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(() => ({ provider: "test" })), + getLlmApi: vi.fn(() => [ + { provider: "test" }, + { provider: "test", name: "default-model" }, + ]), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + }, +})); + +describe("ModelService workflow model prioritization", () => { + let modelService: ModelService; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthConfig; + let mockModels: ModelConfig[]; + + beforeEach(() => { + modelService = new ModelService(); + + mockModels = [ + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + { provider: "openai", name: "gpt-4" } as ModelConfig, + { provider: "anthropic", name: "claude-3-haiku" } as ModelConfig, + ]; + + mockAssistant = { + models: mockModels, + } as AssistantUnrolled; + + mockAuthConfig = {} as AuthConfig; + + // Reset mocks + vi.clearAllMocks(); + }); + + it("should prioritize workflow model over default when workflow file has model specified", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "gpt-4", + prompt: "Test workflow", + }, + slug: "test/workflow", + workflowModelName: "gpt-4", + workflowService: null, + }; + + // Mock createLlmApi to return different models based on the selected model + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + // Should have called createLlmApi with the workflow-specified model + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); + + it("should fall back to persisted model when no workflow model is specified", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + prompt: "Test workflow", + // No model specified + }, + slug: "test/workflow", + workflowModelName: null, + workflowService: null, + }; + + // Mock getModelName to return a persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-sonnet"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "claude-3-sonnet" }), + mockAuthConfig, + ); + }); + + it("should fall back to default model when workflow model is not available", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "non-existent-model", // Model not in available models + prompt: "Test workflow", + }, + slug: "test/workflow", + workflowModelName: "non-existent-model", + workflowService: null, + }; + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + // Should have fallen back to getLlmApi + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should use default model when no workflow file exists", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: null, + }; + + // Make sure getModelName returns null (no persisted model) + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue(null); + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should prioritize workflow model over persisted model", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "gpt-4", // Workflow specifies gpt-4 + prompt: "Test workflow", + }, + slug: "test/workflow", + workflowModelName: "gpt-4", + workflowService: null, + }; + + // Mock getModelName to return a different persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-haiku"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + // Should use workflow model (gpt-4), not persisted model (claude-3-haiku) + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); +}); diff --git a/extensions/cli/src/services/ServiceContainer.ts b/extensions/cli/src/services/ServiceContainer.ts index adaaa1072..d12acf351 100644 --- a/extensions/cli/src/services/ServiceContainer.ts +++ b/extensions/cli/src/services/ServiceContainer.ts @@ -2,7 +2,7 @@ import { EventEmitter } from "events"; import { logger } from "../util/logger.js"; -import { ServiceResult, ServiceState } from "./types.js"; +import { type ServiceResult, type ServiceState } from "./types.js"; /** * Central service container that manages service lifecycle and dependencies diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index a17894ee9..d925c88b1 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { modeService } from "./ModeService.js"; import { SystemMessageService } from "./SystemMessageService.js"; +import { services } from "./index.js"; +const toolPermissionService = services.toolPermissions; + // Mock the systemMessage module vi.mock("../systemMessage.js", () => ({ constructSystemMessage: vi.fn(), @@ -71,35 +73,16 @@ describe("SystemMessageService", () => { constructSystemMessageMock.mockResolvedValue("Test system message"); await service.initialize(config); - const message = await service.getSystemMessage(); + const message = await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", // Default mode ["rule1"], "json", true, - "normal", // Default mode ); expect(message).toBe("Test system message"); }); - - it("should use updated mode when mode changes", async () => { - constructSystemMessageMock.mockResolvedValue("Updated system message"); - - await service.initialize({}); - - // Simulate mode change - modeService.emit("modeChanged", "plan", "normal"); - - const message = await service.getSystemMessage(); - - expect(constructSystemMessageMock).toHaveBeenCalledWith( - undefined, - undefined, - undefined, - "plan", - ); - expect(message).toBe("Updated system message"); - }); }); describe("updateConfig", () => { @@ -114,13 +97,13 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule1"], "json", false, - "normal", ); }); @@ -135,42 +118,17 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule2", "rule3"], "json", undefined, - "normal", ); }); }); - describe("mode tracking", () => { - it("should track current mode from ModeService", async () => { - await service.initialize({}); - - expect(service.getCurrentMode()).toBe("normal"); - - // Simulate mode change - modeService.emit("modeChanged", "auto", "normal"); - - expect(service.getCurrentMode()).toBe("auto"); - }); - - it("should initialize with current mode from ModeService", async () => { - // Mock modeService.getCurrentMode - vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); - - const newService = new SystemMessageService(); - await newService.initialize({}); - - expect(newService.getCurrentMode()).toBe("plan"); - - await newService.cleanup(); - }); - }); - describe("error handling", () => { it("should handle constructSystemMessage errors gracefully", async () => { constructSystemMessageMock.mockRejectedValue( @@ -179,7 +137,7 @@ describe("SystemMessageService", () => { await service.initialize({}); - await expect(service.getSystemMessage()).rejects.toThrow( + await expect(service.getSystemMessage("normal")).rejects.toThrow( "Failed to construct", ); }); diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts index 2711f6990..44ae3098c 100644 --- a/extensions/cli/src/services/SystemMessageService.ts +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -3,7 +3,7 @@ import { constructSystemMessage } from "../systemMessage.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; -import { modeService } from "./ModeService.js"; +import { SERVICE_NAMES } from "./types.js"; export interface SystemMessageServiceState { additionalRules?: string[]; @@ -16,26 +16,8 @@ export interface SystemMessageServiceState { * Provides fresh system messages that reflect current mode and configuration */ export class SystemMessageService extends BaseService { - private currentMode: PermissionMode = "normal"; - constructor() { super("SystemMessageService", {}); - - // Listen to mode changes from ModeService - this.setupModeListener(); - } - - /** - * Set up listener for mode changes - */ - private setupModeListener(): void { - modeService.on("modeChanged", (newMode: PermissionMode) => { - logger.debug(`SystemMessageService: Mode changed to ${newMode}`); - this.currentMode = newMode; - }); - - // Initialize current mode - this.currentMode = modeService.getCurrentMode(); } /** @@ -64,24 +46,28 @@ export class SystemMessageService extends BaseService /** * Get a fresh system message with current mode and configuration */ - public async getSystemMessage(): Promise { + public async getSystemMessage(currentMode: PermissionMode): Promise { const { additionalRules, format, headless } = this.currentState; const systemMessage = await constructSystemMessage( + currentMode, additionalRules, format, headless, - this.currentMode, ); logger.debug("Generated fresh system message", { - mode: this.currentMode, + mode: currentMode, messageLength: systemMessage.length, }); return systemMessage; } + getDependencies(): string[] { + return [SERVICE_NAMES.TOOL_PERMISSIONS]; + } + /** * Update configuration that affects system message */ @@ -93,14 +79,4 @@ export class SystemMessageService extends BaseService logger.debug("SystemMessageService config updated", config); } - - /** - * Get the current mode being used for system messages - */ - public getCurrentMode(): PermissionMode { - return this.currentMode; - } } - -// Export singleton instance -export const systemMessageService = new SystemMessageService(); diff --git a/extensions/cli/src/services/ToolPermissionService.test.ts b/extensions/cli/src/services/ToolPermissionService.test.ts index 2d62ba2cf..b11e506b2 100644 --- a/extensions/cli/src/services/ToolPermissionService.test.ts +++ b/extensions/cli/src/services/ToolPermissionService.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, beforeEach, vi } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock modules vi.mock("../permissions/permissionsYamlLoader.js"); @@ -30,6 +30,7 @@ describe("ToolPermissionService", () => { currentMode: "normal", isHeadless: false, modePolicyCount: 0, + workflowPolicyCount: 0, }); }); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 8271b044e..a6fa5db1e 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,3 +1,5 @@ +import { parseWorkflowTools } from "@continuedev/config-yaml"; + import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; import { @@ -7,20 +9,34 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; + +export interface InitializeToolServiceOverrides { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + mode?: PermissionMode; + isHeadless?: boolean; +} export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; isHeadless: boolean; modePolicyCount?: number; // Track how many policies are from mode vs other sources + workflowPolicyCount?: number; originalPolicies?: ToolPermissions; // Store original policies when switching modes } /** * Service for managing tool permissions with a single source of truth */ -export class ToolPermissionService extends BaseService { +export class ToolPermissionService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("ToolPermissionService", { permissions: { policies: [] }, @@ -30,6 +46,74 @@ export class ToolPermissionService extends BaseService, + ): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.currentState); + } + + /** + * Declare dependencies on other services + */ + getDependencies(): string[] { + return [SERVICE_NAMES.WORKFLOW]; + } + + /** + * Generate workflow-specific policies if a workflow is active + */ + private generateWorkflowPolicies( + workflowServiceState?: WorkflowServiceState, + ): undefined | ToolPermissionPolicy[] { + if (!workflowServiceState?.workflowFile?.tools) { + return undefined; + } + + const parsedTools = parseWorkflowTools( + workflowServiceState.workflowFile.tools, + ); + if (parsedTools.tools.length === 0) { + return undefined; + } + const policies: ToolPermissionPolicy[] = []; + + for (const toolRef of parsedTools.tools) { + if (toolRef.mcpServer) { + if (toolRef.toolName) { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`, + permission: "allow", + }); + } else { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:*`, + permission: "allow", + }); + } + } else if (toolRef.toolName) { + policies.push({ tool: toolRef.toolName, permission: "allow" }); + } + } + + if (policies.length > 0) { + logger.debug(`Generated ${policies.length} workflow tool policies`); + } + + if (parsedTools.allBuiltIn) { + policies.push({ tool: "*", permission: "allow" }); + policies.push({ tool: "mcp:*", permission: "exclude" }); + } else { + policies.push({ tool: "*", permission: "exclude" }); + } + + return policies; + } + /** * Generate mode-specific policies based on the current mode */ @@ -57,7 +141,7 @@ export class ToolPermissionService extends BaseService { - // Ensure permissions.yaml exists before loading + async doInitialize( + runtimeOverrides?: InitializeToolServiceOverrides, + workflowServiceState?: WorkflowServiceState, + ): Promise { await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides); + return this.initializeSync(runtimeOverrides, workflowServiceState); } /** @@ -173,13 +254,12 @@ export class ToolPermissionService extends BaseService { + return [ + { + mode: "normal", + description: "Default mode - follows configured permission policies", + }, + { + mode: "plan", + description: "Planning mode - only allow read-only tools for analysis", + }, + { + mode: "auto", + description: "Automatically allow all tools without asking", + }, + ]; + } } diff --git a/extensions/cli/src/services/WorkflowService.test.ts b/extensions/cli/src/services/WorkflowService.test.ts new file mode 100644 index 000000000..f88e6ed9c --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.test.ts @@ -0,0 +1,292 @@ +import { Mock, vi } from "vitest"; + +import { workflowProcessor } from "../hubLoader.js"; + +import { WorkflowService } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + HubPackageProcessor: vi.fn(), + workflowProcessor: { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +describe("WorkflowService", () => { + let service: WorkflowService; + let mockLoadPackageFromHub: any; + + beforeEach(async () => { + vi.clearAllMocks(); + service = new WorkflowService(); + + // Get the mock function + const hubLoaderModule = await import("../hubLoader.js"); + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + }); + + describe("initialization", () => { + it("should initialize with inactive state when no workflow provided", async () => { + const state = await service.initialize(); + + expect(state).toEqual({ + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: service, + }); + }); + + it("should initialize with inactive state when workflow is empty string", async () => { + const state = await service.initialize(""); + + expect(state).toEqual({ + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: service, + }); + }); + + it("should reject invalid workflow slug format", async () => { + const state = await service.initialize("invalid-slug"); + + expect(state).toEqual({ + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: service, + }); + + // Should not call loadPackageFromHub with invalid slug + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should reject workflow slug with too many parts", async () => { + const state = await service.initialize("owner/package/extra"); + + expect(state).toEqual({ + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: service, + }); + + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should load valid workflow successfully", async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + slug: "owner/package", + workflowModelName: null, + workflowService: service, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: null, + slug: null, + workflowModelName: null, + workflowService: service, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle minimal workflow file", async () => { + const mockWorkflowFile = { + name: "Minimal Workflow", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/minimal"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + slug: "owner/minimal", + workflowModelName: null, + workflowService: service, + }); + }); + }); + + describe("state getters", () => { + beforeEach(async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/package"); + }); + + it("should return workflow state", () => { + const state = service.getState(); + expect(state.workflowFile?.name).toBe("Test Workflow"); + expect(state.slug).toBe("owner/package"); + expect(state.workflowFile?.model).toBe("gpt-4"); + expect(state.workflowFile?.tools).toBe("bash,read,write"); + expect(state.workflowFile?.rules).toBe("Be helpful"); + expect(state.workflowFile?.prompt).toBe("You are a helpful assistant."); + }); + }); + + describe("inactive workflow state", () => { + beforeEach(() => { + service.initialize(); + }); + + it("should return inactive state when no workflow", () => { + const state = service.getState(); + expect(state.workflowFile).toBeNull(); + expect(state.slug).toBeNull(); + }); + }); + + describe("partial workflow data", () => { + it("should handle workflow with only name and prompt", async () => { + const mockWorkflowFile = { + name: "Simple Workflow", + prompt: "Simple prompt", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/simple"); + + const state = service.getState(); + expect(state.workflowFile?.model).toBeUndefined(); + expect(state.workflowFile?.tools).toBeUndefined(); + expect(state.workflowFile?.rules).toBeUndefined(); + expect(state.workflowFile?.prompt).toBe("Simple prompt"); + }); + + it("should handle workflow with empty prompt", async () => { + const mockWorkflowFile = { + name: "Empty Prompt Workflow", + model: "gpt-3.5-turbo", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/empty"); + + const state = service.getState(); + expect(state.workflowFile?.model).toBe("gpt-3.5-turbo"); + expect(state.workflowFile?.prompt).toBe(""); + }); + }); +}); + +describe("workflowProcessor", () => { + it("should have correct type and extensions", () => { + expect(workflowProcessor.type).toBe("workflow"); + expect(workflowProcessor.expectedFileExtensions).toEqual([".md"]); + }); + + it("should parse workflow content correctly", () => { + const content = `--- +name: Test Workflow +model: gpt-4 +tools: bash,read +--- +You are a helpful assistant.`; + + // Set up the mock to return expected result + const expectedResult = { + name: "Test Workflow", + model: "gpt-4", + tools: "bash,read", + prompt: "You are a helpful assistant.", + }; + (workflowProcessor.parseContent as Mock).mockReturnValue(expectedResult); + + const result = workflowProcessor.parseContent(content, "test.md"); + expect(result).toEqual({ + name: "Test Workflow", + model: "gpt-4", + tools: "bash,read", + prompt: "You are a helpful assistant.", + }); + }); + + it("should validate workflow content", () => { + const validWorkflow = { + name: "Valid Workflow", + prompt: "Test prompt", + }; + + const invalidWorkflow = { + prompt: "Test prompt", + // Missing name + }; + + // Set up mock validation responses + (workflowProcessor.validateContent as Mock) + .mockReturnValueOnce(true) // For valid workflow + .mockReturnValueOnce(false); // For invalid workflow + + expect(workflowProcessor.validateContent?.(validWorkflow)).toBe(true); + expect(workflowProcessor.validateContent?.(invalidWorkflow as any)).toBe( + false, + ); + }); + + it("should validate workflow with empty name as invalid", () => { + const invalidWorkflow = { + name: "", + prompt: "Test prompt", + }; + + // Mock validation to return false for empty name + (workflowProcessor.validateContent as Mock).mockReturnValue(false); + + expect(workflowProcessor.validateContent?.(invalidWorkflow)).toBe(false); + }); +}); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts new file mode 100644 index 000000000..cc0096af5 --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.ts @@ -0,0 +1,78 @@ +import { loadPackageFromHub, workflowProcessor } from "../hubLoader.js"; +import { logger } from "../util/logger.js"; + +import { BaseService } from "./BaseService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { WorkflowServiceState } from "./types.js"; + +/** + * Service for managing workflow state + * Loads workflows from the hub and extracts model, tools, and prompt information + */ +export class WorkflowService extends BaseService { + /** + * Set the resolved workflow model name after it's been processed + * Called by ConfigEnhancer after resolving the model slug + */ + setWorkflowModelName(modelName: string): void { + this.setState({ + workflowModelName: modelName, + }); + } + constructor() { + super("WorkflowService", { + workflowService: null, + workflowFile: null, + slug: null, + workflowModelName: null, + }); + } + + /** + * Initialize the workflow service with a workflow slug + */ + async doInitialize(workflowSlug?: string): Promise { + if (!workflowSlug) { + return { + workflowService: this, + workflowFile: null, + slug: null, + workflowModelName: null, + }; + } + + try { + const parts = workflowSlug.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid workflow slug format. Expected "owner/package", got: ${workflowSlug}`, + ); + } + + const workflowFile = await loadPackageFromHub( + workflowSlug, + workflowProcessor, + ); + + return { + workflowService: this, + workflowFile, + slug: workflowSlug, + workflowModelName: null, // Will be set by ConfigEnhancer after model resolution + }; + } catch (error: any) { + logger.error("Failed to initialize WorkflowService:", error); + return { + workflowService: this, + workflowFile: null, + slug: null, + workflowModelName: null, + }; + } + } + + protected override setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set("update", this.currentState); + } +} diff --git a/extensions/cli/src/services/index.initialization.test.ts b/extensions/cli/src/services/index.initialization.test.ts index 7aadcc57d..4d480dfcb 100644 --- a/extensions/cli/src/services/index.initialization.test.ts +++ b/extensions/cli/src/services/index.initialization.test.ts @@ -3,21 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest"; import { serviceContainer } from "./ServiceContainer.js"; import type { ToolPermissionServiceState } from "./ToolPermissionService.js"; -import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js"; +import { getServiceSync, initializeServices, SERVICE_NAMES } from "./index.js"; describe("Service Initialization", () => { beforeEach(() => { // Clean up service container state - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - services.forEach((service) => { + Object.keys(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 6978ced90..3e0109f19 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,9 +1,8 @@ import { vi } from "vitest"; -import { modeService } from "./ModeService.js"; -import { serviceContainer } from "./ServiceContainer.js"; +import { WorkflowService } from "./WorkflowService.js"; -import { initializeServices } from "./index.js"; +import { initializeServices, services } from "./index.js"; // Mock the onboarding module vi.mock("../onboarding.js", () => ({ @@ -17,45 +16,11 @@ vi.mock("../auth/workos.js", () => ({ })); describe("initializeServices", () => { - let mockModeService: any; - let mockServiceContainer: any; + // let mockToolPermissionsService: any; beforeEach(() => { // Reset all mocks vi.clearAllMocks(); - - // Create mock mode service - mockModeService = { - initialize: vi.fn(), - getCurrentMode: vi.fn(), - getToolPermissionService: vi.fn().mockReturnValue({ - getState: vi.fn().mockReturnValue({ - currentMode: "normal", - isHeadless: false, - permissions: { policies: [] }, - }), - }), - }; - - // Create mock service container - mockServiceContainer = { - registerValue: vi.fn(), - register: vi.fn(), - initializeAll: vi.fn().mockResolvedValue(undefined), - }; - - // Set up mocks - (modeService as any).initialize = mockModeService.initialize; - (modeService as any).getCurrentMode = mockModeService.getCurrentMode; - (modeService as any).getToolPermissionService = - mockModeService.getToolPermissionService; - - // Mock serviceContainer methods - (serviceContainer as any).registerValue = - mockServiceContainer.registerValue; - (serviceContainer as any).register = mockServiceContainer.register; - (serviceContainer as any).initializeAll = - mockServiceContainer.initializeAll; }); afterEach(() => { @@ -63,28 +28,8 @@ describe("initializeServices", () => { }); describe("mode conversion", () => { - it("should pass only readonly flag for plan mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "plan", - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - readonly: true, - isHeadless: true, - // auto should NOT be set - }); - }); - it("should pass only auto flag for auto mode", async () => { + const spy = vi.spyOn(services.toolPermissions, "initialize"); await initializeServices({ headless: true, // Skip onboarding toolPermissionOverrides: { @@ -95,63 +40,21 @@ describe("initializeServices", () => { }, }); - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - auto: true, - isHeadless: true, - // readonly should NOT be set - }); - }); - - it("should pass no mode flags for normal mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "normal", + expect(spy).toHaveBeenCalledWith( + { allow: ["tool1"], ask: ["tool2"], exclude: ["tool3"], + mode: "auto", + isHeadless: true, }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should pass no mode flags when mode is undefined", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], + { + slug: null, + workflowFile: null, + workflowModelName: null, + workflowService: expect.any(WorkflowService), }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should call initialize with defaults when no toolPermissionOverrides provided", async () => { - await initializeServices({ - headless: true, // Skip onboarding - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - isHeadless: true, - }); + ); }); }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index d46960ddd..9ff58f365 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -9,20 +9,24 @@ import { ConfigService } from "./ConfigService.js"; import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; -import { modeService } from "./ModeService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; -import { systemMessageService } from "./SystemMessageService.js"; +import { SystemMessageService } from "./SystemMessageService.js"; +import { + InitializeToolServiceOverrides, + ToolPermissionService, +} from "./ToolPermissionService.js"; import { ApiClientServiceState, AuthServiceState, ConfigServiceState, SERVICE_NAMES, ServiceInitOptions, - ServiceInitResult, + WorkflowServiceState, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; +import { WorkflowService } from "./WorkflowService.js"; // Service instances const authService = new AuthService(); @@ -35,28 +39,23 @@ const resourceMonitoringService = new ResourceMonitoringService(); const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); +const workflowService = new WorkflowService(); +const toolPermissionService = new ToolPermissionService(); +const systemMessageService = new SystemMessageService(); /** * Initialize all services and register them with the service container * Handles onboarding internally for TUI mode unless skipOnboarding is true */ -export async function initializeServices( - initOptions: ServiceInitOptions = {}, -): Promise { +export async function initializeServices(initOptions: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); - let wasOnboarded = false; const commandOptions = initOptions.options || {}; // Handle onboarding for TUI mode (headless: false) unless explicitly skipped if (!initOptions.headless && !initOptions.skipOnboarding) { const authConfig = loadAuthConfig(); - const onboardingResult = await initializeWithOnboarding( - authConfig, - commandOptions.config, - commandOptions.rule, - ); - wasOnboarded = onboardingResult.wasOnboarded; + await initializeWithOnboarding(authConfig, commandOptions.config); } // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided @@ -76,46 +75,48 @@ export async function initializeServices( commandOptions.config = CONFIG_PATH; } - // Initialize mode service with tool permission overrides - if (initOptions.toolPermissionOverrides) { - const overrides = { ...initOptions.toolPermissionOverrides }; + serviceContainer.register( + SERVICE_NAMES.WORKFLOW, + () => workflowService.initialize(commandOptions.workflow), + [], + ); - // Convert mode to boolean flags for ModeService - const initArgs: Parameters[0] = { - allow: overrides.allow, - ask: overrides.ask, - exclude: overrides.exclude, - isHeadless: initOptions.headless, - }; - - // Only set the boolean flag that corresponds to the mode - if (overrides.mode === "plan") { - initArgs.readonly = true; - } else if (overrides.mode === "auto") { - initArgs.auto = true; - } - // If mode is "normal" or undefined, no flags are set - - await modeService.initialize(initArgs); - } else { - // Even if no overrides, we need to initialize with defaults - await modeService.initialize({ - isHeadless: initOptions.headless, - }); - } - - // Register the TOOL_PERMISSIONS service with immediate value - // Since ToolPermissionService is already initialized synchronously in ModeService, - // we can register it as a ready value instead of a factory - const toolPermissionState = modeService.getToolPermissionService().getState(); - logger.debug("Registering TOOL_PERMISSIONS with state:", { - currentMode: toolPermissionState.currentMode, - isHeadless: toolPermissionState.isHeadless, - policyCount: toolPermissionState.permissions.policies.length, - }); - serviceContainer.registerValue( + serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, - toolPermissionState, + async () => { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + // Initialize mode service with tool permission overrides + if (initOptions.toolPermissionOverrides) { + const overrides = { ...initOptions.toolPermissionOverrides }; + + // Convert mode to boolean flags for ModeService + const initArgs: InitializeToolServiceOverrides = { + allow: overrides.allow, + ask: overrides.ask, + exclude: overrides.exclude, + isHeadless: initOptions.headless, + }; + + // Only set the boolean flag that corresponds to the mode + if (overrides.mode) { + initArgs.mode = overrides.mode; + } + // If mode is "normal" or undefined, no flags are set + return await toolPermissionService.initialize(initArgs, workflowState); + } else { + // Even if no overrides, we need to initialize with defaults + return await toolPermissionService.initialize( + { + isHeadless: initOptions.headless, + }, + workflowState, + ); + } + }, + [SERVICE_NAMES.WORKFLOW], ); // Initialize SystemMessageService with command options @@ -127,7 +128,7 @@ export async function initializeServices( format: (commandOptions as any).format, // format option from CLI headless: initOptions.headless, }), - [], // No dependencies + [SERVICE_NAMES.TOOL_PERMISSIONS], ); serviceContainer.register( @@ -156,9 +157,10 @@ export async function initializeServices( serviceContainer.register( SERVICE_NAMES.CONFIG, async () => { - const [authState, apiClientState] = await Promise.all([ + const [authState, apiClientState, workflowState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.AUTH), serviceContainer.get(SERVICE_NAMES.API_CLIENT), + serviceContainer.get(SERVICE_NAMES.WORKFLOW), ]); // Ensure organization is selected if authenticated @@ -198,32 +200,38 @@ export async function initializeServices( } } - return configService.initialize( - finalAuthState.authConfig, + return configService.initialize({ + authConfig: finalAuthState.authConfig, configPath, - finalAuthState.organizationId || null, - apiClientState.apiClient, - commandOptions, - ); + // organizationId: finalAuthState.organizationId || null, + apiClient: apiClientState.apiClient, + workflowState, + injectedConfigOptions: commandOptions, + }); }, - [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies ); serviceContainer.register( SERVICE_NAMES.MODEL, async () => { - const [configState, authState] = await Promise.all([ + const [configState, authState, workflowState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.CONFIG), serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.WORKFLOW), ]); if (!configState.config) { throw new Error("Config not available"); } - return modelService.initialize(configState.config, authState.authConfig); + return modelService.initialize( + configState.config, + authState.authConfig, + workflowState, + ); }, - [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth + [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH, SERVICE_NAMES.WORKFLOW], // Depends on config, auth, and workflow ); serviceContainer.register( @@ -270,8 +278,6 @@ export async function initializeServices( await serviceContainer.initializeAll(); logger.debug("Service registry initialized"); - - return { wasOnboarded }; } /** @@ -321,12 +327,13 @@ export const services = { apiClient: apiClientService, mcp: mcpService, fileIndex: fileIndexService, - mode: modeService, resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, + workflow: workflowService, + toolPermissions: toolPermissionService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index ae5262cae..9ce7b355b 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -1,4 +1,8 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + ModelConfig, + WorkflowFile, +} from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { AssistantConfig } from "@continuedev/sdk"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; @@ -6,9 +10,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { PermissionMode, ToolPermissions } from "../permissions/types.js"; +import { PermissionMode } from "../permissions/types.js"; -import { MCPService } from "./MCPService.js"; +import { type MCPService } from "./MCPService.js"; +import { WorkflowService } from "./WorkflowService.js"; /** * Service lifecycle states @@ -104,13 +109,6 @@ export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } -export interface ToolPermissionServiceState { - permissions: ToolPermissions; - currentMode: PermissionMode; - modePolicyCount?: number; - originalPolicies?: ToolPermissions; -} - export interface StorageSyncServiceState { isEnabled: boolean; storageId?: string; @@ -118,6 +116,13 @@ export interface StorageSyncServiceState { lastError?: string | null; } +export interface WorkflowServiceState { + workflowFile: WorkflowFile | null; + slug: string | null; + workflowModelName: string | null; + workflowService: WorkflowService | null; +} + export type { ChatHistoryState } from "./ChatHistoryService.js"; export type { FileIndexServiceState } from "./FileIndexService.js"; @@ -137,6 +142,7 @@ export const SERVICE_NAMES = { CHAT_HISTORY: "chatHistory", UPDATE: "update", STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", } as const; /** diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts new file mode 100644 index 000000000..6d68563af --- /dev/null +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -0,0 +1,650 @@ +import { vi } from "vitest"; + +import { ConfigEnhancer } from "../configEnhancer.js"; + +import { ModelService } from "./ModelService.js"; +import { WorkflowService } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + loadPackagesFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), + workflowProcessor: { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), +})); + +describe("Workflow Integration Tests", () => { + let workflowService: WorkflowService; + let modelService: ModelService; + let configEnhancer: ConfigEnhancer; + let mockLoadPackageFromHub: any; + let mockLoadPackagesFromHub: any; + let mockProcessRule: any; + let mockCreateLlmApi: any; + let mockGetLlmApi: any; + let mockModelProcessor: any; + + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow for integration testing", + model: "gpt-4-workflow", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are a workflow assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mock functions + const hubLoaderModule = await import("../hubLoader.js"); + const configModule = await import("../config.js"); + + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; + mockProcessRule = hubLoaderModule.processRule as any; + mockModelProcessor = hubLoaderModule.modelProcessor; + mockCreateLlmApi = configModule.createLlmApi as any; + mockGetLlmApi = configModule.getLlmApi as any; + + // Create service instances + workflowService = new WorkflowService(); + modelService = new ModelService(); + configEnhancer = new ConfigEnhancer(); + + // Setup default mocks + mockProcessRule.mockResolvedValue("Processed rule content"); + mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); + mockLoadPackageFromHub.mockResolvedValue({ + name: "test-model", + provider: "openai", + }); + mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); + mockGetLlmApi.mockReturnValue([ + { mock: "llmApi" }, + mockAssistant.models[0], + ]); + }); + + describe("Workflow models are injected via ConfigEnhancer", () => { + it("should add workflow model to options when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); + + // Mock loadPackageFromHub to return a model for the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + + // Test that ConfigEnhancer adds the workflow model to options + const baseConfig = { models: [] }; + const baseOptions = {}; // No --model flag + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowState, + ); + + // Should have loaded the workflow model directly via loadPackageFromHub + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "gpt-4-workflow", + mockModelProcessor, + ); + + // The workflow model should be prepended to the models array + expect(enhancedConfig.models).toHaveLength(1); + expect(enhancedConfig.models?.[0]).toEqual({ + name: "gpt-4-workflow", + provider: "openai", + }); + }); + + it("should not add workflow model when no workflow is active", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile).toBeNull(); + + // Test that ConfigEnhancer doesn't add any workflow models + const baseConfig = { models: [] }; + const baseOptions = {}; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowState, + ); + + // Should not have enhanced with any models + expect(enhancedConfig.models).toEqual([]); + }); + + it("should respect --model flag priority over workflow model", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + // Mock loadPackageFromHub for workflow model and loadPackagesFromHub for user models + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + mockLoadPackagesFromHub.mockResolvedValueOnce([ + { + name: "user-specified-model", + provider: "anthropic", + }, + ]); + + // Test that --model flag takes precedence + const baseConfig = { models: [] }; + const baseOptions = { model: ["user-specified-model"] }; // User specified --model + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); + + // Should process the user model via loadPackagesFromHub + expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( + ["user-specified-model"], + mockModelProcessor, + ); + + // Should also load the workflow model + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "gpt-4-workflow", + mockModelProcessor, + ); + + // Both models should be in the config, with user model first (takes precedence) + expect(enhancedConfig.models).toHaveLength(2); + expect(enhancedConfig.models?.[0]).toEqual({ + name: "user-specified-model", + provider: "anthropic", + }); + expect(enhancedConfig.models?.[1]).toEqual({ + name: "gpt-4-workflow", + provider: "openai", + }); + }); + }); + + describe("WorkflowService affects ConfigEnhancer", () => { + it("should inject workflow rules when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + // Rules should be processed normally since workflow rules are now added to options.rule + expect(mockProcessRule).toHaveBeenCalledWith(mockWorkflowFile.rules); + expect(enhancedConfig.rules).toHaveLength(2); + // The workflow rule is processed first, then existing rules + expect(mockProcessRule).toHaveBeenNthCalledWith( + 1, + mockWorkflowFile.rules, + ); + }); + + it("should not inject workflow rules when workflow is inactive", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig?.rules?.[0]).toBe("existing rule"); + }); + + it("should not inject workflow rules when workflow has no rules", async () => { + const workflowWithoutRules = { + ...mockWorkflowFile, + rules: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutRules); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + }); + + describe("Workflow model constraints", () => { + it("should filter available models to only workflow model when specified", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + // Verify that available models include all original models + // (we removed the filtering logic) + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); // Should include both original models + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + + it("should allow all models when no workflow is active", async () => { + await workflowService.initialize(); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + }); + + describe("Error handling", () => { + it("should handle workflow loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + await workflowService.initialize("owner/workflow"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile).toBeNull(); + + // Model service should work normally + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + expect(mockGetLlmApi).toHaveBeenCalled(); + }); + + it("should handle workflow rule processing errors gracefully", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + mockProcessRule.mockRejectedValue(new Error("Rule processing failed")); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + // Should not inject workflow rule but should preserve existing rules + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + + // Removed test for missing service container since workflow service + // should always be initialized before ConfigEnhancer is called + + it("should inject workflow prompt when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + prompts: [], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + // Workflow prompt should be added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + prompt: "You are a workflow assistant.", + name: expect.stringContaining("Test Workflow"), + }); + expect(enhancedConfig.rules).toHaveLength(2); + }); + + it("should add workflow prompt to config alongside other prompts", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + const baseOptions = {}; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); + + // Workflow prompt should be prepended to existing prompts + expect(enhancedConfig.prompts).toHaveLength(2); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Workflow"), + prompt: "You are a workflow assistant.", + }); + expect(enhancedConfig.prompts?.[1]).toMatchObject({ + name: "Existing", + prompt: "existing-prompt", + }); + }); + + it("should not add workflow prompt when workflow has no prompt", async () => { + const workflowWithoutPrompt = { + ...mockWorkflowFile, + prompt: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutPrompt); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + const baseOptions = {}; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); + + // Should only have the existing prompt, no workflow prompt added + expect(enhancedConfig.prompts).toHaveLength(1); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: "Existing", + prompt: "existing-prompt", + }); + }); + }); + + describe("ConfigEnhancer prompt integration", () => { + it("should add workflow prompt to config.prompts when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseOptions = { prompt: ["user-prompt"] }; + const baseConfig = { prompts: [] }; + + // Enhance config with workflow state + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); + + // Verify that the workflow prompt was added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts).toHaveLength(1); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Workflow"), + prompt: "You are a workflow assistant.", + description: "A test workflow for integration testing", + }); + }); + + it("should work end-to-end with workflow prompt in config", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.prompt).toBe( + "You are a workflow assistant.", + ); + + const baseConfig = { prompts: [] }; + const baseOptions = { prompt: ["Tell me about TypeScript"] }; + + // Enhance config with workflow + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowState, + ); + + // Verify workflow prompt is added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); + expect(enhancedConfig.prompts?.[0]?.prompt).toBe( + "You are a workflow assistant.", + ); + expect(enhancedConfig.prompts?.[0]?.name).toContain("Test Workflow"); + }); + }); + + describe("Workflow data extraction", () => { + it("should correctly extract all workflow properties", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); + expect(workflowState.workflowFile?.tools).toBe("bash,read,write"); + expect(workflowState.workflowFile?.rules).toBe( + "Always be helpful and concise", + ); + expect(workflowState.workflowFile?.prompt).toBe( + "You are a workflow assistant.", + ); + expect(workflowState.slug).toBe("owner/workflow"); + }); + + it("should handle partial workflow data", async () => { + const partialWorkflow = { + name: "Partial Workflow", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules + }; + + mockLoadPackageFromHub.mockResolvedValue(partialWorkflow); + await workflowService.initialize("owner/partial"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.model).toBe("gpt-3.5-turbo"); + expect(workflowState.workflowFile?.tools).toBeUndefined(); + expect(workflowState.workflowFile?.rules).toBeUndefined(); + expect(workflowState.workflowFile?.prompt).toBe("Partial prompt"); + }); + }); + + describe("Workflow tools integration", () => { + it("should inject MCP servers from workflow tools", async () => { + const workflowWithTools = { + ...mockWorkflowFile, + tools: "owner/mcp1, another/mcp2:specific_tool", + }; + + // Clear the default mock and setup specific mocks + mockLoadPackageFromHub.mockReset(); + // First call loads the workflow file + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithTools); + // Second call loads the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + // Third call loads mcp1 + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); + // Fourth call loads mcp2 + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp2" }); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "existing-mcp" }], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + expect(enhancedConfig.mcpServers).toHaveLength(3); + // MCPs are prepended in the order they are loaded + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); + expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" }); + expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" }); + }); + + it("should not inject MCP servers when workflow has no tools", async () => { + const workflowWithoutTools = { + ...mockWorkflowFile, + tools: undefined, + }; + + mockLoadPackageFromHub.mockReset(); + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithoutTools); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "existing-mcp" }], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + expect(enhancedConfig.mcpServers).toHaveLength(1); + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "existing-mcp" }); + }); + + it("should deduplicate MCP servers", async () => { + const workflowWithDuplicateTools = { + ...mockWorkflowFile, + tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + }; + + // Clear the default mock and setup specific mocks + mockLoadPackageFromHub.mockReset(); + // First call loads the workflow file + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithDuplicateTools); + // Second call loads the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + // Third call: The parseWorkflowTools will extract only unique MCP servers, so only one loadPackageFromHub call + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "existing-mcp" }], // Changed to avoid confusion + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + workflowService.getState(), + ); + + // parseWorkflowTools deduplicates, so we only get mcp1 once + expect(enhancedConfig.mcpServers).toHaveLength(2); + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); + expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "existing-mcp" }); + }); + }); +}); diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 31572949d..54a2a4154 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -14,6 +14,7 @@ export function addCommonOptions(command: Command): Command { .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") .option("--verbose", "Enable verbose logging") + .option("--beta-status-tool", "Enable beta status tool") .option( "--rule ", "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", @@ -83,6 +84,10 @@ export function addCommonOptions(command: Command): Command { return array; }, [] as string[], + ) + .option( + "--workflow ", + "Load workflow from the hub (slug in format 'owner/package')", ); } @@ -106,6 +111,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "allow", "ask", "exclude", + "workflow", ]; for (const optName of inheritableOptions) { diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index f6db2be36..30df8e832 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -335,5 +335,99 @@ describe("slashCommands", () => { ); expect(result?.exit).toBe(false); }); + + it("should handle custom assistant prompts", async () => { + const assistantWithPrompts: AssistantUnrolled = { + ...mockAssistant, + prompts: [ + { + name: "explain", + description: "Explain the code", + prompt: "Please explain the following code:", + }, + ], + }; + + const result = await handleSlashCommands( + "/explain some code", + assistantWithPrompts, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Please explain the following code:some code", + ); + }); + + it("should handle invokable rules", async () => { + const assistantWithRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "review", + description: "Review this code", + rule: "Perform a code review on the following:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/review some code", + assistantWithRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Perform a code review on the following: some code", + ); + }); + + it("should not treat non-invokable rules as slash commands", async () => { + const assistantWithNonInvokableRule: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "regular", + description: "A regular rule", + rule: "This is a regular rule", + invokable: false, + }, + ], + }; + + const result = await handleSlashCommands( + "/regular", + assistantWithNonInvokableRule, + ); + + // Should return null because the rule is not invokable + expect(result).toBeNull(); + }); + + it("should handle invokable rules from hub (string rules ignored)", async () => { + const assistantWithMixedRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + "string rule", + { + name: "analyze", + description: "Analyze code patterns", + rule: "Analyze the following code for patterns:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/analyze my code", + assistantWithMixedRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe( + "Analyze the following code for patterns: my code", + ); + }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index 69b3f7437..503d13901 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -233,6 +233,21 @@ export async function handleSlashCommands( return { newInput }; } + // Check for invokable rules + const invokableRule = assistant.rules?.find((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + const ruleObj = rule as any; + return ruleObj.invokable === true && ruleObj.name === command; + }); + if (invokableRule) { + const ruleObj = invokableRule as any; + const newInput = ruleObj.rule + " " + args.join(" "); + return { newInput }; + } + // Check if this command would match any available commands (same logic as UI) const allCommands = getAllSlashCommands(assistant, { isRemoteMode: options?.isRemoteMode, diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 8d8eb68a3..4564d20a9 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -13,16 +13,7 @@ import { getAllTools } from "./streamChatResponse.js"; describe("getAllTools - Tool Filtering", () => { beforeEach(() => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.test.ts b/extensions/cli/src/stream/streamChatResponse.helpers.test.ts new file mode 100644 index 000000000..4b13eec25 --- /dev/null +++ b/extensions/cli/src/stream/streamChatResponse.helpers.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { PreprocessedToolCall } from "../tools/types.js"; + +import { handleHeadlessPermission } from "./streamChatResponse.helpers.js"; + +describe("streamChatResponse.helpers", () => { + describe("handleHeadlessPermission", () => { + it("should display error message and exit when tool requires permission in headless mode", async () => { + // Mock the tool call + const toolCall: PreprocessedToolCall = { + id: "call_123", + name: "Write", + arguments: { filepath: "test.txt", content: "hello" }, + argumentsStr: '{"filepath":"test.txt","content":"hello"}', + startNotified: false, + tool: { + name: "Write", + displayName: "Write", + description: "Write to a file", + parameters: { + type: "object", + properties: {}, + }, + run: vi.fn(), + isBuiltIn: true, + }, + }; + + // Mock safeStderr to capture output + const stderrOutputs: string[] = []; + vi.doMock("../init.js", () => ({ + safeStderr: (message: string) => { + stderrOutputs.push(message); + }, + })); + + // Mock gracefulExit to prevent actual process exit + let exitCode: number | undefined; + vi.doMock("../util/exit.js", () => ({ + gracefulExit: async (code: number) => { + exitCode = code; + }, + })); + + // Call the function (it should exit gracefully) + try { + await handleHeadlessPermission(toolCall); + } catch (error) { + // Expected to throw after exit + } + + // Verify error message was displayed + const fullOutput = stderrOutputs.join(""); + expect(fullOutput).toContain("requires permission"); + expect(fullOutput).toContain("headless mode"); + expect(fullOutput).toContain("--auto"); + expect(fullOutput).toContain("--allow"); + expect(fullOutput).toContain("--exclude"); + expect(fullOutput).toContain("Write"); + + // Verify it tried to exit with code 1 + expect(exitCode).toBe(1); + }); + }); +}); diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index cc987aecb..b613fd1cb 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -51,25 +51,30 @@ export function handlePermissionDenied( } // Helper function to handle headless mode permission -export function handleHeadlessPermission( +export async function handleHeadlessPermission( toolCall: PreprocessedToolCall, -): never { +): Promise { const allBuiltinTools = getAllBuiltinTools(); const tool = allBuiltinTools.find((t) => t.name === toolCall.name); const toolName = tool?.displayName || toolCall.name; - console.error( - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, + // Import safeStderr to bypass console blocking in headless mode + const { safeStderr } = await import("../init.js"); + safeStderr( + `Error: Tool '${toolName}' requires permission but cn is running in headless mode.\n`, ); - console.error(`If you want to allow this tool, use --allow ${toolName}.`); - console.error( - `If you don't want the tool to be included, use --exclude ${toolName}.`, + safeStderr( + `If you want to allow all tools without asking, use cn -p --auto "your prompt".\n`, + ); + safeStderr(`If you want to allow this tool, use --allow ${toolName}.\n`); + safeStderr( + `If you don't want the tool to be included, use --exclude ${toolName}.\n`, ); // Use graceful exit to flush telemetry even in headless denial - // Note: We purposely trigger an async exit without awaiting in this sync path - import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1)); - // Throw to satisfy the never return type; process will exit shortly + const { gracefulExit } = await import("../util/exit.js"); + await gracefulExit(1); + // This line will never be reached, but TypeScript needs it for the 'never' return type throw new Error("Exiting due to headless permission requirement"); } @@ -133,7 +138,7 @@ export async function checkToolPermissionApproval( return { approved: true }; } else if (permissionCheck.permission === "ask") { if (isHeadless) { - handleHeadlessPermission(toolCall); + await handleHeadlessPermission(toolCall); } const userApproved = await requestUserPermission(toolCall, callbacks); return userApproved diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index f5a9e74bd..b3af7eb65 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -4,24 +4,16 @@ import { SERVICE_NAMES, initializeServices, serviceContainer, + services, } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; import { getAllTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { + const toolPermissionService = services.toolPermissions; beforeEach(async () => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); (serviceContainer as any).dependencies.delete(service); @@ -46,10 +38,10 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { expect(toolNames).toContain("Edit"); // Switch to plan mode (simulating Shift+Tab during streaming) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // Update the service container (this is what UserInput.tsx does) - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Recompute tools - should now exclude write tools @@ -68,25 +60,25 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { test("getAllTools reflects current mode immediately", async () => { // Start in normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); let tools = await getAllTools(); expect(tools.map((t) => t.function.name)).toContain("Write"); // Switch to plan mode - modeService.switchMode("plan"); - let updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("plan"); + let updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // getAllTools should immediately reflect the new mode tools = await getAllTools(); expect(tools.map((t) => t.function.name)).not.toContain("Write"); // Switch to auto mode - modeService.switchMode("auto"); - updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("auto"); + updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // getAllTools should immediately reflect auto mode (all tools allowed) tools = await getAllTools(); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index a59fa8cf7..2c7ef9566 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,9 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; -import { systemMessageService } from "../services/SystemMessageService.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { services } from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { ToolCall } from "../tools/index.js"; @@ -157,7 +155,9 @@ export async function processStreamingResponse( } // Get fresh system message and inject it - const systemMessage = await systemMessageService.getSystemMessage(); + const systemMessage = await services.systemMessage.getSystemMessage( + services.toolPermissions.getState().currentMode, + ); const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( chatHistory, systemMessage, @@ -337,10 +337,7 @@ export async function streamChatResponse( hasCallbacks: !!callbacks, }); - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; + const isHeadless = services.toolPermissions.isHeadless(); let fullResponse = ""; let finalResponse = ""; @@ -394,12 +391,12 @@ export async function streamChatResponse( // Get response from LLM const { content, toolCalls, shouldContinue } = await processStreamingResponse({ + isHeadless, chatHistory, model, llmApi, abortController, callbacks, - isHeadless, tools, }); diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index d77794734..e419d0bac 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -8,12 +8,13 @@ const { constructSystemMessage } = await import("./systemMessage.js"); vi.mock("./services/ServiceContainer.js", () => ({ serviceContainer: { get: vi.fn().mockResolvedValue({ config: { rules: [] } }), + set: vi.fn(), }, })); -// Mock processPromptOrRule to avoid file system operations in tests -vi.mock("./args.js", () => ({ - processPromptOrRule: vi +// Mock processRule to avoid file system operations in tests +vi.mock("./hubLoader.js", () => ({ + processRule: vi .fn() .mockImplementation((spec: string) => Promise.resolve(spec)), })); @@ -23,7 +24,7 @@ const PLAN_MODE_STRING = "You are operating in _Plan Mode_"; describe("constructSystemMessage", () => { it("should return base system message with rules when additionalRules is provided", async () => { const rules = ["These are the rules for the assistant."]; - const result = await constructSystemMessage(rules); + const result = await constructSystemMessage("normal", rules); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -33,7 +34,7 @@ describe("constructSystemMessage", () => { it("should return base system message with agent content when no rules but agent file exists", async () => { // The implementation checks for agent files like AGENTS.md which exists in this project - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -41,7 +42,7 @@ describe("constructSystemMessage", () => { }); it("should include base system message components", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(""); @@ -50,27 +51,27 @@ describe("constructSystemMessage", () => { }); it("should handle whitespace-only rules message", async () => { - const result = await constructSystemMessage([" "]); + const result = await constructSystemMessage("normal", [" "]); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); }); it("should include working directory information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Working directory:"); expect(result).toContain(""); }); it("should include platform information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Platform:"); }); it("should include current date", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Today's date:"); expect(result).toContain(new Date().toISOString().split("T")[0]); @@ -78,7 +79,7 @@ describe("constructSystemMessage", () => { it("should format rules section correctly", async () => { const rulesMessage = "Rule 1: Do this\nRule 2: Do that"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -89,7 +90,7 @@ describe("constructSystemMessage", () => { const rulesMessage = `Rule 1: First rule Rule 2: Second rule Rule 3: Third rule`; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -98,7 +99,7 @@ Rule 3: Third rule`; it("should handle special characters in rules message", async () => { const rulesMessage = "Rule with characters & symbols!"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -106,7 +107,7 @@ Rule 3: Third rule`; it("should handle very long rules message", async () => { const rulesMessage = "A".repeat(1000); - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -114,7 +115,7 @@ Rule 3: Third rule`; it("should combine rules and agent content when both are present", async () => { const rulesMessage = "These are the rules."; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -123,7 +124,12 @@ Rule 3: Third rule`; }); it("should add headless mode instructions when headless is true", async () => { - const result = await constructSystemMessage(undefined, undefined, true); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + true, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -134,7 +140,12 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is false", async () => { - const result = await constructSystemMessage(undefined, undefined, false); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + false, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -142,7 +153,7 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is undefined", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -150,7 +161,7 @@ Rule 3: Third rule`; }); it("should add JSON format instructions when format is json", async () => { - const result = await constructSystemMessage(undefined, "json"); + const result = await constructSystemMessage("normal", undefined, "json"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain( @@ -162,10 +173,10 @@ Rule 3: Third rule`; it("should add plan mode instructions when mode is plan", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -182,10 +193,10 @@ Rule 3: Third rule`; it("should not add plan mode instructions when mode is not plan", async () => { const result = await constructSystemMessage( + "normal", undefined, undefined, false, - "normal", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -195,8 +206,8 @@ Rule 3: Third rule`; ); }); - it("should not add plan mode instructions when mode is undefined", async () => { - const result = await constructSystemMessage(); + it("should not add plan mode instructions when mode is normal", async () => { + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain(PLAN_MODE_STRING); @@ -207,10 +218,10 @@ Rule 3: Third rule`; it("should include basic plan mode description", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain(PLAN_MODE_STRING); @@ -220,10 +231,10 @@ Rule 3: Third rule`; it("should combine plan mode with headless mode instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, true, - "plan", ); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -235,10 +246,10 @@ Rule 3: Third rule`; it("should combine plan mode with JSON format instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, "json", false, - "plan", ); expect(result).toContain( diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index c9e8920fe..d5dee238f 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -5,9 +5,8 @@ import * as path from "path"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import { processPromptOrRule } from "./args.js"; +import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; -import { modeService } from "./services/ModeService.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; @@ -125,10 +124,10 @@ async function getConfigYamlRules(): Promise { * @returns The comprehensive system message with base message and rules section */ export async function constructSystemMessage( + mode: PermissionMode, additionalRules?: string[], format?: "json", headless?: boolean, - mode?: PermissionMode, ): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; @@ -153,7 +152,7 @@ export async function constructSystemMessage( if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = await processPromptOrRule(ruleSpec); + const processedRule = await processRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( @@ -166,14 +165,11 @@ export async function constructSystemMessage( const configYamlRules = await getConfigYamlRules(); processedRules.push(...configYamlRules); - // Get current mode if not provided - const currentMode = mode ?? modeService.getCurrentMode(); - // Construct the comprehensive system message let systemMessage = baseSystemMessage; // Add plan mode specific instructions if in plan mode - if (currentMode === "plan") { + if (mode === "plan") { systemMessage += '\nYou are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.\n'; } else { diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts index a3623361d..30aaacb86 100644 --- a/extensions/cli/src/tools/edit.ts +++ b/extensions/cli/src/tools/edit.ts @@ -104,18 +104,22 @@ WARNINGS: }, }, preprocess: async (args) => { - const { old_string, new_string, replace_all = false } = args as EditArgs; + const { old_string, new_string, replace_all } = args as EditArgs; const { resolvedPath } = validateAndResolveFilePath(args); - validateSingleEdit(old_string, new_string); + const { oldString, newString, replaceAll } = validateSingleEdit( + old_string, + new_string, + replace_all, + ); const oldContent = fs.readFileSync(resolvedPath, "utf-8"); const newContent = executeFindAndReplace( oldContent, - old_string, - new_string, - replace_all, + oldString, + newString, + replaceAll ?? false, 0, ); diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index fda429563..c185fa57b 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -8,8 +8,8 @@ import { MCPServiceState, SERVICE_NAMES, serviceContainer, + services, } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import type { ModelServiceState } from "../services/types.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; @@ -23,6 +23,7 @@ import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; +import { statusTool } from "./status.js"; import { type Tool, type ToolCall, @@ -57,17 +58,13 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; function getDynamicTools(): Tool[] { const dynamicTools: Tool[] = []; - // Add headless-specific tools if in headless mode - try { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; - if (isHeadless) { - dynamicTools.push(exitTool); - } - } catch { - // Service not ready yet, no dynamic tools + if (services.toolPermissions.isHeadless()) { + dynamicTools.push(exitTool); + } + + // Add beta status tool if --beta-status-tool flag is present + if (process.argv.includes("--beta-status-tool")) { + dynamicTools.push(statusTool); } return dynamicTools; diff --git a/extensions/cli/src/tools/status.ts b/extensions/cli/src/tools/status.ts new file mode 100644 index 000000000..3cdaf6a62 --- /dev/null +++ b/extensions/cli/src/tools/status.ts @@ -0,0 +1,80 @@ +import { + ApiRequestError, + AuthenticationRequiredError, + post, +} from "../util/apiClient.js"; +import { logger } from "../util/logger.js"; + +import { Tool } from "./types.js"; + +/** + * Extract the agent ID from the --id command line flag + */ +function getAgentIdFromArgs(): string | undefined { + const args = process.argv; + const idIndex = args.indexOf("--id"); + if (idIndex !== -1 && idIndex + 1 < args.length) { + return args[idIndex + 1]; + } + return undefined; +} + +export const statusTool: Tool = { + name: "Status", + displayName: "Status", + description: `Set the current status of your task for the user to see + +The default available statuses are: +- PLANNING: You are creating a plan before beginning implementation +- WORKING: The task is in progress +- DONE: The task is complete +- BLOCKED: You need further information from the user in order to proceed + +However, if the user explicitly specifies in their prompt to use one or more different statuses, you can use those as well. + +You should use this tool to notify the user whenever the state of your work changes. By default, the status is assumed to be "PLANNING" prior to you setting a different status.`, + parameters: { + type: "object", + required: ["status"], + properties: { + status: { + type: "string", + description: "The status value to set", + }, + }, + }, + readonly: true, + isBuiltIn: true, + run: async (args: { status: string }): Promise => { + try { + // Get agent ID from --id flag + const agentId = getAgentIdFromArgs(); + if (!agentId) { + const errorMessage = + "Agent ID is required. Please use the --id flag with cn serve."; + logger.error(errorMessage); + return `Error: ${errorMessage}`; + } + + // Call the API endpoint using shared client + await post(`agents/${agentId}/status`, { status: args.status }); + + logger.info(`Status: ${args.status}`); + return `Status set: ${args.status}`; + } catch (error) { + if (error instanceof AuthenticationRequiredError) { + logger.error(error.message); + return "Error: Authentication required"; + } + + if (error instanceof ApiRequestError) { + return `Error setting status: ${error.status} ${error.response || error.statusText}`; + } + + const errorMessage = + error instanceof Error ? error.message : String(error); + logger.error(`Error setting status: ${errorMessage}`); + return `Error setting status: ${errorMessage}`; + } + }, +}; diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx new file mode 100644 index 000000000..c56bec21a --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -0,0 +1,202 @@ +/** + * @vitest-environment jsdom + */ +import { render } from "@testing-library/react"; +import type { ChatHistoryItem } from "core/index.js"; +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { EditMessageSelector } from "./EditMessageSelector.js"; + +describe("EditMessageSelector", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + const history: ChatHistoryItem[] = []; + for (let i = 0; i < count; i++) { + // Alternate between user and assistant messages + if (i % 2 === 0) { + history.push({ + message: { role: "user", content: `User message ${i + 1}` }, + contextItems: [], + }); + } else { + history.push({ + message: { role: "assistant", content: `Assistant message ${i + 1}` }, + contextItems: [], + }); + } + } + return history; + }; + + let mockOnEdit: ReturnType; + let mockOnExit: ReturnType; + + beforeEach(() => { + mockOnEdit = vi.fn(); + mockOnExit = vi.fn(); + vi.clearAllMocks(); + }); + + describe("Initialization", () => { + it("should render 'no user messages' when chat history is empty", () => { + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render 'no user messages' when chat history has only assistant messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "assistant", content: "Hello" }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render user messages list", () => { + const chatHistory = createMockChatHistory(4); // Will have 2 user messages + + const { container } = render( + , + ); + + expect(container.textContent).toContain("Message 1:"); + expect(container.textContent).toContain("Message 2:"); + expect(container.textContent).toContain("User message 1"); + expect(container.textContent).toContain("User message 3"); + }); + + it("should filter out non-user messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "User 1" }, contextItems: [] }, + { + message: { role: "assistant", content: "Assistant 1" }, + contextItems: [], + }, + { message: { role: "system", content: "System 1" }, contextItems: [] }, + { message: { role: "user", content: "User 2" }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should only show 2 user messages + expect(container.textContent).toContain("User 1"); + expect(container.textContent).toContain("User 2"); + expect(container.textContent).not.toContain("Assistant 1"); + expect(container.textContent).not.toContain("System 1"); + }); + + it("should show instruction text in selection mode", () => { + const chatHistory = createMockChatHistory(2); + + const { container } = render( + , + ); + + expect(container.textContent).toContain("↑/↓ to navigate"); + expect(container.textContent).toContain("Enter to edit"); + expect(container.textContent).toContain("Esc to exit"); + }); + }); + + describe("Message preview", () => { + it("should truncate long messages in preview", () => { + const longMessage = "a".repeat(100); + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: longMessage }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should show truncation indicator + expect(container.textContent).toContain("..."); + // Should not show full message (preview is limited to 60 chars) + expect(container.textContent).not.toContain(longMessage); + }); + + it("should show only first line in multiline message preview", () => { + const multilineMessage = "First line\nSecond line\nThird line"; + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: multilineMessage }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("First line"); + expect(container.textContent).not.toContain("Second line"); + }); + }); + + describe("Complex message content", () => { + it("should handle message parts array", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: [ + { type: "text", text: "Hello" }, + { type: "text", text: " world" }, + ], + } as any, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + // Should render something (component handles non-string content gracefully) + expect(container.textContent).toBeDefined(); + }); + }); +}); diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx new file mode 100644 index 000000000..60c8a23c0 --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -0,0 +1,292 @@ +import { Box, Text, useInput } from "ink"; +import React, { useMemo, useState } from "react"; + +import type { ChatHistoryItem } from "../../../../core/index.js"; + +import { defaultBoxStyles } from "./styles.js"; +import { TextBuffer } from "./TextBuffer.js"; + +// Infer the Key type from useInput's callback parameters +type UseInputHandler = Parameters[0]; +type Key = Parameters[1]; + +interface EditMessageSelectorProps { + chatHistory: ChatHistoryItem[]; + onEdit: (messageIndex: number, newContent: string) => void; + onExit: () => void; +} + +export function EditMessageSelector({ + chatHistory, + onEdit, + onExit, +}: EditMessageSelectorProps) { + // Filter to only show user messages + const userMessages = useMemo(() => { + return chatHistory + .map((item, originalIndex) => ({ item, originalIndex })) + .filter(({ item }) => item.message.role === "user"); + }, [chatHistory]); + + const [selectedIndex, setSelectedIndex] = useState( + Math.max(0, userMessages.length - 1), + ); + const [isEditing, setIsEditing] = useState(false); + const [textBuffer] = useState(() => new TextBuffer()); + const [editText, setEditText] = useState(""); + const [cursorPosition, setCursorPosition] = useState(0); + + // Stable callback for TextBuffer state changes (e.g., paste finalization) + const onStateChange = React.useCallback(() => { + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + }, [textBuffer]); + + // Set up callback for when TextBuffer state changes asynchronously + React.useEffect(() => { + textBuffer.setStateChangeCallback(onStateChange); + + return () => { + // Clear any pending timers on unmount + textBuffer.clear(); + }; + }, [textBuffer, onStateChange]); + + // Initialize edit text when selection changes + React.useEffect(() => { + if (!isEditing && userMessages[selectedIndex]) { + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } + }, [selectedIndex, isEditing, userMessages, textBuffer]); + + // Helper to get message content safely + const getMessageContent = React.useCallback( + (index: number): string => { + return typeof userMessages[index]?.item.message.content === "string" + ? userMessages[index].item.message.content + : ""; + }, + [userMessages], + ); + + // Handle input when in editing mode + const handleEditModeInput = React.useCallback( + (input: string, key: Key) => { + if (key.escape) { + setIsEditing(false); + // Reset text to original + const content = getMessageContent(selectedIndex); + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } else if (key.return && !key.shift) { + // Submit the edit + // Expand all paste blocks before submission to restore original content + textBuffer.expandAllPasteBlocks(); + const trimmedText = textBuffer.text.trim(); + if (trimmedText && userMessages[selectedIndex]) { + onEdit(userMessages[selectedIndex].originalIndex, trimmedText); + } + } else if (key.return && key.shift) { + // Handle newline + textBuffer.handleInput("\n", key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } else { + // Let TextBuffer handle the input + textBuffer.handleInput(input, key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } + }, + [ + getMessageContent, + selectedIndex, + textBuffer, + userMessages, + onEdit, + setIsEditing, + setEditText, + setCursorPosition, + ], + ); + + // Handle input when in navigation mode + const handleNavigationInput = React.useCallback( + (input: string, key: Key) => { + if (key.upArrow || input === "k") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } + } else if (key.downArrow || input === "j") { + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } + } else if (key.return) { + // Start editing the selected message - set cursor to end + // Only allow editing if there are messages + if (userMessages.length > 0) { + const content = getMessageContent(selectedIndex); + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } + }, + [ + userMessages.length, + getMessageContent, + selectedIndex, + textBuffer, + onExit, + setSelectedIndex, + setCursorPosition, + setIsEditing, + ], + ); + + useInput((input, key) => { + if (isEditing) { + handleEditModeInput(input, key); + } else { + handleNavigationInput(input, key); + } + }); + + if (userMessages.length === 0) { + return ( + + No user messages to edit. + Press Esc to exit + + ); + } + + const renderEditText = () => { + if (editText.length === 0) { + return ( + + ▋(empty message) + + ); + } + + // Handle multi-line text with cursor + const lines = editText.split("\n"); + let charCount = 0; + let cursorLine = 0; + let cursorCol = 0; + + // Find which line and column the cursor is on + for (let i = 0; i < lines.length; i++) { + if (cursorPosition <= charCount + lines[i].length) { + cursorLine = i; + cursorCol = cursorPosition - charCount; + break; + } + charCount += lines[i].length + 1; // +1 for the newline character + } + + // Handle cursor at the very end + if (cursorPosition >= editText.length) { + cursorLine = lines.length - 1; + cursorCol = lines[cursorLine].length; + } + + return ( + + {lines.map((line, lineIndex) => { + if (lineIndex === cursorLine) { + // Line with cursor + const beforeCursor = line.slice(0, cursorCol); + const atCursor = line.slice(cursorCol, cursorCol + 1); + const afterCursor = line.slice(cursorCol + 1); + + return ( + + {beforeCursor} + {atCursor || " "} + {afterCursor} + + ); + } else { + // Regular line - ensure empty lines still render + return {line || " "}; + } + })} + + ); + }; + + return ( + + + Edit Message (Rewind Conversation) + + + {isEditing + ? "Enter to submit, Esc to cancel, Shift+Enter for newline" + : "↑/↓ to navigate, Enter to edit, Esc to exit"} + + + + {!isEditing && ( + <> + Select a message to edit: + + {userMessages.map((msg, index) => { + const isSelected = index === selectedIndex; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "yellow" : "white"; + const content = + typeof msg.item.message.content === "string" + ? msg.item.message.content + : ""; + const preview = content.split("\n")[0].slice(0, 60); + const truncated = content.length > 60 ? "..." : ""; + + return ( + + + {indicator}Message {index + 1}: {preview} + {truncated} + + + ); + })} + + )} + + {isEditing && ( + <> + + Editing Message {selectedIndex + 1} (will rewind to this point): + + + + {renderEditText()} + + + )} + + ); +} diff --git a/extensions/cli/src/ui/IntroMessage.test.tsx b/extensions/cli/src/ui/IntroMessage.test.tsx index a21d6f79c..6f024b96e 100644 --- a/extensions/cli/src/ui/IntroMessage.test.tsx +++ b/extensions/cli/src/ui/IntroMessage.test.tsx @@ -81,4 +81,19 @@ describe("IntroMessage", () => { expect(lastFrame()).toContain("Model:"); expect(lastFrame()).toContain("Loading..."); }); + + it("renders organization name when provided", () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain("Org:"); + expect(lastFrame()).toContain("Test Organization"); + }); + + it("does not render organization section when not provided", () => { + const { lastFrame } = render(); + + expect(lastFrame()).not.toContain("Org:"); + }); }); diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index e26448479..139db3e8b 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -13,6 +13,7 @@ interface IntroMessageProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; } // Helper function to extract rule names @@ -26,6 +27,7 @@ const IntroMessage: React.FC = ({ config, model, mcpService, + organizationName, }) => { // Get MCP prompts directly (not memoized since they can change after first render) const mcpPrompts = mcpService?.getState().prompts ?? []; @@ -98,6 +100,13 @@ const IntroMessage: React.FC = ({ {/* Tips Display - shown randomly 1 in 5 times */} {showTip && } + {/* Organization name */} + {organizationName && ( + + Org: {organizationName} + + )} + {/* Agent name */} {config && ( diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index 99523c63c..e974c6f8c 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -117,6 +117,13 @@ export const MCPSelector: React.FC = ({ onCancel }) => { { label: "⏹️ Stop all servers", value: "stop-all" }, ); } + + // Add "Explore MCP Servers" option at the bottom + options.push({ + label: "🔍 Explore MCP Servers", + value: "explore-mcp-servers", + }); + return options; }; @@ -280,6 +287,12 @@ export const MCPSelector: React.FC = ({ onCancel }) => { await mcpService.shutdownConnections(); setMessage("All servers stopped"); break; + case "explore-mcp-servers": + // Open the MCP servers hub in the default browser + const open = (await import("open")).default; + await open("https://hub.continue.dev/?type=mcpServers"); + setMessage("Opened MCP servers hub in browser"); + break; case "back": onCancel(); return; diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index 15d88bf29..b3d5765e3 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -31,7 +31,7 @@ const SlashCommandUI: React.FC = ({ { name: "clear", description: "Clear the chat history" }, { name: "exit", description: "Exit the chat" }, ]; - }, [isRemoteMode, assistant?.prompts]); + }, [isRemoteMode, assistant?.prompts, assistant?.rules]); // Filter commands based on the current filter const filteredCommands = allCommands diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index e7714fbc7..dfcd19060 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -7,6 +7,9 @@ import React, { useState, } from "react"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + +import { listUserOrganizations } from "../auth/workos.js"; import { useServices } from "../hooks/useService.js"; import { ApiClientServiceState, @@ -28,7 +31,6 @@ import { useChat } from "./hooks/useChat.js"; import { useContextPercentage } from "./hooks/useContextPercentage.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { - useCurrentMode, useIntroMessage, useLoginHandlers, useSelectors, @@ -95,11 +97,58 @@ function useTUIChatServices(remoteUrl?: string) { mcp: MCPServiceState; apiClient: ApiClientServiceState; update: UpdateServiceState; - }>(["auth", "config", "model", "mcp", "apiClient", "update"]); + toolPermissions: ToolPermissionServiceState; + }>([ + "auth", + "config", + "model", + "mcp", + "apiClient", + "update", + "toolPermissions", + ]); return { services, allServicesReady, isRemoteMode }; } +// Custom hook to fetch organization name +function useOrganizationName(organizationId?: string): string | undefined { + const [organizationName, setOrganizationName] = useState( + undefined, + ); + + useEffect(() => { + if (!organizationId) { + setOrganizationName(undefined); + return; + } + + let isMounted = true; + + async function fetchOrgName() { + try { + const orgs = await listUserOrganizations(); + if (!isMounted) return; + + const org = orgs?.find((o) => o.id === organizationId); + if (org) { + setOrganizationName(org.name); + } + } catch (error) { + logger.debug("Failed to fetch organization name", { error }); + } + } + + fetchOrgName(); + + return () => { + isMounted = false; + }; + }, [organizationId]); + + return organizationName; +} + // Custom hook for chat handlers function useChatHandlers( setShowIntroMessage: (show: boolean) => void, @@ -162,11 +211,8 @@ const TUIChat: React.FC = ({ allServicesReady, ); - // State for current mode (for hiding cwd in plan/auto modes) - const currentMode = useCurrentMode(); - // Use login handlers - const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + const { handleLoginTokenSubmit } = useLoginHandlers( navigateTo, navState, closeCurrentScreen, @@ -220,6 +266,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, @@ -235,9 +282,9 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), - onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, + onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), // Remote mode configuration isRemoteMode, remoteUrl, @@ -264,6 +311,7 @@ const TUIChat: React.FC = ({ configPath, setChatHistory, handleClear, + setStaticRefreshTrigger, ); // Session selection handler @@ -290,6 +338,9 @@ const TUIChat: React.FC = ({ // State for image in clipboard status const [hasImageInClipboard, setHasImageInClipboard] = useState(false); + // Fetch organization name based on auth state + const organizationName = useOrganizationName(services.auth?.organizationId); + return ( {/* Chat history - takes up all available space above input */} @@ -312,6 +363,7 @@ const TUIChat: React.FC = ({ config={services.config?.config || undefined} model={services.model?.model || undefined} mcpService={services.mcp?.mcpService || undefined} + organizationName={organizationName} chatHistory={chatHistory} queuedMessages={queuedMessages} renderMessage={renderMessage} @@ -369,6 +421,9 @@ const TUIChat: React.FC = ({ isRemoteMode={isRemoteMode} onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} + chatHistory={chatHistory} + handleEditMessage={handleEditMessage} + onShowEditSelector={() => navigateTo("edit")} /> {/* Resource debug bar - only in verbose mode */} @@ -378,7 +433,7 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} { buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); // Small typed input should not be mixed into paste - const typedChar = "a"; - buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); - expect(buffer.text).toBe("a"); + const smallChunk = "abc"; + buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); // Both chunks buffered buffer.flushPendingInput(); + expect(buffer.text).toBe(largeChunk + smallChunk); + }); + + it("should allow typing after paste accumulation delay", () => { + vi.useFakeTimers(); + + const largeChunk = "x".repeat(100); + buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); + + // Advance time to simulate user typing after a delay + vi.advanceTimersByTime(60); // so that it is treated as typing + + const typedChar = "a"; + buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("a"); // Typed char inserted immediately + + vi.advanceTimersByTime(250); // Finalize paste expect(buffer.text).toBe("a" + largeChunk); + + vi.useRealTimers(); }); it("should preserve all chunks when expanding (content loss fix)", () => { @@ -611,6 +630,30 @@ describe("TextBuffer", () => { expect(buffer.cursor).toBe(2); }); + it("should limit ctrl+u deletion to current line", () => { + const text = "first line\nsecond line\nthird"; + buffer.setText(text); + buffer.setCursor(text.indexOf("second line") + "second line".length); + + const result = buffer.handleInput("u", { ctrl: true } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird"); + expect(buffer.cursor).toBe("first line\n".length); + }); + + it("should limit ctrl+k deletion to current line", () => { + const text = "first line\nsecond line\nthird"; + buffer.setText(text); + buffer.setCursor(text.indexOf("second line")); + + const result = buffer.handleInput("k", { ctrl: true } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird"); + expect(buffer.cursor).toBe(text.indexOf("second line")); + }); + it("should handle arrow keys", () => { let result = buffer.handleInput("", { leftArrow: true } as any); expect(result).toBe(true); @@ -644,6 +687,38 @@ describe("TextBuffer", () => { expect(buffer.cursor).toBe(0); }); + it("should delete to start of line with meta+backspace", () => { + const text = "first line\nsecond line\nthird line"; + buffer.setText(text); + const cursorPosition = text.indexOf("second line") + "second line".length; + buffer.setCursor(cursorPosition); + + const result = buffer.handleInput("", { + meta: true, + backspace: true, + } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird line"); + expect(buffer.cursor).toBe("first line\n".length); + }); + + it("should delete to end of line with meta+delete", () => { + const text = "first line\nsecond line\nthird line"; + buffer.setText(text); + const cursorPosition = text.indexOf("second line"); + buffer.setCursor(cursorPosition); + + const result = buffer.handleInput("", { + meta: true, + delete: true, + } as any); + + expect(result).toBe(true); + expect(buffer.text).toBe("first line\n\nthird line"); + expect(buffer.cursor).toBe(cursorPosition); + }); + it("should handle option key sequences", () => { const result = buffer.handleInput("\u001b\u007f", {} as any); expect(result).toBe(true); diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 103b48571..768ab0b4b 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -137,6 +137,38 @@ export class TextBuffer { } } + private deleteLineBackward(): void { + if (this._cursor === 0) { + return; + } + + const lastNewline = this._text.lastIndexOf("\n", this._cursor - 1); + const lineStart = lastNewline === -1 ? 0 : lastNewline + 1; + + if (lineStart === this._cursor) { + return; + } + + this._text = + this._text.slice(0, lineStart) + this._text.slice(this._cursor); + this._cursor = lineStart; + } + + private deleteLineForward(): void { + if (this._cursor >= this._text.length) { + return; + } + + const nextNewline = this._text.indexOf("\n", this._cursor); + const lineEnd = nextNewline === -1 ? this._text.length : nextNewline; + + if (lineEnd === this._cursor) { + return; + } + + this._text = this._text.slice(0, this._cursor) + this._text.slice(lineEnd); + } + moveToStart(): void { this._cursor = 0; } @@ -305,26 +337,24 @@ export class TextBuffer { const timeSinceLastInput = now - this._lastInputTime; // If we're already in rapid input mode and this comes quickly, add to buffer - // But only if it's a reasonably large chunk - small inputs are likely typing, not paste - // This prevents typed characters from being mixed into paste content during accumulation - if ( - this._rapidInputBuffer.length > 0 && - timeSinceLastInput < 200 && - input.length >= 50 - ) { - this._rapidInputBuffer += input; - this._lastInputTime = now; + if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 200) { + const isLikelyTyping = input.length < 50 && timeSinceLastInput >= 50; - if (this._rapidInputTimer) { - clearTimeout(this._rapidInputTimer); + if (!isLikelyTyping) { + this._rapidInputBuffer += input; + this._lastInputTime = now; + + if (this._rapidInputTimer) { + clearTimeout(this._rapidInputTimer); + } + + // Reset timer: 200ms pause indicates end of paste + this._rapidInputTimer = setTimeout(() => { + this.finalizeRapidInput(); + }, 200); + + return true; } - - // Reset timer: 200ms pause indicates end of paste - this._rapidInputTimer = setTimeout(() => { - this.finalizeRapidInput(); - }, 200); - - return true; } // Fallback paste detection: some terminals send large pastes as rapid chunks @@ -402,13 +432,10 @@ export class TextBuffer { this.moveToEnd(); return true; case "u": - // Delete from cursor to start of line - this._text = this._text.slice(this._cursor); - this._cursor = 0; + this.deleteLineBackward(); return true; case "k": - // Delete from cursor to end of line - this._text = this._text.slice(0, this._cursor); + this.deleteLineForward(); return true; case "w": this.deleteWordBackward(); @@ -422,8 +449,12 @@ export class TextBuffer { } private handleMetaKey(input: string, key: Key): boolean { - if (key.backspace || key.delete) { - this.deleteWordBackward(); + if (key.backspace) { + this.deleteLineBackward(); + return true; + } + if (key.delete) { + this.deleteLineForward(); return true; } if (key.leftArrow) { diff --git a/extensions/cli/src/ui/UserInput.keyboard.test.ts b/extensions/cli/src/ui/UserInput.keyboard.test.ts index 30cd1e0f1..075a61c46 100644 --- a/extensions/cli/src/ui/UserInput.keyboard.test.ts +++ b/extensions/cli/src/ui/UserInput.keyboard.test.ts @@ -1,29 +1,29 @@ -import { describe, expect, it, beforeEach } from "vitest"; - -import { modeService } from "../services/ModeService.js"; +import { beforeEach, describe, expect, it } from "vitest"; +import { services } from "../services/index.js"; +const toolPermissionService = services.toolPermissions; describe("UserInput Keyboard Shortcuts", () => { beforeEach(() => { // Reset to normal mode for each test - modeService.initialize({}); + toolPermissionService.initialize({}); }); describe("mode cycling logic", () => { it("should cycle through modes in correct order", () => { // Initially should be normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); // Cycle to plan - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); + toolPermissionService.switchMode("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // Cycle to auto - modeService.switchMode("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); + toolPermissionService.switchMode("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // Cycle back to normal - modeService.switchMode("normal"); - expect(modeService.getCurrentMode()).toBe("normal"); + toolPermissionService.switchMode("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); }); it("should cycle through all modes sequentially", () => { @@ -32,8 +32,8 @@ describe("UserInput Keyboard Shortcuts", () => { // Test cycling through all modes for (let i = 0; i < modes.length * 2; i++) { const expectedMode = modes[i % modes.length]; - modeService.switchMode(expectedMode); - expect(modeService.getCurrentMode()).toBe(expectedMode); + toolPermissionService.switchMode(expectedMode); + expect(toolPermissionService.getCurrentMode()).toBe(expectedMode); } }); }); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index f1726f457..fb31e4e5c 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -1,14 +1,17 @@ /* eslint-disable max-lines */ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useCallback, useState } from "react"; +import React, { useCallback, useRef, useState } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; import type { PermissionMode } from "../permissions/types.js"; import type { FileIndexServiceState } from "../services/FileIndexService.js"; -import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { messageQueue } from "../stream/messageQueue.js"; import { InputHistory } from "../util/inputHistory.js"; @@ -106,6 +109,7 @@ interface UserInputProps { hideNormalUI?: boolean; isRemoteMode?: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; } const UserInput: React.FC = ({ @@ -122,9 +126,11 @@ const UserInput: React.FC = ({ hideNormalUI = false, isRemoteMode = false, onImageInClipboardChange, + onShowEditSelector, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); + const lastEscapePressRef = useRef(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -190,17 +196,17 @@ const UserInput: React.FC = ({ // Cycle through permission modes const cycleModes = async () => { const modes: PermissionMode[] = ["normal", "plan", "auto"]; - const currentMode = modeService.getCurrentMode(); + const currentMode = services.toolPermissions.getCurrentMode(); const currentIndex = modes.indexOf(currentMode); const nextIndex = (currentIndex + 1) % modes.length; const nextMode = modes[nextIndex]; - modeService.switchMode(nextMode); + services.toolPermissions.switchMode(nextMode); // Update the service container with the new tool permissions state // Since TOOL_PERMISSIONS was registered with registerValue(), we need to // update its value directly rather than reloading from a factory - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = services.toolPermissions.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Show a brief indicator of the mode change @@ -622,6 +628,25 @@ const UserInput: React.FC = ({ return true; } + // Handle double Esc to open edit message selector + const now = Date.now(); + if ( + inputMode && + !showSlashCommands && + !showFileSearch && + !showBashMode && + onShowEditSelector && + now - lastEscapePressRef.current < 500 + ) { + // Double escape detected + onShowEditSelector(); + lastEscapePressRef.current = 0; // Reset to prevent triple-escape + return true; + } + + // Track single escape press + lastEscapePressRef.current = now; + return false; }; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx new file mode 100644 index 000000000..9e6a92874 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -0,0 +1,277 @@ +import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; + +/** + * Integration tests for the message edit feature in TUIChat + * + * Tests the full flow: + * 1. Double Esc opens EditMessageSelector + * 2. User navigates and selects a message + * 3. User edits the message + * 4. History is rewound and new message is submitted + * 5. Chat updates correctly + */ + +describe("TUIChat - Message Edit Feature", () => { + testBothModes("double Esc should open edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Verify selector is not open initially + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + // Press Esc twice quickly (within 500ms) + stdin.write("\u001b"); // First Esc + stdin.write("\u001b"); // Second Esc + + // Wait for UI to update + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is now open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should handle navigation", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector (double Esc) + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Try navigation keys + stdin.write("j"); // Down + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Up + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Verify selector is still open after navigation + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + }); + + testBothModes("edit selector should exit with Esc", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + // Press Esc to exit + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify edit selector is closed + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes("should handle edit flow without crashing", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // This test verifies the basic flow doesn't crash + // Actual behavior depends on having chat history + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Try to edit (Enter) + stdin.write("\r"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Type something + stdin.write("Test edit"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Exit without submitting (Esc) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not crash + expect(frame).toBeDefined(); + }); + + testBothModes( + "should maintain UI stability during edit operations", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Perform various operations + stdin.write("\u001b"); + stdin.write("\u001b"); // Open edit with separate Esc presses + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector opened + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + stdin.write("k"); // Navigate (no-op with 0 messages) + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b"); // Close + await new Promise((resolve) => setTimeout(resolve, 100)); + + frame = lastFrame(); + + // UI should remain stable and edit selector should be closed + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + expect(frame).not.toContain("No user messages to edit"); + }, + ); +}); + +describe("TUIChat - Edit Selector Navigation", () => { + testBothModes("should handle rapid navigation commands", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Rapid navigation + stdin.write("jjjjkkk"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle rapid input without crashing + expect(frame).toBeDefined(); + }); + + testBothModes("should handle arrow keys in edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Use arrow keys (ANSI escape sequences) + stdin.write("\u001b[A"); // Up arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b[B"); // Down arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle arrow keys + expect(frame).toBeDefined(); + }); +}); + +describe("TUIChat - Edit Feature Edge Cases", () => { + testBothModes( + "should handle opening edit selector with no chat history", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Try to open edit selector immediately (no history) + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should either show "no messages" or handle gracefully + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + }, + ); + + testBothModes("should handle single Esc (not double)", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Single Esc (should not open edit selector) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); // Wait longer than 500ms threshold + + // Verify selector did not open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + + stdin.write("\u001b"); // Another single Esc after timeout + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify selector still did not open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + }); + + testBothModes( + "should prevent triple escape from causing issues", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Triple Esc quickly + stdin.write("\u001b\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should handle gracefully (open then close, or just open) + expect(frame).toBeDefined(); + }, + ); +}); + +describe("TUIChat - Edit Feature Compatibility", () => { + testBothModes( + "edit feature should not interfere with normal input", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type normal input + stdin.write("Hello world"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should show typed text + expect(frame).toBeDefined(); + // Normal input should work + }, + ); + + testBothModes( + "should not conflict with other Esc-based features", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type something + stdin.write("test"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Single Esc (might clear input or do other things) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); + + const frame = lastFrame(); + + // Should handle without conflicts + expect(frame).toBeDefined(); + }, + ); +}); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx index f8d56a5f0..b38a90cb6 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testSingleMode } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - @ File Search Tests", () => { testSingleMode("shows @ character when user types @", "local", async () => { @@ -56,9 +57,8 @@ describe("TUIChat - @ File Search Tests", () => { // Type multiple @ characters stdin.write("@@test"); - // Wait for UI update - await new Promise((resolve) => setTimeout(resolve, 500)); + await waitForNextRender(); const frame = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx index 35aa50a16..e76c00806 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx @@ -1,10 +1,12 @@ -import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; +import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - User Input Tests", () => { - testBothModes("shows typed text in input field", (mode) => { + testBothModes("shows typed text in input field", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); stdin.write("Testing 123"); + await waitForNextRender(); const frame = lastFrame(); // The input might be in a different format, let's be more flexible @@ -23,13 +25,14 @@ describe("TUIChat - User Input Tests", () => { testBothModes("handles Enter key to submit", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); + await waitForNextRender(); const beforeEnter = lastFrame(); expect(beforeEnter).toContain("Ask anything"); stdin.write("\r"); // Wait for the UI to update after pressing enter - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 500)); const afterEnter = lastFrame(); @@ -46,11 +49,12 @@ describe("TUIChat - User Input Tests", () => { testBothModes( "handles special characters in input without crashing", - (mode) => { + async (mode) => { const { lastFrame, stdin } = renderInMode(mode); // Try typing various special characters stdin.write("!@#$%^&*()"); + await waitForNextRender(); const frame = lastFrame(); @@ -58,8 +62,9 @@ describe("TUIChat - User Input Tests", () => { expect(frame).toBeDefined(); expect(frame).not.toBe(""); - // UI should still be functional - expect(frame).toContain("Ask anything"); + // UI should still be functional and show the typed special characters + // Note: "Ask anything" placeholder is replaced when text is typed + expect(frame).toContain("!@#$%^&*()"); // Mode-specific UI elements if (mode === "remote") { diff --git a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx index 1b60203c9..c29727401 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx @@ -1,21 +1,7 @@ -import { vi, beforeEach, describe, it, expect } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -// Mock the services -const mockToolPermissionService = { - reloadPermissions: vi.fn(), - getState: vi.fn(), - getCurrentMode: vi.fn(() => "normal"), -}; - -const mockServices = { - mode: { - getToolPermissionService: vi.fn(() => mockToolPermissionService), - }, -}; - -vi.mock("../../services/index.js", () => ({ - services: mockServices, -})); +import { services } from "../../services/index.js"; +vi.mock("../../services/index.js"); // Mock the permission system vi.mock("../../permissions/policyWriter.js", () => ({ @@ -63,7 +49,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This is the key part we're testing - reload should be called - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Handle errors gracefully } @@ -76,7 +62,7 @@ describe("Permission Policy Reload Workflow", () => { expect(addPolicyToYaml).toHaveBeenCalledWith( "tool: Edit\npermission: allow", ); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); }); it("should handle permission reload failure gracefully", async () => { @@ -90,7 +76,7 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock reloadPermissions to fail - mockToolPermissionService.reloadPermissions.mockRejectedValue( + vi.mocked(services.toolPermissions.reloadPermissions).mockRejectedValue( new Error("Reload failed"), ); @@ -118,7 +104,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This should fail but not break the flow - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Error should be caught and handled gracefully errorCaught = true; @@ -127,7 +113,7 @@ describe("Permission Policy Reload Workflow", () => { // Verify that despite the reload failure, the policy was still created expect(addPolicyToYaml).toHaveBeenCalled(); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); expect(errorCaught).toBe(true); }); @@ -142,7 +128,9 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock successful reload - mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined); + vi.mocked(services.toolPermissions.reloadPermissions).mockResolvedValue( + undefined, + ); const mockActiveRequest = { toolName: "Edit", @@ -167,13 +155,13 @@ describe("Permission Policy Reload Workflow", () => { ); await addPolicyToYaml(policyRule); - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } // AFTER: Policy is now active without restart // Next time user tries to edit a file, it should be automatically allowed - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); // This represents the improvement: the new policy takes effect immediately // without requiring the user to restart the Continue CLI diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index 77b8161ba..c7ab739e5 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -4,11 +4,14 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { getAllTools } from "src/stream/handleToolCalls.js"; -import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; -import { modeService } from "../../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../../services/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; - +const toolPermissionService = services.toolPermissions; describe("TUIChat - Plan Mode Bug Reproduction", () => { let context: any; @@ -20,7 +23,9 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { }); // Ensure mode service is properly initialized in normal mode - await modeService.initialize({}); + await toolPermissionService.doInitialize({ + mode: "normal", + }); }); afterEach(() => { @@ -142,10 +147,10 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { // that causes the actual bug in production // First, set up a realistic service state (not mocked) - await modeService.initialize({ isHeadless: false }); + await toolPermissionService.initialize({ isHeadless: false }); // Register the tool permissions service like the real app does - const initialState = modeService.getToolPermissionService().getState(); + const initialState = toolPermissionService.getState(); serviceContainer.registerValue( SERVICE_NAMES.TOOL_PERMISSIONS, initialState, @@ -155,7 +160,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { expect(() => getAllTools()).not.toThrow(); // Switch modes WITHOUT updating the service container (this simulates the bug) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // The service container still has the old state, so getAllTools() should not find // the updated state with plan mode permissions. However, since the ToolPermissionService @@ -172,9 +177,5 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { const tools = getAllTools(); expect(tools).toBeDefined(); expect(Array.isArray(tools)).toBe(true); - - // But the tools returned will be for "normal" mode, not "plan" mode - // In plan mode, many tools should be excluded, but with stale normal state, all tools are available - const planModeState = modeService.getToolPermissionService().getState(); }); }); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx index 9e67826c5..1f63f3814 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - Slash Commands Tests", () => { testBothModes("shows slash when user types /", async (mode) => { @@ -6,9 +7,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type / to trigger slash command stdin.write("/"); - - // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frame = lastFrame(); @@ -29,9 +28,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi to trigger slash command filtering stdin.write("/exi"); - - // Wait a bit for the UI to update (allow extra time in both modes) - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -52,12 +49,10 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi and then tab stdin.write("/exi"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); stdin.write("\t"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterTab = lastFrame(); @@ -80,8 +75,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type just / stdin.write("/"); - - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -113,8 +107,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command name first stdin.write("/title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterCommand = lastFrame(); if (mode === "remote") { @@ -127,8 +120,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Now add a space and arguments stdin.write(" My Session Title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterArgs = lastFrame(); @@ -151,8 +143,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command with arguments stdin.write("/title Test Session"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameBeforeEnter = lastFrame(); expect(frameBeforeEnter).toContain("/title"); @@ -160,8 +151,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Press Enter - this should execute the command, not try to autocomplete stdin.write("\r"); - - await new Promise((resolve) => setTimeout(resolve, 300)); + await waitForNextRender(); const frameAfterEnter = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts index e450b809a..37ebb5c3e 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts +++ b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts @@ -422,6 +422,20 @@ export async function sendMessage( await new Promise((resolve) => setTimeout(resolve, waitTime)); } +/** + * Helper to wait for next render cycle to complete + * Use this after stdin.write() to ensure at least one render has occurred + * This prevents flaky tests caused by calling lastFrame() before React renders + */ +export async function waitForNextRender(): Promise { + // Wait for multiple ticks to ensure render completes + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + // Add a delay to allow Ink terminal UI to render + // CI environments are slower, so we need a longer delay + await new Promise((resolve) => setTimeout(resolve, 500)); +} + /** * Helper to check if UI shows remote mode indicators */ diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx new file mode 100644 index 000000000..7c3225da6 --- /dev/null +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -0,0 +1,76 @@ +import type { AssistantConfig } from "@continuedev/sdk"; +import React from "react"; + +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import { UserInput } from "../UserInput.js"; + +import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; + +interface ChatScreenContentProps { + activePermissionRequest: ActivePermissionRequest | null; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + stopStream?: boolean, + ) => void; + handleUserMessage: (message: string, imageMap?: Map) => void; + isWaitingForResponse: boolean; + isCompacting: boolean; + inputMode: boolean; + handleInterrupt: () => void; + assistant?: AssistantConfig; + wasInterrupted: boolean; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; + onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; +} + +export const ChatScreenContent: React.FC = ({ + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + isCompacting, + inputMode, + handleInterrupt, + assistant, + wasInterrupted, + handleFileAttached, + isInputDisabled, + isRemoteMode, + onImageInClipboardChange, + onShowEditSelector, +}) => { + if (activePermissionRequest) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/extensions/cli/src/ui/components/ModeIndicator.test.tsx b/extensions/cli/src/ui/components/ModeIndicator.test.tsx index a341e826f..6301c2204 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.test.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.test.tsx @@ -1,15 +1,21 @@ import { render } from "ink-testing-library"; import React from "react"; -import { describe, expect, it, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it } from "vitest"; -import { modeService } from "../../services/ModeService.js"; +import { initializeServices, services } from "src/services/index.js"; import { ModeIndicator } from "./ModeIndicator.js"; describe("ModeIndicator", () => { - beforeEach(() => { + const toolPermissionService = services.toolPermissions; + beforeEach(async () => { // Reset to normal mode for each test - modeService.initialize({}); + await initializeServices({ + headless: true, + toolPermissionOverrides: { + mode: "normal", + }, + }); }); describe("mode display", () => { @@ -29,13 +35,13 @@ describe("ModeIndicator", () => { }); it("should use current mode from service when no mode prop provided", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("plan]"); }); it("should prioritize mode prop over service mode", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("auto]"); }); @@ -49,17 +55,17 @@ describe("ModeIndicator", () => { expect(lastFrame()).toBe(""); // Switch to plan - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); rerender(); expect(lastFrame()).toContain("plan]"); // Switch to auto - modeService.switchMode("auto"); + toolPermissionService.switchMode("auto"); rerender(); expect(lastFrame()).toContain("auto]"); // Switch back to normal - modeService.switchMode("normal"); + toolPermissionService.switchMode("normal"); rerender(); expect(lastFrame()).toBe(""); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.tsx b/extensions/cli/src/ui/components/ModeIndicator.tsx index 05833df68..30cbd558c 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.tsx @@ -1,38 +1,21 @@ import { Text } from "ink"; -import React, { useEffect, useState } from "react"; +import React from "react"; + +import { useServices } from "src/hooks/useService.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { SERVICE_NAMES } from "src/services/types.js"; import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; interface ModeIndicatorProps { mode?: PermissionMode; } const ModeIndicator: React.FC = ({ mode }) => { - const [currentMode, setCurrentMode] = useState( - mode || modeService.getCurrentMode(), - ); - - // Update mode when it changes (for cases where mode prop is not provided) - useEffect(() => { - if (!mode) { - // Listen for immediate mode changes - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - - // Set initial mode - setCurrentMode(modeService.getCurrentMode()); - - return () => { - modeService.off("modeChanged", handleModeChange); - }; - } else if (mode !== currentMode) { - setCurrentMode(mode); - } - }, [mode]); + const { services } = useServices<{ + toolPermissions: ToolPermissionServiceState; + }>([SERVICE_NAMES.TOOL_PERMISSIONS]); + const currentMode = mode ?? services.toolPermissions?.currentMode ?? "normal"; // Don't show indicator for normal mode to keep it clean if (currentMode === "normal") { diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 977d6954a..694c8f215 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -3,18 +3,21 @@ import React from "react"; import { UpdateServiceState } from "src/services/types.js"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; +import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UpdateSelector } from "../UpdateSelector.js"; import { UserInput } from "../UserInput.js"; +import { ChatScreenContent } from "./ChatScreenContent.js"; import { SessionSelectorWithLoading } from "./SessionSelectorWithLoading.js"; -import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ScreenContentProps { isScreenActive: (screen: NavigationScreen) => boolean; @@ -26,7 +29,7 @@ interface ScreenContentProps { handleSessionSelect: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; - activePermissionRequest: any; + activePermissionRequest: ActivePermissionRequest | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, @@ -44,6 +47,9 @@ interface ScreenContentProps { isRemoteMode: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; + chatHistory?: ChatHistoryItem[]; + handleEditMessage?: (messageIndex: number, newContent: string) => void; + onShowEditSelector?: () => void; } function hideScreenContent(state?: UpdateServiceState) { @@ -77,6 +83,9 @@ export const ScreenContent: React.FC = ({ isRemoteMode, onImageInClipboardChange, diffContent, + chatHistory = [], + handleEditMessage, + onShowEditSelector, }) => { if (hideScreenContent(services.update)) { return null; @@ -162,33 +171,40 @@ export const ScreenContent: React.FC = ({ ); } + // Edit message selector + if (isScreenActive("edit")) { + return ( + { + if (handleEditMessage) { + handleEditMessage(messageIndex, newContent); + } + closeCurrentScreen(); + }} + onExit={closeCurrentScreen} + /> + ); + } + // Chat screen with input area if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } return ( - ); } diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 5cb553762..09f9d8bf5 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -14,6 +14,7 @@ interface StaticChatContentProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; chatHistory: ChatHistoryItem[]; queuedMessages?: QueuedMessage[]; renderMessage: ( @@ -29,6 +30,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, chatHistory, queuedMessages = [], renderMessage, @@ -96,6 +98,7 @@ export const StaticChatContent: React.FC = ({ config={config} model={model} mcpService={mcpService} + organizationName={organizationName} />, ); } @@ -129,6 +132,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, processedChatHistory, renderMessage, ]); diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index fd922ca51..6d43414dd 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -20,6 +20,7 @@ export type NavigationScreen = | "session" // Session selector | "diff" // Full-screen diff overlay | "update" // Update selector + | "edit" // Edit message selector | "session"; // Session selector interface NavigationState { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 5cb661333..fe3dc8d05 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,8 +58,8 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, - onLoginPrompt: _onLoginPrompt, onClear, + onRefreshStatic, isRemoteMode = false, remoteUrl, onShowDiff, @@ -455,7 +455,11 @@ export function useChat({ message: string, imageMap?: Map, isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], ) => { + // Use baseHistory if provided (e.g., when editing a message), + // otherwise use current chatHistory + const currentHistory = baseHistory ?? chatHistory; // Handle special commands const handled = await handleSpecialCommands({ message, @@ -524,7 +528,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -591,7 +595,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -721,6 +725,42 @@ export function useChat({ setQueuedMessages([]); }; + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + logger.debug("handleEditMessage called", { + messageIndex, + currentHistoryLength: chatHistory.length, + }); + + // Rewind chat history to exclude the message being edited + const rewindedHistory = chatHistory.slice(0, messageIndex); + + logger.debug("Rewinding history for edit", { + from: chatHistory.length, + to: rewindedHistory.length, + }); + + // Clear any queued messages + setQueuedMessages([]); + + // Clear attached files + setAttachedFiles([]); + + // Update the session with the rewound history + updateSessionHistory(rewindedHistory); + + // Force refresh of StaticChatContent to show truncated history + if (onRefreshStatic) { + onRefreshStatic(); + } + + // Resubmit the edited message with the rewound history as the base + // This ensures processMessage uses the correct base history + await processMessage(newContent, undefined, false, rewindedHistory); + }; + const handleToolPermissionResponse = async ( requestId: string, approved: boolean, @@ -749,7 +789,7 @@ export function useChat({ logger.debug(`Policy created: ${policyRule}`); // Reload permissions to pick up the new policy without requiring restart - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { logger.error("Failed to create policy or reload permissions", { error, @@ -803,6 +843,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index bf449191b..2fe0b0b81 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,9 +18,9 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; + onRefreshStatic?: () => void; // Remote mode props isRemoteMode?: boolean; remoteUrl?: string; @@ -38,6 +38,7 @@ export interface ActivePermissionRequest { toolArgs: any; requestId: string; toolCallPreview?: ToolCallPreview[]; + hasDynamicEvaluation?: boolean; } export interface RemoteServerState { diff --git a/extensions/cli/src/ui/hooks/useModelSelector.ts b/extensions/cli/src/ui/hooks/useModelSelector.ts index c01439bd9..e00f21981 100644 --- a/extensions/cli/src/ui/hooks/useModelSelector.ts +++ b/extensions/cli/src/ui/hooks/useModelSelector.ts @@ -4,7 +4,7 @@ import { serviceContainer, services, } from "../../services/index.js"; -import { ModelServiceState } from "../../services/types.js"; +import { AuthServiceState, ModelServiceState } from "../../services/types.js"; import { useNavigation } from "../context/NavigationContext.js"; interface ModelOption { @@ -21,11 +21,13 @@ interface UseModelSelectorProps { messageType: "system"; }) => void; onModelSwitch?: () => void; + onRefreshUI?: () => void; } export function useModelSelector({ onMessage, onModelSwitch, + onRefreshUI, }: UseModelSelectorProps) { const { closeCurrentScreen } = useNavigation(); @@ -44,8 +46,17 @@ export function useModelSelector({ ); // Persist the model choice using the actual model name + // and update the auth service state to reflect the change if (modelInfo?.name) { - updateModelName(modelInfo.name); + const updatedAuthConfig = updateModelName(modelInfo.name); + + // Update the AUTH service state in the container with the new config + // This ensures that when MODEL service is reloaded, it gets the updated auth config + const currentAuthState = services.auth.getState(); + serviceContainer.set(SERVICE_NAMES.AUTH, { + ...currentAuthState, + authConfig: updatedAuthConfig, + }); } onMessage({ @@ -58,6 +69,11 @@ export function useModelSelector({ if (onModelSwitch) { onModelSwitch(); } + + // Force UI refresh to update the IntroMessage with new model + if (onRefreshUI) { + onRefreshUI(); + } } catch (error: any) { onMessage({ role: "system", diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 04b4cf25d..b4b55fa4a 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -1,7 +1,5 @@ import { useCallback, useEffect, useState } from "react"; -import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; @@ -150,31 +148,12 @@ export function useLoginHandlers( return { handleLoginPrompt, handleLoginTokenSubmit }; } -// Custom hook for mode tracking -export function useCurrentMode() { - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), - ); - - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); - - return currentMode; -} - // Custom hook to combine all selector logic export function useSelectors( configPath: string | undefined, setChatHistory: React.Dispatch>, handleClear: () => void, + setStaticRefreshTrigger?: React.Dispatch>, ): { handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; @@ -205,6 +184,12 @@ export function useSelectors( }, ]); }, + onRefreshUI: () => { + // Force a UI refresh to update the IntroMessage with new model + if (setStaticRefreshTrigger) { + setStaticRefreshTrigger((prev) => prev + 1); + } + }, }); return { diff --git a/extensions/cli/src/util/apiClient.test.ts b/extensions/cli/src/util/apiClient.test.ts new file mode 100644 index 000000000..09bb12ed5 --- /dev/null +++ b/extensions/cli/src/util/apiClient.test.ts @@ -0,0 +1,283 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { + ApiRequestError, + AuthenticationRequiredError, + del, + get, + makeAuthenticatedRequest, + post, + put, +} from "./apiClient.js"; + +// Mock the dependencies +vi.mock("../auth/workos.js", () => ({ + loadAuthConfig: vi.fn(), + getAccessToken: vi.fn(), +})); + +vi.mock("../env.js", () => ({ + env: { + apiBase: "https://api.continue.dev", + }, +})); + +vi.mock("./logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock fetch globally +global.fetch = vi.fn(); + +describe("apiClient", () => { + let mockLoadAuthConfig: any; + let mockGetAccessToken: any; + const mockFetch = vi.mocked(global.fetch); + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mocked functions + const authModule = await import("../auth/workos.js"); + mockLoadAuthConfig = vi.mocked(authModule.loadAuthConfig); + mockGetAccessToken = vi.mocked(authModule.getAccessToken); + + // Setup default successful authentication + mockLoadAuthConfig.mockReturnValue({ some: "config" }); + mockGetAccessToken.mockReturnValue("test-access-token"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("makeAuthenticatedRequest", () => { + test("should make successful API request", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ data: "test" }), + } as unknown as Response); + + const result = await makeAuthenticatedRequest("test-endpoint", { + method: "POST", + body: { key: "value" }, + }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("test-endpoint", "https://api.continue.dev"), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-access-token", + }, + body: JSON.stringify({ key: "value" }), + }, + ); + + expect(result).toEqual({ + data: { data: "test" }, + status: 200, + ok: true, + }); + }); + + test("should handle non-JSON response", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("text/plain") }, + text: vi.fn().mockResolvedValue("plain text response"), + } as unknown as Response); + + const result = await makeAuthenticatedRequest("test-endpoint"); + + expect(result.data).toBe("plain text response"); + }); + + test("should throw AuthenticationRequiredError when no auth config", async () => { + mockLoadAuthConfig.mockReturnValue(null); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + AuthenticationRequiredError, + ); + }); + + test("should throw AuthenticationRequiredError when no access token", async () => { + mockGetAccessToken.mockReturnValue(null); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + AuthenticationRequiredError, + ); + }); + + test("should throw ApiRequestError on API error", async () => { + mockFetch.mockResolvedValue({ + ok: false, + status: 404, + statusText: "Not Found", + headers: { get: vi.fn() }, + text: vi.fn().mockResolvedValue("Resource not found"), + } as unknown as Response); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + ApiRequestError, + ); + }); + + test("should handle network error", async () => { + mockFetch.mockRejectedValue(new Error("Network error")); + + await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow( + "Request failed: Network error", + ); + }); + + test("should handle string body", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ success: true }), + } as unknown as Response); + + await makeAuthenticatedRequest("test-endpoint", { + method: "POST", + body: "raw string body", + }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + body: "raw string body", + }), + ); + }); + + test("should merge custom headers", async () => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({}), + } as unknown as Response); + + await makeAuthenticatedRequest("test-endpoint", { + headers: { "Custom-Header": "custom-value" }, + }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-access-token", + "Custom-Header": "custom-value", + }, + }), + ); + }); + }); + + describe("convenience methods", () => { + beforeEach(() => { + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + headers: { get: vi.fn().mockReturnValue("application/json") }, + json: vi.fn().mockResolvedValue({ success: true }), + } as unknown as Response); + }); + + test("get method should make GET request", async () => { + await get("test-endpoint"); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ method: "GET" }), + ); + }); + + test("post method should make POST request", async () => { + await post("test-endpoint", { data: "test" }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + body: JSON.stringify({ data: "test" }), + }), + ); + }); + + test("put method should make PUT request", async () => { + await put("test-endpoint", { data: "test" }); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "PUT", + body: JSON.stringify({ data: "test" }), + }), + ); + }); + + test("del method should make DELETE request", async () => { + await del("test-endpoint"); + + expect(mockFetch).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ method: "DELETE" }), + ); + }); + }); + + describe("error classes", () => { + test("AuthenticationRequiredError should have correct properties", () => { + const error = new AuthenticationRequiredError(); + + expect(error.name).toBe("AuthenticationRequiredError"); + expect(error.message).toBe( + "Not authenticated. Please run 'cn login' first.", + ); + }); + + test("AuthenticationRequiredError should accept custom message", () => { + const customMessage = "Custom auth error"; + const error = new AuthenticationRequiredError(customMessage); + + expect(error.message).toBe(customMessage); + }); + + test("ApiRequestError should have correct properties", () => { + const error = new ApiRequestError(404, "Not Found", "Resource not found"); + + expect(error.name).toBe("ApiRequestError"); + expect(error.status).toBe(404); + expect(error.statusText).toBe("Not Found"); + expect(error.response).toBe("Resource not found"); + expect(error.message).toContain("404"); + expect(error.message).toContain("Not Found"); + expect(error.message).toContain("Resource not found"); + }); + + test("ApiRequestError should work without response text", () => { + const error = new ApiRequestError(500, "Internal Server Error"); + + expect(error.response).toBeUndefined(); + expect(error.message).toContain("500"); + expect(error.message).toContain("Internal Server Error"); + expect(error.message).not.toContain("undefined"); + }); + }); +}); diff --git a/extensions/cli/src/util/apiClient.ts b/extensions/cli/src/util/apiClient.ts new file mode 100644 index 000000000..16119c4a0 --- /dev/null +++ b/extensions/cli/src/util/apiClient.ts @@ -0,0 +1,193 @@ +/* eslint-disable max-classes-per-file */ +import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; +import { env } from "../env.js"; + +import { logger } from "./logger.js"; + +export interface ApiRequestOptions { + method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; + body?: Record | string; + headers?: Record; +} + +export interface ApiResponse { + data: T; + status: number; + ok: boolean; +} + +export interface ApiError extends Error { + status: number; + statusText: string; + response?: string; +} + +/** + * Authentication error thrown when user is not authenticated + */ +export class AuthenticationRequiredError extends Error { + constructor(message = "Not authenticated. Please run 'cn login' first.") { + super(message); + this.name = "AuthenticationRequiredError"; + } +} + +/** + * API error thrown when the request fails + */ +export class ApiRequestError extends Error implements ApiError { + status: number; + statusText: string; + response?: string; + + constructor(status: number, statusText: string, response?: string) { + const message = response + ? `API request failed: ${status} ${statusText} - ${response}` + : `API request failed: ${status} ${statusText}`; + super(message); + this.name = "ApiRequestError"; + this.status = status; + this.statusText = statusText; + this.response = response; + } +} + +/** + * Make an authenticated API request to the Continue API + * Handles authentication, error handling, and response parsing + */ +export async function makeAuthenticatedRequest( + endpoint: string, + options: ApiRequestOptions = {}, +): Promise> { + // Handle authentication + const authConfig = loadAuthConfig(); + if (!authConfig) { + throw new AuthenticationRequiredError(); + } + + const accessToken = getAccessToken(authConfig); + if (!accessToken) { + throw new AuthenticationRequiredError( + "No access token available. Please run 'cn login' first.", + ); + } + + // Prepare request options + const { method = "GET", body, headers = {} } = options; + + const requestOptions: RequestInit = { + method, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}`, + ...headers, + }, + }; + + // Add body if provided + if (body) { + requestOptions.body = + typeof body === "string" ? body : JSON.stringify(body); + } + + try { + // Make the request + const url = new URL(endpoint, env.apiBase); + logger.debug(`Making ${method} request to: ${url.toString()}`); + + const response = await fetch(url, requestOptions); + + // Handle error responses + if (!response.ok) { + const errorText = await response.text(); + logger.error(`API request failed: ${response.status} ${errorText}`); + throw new ApiRequestError( + response.status, + response.statusText, + errorText, + ); + } + + // Parse response + let data: T; + const contentType = response.headers.get("content-type"); + if (contentType && contentType.includes("application/json")) { + data = await response.json(); + } else { + // If not JSON, return the text as data + data = (await response.text()) as T; + } + + logger.debug(`API request successful: ${response.status}`); + + return { + data, + status: response.status, + ok: response.ok, + }; + } catch (error) { + // Re-throw our custom errors + if ( + error instanceof AuthenticationRequiredError || + error instanceof ApiRequestError + ) { + throw error; + } + + // Handle network/other errors + const errorMessage = error instanceof Error ? error.message : String(error); + logger.error(`Network/request error: ${errorMessage}`); + throw new Error(`Request failed: ${errorMessage}`); + } +} + +/** + * Convenience function for GET requests + */ +export async function get( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "GET", headers }); +} + +/** + * Convenience function for POST requests + */ +export async function post( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "POST", + body, + headers, + }); +} + +/** + * Convenience function for PUT requests + */ +export async function put( + endpoint: string, + body?: Record | string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { + method: "PUT", + body, + headers, + }); +} + +/** + * Convenience function for DELETE requests + */ +export async function del( + endpoint: string, + headers?: Record, +): Promise> { + return makeAuthenticatedRequest(endpoint, { method: "DELETE", headers }); +} diff --git a/extensions/cli/src/util/modelPersistence.ts b/extensions/cli/src/util/modelPersistence.ts new file mode 100644 index 000000000..ace51c396 --- /dev/null +++ b/extensions/cli/src/util/modelPersistence.ts @@ -0,0 +1,19 @@ +import { GlobalContext } from "core/util/GlobalContext.js"; + +/** + * Get the persisted model name for CLI from GlobalContext + * Used for unauthenticated users + */ +export function getPersistedModelName(): string | null { + const globalContext = new GlobalContext(); + return globalContext.get("cliSelectedModel") ?? null; +} + +/** + * Persist the model name for CLI to GlobalContext + * Used for unauthenticated users + */ +export function persistModelName(modelName: string | null): void { + const globalContext = new GlobalContext(); + globalContext.update("cliSelectedModel", modelName ?? undefined); +} diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 4644e17c8..1b1a62086 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -1,12 +1,12 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; -import * as args from "../args.js"; +import { processRule } from "../hubLoader.js"; import { processAndCombinePrompts } from "./promptProcessor.js"; // Mock the args module -vi.mock("../args.js", () => ({ - processPromptOrRule: vi.fn(), +vi.mock("../hubLoader.js", () => ({ + processRule: vi.fn(), })); // Mock the logger @@ -38,7 +38,7 @@ describe("promptProcessor", () => { }); it("should process single additional prompt without initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockResolvedValue("processed prompt"); const result = await processAndCombinePrompts(["prompt1"]); @@ -48,7 +48,7 @@ describe("promptProcessor", () => { }); it("should combine multiple processed prompts", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("first prompt") .mockResolvedValueOnce("second prompt"); @@ -62,7 +62,7 @@ describe("promptProcessor", () => { }); it("should combine processed prompts with initial prompt", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("processed1") .mockResolvedValueOnce("processed2"); @@ -76,7 +76,7 @@ describe("promptProcessor", () => { }); it("should handle processing errors and continue with successful ones", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("success1") .mockRejectedValueOnce(new Error("processing failed")) @@ -89,7 +89,7 @@ describe("promptProcessor", () => { }); it("should return initial prompt when all processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockRejectedValueOnce(new Error("fail1")) .mockRejectedValueOnce(new Error("fail2")); @@ -103,7 +103,7 @@ describe("promptProcessor", () => { }); it("should return undefined when all processing fails and no initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed")); const result = await processAndCombinePrompts(["bad"]); @@ -112,7 +112,7 @@ describe("promptProcessor", () => { }); it("should warn when processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("test error")); const { logger } = await import("./logger.js"); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index c6173738f..b0d24b764 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -1,4 +1,4 @@ -import { processPromptOrRule } from "../args.js"; +import { processRule } from "../hubLoader.js"; import { logger } from "./logger.js"; @@ -20,7 +20,7 @@ export async function processAndCombinePrompts( for (const promptSpec of additionalPrompts) { try { - const processed = await processPromptOrRule(promptSpec); + const processed = await processRule(promptSpec); processedPrompts.push(processed); } catch (error: any) { logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`); diff --git a/extensions/cli/src/util/yamlConfigUpdater.test.ts b/extensions/cli/src/util/yamlConfigUpdater.test.ts index cb65b6b9e..c92d035aa 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.test.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.test.ts @@ -12,7 +12,7 @@ describe("updateAnthropicModelInYaml", () => { expect(result).toContain("name: Local Config"); expect(result).toContain("version: 1.0.0"); expect(result).toContain("schema: v1"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -21,7 +21,7 @@ describe("updateAnthropicModelInYaml", () => { const result = updateAnthropicModelInYaml(invalidYaml, testApiKey); expect(result).toContain("name: Local Config"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); }); @@ -44,7 +44,7 @@ models: expect(result).toContain("# My Continue config"); expect(result).toContain("# List of available models"); expect(result).toContain("uses: openai/gpt-4"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -55,7 +55,7 @@ version: 1.0.0 schema: v1 # List of available models models: - - uses: anthropic/claude-4-sonnet + - uses: anthropic/claude-sonnet-4-5 with: ANTHROPIC_API_KEY: old-key `; @@ -64,7 +64,7 @@ models: expect(result).toContain("# My Continue config"); expect(result).toContain("# List of available models"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).not.toContain("old-key"); }); @@ -84,7 +84,7 @@ models: const result = updateAnthropicModelInYaml(existingConfig, testApiKey); expect(result).toContain("uses: openai/gpt-4"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); }); @@ -94,7 +94,7 @@ models: version: 1.0.0 schema: v1 models: - - uses: anthropic/claude-4-sonnet + - uses: anthropic/claude-sonnet-4-5 with: ANTHROPIC_API_KEY: old-anthropic-key - uses: openai/gpt-4 @@ -104,7 +104,7 @@ models: const result = updateAnthropicModelInYaml(existingConfig, testApiKey); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("uses: openai/gpt-4"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); expect(result).toContain("OPENAI_API_KEY: TEST-openai-test"); @@ -112,7 +112,7 @@ models: // Should only have one anthropic model const anthropicMatches = result.match( - /uses: anthropic\/claude-4-sonnet/g, + /uses: anthropic\/claude-sonnet-4-5/g, ); expect(anthropicMatches).toHaveLength(1); }); @@ -130,7 +130,7 @@ schema: v1 expect(result).toContain("name: Local Config"); expect(result).toContain("models:"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); @@ -147,7 +147,7 @@ models: [] ); expect(result).toContain("name: Local Config"); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); }); @@ -189,7 +189,7 @@ models: "not an array" const result = updateAnthropicModelInYaml(malformedConfig, testApiKey); - expect(result).toContain("uses: anthropic/claude-4-sonnet"); + expect(result).toContain("uses: anthropic/claude-sonnet-4-5"); expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789"); }); diff --git a/extensions/cli/src/util/yamlConfigUpdater.ts b/extensions/cli/src/util/yamlConfigUpdater.ts index 738f075cf..4c249bb1f 100644 --- a/extensions/cli/src/util/yamlConfigUpdater.ts +++ b/extensions/cli/src/util/yamlConfigUpdater.ts @@ -27,7 +27,7 @@ export function updateAnthropicModelInYaml( apiKey: string, ): string { const newModel: ModelConfig = { - uses: "anthropic/claude-4-sonnet", + uses: "anthropic/claude-sonnet-4-5", with: { ANTHROPIC_API_KEY: apiKey, }, @@ -62,7 +62,7 @@ export function updateAnthropicModelInYaml( // Filter out existing anthropic models config.models = config.models.filter( - (model: any) => !model || model.uses !== "anthropic/claude-4-sonnet", + (model: any) => !model || model.uses !== "anthropic/claude-sonnet-4-5", ); // Add the new anthropic model diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 9c0d4c5b8..1862c9b23 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,5 +1,5 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginVersion=1.0.46 +pluginVersion=1.0.47 platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt new file mode 100644 index 000000000..71f8412a5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt @@ -0,0 +1,14 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.vfs.VirtualFile + +fun AnActionEvent.getSelectedFiles(): Array { + val multipleFiles = this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) + if (multipleFiles != null) { + return multipleFiles + } + + return this.getData(CommonDataKeys.VIRTUAL_FILE)?.let { arrayOf(it) } ?: emptyArray() +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt new file mode 100644 index 000000000..8a8884ae1 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt @@ -0,0 +1,38 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent + +class AddToChatAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val browser = e.project?.getBrowser() ?: return + val selectedFiles = e.getSelectedFiles() + + val requestData = selectedFiles.map { vFile -> + val type = if (vFile.isDirectory) "folder" else "file" + + mapOf( + "type" to type, + "fullPath" to vFile.url, + "name" to vFile.name, + ) + } + val requestParams = mapOf( + "data" to requestData + ) + + browser.sendToWebview("addToChat", requestParams) + } + + override fun update(e: AnActionEvent) { + val files = e.getSelectedFiles() + + val isAvailable = files.isNotEmpty() + + e.presentation.isVisible = isAvailable + } + + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT +} 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 61cda0c42..501a56bc3 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 @@ -29,7 +29,9 @@ import java.nio.charset.StandardCharsets import java.nio.file.Paths import javax.swing.* import com.intellij.openapi.components.service +import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager +import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener @@ -39,6 +41,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.vfs.VirtualFile +import com.intellij.util.Function fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -193,6 +196,41 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { } }) + // Handle workspace directories changes + connection.subscribe( + ModuleListener.TOPIC, + object : ModuleListener { + override fun modulesAdded(project: Project, modules: MutableList) { + + val allModulePaths = ModuleManager.getInstance(project).modules + .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } } + + val topLevelModulePaths = allModulePaths + .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } } + + continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray(); + } + + override fun moduleRemoved(project: Project, module: Module) { + val removedPaths = ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } ; + continuePluginService.workspacePaths = continuePluginService.workspacePaths?.toList()?.filter { path -> removedPaths.none {removedPath -> path == removedPath }}?.toTypedArray(); + } + + override fun modulesRenamed( + project: Project, + modules: MutableList, + oldNameProvider: Function + ) { + val allModulePaths = ModuleManager.getInstance(project).modules + .flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } } + + val topLevelModulePaths = allModulePaths + .filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } } + + continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray() + } + } + ) connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun fileClosed(source: FileEditorManager, file: VirtualFile) { 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 f9d82e377..417f12cdb 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 @@ -94,6 +94,7 @@ class MessageTypes { "mcp/reloadServer", "mcp/startAuthentication", "mcp/removeAuthentication", + "mcp/setServerEnabled", "mcp/getPrompt", "context/getContextItems", "context/getSymbolsForFiles", @@ -144,6 +145,7 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "tools/evaluatePolicy", + "tools/preprocessArgs", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 9f407a573..c4eed42d3 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -181,5 +181,12 @@ + + + + + diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index aa8843202..e22df61b8 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -968,11 +968,6 @@ "enum": [ "chat-bison-001", "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "gemini-1.5-flash-8b", "gemini-2.0-flash-exp", "gemini-2.0-flash", "gemini-2.0-flash-thinking-exp-01-21", @@ -1624,12 +1619,7 @@ "command-r", "command-r-plus", "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", "gemini-2.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", "mistral-tiny", "mistral-small", "mistral-medium", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8251f7634..661133f53 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.3.13", + "version": "1.3.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.3.13", + "version": "1.3.15", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index becdc4832..2f99bbf6a 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.3.13", + "version": "1.3.16", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 5290cb4f3..43c4ed8fd 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -192,13 +192,13 @@ export class JumpManager { // identical to the completion content, // then we don't have to jump. if (completionContent !== undefined) { - console.log("completionContent is not null"); + console.debug("completionContent is not null"); const editor = vscode.window.activeTextEditor; if (editor) { try { const completionLines = completionContent.split("\n"); - console.log("completionLines:", completionLines); + console.debug("completionLines:", completionLines); // Get document content at jump location spanning multiple lines. const document = editor.document; @@ -212,7 +212,7 @@ export class JumpManager { if (endLine - startLine + 1 < completionLines.length) { // Not enough lines in document, so content can't be identical. // Proceed to jump! - console.log( + console.debug( "Not enough lines in document to match completion content", ); } else { @@ -224,12 +224,12 @@ export class JumpManager { const lineText = document.lineAt(documentLine).text; if (lineText !== completionLines[i]) { contentMatches = false; - console.log(`Line ${i + 1} doesn't match`); + console.debug(`Line ${i + 1} doesn't match`); } } if (contentMatches) { - console.log( + console.debug( "Skipping jump as content is identical at jump location", ); return false; // Exit early, don't suggest jump. @@ -242,20 +242,20 @@ export class JumpManager { } } - console.log("this._jumpInProgress"); + console.debug("this._jumpInProgress"); this._jumpInProgress = true; this._oldCursorPosition = currentPosition; const editor = vscode.window.activeTextEditor; if (!editor) { - console.log("No active editor, cannot suggest jump"); + console.debug("No active editor, cannot suggest jump"); this._jumpInProgress = false; return false; } const visibleRanges = editor.visibleRanges; if (visibleRanges.length === 0) { - console.log("No visible ranges in editor, cannot suggest jump"); + console.debug("No visible ranges in editor, cannot suggest jump"); this._jumpInProgress = false; return false; } @@ -375,7 +375,7 @@ export class JumpManager { "continue.rejectJump", async () => { if (this._jumpDecorationVisible) { - console.log( + console.debug( "deleteChain from JumpManager.ts: rejectJump and decoration visible", ); NextEditProvider.getInstance().deleteChain(); @@ -447,7 +447,7 @@ export class JumpManager { "jumpManager", async (e, state) => { if (state.jumpInProgress || state.jumpJustAccepted) { - console.log( + console.debug( "JumpManager: jump in progress or just accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index a19a34b3f..07b40795a 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -165,7 +165,7 @@ export class NextEditWindowManager { private constructor() { this.theme = getThemeString(); - console.log( + console.debug( "Next Edit Theme initialized:", this.theme ? `Theme exists: ${JSON.stringify(this.theme)}` @@ -269,7 +269,7 @@ export class NextEditWindowManager { // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { - console.log( + console.debug( "deleteChain from NextEditWindowManager.ts: hide next edit command", ); NextEditProvider.getInstance().deleteChain(); @@ -616,7 +616,7 @@ export class NextEditWindowManager { ) { this.theme = getThemeString(); await this.codeRenderer.setTheme(this.theme); - console.log( + console.debug( "Theme updated:", this.theme ? "Theme exists" : "Theme is undefined", ); @@ -630,7 +630,7 @@ export class NextEditWindowManager { vscode.window.onDidChangeActiveColorTheme(async () => { this.theme = getThemeString(); await this.codeRenderer.setTheme(this.theme); - console.log( + console.debug( "Active theme changed:", this.theme ? "Theme exists" : "Theme is undefined", ); @@ -792,7 +792,7 @@ export class NextEditWindowManager { // Check if line numbers are valid. if (range.start.line < 0 || range.start.line >= doc.lineCount) { - console.log( + console.debug( "Invalid start line:", range.start.line, "doc lines:", @@ -802,7 +802,7 @@ export class NextEditWindowManager { } if (range.end.line < 0 || range.end.line >= doc.lineCount) { - console.log( + console.debug( "Invalid end line:", range.end.line, "doc lines:", @@ -819,7 +819,7 @@ export class NextEditWindowManager { range.start.character < 0 || range.start.character > startLine.text.length ) { - console.log( + console.debug( "Invalid start character:", range.start.character, "line length:", @@ -829,7 +829,7 @@ export class NextEditWindowManager { } if (range.end.character < 0 || range.end.character > endLine.text.length) { - console.log( + console.debug( "Invalid end character:", range.end.character, "line length:", @@ -884,7 +884,7 @@ export class NextEditWindowManager { // Check if document changed during async operation. if (editor.document.version !== docVersion) { - console.log("Document changed during decoration creation, aborting"); + console.debug("Document changed during decoration creation, aborting"); decoration.dispose(); return; } @@ -991,7 +991,7 @@ export class NextEditWindowManager { "nextEditWindowManager", async (e, state) => { if (state.nextEditWindowAccepted) { - console.log( + console.debug( "NextEditWindowManager: Edit was just accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index a80cc4439..99e6d05a3 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -330,7 +330,7 @@ export class SelectionChangeManager { return false; } - console.log( + console.debug( "defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection", ); await NextEditProvider.getInstance().deleteChain(); diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index fbb4ac8ae..271e3342d 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -135,7 +135,7 @@ export class GhostTextAcceptanceTracker { ); if (wasGhostTextAccepted) { - console.log( + console.debug( "GhostTextAcceptanceTracker: ghost text was accepted, preserving chain", ); return true; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 30b48220f..fa640fcfe 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -333,7 +333,7 @@ export class ContinueCompletionProvider let chainExists = this.nextEditProvider.chainExists(); const processedCount = this.prefetchQueue.processedCount; const unprocessedCount = this.prefetchQueue.unprocessedCount; - console.log("isJumping:", isJumping, "/ chainExists:", chainExists); + console.debug("isJumping:", isJumping, "/ chainExists:", chainExists); this.prefetchQueue.peekThreeProcessed(); let resetChainInFullFileDiff = false; @@ -351,7 +351,7 @@ export class ContinueCompletionProvider if (isJumping && chainExists) { // Case 2: Jumping (chain exists, jump was taken) - console.log("trigger reason: jumping"); + console.debug("trigger reason: jumping"); // Reset jump state. this.jumpManager.setJumpInProgress(false); @@ -380,7 +380,7 @@ export class ContinueCompletionProvider } } else if (chainExists) { // Case 3: Accepting next edit outcome (chain exists, jump is not taken). - console.log("trigger reason: accepting"); + console.debug("trigger reason: accepting"); // Try suggesting jump for each location. let isJumpSuggested = false; @@ -428,7 +428,7 @@ export class ContinueCompletionProvider } if (!isJumpSuggested) { - console.log( + console.debug( "No suitable jump location found after trying all positions", ); this.nextEditProvider.deleteChain(); @@ -642,7 +642,7 @@ export class ContinueCompletionProvider if (isFim) { if (!fimText) { - console.log("deleteChain from completionProvider.ts: !fimText"); + console.debug("deleteChain from completionProvider.ts: !fimText"); this.nextEditProvider.deleteChain(); return undefined; } @@ -679,7 +679,7 @@ export class ContinueCompletionProvider // Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse. // In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place. // In case of initial response, we suggested a jump. - console.log( + console.debug( "deleteChain from completionProvider.ts: diffLines.length === 0", ); NextEditProvider.getInstance().deleteChain(); @@ -718,7 +718,7 @@ export class ContinueCompletionProvider if (selectedCompletionInfo) { const { text, range } = selectedCompletionInfo; if (!outcome.completion.startsWith(text)) { - console.log( + console.debug( `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`, range, ); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 23ced0cc5..cb5dd72d5 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,4 +1,5 @@ import fs from "fs"; +import path from "path"; import { IContextProvider } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; @@ -10,6 +11,7 @@ import { getConfigJsonPath, getConfigTsPath, getConfigYamlPath, + getContinueGlobalPath, } from "core/util/paths"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -232,7 +234,9 @@ export class VsCodeExtension { timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY && !NextEditWindowManager.getInstance().hasAccepted() ) { - console.log("VsCodeExtension: typing in progress, preserving chain"); + console.debug( + "VsCodeExtension: typing in progress, preserving chain", + ); return true; } @@ -463,6 +467,18 @@ export class VsCodeExtension { void this.configHandler.reloadConfig("config.ts updated - fs file watch"); }); + // watch global rules directory for changes + const globalRulesDir = path.join(getContinueGlobalPath(), "rules"); + if (fs.existsSync(globalRulesDir)) { + fs.watch(globalRulesDir, { recursive: true }, (eventType, filename) => { + if (filename && filename.endsWith(".md")) { + void this.configHandler.reloadConfig( + "Global rules directory updated - fs file watch", + ); + } + }); + } + vscode.workspace.onDidChangeTextDocument(async (event) => { if (event.contentChanges.length > 0) { selectionManager.documentChanged(); @@ -503,8 +519,22 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidChangeWorkspaceFolders(async (event) => { + const dirs = vscode.workspace.workspaceFolders?.map( + (folder) => folder.uri, + ); + + this.ideUtils.setWokspaceDirectories(dirs); + + this.core.invoke("index/forceReIndex", { + dirs: [ + ...event.added.map((folder) => folder.uri.toString()), + ...event.removed.map((folder) => folder.uri.toString()), + ], + }); + }); + vscode.workspace.onDidOpenTextDocument(async (event) => { - console.log("onDidOpenTextDocument"); const ast = await getAst(event.fileName, event.getText()); if (ast) { DocumentHistoryTracker.getInstance().addDocument( diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 202713cbd..12cc98c35 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -62,6 +62,14 @@ export class SecretStorage { const key = await this.getOrCreateEncryptionKey(); const data = fs.readFileSync(filePath); + // Validate minimum data size to detect corruption early + const minSize = this.saltLength + this.ivLength + this.tagLength; + if (data.length < minSize) { + throw new Error( + `Corrupted cache file: insufficient data (${data.length} bytes, expected at least ${minSize})`, + ); + } + const salt = data.subarray(0, this.saltLength); const iv = data.subarray(this.saltLength, this.saltLength + this.ivLength); const tag = data.subarray( @@ -105,4 +113,12 @@ export class SecretStorage { } return undefined; } + + async delete(key: string): Promise { + const filePath = this.keyToFilepath(key); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + console.log(`Successfully deleted cache file: ${filePath}`); + } + } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index f0af9770d..1c0e60bba 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -161,22 +161,34 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { scopes?: string[], ): Promise { // await this.hasAttemptedRefresh; - const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); - if (!data) { - return []; - } - try { + const data = await this.secretStorage.get(SESSIONS_SECRET_KEY); + if (!data) { + return []; + } + const value = JSON.parse(data) as ContinueAuthenticationSession[]; return value; } catch (e: any) { - // Capture session file parsing errors to Sentry + // Capture session decrypt and parsing errors to Sentry Logger.error(e, { - context: "workOS_sessions_json_parse", - dataLength: data.length, + context: "workOS_sessions_retrieval", + errorMessage: e.message, }); - console.warn(`Error parsing sessions.json: ${e}`); + console.warn(`Error retrieving or parsing sessions: ${e.message}`); + + // Delete the corrupted cache file to allow fresh start on next attempt + // This handles cases where decryption succeeded but JSON parsing failed + try { + await this.secretStorage.delete(SESSIONS_SECRET_KEY); + } catch (deleteError: any) { + console.error( + `Failed to delete corrupted sessions cache:`, + deleteError.message, + ); + } + return []; } } diff --git a/extensions/vscode/src/util/editLoggingUtils.ts b/extensions/vscode/src/util/editLoggingUtils.ts index 767131868..467ab4f0f 100644 --- a/extensions/vscode/src/util/editLoggingUtils.ts +++ b/extensions/vscode/src/util/editLoggingUtils.ts @@ -3,9 +3,6 @@ import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "core/autocomplete/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { RecentlyEditedRange } from "core/nextEdit/types"; -import { getContinueGlobalPath, isFileWithinFolder } from "core/util/paths"; -import fs from "fs"; -import { resolve } from "path"; import * as vscode from "vscode"; import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; @@ -21,23 +18,6 @@ export const getBeforeCursorPos = (range: Range, activePos: Position) => { } }; -const isEditLoggingAllowed = async (editedFileURI: string) => { - const globalContinuePath = getContinueGlobalPath(); - const editLogDirsPath = resolve(globalContinuePath, ".editlogdirs"); - - try { - const fileContent = await fs.promises.readFile(editLogDirsPath, "utf-8"); - const stringItems = fileContent - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0); - - return stringItems.some((dir) => isFileWithinFolder(editedFileURI, dir)); - } catch (error) { - return false; - } -}; - const getWorkspaceDirUri = async (event: vscode.TextDocumentChangeEvent) => { const workspaceFolder = vscode.workspace.getWorkspaceFolder( event.document.uri, @@ -68,7 +48,6 @@ export const handleTextDocumentChange = async ( // Ensure that logging will only happen in the open-source continue repo const workspaceDirUri = await getWorkspaceDirUri(event); if (!workspaceDirUri) return; - if (!(await isEditLoggingAllowed(event.document.uri.toString()))) return; const activeCursorPos = editor.selection.active; const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({ diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index d8593f7d0..6dd9a3aa2 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -74,6 +74,10 @@ export class VsCodeIdeUtils { return this._workspaceDirectories; } + setWokspaceDirectories(dirs: vscode.Uri[] | undefined): void { + this._workspaceDirectories = dirs; + } + getUniqueId() { return getUniqueId(); } diff --git a/gui/src/components/CliInstallBanner.test.tsx b/gui/src/components/CliInstallBanner.test.tsx new file mode 100644 index 000000000..134b5aae2 --- /dev/null +++ b/gui/src/components/CliInstallBanner.test.tsx @@ -0,0 +1,491 @@ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { MockIdeMessenger } from "../context/MockIdeMessenger"; +import * as util from "../util"; +import * as localStorage from "../util/localStorage"; +import { CliInstallBanner } from "./CliInstallBanner"; + +vi.mock("../util", async () => { + const actual = await vi.importActual("../util"); + return { + ...actual, + getPlatform: vi.fn(), + }; +}); + +vi.mock("../util/localStorage", async () => { + const actual = await vi.importActual("../util/localStorage"); + return { + ...actual, + getLocalStorage: vi.fn(), + setLocalStorage: vi.fn(), + }; +}); + +describe("CliInstallBanner", () => { + let mockIdeMessenger: MockIdeMessenger; + + beforeEach(() => { + vi.clearAllMocks(); + mockIdeMessenger = new MockIdeMessenger(); + vi.mocked(util.getPlatform).mockReturnValue("mac"); + vi.mocked(localStorage.getLocalStorage).mockReturnValue(undefined); + }); + + const renderComponent = async (subprocessResponse: [string, string]) => { + // Mock the subprocess call on the IDE + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue( + subprocessResponse, + ); + + return act(async () => + render( + + + , + ), + ); + }; + + describe("CLI detection", () => { + it("does not render when CLI is installed (subprocess returns path)", async () => { + await renderComponent(["/usr/local/bin/cn", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty)", async () => { + await renderComponent(["", "command not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty stdout)", async () => { + await renderComponent(["", ""]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("uses 'which cn' command on mac platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("mac"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'which cn' command on linux platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("linux"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'where cn' command on windows platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("windows"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("where cn"); + }); + }); + + it("handles subprocess errors gracefully", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockRejectedValue( + new Error("Command failed"), + ); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Banner content", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("displays the title", () => { + expect(screen.getByText("Try out the Continue CLI")).toBeInTheDocument(); + }); + + it("displays the description with 'cn' code element", () => { + const description = screen.getByText(/Use/); + expect(description).toBeInTheDocument(); + expect(screen.getByText("cn")).toBeInTheDocument(); + }); + + it("displays the installation command", () => { + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + }); + + it("displays the Learn more link", () => { + expect(screen.getByText("Learn more.")).toBeInTheDocument(); + }); + + it("displays the close button", () => { + // Get the styled close button (it doesn't have a text label) + const buttons = screen.getAllByRole("button"); + // There should be multiple buttons (close, copy, run) + expect(buttons.length).toBeGreaterThan(0); + }); + + it("displays the CommandLine icon", () => { + // The icon should be present in the component + const banner = screen + .getByText("Try out the Continue CLI") + .closest("div"); + expect(banner).toBeInTheDocument(); + }); + }); + + describe("User interactions", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("dismisses banner when close button is clicked", async () => { + const buttons = screen.getAllByRole("button"); + // First button should be the close button (CloseButton component) + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("opens documentation URL when Learn more link is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + const learnMoreLink = screen.getByText("Learn more."); + + fireEvent.click(learnMoreLink); + + expect(postSpy).toHaveBeenCalledWith( + "openUrl", + "https://docs.continue.dev/guides/cli", + ); + }); + + it("displays the installation command with interactive controls", async () => { + // The installation command should be visible + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + // The "Run" text should be visible for the run button + expect(screen.getByText(/Run/i)).toBeInTheDocument(); + }); + + it("runs installation command in terminal when run button is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + + // Find the "Run" text or CommandLineIcon + const runButton = screen.getByText(/Run/i).closest("div"); + if (runButton) { + fireEvent.click(runButton); + + expect(postSpy).toHaveBeenCalledWith("runCommand", { + command: `npm i -g @continuedev/cli && cn "Explore this repo and provide a concise summary of it's contents"`, + }); + } + }); + }); + + describe("Banner visibility states", () => { + it("does not render while CLI check is loading", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockImplementation( + () => + new Promise((resolve) => setTimeout(() => resolve(["", ""]), 100)), + ); + + await act(async () => + render( + + + , + ), + ); + + // Should not be visible immediately + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + it("remains hidden after dismissal even on re-render", async () => { + const { rerender } = await renderComponent(["", "not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + // Dismiss the banner + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + // Re-render the component + rerender( + + + , + ); + + // Should still be hidden + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + describe("Edge cases", () => { + it("handles whitespace in subprocess output", async () => { + await renderComponent([" \n ", ""]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("detects CLI when path has trailing newline", async () => { + await renderComponent(["/usr/local/bin/cn\n", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders banner when stderr contains 'not found'", async () => { + await renderComponent(["", "cn: command not found"]); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Session threshold logic", () => { + const renderWithSessionCount = async ( + sessionCount?: number, + sessionThreshold?: number, + ) => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("shows banner when no threshold is set", async () => { + await renderWithSessionCount(0, undefined); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("does not show banner when session count is below threshold", async () => { + await renderWithSessionCount(2, 3); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("shows banner when session count meets threshold", async () => { + await renderWithSessionCount(3, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("shows banner when session count exceeds threshold", async () => { + await renderWithSessionCount(5, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Permanent dismissal with localStorage", () => { + const renderWithPermanentDismissal = async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("does not show banner when previously dismissed permanently", async () => { + vi.mocked(localStorage.getLocalStorage).mockReturnValue(true); + + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("sets localStorage when dismissed with permanentDismissal=true", async () => { + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).toHaveBeenCalledWith( + "hasDismissedCliInstallBanner", + true, + ); + }); + + it("does not set localStorage when dismissed with permanentDismissal=false", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx new file mode 100644 index 000000000..36662309a --- /dev/null +++ b/gui/src/components/CliInstallBanner.tsx @@ -0,0 +1,167 @@ +import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { useContext, useEffect, useRef, useState } from "react"; +import { CloseButton } from "."; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import useCopy from "../hooks/useCopy"; +import { getPlatform } from "../util"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; +import { Card } from "./ui"; + +interface CliInstallBannerProps { + /** Number of sessions user has had - banner shows only if >= sessionThreshold */ + sessionCount?: number; + /** Minimum sessions before showing banner (default: always show) */ + sessionThreshold?: number; + /** If true, dismissal is permanent via localStorage (default: session only) */ + permanentDismissal?: boolean; +} + +export function CliInstallBanner({ + sessionCount, + sessionThreshold, + permanentDismissal = false, +}: CliInstallBannerProps = {}) { + const ideMessenger = useContext(IdeMessengerContext); + const [cliInstalled, setCliInstalled] = useState(null); + const [dismissed, setDismissed] = useState(false); + const commandTextRef = useRef(null); + const { copyText } = useCopy("npm i -g @continuedev/cli"); + const [showCopiedMessage, setShowCopiedMessage] = useState(false); + + const handleCommandClick = () => { + // Select the text + if (commandTextRef.current) { + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(commandTextRef.current); + selection?.removeAllRanges(); + selection?.addRange(range); + } + // Copy to clipboard + copyText(); + + // Show "Copied!" message for 3 seconds + setShowCopiedMessage(true); + setTimeout(() => setShowCopiedMessage(false), 3000); + }; + + useEffect(() => { + // Check if user has permanently dismissed the banner + if (permanentDismissal) { + const hasDismissed = getLocalStorage("hasDismissedCliInstallBanner"); + if (hasDismissed) { + setDismissed(true); + return; + } + } + + const checkCliInstallation = async () => { + try { + const platform = getPlatform(); + // Use 'which' on mac/linux, 'where' on windows + const command = platform === "windows" ? "where cn" : "which cn"; + + const [stdout, stderr] = await ideMessenger.ide.subprocess(command); + + // If stdout has content (path to cn), it's installed + // If empty or stderr has "not found", it's not installed + const isInstalled = + stdout.trim().length > 0 && !stderr.includes("not found"); + setCliInstalled(isInstalled); + } catch (error) { + // If subprocess throws an error, assume CLI is not installed + setCliInstalled(false); + } + }; + + void checkCliInstallation(); + }, [ideMessenger, permanentDismissal]); + + const handleDismiss = () => { + setDismissed(true); + if (permanentDismissal) { + setLocalStorage("hasDismissedCliInstallBanner", true); + } + }; + + // Don't show if: + // - Still loading CLI status + // - CLI is already installed + // - User has dismissed it + // - Session threshold not met (if threshold is set) + if ( + cliInstalled === null || + cliInstalled === true || + dismissed || + (sessionThreshold !== undefined && + (sessionCount === undefined || sessionCount < sessionThreshold)) + ) { + return null; + } + + return ( +
+ + + + +
+
+
+ + Try out the Continue CLI +
+
+ Use{" "} + + cn + {" "} + in your terminal interactively and then deploy Continuous AI + workflows.{" "} + + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/guides/cli", + ) + } + className="cursor-pointer underline hover:brightness-125" + > + Learn more. + +
+
+
+
+
+ + npm i -g @continuedev/cli + + {showCopiedMessage && ( + + Copied! + + )} +
+
+ + +
+
+
+
+
+
+ ); +} diff --git a/gui/src/components/DropdownButton.tsx b/gui/src/components/DropdownButton.tsx new file mode 100644 index 000000000..5d2a0eaae --- /dev/null +++ b/gui/src/components/DropdownButton.tsx @@ -0,0 +1,69 @@ +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { ToolTip } from "./gui/Tooltip"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "./ui"; + +interface DropdownOption { + value: string; + label: string; +} + +interface DropdownButtonProps { + title: string; + options: DropdownOption[]; + onOptionClick: (value: string) => void; + addButtonTooltip?: string; + className?: string; + variant?: "default" | "sm"; +} + +export function DropdownButton({ + title, + options, + onOptionClick, + addButtonTooltip, + className = "", + variant = "default", +}: DropdownButtonProps) { + const isSmall = variant === "sm"; + const titleSize = isSmall ? "text-sm font-semibold" : "text-xl font-semibold"; + const marginBottom = isSmall ? "mb-2" : "mb-4"; + + return ( +
+

{title}

+ {}}> +
+ + + + + + + + {options.map((option) => ( + + `relative flex cursor-default select-none items-center gap-3 py-2 pl-4 pr-4 ${ + active + ? "bg-list-active text-list-active-foreground" + : "text-foreground" + }` + } + onClick={() => onOptionClick(option.value)} + > + {option.label} + + ))} + +
+
+
+ ); +} diff --git a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx index db26e4b3f..a8ecc29b6 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx +++ b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx @@ -23,9 +23,34 @@ import { visit } from "unist-util-visit"; export function remarkTables() { return (tree: any) => { visit(tree, "paragraph", (paragraphNode, index, parentOfParagraphNode) => { - let buffer = ""; - visit(paragraphNode, "text", (textNode) => { - buffer += textNode.value; + // Collect all child nodes into a buffer, preserving their types + const buffer: any[] = []; + paragraphNode.children.forEach((child: any) => { + buffer.push(child); + }); + + // Flatten buffer to a string for regex matching, but keep track of positions + let bufferString = ""; + const positions: { start: number; end: number; node: any }[] = []; + + // Recursive renderer for inline nodes -> markdown-ish text + function renderInline(node: any): string { + if (!node) return ""; + if (Array.isArray(node.children)) { + return node.children.map(renderInline).join(""); + } + if (typeof node.value === "string") { + return node.value; + } + return ""; + } + + buffer.forEach((item) => { + const start = bufferString.length; + // renderInline returns a markdown-like string for inline nodes so decorations are preserved + const rendered = renderInline(item); + bufferString += rendered; + positions.push({ start, end: bufferString.length, node: item }); }); const tableRegex = @@ -33,7 +58,7 @@ export function remarkTables() { //// header // newline // |:---|----:| // new line // table rows // prevent modifying if no markdown tables are present - if (!buffer.match(tableRegex)) { + if (!bufferString.match(tableRegex)) { return; } @@ -42,7 +67,7 @@ export function remarkTables() { const newNodes = []; let failed = false; - while ((match = tableRegex.exec(buffer)) !== null) { + while ((match = tableRegex.exec(bufferString)) !== null) { const fullTableString = match[0]; const headerGroup = match[1]; const separatorGroup = match[2]; @@ -104,16 +129,46 @@ export function remarkTables() { ], }; - // Add any text before the table as a text node - if (match.index > lastIndex) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex, match.index), - }); - } + // Add any nodes before/after the table in one go + const tableStart = match.index; + const tableEnd = match.index + fullTableString.length; - // Add table node + // Process the text within the table and the surrounding text together + const beforeNodes: any[] = []; + const afterNodes: any[] = []; + + positions.forEach((pos) => { + if (pos.end <= tableStart) { + beforeNodes.push(pos.node); + } else if (pos.start >= tableEnd) { + afterNodes.push(pos.node); + } else if (pos.node.type === "text") { + // Node is text and overlaps with table, may need splitting + const beforeText = pos.node.value.slice( + 0, + Math.max(0, tableStart - pos.start), + ); + const afterText = pos.node.value.slice( + Math.max(0, tableEnd - pos.start), + ); + if (beforeText) + beforeNodes.push({ type: "text", value: beforeText }); + if (afterText) + afterNodes.push({ type: "text", value: afterText }); + } else { + // Node overlaps with table but isn't text (e.g., inlineCode, emphasis, etc.) + if (pos.start < tableStart) beforeNodes.push(pos.node); + if (pos.end > tableEnd) afterNodes.push(pos.node); + } + }); + + // Add to new nodes + newNodes.push(...beforeNodes); newNodes.push(tableNode); + newNodes.push(...afterNodes); + + // Mark positions as consumed + positions.length = 0; } catch (e) { console.error("Failed to parse markdown table after regex match", e); newNodes.push({ @@ -129,14 +184,6 @@ export function remarkTables() { return; } - // Add any remaining text after the last table - if (lastIndex < buffer.length) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex), - }); - } - // Replace the original paragraph node with the new nodes if (newNodes.length > 0) { parentOfParagraphNode.children.splice(index, 1, ...newNodes); diff --git a/gui/src/components/config/FatalErrorNotice.tsx b/gui/src/components/config/FatalErrorNotice.tsx index 2bb9a43b4..4d20aba1c 100644 --- a/gui/src/components/config/FatalErrorNotice.tsx +++ b/gui/src/components/config/FatalErrorNotice.tsx @@ -1,5 +1,5 @@ import { useContext, useMemo } from "react"; -import { useNavigate } from "react-router-dom"; +import { useLocation, useNavigate } from "react-router-dom"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppSelector } from "../../redux/hooks"; @@ -10,7 +10,7 @@ export const FatalErrorIndicator = () => { const { refreshProfiles } = useAuth(); const configError = useAppSelector((store) => store.config.configError); const ideMessenger = useContext(IdeMessengerContext); - + const location = useLocation(); const navigate = useNavigate(); const hasFatalErrors = useMemo(() => { @@ -18,10 +18,11 @@ export const FatalErrorIndicator = () => { }, [configError]); const configLoading = useAppSelector((state) => state.config.loading); - const showConfigPage = () => { navigate(CONFIG_ROUTES.AGENTS); }; + // const onAgentsPage = location. + const currentPath = `${location.pathname}${location.search}`; const { selectedProfile } = useAuth(); @@ -64,9 +65,11 @@ export const FatalErrorIndicator = () => { Reload )} -
- View -
+ {currentPath !== CONFIG_ROUTES.AGENTS && ( +
+ View +
+ )} ); diff --git a/gui/src/components/gui/Switch.tsx b/gui/src/components/gui/Switch.tsx index ddb90af9d..ab70b06b4 100644 --- a/gui/src/components/gui/Switch.tsx +++ b/gui/src/components/gui/Switch.tsx @@ -38,7 +38,14 @@ const ToggleSwitch: React.FC = ({ {isToggled && !!showIfToggled && showIfToggled}
{ + e.stopPropagation(); + onToggle(); + } + } style={{ height: size, width: size * 2, diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx deleted file mode 100644 index ca8df051c..000000000 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { ConfigYaml } from "@continuedev/config-yaml"; -import { PencilIcon } from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; - -type SectionKey = Exclude< - keyof ConfigYaml, - "name" | "version" | "schema" | "metadata" | "env" | "requestOptions" ->; - -interface EditBlockButtonProps { - blockType: T; - block?: NonNullable[T]>[number]; - className?: string; - sourceFile?: string; -} - -function isUsesBlock(block: any): block is { uses: string } { - return typeof block !== "string" && "uses" in block; -} - -export default function EditBlockButton({ - block, - blockType, - className = "", - sourceFile, -}: EditBlockButtonProps) { - const ideMessenger = useContext(IdeMessengerContext); - const { selectedProfile } = useAuth(); - - const openUrl = (path: string) => - ideMessenger.request("controlPlane/openUrl", { - path, - orgSlug: undefined, - }); - - const handleEdit = () => { - if (selectedProfile?.profileType === "local") { - ideMessenger.post("config/openProfile", { - profileId: undefined, - element: { sourceFile }, - }); - } else if (block && isUsesBlock(block)) { - void openUrl(`${block.uses}/new-version`); - } else if (selectedProfile?.fullSlug) { - const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`; - void openUrl(`${slug}/new-version`); - } - }; - - return ( - - ); -} diff --git a/gui/src/components/mainInput/Lump/useEditBlock.ts b/gui/src/components/mainInput/Lump/useEditBlock.ts new file mode 100644 index 000000000..9bbbd15a5 --- /dev/null +++ b/gui/src/components/mainInput/Lump/useEditBlock.ts @@ -0,0 +1,66 @@ +import { ModelDescription } from "core"; +import { useContext } from "react"; +import { useAuth } from "../../../context/Auth"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +export function useEditBlock() { + const ideMessenger = useContext(IdeMessengerContext); + const { selectedProfile } = useAuth(); + + return (slug?: string, sourceFile?: string) => { + if (slug) { + ideMessenger.post("controlPlane/openUrl", { + path: `${slug}/new-version`, + orgSlug: undefined, + }); + } else if (sourceFile) { + ideMessenger.post("openFile", { + path: sourceFile, + }); + } else if ( + selectedProfile?.profileType === "local" && + selectedProfile?.uri + ) { + ideMessenger.post("openFile", { + path: selectedProfile.uri, + }); + } else if ( + selectedProfile?.fullSlug?.ownerSlug && + selectedProfile?.fullSlug.packageSlug + ) { + ideMessenger.post("controlPlane/openUrl", { + path: `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}/new-version`, + orgSlug: undefined, + }); + } else { + // Local etc + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + } + }; +} + +export function useEditModel() { + const editBlock = useEditBlock(); + return (model?: ModelDescription | null) => { + editBlock(undefined, model?.sourceFile); + }; +} + +export function useEditDoc() { + const editBlock = useEditBlock(); + return ( + docConfig?: { uses?: string } | { name: string; sourceFile?: string }, + ) => { + if (!docConfig) { + editBlock(undefined, undefined); + return; + } + if ("name" in docConfig) { + editBlock(undefined, docConfig.sourceFile); + } else { + editBlock(docConfig.uses, undefined); + } + }; +} diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 0fe79297c..b2ba02793 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -198,4 +198,29 @@ export function useMainEditorWebviewListeners({ }, [editor, activeContextProviders, isInEdit, useCurrentFileAsContext], ); + + useWebviewListener( + "addToChat", + async (data) => { + if (!editor) return; + let chain = editor.chain(); + + for (let mention of data.data) { + chain + .insertContent({ + type: "mention", + attrs: { + id: mention.fullPath, + query: mention.fullPath, + itemType: mention.type, + label: mention.name, + }, + }) + .insertContent(" "); + } + + chain.run(); + }, + [editor], + ); } diff --git a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts index afc6c2e2c..64960312b 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts @@ -13,8 +13,8 @@ export async function getPromptV2ContextRequests( } const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs(); const visitedFiles = new Set(); - if (command.promptFile) { - visitedFiles.add(command.promptFile); + if (command.sourceFile) { + visitedFiles.add(command.sourceFile); } const contextRequests: GetContextRequest[] = []; diff --git a/gui/src/components/ui/Card.tsx b/gui/src/components/ui/Card.tsx index 8d315c0d6..2b1a53f68 100644 --- a/gui/src/components/ui/Card.tsx +++ b/gui/src/components/ui/Card.tsx @@ -1,3 +1,5 @@ +import { cn } from "../../util/cn"; + interface CardProps extends React.ComponentProps<"div"> { children: React.ReactNode; } @@ -5,8 +7,8 @@ interface CardProps extends React.ComponentProps<"div"> { export function Card({ children, className = "", ...props }: CardProps) { return (
{children}
diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 12eebae1c..ee262d782 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -50,25 +50,27 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); - const login: AuthContextType["login"] = (useOnboarding: boolean) => { - return new Promise(async (resolve) => { - await ideMessenger - .request("getControlPlaneSessionInfo", { - silent: false, - useOnboarding, - }) - .then((result) => { - if (result.status === "error") { - resolve(false); - return; - } + const login: AuthContextType["login"] = async (useOnboarding: boolean) => { + try { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { + silent: false, + useOnboarding, + }); - const session = result.content; - setSession(session); + if (result.status === "error") { + console.error("Login failed:", result.error); + return false; + } - resolve(true); - }); - }); + const session = result.content; + setSession(session); + + return true; + } catch (error: any) { + console.error("Login request failed:", error); + // Let the error propagate so the caller can handle it + throw error; + } }; const logout = () => { diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index 1669612e1..e2e8a8ec9 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -44,22 +44,8 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { "file:///Users/user/workspace1", "file:///Users/user/workspace2", ], - "history/list": [ - { - title: "Session 1", - sessionId: "session-1", - dateCreated: new Date().toString(), - workspaceDirectory: "/tmp", - }, - { - title: "Remote Agent", - sessionId: "remote-agent-123", - dateCreated: new Date().toString(), - workspaceDirectory: "", - isRemote: true, - remoteId: "agent-123", - }, - ], + "history/list": [], + "docs/getIndexedPages": [], "history/save": undefined, getControlPlaneSessionInfo: { AUTH_TYPE: AuthType.WorkOsStaging, @@ -92,6 +78,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, ], }, + "context/getSymbolsForFiles": {}, + "tools/preprocessArgs": { + preprocessedArgs: undefined, + }, "llm/compileChat": { compiledChatMessages: [], didPrune: false, @@ -114,6 +104,15 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { ], }; +const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = { + "tools/evaluatePolicy": async (data) => { + return { + policy: data.basePolicy, + displayValue: undefined, + }; + }, +}; + const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [ { role: "assistant", @@ -165,7 +164,9 @@ export class MockIdeMessenger implements IIdeMessenger { } responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES }; - responseHandlers: MockResponseHandlers = {}; + responseHandlers: MockResponseHandlers = { + ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS, + }; chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE; chatStreamDelay: number = 0; setChatResponseText(text: string): void { @@ -253,7 +254,7 @@ export class MockIdeMessenger implements IIdeMessenger { resetMocks(): void { this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES }; - this.responseHandlers = {}; + this.responseHandlers = { ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS }; this.chatResponse = DEFAULT_CHAT_RESPONSE; this.chatStreamDelay = 0; } diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 510733da9..e0a2dcf37 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -22,7 +22,10 @@ import { setTTSActive } from "../redux/slices/uiSlice"; import { modelSupportsReasoning } from "core/llm/autodetect"; import { cancelStream } from "../redux/thunks/cancelStream"; import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate"; -import { refreshSessionMetadata } from "../redux/thunks/session"; +import { + loadLastSession, + refreshSessionMetadata, +} from "../redux/thunks/session"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { setDocumentStylesFromLocalStorage, @@ -104,6 +107,7 @@ function ParallelListeners() { await handleConfigUpdate(true, result.content); } dispatch(setConfigLoading(false)); + await dispatch(loadLastSession()); } void initialLoadConfig(); const interval = setInterval(() => { diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index a45b84004..aaa8092f7 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -514,7 +514,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq", "askSage"], + providerOptions: ["groq"], isOpenSource: false, }, llama318bChat: { @@ -841,7 +841,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 32000, }, icon: "mistral.png", - providerOptions: ["mistral", "askSage"], + providerOptions: ["mistral"], isOpenSource: false, }, mistralNemo: { @@ -856,46 +856,6 @@ export const models: { [key: string]: ModelPackage } = { icon: "mistral.png", isOpenSource: true, }, - geminiPro: { - title: "Gemini Pro", - description: "A highly capable model created by Google DeepMind", - params: { - title: "Gemini Pro", - model: "gemini-pro", - contextLength: 32_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini"], - isOpenSource: false, - }, - gemini15Pro: { - title: "Gemini 1.5 Pro", - description: "A newer Gemini model with 1M token context length", - params: { - title: "Gemini 1.5 Pro", - model: "gemini-1.5-pro-latest", - contextLength: 2_000_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini", "askSage"], - isOpenSource: false, - }, - gemini15Flash: { - title: "Gemini 1.5 Flash", - description: - "Fast and versatile multimodal model for scaling across diverse tasks", - params: { - title: "Gemini 1.5 Flash", - model: "gemini-1.5-flash-latest", - contextLength: 1_000_000, - apiKey: "", - }, - icon: "gemini.png", - providerOptions: ["gemini"], - isOpenSource: false, - }, gemini20Flash: { title: "Gemini 2.0 Flash", description: @@ -1154,7 +1114,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 128_000, title: "GPT-4o", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1165,9 +1125,10 @@ export const models: { [key: string]: ModelPackage } = { params: { model: "gpt-4o-mini", contextLength: 128_000, + title: "GPT-4o mini", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1180,7 +1141,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8096, title: "GPT-3.5-Turbo", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1194,7 +1155,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4 Sonnet", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1207,7 +1168,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4.1 Opus", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1358,31 +1319,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["watsonx"], isOpenSource: false, }, - VertexGemini15Pro: { - title: "Gemini 1.5 Pro", - description: "A newer Gemini model with 1M token context length", - params: { - title: "Gemini 1.5 Pro", - model: "gemini-1.5-pro-002", - contextLength: 2_097_152, - }, - icon: "gemini.png", - providerOptions: ["vertexai"], - isOpenSource: false, - }, - VertexGemini15Flash: { - title: "Gemini 1.5 Flash", - description: - "Fast and versatile multimodal model for scaling across diverse tasks", - params: { - title: "Gemini 1.5 Flash", - model: "gemini-1.5-flash-002", - contextLength: 1_048_576, - }, - icon: "gemini.png", - providerOptions: ["vertexai"], - isOpenSource: false, - }, vertexMistralLarge: { title: "Mistral Large", description: @@ -1396,135 +1332,382 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["vertexai"], isOpenSource: false, }, + // OpenAI Models via Ask Sage + asksagegpt4o: { + title: "GPT-4o*", + description: + "An even faster version of GPT-4 with stronger multi-modal capabilities.", + params: { + model: "gpt-4o", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt4omini: { + title: "GPT-4o Mini*", + description: + "A model at less than half the price of gpt-3.5-turbo, but near gpt-4 in capabilities.", + params: { + model: "gpt-4o-mini", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, asksagegpt4gov: { - title: "GPT-4 gov", + title: "GPT-4 gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4 but approved for use by the U.S. Government.", params: { model: "gpt4-gov", contextLength: 128_000, - title: "GPT-4 gov", + maxTokens: 4096, + title: "GPT-4 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ogov: { - title: "GPT-4o gov", + title: "GPT-4o gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4o but approved for use by the U.S. Government.", params: { model: "gpt-4o-gov", contextLength: 128_000, - title: "GPT-4o-gov", + maxTokens: 4096, + title: "GPT-4o-gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt35: { + title: "GPT-3.5*", + description: "Azure OpenAI GPT 3.5 Model.", + params: { + model: "gpt", + contextLength: 4096, + title: "GPT-3.5*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt35gov: { - title: "GPT-3.5-Turbo gov", + title: "GPT-3.5 gov*", description: "U.S. Government. Inexpensive and good ROI.", params: { model: "gpt-gov", - contextLength: 8096, - title: "GPT-3.5-Turbo gov", + contextLength: 16834, + maxTokens: 4096, + title: "GPT-3.5 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ominigov: { - title: "GPT-4o-mini gov", - description: - "U.S. Government. Latest OpenAI GPT 4o-mini model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + title: "GPT-4o-mini gov*", + description: "OpenAI GPT 4o-mini model.", params: { model: "gpt-4o-mini-gov", contextLength: 128_000, - title: "GPT-4o-mini gov", + maxTokens: 16_384, + title: "GPT-4o-mini gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4: { - title: "GPT-4", + title: "GPT-4*", description: "GPT4 is about 5X more expensive than Ask Sage tokens and 50X more expensive than GPT3.5", params: { model: "gpt4", contextLength: 8_192, - title: "GPT-4", - }, - providerOptions: ["openai"], - icon: "openai.png", - isOpenSource: false, - }, - asksagegpt432: { - title: "GPT-4-32k", - description: - "The GPT-4-32k model is a variant of the GPT-4 model developed by OpenAI. It is designed to handle a larger context window, capable of processing up to 32,768 tokens, which makes it suitable for scenarios that require extensive information integration and data analysis", - params: { - model: "gpt4-32k", - contextLength: 32_768, - title: "GPT-4-32k", + title: "GPT-4*", + apiKey: "", }, providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, asksagegpto1: { - title: "GPT-o1", + title: "GPT-o1*", description: "Latest OpenAI GPT-o1 model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)).", params: { model: "gpt-o1", contextLength: 128_000, - title: "GPT-o1", + maxTokens: 32_768, + title: "GPT-o1*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, // stopped here + }, + asksagegpt41: { + title: "GPT-4.1*", + description: "Azure OpenAI GPT 4.1 model.", + params: { + model: "gpt-4.1", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto1mini: { - title: "GPT-o1-mini", - description: - "Latest OpenAI GPT-o1-mini model. More inexpensive than GPT-o1. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + asksagegpt41mini: { + title: "GPT-4.1 mini*", + description: "Azure OpenAI GPT 4.1 mini model.", params: { - model: "gpt-o1-mini", - contextLength: 128_000, - title: "GPT-o1-mini", + model: "gpt-4.1-mini", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 mini*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto3mini: { - title: "GPT-o3-mini", - description: - "o3-mini can outperform o1 in coding and other reasoning tasks, and is 93% cheaper and has lower latency. It supports function calling, Structured Outputs, streaming, and developer messages. o3-mini comes with a larger context window of 200,000 tokens and a max output of 100,000 tokens", + asksagegpt41nano: { + title: "GPT-4.1 nano*", + description: "Azure OpenAI GPT 4.1 nano model.", params: { - model: "gpt-o3-mini", + model: "gpt-4.1-nano", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5: { + title: "GPT-5*", + description: "OpenAI's GPT-5 model", + params: { + model: "gpt-5", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5nano: { + title: "GPT-5-nano*", + description: "OpenAI's GPT-5-nano model", + params: { + model: "gpt-5-nano", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5mini: { + title: "GPT-5-mini*", + description: "OpenAI's GPT-5-mini model", + params: { + model: "gpt-5-mini", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpto3: { + title: "GPT-o3", + description: "Azure OpenAI GPT o3 model.", + params: { + model: "gpt-o3", contextLength: 200_000, - title: "GPT-o3-mini", + maxTokens: 100_000, + title: "GPT-o3", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksageclaude35gov: { - title: "Claude 3.5 Sonnet gov", + asksagegpt04mini: { + title: "GPT-o4-mini", + description: "Azure OpenAI GPT o4-mini model.", + params: { + model: "gpt-o4-mini", + contextLength: 200_000, + maxTokens: 100_000, + title: "GPT-o4-mini", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksageclaude35Sonnet: { + title: "Claude 3.5 Sonnet", description: "Anthropic's most intelligent model, but much less expensive than Claude 3 Opus", params: { - model: "aws-bedrock-claude-35-sonnet-gov", + model: "claude-35-sonnet", contextLength: 200_000, - title: "Claude 3.5 Sonnet gov", + title: "Claude 3.5 Sonnet", + apiKey: "", }, providerOptions: ["askSage"], icon: "anthropic.png", isOpenSource: false, }, + asksageclaude37sonnet: { + title: "Claude 3.7 Sonnet", + description: "Anthropic's 3.7 model.", + params: { + model: "claude-37-sonnet", + contextLength: 200_000, + title: "Claude 3.7 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude37sonnetgov: { + title: "Claude 3.7 Sonnet gov*", + description: "Anthropic's 3.7 Sonnet model.", + params: { + model: "aws-bedrock-claude-37-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.7 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude35gov: { + title: "Claude 3.5 Sonnet gov*", + description: "Anthropic's 3.5 Sonnet model.", + params: { + model: "aws-bedrock-claude-35-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.5 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4s: { + title: "Claude 4 Sonnet", + description: "Anthropic's Claude 4 Sonnet", + params: { + model: "claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4o: { + title: "Claude 4 Opus", + description: "Anthropic's Claude 4 Opus", + params: { + model: "claude-4-opus", + contextLength: 200_000, + title: "Claude 4 Opus", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4sonnet: { + title: "Claude 4 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude45sonnet: { + title: "Claude 4.5 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-45-sonnet", + contextLength: 200_000, + title: "Claude 4.5 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude41opus: { + title: "Claude 4.1 Opus*", + description: "Claude 4.1 Opus", + params: { + model: "google-claude-4-opus", + contextLength: 200_000, + title: "Claude 4.1 Opus*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksagenovalite: { + title: "Nova Lite*", + description: "AWS Gov Nova Lite model.", + params: { + model: "aws-bedrock-nova-lite-gov", + contextLength: 300_000, + title: "Nova Lite*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "aws.png", + isOpenSource: false, + }, asksagegroqllama33: { title: "Llama 3.3", description: "Llama-3.3 is a large language model customized by Groq.", @@ -1532,7 +1715,9 @@ export const models: { [key: string]: ModelPackage } = { title: "Llama 3.3", model: "groq-llama33", contextLength: 128_000, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, @@ -1543,10 +1728,66 @@ export const models: { [key: string]: ModelPackage } = { title: "Groq-70B", model: "groq-70b", contextLength: 8_192, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, + asksagegemini20Flash: { + title: "Gemini 2.0 Flash*", + description: + "Google's powerful workhorse model with low latency and enhanced performance.", + params: { + title: "Gemini 2.0 Flash*", + model: "google-gemini-20-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25Pro: { + title: "Gemini 2.5 Pro*", + description: "Google's Gemini 2.5 Pro model", + params: { + title: "Gemini 2.5 Pro*", + model: "google-gemini-2.5-pro", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25flash: { + title: "Gemini 2.5 Flash*", + description: "Google's Gemini 2.5 Flash model", + params: { + title: "Gemini 2.5 Flash*", + model: "google-gemini-2.5-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegrok4: { + title: "Grok 4", + description: + "xAI's latest and greatest flagship model, offering strong performance in natural language, math and reasoning.", + params: { + title: "Grok 4", + model: "xai-grok", + contextLength: 256_000, + apiKey: "", + }, + icon: "xAI.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, Qwen2Coder: { title: "Qwen 2.5 Coder 7b", description: @@ -1596,7 +1837,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 256000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4FastReasoning: { @@ -1609,7 +1850,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 2_000_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4FastNonReasoning: { @@ -1622,7 +1863,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 2_000_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4: { @@ -1636,7 +1877,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 256_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok3: { @@ -1650,7 +1891,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 131_072, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok3Mini: { @@ -1664,7 +1905,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 131_072, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, gemma2_2b: { diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 1e9d5a292..88e091ce7 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -598,9 +598,6 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n models.gemini20FlashLite, models.gemini20FlashImageGeneration, models.gemini25ProExp, - models.gemini15Pro, - models.geminiPro, - models.gemini15Flash, ], apiKeyUrl: "https://aistudio.google.com/app/apikey", }, @@ -925,11 +922,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo longDescription: "Use the supported Vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate", icon: "vertexai.png", - packages: [ - models.VertexGemini15Pro, - models.VertexGemini15Flash, - models.mistralLarge, - ], + packages: [models.mistralLarge], collectInputFor: [ { inputType: "project", @@ -949,7 +942,6 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ...completionParamsInputsConfigs, ], }, - askSage: { title: "Ask Sage", provider: "askSage", @@ -960,7 +952,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo tags: [ModelProviderTags.RequiresApiKey], params: { apiKey: "", - apiBase: "https://api.asksage.ai/server/", // Default base URL + apiBase: "https://api.asksage.ai/server/", }, collectInputFor: [ { @@ -974,33 +966,46 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo inputType: "text", key: "apiBase", label: "API Base URL", - placeholder: "Enter the API Base URL", + placeholder: "Enter your Ask Sage API base URL", required: true, + defaultValue: "https://api.asksage.ai/server/", }, ...completionParamsInputsConfigs, ], packages: [ - models.asksagegpt4ogov, - models.asksagegpt4ominigov, - models.asksagegpt4gov, - models.asksagegpt35gov, - models.gpt4o, - models.gpt4omini, - models.asksagegpt4, - models.asksagegpt432, - models.asksagegpto1, - models.asksagegpto1mini, - models.gpt35turbo, + models.asksageclaude45sonnet, + models.asksageclaude4sonnet, + models.asksageclaude41opus, + models.asksagegpt5, + models.asksagegpt5nano, + models.asksagegpt5mini, + models.asksagegemini20Flash, + models.asksagegemini25Pro, + models.asksagegemini25flash, models.asksageclaude35gov, - models.claude35Sonnet, - models.claude3Opus, - models.claude3Sonnet, - models.grokBeta, - models.asksagegroqllama33, + models.asksageclaude37sonnetgov, + models.asksagegpt4o, + models.asksagegpt4omini, + models.asksagegpt4gov, + models.asksagegpt4ogov, + models.asksagegpt35, + models.asksagegpt35gov, + models.asksagegpt4ominigov, + models.asksagegpt4, + models.asksagegpto1, + models.asksagegpt41, + models.asksagegpt41mini, + models.asksagegpt41nano, + models.asksagegpto3, + models.asksagegpt04mini, + models.asksagenovalite, models.asksagegroq70b, - models.mistralLarge, - models.llama370bChat, - models.gemini15Pro, + models.asksagegroqllama33, + models.asksagegrok4, + models.asksageclaude35Sonnet, + models.asksageclaude37sonnet, + models.asksageclaude4s, + models.asksageclaude4o, ], apiKeyUrl: "https://chat.asksage.ai/", }, diff --git a/gui/src/pages/config/components/ConfigHeader.tsx b/gui/src/pages/config/components/ConfigHeader.tsx index 6449d11d1..73779258d 100644 --- a/gui/src/pages/config/components/ConfigHeader.tsx +++ b/gui/src/pages/config/components/ConfigHeader.tsx @@ -1,6 +1,7 @@ import { PlusIcon } from "@heroicons/react/24/outline"; import { ToolTip } from "../../../components/gui/Tooltip"; import { Button } from "../../../components/ui"; +import { cn } from "../../../util/cn"; interface ConfigHeaderProps { title: string; @@ -9,6 +10,7 @@ interface ConfigHeaderProps { addButtonTooltip?: string; className?: string; variant?: "default" | "sm"; + showAddButton?: boolean; } export function ConfigHeader({ @@ -18,6 +20,7 @@ export function ConfigHeader({ addButtonTooltip = "Add item", className = "", variant = "default", + showAddButton = true, }: ConfigHeaderProps) { const isSmall = variant === "sm"; const marginBottom = isSmall ? "mb-4" : "mb-6"; @@ -26,13 +29,16 @@ export function ConfigHeader({ return (
{title} {subtext &&

{subtext}

}
- {onAddClick && ( + {showAddButton && onAddClick && (