diff --git a/.continue/rules/mintlify-formatting.md b/.continue/rules/mintlify-formatting.md
new file mode 100644
index 000000000..4df9bdb91
--- /dev/null
+++ b/.continue/rules/mintlify-formatting.md
@@ -0,0 +1,100 @@
+# Mintlify Documentation Formatting Rules
+
+## Component Formatting
+
+When working with Mintlify documentation components (Card, Info, Tip, Note, Warning, etc.), follow these formatting guidelines:
+
+### Bullet Points and Lists
+
+1. **Always add a blank line** after the opening component tag and before the closing tag
+2. **Indent content** by 2 spaces within components
+3. **Use proper list formatting** with each item on its own line:
+ - Start lists on a new line after introductory text
+ - Use `-` for unordered lists
+ - Maintain consistent indentation
+
+### Examples
+
+#### ✅ Correct Formatting:
+
+```mdx
+
+
+ This is the content with proper formatting:
+ - First bullet point
+ - Second bullet point
+ - Third bullet point
+
+
+```
+
+```mdx
+
+
+ Important information here:
+ - Point one
+ - Point two
+ - Point three
+
+
+```
+
+#### ❌ Incorrect Formatting:
+
+```mdx
+
+ This is wrong: - All bullets - On one line - Bad formatting
+
+```
+
+### Component-Specific Rules
+
+1. **Card Components**: Always include blank lines and proper indentation
+2. **Info/Tip/Note/Warning**: Format lists as bullet points, not inline
+3. **CardGroup**: Each Card within should follow the same formatting rules
+4. **Code Blocks**: Within components, maintain proper indentation
+
+### Links in Lists
+
+When including links in bullet points:
+```mdx
+- [Link Text](url): Description of the link
+```
+
+### Nested Components
+
+For nested components, maintain proper indentation levels:
+```mdx
+
+
+
+ Content here:
+ - Bullet one
+ - Bullet two
+
+
+
+
+
+ More content:
+ - Another bullet
+ - Final bullet
+
+
+
+```
+
+## Application
+
+These rules apply to all `.mdx` files in the `docs/` directory, particularly:
+- Guide documents
+- Cookbook documents
+- Reference documentation
+- Any Mintlify-powered documentation
+
+## Automation Note
+
+When using Continue or other AI assistants to generate or modify documentation:
+- Always format Mintlify components according to these rules
+- Review generated content for proper formatting
+- Apply these rules consistently across all documentation
\ No newline at end of file
diff --git a/.continue/rules/no-any-types.md b/.continue/rules/no-any-types.md
new file mode 100644
index 000000000..1ec5f4f3e
--- /dev/null
+++ b/.continue/rules/no-any-types.md
@@ -0,0 +1,5 @@
+---
+globs: "**/*.{ts,tsx}"
+---
+
+Avoid using the `any` type wherever possible. Use unknown or find the correct type. The only acceptable place to use any is when typecasting for test mocks, and even then it's better to avoid and provide a proper mock.
diff --git a/.continue/rules/personality.md b/.continue/rules/personality.md
new file mode 100644
index 000000000..c68d0e35c
--- /dev/null
+++ b/.continue/rules/personality.md
@@ -0,0 +1,6 @@
+---
+name: Personality Rules
+description: Conversational and personality guidelines
+---
+
+When the user challenges your output or asks a question, don't be overly-amiable (e.g. responding "You're right" all the time). Focus on correctness and be willing to tell the user they are wrong.
diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml
index 77f6ceff3..03a9c7855 100644
--- a/.github/actions/run-jetbrains-tests/action.yml
+++ b/.github/actions/run-jetbrains-tests/action.yml
@@ -107,7 +107,7 @@ runs:
cd binary
npm run build
- - name: Start test IDE
+ - name: Run tests
shell: bash
run: |
cd extensions/intellij
@@ -115,21 +115,7 @@ runs:
Xvfb -ac :99 -screen 0 1920x1080x24 &
sleep 10
mkdir -p build/reports
- ./gradlew runIdeForUiTests &
-
- - name: Wait for JB connection
- uses: jtalk/url-health-check-action@v3
- with:
- url: http://127.0.0.1:8082
- max-attempts: 15
- retry-delay: 30s
-
- - name: Run tests
- shell: bash
- run: |
- cd extensions/intellij
- export DISPLAY=:99.0
- ./gradlew test
+ ./gradlew test testIntegration
- name: Move video
if: ${{ failure() }}
diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml
index f718deeca..103b9c7df 100644
--- a/.github/workflows/continue-detailed-review.yaml
+++ b/.github/workflows/continue-detailed-review.yaml
@@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
- uses: continuedev/continue/actions/detailed-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
+ uses: continuedev/continue/actions/detailed-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev
diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml
index 01fffa316..0d5e317c3 100644
--- a/.github/workflows/continue-general-review.yaml
+++ b/.github/workflows/continue-general-review.yaml
@@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
- uses: continuedev/continue/actions/general-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
+ uses: continuedev/continue/actions/general-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml
index 8be01696a..041ff53ca 100644
--- a/.github/workflows/main.yaml
+++ b/.github/workflows/main.yaml
@@ -26,8 +26,24 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
+ check-version:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v5
+ with:
+ fetch-depth: 0 # This ensures all tags are fetched
+
+ - name: Checkout tag
+ run: git checkout ${GITHUB_REF#refs/tags/}
+
+ - name: Make sure version isn't odd
+ run: |
+ cd extensions/vscode
+ node scripts/versionCheck.js
+
build:
- needs: check_release_name
+ needs: [check_release_name, check-version]
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
runs-on: ${{ matrix.os }}
strategy:
@@ -88,22 +104,6 @@ jobs:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"
- check-version:
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v5
- with:
- fetch-depth: 0 # This ensures all tags are fetched
-
- - name: Checkout tag
- run: git checkout ${GITHUB_REF#refs/tags/}
-
- - name: Make sure version isn't odd
- run: |
- cd extensions/vscode
- node scripts/versionCheck.js
-
release:
permissions:
contents: write
diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml
index 12ac77caf..370acb854 100644
--- a/.github/workflows/pr-checks.yaml
+++ b/.github/workflows/pr-checks.yaml
@@ -84,6 +84,9 @@ jobs:
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
gui-checks:
runs-on: ubuntu-latest
@@ -217,6 +220,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
diff --git a/.github/workflows/release-config-yaml.yml b/.github/workflows/release-config-yaml.yml
index fea1c31d4..cae9b51ae 100644
--- a/.github/workflows/release-config-yaml.yml
+++ b/.github/workflows/release-config-yaml.yml
@@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
diff --git a/.github/workflows/release-fetch.yml b/.github/workflows/release-fetch.yml
index fb4636a21..4254d03ff 100644
--- a/.github/workflows/release-fetch.yml
+++ b/.github/workflows/release-fetch.yml
@@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
diff --git a/.github/workflows/release-llm-info.yml b/.github/workflows/release-llm-info.yml
index 7a94eba59..bc41ca21e 100644
--- a/.github/workflows/release-llm-info.yml
+++ b/.github/workflows/release-llm-info.yml
@@ -23,4 +23,7 @@ jobs:
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
- AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
\ No newline at end of file
+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
diff --git a/.github/workflows/release-openai-adapters.yml b/.github/workflows/release-openai-adapters.yml
index e2a6b0622..ea83b5e93 100644
--- a/.github/workflows/release-openai-adapters.yml
+++ b/.github/workflows/release-openai-adapters.yml
@@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml
index cb607033c..252c2538c 100644
--- a/.github/workflows/respond-to-cubic.yaml
+++ b/.github/workflows/respond-to-cubic.yaml
@@ -21,7 +21,12 @@ jobs:
- name: Check if comment contains @continuedev
id: check-mention
run: |
- if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
+ # Create a temporary file to safely handle comment body with special characters
+ cat > /tmp/comment.txt << 'COMMENT_EOF'
+ ${{ github.event.comment.body }}
+ COMMENT_EOF
+
+ if grep -q "@continuedev" /tmp/comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
@@ -83,15 +88,22 @@ jobs:
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
- # Create the prompt for remote session
- PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
+ # Create a temporary file for the prompt to handle special characters and newlines properly
+ cat > /tmp/prompt.txt << 'PROMPT_EOF'
+ Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
${{ github.event.comment.body }}
- Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
+ Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch.
+ PROMPT_EOF
+
+ # Debug output
+ echo "PROMPT content:"
+ cat /tmp/prompt.txt
# Start remote session and capture JSON output
- SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
+ echo "Starting cn with prompt..."
+ SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@@ -108,10 +120,13 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
+ env:
+ ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
- const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
- > ${{ github.event.comment.body }}`;
+ const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
+ const originalComment = process.env.ORIGINAL_COMMENT;
+ const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
await github.rest.issues.createComment({
owner: context.repo.owner,
@@ -125,7 +140,8 @@ jobs:
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
- echo "Original comment: ${{ github.event.comment.body }}"
+ echo "Original comment:"
+ cat /tmp/comment.txt
respond-to-review-comment:
# Only run on pull request review comments
@@ -136,7 +152,12 @@ jobs:
- name: Check if comment contains @continuedev
id: check-mention
run: |
- if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
+ # Create a temporary file to safely handle comment body with special characters
+ cat > /tmp/review_comment.txt << 'COMMENT_EOF'
+ ${{ github.event.comment.body }}
+ COMMENT_EOF
+
+ if grep -q "@continuedev" /tmp/review_comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
@@ -233,7 +254,7 @@ jobs:
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
- SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
+ SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@@ -250,10 +271,13 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
+ env:
+ ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
- const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
- > ${{ github.event.comment.body }}`;
+ const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
+ const originalComment = process.env.ORIGINAL_COMMENT;
+ const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
const commentParams = {
owner: context.repo.owner,
@@ -274,4 +298,5 @@ jobs:
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
- echo "Original comment: ${{ github.event.comment.body }}"
+ echo "Original comment:"
+ cat /tmp/review_comment.txt
diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml
index 5f243f6bc..e763aa04c 100644
--- a/.github/workflows/reusable-release.yml
+++ b/.github/workflows/reusable-release.yml
@@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
+ RELACE_API_KEY:
+ required: false
+ INCEPTION_API_KEY:
+ required: false
permissions:
contents: write
@@ -77,6 +81,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
+ RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
+ INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
- name: Release
env:
diff --git a/.prettierignore b/.prettierignore
index 51cd37d83..cd8b968db 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -4,6 +4,7 @@ binary/out
binary/tmp
core/.continue-test
docs/.docusaurus
+docs/**/*.mdx
extensions/.continue-debug
extensions/vscode/continue_rc_schema.json
extensions/vscode/.vscode-test
@@ -17,6 +18,7 @@ extensions/vscode/models
extensions/intellij/src/main/resources
gui/dist
**/.continueignore
+.continue/rules/mintlify-formatting.md
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 9e8fd7ca9..22349e3a8 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -136,8 +136,9 @@
"name": "Debug CLI",
"type": "node",
"request": "launch",
- "program": "${workspaceFolder}/extensions/cli/src/index.ts",
+ "program": "${workspaceFolder}/extensions/cli/dist/cn.js",
"args": [],
+ "runtimeArgs": ["--enable-source-maps"],
"env": {
"NODE_ENV": "development"
// "CONTINUE_API_BASE": "http://localhost:3001/",
@@ -147,13 +148,17 @@
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["/**"],
- "runtimeArgs": ["--loader", "ts-node/esm"],
"sourceMaps": true,
+ "outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"],
+ "sourceMapPathOverrides": {
+ "../src/*": "${workspaceFolder}/extensions/cli/src/*",
+ "../../core/*": "${workspaceFolder}/core/*"
+ },
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
- "preLaunchTask": "watch-logs",
+ "preLaunchTask": "cli:build-and-watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
},
{
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index ae679efd3..9b34de0f1 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -330,6 +330,26 @@
"cwd": "${workspaceFolder}/extensions/cli"
}
},
+ {
+ "label": "cli:build-no-minify",
+ "type": "shell",
+ "command": "npm",
+ "args": ["run", "build:bundle", "--", "--no-minify"],
+ "group": "build",
+ "presentation": {
+ "echo": true,
+ "reveal": "silent",
+ "focus": false,
+ "panel": "shared",
+ "showReuseMessage": true,
+ "clear": false,
+ "close": true
+ },
+ "problemMatcher": ["$tsc"],
+ "options": {
+ "cwd": "${workspaceFolder}/extensions/cli"
+ }
+ },
{
"label": "cli:test",
"type": "npm",
@@ -373,6 +393,21 @@
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
+ },
+ {
+ "label": "cli:build-and-watch-logs",
+ "dependsOn": ["cli:build-no-minify", "watch-logs"],
+ "dependsOrder": "sequence",
+ "type": "shell",
+ "command": "echo",
+ "args": ["Build and watch logs completed"],
+ "presentation": {
+ "group": "build-tasks",
+ "panel": "shared",
+ "reveal": "silent",
+ "close": true,
+ "focus": false
+ }
}
]
}
diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml
index dd18c447a..0743fcba0 100644
--- a/actions/general-review/action.yml
+++ b/actions/general-review/action.yml
@@ -1,20 +1,20 @@
-name: 'Continue PR Review'
-description: 'Automated code review for pull requests using Continue CLI'
-author: 'Continue Dev, Inc.'
+name: "Continue PR Review"
+description: "Automated code review for pull requests using Continue CLI"
+author: "Continue Dev, Inc."
inputs:
continue-api-key:
- description: 'API key for Continue service'
+ description: "API key for Continue service"
required: true
continue-org:
- description: 'Organization for Continue config'
+ description: "Organization for Continue config"
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
- using: 'composite'
+ using: "composite"
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@@ -27,7 +27,7 @@ runs:
run: |
# Check if this action should run based on event type and user permissions
SHOULD_RUN="false"
-
+
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Check if PR is a draft
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
@@ -56,7 +56,7 @@ runs:
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
-
+
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
@@ -162,14 +162,14 @@ runs:
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > code_review.md << 'EOF'
-## Code Review Summary
+ ## Code Review Summary
-⚠️ AI review skipped: CONTINUE_API_KEY not configured.
+ ⚠️ 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
+ ### Configuration Required
+ - Please set the CONTINUE_API_KEY secret in repository settings
+ - Verify that the organization and config path are valid
+ EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
@@ -180,7 +180,7 @@ EOF
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
exit 1
fi
-
+
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
@@ -192,14 +192,14 @@ EOF
if ! cn --version; then
echo "Warning: Continue CLI not found or not working"
cat > code_review.md << 'EOF'
-## Code Review Summary
+ ## Code Review Summary
-⚠️ AI review skipped: Continue CLI installation failed.
+ ⚠️ AI review skipped: Continue CLI installation failed.
-### Troubleshooting
-- Check that npm installation succeeded
-- Verify @continuedev/cli package is available
-EOF
+ ### Troubleshooting
+ - Check that npm installation succeeded
+ - Verify @continuedev/cli package is available
+ EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "Continue CLI version: $(cn --version)"
@@ -222,15 +222,15 @@ EOF
# Create fallback review
cat > code_review.md << 'EOF'
-## Code Review Summary
+ ## Code Review Summary
-⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
+ ⚠️ AI review failed due to service initialization issues. 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
+ ### 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
else
echo "Review generated successfully"
fi
@@ -294,5 +294,5 @@ EOF
}
branding:
- icon: 'code'
- color: 'blue'
\ No newline at end of file
+ icon: "code"
+ color: "blue"
diff --git a/binary/package-lock.json b/binary/package-lock.json
index 92756d546..001e69a8e 100644
--- a/binary/package-lock.json
+++ b/binary/package-lock.json
@@ -56,6 +56,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
+ "@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
diff --git a/core/codeRenderer/CodeRenderer.ts b/core/codeRenderer/CodeRenderer.ts
index c61d2e3cb..c09b1ef51 100644
--- a/core/codeRenderer/CodeRenderer.ts
+++ b/core/codeRenderer/CodeRenderer.ts
@@ -19,7 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
-import { DiffLine } from "..";
+import { DiffChar, DiffLine } from "..";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
@@ -228,6 +228,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
+ newDiffChars: DiffChar[],
): Promise {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
@@ -236,13 +237,14 @@ export class CodeRenderer {
currLineOffsetFromTop,
newDiffLines,
);
- // console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
options,
+ newDiffChars,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
+ const borderColor = "#6b6b6b";
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
@@ -256,12 +258,11 @@ export class CodeRenderer {
}
-
+
${lineBackgrounds}
${guts}
`;
- // console.log(svg);
return Buffer.from(svg, "utf8");
}
@@ -269,11 +270,56 @@ export class CodeRenderer {
convertShikiHtmlToSvgGut(
shikiHtml: string,
options: ConversionOptions,
+ diffChars: DiffChar[],
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
+
+ const additionSegmentsByLine = new Map<
+ number,
+ Array<{ start: number; end: number }>
+ >();
+
+ diffChars.forEach((diff) => {
+ if (
+ diff.type !== "new" ||
+ diff.newLineIndex === undefined ||
+ diff.newCharIndexInLine === undefined
+ ) {
+ return;
+ }
+
+ if (diff.char.includes("\n")) {
+ return;
+ }
+
+ const start = diff.newCharIndexInLine;
+ const end = start + diff.char.length;
+ const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? [];
+ existing.push({ start, end });
+ additionSegmentsByLine.set(diff.newLineIndex, existing);
+ });
+
+ additionSegmentsByLine.forEach((segments, lineIndex) => {
+ segments.sort((a, b) => a.start - b.start);
+ const merged: Array<{ start: number; end: number }> = [];
+ segments.forEach((segment) => {
+ if (merged.length === 0) {
+ merged.push({ ...segment });
+ return;
+ }
+
+ const last = merged[merged.length - 1];
+ if (segment.start <= last.end) {
+ last.end = Math.max(last.end, segment.end);
+ } else {
+ merged.push({ ...segment });
+ }
+ });
+ additionSegmentsByLine.set(lineIndex, merged);
+ });
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
@@ -309,60 +355,37 @@ export class CodeRenderer {
return `${spans}`;
});
+ const estimatedCharWidth = options.fontSize * 0.6;
+ const additionFill = "rgba(40, 167, 69, 0.25)";
+
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
- const bgColor = classes.includes("highlighted")
- ? this.editorLineHighlight
- : classes.includes("diff add")
- ? "rgba(255, 255, 0, 0.2)"
- : this.editorBackground;
-
const y = index * options.lineHeight;
- const isFirst = index === 0;
- const isLast = index === lines.length - 1;
- const isSingleLine = isFirst && isLast;
- const radius = 10;
+ const segments = additionSegmentsByLine.get(index) ?? [];
+ const backgrounds: string[] = [];
- // Handle single line case (both first and last)
- if (isSingleLine) {
- return ``;
+ if (classes.includes("highlighted")) {
+ backgrounds.push(
+ ``,
+ );
}
- // SVG notes:
- // By default SVGs have anti-aliasing on.
- // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
- // Turning it off with 'shape-rendering="crispEdges"' solves the issue.
- return isFirst
- ? ``
- : isLast
- ? ``
- : ``;
+ segments.forEach(({ start, end }) => {
+ const widthInChars = Math.max(end - start, 0);
+ if (widthInChars <= 0) {
+ return;
+ }
+ const x = start * estimatedCharWidth;
+ const segmentWidth = widthInChars * estimatedCharWidth;
+ backgrounds.push(
+ ``,
+ );
+ });
+
+ return backgrounds.join("\n");
})
+ .filter((bg) => bg.length > 0)
.join("\n");
return {
@@ -394,6 +417,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
+ newDiffChars: DiffChar[],
): Promise {
switch (options.imageType) {
// case "png":
@@ -413,6 +437,7 @@ export class CodeRenderer {
options,
currLineOffsetFromTop,
newDiffLines,
+ newDiffChars,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}
diff --git a/core/commands/slash/built-in-legacy/share.ts b/core/commands/slash/built-in-legacy/share.ts
index daddf8dff..041269ca8 100644
--- a/core/commands/slash/built-in-legacy/share.ts
+++ b/core/commands/slash/built-in-legacy/share.ts
@@ -1,99 +1,17 @@
-import fs from "fs";
-import { homedir } from "node:os";
-import { fileURLToPath, pathToFileURL } from "node:url";
+import { fileURLToPath } from "node:url";
import path from "path";
-import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../../index.js";
-import { renderChatMessage } from "../../../util/messageContent.js";
-import { getContinueGlobalPath } from "../../../util/paths.js";
-
-// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
-function getOffsetDatetime(date: Date): Date {
- const offset = date.getTimezoneOffset();
- const offsetHours = Math.floor(offset / 60);
- const offsetMinutes = offset % 60;
- date.setHours(date.getHours() - offsetHours);
- date.setMinutes(date.getMinutes() - offsetMinutes);
-
- return date;
-}
-
-function asBasicISOString(date: Date): string {
- const isoString = date.toISOString();
-
- return isoString.replace(/[-:]|(\.\d+Z)/g, "");
-}
-
-function reformatCodeBlocks(msgText: string): string {
- const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
- msgText = msgText.replace(
- codeBlockFenceRegex,
- (match, metadata, filename, extension) => {
- const lang = languageForFilepath(filename);
- return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
- },
- );
- // Appease the markdown linter
- return msgText.replace(/```\n```/g, "```\n\n```");
-}
+import { shareSession } from "../../../util/historyUtils.js";
const ShareSlashCommand: SlashCommand = {
name: "share",
description: "Export the current chat session to markdown",
run: async function* ({ ide, history, params }) {
- const now = new Date();
-
- let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
-
- // As currently implemented, the /share command is by definition the last
- // message in the chat history, this will omit it
- for (const msg of history.slice(0, history.length - 1)) {
- let msgText = msg.content;
- msgText = renderChatMessage(msg);
-
- if (msg.role === "user" && msgText.search("```") > -1) {
- msgText = reformatCodeBlocks(msgText);
- }
-
- // format messages as blockquotes
- msgText = msgText.replace(/^/gm, "> ");
-
- content += `\n\n#### ${
- msg.role === "user" ? "_User_" : "_Assistant_"
- }\n\n${msgText}`;
- }
-
- let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
-
- if (outputDir.startsWith("~")) {
- outputDir = outputDir.replace(/^~/, homedir);
- } else if (
- outputDir.startsWith("./") ||
- outputDir.startsWith(".\\") ||
- outputDir === "."
- ) {
- const workspaceDirs = await ide.getWorkspaceDirs();
- // Although the most common situation is to have one directory open in a
- // workspace it's also possible to have just a file open without an
- // associated directory or to use multi-root workspaces in which multiple
- // folders are included. We default to using the first item in the list, if
- // it exists.
- const workspaceDirectory = workspaceDirs?.[0] || "";
- outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
- }
-
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir, { recursive: true });
- }
-
- const dtString = asBasicISOString(getOffsetDatetime(now));
- const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
-
- const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
- await ide.writeFile(fileUrl, content);
- await ide.openFile(fileUrl);
-
+ const fileUrl = await shareSession(ide, history, params?.outputDir);
+ const filePath = fileURLToPath(fileUrl);
+ // output path is the parent directory of the filePath
+ const outPath = path.dirname(filePath);
yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
},
};
diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts
new file mode 100644
index 000000000..d907768cb
--- /dev/null
+++ b/core/commands/slash/ruleBlockSlashCommand.ts
@@ -0,0 +1,15 @@
+import { RuleWithSource, SlashCommandWithSource } from "../..";
+
+export function convertRuleBlockToSlashCommand(
+ rule: RuleWithSource,
+): SlashCommandWithSource {
+ return {
+ name:
+ rule.name ||
+ (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule),
+ description: rule.description ?? "",
+ prompt: rule.rule,
+ source: "invokable-rule",
+ promptFile: rule.ruleFile,
+ };
+}
diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts
new file mode 100644
index 000000000..ccbc2df4f
--- /dev/null
+++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import { RuleWithSource } from "../..";
+import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand";
+
+describe("convertRuleBlockToSlashCommand", () => {
+ it("should convert a rule with all properties to a slash command", () => {
+ const rule: RuleWithSource = {
+ name: "Code Review",
+ rule: "Review this code for best practices",
+ description: "Performs a code review",
+ source: "rules-block",
+ ruleFile: "/path/to/rules.yaml",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result).toEqual({
+ name: "Code Review",
+ description: "Performs a code review",
+ prompt: "Review this code for best practices",
+ source: "invokable-rule",
+ promptFile: "/path/to/rules.yaml",
+ });
+ });
+
+ it("should handle a rule without name", () => {
+ const rule: RuleWithSource = {
+ rule: "Review this code",
+ source: "rules-block",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result.name).toBe("Review this code");
+ expect(result.prompt).toBe("Review this code");
+ });
+
+ it("should truncate long rule text when used as name", () => {
+ const rule: RuleWithSource = {
+ rule: "This is a very long rule text that should be truncated",
+ source: "rules-block",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result.name).toBe("This is a very long ...");
+ expect(result.prompt).toBe(
+ "This is a very long rule text that should be truncated",
+ );
+ });
+
+ it("should handle a rule without description", () => {
+ const rule: RuleWithSource = {
+ name: "Test Rule",
+ rule: "Test rule content",
+ source: "rules-block",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result.description).toBe("");
+ });
+
+ it("should use rule text as the prompt", () => {
+ const rule: RuleWithSource = {
+ name: "Explain Code",
+ rule: "Explain what this code does in simple terms",
+ source: "rules-block",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result.prompt).toBe("Explain what this code does in simple terms");
+ });
+
+ it("should always set source to 'invokable-rule'", () => {
+ const rule: RuleWithSource = {
+ name: "Test",
+ rule: "Test",
+ source: "default-chat",
+ invokable: true,
+ };
+
+ const result = convertRuleBlockToSlashCommand(rule);
+
+ expect(result.source).toBe("invokable-rule");
+ });
+});
diff --git a/core/config/load.ts b/core/config/load.ts
index 370695bd3..b7150fd4c 100644
--- a/core/config/load.ts
+++ b/core/config/load.ts
@@ -215,8 +215,8 @@ function applyRequestOptionsToModels(
// Prepare models
for (const model of models) {
model.requestOptions = {
- ...model.requestOptions,
...config.requestOptions,
+ ...model.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
@@ -545,6 +545,7 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
+
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@@ -555,6 +556,7 @@ async function intermediateToFinalConfig({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
+ requestOptions: config.requestOptions,
}),
),
false,
diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts
index 1ee771c05..42bfcd21d 100644
--- a/core/config/markdown/loadMarkdownRules.ts
+++ b/core/config/markdown/loadMarkdownRules.ts
@@ -3,11 +3,13 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
-import { findUriInDirs } from "../../util/uri";
+import { findUriInDirs, 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
+ * and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
rules: RuleWithSource[];
@@ -16,6 +18,38 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
+ // First, try to load agent files from workspace root
+ const workspaceDirs = await ide.getWorkspaceDirs();
+
+ for (const workspaceDir of workspaceDirs) {
+ let agentFileFound = false;
+ for (const fileName of SUPPORTED_AGENT_FILES) {
+ try {
+ const agentFilePath = joinPathsToUri(workspaceDir, fileName);
+ const agentContent = await ide.readFile(agentFilePath);
+
+ 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(
diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts
index d0c268967..c213bcb66 100644
--- a/core/config/profile/doLoadConfig.ts
+++ b/core/config/profile/doLoadConfig.ts
@@ -18,6 +18,7 @@ import {
Tool,
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
+import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
@@ -155,6 +156,21 @@ export default async function doLoadConfig(options: {
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
+ // Convert invokable rules to slash commands
+ for (const rule of newConfig.rules) {
+ if (rule.invokable) {
+ try {
+ const slashCommand = convertRuleBlockToSlashCommand(rule);
+ (newConfig.slashCommands ??= []).push(slashCommand);
+ } catch (e) {
+ errors.push({
+ message: `Error converting invokable rule ${rule.name} to slash command: ${e instanceof Error ? e.message : e}`,
+ fatal: false,
+ });
+ }
+ }
+ }
+
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
@@ -187,7 +203,6 @@ export default async function doLoadConfig(options: {
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
- // Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;
diff --git a/core/config/types.ts b/core/config/types.ts
index 6048cf4d3..c6441f626 100644
--- a/core/config/types.ts
+++ b/core/config/types.ts
@@ -280,11 +280,6 @@ declare global {
replacement: string;
}
- export interface ContinueError {
- title: string;
- message: string;
- }
-
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
@@ -692,6 +687,8 @@ declare global {
openUrl(url: string): Promise;
+ getExternalUri?(uri: string): Promise;
+
runCommand(command: string): Promise;
saveFile(filepath: string): Promise;
@@ -1061,6 +1058,7 @@ declare global {
filepath?: string;
fileContent?: string;
originalFileContent?: string;
+ autoFormattingDiff?: string;
}
export interface RangeInFileWithContents {
diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts
index 65cb5e0ff..1cfdb7120 100644
--- a/core/config/yaml/loadYaml.ts
+++ b/core/config/yaml/loadYaml.ts
@@ -4,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
+ mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@@ -33,10 +34,7 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
-import {
- convertYamlMcpToContinueMcp,
- convertYamlRuleToContinueRule,
-} from "./yamlToContinueConfig";
+import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@@ -154,16 +152,15 @@ async function loadConfigYaml(options: {
};
}
-async function configYamlToContinueConfig(options: {
+export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
- ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
- let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
+ let { config, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@@ -191,6 +188,7 @@ async function configYamlToContinueConfig(options: {
summarize: null,
},
rules: [],
+ requestOptions: { ...config.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@@ -208,10 +206,17 @@ async function configYamlToContinueConfig(options: {
}
for (const rule of config.rules ?? []) {
- continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
+ const convertedRule = convertYamlRuleToContinueRule(rule);
+ continueConfig.rules.push(convertedRule);
}
- continueConfig.data = config.data;
+ continueConfig.data = config.data?.map((d) => ({
+ ...d,
+ requestOptions: mergeConfigYamlRequestOptions(
+ d.requestOptions,
+ continueConfig.requestOptions,
+ ),
+ }));
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@@ -235,12 +240,6 @@ async function configYamlToContinueConfig(options: {
});
});
- continueConfig.experimental = {
- modelContextProtocolServers: config.mcpServers?.map(
- convertYamlMcpToContinueMcp,
- ),
- };
-
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@@ -292,9 +291,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
- ide,
uniqueId,
- ideSettings,
llmLogger,
config: continueConfig,
});
@@ -379,6 +376,7 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
+
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@@ -391,6 +389,10 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
+ requestOptions: mergeConfigYamlRequestOptions(
+ server.requestOptions,
+ config.requestOptions,
+ ),
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
@@ -449,7 +451,6 @@ export async function loadContinueConfigFromYaml(options: {
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
- ideSettings,
ideInfo,
uniqueId,
llmLogger,
diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts
index 45cbdcbfb..05fa48853 100644
--- a/core/config/yaml/models.ts
+++ b/core/config/yaml/models.ts
@@ -1,12 +1,9 @@
-import { ModelConfig } from "@continuedev/config-yaml";
-
import {
- ContinueConfig,
- IDE,
- IdeSettings,
- ILLMLogger,
- LLMOptions,
-} from "../..";
+ mergeConfigYamlRequestOptions,
+ ModelConfig,
+} from "@continuedev/config-yaml";
+
+import { ContinueConfig, ILLMLogger, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
@@ -29,14 +26,12 @@ function getModelClass(
async function modelConfigToBaseLLM({
model,
uniqueId,
- ideSettings,
llmLogger,
config,
isFromAutoDetect,
}: {
model: ModelConfig;
uniqueId: string;
- ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
isFromAutoDetect?: boolean;
@@ -49,6 +44,11 @@ async function modelConfigToBaseLLM({
const { capabilities, ...rest } = model;
+ const mergedRequestOptions = mergeConfigYamlRequestOptions(
+ rest.requestOptions,
+ config.requestOptions,
+ );
+
let options: LLMOptions = {
...rest,
contextLength: model.defaultCompletionOptions?.contextLength,
@@ -74,6 +74,7 @@ async function modelConfigToBaseLLM({
},
autocompleteOptions: model.autocompleteOptions,
isFromAutoDetect,
+ requestOptions: mergedRequestOptions,
};
// Model capabilities - need to be undefined if not found
@@ -154,17 +155,13 @@ async function modelConfigToBaseLLM({
async function autodetectModels({
llm,
model,
- ide,
uniqueId,
- ideSettings,
llmLogger,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
- ide: IDE;
uniqueId: string;
- ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise {
@@ -183,7 +180,6 @@ async function autodetectModels({
name: modelName,
},
uniqueId,
- ideSettings,
llmLogger,
config,
isFromAutoDetect: true,
@@ -199,23 +195,18 @@ async function autodetectModels({
export async function llmsFromModelConfig({
model,
- ide,
uniqueId,
- ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
- ide: IDE;
uniqueId: string;
- ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
- ideSettings,
llmLogger,
config,
});
@@ -227,9 +218,7 @@ export async function llmsFromModelConfig({
const models = await autodetectModels({
llm: baseLlm,
model,
- ide,
uniqueId,
- ideSettings,
llmLogger,
config,
});
diff --git a/core/config/yaml/models.vitest.ts b/core/config/yaml/models.vitest.ts
new file mode 100644
index 000000000..4b5f33887
--- /dev/null
+++ b/core/config/yaml/models.vitest.ts
@@ -0,0 +1,355 @@
+import { ModelConfig } from "@continuedev/config-yaml";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ContinueConfig, ILLMLogger } from "../..";
+import { llmsFromModelConfig } from "./models";
+
+// Mock the LLM classes
+vi.mock("../../llm/llms", () => ({
+ LLMClasses: [
+ class MockOpenAI {
+ static providerName = "openai";
+ static defaultOptions = {
+ completionOptions: {
+ maxTokens: 2048,
+ },
+ };
+
+ constructor(options: any) {
+ Object.assign(this, options);
+ }
+
+ async listModels() {
+ return ["gpt-4", "gpt-3.5-turbo"];
+ }
+ },
+ class MockAnthropic {
+ static providerName = "anthropic";
+ static defaultOptions = {
+ completionOptions: {
+ maxTokens: 4096,
+ },
+ };
+
+ constructor(options: any) {
+ Object.assign(this, options);
+ }
+
+ async listModels() {
+ return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"];
+ }
+ },
+ ],
+}));
+
+describe("llmsFromModelConfig requestOptions merging", () => {
+ let mockLLMLogger: ILLMLogger;
+ let mockConfig: ContinueConfig;
+
+ beforeEach(() => {
+ mockLLMLogger = { log: vi.fn() } as any;
+ mockConfig = {
+ requestOptions: {
+ timeout: 30000,
+ headers: {
+ "User-Agent": "Continue/1.0.0",
+ },
+ proxy: "global-proxy",
+ },
+ contextProviders: [],
+ mcpServerStatuses: [],
+ rules: [],
+ selectedModelByRole: {
+ apply: null,
+ autocomplete: null,
+ chat: null,
+ edit: null,
+ embed: null,
+ rerank: null,
+ summarize: null,
+ },
+ modelsByRole: {
+ apply: [],
+ autocomplete: [],
+ chat: [],
+ edit: [],
+ embed: [],
+ rerank: [],
+ summarize: [],
+ },
+ slashCommands: [],
+ tools: [],
+ allowAnonymousTelemetry: false,
+ } as ContinueConfig;
+ vi.clearAllMocks();
+ });
+
+ it("should merge model requestOptions with config requestOptions", async () => {
+ const model: ModelConfig = {
+ name: "test-openai",
+ provider: "openai",
+ model: "gpt-4",
+ requestOptions: {
+ timeout: 60000,
+ headers: {
+ Authorization: "Bearer token123",
+ },
+ proxy: "model-proxy",
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: mockConfig,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ // The LLM should have merged requestOptions
+ expect(llm.requestOptions).toEqual({
+ timeout: 60000, // model-specific takes precedence
+ headers: {
+ "User-Agent": "Continue/1.0.0", // from global request options
+ Authorization: "Bearer token123", // from model
+ },
+ proxy: "model-proxy", // model-specific takes precedence
+ });
+ });
+
+ it("should use config requestOptions when model has no requestOptions", async () => {
+ const model: ModelConfig = {
+ name: "test-openai",
+ provider: "openai",
+ model: "gpt-4",
+ // no requestOptions
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: mockConfig,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ // The LLM should have config requestOptions
+ expect(llm.requestOptions).toEqual(mockConfig.requestOptions);
+ });
+
+ it("should use model requestOptions when config has no requestOptions", async () => {
+ const model: ModelConfig = {
+ name: "test-openai",
+ provider: "openai",
+ model: "gpt-4",
+ requestOptions: {
+ timeout: 45000,
+ headers: {
+ "API-Key": "secret",
+ },
+ },
+ };
+
+ const configWithoutOptions = { ...mockConfig };
+ delete configWithoutOptions.requestOptions;
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: configWithoutOptions,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ // The LLM should have model requestOptions
+ expect(llm.requestOptions).toEqual(model.requestOptions);
+ });
+
+ it("should handle empty headers correctly in merge", async () => {
+ const model: ModelConfig = {
+ name: "test-openai",
+ provider: "openai",
+ model: "gpt-4",
+ requestOptions: {
+ timeout: 60000,
+ headers: {},
+ },
+ };
+
+ const configWithEmptyHeaders = {
+ ...mockConfig,
+ requestOptions: {
+ ...mockConfig.requestOptions!,
+ headers: {},
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: configWithEmptyHeaders,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ // When headers merge to empty object, they should be undefined
+ expect(llm.requestOptions).toEqual({
+ timeout: 60000,
+ proxy: "global-proxy",
+ headers: undefined,
+ });
+ });
+
+ it("should handle autodetect models with merged requestOptions", async () => {
+ const model: ModelConfig = {
+ name: "autodetect-openai",
+ provider: "openai",
+ model: "AUTODETECT",
+ requestOptions: {
+ timeout: 120000,
+ headers: {
+ "X-Custom": "autodetect",
+ },
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: mockConfig,
+ });
+
+ // Should return multiple models from listModels()
+ expect(result.length).toBeGreaterThan(0);
+
+ // Each detected model should have the merged requestOptions
+ result.forEach((llm) => {
+ expect(llm.requestOptions).toEqual({
+ timeout: 120000, // model-specific takes precedence
+ headers: {
+ "User-Agent": "Continue/1.0.0", // from global request options
+ "X-Custom": "autodetect", // from model
+ },
+ proxy: "global-proxy", // from global request options
+ });
+ });
+ });
+
+ it("should handle unknown provider gracefully", async () => {
+ const model: ModelConfig = {
+ name: "unknown-provider",
+ provider: "unknown",
+ model: "unknown-model",
+ requestOptions: {
+ timeout: 60000,
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: mockConfig,
+ });
+
+ // Should return empty array for unknown provider
+ expect(result).toHaveLength(0);
+ });
+
+ it("should preserve other model properties while merging requestOptions", async () => {
+ const model: ModelConfig = {
+ name: "test-anthropic",
+ provider: "anthropic",
+ model: "claude-3-5-sonnet-20241022",
+ roles: ["chat", "summarize"],
+ capabilities: ["tool_use", "image_input"],
+ defaultCompletionOptions: {
+ temperature: 0.7,
+ maxTokens: 1000,
+ },
+ requestOptions: {
+ timeout: 90000,
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: mockConfig,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ // Should preserve model properties
+ expect(llm.title).toBe("test-anthropic");
+ expect(llm.completionOptions?.temperature).toBe(0.7);
+ expect(llm.completionOptions?.maxTokens).toBe(1000);
+ expect(llm.capabilities?.tools).toBe(true);
+ expect(llm.capabilities?.uploadImage).toBe(true);
+
+ // Should have merged requestOptions
+ expect(llm.requestOptions).toEqual({
+ timeout: 90000,
+ headers: {
+ "User-Agent": "Continue/1.0.0",
+ },
+ proxy: "global-proxy",
+ });
+ });
+
+ it("should handle complex header merging scenarios", async () => {
+ const model: ModelConfig = {
+ name: "complex-headers",
+ provider: "openai",
+ model: "gpt-4",
+ requestOptions: {
+ headers: {
+ Authorization: "Bearer model-token",
+ Accept: "application/json", // Should override config Accept
+ "X-Model-Specific": "true",
+ },
+ },
+ };
+
+ const configWithMoreHeaders = {
+ ...mockConfig,
+ requestOptions: {
+ ...mockConfig.requestOptions!,
+ headers: {
+ ...mockConfig.requestOptions!.headers,
+ Accept: "text/plain", // Should be overridden by model
+ "Cache-Control": "no-cache",
+ },
+ },
+ };
+
+ const result = await llmsFromModelConfig({
+ model,
+ uniqueId: "test-id",
+ llmLogger: mockLLMLogger,
+ config: configWithMoreHeaders,
+ });
+
+ expect(result).toHaveLength(1);
+ const llm = result[0];
+
+ expect(llm.requestOptions?.headers).toEqual({
+ "User-Agent": "Continue/1.0.0", // from global request options
+ "Cache-Control": "no-cache", // from global request options
+ Authorization: "Bearer model-token", // from model
+ Accept: "application/json", // from model (overrides config)
+ "X-Model-Specific": "true", // from model
+ });
+ });
+});
diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts
index 8d61e06bc..0a4d30dcd 100644
--- a/core/config/yaml/yamlToContinueConfig.ts
+++ b/core/config/yaml/yamlToContinueConfig.ts
@@ -13,8 +13,10 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
+ description: rule.description,
ruleFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
+ invokable: rule.invokable ?? false,
};
}
}
diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts
index 320a3e0e5..a7978b2d2 100644
--- a/core/context/mcp/MCPConnection.ts
+++ b/core/context/mcp/MCPConnection.ts
@@ -52,6 +52,7 @@ class MCPConnection {
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
+ public infos: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
@@ -84,6 +85,7 @@ class MCPConnection {
}
async disconnect() {
+ this.status = "not-connected";
this.abortController.abort();
await this.client.close();
await this.transport.close();
@@ -93,6 +95,7 @@ class MCPConnection {
return {
...this.options,
errors: this.errors,
+ infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@@ -122,6 +125,7 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
+ this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
@@ -280,6 +284,16 @@ class MCPConnection {
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
+ if (["uv", "uvx"].includes(command)) {
+ this.infos.push(
+ 'Please install uv by following the installation guide: https://docs.astral.sh/uv/getting-started/installation/',
+ );
+ }
+ if (["node", "npx"].includes(command)) {
+ this.infos.push(
+ 'Please install npx by following the installation guide: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm',
+ );
+ }
} else {
errorMessage += "Error: " + error.message;
}
diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts
index 3f69d8f23..873805052 100644
--- a/core/context/mcp/MCPConnection.vitest.ts
+++ b/core/context/mcp/MCPConnection.vitest.ts
@@ -142,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
+ infos: [],
isProtectedResource: false,
prompts: [],
resources: [],
diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts
index c9dc41929..9dbfc28b8 100644
--- a/core/context/mcp/MCPManagerSingleton.ts
+++ b/core/context/mcp/MCPManagerSingleton.ts
@@ -13,6 +13,7 @@ export class MCPManagerSingleton {
public onConnectionsRefreshed?: () => void;
public connections: Map = new Map();
+ private disconnectedServers: string[] = [];
private abortController: AbortController = new AbortController();
@@ -25,6 +26,18 @@ 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;
+ }
+
createConnection(id: string, options: MCPOptions): MCPConnection {
if (this.connections.has(id)) {
return this.connections.get(id)!;
@@ -163,9 +176,19 @@ export class MCPManagerSingleton {
}),
(async () => {
await Promise.all(
- Array.from(this.connections.values()).map(async (connection) => {
- await connection.connectClient(force, this.abortController.signal);
- }),
+ 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,
+ );
+ }),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts
index 0b711082f..dc41ddb73 100644
--- a/core/context/mcp/MCPOauth.ts
+++ b/core/context/mcp/MCPOauth.ts
@@ -12,65 +12,121 @@ import { IDE, MCPServerStatus, SSEOptions } from "../..";
import http from "http";
import url from "url";
+import crypto from "crypto";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
-let authenticatingMCPContext = null as {
- authenticatingServer: MCPServerStatus;
- ide: IDE;
-} | null;
+// Use a Map to support concurrent authentications for different servers
+const authenticatingContexts = new Map<
+ string,
+ {
+ authenticatingServer: MCPServerStatus;
+ ide: IDE;
+ state?: string;
+ }
+>();
+
+// Map state parameters to server URLs for OAuth callback matching
+const stateToServerUrl = new Map();
const PORT = 3000;
-const server = http.createServer((req, res) => {
- try {
- if (!req.url) {
- throw new Error("no url found");
- }
+let serverInstance: http.Server | null = null;
- const parsedUrl = url.parse(req.url, true);
- if (!parsedUrl.query["code"]) {
- throw new Error("no query params found");
- }
+const createServerForOAuth = () =>
+ http.createServer((req, res) => {
+ try {
+ if (!req.url) {
+ throw new Error("no url found");
+ }
- void handleMCPOauthCode(parsedUrl.query["code"] as string);
+ const parsedUrl = url.parse(req.url, true);
+ if (!parsedUrl.query["code"]) {
+ throw new Error("no query params found");
+ }
- const html = `
+ const code = parsedUrl.query["code"] as string;
+ const state = parsedUrl.query["state"] as string | undefined;
+
+ void handleMCPOauthCode(code, state);
+
+ const html = `
Authentication Complete
Authentication Complete. You can close this page now.
`;
- res.writeHead(200, {
- "Content-Type": "text/html",
- });
- res.end(html);
- } catch (error) {
- res.writeHead(400, { "Content-Type": "text/plain" });
- res.end(`Unexpected redirect error: ${(error as Error).message}`);
- }
-});
+ res.writeHead(200, {
+ "Content-Type": "text/html",
+ });
+ res.end(html);
+ } catch (error) {
+ res.writeHead(400, { "Content-Type": "text/plain" });
+ res.end(`Unexpected redirect error: ${(error as Error).message}`);
+ }
+ });
type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
type MCPOauthStorageKey = keyof MCPOauthStorage;
class MCPConnectionOauthProvider implements OAuthClientProvider {
private globalContext: GlobalContext;
+ private _redirectUrl: string;
+ private _redirectUrlInitialized: Promise;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
+ // Set default redirect URL immediately for synchronous access
+ this._redirectUrl = `http://localhost:${PORT}`;
+ // Initialize actual redirect URL asynchronously
+ this._redirectUrlInitialized = this._initializeRedirectUrl();
+ }
+
+ private async _initializeRedirectUrl(): Promise {
+ try {
+ // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI
+ if (this.ide.getExternalUri) {
+ const localUri = `http://localhost:${PORT}`;
+ const externalUri = await this.ide.getExternalUri(localUri);
+ this._redirectUrl = externalUri;
+ }
+ // Otherwise keep the default localhost URL
+ } catch (error) {
+ console.error("Failed to initialize redirect URL:", error);
+ // Keep default URL on error
+ }
}
get redirectUrl() {
- return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
+ // Always return a valid URL, even if initialization is pending
+ return this._redirectUrl;
+ }
+
+ getRedirectUrlWithState(state: string): string {
+ // Add state parameter to redirect URL
+ const urlObj = new URL(this._redirectUrl);
+ urlObj.searchParams.set("state", state);
+ return urlObj.toString();
+ }
+
+ async ensureRedirectUrl(): Promise {
+ // Wait for initialization to complete before returning
+ await this._redirectUrlInitialized;
+ return this._redirectUrl;
}
get clientMetadata() {
+ // Generate state parameter if needed
+ const state = authenticatingContexts.get(this.oauthServerUrl)?.state;
+ const redirectUri = state
+ ? this.getRedirectUrlWithState(state)
+ : this.redirectUrl;
+
return {
- redirect_uris: [this.redirectUrl],
+ redirect_uris: [redirectUri],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
@@ -151,14 +207,28 @@ class MCPConnectionOauthProvider implements OAuthClientProvider {
}
async redirectToAuthorization(authorizationUrl: URL) {
- if (!server.listening) {
- server.listen(PORT, () => {
- console.debug(
- `Server started for MCP Oauth process at http://localhost:${PORT}/`,
- );
- });
+ // Ensure redirect URL is initialized before proceeding
+ await this.ensureRedirectUrl();
+
+ // Only create and start local server if using localhost redirect
+ // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism
+ if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) {
+ if (!serverInstance) {
+ serverInstance = createServerForOAuth();
+ }
+ if (!serverInstance.listening) {
+ await new Promise((resolve, reject) => {
+ serverInstance!.listen(PORT, () => {
+ console.debug(
+ `Server started for MCP Oauth process at http://localhost:${PORT}/`,
+ );
+ resolve();
+ });
+ serverInstance!.on("error", reject);
+ });
+ }
}
- void this.ide.openUrl(authorizationUrl.toString());
+ await this.ide.openUrl(authorizationUrl.toString());
}
}
@@ -175,49 +245,109 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
- authenticatingMCPContext = {
+ // Ensure redirect URL is ready before starting auth
+ await authProvider.ensureRedirectUrl();
+
+ // Generate a unique state parameter for this auth flow
+ const state = crypto.randomUUID();
+
+ // Store context for this specific server with state
+ authenticatingContexts.set(mcpServerUrl, {
authenticatingServer: mcpServer,
ide,
- };
- return await auth(authProvider, {
- serverUrl: mcpServerUrl,
+ state,
});
+
+ // Map state to server URL for callback matching
+ stateToServerUrl.set(state, mcpServerUrl);
+
+ try {
+ return await auth(authProvider, {
+ serverUrl: mcpServerUrl,
+ });
+ } catch (error) {
+ // Clean up on error
+ authenticatingContexts.delete(mcpServerUrl);
+ stateToServerUrl.delete(state);
+ throw error;
+ }
}
/**
* handle the authentication code received from the oauth redirect
*/
-async function handleMCPOauthCode(authorizationCode: string) {
- if (!authenticatingMCPContext) {
- return;
- }
- const { ide, authenticatingServer } = authenticatingMCPContext;
- const serverUrl = (authenticatingServer.transport as SSEOptions).url;
+async function handleMCPOauthCode(authorizationCode: string, state?: string) {
+ let serverUrl: string | undefined;
+ let context:
+ | { authenticatingServer: MCPServerStatus; ide: IDE; state?: string }
+ | undefined;
- if (!serverUrl) {
- void ide.showToast("error", "No MCP server url found for authentication");
+ if (state) {
+ // Use state parameter to find the correct server
+ serverUrl = stateToServerUrl.get(state);
+ if (serverUrl) {
+ context = authenticatingContexts.get(serverUrl);
+ }
+ } else {
+ // Fallback: if no state or single context, use the first one
+ const contexts = Array.from(authenticatingContexts.entries());
+ if (contexts.length === 1) {
+ [serverUrl, context] = contexts[0];
+ }
+ }
+
+ if (!context || !serverUrl) {
+ console.error("No matching authenticating context found for state:", state);
return;
}
- if (!authorizationCode) {
- void ide.showToast(
- "error",
- `No MCP authorization code found for ${serverUrl}`,
- );
- return;
+
+ const { ide, authenticatingServer } = context;
+
+ try {
+ if (!serverUrl) {
+ throw new Error("No MCP server url found for authentication");
+ }
+ if (!authorizationCode) {
+ throw new Error(`No MCP authorization code found for ${serverUrl}`);
+ }
+
+ // Close the server before processing auth
+ if (serverInstance) {
+ await new Promise((resolve) => {
+ serverInstance!.close(() => {
+ console.debug("Server for MCP Oauth process was closed");
+ serverInstance = null;
+ resolve();
+ });
+ });
+ }
+
+ const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
+ await authProvider.ensureRedirectUrl();
+ const authStatus = await auth(authProvider, {
+ serverUrl,
+ authorizationCode,
+ });
+
+ if (authStatus === "AUTHORIZED") {
+ const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
+ await MCPManagerSingleton.getInstance().refreshConnection(
+ authenticatingServer.id,
+ );
+ }
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ console.error("OAuth authorization failed:", errorMessage);
+ if (context?.ide) {
+ await context.ide.showToast("error", `OAuth failed: ${errorMessage}`);
+ }
+ } finally {
+ // Always clean up the context and state mapping
+ authenticatingContexts.delete(serverUrl);
+ if (state) {
+ stateToServerUrl.delete(state);
+ }
}
- server.close(() => console.debug("Server for MCP Oauth process was closed"));
- const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
- const authStatus = await auth(authProvider, {
- serverUrl,
- authorizationCode,
- });
- if (authStatus === "AUTHORIZED") {
- const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
- await MCPManagerSingleton.getInstance().refreshConnection(
- authenticatingServer.id,
- );
- }
- authenticatingMCPContext = null;
}
export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
diff --git a/core/context/mcp/MCPOauth.vitest.ts b/core/context/mcp/MCPOauth.vitest.ts
index 44deff10b..44539eb54 100644
--- a/core/context/mcp/MCPOauth.vitest.ts
+++ b/core/context/mcp/MCPOauth.vitest.ts
@@ -33,6 +33,7 @@ describe("MCPOauth", () => {
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
+ getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
};
mockMcpServer = {
@@ -178,4 +179,155 @@ describe("MCPOauth", () => {
});
});
});
+
+ describe("redirect URL handling", () => {
+ test("should use getExternalUri when available for VS Code", async () => {
+ const vscodeIde = {
+ ...mockIde,
+ getExternalUri: vi.fn((uri) =>
+ Promise.resolve("https://vscode.dev/redirect"),
+ ),
+ };
+
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+ mockAuth.mockResolvedValue("AUTHORIZED");
+
+ await performAuth(mockMcpServer, vscodeIde);
+
+ expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
+ "http://localhost:3000",
+ );
+ });
+
+ test("should fallback to localhost when getExternalUri is not available", async () => {
+ const ideWithoutExternalUri = {
+ openUrl: vi.fn(() => Promise.resolve()),
+ showToast: vi.fn(() => Promise.resolve()),
+ };
+
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+ mockAuth.mockResolvedValue("AUTHORIZED");
+
+ await performAuth(mockMcpServer, ideWithoutExternalUri as any);
+
+ // Should still work without getExternalUri
+ expect(mockAuth).toHaveBeenCalled();
+ });
+
+ test("should handle getExternalUri errors gracefully", async () => {
+ const errorIde = {
+ ...mockIde,
+ getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
+ };
+
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+ mockAuth.mockResolvedValue("AUTHORIZED");
+
+ // Should not throw, should fallback to localhost
+ await performAuth(mockMcpServer, errorIde);
+
+ expect(mockAuth).toHaveBeenCalled();
+ });
+ });
+
+ describe("concurrent authentication", () => {
+ test("should handle multiple concurrent auth flows", async () => {
+ const server1 = {
+ id: "server-1",
+ transport: { type: "sse" as const, url: "https://server1.com" },
+ status: "connected" as const,
+ errors: [],
+ infos: [],
+ isProtectedResource: false,
+ prompts: [],
+ tools: [],
+ resources: [],
+ resourceTemplates: [],
+ name: "server-1",
+ };
+ const server2 = {
+ id: "server-2",
+ transport: { type: "sse" as const, url: "https://server2.com" },
+ status: "connected" as const,
+ errors: [],
+ infos: [],
+ isProtectedResource: false,
+ prompts: [],
+ tools: [],
+ resources: [],
+ resourceTemplates: [],
+ name: "server-2",
+ };
+
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+ mockAuth.mockResolvedValue("AUTHORIZED");
+
+ // Start two auth flows concurrently
+ const [result1, result2] = await Promise.all([
+ performAuth(server1, mockIde),
+ performAuth(server2, mockIde),
+ ]);
+
+ expect(result1).toBe("AUTHORIZED");
+ expect(result2).toBe("AUTHORIZED");
+ expect(mockAuth).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ describe("error handling", () => {
+ test("should clean up context on auth failure", async () => {
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+
+ // First successful call to set up the context
+ mockAuth.mockResolvedValueOnce("AUTHORIZED");
+ await performAuth(mockMcpServer, mockIde);
+
+ // Reset mock for the failure test
+ mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
+
+ // Second call that should fail and clean up
+ await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow(
+ "Auth failed",
+ );
+
+ // Verify auth was called twice
+ expect(mockAuth).toHaveBeenCalledTimes(2);
+
+ // The context cleanup happens internally in performAuth's catch block
+ // We can verify it indirectly by checking that a subsequent auth call works
+ mockAuth.mockResolvedValueOnce("AUTHORIZED");
+ const result = await performAuth(mockMcpServer, mockIde);
+ expect(result).toBe("AUTHORIZED");
+ });
+
+ test("should handle missing server URL", async () => {
+ const invalidServer = {
+ id: "invalid",
+ transport: { type: "sse" as const, url: "" },
+ status: "connected" as const,
+ errors: [],
+ infos: [],
+ isProtectedResource: false,
+ prompts: [],
+ tools: [],
+ resources: [],
+ resourceTemplates: [],
+ name: "invalid",
+ };
+
+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
+ const mockAuth = vi.mocked(auth);
+ mockAuth.mockResolvedValue("AUTHORIZED");
+
+ await performAuth(invalidServer, mockIde);
+
+ // Should still attempt auth with empty URL
+ expect(mockAuth).toHaveBeenCalled();
+ });
+ });
});
diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts
index a8607386f..0a0650804 100644
--- a/core/control-plane/client.ts
+++ b/core/control-plane/client.ts
@@ -11,10 +11,19 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
-import { IDE, ModelDescription } from "../index.js";
+import {
+ IDE,
+ ModelDescription,
+ Session,
+ BaseSessionMetadata,
+} from "../index.js";
import { Logger } from "../util/Logger.js";
-import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
+import {
+ ControlPlaneSessionInfo,
+ HubSessionInfo,
+ isOnPremSession,
+} from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface PolicyResponse {
@@ -41,6 +50,11 @@ export interface FreeTrialStatus {
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
+export interface RemoteSessionMetadata extends BaseSessionMetadata {
+ isRemote: true;
+ remoteId: string;
+}
+
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise,
@@ -303,4 +317,127 @@ export class ControlPlaneClient {
return null;
}
}
+
+ /**
+ * Check if remote sessions should be enabled based on feature flags
+ * Requires: PostHog feature flag AND @continue.dev email
+ */
+ public async shouldEnableRemoteSessions(): Promise {
+ // Check if user is signed in
+ if (!(await this.isSignedIn())) {
+ return false;
+ }
+
+ // Check if user has @continue.dev email
+ try {
+ const sessionInfo = await this.sessionInfoPromise;
+ if (isOnPremSession(sessionInfo) || !sessionInfo) {
+ return false;
+ }
+
+ const hubSession = sessionInfo as HubSessionInfo;
+ const email = hubSession.account?.id;
+
+ return email ? email.includes("@continue.dev") : false;
+ } catch (e) {
+ Logger.error(e, {
+ context: "control_plane_check_remote_sessions_enabled",
+ });
+ return false;
+ }
+ }
+
+ /**
+ * Get current user's session info
+ */
+ public async getSessionInfo(): Promise {
+ return await this.sessionInfoPromise;
+ }
+
+ /**
+ * Fetch remote agents/sessions from the control plane
+ * Currently restricted to @continue.dev emails for internal use
+ */
+ public async listRemoteSessions(): Promise {
+ if (!(await this.isSignedIn())) {
+ return [];
+ }
+
+ try {
+ // Note: This endpoint is currently restricted to internal @continue.dev users
+ // In the future, this may be expanded to support broader remote session access
+ const resp = await this.requestAndHandleError("agents/devboxes", {
+ method: "GET",
+ });
+
+ const agents = (await resp.json()) as any[];
+
+ return agents.map(
+ (agent: any): RemoteSessionMetadata => ({
+ sessionId: `remote-${agent.id}`,
+ title: agent.name || "Remote Agent",
+ dateCreated: new Date(agent.create_time_ms).toISOString(),
+ workspaceDirectory: "",
+ isRemote: true,
+ remoteId: agent.id,
+ }),
+ );
+ } catch (e) {
+ // Log error but don't throw - remote sessions are optional
+ Logger.error(e, {
+ context: "control_plane_list_remote_sessions",
+ });
+ return [];
+ }
+ }
+
+ public async loadRemoteSession(remoteId: string): Promise {
+ if (!(await this.isSignedIn())) {
+ throw new Error("Not signed in to load remote session");
+ }
+
+ try {
+ // First get the tunnel URL for the remote agent
+ const tunnelResp = await this.requestAndHandleError(
+ `agents/devboxes/${remoteId}/tunnel`,
+ {
+ method: "POST",
+ },
+ );
+
+ const tunnelData = (await tunnelResp.json()) as { url?: string };
+ const tunnelUrl = tunnelData.url;
+
+ if (!tunnelUrl) {
+ throw new Error(`Failed to get tunnel URL for agent ${remoteId}`);
+ }
+
+ // Now fetch the session state from the remote agent's /state endpoint
+ const stateResponse = await fetch(`${tunnelUrl}/state`);
+ if (!stateResponse.ok) {
+ throw new Error(
+ `Failed to fetch state from remote agent: ${stateResponse.statusText}`,
+ );
+ }
+
+ const remoteState = (await stateResponse.json()) as { session?: Session };
+
+ // The remote state contains a session property with the full session data
+ if (!remoteState.session) {
+ throw new Error(
+ "Remote agent returned invalid state - no session found",
+ );
+ }
+
+ return remoteState.session;
+ } catch (e) {
+ Logger.error(e, {
+ context: "control_plane_load_remote_session",
+ remoteId,
+ });
+ throw new Error(
+ `Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`,
+ );
+ }
+ }
}
diff --git a/core/core.ts b/core/core.ts
index 7bf77a389..4e7772bc5 100644
--- a/core/core.ts
+++ b/core/core.ts
@@ -17,6 +17,7 @@ import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
+import Lemonade from "./llm/llms/Lemonade";
import Ollama from "./llm/llms/Ollama";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
@@ -29,8 +30,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
+ killTerminalProcess,
markProcessAsBackgrounded,
-} from "./util/processTerminalBackgroundStates";
+} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@@ -76,6 +78,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 { shareSession } from "./util/historyUtils";
import { Logger } from "./util/Logger.js";
import { getUriPathBasename } from "./util/uri";
@@ -230,6 +233,17 @@ export class Core {
return;
}
+ // Check for disableIndexing to prevent race condition
+ const { config } = await this.configHandler.loadConfig();
+ if (!config || config.disableIndexing) {
+ void this.messenger.request("indexProgress", {
+ progress: 0,
+ desc: "Indexing is disabled",
+ status: "disabled",
+ });
+ return;
+ }
+
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@@ -312,8 +326,27 @@ export class Core {
});
// History
- on("history/list", (msg) => {
- return historyManager.list(msg.data);
+ on("history/list", async (msg) => {
+ const localSessions = historyManager.list(msg.data);
+
+ // Check if remote sessions should be enabled based on feature flags
+ const shouldFetchRemote =
+ await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
+
+ // Get remote sessions from control plane if feature is enabled
+ const remoteSessions = shouldFetchRemote
+ ? await this.configHandler.controlPlaneClient.listRemoteSessions()
+ : [];
+
+ // Combine and sort by date (most recent first)
+ const allSessions = [...localSessions, ...remoteSessions].sort(
+ (a, b) =>
+ new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
+ );
+
+ // Apply limit if specified
+ const limit = msg.data?.limit ?? 100;
+ return allSessions.slice(0, limit);
});
on("history/delete", (msg) => {
@@ -324,10 +357,23 @@ export class Core {
return historyManager.load(msg.data.id);
});
+ on("history/loadRemote", async (msg) => {
+ return this.configHandler.controlPlaneClient.loadRemoteSession(
+ msg.data.remoteId,
+ );
+ });
+
on("history/save", (msg) => {
historyManager.save(msg.data);
});
+ on("history/share", async (msg) => {
+ const session = historyManager.load(msg.data.id);
+ const outputDir = msg.data.outputDir;
+ const history = session.history.map((msg) => msg.message);
+ await shareSession(this.ide, history, outputDir);
+ });
+
on("history/clear", (msg) => {
historyManager.clearAll();
});
@@ -446,6 +492,20 @@ 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/getPrompt", async (msg) => {
const { serverName, promptName, args } = msg.data;
@@ -727,20 +787,13 @@ export class Core {
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
- return streamDiffLines({
- highlighted: data.highlighted,
- prefix: data.prefix,
- suffix: data.suffix,
+ return streamDiffLines(
+ data,
llm,
- // rules included for edit, NOT apply
- rulesToInclude: data.includeRulesInSystemMessage
- ? config.rules
- : undefined,
- input: data.input,
- language: data.language,
- overridePrompt: undefined,
abortController,
- });
+ undefined,
+ data.includeRulesInSystemMessage ? config.rules : undefined,
+ );
});
on("cancelApply", async (msg) => {
@@ -1061,6 +1114,10 @@ export class Core {
},
);
+ on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
+ await killTerminalProcess(toolCallId);
+ });
+
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
@@ -1195,6 +1252,9 @@ export class Core {
if (
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
+ uri.endsWith("AGENTS.md") ||
+ uri.endsWith("AGENT.md") ||
+ uri.endsWith("CLAUDE.md") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") &&
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
@@ -1257,6 +1317,9 @@ export class Core {
if (msg.data.title === "Ollama") {
const models = await new Ollama({ model: "" }).listModels();
return models;
+ } else if (msg.data.title === "Lemonade") {
+ const models = await new Lemonade({ model: "" }).listModels();
+ return models;
} else {
return undefined;
}
@@ -1342,6 +1405,8 @@ export class Core {
selectedCode,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
+ // Important note: context providers fetch uses global request options not LLM request options
+ // Because LLM calls are handled separately
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});
diff --git a/core/edit/constants.ts b/core/edit/constants.ts
index ecc3340ca..0fcc4853e 100644
--- a/core/edit/constants.ts
+++ b/core/edit/constants.ts
@@ -1 +1,3 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";
+
+export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";
diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts
index a835fe357..5c9f2fef6 100644
--- a/core/edit/recursiveStream.ts
+++ b/core/edit/recursiveStream.ts
@@ -1,7 +1,14 @@
-import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
+import {
+ ChatMessage,
+ ILLM,
+ Prediction,
+ PromptLog,
+ type StreamDiffLinesType,
+} from "..";
import { DEFAULT_MAX_TOKENS } from "../llm/constants";
import { countTokens } from "../llm/countTokens";
import { renderChatMessage } from "../util/messageContent";
+import { APPLY_UNIQUE_TOKEN } from "./constants.js";
const INFINITE_STREAM_SAFETY = 0.9;
@@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
+ type: StreamDiffLinesType,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@@ -28,8 +36,11 @@ export async function* recursiveStream(
let buffer = currentBuffer;
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
+ const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm);
if (typeof prompt === "string") {
- const generator = llm.streamComplete(prompt, abortController.signal, {
+ const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt;
+
+ const generator = llm.streamComplete(finalPrompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@@ -62,7 +73,11 @@ export async function* recursiveStream(
}
}
} else {
- const generator = llm.streamChat(prompt, abortController.signal, {
+ const promptMessages = injectApplyToken
+ ? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN)
+ : prompt;
+
+ const generator = llm.streamChat(promptMessages, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@@ -104,3 +119,36 @@ export async function* recursiveStream(
}
}
}
+
+function shouldInjectApplyToken(llm: ILLM): boolean {
+ const model = llm.model?.toLowerCase() ?? "";
+ return (
+ llm.underlyingProviderName === "inception" && model.includes("mercury")
+ );
+}
+
+function appendTokenToLastMessage(
+ messages: ChatMessage[],
+ token: string,
+): ChatMessage[] {
+ if (messages.length === 0) {
+ return messages;
+ }
+
+ const lastMessage = messages[messages.length - 1];
+ if (typeof lastMessage.content !== "string") {
+ return messages;
+ }
+
+ if (lastMessage.content.endsWith(token)) {
+ return messages;
+ }
+
+ const updatedMessages = [...messages];
+ updatedMessages[updatedMessages.length - 1] = {
+ ...lastMessage,
+ content: lastMessage.content + token,
+ };
+
+ return updatedMessages;
+}
diff --git a/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts b/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts
new file mode 100644
index 000000000..9ae1857b6
--- /dev/null
+++ b/core/edit/searchAndReplace/executeFindAndReplace.vitest.ts
@@ -0,0 +1,252 @@
+import { describe, expect, it } from "vitest";
+import { ContinueErrorReason } from "../../util/errors";
+import { executeFindAndReplace } from "./performReplace";
+
+describe("executeFindAndReplace", () => {
+ describe("normal cases", () => {
+ it("should replace single occurrence by default", () => {
+ const content = "Hello world\nThis is a test file\nGoodbye";
+ const result = executeFindAndReplace(content, "Hello", "Hi", false);
+
+ expect(result).toBe("Hi world\nThis is a test file\nGoodbye");
+ });
+
+ it("should replace single occurrence when replaceAll is false", () => {
+ const content = "Hello world\nHello again";
+ const result = executeFindAndReplace(
+ content,
+ "Hello world",
+ "Hi world",
+ false,
+ );
+
+ expect(result).toBe("Hi world\nHello again");
+ });
+
+ it("should replace all occurrences when replaceAll is true", () => {
+ const content = "Hello world\nHello again\nHello there";
+ const result = executeFindAndReplace(content, "Hello", "Hi", true);
+
+ expect(result).toBe("Hi world\nHi again\nHi there");
+ });
+
+ it("should handle empty new string (deletion)", () => {
+ const content = "Hello world";
+ const result = executeFindAndReplace(content, "Hello ", "", false);
+
+ expect(result).toBe("world");
+ });
+
+ it("should handle empty old string replacement (insertion at start)", () => {
+ const content = "";
+ const result = executeFindAndReplace(content, "", "Hello world", false);
+
+ expect(result).toBe("Hello world");
+ });
+
+ it("should preserve whitespace and indentation", () => {
+ const content =
+ "function test() {\n const value = 'old';\n return value;\n}";
+ const result = executeFindAndReplace(
+ content,
+ " const value = 'old';",
+ " const value = 'new';",
+ false,
+ );
+
+ expect(result).toBe(
+ "function test() {\n const value = 'new';\n return value;\n}",
+ );
+ });
+
+ it("should handle multiline strings", () => {
+ const content = "line1\nline2\nline3";
+ const result = executeFindAndReplace(
+ content,
+ "line1\nline2",
+ "newline1\nnewline2",
+ false,
+ );
+
+ expect(result).toBe("newline1\nnewline2\nline3");
+ });
+ });
+
+ describe("special character handling", () => {
+ it("should handle regex special characters in old string", () => {
+ const content = "const regex = /[a-z]+/g;";
+ const result = executeFindAndReplace(
+ content,
+ "/[a-z]+/g",
+ "/[A-Z]+/g",
+ false,
+ );
+
+ expect(result).toBe("const regex = /[A-Z]+/g;");
+ });
+
+ it("should handle dollar signs in strings", () => {
+ const content = 'const text = "Hello $world"';
+ const result = executeFindAndReplace(
+ content,
+ '"Hello $world"',
+ '"Hi $universe"',
+ false,
+ );
+
+ expect(result).toBe('const text = "Hi $universe"');
+ });
+
+ it("should handle backslashes", () => {
+ const content = 'const path = "C:\\Users\\test"';
+ const result = executeFindAndReplace(
+ content,
+ "C:\\Users\\test",
+ "D:\\Users\\test",
+ false,
+ );
+
+ expect(result).toBe('const path = "D:\\Users\\test"');
+ });
+
+ it("should handle parentheses", () => {
+ const content = "function test() { return 'old'; }";
+ const result = executeFindAndReplace(
+ content,
+ "() { return 'old'; }",
+ "() { return 'new'; }",
+ false,
+ );
+
+ expect(result).toBe("function test() { return 'new'; }");
+ });
+
+ it("should handle square brackets", () => {
+ const content = "const arr = [1, 2, 3];";
+ const result = executeFindAndReplace(
+ content,
+ "[1, 2, 3]",
+ "[4, 5, 6]",
+ false,
+ );
+
+ expect(result).toBe("const arr = [4, 5, 6];");
+ });
+ });
+
+ describe("replaceAll behavior", () => {
+ it("should replace all occurrences including partial matches", () => {
+ const content = "test testing tested test";
+ const result = executeFindAndReplace(content, "test", "exam", true);
+
+ expect(result).toBe("exam examing examed exam");
+ });
+
+ it("should replace all occurrences with empty string", () => {
+ const content = "remove this remove that remove everything";
+ const result = executeFindAndReplace(content, "remove ", "", true);
+
+ expect(result).toBe("this that everything");
+ });
+
+ it("should handle overlapping patterns correctly", () => {
+ const content = "aaaa";
+ const result = executeFindAndReplace(content, "aa", "b", true);
+
+ expect(result).toBe("bb");
+ });
+ });
+
+ describe("error cases", () => {
+ it("should throw error when string not found", () => {
+ const content = "Hello world";
+
+ expect(() => {
+ executeFindAndReplace(content, "xyz", "abc", false);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
+ }),
+ );
+ });
+
+ it("should throw error with edit context when string not found", () => {
+ const content = "Hello world";
+
+ expect(() => {
+ executeFindAndReplace(content, "xyz", "abc", false, 2);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
+ }),
+ );
+ });
+
+ it("should throw error when multiple occurrences exist and replaceAll is false", () => {
+ const content = "Hello world\nHello again\nHello there";
+
+ expect(() => {
+ executeFindAndReplace(content, "Hello", "Hi", false);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
+ }),
+ );
+ });
+
+ it("should throw error with edit context for multiple occurrences", () => {
+ const content = "test test test";
+
+ expect(() => {
+ executeFindAndReplace(content, "test", "exam", false, 1);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
+ }),
+ );
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle single character replacement", () => {
+ const content = "a b c";
+ const result = executeFindAndReplace(content, "b", "x", false);
+
+ expect(result).toBe("a x c");
+ });
+
+ it("should handle very long strings", () => {
+ const longString = "a".repeat(10000);
+ const content = `start${longString}end`;
+ const result = executeFindAndReplace(content, longString, "short", false);
+
+ expect(result).toBe("startshortend");
+ });
+
+ it("should handle strings at beginning of content", () => {
+ const content = "start middle end";
+ const result = executeFindAndReplace(content, "start", "begin", false);
+
+ expect(result).toBe("begin middle end");
+ });
+
+ it("should handle strings at end of content", () => {
+ const content = "start middle end";
+ const result = executeFindAndReplace(content, "end", "finish", false);
+
+ expect(result).toBe("start middle finish");
+ });
+
+ it("should handle entire content replacement", () => {
+ const content = "replace everything";
+ const result = executeFindAndReplace(
+ content,
+ "replace everything",
+ "new content",
+ false,
+ );
+
+ expect(result).toBe("new content");
+ });
+ });
+});
diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.ts b/core/edit/searchAndReplace/findAndReplaceUtils.ts
new file mode 100644
index 000000000..b85dcdfb9
--- /dev/null
+++ b/core/edit/searchAndReplace/findAndReplaceUtils.ts
@@ -0,0 +1,53 @@
+import { ContinueError, ContinueErrorReason } from "../../util/errors";
+
+export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
+ "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
+
+/**
+ * Validates a single edit operation
+ */
+export function validateSingleEdit(
+ oldString: string,
+ newString: string,
+ index?: number,
+): void {
+ const context = index !== undefined ? `edit at index ${index}: ` : "";
+
+ if (!oldString && oldString !== "") {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceMissingOldString,
+ `${context}old_string is required`,
+ );
+ }
+ if (newString === undefined) {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceMissingNewString,
+ `${context}new_string is required`,
+ );
+ }
+ if (oldString === newString) {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ `${context}old_string and new_string must be different`,
+ );
+ }
+}
+
+export function trimEmptyLines({
+ lines,
+ fromEnd,
+}: {
+ lines: string[];
+ fromEnd: boolean;
+}): string[] {
+ lines = fromEnd ? lines.slice().reverse() : lines.slice();
+ const newLines: string[] = [];
+ let shouldContinueRemoving = true;
+ for (let index = 0; index < lines.length; index++) {
+ const line = lines[index];
+ if (shouldContinueRemoving && line.trim() === "") continue;
+ shouldContinueRemoving = false;
+ newLines.push(line);
+ }
+ return fromEnd ? newLines.reverse() : newLines;
+}
diff --git a/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts
new file mode 100644
index 000000000..b08413a9d
--- /dev/null
+++ b/core/edit/searchAndReplace/findAndReplaceUtils.vitest.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from "vitest";
+import { ContinueErrorReason } from "../../util/errors";
+import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils";
+
+describe("validateSingleEdit", () => {
+ describe("valid inputs", () => {
+ it("should not throw for valid non-empty strings", () => {
+ expect(() => {
+ validateSingleEdit("old", "new");
+ }).not.toThrow();
+ });
+
+ it("should allow empty old_string for file creation", () => {
+ expect(() => {
+ validateSingleEdit("", "new content");
+ }).not.toThrow();
+ });
+
+ it("should allow empty new_string for deletion", () => {
+ expect(() => {
+ validateSingleEdit("delete me", "");
+ }).not.toThrow();
+ });
+
+ it("should allow multiline strings", () => {
+ expect(() => {
+ validateSingleEdit("line1\nline2", "newline1\nnewline2");
+ }).not.toThrow();
+ });
+
+ it("should allow special characters", () => {
+ expect(() => {
+ validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
+ }).not.toThrow();
+ });
+ });
+
+ describe("invalid inputs", () => {
+ it("should throw error when old_string is null", () => {
+ expect(() => {
+ validateSingleEdit(null as any, "new");
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingOldString,
+ }),
+ );
+ });
+
+ it("should throw error when old_string is undefined", () => {
+ expect(() => {
+ validateSingleEdit(undefined as any, "new");
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingOldString,
+ }),
+ );
+ });
+
+ it("should throw error when new_string is undefined", () => {
+ expect(() => {
+ validateSingleEdit("old", undefined as any);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingNewString,
+ }),
+ );
+ });
+
+ it("should throw error when old_string and new_string are identical", () => {
+ expect(() => {
+ validateSingleEdit("same", "same");
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ }),
+ );
+ });
+
+ it("should throw error when both are empty strings", () => {
+ expect(() => {
+ validateSingleEdit("", "");
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ }),
+ );
+ });
+ });
+
+ describe("error messages with context", () => {
+ it("should include edit number in error messages when index provided", () => {
+ expect(() => {
+ validateSingleEdit(null as any, "new", 2);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingOldString,
+ }),
+ );
+ });
+
+ it("should include edit number for new_string errors", () => {
+ expect(() => {
+ validateSingleEdit("old", undefined as any, 0);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingNewString,
+ }),
+ );
+ });
+
+ it("should include edit number for identical strings error", () => {
+ expect(() => {
+ validateSingleEdit("same", "same", 4);
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ }),
+ );
+ });
+
+ it("should not include context when index not provided", () => {
+ expect(() => {
+ validateSingleEdit("same", "same");
+ }).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ }),
+ );
+ });
+ });
+});
+
+describe("trimEmptyLines", () => {
+ it("trims leading empty lines from start", () => {
+ const input = ["", "", "a", "", "b"];
+ const result = trimEmptyLines({ lines: input, fromEnd: false });
+ expect(result).toEqual(["a", "", "b"]);
+ });
+
+ it("trims trailing empty lines from end", () => {
+ const input = ["a", "", "b", "", ""];
+ const result = trimEmptyLines({ lines: input, fromEnd: true });
+ expect(result).toEqual(["a", "", "b"]);
+ });
+
+ it("returns empty array when all lines are empty", () => {
+ const input = ["", "", ""];
+ const result = trimEmptyLines({ lines: input, fromEnd: false });
+ expect(result).toEqual([]);
+ });
+});
diff --git a/extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts b/core/edit/searchAndReplace/findSearchMatch.ts
similarity index 75%
rename from extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts
rename to core/edit/searchAndReplace/findSearchMatch.ts
index 9597d5070..9093bc27b 100644
--- a/extensions/cli/src/tools/searchAndReplace/findSearchMatch.ts
+++ b/core/edit/searchAndReplace/findSearchMatch.ts
@@ -4,7 +4,7 @@
interface BasicMatchResult {
/** The starting character index of the match in the file content */
startIndex: number;
- /** The ending character index of the match in the file content */
+ /** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/
endIndex: number;
}
@@ -81,32 +81,38 @@ function whitespaceIgnoredMatch(
}
// Map the stripped position back to the original file content
- let originalStartIndex = 0;
+ let originalStartIndex = -1;
let strippedCharCount = 0;
- // Find the original position by counting non-whitespace characters
+ // Find the original start position by counting non-whitespace characters
for (let i = 0; i < fileContent.length; i++) {
- if (strippedCharCount === strippedIndex) {
- originalStartIndex = i;
- break;
- }
if (!/\s/.test(fileContent[i])) {
+ if (strippedCharCount === strippedIndex) {
+ originalStartIndex = i;
+ break;
+ }
strippedCharCount++;
}
}
- // Find the end position by counting the length of the search content
- let originalEndIndex = originalStartIndex;
- let matchedChars = 0;
+ if (originalStartIndex === -1) {
+ return null; // Should not happen if strippedIndex was valid
+ }
- for (
- let i = originalStartIndex;
- i < fileContent.length && matchedChars < strippedSearchContent.length;
- i++
- ) {
+ // Find the end position by counting through all characters (including whitespace)
+ // that correspond to the stripped search content length
+ let originalEndIndex = originalStartIndex;
+ let matchedNonWhitespaceChars = 0;
+
+ for (let i = originalStartIndex; i < fileContent.length; i++) {
if (!/\s/.test(fileContent[i])) {
- matchedChars++;
+ matchedNonWhitespaceChars++;
+ if (matchedNonWhitespaceChars === strippedSearchContent.length) {
+ originalEndIndex = i + 1;
+ break;
+ }
}
+ // Always update end index to include current position (whether whitespace or not)
originalEndIndex = i + 1;
}
@@ -118,6 +124,7 @@ function whitespaceIgnoredMatch(
/**
* Calculate the Jaro similarity between two strings
+ * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
@@ -278,7 +285,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
- { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
+ // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
];
/**
@@ -315,3 +322,58 @@ export function findSearchMatch(
return null;
}
+
+/**
+ * Find all matches for search content in file content.
+ * Uses the same matching strategies as findSearchMatch, applied iteratively.
+ *
+ * @param fileContent - The complete content of the file to search in
+ * @param searchContent - The content to search for
+ * @returns Array of match results with character positions, empty array if no matches found
+ */
+export function findSearchMatches(
+ fileContent: string,
+ searchContent: string,
+): SearchMatchResult[] {
+ const matches: SearchMatchResult[] = [];
+
+ // Special case: empty search string always matches at position 0
+ if (searchContent.trim() === "") {
+ return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }];
+ }
+
+ let remainingContent = fileContent;
+ let currentOffset = 0;
+
+ while (remainingContent.length > 0) {
+ const match = findSearchMatch(remainingContent, searchContent);
+
+ if (match === null) {
+ break;
+ }
+
+ // Adjust match positions to account for the current offset
+ const adjustedMatch: SearchMatchResult = {
+ startIndex: match.startIndex + currentOffset,
+ endIndex: match.endIndex + currentOffset,
+ strategyName: match.strategyName,
+ };
+
+ // Prevent infinite loops by ensuring we're making progress
+ // If the new match starts at or before the last match's start position, break
+ if (
+ matches.length > 0 &&
+ adjustedMatch.startIndex <= matches[matches.length - 1].startIndex
+ ) {
+ break;
+ }
+
+ matches.push(adjustedMatch);
+
+ // Update offset and truncate content after the current match
+ currentOffset = adjustedMatch.endIndex;
+ remainingContent = fileContent.slice(currentOffset);
+ }
+
+ return matches;
+}
diff --git a/core/edit/searchAndReplace/findSearchMatch.vitest.ts b/core/edit/searchAndReplace/findSearchMatch.vitest.ts
new file mode 100644
index 000000000..54c2f5128
--- /dev/null
+++ b/core/edit/searchAndReplace/findSearchMatch.vitest.ts
@@ -0,0 +1,571 @@
+import { describe, expect, it } from "vitest";
+import { findSearchMatch } from "./findSearchMatch";
+
+describe("findSearchMatch", () => {
+ describe("Empty search content", () => {
+ it("should return position 0 for empty string", () => {
+ const result = findSearchMatch("some file content", "");
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+
+ it("should return position 0 for whitespace-only string", () => {
+ const result = findSearchMatch("some file content", " \n\t ");
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+
+ it("should handle empty file content with empty search", () => {
+ const result = findSearchMatch("", "");
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+ });
+
+ describe("Exact match strategy", () => {
+ it("should find exact match at beginning of file", () => {
+ const fileContent = "hello world";
+ const searchContent = "hello";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 5,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find exact match in middle of file", () => {
+ const fileContent = "hello world test";
+ const searchContent = "world";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 6,
+ endIndex: 11,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find exact match at end of file", () => {
+ const fileContent = "hello world";
+ const searchContent = "world";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 6,
+ endIndex: 11,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find multi-line exact match", () => {
+ const fileContent = "line1\nline2\nline3";
+ const searchContent = "line2\nline3";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 6,
+ endIndex: 17,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle exact match with special characters", () => {
+ const fileContent = 'function test() { return "hello"; }';
+ const searchContent = '{ return "hello"; }';
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 16,
+ endIndex: 35,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find first occurrence when multiple matches exist", () => {
+ const fileContent = "test test test";
+ const searchContent = "test";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 4,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle case-sensitive matching", () => {
+ const fileContent = "Hello World";
+ const searchContent = "hello";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ // Should not match due to case sensitivity, will fall through to other strategies
+ expect(result).toBeNull();
+ });
+ });
+
+ describe("Trimmed match strategy fallback", () => {
+ it("should find match when search content has leading/trailing whitespace", () => {
+ const fileContent = "hello world";
+ const searchContent = " hello ";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 5,
+ strategyName: "trimmedMatch",
+ });
+ });
+
+ it("should find match when search content has tabs and newlines", () => {
+ const fileContent = "function test() {}";
+ const searchContent = "\t\nfunction test()\n\t";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 15,
+ strategyName: "trimmedMatch",
+ });
+ });
+
+ it("should handle complex whitespace trimming", () => {
+ const fileContent = "const x = 5;";
+ const searchContent = " \n\t const x = 5; \t\n ";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 12,
+ strategyName: "trimmedMatch",
+ });
+ });
+ });
+
+ describe("Whitespace ignored strategy fallback", () => {
+ it("should match content with different whitespace formatting", () => {
+ const fileContent = "function test() {\n return true;\n}";
+ const searchContent = "function test(){return true;}";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 34,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle mixed whitespace differences", () => {
+ const fileContent = "if (condition) {\n doSomething();\n}";
+ const searchContent = "if(condition){doSomething();}";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 37,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match with tabs vs spaces differences", () => {
+ const fileContent = "function test() {\n\treturn 42;\n}";
+ const searchContent = "function test() {\n return 42;\n}";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 31,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle partial matches within larger content", () => {
+ const fileContent = "before\nfunction test() {\n return true;\n}\nafter";
+ const searchContent = "function test(){return true;}";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 7,
+ endIndex: 41,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should recognize empty search", () => {
+ const fileContent = "some content";
+ const searchContent = " \t\n ";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+
+ it("should handle complex nested structures with whitespace differences", () => {
+ const fileContent = `{
+ "key": "value",
+ "nested": {
+ "prop": 123
+ }
+}`;
+ const searchContent = '{"key":"value","nested":{"prop":123}}';
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 55,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match content in middle of file with complex indentation", () => {
+ const fileContent = `import React from 'react';
+
+function MyComponent() {
+ const handleClick = () => {
+ console.log('clicked');
+ };
+ return ;
+}
+
+export default MyComponent;`;
+ const searchContent = `const handleClick=()=>{console.log('clicked');};`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 55,
+ endIndex: 115,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle matches with mixed line endings and special characters", () => {
+ const fileContent = `\r\n\r\n \r\n \r\n \r\n`;
+ const searchContent = `Hello&goodbye
`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 39,
+ endIndex: 95,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match content surrounded by different types of whitespace", () => {
+ const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`;
+ const searchContent = `address:{street:"MainSt",city:"NYC"}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 45,
+ endIndex: 96,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ // IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both
+ it("should handle unicode characters with whitespace differences", () => {
+ const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`;
+ const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 44,
+ endIndex: 89,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match across multiple nested blocks with varying indentation", () => {
+ const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`;
+ const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 43,
+ endIndex: 132,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle regex-like patterns with escaped characters", () => {
+ const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`;
+ const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 29,
+ endIndex: 110,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match SQL-like content with varying whitespace", () => {
+ const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`;
+ const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 89,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => {
+ const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`;
+ const searchContent = `functionprocessdata(input){returninput.trim();}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 56,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match content with Windows-style CRLF line endings", () => {
+ const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`;
+ const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 37,
+ endIndex: 105,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle deeply nested JSON with mixed formatting", () => {
+ const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`;
+ const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 87,
+ endIndex: 243,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match XML content with attribute spacing differences", () => {
+ const fileContent = `\n\n - \n Test Item\n 100\n
\n`;
+ const searchContent = `TestItem100`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 48,
+ endIndex: 155,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle mathematical expressions with varying spacing", () => {
+ const fileContent = `const result = (a + b) * c - d / e;\nconst complex = Math.sqrt( x ** 2 + y ** 2 );\nconst formula = ( ( a + b ) * ( c - d ) ) / ( e + f );`;
+ const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 36,
+ endIndex: 142,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should match across comments and code with whitespace variations", () => {
+ const fileContent = `/* Multi-line comment\n with varying indentation */\nfunction processData(input) {\n // Single line comment\n const cleaned = input.trim();\n /* Another comment */\n return cleaned.toLowerCase();\n}`;
+ const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 205,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+ });
+
+ describe("No match scenarios", () => {
+ it("should return null when no strategy finds a match", () => {
+ const fileContent = "hello world";
+ const searchContent = "goodbye";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toBeNull();
+ });
+
+ it("should return null for completely different content", () => {
+ const fileContent = "function test() { return true; }";
+ const searchContent = "class MyClass { }";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toBeNull();
+ });
+
+ it("should return null when search content is longer than file content", () => {
+ const fileContent = "short";
+ const searchContent = "this is much longer than the file content";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toBeNull();
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle empty file content with non-empty search", () => {
+ const fileContent = "";
+ const searchContent = "something";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toBeNull();
+ });
+
+ it("should handle single character matches", () => {
+ const fileContent = "a";
+ const searchContent = "a";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 1,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle unicode characters", () => {
+ const fileContent = "Hello 🌍 World";
+ const searchContent = "🌍";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 6,
+ endIndex: 8, // Unicode emoji takes 2 character positions
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle newlines and carriage returns", () => {
+ const fileContent = "line1\r\nline2\nline3";
+ const searchContent = "\r\nline2";
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 5,
+ endIndex: 12,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle very long content efficiently", () => {
+ const longContent = "a".repeat(10000) + "target" + "b".repeat(10000);
+ const searchContent = "target";
+ const result = findSearchMatch(longContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 10000,
+ endIndex: 10006,
+ strategyName: "exactMatch",
+ });
+ });
+ });
+
+ describe("Strategy precedence", () => {
+ it("should prefer exact match over trimmed match", () => {
+ const fileContent = "hello world hello";
+ const searchContent = "hello"; // This exists exactly, so should use exactMatch
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 5,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should prefer trimmed match over whitespace ignored match", () => {
+ // Set up content where trimmed match would work but whitespace ignored would also work
+ const fileContent = "hello world";
+ const searchContent = " hello "; // Has whitespace but trimmed version exists
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 5,
+ strategyName: "trimmedMatch",
+ });
+ });
+
+ it("should fall back through strategies in correct order", () => {
+ const fileContent = "function test() {\n return true;\n}";
+ const searchContent = " function test(){return true;} "; // Needs whitespace ignored
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 34,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+ });
+
+ describe("Real-world code examples", () => {
+ it("should handle JavaScript function matching", () => {
+ const fileContent = `function calculateSum(a, b) {
+ const result = a + b;
+ return result;
+}`;
+ const searchContent = `function calculateSum(a, b) {
+ const result = a + b;
+ return result;
+}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 72,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle HTML tag matching with different formatting", () => {
+ const fileContent = ``;
+ const searchContent = ``;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 51,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should handle CSS rule matching", () => {
+ const fileContent = `.button {
+ background-color: blue;
+ color: white;
+}`;
+ const searchContent = `.button{background-color:blue;color:white;}`;
+ const result = findSearchMatch(fileContent, searchContent);
+
+ expect(result).toEqual({
+ startIndex: 0,
+ endIndex: 53,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+ });
+});
diff --git a/core/edit/searchAndReplace/findSearchMatches.test.ts b/core/edit/searchAndReplace/findSearchMatches.test.ts
new file mode 100644
index 000000000..392637a62
--- /dev/null
+++ b/core/edit/searchAndReplace/findSearchMatches.test.ts
@@ -0,0 +1,368 @@
+import { findSearchMatches } from "./findSearchMatch";
+
+describe("findSearchMatches", () => {
+ describe("exact match strategy", () => {
+ it("should find single occurrence", () => {
+ const content = "const foo = 'bar';";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 6,
+ endIndex: 9,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find multiple occurrences", () => {
+ const content = "const foo = 'foo';";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(2);
+ expect(matches[0]).toEqual({
+ startIndex: 6,
+ endIndex: 9,
+ strategyName: "exactMatch",
+ });
+ expect(matches[1]).toEqual({
+ startIndex: 13,
+ endIndex: 16,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should find overlapping pattern occurrences correctly", () => {
+ const content = "aaaa";
+ const search = "aa";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(2);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 2,
+ strategyName: "exactMatch",
+ });
+ expect(matches[1]).toEqual({
+ startIndex: 2,
+ endIndex: 4,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should return empty array when no matches found", () => {
+ const content = "const bar = 'baz';";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toEqual([]);
+ });
+
+ it("should handle multi-line content", () => {
+ const content = `line 1 foo
+line 2 bar
+line 3 foo`;
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(2);
+ expect(matches[0]).toEqual({
+ startIndex: 7,
+ endIndex: 10,
+ strategyName: "exactMatch",
+ });
+ expect(matches[1]).toEqual({
+ startIndex: 29,
+ endIndex: 32,
+ strategyName: "exactMatch",
+ });
+ });
+ });
+
+ describe("trimmed match strategy", () => {
+ it("should find trimmed occurrences when exact match fails", () => {
+ const content = "const foo = 'bar';";
+ const search = " foo ";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 6,
+ endIndex: 9,
+ strategyName: "trimmedMatch",
+ });
+ });
+
+ it("should find multiple trimmed occurrences", () => {
+ const content = "const foo = 'foo';";
+ const search = " foo ";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(2);
+ expect(matches[0]).toEqual({
+ startIndex: 6,
+ endIndex: 9,
+ strategyName: "trimmedMatch",
+ });
+ expect(matches[1]).toEqual({
+ startIndex: 13,
+ endIndex: 16,
+ strategyName: "trimmedMatch",
+ });
+ });
+ });
+
+ describe("whitespace ignored match strategy", () => {
+ it("should find matches ignoring internal whitespace", () => {
+ const content = "const foo = bar;";
+ const search = "const foo=bar";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 15,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+
+ it("should find multiple matches ignoring whitespace", () => {
+ const content = `const foo = bar;
+const baz = foo;`;
+ const search = "const foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 9,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle complex whitespace patterns", () => {
+ const content = `function test() {
+ return true;
+}`;
+ const search = "function test(){return true;}";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 34,
+ strategyName: "whitespaceIgnoredMatch",
+ });
+ });
+ });
+
+ describe("empty search content", () => {
+ it("should return single match at position 0 for empty string", () => {
+ const content = "const foo = 'bar';";
+ const search = "";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+
+ it("should return single match at position 0 for whitespace-only string", () => {
+ const content = "const foo = 'bar';";
+ const search = " \n\t ";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle searching in empty content", () => {
+ const content = "";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toEqual([]);
+ });
+
+ it("should handle searching for content at the beginning", () => {
+ const content = "foo bar baz";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 3,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle searching for content at the end", () => {
+ const content = "foo bar baz";
+ const search = "baz";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 8,
+ endIndex: 11,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle searching for the entire content", () => {
+ const content = "foo bar baz";
+ const search = "foo bar baz";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 11,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle special characters", () => {
+ const content = "const regex = /[a-z]+/g;";
+ const search = "/[a-z]+/g";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 14,
+ endIndex: 23,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle Unicode characters", () => {
+ const content = "const emoji = '🚀 Hello 🌍';";
+ const search = "🚀 Hello 🌍";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 15,
+ endIndex: 26,
+ strategyName: "exactMatch",
+ });
+ });
+ });
+
+ describe("performance considerations", () => {
+ it("should handle long content with multiple matches", () => {
+ const repeatedContent = "foo bar ".repeat(1000);
+ const search = "foo";
+ const matches = findSearchMatches(repeatedContent, search);
+
+ expect(matches).toHaveLength(1000);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 3,
+ strategyName: "exactMatch",
+ });
+ expect(matches[999]).toEqual({
+ startIndex: 7992,
+ endIndex: 7995,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should prevent infinite loops on edge cases", () => {
+ const content = "aaaa";
+ const search = "";
+ const matches = findSearchMatches(content, search);
+
+ // Should only return one match for empty search
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toEqual({
+ startIndex: 0,
+ endIndex: 0,
+ strategyName: "emptySearch",
+ });
+ });
+ });
+
+ describe("strategy selection", () => {
+ it("should use exact match strategy when possible", () => {
+ const content = "const foo = bar;";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0].strategyName).toBe("exactMatch");
+ });
+
+ it("should fallback to trimmed match when exact fails", () => {
+ const content = "const foo = bar;";
+ const search = " foo ";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0].strategyName).toBe("trimmedMatch");
+ });
+
+ it("should fallback to whitespace ignored when others fail", () => {
+ const content = "const foo = bar;";
+ const search = "const foo=bar";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
+ });
+ });
+
+ describe("complex patterns", () => {
+ it("should handle multiple matches with different line endings", () => {
+ const content = "foo\r\nbar\r\nfoo\nfoo";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(3);
+ expect(matches[0].startIndex).toBe(0);
+ expect(matches[1].startIndex).toBe(10);
+ expect(matches[2].startIndex).toBe(14);
+ });
+
+ it("should handle matches across different strategies", () => {
+ const content = "const foo = 'bar';\n const foo='baz';";
+ const search = "foo";
+ const matches = findSearchMatches(content, search);
+
+ // Both occurrences of "foo" should be found with exact match
+ expect(matches).toHaveLength(2);
+ expect(matches[0]).toEqual({
+ startIndex: 6,
+ endIndex: 9,
+ strategyName: "exactMatch",
+ });
+ expect(matches[1]).toEqual({
+ startIndex: 29,
+ endIndex: 32,
+ strategyName: "exactMatch",
+ });
+ });
+
+ it("should handle code with mixed indentation", () => {
+ const content = `\tfunction test() {
+ return true;
+\t}`;
+ const search = "function test(){return true;}";
+ const matches = findSearchMatches(content, search);
+
+ expect(matches).toHaveLength(1);
+ expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
+ });
+ });
+});
diff --git a/core/edit/searchAndReplace/multiEdit.vitest.ts b/core/edit/searchAndReplace/multiEdit.vitest.ts
new file mode 100644
index 000000000..401a724ff
--- /dev/null
+++ b/core/edit/searchAndReplace/multiEdit.vitest.ts
@@ -0,0 +1,341 @@
+import { describe, expect, it } from "vitest";
+import { EditOperation } from "../../tools/definitions/multiEdit";
+import { ContinueErrorReason } from "../../util/errors";
+import { validateMultiEdit } from "./multiEditValidation";
+import { executeMultiFindAndReplace } from "./performReplace";
+
+describe("multiEdit shared validation", () => {
+ describe("validateMultiEdit", () => {
+ it("should throw error if edits is not an array", () => {
+ expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.MultiEditEditsArrayRequired,
+ }),
+ );
+ });
+
+ it("should throw error if edits is missing", () => {
+ expect(() => validateMultiEdit({})).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.MultiEditEditsArrayRequired,
+ }),
+ );
+ });
+
+ it("should throw error if edits array is empty", () => {
+ expect(() => validateMultiEdit({ edits: [] })).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.MultiEditEditsArrayEmpty,
+ }),
+ );
+ });
+
+ it("should return valid edits", () => {
+ const edits: EditOperation[] = [
+ { old_string: "hello", new_string: "world" },
+ ];
+ const result = validateMultiEdit({ edits });
+ expect(result.edits).toEqual(edits);
+ });
+ });
+
+ describe("validateMultiEdit - individual edit validation", () => {
+ it("should throw error if edit has missing old_string", () => {
+ const args = {
+ edits: [
+ {
+ old_string: undefined as any,
+ new_string: "Hi there",
+ },
+ ],
+ };
+
+ expect(() => validateMultiEdit(args)).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingOldString,
+ }),
+ );
+ });
+
+ it("should throw error if edit has missing new_string", () => {
+ const args = {
+ edits: [
+ {
+ old_string: "Hello world",
+ new_string: undefined as any,
+ },
+ ],
+ };
+
+ expect(() => validateMultiEdit(args)).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMissingNewString,
+ }),
+ );
+ });
+
+ it("should throw error if old_string and new_string are the same", () => {
+ const args = {
+ edits: [
+ {
+ old_string: "Hello world",
+ new_string: "Hello world",
+ },
+ ],
+ };
+
+ expect(() => validateMultiEdit(args)).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
+ }),
+ );
+ });
+
+ it("should throw error if non-first edit has empty old_string", () => {
+ const args = {
+ edits: [
+ {
+ old_string: "Hello world",
+ new_string: "Hi there",
+ },
+ {
+ old_string: "",
+ new_string: "Invalid insertion",
+ },
+ ],
+ };
+
+ expect(() => validateMultiEdit(args)).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
+ }),
+ );
+ });
+
+ it("should allow first edit to have empty old_string", () => {
+ const args = {
+ edits: [
+ {
+ old_string: "",
+ new_string: "New content",
+ },
+ ],
+ };
+
+ expect(() => validateMultiEdit(args)).not.toThrow();
+ });
+ });
+
+ describe("executeMultiFindAndReplace", () => {
+ const originalContent = "Hello world\nThis is a test file\nGoodbye world";
+
+ it("should handle single edit", () => {
+ const edits = [
+ {
+ old_string: "Hello world",
+ new_string: "Hi there",
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(originalContent, edits);
+ expect(result).toBe("Hi there\nThis is a test file\nGoodbye world");
+ });
+
+ it("should handle multiple edits", () => {
+ const edits = [
+ {
+ old_string: "Hello world",
+ new_string: "Hi there",
+ },
+ {
+ old_string: "Goodbye world",
+ new_string: "See you later",
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(originalContent, edits);
+ expect(result).toBe("Hi there\nThis is a test file\nSee you later");
+ });
+
+ it("should handle replace_all", () => {
+ const edits = [
+ {
+ old_string: "world",
+ new_string: "universe",
+ replace_all: true,
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(originalContent, edits);
+ expect(result).toBe(
+ "Hello universe\nThis is a test file\nGoodbye universe",
+ );
+ });
+
+ it("should handle empty old_string as insertion at beginning", () => {
+ const edits = [
+ {
+ old_string: "",
+ new_string: "New first line\n",
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(originalContent, edits);
+ expect(result).toBe(
+ "New first line\nHello world\nThis is a test file\nGoodbye world",
+ );
+ });
+
+ it("should handle empty string in empty file", () => {
+ const edits = [
+ {
+ old_string: "",
+ new_string: "Content for empty file",
+ },
+ ];
+
+ // Empty old_string matches at position 0 (beginning of file)
+ const result = executeMultiFindAndReplace("", edits);
+ expect(result).toBe("Content for empty file");
+ });
+
+ it("should apply edits sequentially", () => {
+ const edits = [
+ {
+ old_string: "Hello world",
+ new_string: "Hi universe",
+ },
+ {
+ old_string: "Hi universe",
+ new_string: "Greetings cosmos",
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(originalContent, edits);
+ expect(result).toBe(
+ "Greetings cosmos\nThis is a test file\nGoodbye world",
+ );
+ });
+
+ it("should throw error if old_string is not found", () => {
+ const edits = [
+ {
+ old_string: "Not found",
+ new_string: "Hi there",
+ },
+ ];
+
+ expect(() =>
+ executeMultiFindAndReplace(originalContent, edits),
+ ).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
+ }),
+ );
+ });
+
+ it("should throw error if old_string appears multiple times and replace_all is false", () => {
+ const edits = [
+ {
+ old_string: "world",
+ new_string: "universe",
+ replace_all: false,
+ },
+ ];
+
+ expect(() =>
+ executeMultiFindAndReplace(originalContent, edits),
+ ).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
+ }),
+ );
+ });
+
+ it("should throw if string not found in edit sequence", () => {
+ const content = "Hello world";
+ const edits = [
+ { old_string: "Hello", new_string: "Hi" },
+ { old_string: "not found", new_string: "test" },
+ ];
+
+ expect(() => executeMultiFindAndReplace(content, edits)).toThrowError(
+ expect.objectContaining({
+ reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
+ }),
+ );
+ });
+
+ it("should handle whitespace differences using findSearchMatch", () => {
+ const content = "function test() {\n return true;\n}";
+ const edits = [
+ {
+ old_string: "function test(){return true;}",
+ new_string: "function test() { return false; }",
+ },
+ ];
+
+ const result = executeMultiFindAndReplace(content, edits);
+ expect(result).toBe("function test() { return false; }");
+ });
+
+ it("should handle mixed replace_all settings", () => {
+ const content = "x y x z x";
+ const edits = [
+ { old_string: "x", new_string: "a", replace_all: true },
+ { old_string: "y", new_string: "b" },
+ ];
+
+ const result = executeMultiFindAndReplace(content, edits);
+ expect(result).toBe("a b a z a");
+ });
+ });
+
+ describe("preprocessing logic", () => {
+ const originalContent = "Hello world\nThis is a test file\nGoodbye world";
+
+ it("should handle single edit preprocessing", () => {
+ const edits = [
+ {
+ old_string: "Hello world",
+ new_string: "Hi there",
+ },
+ ];
+
+ const newContent = executeMultiFindAndReplace(originalContent, edits);
+
+ expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world");
+ });
+
+ it("should handle multiple edits preprocessing", () => {
+ const edits = [
+ {
+ old_string: "Hello world",
+ new_string: "Hi there",
+ },
+ {
+ old_string: "Goodbye world",
+ new_string: "See you later",
+ },
+ ];
+
+ const newContent = executeMultiFindAndReplace(originalContent, edits);
+
+ expect(newContent).toBe("Hi there\nThis is a test file\nSee you later");
+ });
+
+ it("should count edits correctly", () => {
+ const edits = [
+ { old_string: "Hello", new_string: "Hi" },
+ { old_string: "world", new_string: "universe", replace_all: true },
+ ];
+
+ const newContent = executeMultiFindAndReplace(originalContent, edits);
+
+ expect(newContent).toBe(
+ "Hi universe\nThis is a test file\nGoodbye universe",
+ );
+ expect(edits.length).toBe(2);
+ });
+ });
+});
diff --git a/core/edit/searchAndReplace/multiEditValidation.ts b/core/edit/searchAndReplace/multiEditValidation.ts
new file mode 100644
index 000000000..b103884fb
--- /dev/null
+++ b/core/edit/searchAndReplace/multiEditValidation.ts
@@ -0,0 +1,50 @@
+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;
+
+ // Validate that edits is a non-empty array
+ if (!edits || !Array.isArray(edits)) {
+ throw new ContinueError(
+ ContinueErrorReason.MultiEditEditsArrayRequired,
+ "edits array is required",
+ );
+ }
+
+ if (edits.length === 0) {
+ throw new ContinueError(
+ ContinueErrorReason.MultiEditEditsArrayEmpty,
+ "edits array must contain at least one edit",
+ );
+ }
+
+ // Validate each individual edit
+ for (let i = 0; i < edits.length; i++) {
+ const edit = edits[i];
+
+ // Use existing single edit validation
+ validateSingleEdit(edit.old_string, edit.new_string, i);
+
+ // Only the first edit can have empty old_string (for insertion at beginning)
+ if (i > 0 && edit.old_string === "") {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
+ `Edit at index ${i}: old_string cannot be empty. Only the first edit can have an empty old_string for insertion at the beginning of the file.`,
+ );
+ }
+ }
+
+ return { edits };
+}
diff --git a/core/edit/searchAndReplace/performReplace.ts b/core/edit/searchAndReplace/performReplace.ts
new file mode 100644
index 000000000..65453e06c
--- /dev/null
+++ b/core/edit/searchAndReplace/performReplace.ts
@@ -0,0 +1,70 @@
+import { EditOperation } from "../../tools/definitions/multiEdit";
+import { ContinueError, ContinueErrorReason } from "../../util/errors";
+import { findSearchMatches } from "./findSearchMatch";
+
+export function executeFindAndReplace(
+ fileContent: string,
+ oldString: string,
+ newString: string,
+ replaceAll: boolean,
+ editIndex = 0,
+): string {
+ const matches = findSearchMatches(fileContent, oldString);
+
+ if (matches.length === 0) {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceOldStringNotFound,
+ `Edit at index ${editIndex}: string not found in file: "${oldString}"`,
+ );
+ }
+
+ if (replaceAll) {
+ // Apply replacements in reverse order to maintain correct positions
+ let result = fileContent;
+ for (let i = matches.length - 1; i >= 0; i--) {
+ const match = matches[i];
+ result =
+ result.substring(0, match.startIndex) +
+ newString +
+ result.substring(match.endIndex);
+ }
+ return result;
+ } else {
+ // For single replacement, check for multiple matches first
+ if (matches.length > 1) {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceMultipleOccurrences,
+ `Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
+ );
+ }
+
+ // Apply single replacement
+ const match = matches[0];
+ return (
+ fileContent.substring(0, match.startIndex) +
+ newString +
+ fileContent.substring(match.endIndex)
+ );
+ }
+}
+
+export function executeMultiFindAndReplace(
+ fileContent: string,
+ edits: EditOperation[],
+): string {
+ let result = fileContent;
+
+ // Apply edits in sequence
+ for (let editIndex = 0; editIndex < edits.length; editIndex++) {
+ const edit = edits[editIndex];
+ result = executeFindAndReplace(
+ result,
+ edit.old_string,
+ edit.new_string,
+ edit.replace_all ?? false,
+ editIndex,
+ );
+ }
+
+ return result;
+}
diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts
index 53caa0df5..b76cad23e 100644
--- a/core/edit/streamDiffLines.ts
+++ b/core/edit/streamDiffLines.ts
@@ -4,6 +4,7 @@ import {
ILLM,
Prediction,
RuleWithSource,
+ StreamDiffLinesPayload,
ToolResultChatMessage,
UserChatMessage,
} from "../";
@@ -20,6 +21,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
+import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@@ -42,6 +44,20 @@ function constructEditPrompt(
});
}
+function constructApplyPrompt(
+ originalCode: string,
+ newCode: string,
+ llm: ILLM,
+) {
+ const template = llm.promptTemplates?.apply ?? defaultApplyPrompt;
+ const rendered = llm.renderPromptTemplate(template, [], {
+ original_code: originalCode,
+ new_code: newCode,
+ });
+
+ return rendered;
+}
+
export async function* addIndentation(
diffLineGenerator: AsyncGenerator,
indentation: string,
@@ -58,27 +74,15 @@ function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
}
-export async function* streamDiffLines({
- prefix,
- highlighted,
- suffix,
- llm,
- abortController,
- input,
- language,
- overridePrompt,
- rulesToInclude,
-}: {
- prefix: string;
- highlighted: string;
- suffix: string;
- llm: ILLM;
- abortController: AbortController;
- input: string;
- language: string | undefined;
- overridePrompt: ChatMessage[] | undefined;
- rulesToInclude: RuleWithSource[] | undefined;
-}): AsyncGenerator {
+export async function* streamDiffLines(
+ options: StreamDiffLinesPayload,
+ llm: ILLM,
+ abortController: AbortController,
+ overridePrompt: ChatMessage[] | undefined,
+ rulesToInclude: RuleWithSource[] | undefined,
+): AsyncGenerator {
+ const { type, prefix, highlighted, suffix, input, language } = options;
+
void Telemetry.capture(
"inlineEdit",
{
@@ -104,7 +108,9 @@ export async function* streamDiffLines({
// For apply can be overridden with simply apply prompt
let prompt =
overridePrompt ??
- constructEditPrompt(prefix, highlighted, suffix, llm, input, language);
+ (type === "apply"
+ ? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm)
+ : constructEditPrompt(prefix, highlighted, suffix, llm, input, language));
// Rules can be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
@@ -159,7 +165,13 @@ export async function* streamDiffLines({
content: highlighted,
};
- const completion = recursiveStream(llm, abortController, prompt, prediction);
+ const completion = recursiveStream(
+ llm,
+ abortController,
+ type,
+ prompt,
+ prediction,
+ );
let lines = streamLines(completion);
diff --git a/core/index.d.ts b/core/index.d.ts
index 6e80bc5d3..30bb42006 100644
--- a/core/index.d.ts
+++ b/core/index.d.ts
@@ -272,7 +272,7 @@ export interface Session {
history: ChatHistoryItem[];
}
-export interface SessionMetadata {
+export interface BaseSessionMetadata {
sessionId: string;
title: string;
dateCreated: string;
@@ -310,11 +310,6 @@ export interface FileEdit {
replacement: string;
}
-export interface ContinueError {
- title: string;
- message: string;
-}
-
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
@@ -824,6 +819,8 @@ export interface IDE {
openUrl(url: string): Promise;
+ getExternalUri?(uri: string): Promise;
+
runCommand(command: string, options?: TerminalOptions): Promise;
saveFile(fileUri: string): Promise;
@@ -1099,6 +1096,7 @@ export interface Tool {
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
+ toolCallIcon?: string;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record,
@@ -1281,6 +1279,7 @@ export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
timeout?: number;
+ requestOptions?: RequestOptions;
}
export type MCPConnectionStatus =
@@ -1333,6 +1332,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
+ infos: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
@@ -1387,9 +1387,12 @@ export interface ApplyState {
fileContent?: string;
originalFileContent?: string;
toolCallId?: string;
+ autoFormattingDiff?: string;
}
-export interface StreamDiffLinesPayload {
+export type StreamDiffLinesType = "edit" | "apply";
+interface StreamDiffLinesOptionsBase {
+ type: StreamDiffLinesType;
prefix: string;
highlighted: string;
suffix: string;
@@ -1400,6 +1403,19 @@ export interface StreamDiffLinesPayload {
fileUri?: string;
}
+interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase {
+ type: "edit";
+}
+
+interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase {
+ type: "apply";
+ newCode: string;
+}
+
+type StreamDiffLinesPayload =
+ | StreamDiffLinesOptionsApply
+ | StreamDiffLinesOptionsEdit;
+
export interface HighlightedCodePayload {
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;
@@ -1795,7 +1811,8 @@ export type RuleSource =
| "rules-block"
| "colocated-markdown"
| "json-systemMessage"
- | ".continuerules";
+ | ".continuerules"
+ | "agent-file";
export interface RuleWithSource {
name?: string;
@@ -1807,6 +1824,7 @@ export interface RuleWithSource {
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
+ invokable?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;
diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts
index 8a4e60a49..4a0648420 100644
--- a/core/indexing/docs/DocsService.ts
+++ b/core/indexing/docs/DocsService.ts
@@ -272,7 +272,7 @@ export default class DocsService {
id: doc.startUrl,
isReindexing: false,
title: doc.title,
- debugInfo: `max depth: ${doc.maxDepth}`,
+ debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
@@ -468,7 +468,7 @@ export default class DocsService {
embeddingsProviderId: provider.embeddingId,
isReindexing: forceReindex && indexExists,
title: siteIndexingConfig.title,
- debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
+ debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`,
icon: siteIndexingConfig.faviconUrl,
url: siteIndexingConfig.startUrl,
};
diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts
index c7738a0fa..96b08f6e1 100644
--- a/core/indexing/ignore.ts
+++ b/core/indexing/ignore.ts
@@ -2,6 +2,7 @@ import ignore from "ignore";
import path from "path";
import { fileURLToPath } from "url";
+import { ContinueError, ContinueErrorReason } from "../util/errors";
// Security-focused ignore patterns - these should always be excluded for security reasons
export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
@@ -203,6 +204,13 @@ export const DEFAULT_IGNORE_DIRS = [
...ADDITIONAL_INDEXING_IGNORE_DIRS,
];
+export const DEFAULT_IGNORES = [
+ ...DEFAULT_IGNORE_FILETYPES,
+ ...DEFAULT_IGNORE_DIRS,
+];
+
+export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`;
+
// Create ignore instances
export const defaultSecurityIgnoreFile = ignore().add(
DEFAULT_SECURITY_IGNORE_FILETYPES,
@@ -252,7 +260,8 @@ export function isSecurityConcern(filePathOrUri: string) {
export function throwIfFileIsSecurityConcern(filepath: string) {
if (isSecurityConcern(filepath)) {
- throw new Error(
+ throw new ContinueError(
+ ContinueErrorReason.FileIsSecurityConcern,
`Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
);
}
diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts
index 8e036ff3a..2ccc325cf 100644
--- a/core/llm/autodetect.ts
+++ b/core/llm/autodetect.ts
@@ -1,4 +1,9 @@
-import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
+import {
+ ChatMessage,
+ ModelCapability,
+ ModelDescription,
+ TemplateType,
+} from "../index.js";
import { NEXT_EDIT_MODELS } from "./constants.js";
import {
@@ -40,6 +45,7 @@ import {
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
+ "lemonade",
"openai",
"nvidia",
"ollama",
@@ -62,6 +68,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
+ "lemonade",
"cohere",
"gemini",
"msty",
@@ -80,26 +87,24 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"watsonx",
];
-const MODEL_SUPPORTS_IMAGES: string[] = [
- "llava",
- "gpt-4-turbo",
- "gpt-4o",
- "gpt-4o-mini",
- "gpt-4-vision",
- "claude-3",
- "c4ai-aya-vision-8b",
- "c4ai-aya-vision-32b",
- "gemini-ultra",
- "gemini-1.5-pro",
- "gemini-1.5-flash",
- "sonnet",
- "opus",
- "haiku",
- "pixtral",
- "llama3.2",
- "llama-3.2",
- "llama4",
- "granite-vision",
+const MODEL_SUPPORTS_IMAGES: RegExp[] = [
+ /llava/,
+ /gpt-4-turbo/,
+ /gpt-4o/,
+ /gpt-4o-mini/,
+ /claude-3/,
+ /gemini-ultra/,
+ /gemini-1\.5-pro/,
+ /gemini-1\.5-flash/,
+ /sonnet/,
+ /opus/,
+ /haiku/,
+ /pixtral/,
+ /llama-?3\.2/,
+ /llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed
+ /\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't!
+ /\b(pali|med)gemma/,
+ /qwen(.*)vl/,
];
function modelSupportsImages(
@@ -115,10 +120,14 @@ function modelSupportsImages(
return false;
}
- const lower = model.toLowerCase();
+ const lowerModel = model.toLowerCase();
+ const lowerTitle = title?.toLowerCase() ?? "";
+
if (
+ lowerModel.includes("vision") ||
+ lowerTitle.includes("vision") ||
MODEL_SUPPORTS_IMAGES.some(
- (modelName) => lower.includes(modelName) || title?.includes(modelName),
+ (modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle),
)
) {
return true;
@@ -126,6 +135,26 @@ function modelSupportsImages(
return false;
}
+
+function modelSupportsReasoning(
+ model: ModelDescription | null | undefined,
+): boolean {
+ if (!model) {
+ return false;
+ }
+ if ("anthropic" === model.underlyingProviderName) {
+ return true;
+ }
+ if (model.model.includes("deepseek-r")) {
+ return true;
+ }
+ if (model.completionOptions?.reasoning) {
+ // Reasoning support is forced at the config level. Model might not necessarily support it though!
+ return true;
+ }
+ return false;
+}
+
const PARALLEL_PROVIDERS: string[] = [
"anthropic",
"bedrock",
@@ -421,4 +450,5 @@ export {
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsNextEdit,
+ modelSupportsReasoning,
};
diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts
index 9d1badd0c..0749fbdfb 100644
--- a/core/llm/countTokens.ts
+++ b/core/llm/countTokens.ts
@@ -85,7 +85,7 @@ function encodingForModel(modelName: string): Encoding {
function countImageTokens(content: MessagePart): number {
if (content.type === "imageUrl") {
- return 85;
+ return 1024;
}
throw new Error("Non-image content type");
}
diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts
index 1e7031f50..a35fe49da 100644
--- a/core/llm/index.test.ts
+++ b/core/llm/index.test.ts
@@ -95,10 +95,31 @@ describe("BaseLLM", () => {
test("should return true when modelSupportsImages returns true", () => {
baseLLM.model = "gpt-4-vision";
expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "fancy-vision-model";
+ expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "gemma3:4b";
+ expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "google/gemma-3-270m";
+ expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "foo/paligemma-custom-100";
+ expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "foo/medgemma_4b_it_16Q";
+ expect(baseLLM.supportsImages()).toBe(true);
+
+ baseLLM.model = "qwen2.5vl";
+ expect(baseLLM.supportsImages()).toBe(true);
});
test("should return false when modelSupportsImages returns false", () => {
expect(baseLLM.supportsImages()).toBe(false);
+
+ baseLLM.model = "gemma3n";
+ expect(baseLLM.supportsImages()).toBe(false);
});
});
diff --git a/core/llm/index.ts b/core/llm/index.ts
index f8fefd381..751a537ea 100644
--- a/core/llm/index.ts
+++ b/core/llm/index.ts
@@ -30,6 +30,7 @@ import {
TemplateType,
Usage,
} from "../index.js";
+import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
import { Logger } from "../util/Logger.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
@@ -503,6 +504,24 @@ export abstract class BaseLLM implements ILLM {
: "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
throw new Error(message);
}
+ if (
+ e.code === "ECONNREFUSED" &&
+ e.message.includes("http://localhost:8000")
+ ) {
+ const isInstalled = await isLemonadeInstalled();
+ let message: string;
+ if (process.platform === "linux") {
+ // On Linux, isLemonadeInstalled checks if it's running (via health endpoint)
+ message =
+ "Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions.";
+ } else {
+ // On Windows, we can check if it's installed
+ message = isInstalled
+ ? "Unable to connect to local Lemonade instance. Lemonade server may not be running."
+ : "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running.";
+ }
+ throw new Error(message);
+ }
}
throw e;
}
@@ -537,18 +556,14 @@ export abstract class BaseLLM implements ILLM {
}
private _formatChatMessage(msg: ChatMessage): string {
- let contentToShow = "";
- if (msg.role === "tool") {
- contentToShow = msg.content;
- } else if (msg.role === "assistant" && msg.toolCalls?.length) {
- contentToShow = msg.toolCalls
+ let contentToShow = renderChatMessage(msg);
+ if (msg.role === "assistant" && msg.toolCalls?.length) {
+ contentToShow += msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
- } else if ("content" in msg) {
- contentToShow = renderChatMessage(msg);
}
return `<${msg.role}>\n${contentToShow}\n\n`;
@@ -1041,6 +1056,10 @@ export abstract class BaseLLM implements ILLM {
const msg = fromChatResponse(response);
yield msg;
completion = this._formatChatMessage(msg);
+ interaction?.logItem({
+ kind: "message",
+ message: msg,
+ });
} else {
// Stream true
const stream = this.openaiAdapter.chatCompletionStream(
diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts
index 74c950350..fdaac3290 100644
--- a/core/llm/llms/Anthropic.ts
+++ b/core/llm/llms/Anthropic.ts
@@ -68,6 +68,17 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
+ private buildTextPart(text: string, addCaching: boolean) {
+ const part: any = {
+ type: "text",
+ text,
+ };
+ if (addCaching) {
+ part.cache_control = { type: "ephemeral" };
+ }
+ return part;
+ }
+
private convertMessage(message: ChatMessage, addCaching: boolean): any {
if (message.role === "tool") {
return {
@@ -81,14 +92,30 @@ class Anthropic extends BaseLLM {
],
};
} else if (message.role === "assistant" && message.toolCalls) {
- return {
- role: "assistant",
- content: message.toolCalls.map((toolCall) => ({
+ const parts: any[] = [];
+ if (message.content) {
+ if (typeof message.content === "string") {
+ parts.push(this.buildTextPart(message.content, addCaching));
+ } else if (message.content.length > 0) {
+ const textContent = message.content.filter((p) => p.type === "text");
+ const textParts = textContent.map((part, idx) => {
+ const cache = idx === textContent.length - 1 && addCaching;
+ return this.buildTextPart(part.text, cache);
+ });
+ parts.push(...textParts);
+ }
+ }
+ parts.push(
+ ...message.toolCalls.map((toolCall) => ({
type: "tool_use",
id: toolCall.id,
name: toolCall.function?.name,
input: safeParseToolCallArgs(toolCall),
})),
+ );
+ return {
+ role: "assistant",
+ content: parts,
};
} else if (message.role === "thinking" && !message.redactedThinking) {
return {
@@ -154,9 +181,7 @@ class Anthropic extends BaseLLM {
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
- const filteredmessages = msgs.filter(
- (m) => m.role !== "system" && !!m.content,
- );
+ const filteredmessages = msgs.filter((m) => m.role !== "system");
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts
index 893932f03..ea47b63ae 100644
--- a/core/llm/llms/Bedrock.ts
+++ b/core/llm/llms/Bedrock.ts
@@ -1,13 +1,19 @@
import {
BedrockRuntimeClient,
ContentBlock,
+ ContentBlockDelta,
+ ContentBlockStart,
+ ContentBlockStartEvent,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandOutput,
ImageFormat,
InvokeModelCommand,
Message,
+ ReasoningContentBlockDelta,
ToolConfiguration,
+ ToolUseBlock,
+ ToolUseBlockDelta,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
@@ -25,15 +31,6 @@ interface ModelConfig {
extractEmbeddings: (responseBody: any) => number[][];
}
-/**
- * Interface for tool use state tracking
- */
-interface ToolUseState {
- toolUseId: string;
- name: string;
- input: string;
-}
-
/**
* Interface for prompt caching metrics
*/
@@ -50,7 +47,6 @@ class Bedrock extends BaseLLM {
profile: "bedrock",
};
- private _currentToolResponse: Partial | null = null;
private _promptCachingMetrics: PromptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0,
@@ -149,108 +145,99 @@ class Bedrock extends BaseLLM {
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
}
- if (chunk.contentBlockDelta?.delta) {
- const delta: any = chunk.contentBlockDelta.delta;
-
+ const contentBlockDelta: ContentBlockDelta | undefined =
+ chunk.contentBlockDelta?.delta;
+ if (contentBlockDelta) {
// Handle text content
- if (chunk.contentBlockDelta.delta.text) {
+ if (contentBlockDelta.text) {
yield {
role: "assistant",
- content: chunk.contentBlockDelta.delta.text,
+ content: contentBlockDelta.text,
};
continue;
}
-
- // Handle text content
- if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
+ if (contentBlockDelta.reasoningContent?.text) {
yield {
role: "thinking",
- content: (chunk.contentBlockDelta.delta as any).reasoningContent
- .text,
+ content: contentBlockDelta.reasoningContent.text,
};
continue;
}
-
- // Handle signature for thinking
- if (delta.reasoningContent?.signature) {
+ if (contentBlockDelta.reasoningContent?.signature) {
yield {
role: "thinking",
content: "",
- signature: delta.reasoningContent.signature,
+ signature: contentBlockDelta.reasoningContent.signature,
};
continue;
}
-
- // Handle redacted thinking
- if (delta.redactedReasoning?.data) {
- yield {
- role: "thinking",
- content: "",
- redactedThinking: delta.redactedReasoning.data,
- };
- continue;
- }
-
- if (
- chunk.contentBlockDelta.delta.toolUse?.input &&
- this._currentToolResponse
- ) {
- // Append the new input to the existing string
- if (this._currentToolResponse.input === undefined) {
- this._currentToolResponse.input = "";
- }
- this._currentToolResponse.input +=
- chunk.contentBlockDelta.delta.toolUse.input;
- continue;
- }
}
- if (chunk.contentBlockStart?.start) {
- const start: any = chunk.contentBlockStart.start;
- if (start.redactedReasoning) {
+ const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk
+ .contentBlockDelta?.delta as ReasoningContentBlockDelta;
+ if (reasoningDelta) {
+ if (reasoningDelta.redactedContent) {
yield {
role: "thinking",
content: "",
- redactedThinking: start.redactedReasoning.data,
+ redactedThinking: reasoningDelta.text,
};
continue;
}
-
- const toolUse = chunk.contentBlockStart.start.toolUse;
- if (toolUse?.toolUseId && toolUse?.name) {
- this._currentToolResponse = {
- toolUseId: toolUse.toolUseId,
- name: toolUse.name,
- input: "",
- };
- }
- continue;
}
- if (chunk.contentBlockStop) {
- if (this._currentToolResponse) {
- yield {
- role: "assistant",
- content: "",
- toolCalls: [
- {
- id: this._currentToolResponse.toolUseId,
- type: "function",
- function: {
- name: this._currentToolResponse.name,
- arguments: this._currentToolResponse.input,
- },
+ const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk
+ .contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta;
+ const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta
+ ?.delta?.toolUse as ToolUseBlock;
+ if (toolUseBlockDelta && toolUseBlock) {
+ yield {
+ role: "assistant",
+ content: "",
+ toolCalls: [
+ {
+ id: toolUseBlock.toolUseId,
+ type: "function",
+ function: {
+ name: toolUseBlock.name,
+ arguments: toolUseBlockDelta.input,
},
- ],
- };
- this._currentToolResponse = null;
- }
+ },
+ ],
+ };
continue;
}
+
+ const contentBlockStart: ContentBlockStartEvent | undefined =
+ chunk.contentBlockStart as ContentBlockStartEvent;
+ if (contentBlockStart) {
+ const start: ContentBlockStart | undefined = chunk.contentBlockStart
+ ?.start as ContentBlockStart;
+ if (start) {
+ const toolUseBlock: ToolUseBlock | undefined =
+ start.toolUse as ToolUseBlock;
+ if (toolUseBlock?.toolUseId && toolUseBlock?.name) {
+ yield {
+ role: "assistant",
+ content: "",
+ toolCalls: [
+ {
+ id: toolUseBlock.toolUseId,
+ type: "function",
+ function: {
+ name: toolUseBlock.name,
+ arguments: "",
+ },
+ },
+ ],
+ };
+ continue;
+ }
+ }
+ }
}
} catch (error: unknown) {
// Clean up state and let the original error bubble up to the retry decorator
- this._currentToolResponse = null;
throw error;
}
}
@@ -348,6 +335,9 @@ class Bedrock extends BaseLLM {
budget_tokens: options.reasoningBudgetTokens,
}
: undefined,
+ anthropic_beta: options.model.includes("claude")
+ ? ["fine-grained-tool-streaming-2025-05-14"]
+ : undefined,
},
};
}
diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts
index 9d2b67ea7..3abce6cba 100644
--- a/core/llm/llms/Inception.ts
+++ b/core/llm/llms/Inception.ts
@@ -2,6 +2,7 @@ import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
+import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js";
import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
import OpenAI from "./OpenAI.js";
@@ -96,40 +97,21 @@ class Inception extends OpenAI {
options: CompletionOptions,
): AsyncGenerator {
if (this.isNextEdit(messages)) {
- messages = this.removeNextEditToken(messages);
-
- // Use edit/completions endpoint.
- const endpoint = new URL("edit/completions", this.apiBase);
-
- const resp = await this.fetch(endpoint, {
- method: "POST",
- body: JSON.stringify({
- model: options.model,
- messages: messages,
- max_tokens: options.maxTokens,
- temperature: options.temperature,
- top_p: options.topP,
- frequency_penalty: options.frequencyPenalty,
- presence_penalty: options.presencePenalty,
- stop: options.stop,
- stream: true,
- }),
- headers: {
- "Content-Type": "application/json",
- Accept: "application/json",
- Authorization: `Bearer ${this.apiKey}`,
- },
+ messages = this.removeToken(messages, UNIQUE_TOKEN);
+ yield* this.streamSpecialEndpoint(
+ "edit/completions",
+ messages,
signal,
- });
-
- for await (const chunk of streamSse(resp)) {
- if (chunk.choices?.[0]?.delta?.content) {
- yield {
- role: "assistant",
- content: chunk.choices[0].delta.content,
- };
- }
- }
+ options,
+ );
+ } else if (this.isApply(messages)) {
+ messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN);
+ yield* this.streamSpecialEndpoint(
+ "apply/completions",
+ messages,
+ signal,
+ options,
+ );
} else {
// Use regular chat/completions endpoint - call parent OpenAI implementation.
yield* super._streamChat(messages, signal, options);
@@ -145,23 +127,68 @@ class Inception extends OpenAI {
);
}
- private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
+ private isApply(messages: ChatMessage[]): boolean {
+ return messages.some(
+ (message) =>
+ typeof message.content === "string" &&
+ message.content.endsWith(APPLY_UNIQUE_TOKEN),
+ );
+ }
+
+ private removeToken(messages: ChatMessage[], token: string): ChatMessage[] {
const lastMessage = messages[messages.length - 1];
if (
typeof lastMessage?.content === "string" &&
- lastMessage.content.endsWith(UNIQUE_TOKEN)
+ lastMessage.content.endsWith(token)
) {
const cleanedMessages = [...messages];
cleanedMessages[cleanedMessages.length - 1] = {
...lastMessage,
- content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
+ content: lastMessage.content.slice(0, -token.length),
};
return cleanedMessages;
}
return messages;
}
+
+ private async *streamSpecialEndpoint(
+ path: string,
+ messages: ChatMessage[],
+ signal: AbortSignal,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ const endpoint = new URL(path, this.apiBase);
+
+ const resp = await this.fetch(endpoint, {
+ method: "POST",
+ body: JSON.stringify({
+ model: options.model,
+ messages,
+ max_tokens: options.maxTokens,
+ temperature: options.temperature,
+ top_p: options.topP,
+ frequency_penalty: options.frequencyPenalty,
+ presence_penalty: options.presencePenalty,
+ stop: options.stop,
+ stream: true,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ Accept: "application/json",
+ Authorization: `Bearer ${this.apiKey}`,
+ },
+ signal,
+ });
+
+ for await (const chunk of streamSse(resp)) {
+ const content = chunk.choices?.[0]?.delta?.content;
+ if (content) {
+ yield { role: "assistant", content };
+ }
+ }
+ }
}
export default Inception;
diff --git a/core/llm/llms/Lemonade.ts b/core/llm/llms/Lemonade.ts
new file mode 100644
index 000000000..94860f929
--- /dev/null
+++ b/core/llm/llms/Lemonade.ts
@@ -0,0 +1,12 @@
+import { LLMOptions } from "../../index.js";
+
+import OpenAI from "./OpenAI.js";
+
+class Lemonade extends OpenAI {
+ static providerName = "lemonade";
+ static defaultOptions: Partial = {
+ apiBase: "http://localhost:8000/api/v1/",
+ };
+}
+
+export default Lemonade;
diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts
index 1d069ff71..0a239fce9 100644
--- a/core/llm/llms/Ollama.ts
+++ b/core/llm/llms/Ollama.ts
@@ -87,6 +87,7 @@ interface OllamaChatOptions extends OllamaBaseOptions {
tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
+ think?: boolean; // if true the model will be prompted to think about the response before generating it
}
type OllamaBaseResponse = {
@@ -146,7 +147,6 @@ class Ollama extends BaseLLM implements ModelInstaller {
private static modelsBeingInstalledMutex = new Mutex();
private fimSupported: boolean = false;
-
constructor(options: LLMOptions) {
super(options);
@@ -269,6 +269,11 @@ class Ollama extends BaseLLM implements ModelInstaller {
return this.modelMap[this.model] ?? this.model;
}
+ get contextLength() {
+ const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185
+ return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH;
+ }
+
private _getModelFileParams(
options: CompletionOptions,
): OllamaModelFileParams {
@@ -393,6 +398,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
model: this._getModel(),
messages: ollamaMessages,
options: this._getModelFileParams(options),
+ think: options.reasoning,
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
// format: options.format, // Not currently in base completion options
diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts
index 27006aea1..83166b6a2 100644
--- a/core/llm/llms/OpenAI.ts
+++ b/core/llm/llms/OpenAI.ts
@@ -174,7 +174,7 @@ class OpenAI extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
- Authorization: `Bearer ${this.apiKey}`,
+ ...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }),
"api-key": this.apiKey ?? "", // For Azure
};
}
diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts
index b35aaa59c..f2ef6bde2 100644
--- a/core/llm/llms/OpenRouter.ts
+++ b/core/llm/llms/OpenRouter.ts
@@ -1,3 +1,5 @@
+import { ChatCompletionCreateParams } from "openai/resources/index";
+
import { LLMOptions } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
@@ -13,6 +15,127 @@ class OpenRouter extends OpenAI {
},
useLegacyCompletionsEndpoint: false,
};
+
+ /**
+ * Detect if the model is an Anthropic/Claude model
+ */
+ private isAnthropicModel(model?: string): boolean {
+ if (!model) return false;
+ const modelLower = model.toLowerCase();
+ return modelLower.includes("claude");
+ }
+
+ /**
+ * Add cache_control to message content for Anthropic models
+ */
+ private addCacheControlToContent(content: any, addCaching: boolean): any {
+ if (!addCaching) return content;
+
+ if (typeof content === "string") {
+ return [
+ {
+ type: "text",
+ text: content,
+ cache_control: { type: "ephemeral" },
+ },
+ ];
+ }
+
+ if (Array.isArray(content)) {
+ // For array content, add cache_control to the last text item
+ return content.map((part, idx) => {
+ if (part.type === "text" && idx === content.length - 1) {
+ return {
+ ...part,
+ cache_control: { type: "ephemeral" },
+ };
+ }
+ return part;
+ });
+ }
+
+ return content;
+ }
+
+ /**
+ * Override modifyChatBody to add Anthropic caching when appropriate
+ */
+ protected modifyChatBody(
+ body: ChatCompletionCreateParams,
+ ): ChatCompletionCreateParams {
+ // First apply parent modifications
+ body = super.modifyChatBody(body);
+
+ // Check if we should apply Anthropic caching
+ if (
+ !this.isAnthropicModel(body.model) ||
+ (!this.cacheBehavior && !this.completionOptions.promptCaching)
+ ) {
+ return body;
+ }
+
+ const shouldCacheConversation =
+ this.cacheBehavior?.cacheConversation ||
+ this.completionOptions.promptCaching;
+ const shouldCacheSystemMessage =
+ this.cacheBehavior?.cacheSystemMessage ||
+ this.completionOptions.promptCaching;
+
+ if (!shouldCacheConversation && !shouldCacheSystemMessage) {
+ return body;
+ }
+
+ // Follow the same logic as Anthropic.ts: filter out system messages first
+ const filteredMessages = body.messages.filter(
+ (m: any) => m.role !== "system" && !!m.content,
+ );
+
+ // Find the last two user message indices from the filtered array
+ const lastTwoUserMsgIndices = filteredMessages
+ .map((msg: any, index: number) => (msg.role === "user" ? index : -1))
+ .filter((index: number) => index !== -1)
+ .slice(-2);
+
+ // Create a mapping from filtered indices to original indices
+ let filteredIndex = 0;
+ const filteredToOriginalIndexMap: number[] = [];
+ body.messages.forEach((msg: any, originalIndex: number) => {
+ if (msg.role !== "system" && !!msg.content) {
+ filteredToOriginalIndexMap[filteredIndex] = originalIndex;
+ filteredIndex++;
+ }
+ });
+
+ // Modify messages to add cache_control
+ body.messages = body.messages.map((message: any, idx) => {
+ // Handle system message caching
+ if (message.role === "system" && shouldCacheSystemMessage) {
+ return {
+ ...message,
+ content: this.addCacheControlToContent(message.content, true),
+ };
+ }
+
+ // Handle conversation caching for last two user messages
+ // Check if this message's index (in filtered array) is one of the last two user messages
+ const filteredIdx = filteredToOriginalIndexMap.indexOf(idx);
+ if (
+ message.role === "user" &&
+ shouldCacheConversation &&
+ filteredIdx !== -1 &&
+ lastTwoUserMsgIndices.includes(filteredIdx)
+ ) {
+ return {
+ ...message,
+ content: this.addCacheControlToContent(message.content, true),
+ };
+ }
+
+ return message;
+ });
+
+ return body;
+ }
}
export default OpenRouter;
diff --git a/core/llm/llms/OpenRouter.vitest.ts b/core/llm/llms/OpenRouter.vitest.ts
new file mode 100644
index 000000000..e6e8afdd2
--- /dev/null
+++ b/core/llm/llms/OpenRouter.vitest.ts
@@ -0,0 +1,236 @@
+import { ChatCompletionCreateParams } from "openai/resources/index";
+import { describe, expect, it } from "vitest";
+
+import OpenRouter from "./OpenRouter";
+
+describe("OpenRouter Anthropic Caching", () => {
+ it("should detect Anthropic models correctly", () => {
+ const openRouter = new OpenRouter({
+ model: "claude-3-5-sonnet-latest",
+ apiKey: "test-key",
+ });
+
+ // Test private method through modifyChatBody
+ const body: ChatCompletionCreateParams = {
+ model: "claude-3-5-sonnet-latest",
+ messages: [],
+ };
+
+ // Should not throw
+ openRouter["modifyChatBody"](body);
+ });
+
+ it("should add cache_control to user messages when caching is enabled", () => {
+ const openRouter = new OpenRouter({
+ model: "anthropic/claude-3.5-sonnet",
+ apiKey: "test-key",
+ cacheBehavior: {
+ cacheConversation: true,
+ cacheSystemMessage: false,
+ },
+ });
+
+ const body: ChatCompletionCreateParams = {
+ model: "anthropic/claude-3.5-sonnet",
+ messages: [
+ { role: "user", content: "First message" },
+ { role: "assistant", content: "Response" },
+ { role: "user", content: "Second message" },
+ { role: "assistant", content: "Another response" },
+ { role: "user", content: "Third message" },
+ ],
+ };
+
+ const modifiedBody = openRouter["modifyChatBody"](body);
+
+ // Check that the last two user messages have cache_control
+ const userMessages = modifiedBody.messages.filter(
+ (msg: any) => msg.role === "user",
+ );
+
+ // First user message should not have cache_control
+ expect(userMessages[0].content).toBe("First message");
+
+ // Last two user messages should have cache_control
+ expect(userMessages[1].content).toEqual([
+ {
+ type: "text",
+ text: "Second message",
+ cache_control: { type: "ephemeral" },
+ },
+ ]);
+
+ expect(userMessages[2].content).toEqual([
+ {
+ type: "text",
+ text: "Third message",
+ cache_control: { type: "ephemeral" },
+ },
+ ]);
+ });
+
+ it("should correctly handle cache_control with system messages present", () => {
+ const openRouter = new OpenRouter({
+ model: "claude-3-5-sonnet-latest",
+ apiKey: "test-key",
+ cacheBehavior: {
+ cacheConversation: true,
+ cacheSystemMessage: true,
+ },
+ });
+
+ const body: ChatCompletionCreateParams = {
+ model: "claude-3-5-sonnet-latest",
+ messages: [
+ { role: "system", content: "You are a helpful assistant" },
+ { role: "user", content: "First user message" },
+ { role: "assistant", content: "First assistant response" },
+ { role: "user", content: "Second user message" },
+ { role: "assistant", content: "Second assistant response" },
+ { role: "user", content: "Third user message" },
+ ],
+ };
+
+ const modifiedBody = openRouter["modifyChatBody"](body);
+
+ // System message should have cache_control
+ expect(modifiedBody.messages[0]).toEqual({
+ role: "system",
+ content: [
+ {
+ type: "text",
+ text: "You are a helpful assistant",
+ cache_control: { type: "ephemeral" },
+ },
+ ],
+ });
+
+ // Check user messages - should follow Anthropic filtering logic
+ const userMessages = modifiedBody.messages.filter(
+ (msg: any) => msg.role === "user",
+ );
+
+ // First user message should NOT have cache_control (only last 2)
+ expect(userMessages[0].content).toBe("First user message");
+
+ // Last two user messages should have cache_control
+ expect(userMessages[1].content).toEqual([
+ {
+ type: "text",
+ text: "Second user message",
+ cache_control: { type: "ephemeral" },
+ },
+ ]);
+
+ expect(userMessages[2].content).toEqual([
+ {
+ type: "text",
+ text: "Third user message",
+ cache_control: { type: "ephemeral" },
+ },
+ ]);
+
+ // Assistant messages should remain unchanged
+ expect(modifiedBody.messages[2].content).toBe("First assistant response");
+ expect(modifiedBody.messages[4].content).toBe("Second assistant response");
+ });
+
+ it("should add cache_control to system message when caching is enabled", () => {
+ const openRouter = new OpenRouter({
+ model: "claude-3-5-sonnet-latest",
+ apiKey: "test-key",
+ cacheBehavior: {
+ cacheConversation: false,
+ cacheSystemMessage: true,
+ },
+ });
+
+ const body: ChatCompletionCreateParams = {
+ model: "claude-3-5-sonnet-latest",
+ messages: [
+ { role: "system", content: "You are a helpful assistant" },
+ { role: "user", content: "Hello" },
+ ],
+ };
+
+ const modifiedBody = openRouter["modifyChatBody"](body);
+
+ // System message should have cache_control
+ expect(modifiedBody.messages[0]).toEqual({
+ role: "system",
+ content: [
+ {
+ type: "text",
+ text: "You are a helpful assistant",
+ cache_control: { type: "ephemeral" },
+ },
+ ],
+ });
+
+ // User message should remain unchanged
+ expect(modifiedBody.messages[1]).toEqual({
+ role: "user",
+ content: "Hello",
+ });
+ });
+
+ it("should handle array content correctly", () => {
+ const openRouter = new OpenRouter({
+ model: "claude-3-5-sonnet-latest",
+ apiKey: "test-key",
+ cacheBehavior: {
+ cacheConversation: true,
+ cacheSystemMessage: false,
+ },
+ });
+
+ const body: ChatCompletionCreateParams = {
+ model: "claude-3-5-sonnet-latest",
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "First part" },
+ { type: "text", text: "Second part" },
+ ],
+ },
+ ],
+ };
+
+ const modifiedBody = openRouter["modifyChatBody"](body);
+
+ // Only the last text part should have cache_control
+ expect(modifiedBody.messages[0].content).toEqual([
+ { type: "text", text: "First part" },
+ {
+ type: "text",
+ text: "Second part",
+ cache_control: { type: "ephemeral" },
+ },
+ ]);
+ });
+
+ it("should not modify messages for non-Anthropic models", () => {
+ const openRouter = new OpenRouter({
+ model: "gpt-4o",
+ apiKey: "test-key",
+ cacheBehavior: {
+ cacheConversation: true,
+ cacheSystemMessage: true,
+ },
+ });
+
+ const body: ChatCompletionCreateParams = {
+ model: "gpt-4o",
+ messages: [
+ { role: "system", content: "System message" },
+ { role: "user", content: "User message" },
+ ],
+ };
+
+ const modifiedBody = openRouter["modifyChatBody"](body);
+
+ // Messages should remain unchanged
+ expect(modifiedBody.messages).toEqual(body.messages);
+ });
+});
diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts
index db37c9276..d7c334122 100644
--- a/core/llm/llms/SambaNova.ts
+++ b/core/llm/llms/SambaNova.ts
@@ -9,17 +9,16 @@ class SambaNova extends OpenAI {
};
private static MODEL_IDS: { [name: string]: string } = {
- "llama4-scout": "Llama-4-Scout-17B-16E-Instruct",
"llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct",
"llama3.3-70b": "Meta-Llama-3.3-70B-Instruct",
+ "llama3.3-swalllow-70b": "Llama-3.3-Swallow-70B-Instruct-v0.4",
"llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
- "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
- "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct",
- "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct",
- "qwq-32b": "QwQ-32B",
"deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B",
"deepseek-r1": "DeepSeek-R1",
"deepseek-v3": "DeepSeek-V3-0324",
+ "deepseek-v3.1": "DeepSeek-V3-0324",
+ "gpt-oss-120b": "gpt-oss-120b",
+ "qwen3-32b": "Qwen3-32B",
};
protected _convertModelName(model: string) {
diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts
index 7a058ced7..bb4301576 100644
--- a/core/llm/llms/index.ts
+++ b/core/llm/llms/index.ts
@@ -33,6 +33,7 @@ import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
+import Lemonade from "./Lemonade";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@@ -82,6 +83,7 @@ export const LLMClasses = [
LlamaCpp,
OpenAI,
OVHcloud,
+ Lemonade,
LMStudio,
Mistral,
Bedrock,
diff --git a/core/llm/rules/rules-utils.ts b/core/llm/rules/rules-utils.ts
new file mode 100644
index 000000000..3645576ed
--- /dev/null
+++ b/core/llm/rules/rules-utils.ts
@@ -0,0 +1,46 @@
+import { RuleWithSource } from "../..";
+import { getLastNPathParts } from "../../util/uri";
+
+export function getRuleDisplayName(rule: RuleWithSource): string {
+ if (rule.name) {
+ return rule.name;
+ }
+ return getRuleSourceDisplayName(rule);
+}
+
+export function getRuleSourceDisplayName(rule: RuleWithSource): string {
+ switch (rule.source) {
+ case ".continuerules":
+ return "Project rules";
+ case "default-chat":
+ return "Default chat system message";
+ case "default-plan":
+ return "Default plan mode system message";
+ case "default-agent":
+ return "Default agent system message";
+ case "json-systemMessage":
+ return "System Message (JSON)";
+ case "model-options-agent":
+ return "Base System Agent Message";
+ case "model-options-plan":
+ return "Base System Plan Message";
+ case "model-options-chat":
+ return "Base System Chat Message";
+ case "agent-file":
+ if (rule.ruleFile) {
+ return getLastNPathParts(rule.ruleFile, 2);
+ } else {
+ return "Agent file";
+ }
+ case "colocated-markdown":
+ if (rule.ruleFile) {
+ return getLastNPathParts(rule.ruleFile, 2);
+ } else {
+ return "rules.md";
+ }
+ case "rules-block":
+ return "Rules Block";
+ default:
+ return rule.source;
+ }
+}
diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts
index bef15522e..d1a0d4fe0 100644
--- a/core/llm/streamChat.ts
+++ b/core/llm/streamChat.ts
@@ -95,7 +95,7 @@ export async function* llmStreamChat(
...init,
signal: abortController.signal,
},
- config.requestOptions,
+ model.requestOptions,
),
completionOptions,
abortController,
diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts
index 61d23a732..bafad3f3b 100644
--- a/core/llm/templates/edit/gpt.ts
+++ b/core/llm/templates/edit/gpt.ts
@@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
return paragraphs.join("\n\n");
};
+
+export const defaultApplyPrompt: PromptTemplateFunction = (
+ history,
+ otherData,
+) => {
+ return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`;
+};
diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts
index ed40733a5..6d1b609e6 100644
--- a/core/llm/toolSupport.ts
+++ b/core/llm/toolSupport.ts
@@ -203,7 +203,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> =
if (
model.toLowerCase().startsWith("meta-llama-3") ||
model.toLowerCase().includes("llama-4") ||
- model.toLowerCase().includes("deepseek")
+ model.toLowerCase().includes("deepseek") ||
+ model.toLowerCase().includes("gpt") ||
+ model.toLowerCase().includes("qwen")
) {
return true;
}
@@ -374,9 +376,8 @@ export function isRecommendedAgentModel(modelName: string): boolean {
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
- [/gpt/, /4/],
[/gpt-5/],
- [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
+ [/claude/, /sonnet/, /3\.7|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {
diff --git a/core/package-lock.json b/core/package-lock.json
index 690d9d070..180a40903 100644
--- a/core/package-lock.json
+++ b/core/package-lock.json
@@ -152,10 +152,10 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
- "version": "1.0.96",
+ "version": "1.17.0",
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@@ -179,17 +179,22 @@
},
"../packages/fetch": {
"name": "@continuedev/fetch",
- "version": "1.0.16",
+ "version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
+ "@semantic-release/changelog": "^6.0.3",
+ "@semantic-release/git": "^10.0.1",
+ "@semantic-release/github": "^9.2.6",
+ "@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
+ "semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}
@@ -199,20 +204,25 @@
"version": "1.0.9",
"license": "Apache-2.0",
"devDependencies": {
+ "@semantic-release/changelog": "^6.0.3",
+ "@semantic-release/git": "^10.0.1",
+ "@semantic-release/github": "^9.2.6",
+ "@semantic-release/npm": "^10.0.6",
"@types/node": "^22.15.29",
+ "semantic-release": "^21.1.2",
"typescript": "^5.5.2"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
- "version": "1.5.1",
+ "version": "1.15.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
- "@continuedev/config-yaml": "^1.8.0",
- "@continuedev/fetch": "^1.0.16",
+ "@continuedev/config-yaml": "^1.14.0",
+ "@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@@ -7903,13 +7913,13 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
- "version": "1.8.2",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
- "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
+ "version": "1.12.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz",
+ "integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
- "form-data": "^4.0.0",
+ "form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@@ -9922,14 +9932,15 @@
}
},
"node_modules/es-set-tostringtag": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
- "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
- "peer": true,
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
"dependencies": {
- "get-intrinsic": "^1.2.4",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
- "hasown": "^2.0.1"
+ "hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@@ -11326,12 +11337,15 @@
}
},
"node_modules/form-data": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
- "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
+ "license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@@ -11980,7 +11994,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
- "peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index 5add878be..eb7be1bf6 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -35,7 +35,7 @@ import {
RangeInFileWithNextEditInfo,
SerializedContinueConfig,
Session,
- SessionMetadata,
+ BaseSessionMetadata,
SiteIndexingConfig,
SlashCommandDescWithSource,
StreamDiffLinesPayload,
@@ -49,7 +49,10 @@ import {
ControlPlaneEnv,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
-import { FreeTrialStatus } from "../control-plane/client";
+import {
+ FreeTrialStatus,
+ RemoteSessionMetadata,
+} from "../control-plane/client";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
@@ -71,10 +74,15 @@ export type ToCoreFromIdeOrWebviewProtocol = {
cancelApply: [undefined, void];
// History
- "history/list": [ListHistoryOptions, SessionMetadata[]];
+ "history/list": [
+ ListHistoryOptions,
+ (BaseSessionMetadata | RemoteSessionMetadata)[],
+ ];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
+ "history/loadRemote": [{ remoteId: string }, Session];
"history/save": [Session, void];
+ "history/share": [{ id: string; outputDir?: string }, void];
"history/clear": [undefined, void];
"devdata/log": [DevDataLogEvent, void];
"config/addOpenAiKey": [string, void];
@@ -140,6 +148,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
+ "mcp/disconnectServer": [{ id: string }, void];
+ "mcp/getDisconnectedServers": [undefined, string[]];
"mcp/getPrompt": [
{
serverName: string;
@@ -313,5 +323,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
+ "process/killTerminalProcess": [{ toolCallId: string }, void];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};
diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts
index 232953f88..21eab1f7f 100644
--- a/core/protocol/ideWebview.ts
+++ b/core/protocol/ideWebview.ts
@@ -48,6 +48,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
+ "session/share": [{ sessionId: string }, void];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts
index 91819a33d..f02727a37 100644
--- a/core/protocol/passThrough.ts
+++ b/core/protocol/passThrough.ts
@@ -13,6 +13,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/list",
"history/delete",
"history/load",
+ "history/loadRemote",
"history/save",
"history/clear",
"devdata/log",
@@ -31,6 +32,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
+ "mcp/disconnectServer",
+ "mcp/getDisconnectedServers",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@@ -86,6 +89,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
+ "process/killTerminalProcess",
];
// Message types to pass through from core to webview
diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts
index c1d203972..faec8a94b 100644
--- a/core/tools/callTool.ts
+++ b/core/tools/callTool.ts
@@ -1,3 +1,4 @@
+import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { canParseUrl } from "../util/url";
@@ -87,10 +88,14 @@ async function callToolFromUri(
if (!client) {
throw new Error("MCP connection not found");
}
- const response = await client.client.callTool({
- name: toolName,
- arguments: args,
- });
+ const response = await client.client.callTool(
+ {
+ name: toolName,
+ arguments: args,
+ },
+ CallToolResultSchema,
+ { timeout: client.options.timeout },
+ );
if (response.isError === true) {
throw new Error(JSON.stringify(response.content));
diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts
index 8f651a601..4d52cd665 100644
--- a/core/tools/definitions/createNewFile.ts
+++ b/core/tools/definitions/createNewFile.ts
@@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createNewFileTool: Tool = {
type: "function",
displayTitle: "Create New File",
- wouldLikeTo: "create a new file at {{{ filepath }}}",
- isCurrently: "creating a new file at {{{ filepath }}}",
- hasAlready: "created a new file at {{{ filepath }}}",
+ wouldLikeTo: "create {{{ filepath }}}",
+ isCurrently: "creating {{{ filepath }}}",
+ hasAlready: "created {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: true,
diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts
index 7dcb8cd51..2b8f1c4ed 100644
--- a/core/tools/definitions/createRuleBlock.ts
+++ b/core/tools/definitions/createRuleBlock.ts
@@ -84,4 +84,5 @@ For example:`,
["alwaysApply", "false"],
],
},
+ toolCallIcon: "PencilIcon",
};
diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts
index 07a76a991..2498dcc59 100644
--- a/core/tools/definitions/fetchUrlContent.ts
+++ b/core/tools/definitions/fetchUrlContent.ts
@@ -6,7 +6,7 @@ export const fetchUrlContentTool: Tool = {
displayTitle: "Read URL",
wouldLikeTo: "fetch {{{ url }}}",
isCurrently: "fetching {{{ url }}}",
- hasAlready: "viewed {{{ url }}}",
+ hasAlready: "fetched {{{ url }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -30,4 +30,5 @@ export const fetchUrlContentTool: Tool = {
prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
exampleArgs: [["url", "https://example.com"]],
},
+ toolCallIcon: "GlobeAltIcon",
};
diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts
index 5e710c04b..5159ea3ea 100644
--- a/core/tools/definitions/globSearch.ts
+++ b/core/tools/definitions/globSearch.ts
@@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const globSearchTool: Tool = {
type: "function",
displayTitle: "Glob File Search",
- wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
- isCurrently: 'finding file matches for "{{{ pattern }}}"',
- hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
+ wouldLikeTo: 'search for files like "{{{ pattern }}}"',
+ isCurrently: 'searching for files like "{{{ pattern }}}"',
+ hasAlready: 'searched for files like "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
- "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
+ "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],
@@ -30,4 +30,5 @@ export const globSearchTool: Tool = {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
+ toolCallIcon: "MagnifyingGlassIcon",
};
diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts
index cc4f9c49c..c9e78d62d 100644
--- a/core/tools/definitions/grepSearch.ts
+++ b/core/tools/definitions/grepSearch.ts
@@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const grepSearchTool: Tool = {
type: "function",
displayTitle: "Grep Search",
- wouldLikeTo: 'search for "{{{ query }}}" in the repository',
- isCurrently: 'getting search results for "{{{ query }}}"',
- hasAlready: 'retrieved search results for "{{{ query }}}"',
+ wouldLikeTo: 'search for "{{{ query }}}"',
+ isCurrently: 'searching for "{{{ query }}}"',
+ hasAlready: 'searched for "{{{ query }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.GrepSearch,
description:
- "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
+ "Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
parameters: {
type: "object",
required: ["query"],
@@ -31,4 +31,5 @@ export const grepSearchTool: Tool = {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
+ toolCallIcon: "MagnifyingGlassIcon",
};
diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts
index 86d9581af..49ac5b1c6 100644
--- a/core/tools/definitions/ls.ts
+++ b/core/tools/definitions/ls.ts
@@ -5,9 +5,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "ls",
- wouldLikeTo: "list files and folders in {{{ dirPath }}}",
- isCurrently: "listing files and folders in {{{ dirPath }}}",
- hasAlready: "listed files and folders in {{{ dirPath }}}",
+ wouldLikeTo: "list files in {{{ dirPath }}}",
+ isCurrently: "listing files in {{{ dirPath }}}",
+ hasAlready: "listed files in {{{ dirPath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -38,4 +38,5 @@ export const lsTool: Tool = {
["recursive", "false"],
],
},
+ toolCallIcon: "FolderIcon",
};
diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts
index e50fd459c..660537caf 100644
--- a/core/tools/definitions/multiEdit.ts
+++ b/core/tools/definitions/multiEdit.ts
@@ -50,12 +50,6 @@ CRITICAL REQUIREMENTS:
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
-If you want to create a new file, use:
-- A new file path, including new directory if needed
-- First edit: empty old_string and the new file's contents as new_string
-- Subsequent edits are not allowed - there is no need since you are creating
-- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
-
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts
index da1cb129b..87d1adc22 100644
--- a/core/tools/definitions/readCurrentlyOpenFile.ts
+++ b/core/tools/definitions/readCurrentlyOpenFile.ts
@@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = {
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
isCurrently: "reading the current file",
- hasAlready: "viewed the current file",
+ hasAlready: "read the current file",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -24,4 +24,5 @@ export const readCurrentlyOpenFileTool: Tool = {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
},
+ toolCallIcon: "DocumentTextIcon",
};
diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts
index 2fc606883..ee6c1c91c 100644
--- a/core/tools/definitions/readFile.ts
+++ b/core/tools/definitions/readFile.ts
@@ -6,7 +6,7 @@ export const readFileTool: Tool = {
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
isCurrently: "reading {{{ filepath }}}",
- hasAlready: "viewed {{{ filepath }}}",
+ hasAlready: "read {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -31,4 +31,5 @@ export const readFileTool: Tool = {
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "DocumentIcon",
};
diff --git a/core/tools/definitions/readFileRange.ts b/core/tools/definitions/readFileRange.ts
index 91e94d574..41a7bfcfd 100644
--- a/core/tools/definitions/readFileRange.ts
+++ b/core/tools/definitions/readFileRange.ts
@@ -9,7 +9,7 @@ export const readFileRangeTool: Tool = {
isCurrently:
"reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
hasAlready:
- "viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
+ "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@@ -48,4 +48,5 @@ export const readFileRangeTool: Tool = {
],
},
defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "DocumentIcon",
};
diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts
index aa1555e15..7740cb45a 100644
--- a/core/tools/definitions/searchWeb.ts
+++ b/core/tools/definitions/searchWeb.ts
@@ -30,4 +30,5 @@ export const searchWebTool: Tool = {
prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
+ toolCallIcon: "GlobeAltIcon",
};
diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts
index 3cbbee3cf..653fba584 100644
--- a/core/tools/definitions/singleFindAndReplace.ts
+++ b/core/tools/definitions/singleFindAndReplace.ts
@@ -12,9 +12,9 @@ export interface SingleFindAndReplaceArgs {
export const singleFindAndReplaceTool: Tool = {
type: "function",
displayTitle: "Find and Replace",
- wouldLikeTo: "find and replace in {{{ filepath }}}",
- isCurrently: "finding and replacing in {{{ filepath }}}",
- hasAlready: "found and replaced in {{{ filepath }}}",
+ wouldLikeTo: "edit {{{ filepath }}}",
+ isCurrently: "editing {{{ filepath }}}",
+ hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts
index 14d6176f2..4c397a04b 100644
--- a/core/tools/definitions/viewDiff.ts
+++ b/core/tools/definitions/viewDiff.ts
@@ -23,4 +23,5 @@ export const viewDiffTool: Tool = {
prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
},
defaultToolPolicy: "allowedWithoutPermission",
+ toolCallIcon: "CodeBracketIcon",
};
diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts
index 0d1d94046..176855e2b 100644
--- a/core/tools/definitions/viewRepoMap.ts
+++ b/core/tools/definitions/viewRepoMap.ts
@@ -23,4 +23,5 @@ export const viewRepoMapTool: Tool = {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
defaultToolPolicy: "allowedWithPermission",
+ toolCallIcon: "MapIcon",
};
diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts
index 4ef686445..f8776716f 100644
--- a/core/tools/definitions/viewSubdirectory.ts
+++ b/core/tools/definitions/viewSubdirectory.ts
@@ -30,4 +30,5 @@ export const viewSubdirectoryTool: Tool = {
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
defaultToolPolicy: "allowedWithPermission",
+ toolCallIcon: "FolderOpenIcon",
};
diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts
index b106396af..cccf3353b 100644
--- a/core/tools/implementations/runTerminalCommand.ts
+++ b/core/tools/implementations/runTerminalCommand.ts
@@ -36,8 +36,11 @@ import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import {
isProcessBackgrounded,
+ markProcessAsRunning,
removeBackgroundedProcess,
-} from "../../util/processTerminalBackgroundStates";
+ removeRunningProcess,
+ updateProcessOutput,
+} from "../../util/processTerminalStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@@ -120,6 +123,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
env: getColorEnv(), // Add enhanced environment for colors
});
+ // Track this process for foreground cancellation
+ if (toolCallId && waitForCompletion) {
+ markProcessAsRunning(
+ toolCallId,
+ childProc,
+ extras.onPartialOutput,
+ terminalOutput,
+ );
+ }
+
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
@@ -127,6 +140,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
+ // Update the tracked output for potential cancellation notifications
+ if (toolCallId && waitForCompletion) {
+ updateProcessOutput(toolCallId, terminalOutput);
+ }
+
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion
@@ -153,6 +171,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
+ // Update the tracked output for potential cancellation notifications
+ if (toolCallId && waitForCompletion) {
+ updateProcessOutput(toolCallId, terminalOutput);
+ }
+
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
@@ -182,15 +205,19 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
childProc.on("close", (code) => {
- // If this process has been backgrounded, clean it up from the map and return
- if (isProcessBackgrounded(toolCallId)) {
- removeBackgroundedProcess(toolCallId);
- return;
+ // Clean up process tracking
+ if (toolCallId) {
+ if (isProcessBackgrounded(toolCallId)) {
+ removeBackgroundedProcess(toolCallId);
+ return;
+ }
+ // Remove from foreground tracking if it was tracked
+ removeRunningProcess(toolCallId);
}
if (waitForCompletion) {
// Normal completion, resolve now
- if (code === 0) {
+ if (!code || code === 0) {
const status = "Command completed";
resolve([
{
@@ -234,10 +261,14 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
- // If this process has been backgrounded, clean it up from the map and return
- if (isProcessBackgrounded(toolCallId)) {
- removeBackgroundedProcess(toolCallId);
- return;
+ // Clean up process tracking
+ if (toolCallId) {
+ if (isProcessBackgrounded(toolCallId)) {
+ removeBackgroundedProcess(toolCallId);
+ return;
+ }
+ // Remove from foreground tracking if it was tracked
+ removeRunningProcess(toolCallId);
}
reject(error);
@@ -281,6 +312,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
);
+ // Track this process for foreground cancellation
+ if (toolCallId) {
+ markProcessAsRunning(toolCallId, childProc, undefined, "");
+ }
+
let stdout = "";
let stderr = "";
@@ -293,6 +329,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("close", (code) => {
+ // Clean up process tracking
+ if (toolCallId) {
+ removeRunningProcess(toolCallId);
+ }
+
if (code === 0) {
resolve({ stdout, stderr });
} else {
@@ -305,6 +346,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
+ // Clean up process tracking
+ if (toolCallId) {
+ removeRunningProcess(toolCallId);
+ }
reject(error);
});
},
diff --git a/core/tools/implementations/runTerminalCommand.vitest.ts b/core/tools/implementations/runTerminalCommand.vitest.ts
index 659163eb8..230d482f7 100644
--- a/core/tools/implementations/runTerminalCommand.vitest.ts
+++ b/core/tools/implementations/runTerminalCommand.vitest.ts
@@ -12,7 +12,7 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
-import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
+import * as processTerminalStates from "../../util/processTerminalStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
@@ -39,12 +39,8 @@ describe("runTerminalCommandImpl", () => {
vi.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
- // Get any processes that might be already tracked and clear them
- const processMap = (processBackgroundStates as any)
- .processTerminalBackgroundStates;
- if (processMap && typeof processMap.clear === "function") {
- processMap.clear();
- }
+ // Clear any processes that might be already tracked
+ processTerminalStates.clearAllBackgroundProcesses();
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts
index 9df82e78d..7d9b5256e 100644
--- a/core/tools/implementations/viewDiff.ts
+++ b/core/tools/implementations/viewDiff.ts
@@ -9,6 +9,17 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => {
// TODO includeUnstaged should be an option
const combinedDiff = diffs.join("\n");
+
+ if (!combinedDiff.trim()) {
+ return [
+ {
+ name: "Diff",
+ description: "current Git diff",
+ content: "The current diff is empty",
+ },
+ ];
+ }
+
const diffLines = combinedDiff.split("\n");
let truncated = false;
diff --git a/core/tools/index.ts b/core/tools/index.ts
index 3a45ea295..e021a601c 100644
--- a/core/tools/index.ts
+++ b/core/tools/index.ts
@@ -1,10 +1,10 @@
import { ConfigDependentToolParams, Tool } from "..";
+import { isRecommendedAgentModel } from "../llm/toolSupport";
import * as toolDefinitions from "./definitions";
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
export const getBaseToolDefinitions = () => [
toolDefinitions.readFileTool,
-
toolDefinitions.createNewFileTool,
toolDefinitions.runTerminalCommandTool,
toolDefinitions.globSearchTool,
@@ -13,7 +13,6 @@ export const getBaseToolDefinitions = () => [
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
- toolDefinitions.singleFindAndReplaceTool,
];
export const getConfigDependentToolDefinitions = (
@@ -38,10 +37,11 @@ export const getConfigDependentToolDefinitions = (
);
}
- if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
+ if (modelName && isRecommendedAgentModel(modelName)) {
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);
+ tools.push(toolDefinitions.singleFindAndReplaceTool);
}
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts
index ad3815a9a..6a7042d8f 100644
--- a/core/tools/mcpToolName.vitest.ts
+++ b/core/tools/mcpToolName.vitest.ts
@@ -5,6 +5,7 @@ import { getMCPToolName } from "./mcpToolName";
const createMcpServer = (name: string): MCPServerStatus => ({
name,
errors: [],
+ infos: [],
prompts: [],
tools: [],
resources: [],
diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts
index 59daf21c9..0a1778395 100644
--- a/core/util/GlobalContext.ts
+++ b/core/util/GlobalContext.ts
@@ -44,9 +44,8 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
- shownDeprecatedProviderWarnings: {
- [providerTitle: string]: boolean;
- };
+ shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
+ autoUpdateCli: boolean;
mcpOauthStorage: {
[serverUrl: string]: {
clientInformation?: OAuthClientInformationFull;
@@ -66,16 +65,7 @@ export class GlobalContext {
) {
const filepath = getGlobalContextFilePath();
if (!fs.existsSync(filepath)) {
- fs.writeFileSync(
- filepath,
- JSON.stringify(
- {
- [key]: value,
- },
- null,
- 2,
- ),
- );
+ fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2));
} else {
const data = fs.readFileSync(filepath, "utf-8");
@@ -113,10 +103,7 @@ export class GlobalContext {
}
// Recreate the file with salvaged values plus the new value
- const newData = {
- ...salvaged,
- [key]: value,
- };
+ const newData = { ...salvaged, [key]: value };
fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
return;
@@ -174,10 +161,7 @@ export class GlobalContext {
newValues: Partial,
): SharedConfigSchema {
const currentSharedConfig = this.getSharedConfig();
- const updatedSharedConfig = {
- ...currentSharedConfig,
- ...newValues,
- };
+ const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
@@ -189,10 +173,7 @@ export class GlobalContext {
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
- const newSelections = {
- ...forProfile,
- [role]: title,
- };
+ const newSelections = { ...forProfile, [role]: title };
this.update("selectedModelsByProfileId", {
...currentSelections,
diff --git a/core/util/errors.ts b/core/util/errors.ts
index f80fa6b70..9a5c07443 100644
--- a/core/util/errors.ts
+++ b/core/util/errors.ts
@@ -10,3 +10,44 @@ export function getRootCause(err: any): any {
}
return err;
}
+
+export class ContinueError extends Error {
+ reason: ContinueErrorReason;
+
+ constructor(reason: ContinueErrorReason, message?: string) {
+ super(message);
+ this.reason = reason;
+ this.name = "ContinueError";
+ }
+}
+
+export enum ContinueErrorReason {
+ // Find and Replace validation errors
+ FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings",
+ FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
+ FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
+ FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
+ FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
+ FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
+ FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
+
+ // Multi-edit
+ MultiEditEditsArrayRequired = "multi_edit_edits_array_required",
+ MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty",
+ MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation",
+ MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first",
+
+ // General Edit
+ EditToolFileNotRead = "edit_tool_file_not_yet_read",
+
+ // General File
+ FileAlreadyExists = "file_already_exists",
+ FileNotFound = "file_not_found",
+ FileWriteError = "file_write_error",
+ FileIsSecurityConcern = "file_is_security_concern",
+ ParentDirectoryNotFound = "parent_directory_not_found",
+
+ // Other
+ Unspecified = "unspecified",
+ Unknown = "unknown",
+}
diff --git a/core/util/history.ts b/core/util/history.ts
index 447249ded..02e3f8fee 100644
--- a/core/util/history.ts
+++ b/core/util/history.ts
@@ -1,6 +1,6 @@
import * as fs from "fs";
-import { Session, SessionMetadata } from "../index.js";
+import { Session, BaseSessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { NEW_SESSION_TITLE } from "./constants.js";
@@ -22,14 +22,14 @@ function safeParseArray(
}
export class HistoryManager {
- list(options: ListHistoryOptions): SessionMetadata[] {
+ list(options: ListHistoryOptions): BaseSessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
- let sessions = safeParseArray(content) ?? [];
+ let sessions = safeParseArray(content) ?? [];
sessions = sessions
.filter((session: any) => {
// Filter out old format
@@ -59,7 +59,7 @@ export class HistoryManager {
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList =
- safeParseArray(
+ safeParseArray(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
@@ -118,7 +118,7 @@ export class HistoryManager {
try {
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
- let sessionsList: SessionMetadata[];
+ let sessionsList: BaseSessionMetadata[];
try {
sessionsList = JSON.parse(rawSessionsList);
} catch (e) {
@@ -141,7 +141,7 @@ export class HistoryManager {
}
if (!found) {
- const sessionMetadata: SessionMetadata = {
+ const sessionMetadata: BaseSessionMetadata = {
sessionId: session.sessionId,
title: session.title,
dateCreated: String(Date.now()),
diff --git a/core/util/historyUtils.ts b/core/util/historyUtils.ts
new file mode 100644
index 000000000..fc0939c7b
--- /dev/null
+++ b/core/util/historyUtils.ts
@@ -0,0 +1,105 @@
+import fs from "fs";
+import { homedir } from "node:os";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import path from "path";
+
+import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js";
+import { ChatMessage, IDE } from "../index.js";
+import { renderChatMessage } from "../util/messageContent.js";
+import { getContinueGlobalPath } from "../util/paths.js";
+
+// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
+function getOffsetDatetime(date: Date): Date {
+ const offset = date.getTimezoneOffset();
+ const offsetHours = Math.floor(offset / 60);
+ const offsetMinutes = offset % 60;
+ date.setHours(date.getHours() - offsetHours);
+ date.setMinutes(date.getMinutes() - offsetMinutes);
+
+ return date;
+}
+
+function asBasicISOString(date: Date): string {
+ const isoString = date.toISOString();
+
+ return isoString.replace(/[-:]|(\.\d+Z)/g, "");
+}
+
+function reformatCodeBlocks(msgText: string): string {
+ const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
+ msgText = msgText.replace(
+ codeBlockFenceRegex,
+ (match, metadata, filename, extension) => {
+ const lang = languageForFilepath(filename);
+ return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
+ },
+ );
+ // Appease the markdown linter
+ return msgText.replace(/```\n```/g, "```\n\n```");
+}
+
+export function toMarkDown(history: ChatMessage[], time?: Date): string {
+ if (!time) {
+ time = new Date();
+ }
+ let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`;
+
+ for (const msg of history) {
+ let msgText = renderChatMessage(msg);
+ if (!msgText) {
+ continue; // Skip messages without content
+ }
+
+ if (msg.role === "user" && msgText.search("```") > -1) {
+ msgText = reformatCodeBlocks(msgText);
+ }
+
+ // format messages as blockquotes
+ msgText = msgText.replace(/^/gm, "> ");
+
+ content += `\n\n#### ${
+ msg.role === "user" ? "_User_" : "_Assistant_"
+ }\n\n${msgText}`;
+ }
+ return content;
+}
+
+export async function shareSession(
+ ide: IDE,
+ history: ChatMessage[],
+ outputDir?: string,
+) {
+ const now = new Date();
+ const content = toMarkDown(history, now);
+
+ outputDir = outputDir ?? getContinueGlobalPath();
+
+ if (outputDir.startsWith("~")) {
+ outputDir = outputDir.replace(/^~/, homedir);
+ } else if (
+ outputDir.startsWith("./") ||
+ outputDir.startsWith(".\\") ||
+ outputDir === "."
+ ) {
+ const workspaceDirs = await ide.getWorkspaceDirs();
+ // Although the most common situation is to have one directory open in a
+ // workspace it's also possible to have just a file open without an
+ // associated directory or to use multi-root workspaces in which multiple
+ // folders are included. We default to using the first item in the list, if
+ // it exists.
+ const workspaceDirectory = workspaceDirs?.[0] || "";
+ outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
+ }
+
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
+ const dtString = asBasicISOString(getOffsetDatetime(now));
+ const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
+
+ const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
+ await ide.writeFile(fileUrl, content);
+ await ide.openFile(fileUrl);
+ return fileUrl;
+}
diff --git a/core/util/lemonadeHelper.ts b/core/util/lemonadeHelper.ts
new file mode 100644
index 000000000..ff8d4dfbc
--- /dev/null
+++ b/core/util/lemonadeHelper.ts
@@ -0,0 +1,59 @@
+import { exec } from "node:child_process";
+import { IDE } from "..";
+
+export async function isLemonadeInstalled(): Promise {
+ // On Windows, check if lemonade-server command exists
+ if (process.platform === "win32") {
+ return new Promise((resolve, _reject) => {
+ exec("where.exe lemonade-server", (error, _stdout, _stderr) => {
+ resolve(!error);
+ });
+ });
+ }
+
+ // On Linux, check if the health endpoint is accessible
+ try {
+ const response = await fetch("http://localhost:8000/api/v1/health", {
+ method: "GET",
+ signal: AbortSignal.timeout(3000), // 3 second timeout
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ return data.status === "ok";
+ }
+ return false;
+ } catch {
+ return false;
+ }
+}
+
+export async function startLocalLemonade(ide: IDE): Promise {
+ let startCommand: string | undefined;
+
+ switch (process.platform) {
+ case "linux": // Linux
+ // On Linux, direct users to start Lemonade manually
+ return ide.showToast(
+ "info",
+ "Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.",
+ );
+
+ case "win32": // Windows
+ startCommand = "lemonade-server serve\n";
+ break;
+
+ default:
+ return ide.showToast(
+ "error",
+ "Cannot start Lemonade: platform not supported!",
+ );
+ }
+
+ if (startCommand) {
+ return ide.runCommand(startCommand, {
+ reuseTerminal: true,
+ terminalName: "Start Lemonade",
+ });
+ }
+}
diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts
index 31c447389..5a0bc95bf 100644
--- a/core/util/messageContent.ts
+++ b/core/util/messageContent.ts
@@ -35,6 +35,21 @@ export function renderContextItems(contextItems: ContextItem[]): string {
return contextItems.map((item) => item.content).join("\n\n");
}
+export function renderContextItemsWithStatus(contextItems: any[]): string {
+ return contextItems
+ .map((item) => {
+ let result = item.content;
+
+ // If this item has a status, append it directly after the content
+ if (item.status) {
+ result += `\n[Status: ${item.status}]`;
+ }
+
+ return result;
+ })
+ .join("\n\n");
+}
+
export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
switch (message.role) {
case "user":
diff --git a/core/util/parameters.ts b/core/util/parameters.ts
index fbcdbca66..9bdb5544b 100644
--- a/core/util/parameters.ts
+++ b/core/util/parameters.ts
@@ -21,7 +21,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
transform: true,
showWhateverWeHaveAtXMs: 300,
// Experimental options: true = enabled, false = disabled, number = enabled w priority
- experimental_includeClipboard: true,
+ experimental_includeClipboard: false,
experimental_includeRecentlyVisitedRanges: true,
experimental_includeRecentlyEditedRanges: true,
experimental_includeDiff: true,
diff --git a/core/util/processTerminalBackgroundStates.test.ts b/core/util/processTerminalBackgroundStates.test.ts
deleted file mode 100644
index 03a6e3de5..000000000
--- a/core/util/processTerminalBackgroundStates.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import {
- markProcessAsBackgrounded,
- isProcessBackgrounded,
- removeBackgroundedProcess,
-} from "./processTerminalBackgroundStates";
-
-describe("processTerminalBackgroundStates", () => {
- beforeEach(() => {
- // Clear any backgrounded processes before each test
- const backgroundedProcesses = Array.from(
- Object.getOwnPropertySymbols(global),
- ).find(
- (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
- );
-
- if (backgroundedProcesses) {
- // Reset the map by reimporting the module
- jest.resetModules();
- }
- });
-
- test("should mark a process as backgrounded", () => {
- const toolCallId = "test-123";
- markProcessAsBackgrounded(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
- });
-
- test("should correctly identify non-backgrounded processes", () => {
- const toolCallId = "test-123";
- const anotherToolCallId = "test-456";
-
- markProcessAsBackgrounded(toolCallId);
-
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
- expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
- });
-
- test("should remove a process from backgrounded state", () => {
- const toolCallId = "test-123";
-
- markProcessAsBackgrounded(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(true);
-
- removeBackgroundedProcess(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(false);
- });
-
- test("should handle removing non-existent processes", () => {
- const toolCallId = "test-123";
-
- // Should not throw an error
- removeBackgroundedProcess(toolCallId);
- expect(isProcessBackgrounded(toolCallId)).toBe(false);
- });
-
- test("should handle multiple processes", () => {
- const toolCallId1 = "test-123";
- const toolCallId2 = "test-456";
- const toolCallId3 = "test-789";
-
- markProcessAsBackgrounded(toolCallId1);
- markProcessAsBackgrounded(toolCallId2);
-
- expect(isProcessBackgrounded(toolCallId1)).toBe(true);
- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
- expect(isProcessBackgrounded(toolCallId3)).toBe(false);
-
- removeBackgroundedProcess(toolCallId1);
-
- expect(isProcessBackgrounded(toolCallId1)).toBe(false);
- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
- });
-});
diff --git a/core/util/processTerminalBackgroundStates.ts b/core/util/processTerminalBackgroundStates.ts
deleted file mode 100644
index 437b90925..000000000
--- a/core/util/processTerminalBackgroundStates.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Track which processes have been backgrounded
-const processTerminalBackgroundStates = new Map();
-
-// Function to mark a process as backgrounded
-export function markProcessAsBackgrounded(toolCallId: string): void {
- processTerminalBackgroundStates.set(toolCallId, true);
-}
-
-// Function to check if a process is backgrounded
-export function isProcessBackgrounded(toolCallId: string): boolean {
- return processTerminalBackgroundStates.has(toolCallId);
-}
-
-// Function to remove a process from the backgrounded processes map
-export function removeBackgroundedProcess(toolCallId: string): void {
- processTerminalBackgroundStates.delete(toolCallId);
-}
diff --git a/core/util/processTerminalStates.test.ts b/core/util/processTerminalStates.test.ts
new file mode 100644
index 000000000..6b9e39f00
--- /dev/null
+++ b/core/util/processTerminalStates.test.ts
@@ -0,0 +1,367 @@
+import { ChildProcess } from "child_process";
+import {
+ clearAllBackgroundProcesses,
+ getAllBackgroundedProcessIds,
+ getAllRunningProcessIds,
+ getRunningProcess,
+ isProcessBackgrounded,
+ isProcessRunning,
+ killAllRunningTerminalProcesses,
+ killMultipleTerminalProcesses,
+ killTerminalProcess,
+ markProcessAsBackgrounded,
+ markProcessAsRunning,
+ removeBackgroundedProcess,
+ removeRunningProcess,
+ updateProcessOutput,
+} from "./processTerminalStates";
+
+// Mock ChildProcess
+const createMockProcess = (
+ pid: number = 123,
+ killed: boolean = false,
+): jest.Mocked => {
+ const mockProcess = {
+ pid,
+ killed,
+ kill: jest.fn(),
+ } as unknown as jest.Mocked;
+
+ // Make kill() update the killed property
+ mockProcess.kill.mockImplementation(() => {
+ (mockProcess as any).killed = true;
+ return true;
+ });
+
+ return mockProcess;
+};
+
+describe("processTerminalStates", () => {
+ beforeEach(() => {
+ // Clear all running processes
+ const runningIds = getAllRunningProcessIds();
+ runningIds.forEach((id) => removeRunningProcess(id));
+
+ // Clear all backgrounded processes
+ const backgroundedIds = getAllBackgroundedProcessIds();
+ backgroundedIds.forEach((id) => removeBackgroundedProcess(id));
+
+ // Clear all timers
+ jest.clearAllTimers();
+ });
+
+ test("should mark a process as backgrounded", () => {
+ const toolCallId = "test-123";
+ markProcessAsBackgrounded(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+ });
+
+ test("should correctly identify non-backgrounded processes", () => {
+ const toolCallId = "test-123";
+ const anotherToolCallId = "test-456";
+
+ markProcessAsBackgrounded(toolCallId);
+
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+ expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
+ });
+
+ test("should remove a process from backgrounded state", () => {
+ const toolCallId = "test-123";
+
+ markProcessAsBackgrounded(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
+
+ removeBackgroundedProcess(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
+ });
+
+ test("should handle removing non-existent processes", () => {
+ const toolCallId = "test-123";
+
+ // Should not throw an error
+ removeBackgroundedProcess(toolCallId);
+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
+ });
+
+ test("should handle multiple processes", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const toolCallId3 = "test-789";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ expect(isProcessBackgrounded(toolCallId1)).toBe(true);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
+ expect(isProcessBackgrounded(toolCallId3)).toBe(false);
+
+ removeBackgroundedProcess(toolCallId1);
+
+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
+ });
+
+ describe("foreground process functions", () => {
+ test("should mark a process as running", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+ const mockCallback = jest.fn();
+ const initialOutput = "initial output";
+
+ markProcessAsRunning(
+ toolCallId,
+ mockProcess,
+ mockCallback,
+ initialOutput,
+ );
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
+ });
+
+ test("should handle process without callback or initial output", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
+ });
+
+ test("should correctly identify non-running processes", () => {
+ const toolCallId = "test-123";
+ const anotherToolCallId = "test-456";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ expect(isProcessRunning(toolCallId)).toBe(true);
+ expect(isProcessRunning(anotherToolCallId)).toBe(false);
+ });
+
+ test("should update process output", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+ const initialOutput = "initial";
+ const updatedOutput = "updated output";
+
+ markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput);
+ updateProcessOutput(toolCallId, updatedOutput);
+
+ // We can't directly test the output value, but we can ensure the function doesn't throw
+ expect(() =>
+ updateProcessOutput(toolCallId, updatedOutput),
+ ).not.toThrow();
+ });
+
+ test("should handle updating output for non-existent process", () => {
+ const toolCallId = "non-existent";
+
+ expect(() =>
+ updateProcessOutput(toolCallId, "some output"),
+ ).not.toThrow();
+ });
+
+ test("should remove a process from running state", () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+ expect(isProcessRunning(toolCallId)).toBe(true);
+
+ removeRunningProcess(toolCallId);
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ expect(getRunningProcess(toolCallId)).toBeUndefined();
+ });
+
+ test("should handle removing non-existent running processes", () => {
+ const toolCallId = "test-123";
+
+ expect(() => removeRunningProcess(toolCallId)).not.toThrow();
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ });
+
+ test("should return undefined for non-existent running process", () => {
+ const toolCallId = "non-existent";
+
+ expect(getRunningProcess(toolCallId)).toBeUndefined();
+ });
+ });
+
+ describe("terminal command cancellation", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test("should cancel a running terminal command", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+ expect(isProcessRunning(toolCallId)).toBe(true);
+
+ await killTerminalProcess(toolCallId);
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId)).toBe(false);
+ });
+
+ test("should handle cancelling non-existent process", async () => {
+ const toolCallId = "non-existent";
+
+ await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow();
+ });
+
+ test("should handle cancelling already killed process", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess(123, true); // Already killed
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ await killTerminalProcess(toolCallId);
+
+ expect(mockProcess.kill).not.toHaveBeenCalled();
+ });
+
+ test("should send SIGKILL after timeout if process not killed", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ // Mock kill to not actually set killed=true for SIGTERM
+ mockProcess.kill.mockImplementation((signal) => {
+ if (signal === "SIGKILL") {
+ (mockProcess as any).killed = true;
+ }
+ return true;
+ });
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ const cancelPromise = killTerminalProcess(toolCallId);
+
+ // Fast-forward time to trigger the timeout
+ jest.advanceTimersByTime(5000);
+
+ await cancelPromise;
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL");
+ });
+
+ test("should not send SIGKILL if process was already killed", async () => {
+ const toolCallId = "test-123";
+ const mockProcess = createMockProcess();
+
+ markProcessAsRunning(toolCallId, mockProcess);
+
+ const cancelPromise = killTerminalProcess(toolCallId);
+
+ // Fast-forward time to trigger the timeout
+ jest.advanceTimersByTime(5000);
+
+ await cancelPromise;
+
+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL
+ });
+ });
+
+ describe("utility functions", () => {
+ test("should get all running process IDs", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ const runningIds = getAllRunningProcessIds();
+ expect(runningIds).toContain(toolCallId1);
+ expect(runningIds).toContain(toolCallId2);
+ expect(runningIds).toHaveLength(2);
+ });
+
+ test("should get all backgrounded process IDs", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ const backgroundedIds = getAllBackgroundedProcessIds();
+ expect(backgroundedIds).toContain(toolCallId1);
+ expect(backgroundedIds).toContain(toolCallId2);
+ expect(backgroundedIds).toHaveLength(2);
+ });
+
+ test("should return empty arrays when no processes", () => {
+ expect(getAllRunningProcessIds()).toEqual([]);
+ expect(getAllBackgroundedProcessIds()).toEqual([]);
+ });
+
+ test("should cancel multiple terminal commands", async () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ await killMultipleTerminalProcesses([toolCallId1, toolCallId2]);
+
+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId1)).toBe(false);
+ expect(isProcessRunning(toolCallId2)).toBe(false);
+ });
+
+ test("should cancel all running terminal commands", async () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+ const mockProcess1 = createMockProcess(123);
+ const mockProcess2 = createMockProcess(456);
+
+ markProcessAsRunning(toolCallId1, mockProcess1);
+ markProcessAsRunning(toolCallId2, mockProcess2);
+
+ const cancelledIds = await killAllRunningTerminalProcesses();
+
+ expect(cancelledIds).toContain(toolCallId1);
+ expect(cancelledIds).toContain(toolCallId2);
+ expect(cancelledIds).toHaveLength(2);
+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(isProcessRunning(toolCallId1)).toBe(false);
+ expect(isProcessRunning(toolCallId2)).toBe(false);
+ });
+
+ test("should return empty array when no running commands to cancel", async () => {
+ const cancelledIds = await killAllRunningTerminalProcesses();
+ expect(cancelledIds).toEqual([]);
+ });
+
+ test("should clear all background processes", () => {
+ const toolCallId1 = "test-123";
+ const toolCallId2 = "test-456";
+
+ markProcessAsBackgrounded(toolCallId1);
+ markProcessAsBackgrounded(toolCallId2);
+
+ expect(getAllBackgroundedProcessIds()).toHaveLength(2);
+
+ clearAllBackgroundProcesses();
+
+ expect(getAllBackgroundedProcessIds()).toEqual([]);
+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
+ expect(isProcessBackgrounded(toolCallId2)).toBe(false);
+ });
+ });
+});
diff --git a/core/util/processTerminalStates.ts b/core/util/processTerminalStates.ts
new file mode 100644
index 000000000..cad243a82
--- /dev/null
+++ b/core/util/processTerminalStates.ts
@@ -0,0 +1,119 @@
+import { ChildProcess } from "child_process";
+
+// Track which processes have been backgrounded
+const processTerminalBackgroundStates = new Map();
+
+// Track which foreground processes are currently running
+interface RunningProcessInfo {
+ process: ChildProcess;
+ onPartialOutput?: (params: {
+ toolCallId: string;
+ contextItems: any[];
+ }) => void;
+ currentOutput: string;
+}
+
+const processTerminalForegroundStates = new Map();
+
+// Background process functions (existing)
+export function markProcessAsBackgrounded(toolCallId: string): void {
+ processTerminalBackgroundStates.set(toolCallId, true);
+}
+
+export function isProcessBackgrounded(toolCallId: string): boolean {
+ return processTerminalBackgroundStates.has(toolCallId);
+}
+
+export function removeBackgroundedProcess(toolCallId: string): void {
+ processTerminalBackgroundStates.delete(toolCallId);
+}
+
+// Foreground process functions (new)
+export function markProcessAsRunning(
+ toolCallId: string,
+ process: ChildProcess,
+ onPartialOutput?: (params: {
+ toolCallId: string;
+ contextItems: any[];
+ }) => void,
+ currentOutput: string = "",
+): void {
+ processTerminalForegroundStates.set(toolCallId, {
+ process,
+ onPartialOutput,
+ currentOutput,
+ });
+}
+
+export function isProcessRunning(toolCallId: string): boolean {
+ return processTerminalForegroundStates.has(toolCallId);
+}
+
+export function getRunningProcess(
+ toolCallId: string,
+): ChildProcess | undefined {
+ const info = processTerminalForegroundStates.get(toolCallId);
+ return info?.process;
+}
+
+export function updateProcessOutput(toolCallId: string, output: string): void {
+ const info = processTerminalForegroundStates.get(toolCallId);
+ if (info) {
+ info.currentOutput = output;
+ }
+}
+
+export function removeRunningProcess(toolCallId: string): void {
+ processTerminalForegroundStates.delete(toolCallId);
+}
+
+export async function killTerminalProcess(toolCallId: string): Promise {
+ const processInfo = processTerminalForegroundStates.get(toolCallId);
+ if (processInfo && !processInfo.process.killed) {
+ const { process } = processInfo;
+
+ process.kill("SIGTERM");
+
+ // Force kill after 5 seconds if still running
+ setTimeout(() => {
+ if (!process.killed) {
+ process.kill("SIGKILL");
+ }
+ }, 5000);
+
+ processTerminalForegroundStates.delete(toolCallId);
+ }
+}
+
+// Function to cancel multiple terminal commands at once
+export async function killMultipleTerminalProcesses(
+ toolCallIds: string[],
+): Promise {
+ const cancelPromises = toolCallIds.map((toolCallId) =>
+ killTerminalProcess(toolCallId),
+ );
+ await Promise.all(cancelPromises);
+}
+
+// Function to cancel ALL currently running terminal commands
+export async function killAllRunningTerminalProcesses(): Promise {
+ const runningIds = getAllRunningProcessIds();
+ if (runningIds.length > 0) {
+ await killMultipleTerminalProcesses(runningIds);
+ }
+ return runningIds; // Return the IDs that were cancelled
+}
+
+// Utility functions
+export function getAllRunningProcessIds(): string[] {
+ return Array.from(processTerminalForegroundStates.keys());
+}
+
+export function getAllBackgroundedProcessIds(): string[] {
+ return Array.from(processTerminalBackgroundStates.keys());
+}
+
+// Utility function for testing - clears all background process states
+export function clearAllBackgroundProcesses(): void {
+ processTerminalBackgroundStates.clear();
+}
diff --git a/docs/customize/custom-providers.mdx b/docs/customize/custom-providers.mdx
index 068f0cdca..b66559487 100644
--- a/docs/customize/custom-providers.mdx
+++ b/docs/customize/custom-providers.mdx
@@ -19,116 +19,62 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: file
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "file" }] }
-```
-
### @Code Context Provider – Reference Functions and Classes
Reference specific functions or classes from throughout your project.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: code
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "code" }] }
-```
-
### @Git Diff Context Provider – Reference Branch Changes
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: diff
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "diff" }] }
-```
-
### @Current File Context Provider – Reference the Active File
Reference the currently open file.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: currentFile
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "currentFile" }] }
-```
-
### @Terminal Context Provider – Reference Last Terminal Command and Output
Reference the last command you ran in your IDE's terminal and its output.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: terminal
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "terminal" }] }
-```
-
### @Docs Context Provider – Reference Documentation Site Content
Reference the contents from any documentation site.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: docs
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "docs" }] }
-```
-
Note that this will only enable the `@Docs` context provider.
To use it, you need to add a documentation site to your config file. See the [docs](/customize/overview#documentation-context) page for more information.
@@ -137,9 +83,6 @@ To use it, you need to add a documentation site to your config file. See the [do
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
-- YAML
-- JSON
-
config.yaml
```
@@ -149,21 +92,12 @@ context:
onlyPinned: true
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] }
-```
-
### @Web Context Provider – Reference Relevant Web Pages
Reference relevant pages from across the web, automatically determined from your input.
Optionally, set `n` to limit the number of results returned (default 6).
-- YAML
-- JSON
-
config.yaml
```
@@ -173,19 +107,10 @@ context:
n: 5
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "web", "params": { "n": 5 } }] }
-```
-
### @Codebase Context Provider – Reference Relevant Codebase Snippets
Reference the most relevant snippets from your codebase.
-- YAML
-- JSON
-
config.yaml
```
@@ -193,40 +118,22 @@ context:
- provider: codebase
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "codebase" }] }
-```
-
Read more about indexing and retrieval [here](/customize/overview#codebase-context).
### @Folder Context Provider – Reference Code from a Specific Folder
Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
-- YAML
-- JSON
-
config.yaml
```
context: - provider: folder
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "folder" }] }
-```
-
### @Search Context Provider – Reference Code Search Results
Reference the results of codebase search, just like the results you would get from VS Code search.
-- YAML
-- JSON
-
config.yaml
```
@@ -236,21 +143,12 @@ context:
maxResults: 100 # optional, defaults to 200
```
-config.json
-
-```json
-{ "contextProviders": [ { "name": "search", "params": { "maxResults": 100 // optional, defaults to 200 } } ]}
-```
-
This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
### @Url Context Provider – Reference Content from a URL
Reference the markdown converted contents of a given URL.
-- YAML
-- JSON
-
config.yaml
```
@@ -258,19 +156,10 @@ context:
- provider: url
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "url" }] }
-```
-
### @Clipboard Context Provider – Reference Clipboard Items
Reference recent clipboard items
-- YAML
-- JSON
-
config.yaml
```
@@ -278,19 +167,10 @@ context:
- provider: clipboard
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "clipboard" }] }
-```
-
### @Tree Context Provider – Reference Workspace File Structure
Reference the structure of your current workspace.
-- YAML
-- JSON
-
config.yaml
```
@@ -298,19 +178,10 @@ context:
- provider: tree
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "tree" }] }
-```
-
### @Problems Context Provider – Reference Problems in the Current File
Get Problems from the current file.
-- YAML
-- JSON
-
config.yaml
```
@@ -318,19 +189,10 @@ context:
- provider: problems
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "problems" }] }
-```
-
### @Debugger Context Provider – Reference Debugger Local Variables
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
-- YAML
-- JSON
-
config.yaml
```
@@ -340,12 +202,6 @@ context:
stackDepth: 3
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "debugger", "params": { "stackDepth": 3 } }] }
-```
-
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
### @Repository Map Context Provider – Reference Codebase Outline and Signatures
@@ -354,9 +210,6 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
-- YAML
-- JSON
-
config.yaml
```
@@ -366,12 +219,6 @@ context:
includeSignatures: false # default true
```
-config.json
-
-```json
-{ "contextProviders": [ { "name": "repo-map", "params": { "includeSignatures": false // default true } } ]}
-```
-
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repository map from.
@@ -382,9 +229,6 @@ This context provider is inspired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
-- YAML
-- JSON
-
config.yaml
```
@@ -392,19 +236,10 @@ context:
- provider: os
```
-config.json
-
-```json
-{ "contextProviders": [{ "name": "os" }] }
-```
-
### Using the Model Context Protocol (MCP) in Continue
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
-- YAML
-- JSON
-
config.yaml
```
@@ -417,24 +252,6 @@ mcpServers:
- /Users/NAME/test.db
```
-config.json
-
-```json
-{
- "experimental": {
- "modelContextProtocolServers": [
- {
- "transport": {
- "type": "stdio",
- "command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
- }
- }
- ]
- }
-}
-```
-
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### How to Request a New Context Provider in Continue
diff --git a/docs/customize/deep-dives/custom-providers.mdx b/docs/customize/deep-dives/custom-providers.mdx
index dc60dc560..9adc078ab 100644
--- a/docs/customize/deep-dives/custom-providers.mdx
+++ b/docs/customize/deep-dives/custom-providers.mdx
@@ -15,251 +15,95 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
-
-
- ```yaml config.yaml
- context:
- - provider: file
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "file"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: file
+```
### `@Code`
Reference specific functions or classes from throughout your project.
-
-
- ```yaml config.yaml
- context:
- - provider: code
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "code"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: code
+```
### `@Git Diff`
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
-
-
- ```yaml config.yaml
- context:
- - provider: diff
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "diff"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: diff
+```
### `@Current File`
Reference the currently open file.
-
-
- ```yaml config.yaml
- context:
- - provider: currentFile
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "currentFile"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: currentFile
+```
### `@Terminal`
Reference the last command you ran in your IDE's terminal and its output.
-
-
- ```yaml config.yaml
- context:
- - provider: terminal
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "terminal"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: terminal
+```
### `@Open`
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
-
-
- ```yaml config.yaml
- context:
- - provider: open
- params:
- onlyPinned: true
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "open",
- "params": {
- "onlyPinned": true
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: open
+ params:
+ onlyPinned: true
+```
### `@Clipboard`
Reference recent clipboard items
-
-
- ```yaml config.yaml
- context:
- - provider: clipboard
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "clipboard"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: clipboard
+```
### `@Tree`
Reference the structure of your current workspace.
-
-
- ```yaml config.yaml
- context:
- - provider: tree
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "tree"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: tree
+```
### `@Problems`
Get Problems from the current file.
-
-
- ```yaml config.yaml
- context:
- - provider: problems
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "problems"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: problems
+```
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
-
-
- ```yaml config.yaml
- context:
- - provider: debugger
- params:
- stackDepth: 3
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "debugger",
- "params": {
- "stackDepth": 3
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: debugger
+ params:
+ stackDepth: 3
+```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
@@ -269,30 +113,12 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
-
-
- ```yaml config.yaml
- context:
- - provider: repo-map
- params:
- includeSignatures: false # default true
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "repo-map",
- "params": {
- "includeSignatures": false // default true
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: repo-map
+ params:
+ includeSignatures: false # default true
+```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
@@ -304,56 +130,23 @@ This context provider is inpsired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
-
-
- ```yaml config.yaml
- context:
- - provider: os
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "os"
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: os
+```
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
-
-
- ```yaml config.yaml
- context:
- - provider: http
- params:
- url: "https://api.example.com/v1/users"
- headers:
- - Authorization: "Bearer "
- ```
-
-
- ```json config.json
- {
- "contextProviders": [
- {
- "name": "http",
- "params": {
- "url": "https://api.example.com/v1/users"
- }
- }
- ]
- }
- ```
-
-
+```yaml config.yaml
+context:
+ - provider: http
+ params:
+ url: "https://api.example.com/v1/users"
+ headers:
+ - Authorization: "Bearer "
+```
The receiving URL should expect to receive the following parameters:
@@ -375,36 +168,15 @@ Response
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
-
-
- ```yaml config.yaml
- mcpServers:
- - name: My MCP Server
- command: uvx
- args:
- - mcp-server-sqlite
- - --db-path
- - /Users/NAME/test.db
- ```
-
-
- ```json config.json
- {
- "experimental": {
- "modelContextProtocolServers": [
- {
- "transport": {
- "type": "stdio",
- "command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
- }
- }
- ]
- }
- }
- ```
-
-
+```yaml config.yaml
+mcpServers:
+ - name: My MCP Server
+ command: uvx
+ args:
+ - mcp-server-sqlite
+ - --db-path
+ - /Users/NAME/test.db
+```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
diff --git a/docs/customize/deep-dives/model-capabilities.mdx b/docs/customize/deep-dives/model-capabilities.mdx
index 3e8a998eb..661ce9c5e 100644
--- a/docs/customize/deep-dives/model-capabilities.mdx
+++ b/docs/customize/deep-dives/model-capabilities.mdx
@@ -231,12 +231,13 @@ This matrix shows which models support tool use and image input capabilities. Co
| Model | Tool Use | Image Input | Context Window |
| :------------- | -------- | ----------- | -------------- |
| Qwen 3 Coder | Yes | No | 32k |
+| Qwen 2.5 VL | No | Yes | 128k |
| Devstral Small | Yes | No | 32k |
| Llama 3.1 | Yes | No | 128k |
| Llama 3 | Yes | No | 8k |
| Mistral | Yes | No | 32k |
| Codestral | Yes | No | 32k |
-| Gemma 3 4B | Yes | No | 8k |
+| Gemma 3 4B | Yes | Yes | 128k |
### Notes
diff --git a/docs/customize/model-providers/assets/tetrate-get-api-key.png b/docs/customize/model-providers/assets/tetrate-get-api-key.png
new file mode 100644
index 000000000..e6f88b4bd
Binary files /dev/null and b/docs/customize/model-providers/assets/tetrate-get-api-key.png differ
diff --git a/docs/customize/model-providers/assets/tetrate-remix.png b/docs/customize/model-providers/assets/tetrate-remix.png
index c64d1d86d..a418f8a81 100644
Binary files a/docs/customize/model-providers/assets/tetrate-remix.png and b/docs/customize/model-providers/assets/tetrate-remix.png differ
diff --git a/docs/customize/model-providers/assets/tetrate-sign-in.png b/docs/customize/model-providers/assets/tetrate-sign-in.png
new file mode 100644
index 000000000..0833ab383
Binary files /dev/null and b/docs/customize/model-providers/assets/tetrate-sign-in.png differ
diff --git a/docs/customize/model-providers/more/SambaNova.mdx b/docs/customize/model-providers/more/SambaNova.mdx
index acd83a682..4b46333d1 100644
--- a/docs/customize/model-providers/more/SambaNova.mdx
+++ b/docs/customize/model-providers/more/SambaNova.mdx
@@ -1,6 +1,6 @@
---
title: "SambaNova"
-description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
+description: "Configure SambaCloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
---
The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup.
@@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
```yaml title="config.yaml"
models:
- - name: SambaNova Llama 4 Scout
+ - name: GPT OSS 120B
provider: sambanova
- model: Llama-4-Scout-17B-16E-Instruct
+ model: gpt-oss-120b
apiKey:
```
@@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
{
"models": [
{
- "title": "SambaNova Llama 4 Scout",
+ "title": "GPT OSS 120B",
"provider": "sambanova",
- "model": "Llama-4-Scout-17B-16E-Instruct",
+ "model": "gpt-oss-120b",
"apiKey": ""
}
]
diff --git a/docs/customize/model-providers/more/lemonade.mdx b/docs/customize/model-providers/more/lemonade.mdx
new file mode 100644
index 000000000..79afd957d
--- /dev/null
+++ b/docs/customize/model-providers/more/lemonade.mdx
@@ -0,0 +1,81 @@
+---
+title: "Lemonade Server"
+description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs"
+---
+
+
+ Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration
+
+
+## Overview
+
+Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms.
+
+## Installation
+
+Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/).
+
+## Configuration
+
+Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration.
+
+### Option 1: Using the Continue UI (Recommended)
+
+1. Click on the model selector dropdown in Continue
+2. Select "Add Model"
+3. Choose "Lemonade Server" from the provider list
+4. Continue will automatically configure the connection
+
+### Option 2: Manual Configuration
+
+If you need custom settings, you can manually configure Lemonade:
+
+
+
+ ```yaml title="config.yaml"
+ models:
+ - name: Lemonade
+ provider: lemonade
+ model:
+ apiBase: http://localhost:8000/api/v1/
+ ```
+
+
+ ```json title="config.json"
+ {
+ "models": [
+ {
+ "title": "Lemonade",
+ "provider": "lemonade",
+ "model": "",
+ "apiBase": "http://localhost:8000/api/v1/"
+ }
+ ]
+ }
+ ```
+
+
+
+## Getting Started
+
+1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/)
+2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default)
+3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue
+4. **Load a model**: Choose your preferred model through the interface
+
+## Hardware Support
+
+Lemonade Server automatically detects and optimizes for available hardware:
+- **NPU**: Neural Processing Unit acceleration for efficient inference
+- **GPU**: Full GPU acceleration support
+- **CPU**: Optimized CPU fallback when accelerators are unavailable
+
+## Key Features
+
+- OpenAI-compatible API for seamless integration
+- Support for popular model formats
+- Automatic hardware detection and optimization
+- Integration with Continue, Open WebUI, Gaia, and AnythingLLM
+- Active open-source community
+
+[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts)
\ No newline at end of file
diff --git a/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx
index 648e3800e..a074eef7d 100644
--- a/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx
+++ b/docs/customize/model-providers/top-level/tetrate_agent_router_service.mdx
@@ -3,81 +3,250 @@ title: "Tetrate Agent Router Service"
sidebarTitle: "Tetrate Agent Router Service"
slug: ../tetrate-agent-router-service
---
-
-The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities as well as embedding services.
+The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities.
This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
-## Getting Started
+
+Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast.
+
-1. Obtain an API key from the [Agent Router Service portal](https://api.router.tetrate.ai/)
-2. Configure Continue to use Agent Router Service as your model provider
+## Setup
-## Configuring Models
+
+
+Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key
+
+
-You can also quickly use models from Tetrate on the Cotninue Hub by visiting Tetrate on the Continue Hub [here](https://hub.continue.dev/tetrate). The easiest way if you don't see the model you want to use is to remix one of the models on the Tetrate page and change the model to the one you want to use.
+
+Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key
+
+
+
+
+- Choose a configuration method below.
+- If you use the Continue VS Code extension, install version `>=1.2.3`.
+
+
+
+
+
+### Quickstart with Continue Hub
+
+Fastest way: use preconfigured models from Tetrate on Continue Hub
+
+
+
+Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4))
+
+
+
+Click "Use Model", or "Remix" to change the model ID if needed
+
+
+
+Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables)
+
+Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects.
+
+
+

-### Available Models
+
+If a model is missing, remix a similar one and set the `model` field to the target ID.
+
-Agent Router Service supports routing to various models.
-Go to the [Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
+### Configuration Methods
-## Configuration Options
+
+
+ Use a Tetrate model block from the Hub or define it directly in your local agent configuration.
+
+
+ Use a Tetrate model block from the Hub or define your own on the Hub.
+
+
+ Create a local model block for reuse across agents without publishing it to the Hub.
+
+
-As Agent Router Service is an OpenAI API compatible provider, you can configure it like any other OpenAI API compatible provider. Therefore you will be setting `provider: openai` and `apiBase: https://api.router.tetrate.ai/v1`.
-Update your Continue configuration file (`~/.continue/config.yaml`) with your Agent Router Service API key:
+### Configuration Examples
+
+**Click a tab** to see an example.
+
+
+
-### On your local machine
+**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks.
-#### In your config.yaml
+Use a Tetrate model block from the Hub in your local agent configuration:
-```yaml title="config.yaml"
+```yaml title="~/.continue/config.yaml"
+name: Local Agent
+version: 1.0.0
+schema: v1
models:
- - name:
- provider: openai
- model:
- apiKey:
- apiBase: https://api.router.tetrate.ai/v1
+ - uses: tetrate/claude-sonnet-4
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - provider: code
+ - provider: docs
+ - provider: diff
+ - provider: terminal
+ - provider: problems
+ - provider: folder
+ - provider: codebase
```
-#### As a local model block
+Or define the model directly:
-Review the configuration reference for [model blocks](/reference#models) and using [local blocks](/reference#local-blocks). Ensure you look at the roles and capabilities section and review the [model capabilities guide](/customize/deep-dives/model-capabilities).
+```yaml title="~/.continue/config.yaml"
+name: Local Agent
+version: 1.0.0
+schema: v1
+models:
+ - name: Claude Sonnet 4
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ secrets.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+context:
+ - provider: code
+ - provider: docs
+ - provider: diff
+ - provider: terminal
+ - provider: problems
+ - provider: folder
+ - provider: codebase
+```
+
+
+**When to use**: Share configurations across teams or contribute to the community.
-```yaml title="model_name.yaml"
- name:
- models:
- - name:
- provider: openai
- model:
- apiKey: ${{ inputs.TETRATE_API_KEY }}
- apiBase: https://api.router.tetrate.ai/v1
- roles:
- - chat
- - edit
- - apply
- capabilities:
- - tool_use
+**The Model Block:**
+
+```yaml title="tetrate/claude-sonnet-4"
+name: Claude Sonnet 4
+version: 1.0.14
+schema: v1
+models:
+ - name: Claude Sonnet 4 - Tetrate
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ inputs.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+```
+View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4).
+
+**Reference it in your Agent configuration:**
+
+```yaml title="my-agent"
+name: My Agent
+version: 1.0.0
+schema: v1
+models:
+ - uses: tetrate/claude-sonnet-4
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - uses: continuedev/diff-context
+ - uses: continuedev/terminal-context
+ - uses: continuedev/file-context
+```
+
+To customize, see the [model block creation guide](/hub/blocks/create-a-block).
+
+
+
+
+
+**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub).
+
+**The Local Model Block:**
+
+Name the file `my-claude-4-model.yaml` so you can reference it in the Agent.
+
+
+```yaml title="~/.continue/models/my-claude-4-model.yaml"
+name: Claude Sonnet 4
+version: 1.0.1
+schema: v1
+models:
+ - name: Claude Sonnet 4
+ provider: tars
+ model: claude-4-sonnet-20250514
+ apiKey: ${{ inputs.TETRATE_API_KEY }}
+ roles:
+ - chat
+ - edit
+ - apply
+ capabilities:
+ - tool_use
+```
+Reference it as `my-claude-4-model` in your Agent configuration:
+
+```yaml title="~/.continue/agents/simple-agent.yaml"
+name: Simple Agent
+version: 1.0.0
+schema: v1
+models:
+ - uses: my-claude-4-model
+ with:
+ TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
+context:
+ - uses: continuedev/diff-context
+ - uses: continuedev/terminal-context
+ - uses: continuedev/file-context
```
-### On Model Block on Continue Hub
-Learn how to use model blocks on Continue Hub [here](/hub/blocks/create-a-block).
+
+Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks).
+
-```yaml title="model_name.yaml"
- name:
- models:
- - name:
- provider: openai
- model:
- apiKey: ${{ inputs.TETRATE_API_KEY }}
- apiBase: https://api.router.tetrate.ai/v1
- roles:
- - chat
- - edit
- - apply
- capabilities:
- - tool_use
-```
+
+
+
+---
+
+## Troubleshooting Common Issues
+
+
+
+ Verify your API key is active and has no extra spaces.
+
+
+ Confirm the model ID matches the Tetrate catalog.
+
+
+ Check your network or try a less-loaded model. Contact Tetrate support if issues persist.
+
+
+ Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published.
+
+
+
+---
+
+## Join the Community
+Connect with Tetrate and other builders for help and discussion.
+
+
+
+Get answers, insights, and best practices for secure, scalable infrastructure
+
+
diff --git a/docs/customize/model-roles/chat.mdx b/docs/customize/model-roles/chat.mdx
index afafb8591..f7fbedbc3 100644
--- a/docs/customize/model-roles/chat.mdx
+++ b/docs/customize/model-roles/chat.mdx
@@ -36,20 +36,6 @@ Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [An
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Claude Opus 4.1",
- "provider": "anthropic",
- "model": "claude-4-1-opus",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Gemma from Google DeepMind
@@ -88,37 +74,6 @@ If you prefer to use an open-weight model, then the Gemma family of Models from
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemma 3 27B",
- "provider": "ollama",
- "model": "gemma3:27b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemma 3 27B",
- "provider": "together",
- "model": "google/gemma-2-27b-it",
- "apiKey": ""
- }
- ]
- }
- ```
-
-
-
### GPT-4o from OpenAI
@@ -138,20 +93,6 @@ If you prefer to use a model from [OpenAI](../model-providers/top-level/openai),
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "GPT-4o",
- "provider": "openai",
- "model": "",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Grok-2 from xAI
@@ -171,20 +112,6 @@ If you prefer to use a model from [xAI](../model-providers/more/xAI), then we re
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Grok-2",
- "provider": "xAI",
- "model": "grok-2-latest",
- "apiKey": ""
- }
- ]
- }
- ```
-
### Gemini 2.0 Flash from Google
@@ -204,20 +131,6 @@ If you prefer to use a model from [Google](../model-providers/top-level/gemini),
apiKey:
```
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Gemini 2.0 Flash",
- "provider": "gemini",
- "model": "gemini-2.0-flash",
- "apiKey": ""
- }
- ]
- }
- ```
-
## Local, offline experience
@@ -268,49 +181,6 @@ If your local machine can run an 8B parameter model, then we recommend running L
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "ollama",
- "model": "llama3.1:8b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "lmstudio",
- "model": "llama3.1-8b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "Llama 3.1 8B",
- "provider": "msty",
- "model": "llama3.1-8b"
- }
- ]
- }
- ```
-
-
-
### DeepSeek Coder 2 16B
@@ -357,50 +227,6 @@ If your local machine can run a 16B parameter model, then we recommend running D
-
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "ollama",
- "model": "deepseek-coder-v2:16b",
- "apiBase": "http://localhost:11434"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "lmstudio",
- "model": "deepseek-coder-v2:16b"
- }
- ]
- }
- ```
-
-
- ```json title="config.json"
- {
- "models": [
- {
- "title": "DeepSeek Coder 2 16B",
- "provider": "msty",
- "model": "deepseek-coder-v2:16b"
- }
- ]
- }
- ```
-
-
-
## Other experiences
diff --git a/docs/customize/model-roles/edit.mdx b/docs/customize/model-roles/edit.mdx
index e60d47017..e150cd518 100644
--- a/docs/customize/model-roles/edit.mdx
+++ b/docs/customize/model-roles/edit.mdx
@@ -10,38 +10,15 @@ It's often useful to select a different model to respond to Edit prompts than fo
In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used.
-
-
- Use model roles.
- ```yaml title="config.yaml"
- models:
- - name: Claude 3.5 Sonnet
- provider: anthropic
- model: claude-3-5-sonnet-latest
- apiKey:
- roles:
- - edit
- ```
-
-
- Set the `experimental.modelRoles.inlineEdit` property in `config.json`.
- ```json title="config.json"
- {
- "models": {
- "name": "Claude 3.5 Sonnet",
- "provider": "anthropic",
- "model": "claude-3-5-sonnet-latest",
- "apiKey": ""
- },
- "experimental": {
- "modelRoles": {
- "inlineEdit": "Claude 3.5 Sonnet",
- }
- }
- }
- ```
-
-
+```yaml title="config.yaml"
+models:
+ - name: Claude 4 Sonnet
+ provider: anthropic
+ model: claude-3-5-sonnet-latest
+ apiKey:
+ roles:
+ - edit
+```
Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat.
diff --git a/docs/customize/model-roles/reranking.mdx b/docs/customize/model-roles/reranking.mdx
index ed5974b4b..95c4bfc8a 100644
--- a/docs/customize/model-roles/reranking.mdx
+++ b/docs/customize/model-roles/reranking.mdx
@@ -23,7 +23,10 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
- [Voyage Rerank 2 Block](https://hub.continue.dev/voyageai/rerank-2)
+ ```yaml title="config.yaml"
+ models:
+ - uses: voyageai/rerank-2
+ ```
```yaml title="config.yaml"
@@ -36,19 +39,6 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "voyage",
- "params": {
- "model": "rerank-2",
- "apiKey": ""
- }
- }
- }
- ```
-
### Cohere
@@ -71,19 +61,6 @@ See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rer
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "cohere",
- "params": {
- "model": "rerank-english-v3.0",
- "apiKey": ""
- }
- }
- }
- ```
-
### LLM
@@ -105,21 +82,9 @@ If you only have access to a single LLM, then you can use it as a reranker. This
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "llm",
- "params": {
- "modelTitle": "My Model Title"
- }
- }
- }
- ```
-
-The `"modelTitle"` field must match one of the models in your "models" array in config.json.
+
### Text Embeddings Inference
@@ -142,17 +107,4 @@ The `"modelTitle"` field must match one of the models in your "models" array in
- rerank
```
-
- ```json title="config.json"
- {
- "reranker": {
- "name": "huggingface-tei",
- "params": {
- "apiBase": "http://localhost:8080",
- "apiKey": ""
- }
- }
- }
- ```
-
diff --git a/docs/docs.json b/docs/docs.json
index e57798880..65324309d 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -233,6 +233,8 @@
"guides/codebase-documentation-awareness",
"guides/cli",
"guides/continuous-ai",
+ "guides/snyk-mcp-continue-cookbook",
+ "guides/continuous-ai-readiness-assessment",
"guides/plan-mode-guide",
"guides/ollama-guide",
"guides/instinct",
@@ -240,6 +242,14 @@
"guides/custom-code-rag",
"guides/how-to-self-host-a-model"
]
+ },
+ {
+ "group": "Cookbooks",
+ "icon": "book-open-cover",
+ "pages": [
+ "guides/posthog-github-continuous-ai",
+ "guides/netlify-mcp-continuous-deployment"
+ ]
}
]
},
@@ -353,10 +363,6 @@
"source": "/hub/blocks",
"destination": "/hub/blocks/intro"
},
- {
- "source": "/hub/agents/intro",
- "destination": "/hub/agents/intro"
- },
{
"source": "/customize",
"destination": "/customization/overview"
diff --git a/docs/features/autocomplete/next-edit.mdx b/docs/features/autocomplete/next-edit.mdx
index 9deb0c3af..c39148427 100644
--- a/docs/features/autocomplete/next-edit.mdx
+++ b/docs/features/autocomplete/next-edit.mdx
@@ -6,7 +6,7 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your
Next Edit is currently an experimental feature. It requires
[Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder
- model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in
+ model](https://hub.continue.dev/inception/mercury-coder) configured in
your Continue autocomplete settings and is not yet available for JetBrains
use.
@@ -73,7 +73,6 @@ Next Edit activates automatically when:
Next Edit requires:
- Compatible AI models (Mercury Coder or Instinct)
-- Continue development team access
- VS Code (JetBrains support coming soon)
- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview)
diff --git a/docs/guides/cli.mdx b/docs/guides/cli.mdx
index 069bf640a..4610d6301 100644
--- a/docs/guides/cli.mdx
+++ b/docs/guides/cli.mdx
@@ -87,6 +87,12 @@ cn --ask Bash(curl*)
cn --exclude Fetch
```
+## API Key Authentication
+
+For automation in CI or other headless environments, you can use an API key to authenticate with Continue. First, obtain your personal API key [here](https://hub.continue.dev/settings/api-keys). Then, set it as the `CONTINUE_API_KEY` environment variable. You can now use `cn -p` (headless mode) without needing to log in.
+
+If you wish to run an automation on behalf of your organization you can obtain an organization-scoped API key by going to [your organization's settings](https://hub.continue.dev/settings/organizations) -> API Keys.
+
## Troubleshooting
Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`.
diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx
index a79805a34..d061bce98 100644
--- a/docs/guides/codebase-documentation-awareness.mdx
+++ b/docs/guides/codebase-documentation-awareness.mdx
@@ -1,11 +1,10 @@
---
-title: How to make your agent aware of codebases and documentation
+title: How to Make Your Agent Aware of Codebases and Documentation
description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance
keywords: [agent, codebase, documentation, MCP, context, RAG, tools]
+sidebarTitle: Codebase and Documentation Awareness
---
-# How to make your agent aware of codebases and documentation
-
AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate.
## Make your agent aware of your open codebase
@@ -28,18 +27,21 @@ Rules guide your agent's behavior and understanding. Place markdown files in `.c
# Project Architecture
This is a React application with:
+
- Components in `/src/components`
- API routes in `/src/api`
- State management using Redux in `/src/store`
## Coding Standards
+
- Use TypeScript for all new files
- Follow the existing naming conventions
- Write tests for all new features
```
- Place rules files at different levels of your project hierarchy to scope when they trigger
+ Place rules files at different levels of your project hierarchy to scope when
+ they trigger
Learn more about [rules configuration](/customize/deep-dives/rules).
@@ -60,6 +62,7 @@ Create rules that point to external codebases:
# External Dependencies
Our authentication system is based on:
+
- [Auth.js documentation](https://authjs.dev/)
- [Example implementation](https://github.com/nextauthjs/next-auth-example)
@@ -76,6 +79,7 @@ Add rules to guide CLI usage:
# Repository Access
You can use the `gh` CLI to:
+
- Search for issues: `gh issue list --repo owner/repo`
- View pull requests: `gh pr list --repo owner/repo`
- Clone repositories: `gh repo clone owner/repo`
@@ -86,6 +90,7 @@ You can use the `gh` CLI to:
[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository.
Once configured, your agent can explore repositories like:
+
- "Explore the React repository structure"
- "Find how authentication is implemented in NextAuth.js"
@@ -115,6 +120,7 @@ Guide your agent to relevant documentation:
# Documentation Resources
For framework-specific questions, refer to:
+
- React: https://react.dev/reference/react
- Next.js: https://nextjs.org/docs
- Tailwind CSS: https://tailwindcss.com/docs
@@ -127,6 +133,7 @@ Always cite documentation when explaining concepts.
[Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation:
Your agent can then answer questions like:
+
- "How do I use React hooks?"
- "What's the syntax for Tailwind CSS animations?"
@@ -142,6 +149,7 @@ Create rules that reference internal resources:
# Internal Documentation
Our team documentation is available at:
+
- API Documentation: https://internal.docs/api
- Architecture Guide: https://internal.docs/architecture
- Deployment Process: https://internal.docs/deployment
diff --git a/docs/guides/continuous-ai-readiness-assessment.mdx b/docs/guides/continuous-ai-readiness-assessment.mdx
new file mode 100644
index 000000000..f72e5dd85
--- /dev/null
+++ b/docs/guides/continuous-ai-readiness-assessment.mdx
@@ -0,0 +1,309 @@
+---
+title: Assessing Your Team's Readiness for Continuous AI
+description: Complete framework to evaluate team readiness for Continuous AI adoption with maturity levels, assessment criteria, and implementation roadmap.
+sidebarTitle: Continuous AI Readiness Assessment
+---
+
+
+ **TL;DR:** Use this assessment framework to determine if your team is ready to
+ move from individual AI tool usage to automated Continuous AI workflows.
+ Covers technical infrastructure, processes, culture, and organizational
+ support.
+
+
+## Assessing Continuous AI Readiness
+
+Continuous AI can dramatically improve development velocity and code quality, but successful implementation requires careful evaluation across four key dimensions.
+
+
+ Rushing into Continuous AI without proper foundations leads to frustration and
+ failed initiatives. Use this framework to identify gaps before scaling.
+
+
+### 1. Identify Your Current Maturity Level
+
+Determine where your team falls on the Continuous AI maturity spectrum:
+
+
+
+ Developers use AI tools inconsistently with highly variable results.
+
+ **Characteristics:**
+ - High rejection rates of AI-generated code (>50%)
+ - No shared standards or prompting rules
+ - AI tools lack context about your codebase
+ - Ad-hoc usage without team coordination
+
+
+
+
+ AI is systematically integrated into team workflows and CI/CD pipelines.
+
+**Characteristics:**
+
+- Consistent adoption across 80%+ of team members
+- AI integrated into code reviews and deployment processes
+- Documented standards for prompts and tool usage
+- Basic metrics tracking AI impact
+
+
+
+
+ Certain development processes run autonomously with minimal human oversight.
+
+ **Characteristics:**
+ - Human intervention rates below 15%
+ - Robust monitoring and automated rollback systems
+ - Measurable ROI from automation initiatives
+ - Advanced context awareness and learning loops
+
+
+
+
+### 2. Evaluate Readiness Across Four Key Dimensions
+
+Assess your team's strengths and potential risks across these critical areas:
+
+
+
+ **Key Questions:**
+ - Do our development tools integrate reliably?
+ - Can we measure AI effectiveness and impact?
+ - Are security policies compatible with AI workflows?
+
+ **🟢 Green Flags:**
+ - Stable tool integrations with >99.5% uptime
+ - Comprehensive monitoring and observability
+ - Security policies that support AI tool usage
+ - Automated testing and deployment pipelines
+
+ **🔴 Red Flags:**
+ - Frequent integration breakdowns
+ - No performance tracking or metrics
+ - Restrictive security policies blocking AI tools
+ - Manual deployment processes
+
+
+
+
+ **Key Questions:**
+ - Are our development workflows consistent and documented?
+ - Do we have quality gates and review processes?
+ - Can we reproduce builds and deployments reliably?
+
+ **🟢 Green Flags:**
+ - Clear coding standards and style guides
+ - Automated CI/CD with quality gates
+ - Documented, repeatable processes
+ - Consistent code review practices
+
+ **🔴 Red Flags:**
+ - Inconsistent code reviews
+ - Ad-hoc deployment processes
+ - "Works on my machine" culture
+ - Undocumented tribal knowledge
+
+
+
+
+ **Key Questions:**
+ - Are developers open to adopting new AI-powered workflows?
+ - How does the team handle experimentation and failure?
+ - Do team members collaborate effectively on new initiatives?
+
+ **🟢 Green Flags:**
+ - High curiosity and willingness to experiment
+ - Collaborative problem-solving culture
+ - Constructive feedback and learning mindset
+ - Active knowledge sharing practices
+
+**🔴 Red Flags:**
+
+- Strong resistance to workflow changes
+- Blame culture around mistakes
+- Perfectionism blocking experimentation
+- Siloed work with minimal collaboration
+
+
+
+
+ **Key Questions:**
+ - Does leadership provide budget and resources for AI initiatives?
+ - Is there tolerance for experimentation and learning?
+ - Are expectations realistic for ROI timelines?
+
+ **🟢 Green Flags:**
+ - Executive buy-in and strategic alignment
+ - Dedicated budget for training and tools
+ - 3-6 month ROI expectations
+ - Support for calculated risk-taking
+
+ **🔴 Red Flags:**
+ - Pressure for immediate ROI (weeks)
+ - No allocated budget for AI initiatives
+ - High risk aversion culture
+ - Lack of leadership engagement
+
+
+
+
+### 3. Critical Warning Signs
+
+
+ **Stop and address these issues before scaling Continuous AI:**
+
+
+
+
+ - Builds breaking regularly (>5% failure rate)
+ - Unstable deployments or rollback frequency >10%
+ - No monitoring or observability systems
+ - Critical security policy conflicts
+
+
+
+
+ - More than 30% of team opposed to AI tools
+ - No established feedback or learning culture
+ - History of failed automation initiatives
+ - Resistance to changing existing workflows
+
+
+
+
+ - Inconsistent development workflows
+ - No quality gates or review processes
+ - Manual deployment and testing processes
+ - Lack of documentation and standards
+
+
+
+
+ - Leadership expecting ROI in weeks vs months
+ - No allocated budget for AI initiatives
+ - High pressure, low experimentation tolerance
+ - Lack of strategic alignment on AI adoption
+
+
+
+
+### 4. Implementation Roadmap
+
+Based on your assessment results, follow this step-by-step approach:
+
+
+
+ Document current performance across key areas:
+
+ - Development velocity (story
+ points, cycle time)
+ - Code quality metrics (bug rates, technical debt)
+ - Review times and approval rates
+ - Developer satisfaction and productivity
+ scores
+
+
+
+
+ Choose one high-impact, low-risk workflow to automate first:
+
+ - **Code Review:** Automated analysis and suggestions
+ - **Documentation:** Auto-generated API docs and README updates
+ - **Testing:** Automated test generation and maintenance
+ - **Refactoring:** Systematic code improvement suggestions
+
+
+
+
+ Create and document consistent practices:
+ - AI tool selection and configuration guidelines
+
+ - Prompting standards and best practices
+
+ - Quality gates and review processes
+
+ - Security and compliance requirements
+
+
+
+
+ Run controlled experiments with success criteria:
+ - Start with 2-3 team members for 2-4 weeks
+ - Track metrics against baseline performance
+ - Gather qualitative feedback on developer experience
+ - Document lessons learned and optimization opportunities
+
+
+
+
+ Expand successful pilots across the organization:
+ - Roll out to additional team members gradually
+ - Implement monitoring and alerting systems
+ - Establish feedback loops for continuous improvement
+ - Plan next automation targets based on results
+
+
+
+
+
+
+ Comprehensive explanation of maturity levels and organizational readiness
+ factors
+
+
+
+ Technical implementation details and best practices for Continuous AI
+ workflows
+
+
+
+## Quick Assessment Checklist
+
+
+ **Ready to get started?** Use this quick checklist to gauge your immediate
+ readiness:
+
+
+**Technical Foundation (Score: \_\_\_/4)**
+
+- Stable CI/CD pipelines with \<5% failure rate
+- Monitoring and observability systems in place
+- Security policies support AI tool integration
+- Development environment standardization
+
+**Process Maturity (Score: \_\_\_/4)**
+
+- Documented coding standards and review processes
+- Consistent deployment and rollback procedures
+- Quality gates and automated testing
+- Regular retrospectives and process improvement
+
+**Team Culture (Score: \_\_\_/4)**
+
+- \<30% resistance to AI tool adoption
+- Active experimentation and learning culture
+- Collaborative problem-solving approach
+- Constructive feedback and knowledge sharing
+
+**Organizational Support (Score: \_\_\_/4)**
+
+- Leadership buy-in and strategic alignment
+- Dedicated budget for AI initiatives and training
+- 3-6 month ROI expectations (not weeks)
+- Support for calculated risk-taking
+
+---
+
+**Overall Readiness Score: \_\_\_/16**
+
+- **12-16:** Ready to begin Continuous AI implementation
+- **8-11:** Address gaps in 1-2 areas before scaling
+- **\<8:** Focus on foundational improvements first
diff --git a/docs/guides/instinct.mdx b/docs/guides/instinct.mdx
index 19f9bf7a1..ac933c33c 100644
--- a/docs/guides/instinct.mdx
+++ b/docs/guides/instinct.mdx
@@ -9,7 +9,7 @@ description: "Learn how to run Instinct, Continue's leading open Next Edit model
[HuggingFace model card](https://huggingface.co/continuedev/instinct).
-We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev).
+We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev/instinct/).
@@ -17,7 +17,7 @@ We recently released Instinct, a state-of-the-art open Next Edit model. Robustly
### 1. Install Ollama
-If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx).
+If you haven't already installed Ollama, see our guide [here](./ollama-guide).
### 2. Download Instinct
diff --git a/docs/guides/netlify-mcp-continuous-deployment.mdx b/docs/guides/netlify-mcp-continuous-deployment.mdx
new file mode 100644
index 000000000..b16c8d5f3
--- /dev/null
+++ b/docs/guides/netlify-mcp-continuous-deployment.mdx
@@ -0,0 +1,614 @@
+---
+title: "Netlify Performance Optimization Cookbook"
+description: "Optimize web performance with A/B testing, automated monitoring, and data-driven improvements using Netlify MCP and Continue."
+sidebarTitle: "Using Netlify MCP for Performance Optimization"
+---
+
+
+ Use AI to automatically monitor performance metrics, run A/B tests between
+ branches, and get actionable optimization suggestions based on real user data
+ from Netlify Analytics
+
+
+
+ **Did You Know?** Netlify is more than just static hosting! It offers:
+ - [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches
+ - [Analytics](https://docs.netlify.com/analytics/get-started/) with Core Web Vitals tracking
+ - [Edge Functions](https://docs.netlify.com/edge-functions/overview/) for personalization at the edge
+ - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) ecosystem with 100+ integrations
+ - [Forms](https://docs.netlify.com/forms/setup/) with built-in spam protection
+ - [Identity](https://docs.netlify.com/visitor-access/identity/) for user authentication
+ - [Large Media](https://docs.netlify.com/large-media/overview/) for Git LFS support
+
+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 [A/B tests](https://docs.netlify.com/site-deploys/split-testing/) between branches to measure performance impact
+- Monitor [Core Web Vitals](https://docs.netlify.com/analytics/get-started/#core-web-vitals) and build performance metrics
+- Automatically block deploys that degrade performance using [Deploy Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts)
+- Optimize build times with [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) and bundle sizes with AI assistance
+
+## Prerequisites
+
+- GitHub repository with a web project
+- [Netlify account](https://netlify.com) (free tier works)
+- Node.js 22+ installed (required for Netlify)
+- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`)
+- [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) configured
+- [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) (recommended)
+
+## Quick Setup
+
+
+
+ ```bash
+ npm i -g @continuedev/cli
+ ```
+
+
+
+ 1. Install Netlify CLI: `npm i -g netlify-cli` 2. Authenticate with Netlify:
+ `netlify login` 3. Visit [Netlify MCP on Continue
+ Hub](https://hub.continue.dev/netlify/netlify-mcp) 4. Follow the configuration
+ instructions for your editor
+
+
+
+ Install the [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) bundle for best practices:
+
+ 1. Visit the bundle page on Continue Hub
+ 2. Click **"Install Rules"**
+ 3. Rules automatically apply to your agent
+
+
+
+
+ Test the connection with cn CLI:
+
+ ```bash
+ cn
+ # Then in TUI mode:
+ "Check my Netlify auth and list sites"
+ ```
+
+
+
+
+
+ The Netlify Development Rules bundle includes guardrails for: - Proper
+ `.gitignore` configuration - Function structure and placement - Edge function
+ constraints - Local development best practices
+
+
+## Performance Optimization Steps
+
+### Step 1: Baseline Performance Metrics
+
+Establish your current performance baseline using cn CLI:
+
+```bash
+# Start cn in TUI mode
+cn
+
+# Then ask:
+"Show my site's Core Web Vitals and build times"
+```
+
+
+ **Test in Plan Mode First**: Before making performance optimizations that
+ might affect your site, 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. For example: `"Set up
+ A/B testing between main and feature branch with performance monitoring"`
+
+
+
+
+ Netlify automatically tracks:
+ - **Build Performance**: Compile times, cache
+ hits
+ - **Runtime Performance**: Core Web Vitals, Time to Interactive
+ - **Resource Usage**: Bandwidth, function execution times
+
+
+
+### Step 2: A/B Test Branch Performance
+
+Compare performance between branches:
+
+```bash
+# In cn TUI mode:
+"Set up A/B test between main and feature branch on Netlify:
+- Split traffic 50/50 between branches
+- Track Core Web Vitals for each variant
+- Monitor conversion metrics and bounce rate
+- Enable analytics to measure performance impact
+- Configure cookie-based visitor persistence
+- Set test duration for 1000 unique visitors
+- Auto-conclude test when statistical significance reached
+Report winner based on performance + conversion metrics"
+```
+
+
+ **Enhanced Analytics**: Combine Netlify's A/B testing with PostHog session
+ recordings to understand not just which variant performs better, but why users
+ behave differently. See our [PostHog session analysis
+ guide](/guides/posthog-github-continuous-ai) to set up session tracking and
+ create a complete continuous AI analytics workflow.
+
+
+### Step 3: Advanced Build Optimization with Netlify
+
+Leverage Netlify's powerful build features to dramatically reduce build times:
+
+```bash
+# In cn TUI mode:
+"Optimize my Netlify build performance using these features:
+
+1. Enable Netlify Cache Plugin for dependency caching
+ - Configure @netlify/plugin-cache for node_modules
+ - Set up custom cache directories for .next/cache or .nuxt
+ - Enable Gatsby's incremental builds if applicable
+
+2. Set up Build Plugins from Netlify's ecosystem:
+ - Install @netlify/plugin-lighthouse for performance monitoring
+ - Add netlify-plugin-checklinks to prevent broken links
+ - Configure netlify-plugin-submit-sitemap for SEO
+
+3. Implement Conditional Builds:
+ - Skip builds when only docs change (ignore: /docs/**)
+ - Use build.ignore script for custom logic
+ - Set up monorepo-specific build triggers
+
+4. Configure concurrent builds for monorepos
+ - Set base directory per package
+ - Use pnpm workspaces or yarn workspaces
+
+Show me the netlify.toml configuration and explain each optimization"
+```
+
+
+ **Netlify Build Features You're Getting**:
+ - [Build Caching](https://docs.netlify.com/configure-builds/build-caching/) - Persist dependencies between builds
+ - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) - Extend build process with 100+ plugins
+ - [Conditional Builds](https://docs.netlify.com/configure-builds/ignore-builds/) - Skip unnecessary builds
+ - [Monorepo Support](https://docs.netlify.com/configure-builds/monorepos/) - Optimize multi-package repos
+
+These features can reduce build times by 50-70% for most projects!
+
+
+
+
+ **Discover more optimization prompts!** The Netlify community has documented dozens of build optimization strategies in their [Support Guide: How can I optimize my Netlify build time](https://answers.netlify.com/t/support-guide-how-can-i-optimize-my-netlify-build-time/3907).
+
+ Use this guide as inspiration for cn CLI prompts not covered in this cookbook, such as:
+ - `"Configure my builds to skip Dependabot PRs automatically"`
+ - `"Set up custom ignore patterns for documentation-only changes"`
+ - `"Optimize my Contentful webhooks to prevent duplicate builds"`
+ - `"Show me how to use build hooks instead of automatic git triggers"`
+ - `"Help me choose between Astro and Hugo based on build performance"`
+
+ The community guide contains real-world scenarios that you can turn into AI-assisted solutions - just describe what you want to achieve and let cn CLI handle the implementation!
+
+
+### Step 4: Bundle Analysis with Netlify's Built-in Tools
+
+Use Netlify's bundle analyzer and optimization features:
+
+```bash
+# In cn TUI mode:
+"Analyze and optimize my bundle using Netlify's tools:
+
+1. Enable Netlify Bundle Analyzer:
+ - Add @netlify/plugin-bundle-analyzer to plugins
+ - Configure size thresholds in netlify.toml
+ - Generate visual bundle reports
+
+2. Set up Asset Optimization:
+ - Enable automatic JS minification
+ - Configure CSS optimization
+ - Turn on HTML minification
+ - Set up image processing pipeline
+
+3. Implement Smart Code Splitting:
+ - Analyze current chunks with the bundle analyzer
+ - Identify components over 50KB for splitting
+ - Configure webpack/vite for optimal chunking
+ - Set up route-based code splitting
+
+4. Configure Netlify's CDN for optimal delivery:
+ - Set cache headers for static assets
+ - Enable Brotli compression
+ - Configure edge caching rules
+
+Generate a full report with before/after bundle sizes"
+```
+
+
+
+ **Features Available Through Netlify MCP**:
+ - [Bundle
+ Analyzer](https://docs.netlify.com/configure-builds/build-plugins/bundle-analyzer/): Visualize your JavaScript bundles
+ - [Asset
+ Optimization](https://docs.netlify.com/configure-builds/post-processing/):
+ Automatic minification and compression
+ - [Edge
+ Network](https://docs.netlify.com/platform/edge-network/): Global CDN with
+ smart caching
+ - [Deploy
+ Previews](https://docs.netlify.com/site-deploys/deploy-previews/): Test
+ optimizations before production
+
+
+
+### Step 5: Image Optimization
+
+Optimize images for better performance:
+
+```bash
+# In cn TUI mode:
+"Set up Cloudinary image optimization for my Netlify site:
+- Install @cloudinary/netlify-plugin via MCP
+- Auto-convert images to WebP with fallbacks
+- Generate responsive sizes (320w, 640w, 1024w, 1920w)
+- Add lazy loading for all images
+- Configure blur-up placeholders
+- Update netlify.toml with Cloudinary settings
+Target: Reduce image payload by 60-80% and improve LCP"
+```
+
+## Continuous Performance Monitoring
+
+### Step 6: Performance Budget Enforcement with Lighthouse CI
+
+Set and enforce performance budgets with automated testing:
+
+```bash
+# In cn TUI mode:
+"Set up Lighthouse CI with performance budgets for my Netlify site:
+
+Requirements:
+- LCP must be < 2.5 seconds
+- JavaScript bundle must be < 200KB
+- Total size < 500KB
+- Performance score >= 90
+
+Setup needed:
+1. Install @lhci/cli and @netlify/plugin-lighthouse
+2. Create lighthouserc.js with these budget assertions
+3. Configure netlify.toml to run checks on all deploys
+4. Add GitHub status checks to block PRs that exceed budgets
+5. Create performance dashboard at /lighthouse-reports
+
+Please configure the complete Lighthouse CI setup with these budgets."
+```
+
+
+ This comprehensive setup will automatically test every deploy preview and
+ production deployment, blocking any changes that violate your performance
+ budgets.
+
+
+### Step 7: Real User Monitoring with Netlify Analytics
+
+Leverage Netlify's built-in analytics and integrate advanced RUM solutions:
+
+```bash
+# In cn TUI mode:
+"Set up comprehensive Real User Monitoring for my Netlify site:
+
+1. Configure Netlify Analytics Pro (requires Pro account):
+ - Set up server-side analytics (no JS required)
+ - Track Core Web Vitals (LCP, FID, CLS, INP)
+ - Monitor top pages by performance score
+ - Create custom performance alerts
+ - Configure weekly performance reports
+
+2. Integrate Web Vitals tracking:
+ - Install web-vitals library for detailed metrics
+ - Send metrics to Netlify Functions endpoint
+ - Store performance data in Netlify Blobs
+ - Create performance dashboard at /metrics
+
+3. Set up Performance Alerts:
+ - Alert when P75 LCP > 3 seconds
+ - Notify if CLS increases by 20%
+ - Monitor JavaScript error rates
+ - Track 404s and broken resources
+ - Send alerts to Slack via Netlify Functions
+
+4. Configure Geographic Performance Monitoring:
+ - Use Netlify Edge Functions to track region-specific metrics
+ - Identify slow regions with Edge geo data
+ - Compare performance across CDN nodes
+ - Optimize edge caching for slow regions
+
+5. Create Custom Performance Dashboard:
+ - Build dashboard page using Netlify Functions
+ - Display real-time Core Web Vitals
+ - Show performance trends over time
+ - Include browser and device breakdowns
+
+Show me the complete implementation with all code and configurations"
+```
+
+
+ **Note**: Netlify Analytics Pro requires a paid Netlify Pro account ($19/month
+ per site). The prompt above assumes you have this plan. For free tier users,
+ focus on steps 2-5 which use Netlify Functions and Edge Functions to build
+ custom analytics.
+
+
+
+ **Netlify Analytics Advantages**:
+ - [Server-side Analytics](https://docs.netlify.com/analytics/get-started/) - No client-side JavaScript needed
+ - [Core Web Vitals](https://docs.netlify.com/analytics/core-web-vitals/) - Automatic tracking of Google's metrics
+ - [Custom Metrics](https://docs.netlify.com/functions/logs/) - Track any metric via Functions
+ - [Edge Insights](https://docs.netlify.com/edge-functions/overview/#geolocation) - Geographic performance data
+ - [No Cookie Banner Required](https://docs.netlify.com/analytics/get-started/#privacy) - GDPR compliant by default
+
+Unlike Google Analytics, Netlify Analytics:
+
+- Doesn't slow down your site (server-side)
+- Captures 100% of traffic (no ad blockers)
+- Respects user privacy (no cookies)
+- Shows bot traffic separately
+
+
+
+
+ **Pro Tip**
+ Combine Netlify Analytics with Edge Functions to create a
+ powerful RUM solution that:
+ - Tracks performance by user segment
+ - A/B tests
+ performance optimizations
+ - Personalizes content based on connection speed
+ - Automatically serves lighter assets to slow connections
+
+
+
+## Automated Performance Checks
+
+### GitHub Actions Performance Guard
+
+Block PRs that degrade performance:
+
+```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: "22"
+
+ - name: Deploy and Test Performance
+ id: perf
+ env:
+ NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
+ NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
+ run: |
+ npx @continuedev/cli@latest << 'EOF'
+ Deploy PR preview and run Lighthouse.
+ Compare scores with main branch.
+ Output JSON with score deltas.
+ EOF > performance.json
+
+ - name: Comment Performance Results
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const fs = require('fs');
+ const perf = JSON.parse(fs.readFileSync('performance.json'));
+
+ const emoji = perf.score_delta < -10 ? '🔴' :
+ perf.score_delta < 0 ? '🟡' : '🟢';
+
+ const comment = `## ${emoji} Performance Impact
+
+ | Metric | Main | PR | Delta |
+ |--------|------|----|---------|
+ | Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} |
+ | LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s |
+ | Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB |
+
+ ${perf.score_delta < -10 ? '⚠️ **This PR significantly degrades performance. Please optimize before merging.**' : ''}
+
+ [View Full Report](${perf.report_url})`;
+
+ github.rest.issues.createComment({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ body: comment
+ });
+
+ // Fail check if performance degrades significantly
+ if (perf.score_delta < -10) {
+ core.setFailed('Performance degraded by more than 10 points');
+ }
+```
+
+
+ This workflow will: - **Block merge** if performance score drops >10 points -
+ **Warn** on any performance regression - **Celebrate** improvements with green
+ indicators
+
+
+## Performance Testing Locally
+
+### Step 8: Local Performance Testing
+
+Test performance before deploying:
+
+```bash
+# In cn TUI mode:
+"Run production build and measure bundle sizes"
+```
+
+### Step 9: Pre-commit Performance Checks
+
+Prevent performance regressions before they happen:
+
+```bash
+# In cn TUI mode:
+"Add pre-commit hooks for bundle size limits"
+```
+
+## Performance Troubleshooting
+
+### Debug Performance Issues
+
+Identify and fix performance bottlenecks:
+
+```bash
+# In cn TUI mode:
+"Why did my performance score drop?"
+```
+
+### Performance Issue Quick Fixes
+
+| Issue | Quick Fix Command (in cn TUI) |
+| ------------- | --------------------------------- |
+| Slow LCP | `"Preload critical resources"` |
+| High CLS | `"Add size attributes to images"` |
+| Large bundles | `"Implement code splitting"` |
+| Slow builds | `"Enable build caching"` |
+| Poor caching | `"Configure cache headers"` |
+
+## What You've Accomplished
+
+
+
+ You've built an AI-powered performance optimization system that:
+ - Automatically monitors Core Web Vitals
+ - Runs A/B tests between branches
+ - Blocks deployments that degrade performance
+ - Provides actionable optimization
+ suggestions
+
+
+
+## Discover Netlify's Hidden Performance Gems
+
+Features many developers don't know Netlify offers:
+
+
+
+
+ **[Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)**
+ - Run code at the edge, closer to users
+ - Transform responses on-the-fly
+ - A/B test at the edge level
+ - Personalize content without client-side JS
+
+
+
+
+
+ **[Netlify Graph](https://docs.netlify.com/graph/overview/)**
+ - Unified GraphQL gateway for all your APIs
+ - Automatic TypeScript generation
+ - Built-in authentication handling
+ - Zero client-side API keys needed
+
+
+
+
+ **[On-Demand
+ Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)** -
+ Generate pages only when requested - Cache dynamically generated content -
+ Perfect for large sites (10k+ pages) - Reduce build times dramatically
+
+
+
+ **[Background Functions](https://docs.netlify.com/functions/background-functions/)**
+ - Run tasks up to 15 minutes
+ - Process webhooks asynchronously
+ - Handle heavy computations
+ - No timeout worries
+
+
+
+```bash
+# Try these advanced features in cn TUI mode:
+"Show me how to use Netlify Edge Functions for geo-based personalization"
+"Set up On-Demand Builders for my blog with 5000 posts"
+"Configure Background Functions for image processing"
+```
+
+## Performance Best Practices
+
+The Netlify Performance Rules enforce:
+
+
+
+ - Dependency caching enabled
+ - Parallel builds when possible
+ - Incremental compilation
+ - Smart cache invalidation
+
+
+
+ - Automatic image optimization
+ - Efficient resource hints (preload, prefetch)
+ - Optimal cache headers
+ - CDN configuration
+
+
+
+ - Performance budgets enforced
+ - Core Web Vitals tracking
+ - Real user monitoring
+ - Automated alerts
+
+
+
+## Advanced Performance Strategies
+
+### Progressive Enhancement
+
+```bash
+# In cn TUI mode:
+"Implement progressive enhancement with basic HTML first"
+```
+
+### Multi-variant Testing
+
+```bash
+# In cn TUI mode:
+"Test 3 bundle strategies and auto-select winner"
+```
+
+### Predictive Prefetching
+
+```bash
+# In cn TUI mode:
+"Analyze navigation patterns and prefetch next pages"
+```
+
+## Next Steps
+
+- Install [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) from Continue Hub
+- Set up [Performance Monitoring](https://docs.netlify.com/analytics/get-started/)
+- Configure [A/B Testing](https://docs.netlify.com/split-testing/overview/)
+- Join the [Continue Discord](https://discord.gg/continue) for support
+
+## Resources
+
+- [Netlify MCP on Continue Hub](https://hub.continue.dev/netlify/netlify-mcp)
+- [Core Web Vitals Guide](https://web.dev/vitals/)
+- [Netlify Analytics Documentation](https://docs.netlify.com/analytics/)
+- [Continue Performance Guides](https://docs.continue.dev/guides)
diff --git a/docs/guides/ollama-guide.mdx b/docs/guides/ollama-guide.mdx
index e3fa3516a..724afa1ef 100644
--- a/docs/guides/ollama-guide.mdx
+++ b/docs/guides/ollama-guide.mdx
@@ -190,9 +190,12 @@ models:
#### If Agent Mode Shows "Not Supported"
+
+
1. First, add `capabilities: [tool_use]` to your model config
2. If you still get errors, the model may not actually support tools despite documentation
3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral)
+4. Alternatively, you can turn on [System Message tools](/features/agent/model-setup#how-system-message-tools-work)
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details.
diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx
index 3a609ac15..3ca80dae0 100644
--- a/docs/guides/overview.mdx
+++ b/docs/guides/overview.mdx
@@ -13,6 +13,15 @@ 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
+
+## MCP Integration Cookbooks
+
+Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue:
+
+- [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
+- [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers
## What Advanced Tutorials Are Available
diff --git a/docs/guides/posthog-github-continuous-ai.mdx b/docs/guides/posthog-github-continuous-ai.mdx
new file mode 100644
index 000000000..1742d6011
--- /dev/null
+++ b/docs/guides/posthog-github-continuous-ai.mdx
@@ -0,0 +1,517 @@
+---
+title: "Building a Continuous AI Workflow with PostHog and GitHub"
+description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically."
+sidebarTitle: "PostHog Session Analysis with Continue CLI"
+---
+
+
+ A fully automated workflow that uses Continue CLI to fetch PostHog session
+ data, analyze user experience issues with AI, and automatically create GitHub
+ issues with specific technical recommendations
+
+
+## Prerequisites
+
+Before starting, ensure you have:
+
+- GitHub repository where you want to create issues
+- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)**
+- Node.js 18+ installed locally
+- Continue CLI account with **active credits** (required for API usage)
+
+
+
+ ```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 will securely store your API keys as secrets that can be referenced in prompts.
+
+
+
+
+ Continue CLI handles the complex API interactions - you just need to provide
+ the right prompts!
+
+
+## Step 1: Set Up Your Credentials
+
+First, you'll need to gather your PostHog and GitHub API credentials and add them as secrets in Continue CLI.
+
+
+
+ You'll need a **Personal API Key** (not a Project API key) to access session recordings:
+
+ 1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog
+ 2. Click **+ Create a personal API Key**
+ 3. Name it "Continue CLI Session Analysis"
+ 4. Select these scopes:
+ - `session_recording:read` - **Required** for accessing session data
+ - `insight:read`
+ - `query:read`
+ - `session_recording_playlist:read`
+ 5. Copy the key immediately (you won't see it again!)
+ 6. Note your **Project ID** from your PostHog project settings
+ 7. Note your PostHog host URL (e.g., `https://us.posthog.com` or your custom domain)
+ 8. You'll also need your POSTHOG_AUTH_HEADER value, which is simply `Bearer YOUR_API_KEY`
+
+
+ **Find Your Project Details**: Your Project ID is in your PostHog URL:
+ `https://app.posthog.com/project/YOUR_PROJECT_ID`
+
+
+
+
+ You'll need a **Personal Access Token** to create issues in your GitHub repository:
+
+ 1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new)
+ 2. Click **"Generate new token (classic)"**
+ 3. Name it "Continue CLI PostHog Analysis"
+ 4. Select these scopes:
+ - `repo` (or just `public_repo` if your repository is public)
+ - `issues:write` - **Required** for creating issues
+ 5. Copy the token immediately
+
+
+
+
+### Add Secrets to Continue CLI
+
+To add environment variables to your Continue Hub account:
+
+1. Go to the [Continue Hub](https://hub.continue.dev)
+2. Sign in to your account
+3. Navigate to your user settings
+4. Look for the "Secrets" section
+5. Add your variables there (like POSTHOG_API_KEY, POSTHOG_PROJECT_ID,
+ POSTHOG_HOST,GITHUB_PAT, etc.)
+
+These environment variables will then be securely stored and available for use in
+your Continue workflows.
+
+## PostHog GitHub Continuous AI Workflow Options
+
+
+ Skip the manual setup and use our pre-built PostHog GitHub agent that includes
+ optimized prompts, rules, and the PostHog MCP for more consistent results.
+
+
+After completing **Step 1** below, you have two paths to get started:
+
+
+
+ **Perfect for:** Immediate results with optimized prompts and built-in debugging
+
+
+
+ Visit the [PostHog GitHub Continuous AI Agent](https://hub.continue.dev/continuedev/awesome-models-posthog-gh) on Continue Hub and click **"Install Agent"**
+
+ This agent includes:
+ - **Optimized prompts** for PostHog analysis and GitHub issue creation
+ - **Built-in rules** for consistent formatting and error handling
+ - **PostHog MCP** for more reliable API interactions
+
+
+
+ The agent uses these Hub resources automatically:
+ - **Environment Variables**: [bekahhw/env-vars](https://hub.continue.dev/bekahhw/env-vars)
+ - **Analysis Rules**: [bekah-hawrot-weigel/posthog-github-continuous-ai-rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules)
+ - **Analysis Prompt**: [continuedev/posthog-analysis](https://hub.continue.dev/continuedev/posthog-analysis)
+ - **Issue Creation Prompt**: [continuedev/github-issues](https://hub.continue.dev/continuedev/github-issues)
+
+
+
+ Navigate to your project directory and run:
+ ```bash
+ cn "Give me my PostHog Session data and create GitHub issues based on the problems."
+ ```
+
+ That's it! The agent handles everything automatically.
+
+
+
+
+ **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the PostHog MCP integration and pre-tested prompts.
+
+
+
+
+
+ **Perfect for:** Learning the process and customizing prompts.
+
+ Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically.
+
+### Run the PostHog Analysis
+
+Use this prompt with Continue CLI to fetch and analyze your PostHog sessions:
+
+```bash
+cn -p "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."
+```
+
+### Create GitHub Issues from PostHog Analysis
+
+Now use Continue CLI to create GitHub issues from your analysis results:
+
+```bash
+cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
+
+Use these details from my secrets:
+- GITHUB_PAT: My GitHub Personal Access Token
+- Repository: Extract from git remote or ask me to specify
+
+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.
+"
+```
+
+
+
+
+
+ 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 below) The agent will automatically detect and use your
+ configuration.
+
+
+
+---
+
+
+**Repository Labels Required**: Make sure your GitHub repository has these labels:
+- `bug`, `enhancement`
+- `high-priority`, `medium-priority`, `low-priority`
+- `user-experience`, `automated`
+
+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
+
+
+## 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
+
+After completing this guide, you have a complete **Continuous AI system** that:
+
+- **Monitors user experience** - Automatically fetches and analyzes PostHog session data
+
+- **Identifies problems intelligently** - Uses AI to spot patterns and technical issues
+
+- **Creates actionable tasks** - Generates GitHub issues with specific recommendations
+
+- **Runs autonomously** - Operates daily without manual intervention using GitHub Actions
+
+- **Scales with your team** - Handles growing amounts of session data automatically
+
+
+ Your system now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine analysis tasks with human oversight through GitHub issue
+ review and prioritization.
+
+
+## Security Best Practices
+
+
+
+ **Protect Your API Keys:**
+ - Store all credentials as GitHub Secrets, never in
+ code
+ - Use Continue CLI's secure secret storage
+ - Limit token scopes to minimum required permissions
+ - Rotate API keys regularly (every 90 days recommended)
+ - Monitor token usage for unusual activity
+
+
+
+## Advanced Prompts
+
+Consider enhancing your workflow with these advanced Continue CLI prompts:
+
+
+
+ "Analyze PostHog performance metrics alongside session recordings to
+ identify slow page loads affecting user experience"
+
+
+ "Cross-reference JavaScript console errors with user actions to identify the
+ root cause of UX issues"
+
+
+ "Analyze how PostHog feature flags impact user behavior in session
+ recordings"
+
+
+ "Create Slack alerts when critical UX issues are detected in PostHog
+ sessions"
+
+
+
+## Next Steps
+
+1. **Monitor your first issues** - Review the GitHub issues created and implement fixes
+2. **Measure impact** - Track how resolved issues improve PostHog metrics
+3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality
+4. **Scale the system** - Add more data sources or create specialized analysis workflows
diff --git a/docs/guides/running-continue-without-internet.mdx b/docs/guides/running-continue-without-internet.mdx
index 9217d66da..98e80b974 100644
--- a/docs/guides/running-continue-without-internet.mdx
+++ b/docs/guides/running-continue-without-internet.mdx
@@ -3,7 +3,7 @@ title: "How to Run Continue Without Internet"
description: "Learn how to set up Continue for air-gapped or offline environments using local models, including steps to disable telemetry and configure local model providers"
---
-1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
-2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry).
-3. Also in `config.json`, set the default model to a local model. You can available options [here](/customization/models#openai).
-4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect.
+1. Download the latest .vsix file from the [GitHub Releases page](https://github.com/continuedev/continue/releases) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
+2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](https://docs.continue.dev/reference/telemetry).
+3. In your `config.yaml` file (or through the Continue UI), set the default model to a local model. You can find available local model options [here](https://docs.continue.dev/reference/model-providers/ollama).
+4. Restart VS Code to ensure that the changes to `config.yaml` take effect.
diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx
new file mode 100644
index 000000000..6705fd15c
--- /dev/null
+++ b/docs/guides/snyk-mcp-continue-cookbook.mdx
@@ -0,0 +1,404 @@
+---
+title: "Automated Security Scanning with Snyk MCP and Continue"
+description: "Set up an AI-powered security workflow that automatically scans your code, dependencies, infrastructure, and containers using natural language commands."
+sidebarTitle: "Snyk Security Scanning with Continue"
+---
+
+
+ An automated security scanning system that uses Continue's AI agent with Snyk
+ MCP to identify vulnerabilities in code, dependencies, infrastructure, and
+ containers - 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 18+ installed locally
+- [Snyk account](https://snyk.io/) (free tier works)
+- A local project to scan for vulnerabilities
+
+
+
+ Visit the [Snyk MCP on Continue Hub](https://hub.continue.dev/snyk/snyk-mcp) and click **Install** to add it to your Continue account.
+
+ This will add Snyk MCP to your agent's available tools. The Hub listing automatically configures the MCP command:
+ ```bash
+ npx -y snyk@latest mcp -t stdio
+ ```
+
+
+ **Alternative installation methods:**
+ 1. **Quick CLI install**: `cn -p --mcp snyk/snyk-mcp`
+ 2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
+
+ Once installed, Snyk MCP tools become available to your Continue agent for all prompts.
+
+
+
+ The MCP will request authentication and folder trust permissions when first used.
+ This is handled automatically by the Continue agent.
+
+
+
+
+
+ Install the [Snyk Secure-at-Inception rules](https://hub.continue.dev/snyk/secure-at-inception) from the Hub to enable automatic security scanning.
+
+ **How to add rules to your agent:**
+ 1. Visit the rules link above and click **Install**
+ 2. The rules will be added to your agent configuration automatically
+ 3. Rules apply globally to all your Continue sessions
+
+ These rules configure your agent to:
+ - **Run [SAST](https://snyk.io/learn/application-security/sast/) scans** on newly generated or modified code
+ - **Check dependencies** when adding or updating packages
+ - **Auto-fix issues** using Snyk's recommendations, then rescan
+
+
+
+
+ Use this prompt with your Continue agent to set up authentication:
+
+ ```
+ Check Snyk auth status. If not authenticated, authenticate me and confirm my org context.
+ ```
+
+ Or use the Continue CLI:
+ ```bash
+ cn -p "Check Snyk auth status. If not authenticated, authenticate me and confirm my org context."
+ ```
+
+
+ A browser window will open for Snyk login. After authenticating, approve
+ the request to trust your project folder when prompted.
+
+
+
+
+
+## Security Scanning Recipes
+
+Now you can use natural language prompts to run comprehensive security scans. The Continue agent automatically calls the appropriate Snyk 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 one-off commands
+
+ **Test in Plan Mode First**: Before running security scans 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. For example: `"Run a
+ Snyk Code scan and fix the top 3 issues"`
+
+
+### Code Vulnerability Scanning ([SAST](https://snyk.io/learn/application-security/sast/))
+
+
+ Scan your source code for security vulnerabilities and code quality issues.
+
+**Example prompt:**
+```
+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.
+```
+
+**Using Continue CLI:**
+```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."
+```
+
+
+
+### Dependency Scanning ([SCA](https://snyk.io/learn/software-composition-analysis-sca/))
+
+
+ Check open source dependencies for known vulnerabilities.
+
+**Example prompt:**
+```
+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).
+```
+
+**Using Continue CLI:**
+```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)."
+```
+
+
+
+### Infrastructure as Code ([IaC](https://snyk.io/learn/infrastructure-as-code-iac/))
+
+
+ Scan Terraform, CloudFormation, and Kubernetes configs for misconfigurations.
+
+**Example prompt:**
+```
+Scan ./infra with Snyk IaC. Report high/critical misconfigs
+with exact files/lines. Provide code changes and re-scan to confirm.
+```
+
+**Using Continue CLI:**
+```bash
+cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm."
+```
+
+
+
+### Container Scanning
+
+
+ Analyze Docker images for vulnerabilities in base images and packages.
+
+**Example prompt:**
+```
+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).
+```
+
+**Using Continue CLI:**
+```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)."
+```
+
+
+
+### Pull Request Scanning
+
+
+ Focus scanning on modified files to catch issues before merging.
+
+**Example prompt:**
+```
+Scan only files changed since origin/main with Snyk Code.
+Block if new high issues would be introduced. Show deltas.
+```
+
+**Using Continue CLI:**
+```bash
+cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas."
+```
+
+
+
+### Security Learning
+
+
+ Access security education resources based on identified vulnerabilities ([CWE](https://cwe.mitre.org/)).
+
+**Example prompt:**
+```
+Open Snyk Learn lessons related to the top CWE(s) from this scan.
+```
+
+**Using Continue CLI:**
+```bash
+cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan."
+```
+
+
+
+## Continuous Security with GitHub Actions
+
+This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline using Continue CLI in headless mode (`cn -p`) with Snyk MCP.
+
+### 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
+
+Create `.github/workflows/snyk-security.yml` in your repository:
+
+```yaml
+name: Security Scanning with Snyk MCP
+
+on:
+ pull_request:
+ branches: [main]
+ push:
+ branches: [main]
+ schedule:
+ - cron: "0 8 * * *" # Daily at 8 AM UTC
+
+jobs:
+ security-scan:
+ runs-on: ubuntu-latest
+
+ 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"
+
+ - name: Authenticate Continue CLI
+ run: |
+ cn auth login --api-key "${{ secrets.CONTINUE_API_KEY }}"
+ echo "✅ Continue CLI authenticated"
+
+ - name: Run Security Scans
+ 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."
+
+ echo "📦 Checking dependencies..."
+ cn -p "Run Snyk Open Source on this repo.
+ Fail on fixable high issues."
+
+ - name: Generate Security Report
+ if: always()
+ run: |
+ cn -p "Generate a markdown security report summarizing:
+ - Total vulnerabilities by severity
+ - Top 3 critical issues (if any)
+ - Recommended next steps
+ Save to security-report.md"
+
+ - name: Upload Security Report
+ uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: security-report-${{ github.run_number }}
+ path: security-report.md
+ retention-days: 30
+```
+
+
+ The Snyk MCP authentication is handled through Continue Hub. No need to manage
+ Snyk tokens directly in CI - the agent manages authentication.
+
+
+## Security Guardrails
+
+Implement automated security policies using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
+
+
+ **Coming Soon**: These security guardrail prompts will be available as pre-configured rules on the Continue Hub for easy installation.
+
+
+
+ ```bash
+ "Always run Snyk Code before committing newly
+ generated code; refuse to proceed if high
+ issues remain."
+ ```
+
+
+
+ ```bash
+ "When adding/updating a dependency, run Snyk Open Source, choose the
+ lowest-risk upgrade, and re-test."
+ ```
+
+
+
+ ```bash
+ "Before building containers, scan base images and recommend
+ security-hardened alternatives."
+ ```
+
+
+
+ ```bash
+ "Scan all Terraform changes for compliance
+ violations before applying infrastructure."
+ ```
+
+
+
+ Enable the **Secure-at-Inception** rules from the Hub to automatically apply
+ these guardrails to all code generation and modifications.
+
+
+## Troubleshooting
+
+### Authentication Issues
+
+```bash
+"Check Snyk auth status and current org. If not authenticated,
+help me authenticate. Then run a quick Code scan on ./
+with severity medium and print one example issue."
+```
+
+### Fix Validation
+
+```bash
+"Propose minimal diffs only in affected files,
+then rerun the same Snyk scan to confirm resolution."
+```
+
+### Connection Problems
+
+
+ **Verification Steps:** - Snyk MCP is installed via [Continue
+ Hub](https://hub.continue.dev/snyk/snyk-mcp) - Secure-at-Inception rules are
+ [enabled](https://hub.continue.dev/snyk/secure-at-inception) - Authentication
+ completed successfully - Project folder has been trusted
+
+
+## What You've Built
+
+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
+
+
+ Your security workflow now operates at **[Level 2 Continuous
+ AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
+ AI handles routine security scanning and remediation with human oversight
+ through review and approval of fixes.
+
+
+## Next Steps
+
+1. **Run your first scan** - Try the [SAST](https://snyk.io/learn/application-security/sast/) prompt on your current project
+2. **Review findings** - Analyze the security report and implement fixes
+3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
+4. **Customize rules** - Add project-specific security policies
+5. **Monitor trends** - Track [vulnerability](https://snyk.io/learn/security-vulnerability/) reduction over time
+
+## Additional Resources
+
+
+
+ Complete Snyk platform documentation
+
+
+ Explore more MCP integrations and agents
+
+
+ Learn about secure coding practices
+
+
+ Understanding MCP architecture
+
+
diff --git a/docs/images/guides/images/agent-not-supported.png b/docs/images/guides/images/agent-not-supported.png
new file mode 100644
index 000000000..1846dede1
Binary files /dev/null and b/docs/images/guides/images/agent-not-supported.png differ
diff --git a/docs/reference.mdx b/docs/reference.mdx
index 0024f5bff..2738d55e9 100644
--- a/docs/reference.mdx
+++ b/docs/reference.mdx
@@ -219,7 +219,7 @@ The `models` section defines the language models used in your configuration. Mod
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
+ - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models.
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
- `requestOptions`: HTTP request options specific to the model.
@@ -251,6 +251,7 @@ The `models` section defines the language models used in your configuration. Mod
- `modelTimeout`: Model timeout for autocomplete requests in milliseconds.
- `maxSuffixPercentage`: Maximum percentage of prompt allocated for suffix.
- `prefixPercentage`: Percentage of input allocated for prefix.
+ - `transform`: If `false`, disables trimming of multiline completions. Defaults to `true`. Useful for models that generate better multiline completions without transformations.
- `template`: Custom template for autocomplete using Mustache syntax. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables.
- `onlyMyCode`: Only includes code within the repository for context.
- `useCache`: If `true`, enables caching for completions.
@@ -402,6 +403,7 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
- `env`: An optional map of environment variables for the server process.
- `cwd`: An optional working directory to run the command in. Can be absolute or relative path.
- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
+- `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models).
**Example:**
diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx
index 5960f07f8..e11152efe 100644
--- a/docs/reference/json-reference.mdx
+++ b/docs/reference/json-reference.mdx
@@ -191,7 +191,7 @@ Parameters that control the behavior of text generation and completion settings.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `numGpu`: For Ollama, this parameter overrides the number of gpu layers that will be used to load the model into VRAM.
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
-- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ models.
+- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ and some Ollama models.
- `reasoningBudgetTokens`: Sets budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
Example
@@ -485,8 +485,6 @@ Several experimental config parameters are available, as described below:
- `applyCodeBlock`: Model title for applying code blocks.
- `repoMapFileSelection`: Model title for repo map selections.
-
-
- `modelContextProtocolServers`: See [Model Context Protocol](/customize/deep-dives/mcp)
Example
@@ -540,5 +538,3 @@ Some deprecated `config.json` settings are no longer stored in config and have b
- `codeWrap`
- `displayRawMarkdown`
- `showChatScrollbar`
-
-
diff --git a/docs/reference/yaml-migration.mdx b/docs/reference/yaml-migration.mdx
index 4abcaf154..302237faf 100644
--- a/docs/reference/yaml-migration.mdx
+++ b/docs/reference/yaml-migration.mdx
@@ -1,17 +1,16 @@
---
title: "Migrating Config to YAML"
-description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from to ."
+description: "Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from config.json to config.yaml."
---
See also
- [Intro to YAML](https://yaml.org/)
-- [JSON Continue Config Reference](/reference)
- [YAML Continue Config Reference](/reference)
## Create YAML file
-Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`.
+Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current config.json file. If a `config.yaml` file is present, it will be loaded instead of config.json.
Give your configuration a `name` and a `version`:
@@ -87,12 +86,12 @@ config.json
config.yaml
-```
+```yaml
models:
- name: GPT-4
provider: openai
model: gpt-4
- apiKey:
+ apiKey:
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
@@ -101,7 +100,8 @@ models:
- edit
- name: My Voyage Reranker
provider: voyage
- apiKey:
+ model: rerank-2
+ apiKey:
roles:
- rerank
- name: My Starcoder
@@ -111,22 +111,25 @@ models:
- autocomplete
- name: My Ada Embedder
provider: openai
- apiKey:
+ model: text-embedding-ada-002
+ apiKey:
roles:
- embed
embedOptions:
- - maxChunkSize: 256
- - maxBatchSize: 5
+ maxChunkSize: 256
+ maxBatchSize: 5
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- - name: My Open AI Compatible Model - Apply
+ roles:
+ - chat
+ - name: My Open AI Compatible Model
provider: openai
model: my-openai-compatible-model
apiBase: http://3.3.3.3/v1
requestOptions:
headers:
- X-Auth-Token:
+ X-Auth-Token:
roles:
- chat
- apply
@@ -159,7 +162,7 @@ config.json
config.yaml
-```
+```yaml
context:
- provider: docs
- provider: codebase
@@ -178,14 +181,16 @@ The `systemMessage` property has been replaced with a `rules` property that take
config.json
```json
-{ "systemMessage": "Always give concise responses" }
+{
+ "systemMessage": "Always give concise responses"
+}
```
**After**
config.yaml
-```
+```yaml
rules:
- Always give concise responses
```
@@ -214,7 +219,7 @@ config.json
config.yaml
-```
+```yaml
prompts:
- name: check
description: Check for mistakes in my code
@@ -239,8 +244,14 @@ config.json
```json
{
"docs": [
- { "startUrl": "https://docs.nestjs.com/", "title": "nest.js" },
- { "startUrl": "https://mysite.com/docs/", "title": "My site" }
+ {
+ "startUrl": "https://docs.nestjs.com/",
+ "title": "nest.js"
+ },
+ {
+ "startUrl": "https://mysite.com/docs/",
+ "title": "My site"
+ }
]
}
```
@@ -249,7 +260,7 @@ config.json
config.yaml
-```
+```yaml
docs:
- name: nest.js
startUrl: https://docs.nestjs.com/
@@ -279,8 +290,14 @@ config.json
"transport": {
"type": "stdio",
"command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"],
- "env": { "KEY": "" }
+ "args": [
+ "mcp-server-sqlite",
+ "--db-path",
+ "/Users/NAME/test.db"
+ ],
+ "env": {
+ "KEY": ""
+ }
}
}
]
@@ -292,7 +309,7 @@ config.json
config.yaml
-```
+```yaml
mcpServers:
- name: My MCP Server
command: uvx
@@ -308,13 +325,11 @@ mcpServers:
## Deprecated configuration options
-Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`.
+Some deprecated config.json settings are no longer stored in config and have been moved to be editable through the user settings (Gear Icon). If found in config.json, they will be auto-migrated to User Settings and removed from config.json.
-See the [JSON Config Reference](/reference) for more information on fully deprecated options.
+The following top-level fields from config.json have been deprecated and don't have a config.yaml equivalent:
-The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent:
-
-- Slash commands (JSON `slashCommands`)
+- Slash commands (`slashCommands`)
- top-level `requestOptions`
@@ -332,7 +347,7 @@ The following top-level fields from `config.json` still work when using `config.
- `analytics`
-The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI
+The following top-level fields from config.json have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI
- `customCommands`
- `experimental`
diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs
index 5f4e18656..11515b20b 100644
--- a/extensions/cli/build.mjs
+++ b/extensions/cli/build.mjs
@@ -1,10 +1,14 @@
#!/usr/bin/env node
import * as esbuild from "esbuild";
-import { chmodSync, writeFileSync } from "fs";
+import { chmodSync, copyFileSync, writeFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
+// Parse command line arguments
+const args = process.argv.slice(2);
+const noMinify = args.includes("--no-minify");
+
const __dirname = dirname(fileURLToPath(import.meta.url));
// List of packages to mark as external (ONLY native modules that cannot be bundled)
@@ -13,6 +17,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const external = [
"@sentry/profiling-node", // Contains native profiler bindings (optional)
"fsevents", // macOS native file watcher (optional dependency)
+ "./xhr-sync-worker.js", // JSDOM worker file that needs to be copied separately
];
console.log("Building CLI with esbuild...");
@@ -38,7 +43,7 @@ try {
outfile: "dist/index.js",
external,
sourcemap: true,
- minify: true, // Minify for smaller bundle size
+ minify: !noMinify, // Use --no-minify flag to control minification
metafile: true,
plugins: [optionalDevtoolsPlugin],
@@ -76,16 +81,32 @@ try {
// Add banner to create require for CommonJS packages
banner: {
- js: `import { createRequire } from 'module';
-const require = createRequire(import.meta.url);`,
+ js: `import { createRequire as __createRequire } from 'module';
+const require = __createRequire(import.meta.url);`,
},
});
// Write metafile for analysis
writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
- // Create wrapper script with shebang
- writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
+ // Create wrapper script with shebang that explicitly runs the CLI
+ // Note: We must call runCli(); a plain dynamic import will not execute the CLI.
+ writeFileSync(
+ "dist/cn.js",
+ "#!/usr/bin/env node\nimport { runCli } from './index.js';\nawait runCli();\n",
+ );
+ // Copy worker files needed by JSDOM
+ const workerSource = resolve(
+ __dirname,
+ "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
+ );
+ const workerDest = resolve(__dirname, "dist/xhr-sync-worker.js");
+ try {
+ copyFileSync(workerSource, workerDest);
+ console.log("✓ Copied xhr-sync-worker.js");
+ } catch (error) {
+ console.warn("Warning: Could not copy xhr-sync-worker.js:", error.message);
+ }
// Make the wrapper script executable
chmodSync("dist/cn.js", 0o755);
diff --git a/extensions/cli/docs/storage-sync.md b/extensions/cli/docs/storage-sync.md
new file mode 100644
index 000000000..fd42e674c
--- /dev/null
+++ b/extensions/cli/docs/storage-sync.md
@@ -0,0 +1,55 @@
+# Storage Sync Flow for `cn serve`
+
+## Overview
+
+The `--id ` flag enables the `cn serve` command to periodically persist session state to an external Continue-managed storage bucket. On startup, the CLI exchanges the provided `storageId` for two pre-signed S3 URLs - one for `session.json` and one for `diff.txt` - and then pushes fresh copies of those files every 30 seconds.
+
+This document captures the responsibilities for both the CLI and backend components so we can iterate on the feature together.
+
+## CLI Responsibilities
+
+- **Flag plumbing**: When `cn serve` is invoked with `--id `, the CLI treats that value as an opaque identifier.
+- **API key auth**: The CLI attaches the user-level Continue API key (same mechanism we already use for other authenticated requests) to backend calls.
+- **Presign handshake**:
+ 1. On startup, issue `POST https://api.continue.dev/agents/storage/presigned-url` with JSON payload `{ "storageId": "" }`.
+ 2. Expect a response payload containing two pre-signed `PUT` URLs and their target object keys:
+ ```json
+ {
+ "session": {
+ "key": "sessions//session.json",
+ "putUrl": "https:///..."
+ },
+ "diff": {
+ "key": "sessions//diff.txt",
+ "putUrl": "https:///..."
+ }
+ }
+ ```
+ 3. If the call fails, log and continue without remote storage (no retries yet).
+- **Periodic uploads**:
+ - Every 30 seconds (configurable later), serialize the in-memory session to `session.json` and fetch the `/diff` payload to produce `diff.txt`.
+ - Upload both artifacts using their respective `PUT` URLs. For now we overwrite the same objects each cycle.
+ - Errors should be logged but non-fatal; the server keeps running.
+ - If the repo check fails (no git repo or missing `main`), `diff.txt` uploads an empty string and we log the condition once for debugging.
+
+## Backend Responsibilities
+
+- **Endpoint surface**: `POST /agents/storage/presigned-url` accepts a JSON body `{ "storageId": string }`.
+- **Authentication**: Leverage the caller's Continue API key (the request arrives with the standard `Authorization: Bearer ` header). Apply normal auth/tenant validation so users can only request URLs tied to their account/org.
+- **URL issuance**:
+ - Resolve `storageId` into the desired S3 prefix (e.g., `sessions///`).
+ - Generate two short-lived pre-signed `PUT` URLs: one for `session.json`, one for `diff.txt`.
+ - Return both URLs and their keys in the response payload described above.
+- **Expiration**: The initial implementation can hand out URLs with a generous TTL (e.g., 60 minutes). Later we will add CLI-side refresh logic before expiry.
+
+## Open Questions & Future Enhancements
+
+- **URL refresh**: When the presigned URLs expire we currently have no refresh cycle. We'd need either a renewal endpoint or to re-call the existing endpoint on failure.
+- **Upload cadence**: The 30-second interval is hard-coded for now. Consider making it configurable in both CLI and backend policies.
+- **Error telemetry**: Decide if repeated upload failures should trip analytics or circuit breakers.
+- **Diff source**: `diff.txt` currently mirrors the `/diff` endpoint response. Confirm backend expectations for format and size limits.
+- **Security**: We might want to sign responses or enforce stricter scope on `storageId` mapping (e.g., require both org + storageId and validate ownership).
+
+---
+
+This document should evolve alongside implementation details; update it whenever the API contract or client behavior changes.
diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json
index e74cc388e..c8aeaf70d 100644
--- a/extensions/cli/package-lock.json
+++ b/extensions/cli/package-lock.json
@@ -9,7 +9,9 @@
"version": "0.0.0-dev",
"license": "Apache-2.0",
"dependencies": {
- "@sentry/profiling-node": "^9.43.0"
+ "@sentry/profiling-node": "^9.43.0",
+ "fdir": "^6.4.2",
+ "fzf": "^0.5.2"
},
"bin": {
"cn": "dist/cn.js"
@@ -43,7 +45,6 @@
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/react": "^19.1.8",
- "@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@types/turndown": "^5.0.5",
@@ -86,8 +87,8 @@
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
+ "prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",
- "readline-sync": "^1.4.10",
"semantic-release": "^24.2.7",
"shell-quote": "^1.8.3",
"supertest": "^7.1.3",
@@ -235,11 +236,11 @@
},
"../../packages/config-yaml": {
"name": "@continuedev/config-yaml",
- "version": "1.0.96",
+ "version": "1.17.0",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "@continuedev/config-types": "file:../config-types",
+ "@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@@ -263,15 +264,15 @@
},
"../../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
- "version": "1.5.1",
+ "version": "1.15.0",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
- "@continuedev/config-yaml": "^1.8.0",
- "@continuedev/fetch": "^1.0.16",
+ "@continuedev/config-yaml": "^1.14.0",
+ "@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@@ -5404,13 +5405,6 @@
"csstype": "^3.0.2"
}
},
- "node_modules/@types/readline-sync": {
- "version": "1.4.8",
- "resolved": "https://registry.npmjs.org/@types/readline-sync/-/readline-sync-1.4.8.tgz",
- "integrity": "sha512-BL7xOf0yKLA6baAX6MMOnYkoflUyj/c7y3pqMRfU0va7XlwHAOTOIo4x55P/qLfMsuaYdJJKubToLqRVmRtRZA==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/send": {
"version": "0.17.5",
"resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.5.tgz",
@@ -9477,6 +9471,23 @@
"reusify": "^1.0.4"
}
},
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
@@ -9905,6 +9916,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/fzf": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/fzf/-/fzf-0.5.2.tgz",
+ "integrity": "sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
@@ -12060,6 +12077,19 @@
"node": ">=8.6"
}
},
+ "node_modules/micromatch/node_modules/picomatch": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/mime": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz",
@@ -15736,13 +15766,13 @@
"license": "ISC"
},
"node_modules/picomatch": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
- "dev": true,
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "devOptional": true,
"license": "MIT",
"engines": {
- "node": ">=8.6"
+ "node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
@@ -15972,6 +16002,93 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/prettier-plugin-tailwindcss": {
+ "version": "0.6.14",
+ "resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
+ "integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.21.3"
+ },
+ "peerDependencies": {
+ "@ianvs/prettier-plugin-sort-imports": "*",
+ "@prettier/plugin-hermes": "*",
+ "@prettier/plugin-oxc": "*",
+ "@prettier/plugin-pug": "*",
+ "@shopify/prettier-plugin-liquid": "*",
+ "@trivago/prettier-plugin-sort-imports": "*",
+ "@zackad/prettier-plugin-twig": "*",
+ "prettier": "^3.0",
+ "prettier-plugin-astro": "*",
+ "prettier-plugin-css-order": "*",
+ "prettier-plugin-import-sort": "*",
+ "prettier-plugin-jsdoc": "*",
+ "prettier-plugin-marko": "*",
+ "prettier-plugin-multiline-arrays": "*",
+ "prettier-plugin-organize-attributes": "*",
+ "prettier-plugin-organize-imports": "*",
+ "prettier-plugin-sort-imports": "*",
+ "prettier-plugin-style-order": "*",
+ "prettier-plugin-svelte": "*"
+ },
+ "peerDependenciesMeta": {
+ "@ianvs/prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "@prettier/plugin-hermes": {
+ "optional": true
+ },
+ "@prettier/plugin-oxc": {
+ "optional": true
+ },
+ "@prettier/plugin-pug": {
+ "optional": true
+ },
+ "@shopify/prettier-plugin-liquid": {
+ "optional": true
+ },
+ "@trivago/prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "@zackad/prettier-plugin-twig": {
+ "optional": true
+ },
+ "prettier-plugin-astro": {
+ "optional": true
+ },
+ "prettier-plugin-css-order": {
+ "optional": true
+ },
+ "prettier-plugin-import-sort": {
+ "optional": true
+ },
+ "prettier-plugin-jsdoc": {
+ "optional": true
+ },
+ "prettier-plugin-marko": {
+ "optional": true
+ },
+ "prettier-plugin-multiline-arrays": {
+ "optional": true
+ },
+ "prettier-plugin-organize-attributes": {
+ "optional": true
+ },
+ "prettier-plugin-organize-imports": {
+ "optional": true
+ },
+ "prettier-plugin-sort-imports": {
+ "optional": true
+ },
+ "prettier-plugin-style-order": {
+ "optional": true
+ },
+ "prettier-plugin-svelte": {
+ "optional": true
+ }
+ }
+ },
"node_modules/pretty-format": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
@@ -16322,16 +16439,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/readline-sync": {
- "version": "1.4.10",
- "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz",
- "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 0.8.0"
- }
- },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -18018,37 +18125,6 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
- "node_modules/tinyglobby/node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/tinyglobby/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/tinygradient": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz",
@@ -18759,37 +18835,6 @@
"url": "https://opencollective.com/vitest"
}
},
- "node_modules/vite/node_modules/fdir": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
- "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12.0.0"
- },
- "peerDependencies": {
- "picomatch": "^3 || ^4"
- },
- "peerDependenciesMeta": {
- "picomatch": {
- "optional": true
- }
- }
- },
- "node_modules/vite/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/vitest": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz",
@@ -18863,19 +18908,6 @@
}
}
},
- "node_modules/vitest/node_modules/picomatch": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
- "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
diff --git a/extensions/cli/package.json b/extensions/cli/package.json
index 68594f379..4932efa40 100644
--- a/extensions/cli/package.json
+++ b/extensions/cli/package.json
@@ -37,14 +37,16 @@
"license": "Apache-2.0",
"repository": {
"type": "git",
- "url": "https://github.com/continuedev/cli.git"
+ "url": "https://github.com/continuedev/continue.git"
},
"bugs": {
"url": "https://github.com/continuedev/continue/issues"
},
"homepage": "https://continue.dev",
"dependencies": {
- "@sentry/profiling-node": "^9.43.0"
+ "@sentry/profiling-node": "^9.43.0",
+ "fdir": "^6.4.2",
+ "fzf": "^0.5.2"
},
"devDependencies": {
"@continuedev/config-yaml": "file:../../packages/config-yaml",
@@ -75,7 +77,6 @@
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/react": "^19.1.8",
- "@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@types/turndown": "^5.0.5",
@@ -118,8 +119,8 @@
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"prettier": "^3.6.2",
+ "prettier-plugin-tailwindcss": "^0.6.14",
"react": "^19.1.0",
- "readline-sync": "^1.4.10",
"semantic-release": "^24.2.7",
"shell-quote": "^1.8.3",
"supertest": "^7.1.3",
diff --git a/extensions/cli/src/__mocks__/config.ts b/extensions/cli/src/__mocks__/config.ts
index 8b69b7944..c12019479 100644
--- a/extensions/cli/src/__mocks__/config.ts
+++ b/extensions/cli/src/__mocks__/config.ts
@@ -13,5 +13,4 @@ export const getLlmApi =
) => [any, any]
>();
export const getModel = vi.fn<(config: any, modelName: string) => any>();
-export const createLlmApi =
- vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();
+export const createLlmApi = vi.fn<(model: any, authConfig: any) => any>();
diff --git a/extensions/cli/src/auth/authEnv.ts b/extensions/cli/src/auth/authEnv.ts
new file mode 100644
index 000000000..6b58ad963
--- /dev/null
+++ b/extensions/cli/src/auth/authEnv.ts
@@ -0,0 +1,5 @@
+import * as path from "path";
+
+import { env } from "../env.js";
+
+export const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
diff --git a/extensions/cli/src/auth/orgSelection.test.ts b/extensions/cli/src/auth/orgSelection.test.ts
new file mode 100644
index 000000000..838a20899
--- /dev/null
+++ b/extensions/cli/src/auth/orgSelection.test.ts
@@ -0,0 +1,233 @@
+import * as fs from "fs";
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ autoSelectOrganizationAndConfig,
+ createUpdatedAuthConfig,
+} from "./orgSelection.js";
+import type { AuthenticatedConfig } from "./workos.js";
+
+// Mock dependencies
+vi.mock("fs");
+vi.mock("../config.js");
+vi.mock("../env.js");
+vi.mock("./workos.js");
+
+const mockApiClient = {
+ listOrganizations: vi.fn(),
+ listAssistants: vi.fn(),
+} as any; // Mock API client for testing
+
+describe("orgSelection", () => {
+ const mockConfig: AuthenticatedConfig = {
+ userId: "user123",
+ userEmail: "user@example.com",
+ accessToken: "token123",
+ refreshToken: "refresh123",
+ expiresAt: Date.now() + 3600000,
+ organizationId: undefined,
+ configUri: undefined,
+ modelName: undefined,
+ };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+
+ // Mock modules using vi.mocked
+ const configMod = await import("../config.js");
+ const envMod = await import("../env.js");
+ const workosMod = await import("./workos.js");
+
+ vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient);
+ vi.mocked(envMod.env).continueHome = "/mock/home";
+ vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {});
+
+ // Default: no local config
+ vi.mocked(fs.existsSync).mockReturnValue(false);
+ });
+
+ describe("createUpdatedAuthConfig", () => {
+ it("should update organization ID", () => {
+ const result = createUpdatedAuthConfig(mockConfig, "org123");
+ expect(result.organizationId).toBe("org123");
+ });
+
+ it("should update organization ID and config URI", () => {
+ const result = createUpdatedAuthConfig(
+ mockConfig,
+ "org123",
+ "slug://owner/assistant",
+ );
+ expect(result.organizationId).toBe("org123");
+ expect(result!.configUri).toBe("slug://owner/assistant");
+ });
+
+ it("should set personal organization", () => {
+ const result = createUpdatedAuthConfig(mockConfig, null);
+ expect(result.organizationId).toBe(null);
+ });
+ });
+
+ describe("autoSelectOrganizationAndConfig scenarios", () => {
+ it("Priority 1: Org with assistants → select first assistant", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [
+ { id: "org1", name: "Org 1" },
+ { id: "org2", name: "Org 2" },
+ ],
+ });
+
+ // Mock API calls in order: org1 assistants, org2 assistants
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1") return Promise.resolve([]);
+ if (organizationId === "org2")
+ return Promise.resolve([
+ { ownerSlug: "owner", packageSlug: "assistant1" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe("org2");
+ expect(result!.configUri).toBe("slug://owner/assistant1");
+ });
+
+ it("Priority 2: No org assistants → personal assistants exist", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1") return Promise.resolve([]);
+ if (organizationId === undefined)
+ return Promise.resolve([
+ { ownerSlug: "personal", packageSlug: "my-assistant" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null); // personal org
+ expect(result!.configUri).toBe("slug://personal/my-assistant");
+ expect(mockApiClient.listAssistants).toHaveBeenCalledWith({
+ organizationId: undefined,
+ });
+ });
+
+ it("Priority 3: No assistants anywhere → local config.yaml exists", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
+ vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toContain("config.yaml");
+ });
+
+ it("Priority 4: No assistants, no config.yaml → fallback", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
+ vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBeUndefined();
+ });
+
+ it("Multiple orgs with assistants → pick first one", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [
+ { id: "org1", name: "Org 1" },
+ { id: "org2", name: "Org 2" },
+ ],
+ });
+
+ mockApiClient.listAssistants.mockImplementation(
+ ({ organizationId }: { organizationId?: string }) => {
+ if (organizationId === "org1")
+ return Promise.resolve([
+ { ownerSlug: "owner1", packageSlug: "assistant1" },
+ ]);
+ if (organizationId === "org2")
+ return Promise.resolve([
+ { ownerSlug: "owner2", packageSlug: "assistant2" },
+ ]);
+ return Promise.resolve([]);
+ },
+ );
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe("org1"); // First org wins
+ expect(result!.configUri).toBe("slug://owner1/assistant1");
+ });
+
+ it("Personal assistants API fails → fallback to config.yaml", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [{ id: "org1", name: "Org 1" }],
+ });
+
+ mockApiClient.listAssistants
+ .mockResolvedValueOnce([]) // org1: no assistants
+ .mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error
+
+ vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toContain("config.yaml");
+ });
+
+ it("Empty organizations list → check personal assistants", async () => {
+ mockApiClient.listOrganizations.mockResolvedValue({
+ organizations: [], // No orgs
+ });
+
+ mockApiClient.listAssistants.mockResolvedValue([
+ { ownerSlug: "personal", packageSlug: "my-assistant" },
+ ]);
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBe("slug://personal/my-assistant");
+ });
+
+ it("API error → fallback with error message", async () => {
+ mockApiClient.listOrganizations.mockRejectedValue(
+ new Error("Network error"),
+ );
+
+ const consoleSpy = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const result = await autoSelectOrganizationAndConfig(mockConfig);
+
+ expect(result!.organizationId).toBe(null);
+ expect(result!.configUri).toBeUndefined();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Error fetching organizations:"),
+ "Network error",
+ );
+
+ consoleSpy.mockRestore();
+ });
+ });
+});
diff --git a/extensions/cli/src/auth/orgSelection.ts b/extensions/cli/src/auth/orgSelection.ts
new file mode 100644
index 000000000..e82bea8ae
--- /dev/null
+++ b/extensions/cli/src/auth/orgSelection.ts
@@ -0,0 +1,155 @@
+import * as fs from "fs";
+import * as path from "path";
+
+import chalk from "chalk";
+
+import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js";
+import { saveAuthConfig } from "../auth/workos.js";
+import { getApiClient } from "../config.js";
+import { env } from "../env.js";
+
+/**
+ * Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
+ */
+export function createUpdatedAuthConfig(
+ config: AuthenticatedConfig,
+ organizationId: string | null | undefined,
+ configUri?: string | null,
+): AuthenticatedConfig {
+ return {
+ userId: config.userId,
+ userEmail: config.userEmail,
+ accessToken: config.accessToken,
+ refreshToken: config.refreshToken,
+ expiresAt: config.expiresAt,
+ organizationId,
+ configUri: configUri ?? config.configUri,
+ modelName: config.modelName,
+ };
+}
+
+/**
+ * Check if an organization has available assistants
+ */
+async function hasOrgAssistants(
+ apiClient: ReturnType,
+ organizationId: string,
+): Promise {
+ try {
+ const assistants = await apiClient.listAssistants({ organizationId });
+ return assistants.length > 0;
+ } catch {
+ // If we can't check, assume no assistants
+ return false;
+ }
+}
+
+/**
+ * Get the first available assistant from an organization
+ */
+async function getFirstAssistant(
+ apiClient: ReturnType,
+ organizationId: string,
+): Promise {
+ try {
+ const assistants = await apiClient.listAssistants({ organizationId });
+ if (assistants.length > 0) {
+ const first = assistants[0];
+ return `${first.ownerSlug}/${first.packageSlug}`;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Check if personal local config.yaml exists
+ */
+function hasPersonalLocalConfig(): boolean {
+ const defaultConfigPath = path.join(env.continueHome, "config.yaml");
+ return fs.existsSync(defaultConfigPath);
+}
+
+/**
+ * Automatically select organization and configuration for authenticated config
+ * Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback
+ */
+export async function autoSelectOrganizationAndConfig(
+ authenticatedConfig: AuthenticatedConfig,
+): Promise {
+ const apiClient = getApiClient(authenticatedConfig.accessToken);
+
+ try {
+ const resp = await apiClient.listOrganizations();
+ const organizations = resp.organizations;
+
+ // Priority 1: Find any organization that has assistants - use first assistant
+ for (const org of organizations) {
+ const hasAssistants = await hasOrgAssistants(apiClient, org.id);
+ if (hasAssistants) {
+ // Get the first assistant from this org
+ const firstAssistantSlug = await getFirstAssistant(apiClient, org.id);
+ const configUri = firstAssistantSlug
+ ? `slug://${firstAssistantSlug}`
+ : undefined;
+
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ org.id,
+ configUri,
+ );
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ }
+ }
+
+ // Priority 2: Check if personal organization has assistants
+ try {
+ const personalAssistants = await apiClient.listAssistants({
+ organizationId: undefined,
+ });
+ if (personalAssistants.length > 0) {
+ const firstAssistant = personalAssistants[0];
+ const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`;
+ const configUri = `slug://${firstAssistantSlug}`;
+
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ null,
+ configUri,
+ );
+ saveAuthConfig(updatedConfig);
+ console.log(chalk.green("✓ Automatically selected personal assistant"));
+ return updatedConfig;
+ }
+ } catch {
+ // If personal assistants can't be fetched, continue to next priority
+ }
+
+ // Priority 3: If no assistants anywhere, use local config.yaml
+ if (hasPersonalLocalConfig()) {
+ const updatedConfig = createUpdatedAuthConfig(
+ authenticatedConfig,
+ null,
+ `file://${path.join(env.continueHome, "config.yaml")}`,
+ );
+ saveAuthConfig(updatedConfig);
+ console.log(chalk.green("✓ Using local config.yaml"));
+ return updatedConfig;
+ }
+
+ // no org assistants or config.yaml
+ const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ } catch (error: any) {
+ console.error(
+ chalk.red("Error fetching organizations:"),
+ error.response?.data?.message || error.message || error,
+ );
+ const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
+ saveAuthConfig(updatedConfig);
+ return updatedConfig;
+ }
+}
diff --git a/extensions/cli/src/auth/workos.helpers.ts b/extensions/cli/src/auth/workos.helpers.ts
index efd2151cc..cc4690cdf 100644
--- a/extensions/cli/src/auth/workos.helpers.ts
+++ b/extensions/cli/src/auth/workos.helpers.ts
@@ -2,6 +2,7 @@ import chalk from "chalk";
import { getApiClient } from "../config.js";
import { safeStderr } from "../init.js";
+import { gracefulExit } from "../util/exit.js";
import type {
AuthConfig,
@@ -15,7 +16,7 @@ import { saveAuthConfig } from "./workos.js";
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
- organizationId: string | null,
+ organizationId: string | null | undefined,
): AuthenticatedConfig {
return {
userId: config.userId,
@@ -76,7 +77,7 @@ export async function handleCliOrgForEnvironmentAuth(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
- process.exit(1);
+ await gracefulExit(1);
}
const apiClient = getApiClient(authConfig.accessToken);
@@ -107,7 +108,7 @@ export async function handleCliOrgForAuthenticatedConfig(
"The --org flag is only supported in headless mode (with -p/--print flag)\n",
),
);
- process.exit(1);
+ await gracefulExit(1);
}
const apiClient = getApiClient(authenticatedConfig.accessToken);
@@ -123,43 +124,3 @@ export async function handleCliOrgForAuthenticatedConfig(
saveAuthConfig(updatedConfig);
return updatedConfig;
}
-
-/**
- * Automatically select organization for authenticated config
- */
-export async function autoSelectOrganization(
- authenticatedConfig: AuthenticatedConfig,
-): Promise {
- const apiClient = getApiClient(authenticatedConfig.accessToken);
-
- try {
- const resp = await apiClient.listOrganizations();
- const organizations = resp.organizations;
-
- if (organizations.length === 0) {
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- }
-
- // Automatically select the first organization if available
- const selectedOrg = organizations[0];
- const selectedOrgId = selectedOrg.id;
-
- const updatedConfig = createUpdatedAuthConfig(
- authenticatedConfig,
- selectedOrgId,
- );
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- } catch (error: any) {
- console.error(
- chalk.red("Error fetching organizations:"),
- error.response?.data?.message || error.message || error,
- );
- console.info(chalk.yellow("Continuing without organization selection."));
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
- }
-}
diff --git a/extensions/cli/src/auth/workos.orgScope.test.ts b/extensions/cli/src/auth/workos.orgScope.test.ts
new file mode 100644
index 000000000..7367a3024
--- /dev/null
+++ b/extensions/cli/src/auth/workos.orgScope.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+
+import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js";
+
+describe("ensureOrganization with API key org scope", () => {
+ const originalEnv = { ...process.env };
+ const originalFetch = global.fetch;
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ afterEach(() => {
+ process.env = { ...originalEnv };
+ global.fetch = originalFetch as any;
+ });
+
+ it("resolves organizationId via auth/scope for API key auth", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ organizationId: "org_123" }),
+ });
+ (global as any).fetch = mockFetch;
+
+ const envAuthConfig = {
+ accessToken: "sk_test_api_key",
+ organizationId: null as string | null,
+ } as const;
+
+ const result = await ensureOrganization(envAuthConfig, true);
+ expect(result).not.toBeNull();
+ if (result && isEnvironmentAuthConfig(result)) {
+ expect(result.organizationId).toBe("org_123");
+ } else {
+ throw new Error("Expected environment auth config result");
+ }
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+
+ it("keeps organizationId null if endpoint not available", async () => {
+ const mockFetch = vi.fn().mockResolvedValue({ ok: false });
+ (global as any).fetch = mockFetch;
+
+ const envAuthConfig = {
+ accessToken: "sk_test_api_key",
+ organizationId: null as string | null,
+ } as const;
+
+ const result = await ensureOrganization(envAuthConfig, true);
+ expect(result).not.toBeNull();
+ if (result && isEnvironmentAuthConfig(result)) {
+ expect(result.organizationId).toBeNull();
+ } else {
+ throw new Error("Expected environment auth config result");
+ }
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts
index 8ae14c25f..d110ea161 100644
--- a/extensions/cli/src/auth/workos.ts
+++ b/extensions/cli/src/auth/workos.ts
@@ -1,4 +1,5 @@
import * as fs from "fs";
+import * as os from "os";
import * as path from "path";
import chalk from "chalk";
@@ -12,8 +13,12 @@ if (!globalThis.fetch) {
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
}
-// Config file path
-const AUTH_CONFIG_PATH = path.join(env.continueHome, "auth.json");
+// Config file path - define as a function to avoid initialization order issues
+function getAuthConfigPath() {
+ const continueHome =
+ process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
+ return path.join(continueHome, "auth.json");
+}
// Represents an authenticated user's configuration
export interface AuthenticatedConfig {
@@ -22,7 +27,7 @@ export interface AuthenticatedConfig {
accessToken: string;
refreshToken: string;
expiresAt: number;
- organizationId: string | null; // null means personal organization
+ organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
@@ -74,7 +79,9 @@ export function getAccessToken(config: AuthConfig): string | null {
/**
* Gets the organization ID from any auth config type
*/
-export function getOrganizationId(config: AuthConfig): string | null {
+export function getOrganizationId(
+ config: AuthConfig,
+): string | null | undefined {
if (config === null) return null;
return config.organizationId;
}
@@ -96,10 +103,9 @@ export function getModelName(config: AuthConfig): string | null {
}
// URI utility functions have been moved to ./uriUtils.ts
+import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
- autoSelectOrganization,
- createUpdatedAuthConfig,
handleCliOrgForAuthenticatedConfig,
handleCliOrgForEnvironmentAuth,
} from "./workos.helpers.js";
@@ -130,8 +136,9 @@ export function loadAuthConfig(): AuthConfig {
}
try {
- if (fs.existsSync(AUTH_CONFIG_PATH)) {
- const data = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, "utf8"));
+ const authConfigPath = getAuthConfigPath();
+ if (fs.existsSync(authConfigPath)) {
+ const data = JSON.parse(fs.readFileSync(authConfigPath, "utf8"));
// Validate that we have all required fields for authenticated config
if (
@@ -173,13 +180,14 @@ export function saveAuthConfig(config: AuthenticatedConfig): void {
}
try {
+ const authConfigPath = getAuthConfigPath();
// Make sure the directory exists
- const dir = path.dirname(AUTH_CONFIG_PATH);
+ const dir = path.dirname(authConfigPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
- fs.writeFileSync(AUTH_CONFIG_PATH, JSON.stringify(config, null, 2));
+ fs.writeFileSync(authConfigPath, JSON.stringify(config, null, 2));
} catch (error) {
console.error(`Error saving auth config: ${error}`);
}
@@ -360,7 +368,7 @@ async function pollForDeviceToken(
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: tokenExpiresAt,
- organizationId: null,
+ organizationId: undefined, // undefined triggers auto-selection, null means personal org selected
};
// Save the config
@@ -540,8 +548,10 @@ export async function ensureOrganization(
);
}
} else if (isEnvironmentAuthConfig(authConfig)) {
- // No CLI organization slug (or "personal" was specified) - return as-is
- return authConfig;
+ // No CLI organization slug (or "personal" was specified)
+ // If using API key auth, attempt to resolve its organization scope once
+ const resolved = await resolveOrgScopeForApiKey(authConfig);
+ return resolved;
}
// If not authenticated, return as-is
@@ -561,20 +571,71 @@ export async function ensureOrganization(
);
}
- // If already have organization ID (including null for personal), return as-is
- if (authenticatedConfig.organizationId !== undefined) {
- return authenticatedConfig;
+ // Only auto-select if user hasn't made any previous selections
+ // - organizationId === undefined means first-time setup
+ // - configUri being set means they've chosen a specific assistant/config
+ if (
+ authenticatedConfig.organizationId === undefined &&
+ !authenticatedConfig.configUri
+ ) {
+ return autoSelectOrganizationAndConfig(authenticatedConfig);
}
- // In headless mode, default to personal organization if none saved
- if (isHeadless) {
- const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
- saveAuthConfig(updatedConfig);
- return updatedConfig;
+ // User already has made a selection (org or config) - respect their choice
+ return authenticatedConfig;
+}
+
+/**
+ * Attempts to resolve the organization scope for API key auth (environment-based auth).
+ * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
+ * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
+ */
+async function resolveOrgScopeForApiKey(
+ envConfig: EnvironmentAuthConfig,
+): Promise {
+ // If already set (including explicit null), return as-is
+ if (envConfig.organizationId !== null) {
+ return envConfig;
}
- // Need to select organization
- return autoSelectOrganization(authenticatedConfig);
+ const accessToken = envConfig.accessToken;
+ if (!accessToken) return envConfig;
+
+ try {
+ // Prefer a dedicated endpoint for scope discovery. This should return JSON like:
+ // { organizationId: string | null } (aka orgScopeId)
+ const url = new URL("auth/scope", env.apiBase);
+ const resp = await fetch(url, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!resp.ok) {
+ // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
+ return envConfig;
+ }
+
+ const data: any = await resp.json().catch(() => ({}));
+ const orgId =
+ data?.organizationId ??
+ data?.orgScopeId ??
+ data?.organization?.id ??
+ null;
+
+ if (orgId && typeof orgId === "string") {
+ return {
+ ...envConfig,
+ organizationId: orgId,
+ };
+ }
+ } catch {
+ // Network or parsing issues: leave config unchanged
+ }
+
+ return envConfig;
}
/**
@@ -624,10 +685,9 @@ export async function hasMultipleOrganizations(): Promise {
* Logs the user out by clearing saved credentials
*/
export function logout(): void {
- const onboardingFlagPath = path.join(
- env.continueHome,
- ".onboarding_complete",
- );
+ const continueHome =
+ process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
+ const onboardingFlagPath = path.join(continueHome, ".onboarding_complete");
// Remove onboarding completion flag so user will go through onboarding again
if (fs.existsSync(onboardingFlagPath)) {
@@ -643,8 +703,9 @@ export function logout(): void {
return;
}
- if (fs.existsSync(AUTH_CONFIG_PATH)) {
- fs.unlinkSync(AUTH_CONFIG_PATH);
+ const authConfigPath = getAuthConfigPath();
+ if (fs.existsSync(authConfigPath)) {
+ fs.unlinkSync(authConfigPath);
console.info(chalk.green("Successfully logged out"));
} else {
console.info(chalk.yellow("No active session found"));
diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts
index 96e74c9ae..a954e8b34 100644
--- a/extensions/cli/src/commands/chat.ts
+++ b/extensions/cli/src/commands/chat.ts
@@ -1,12 +1,12 @@
import { ModelConfig } from "@continuedev/config-yaml";
+import { BaseLlmApi } from "@continuedev/openai-adapters";
import chalk from "chalk";
-import type { ChatHistoryItem, Session } from "core/index.js";
+import { ChatHistoryItem, Session } from "core";
import { ChatDescriber } from "core/util/chatDescriber.js";
-import * as readlineSync from "readline-sync";
import { compactChatHistory, findCompactionIndex } from "../compaction.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
-import { safeStdout } from "../init.js";
+import { safeStderr, safeStdout } from "../init.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { sentryService } from "../sentry.js";
@@ -22,8 +22,10 @@ import { streamChatResponse } from "../stream/streamChatResponse.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
+import { gracefulExit } from "../util/exit.js";
import { formatAnthropicError, formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
+import { question } from "../util/prompt.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
@@ -96,7 +98,7 @@ export async function initializeChatHistory(
return newSession.history;
} else {
logger.error(chalk.red(`Session with ID "${options.fork}" not found.`));
- process.exit(1);
+ await gracefulExit(1);
}
}
@@ -118,7 +120,7 @@ export async function initializeChatHistory(
async function handleManualCompaction(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
- llmApi: any,
+ llmApi: BaseLlmApi,
isHeadless: boolean,
): Promise<{ compactionIndex?: number | null } | void> {
if (!isHeadless) {
@@ -159,11 +161,66 @@ async function handleManualCompaction(
}
}
+// Helper function to get streaming response based on compaction state
+async function getStreamingResponse(
+ compactionIndex: number | null | undefined,
+ model: ModelConfig,
+ llmApi: BaseLlmApi,
+): Promise {
+ const abortController = new AbortController();
+
+ if (compactionIndex !== null && compactionIndex !== undefined) {
+ // Use service to compute history for LLM
+ const historyForLLM =
+ services.chatHistory.getHistoryForLLM(compactionIndex);
+
+ return await streamChatResponse(
+ historyForLLM,
+ model,
+ llmApi,
+ abortController,
+ );
+ } else {
+ // No compaction - get full history from service
+ return await streamChatResponse(
+ services.chatHistory.getHistory(),
+ model,
+ llmApi,
+ abortController,
+ );
+ }
+}
+
+// Helper function to process and output response in headless mode
+function processAndOutputResponse(
+ finalResponse: string,
+ isHeadless: boolean,
+ silent?: boolean,
+ format?: "json",
+): void {
+ if (isHeadless && finalResponse && finalResponse.trim()) {
+ let processedResponse = finalResponse;
+
+ // Strip think tags if --silent flag is enabled
+ if (silent) {
+ processedResponse = stripThinkTags(processedResponse);
+ }
+
+ // Process output based on format
+ const outputResponse =
+ format === "json"
+ ? processJsonOutput(processedResponse)
+ : processedResponse;
+
+ safeStdout(outputResponse + "\n");
+ }
+}
+
// Helper function to handle auto-compaction for headless mode
async function handleAutoCompaction(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
- llmApi: any,
+ llmApi: BaseLlmApi,
isHeadless: boolean,
format?: "json",
): Promise {
@@ -243,7 +300,7 @@ async function handleAutoCompaction(
*/
async function handleTitleGeneration(
assistantResponse: string,
- llmApi: any,
+ llmApi: BaseLlmApi,
model: ModelConfig,
): Promise {
try {
@@ -269,7 +326,7 @@ interface ProcessMessageOptions {
userInput: string;
chatHistory: ChatHistoryItem[];
model: ModelConfig;
- llmApi: any;
+ llmApi: BaseLlmApi;
isHeadless: boolean;
format?: "json";
silent?: boolean;
@@ -324,71 +381,35 @@ async function processMessage(
}
try {
- const abortController = new AbortController();
-
- // Service-driven streaming; history updates occur via ChatHistoryService
- let finalResponse;
- if (compactionIndex !== null && compactionIndex !== undefined) {
- // Use service to compute history for LLM
- const historyForLLM =
- services.chatHistory.getHistoryForLLM(compactionIndex);
-
- finalResponse = await streamChatResponse(
- historyForLLM,
- model,
- llmApi,
- abortController,
- );
- } else {
- // No compaction - get full history from service
- finalResponse = await streamChatResponse(
- services.chatHistory.getHistory(),
- model,
- llmApi,
- abortController,
- );
- }
+ // Get AI response with potential tool usage
+ const finalResponse = await getStreamingResponse(
+ compactionIndex,
+ model,
+ llmApi,
+ );
// Generate session title after first assistant response
if (firstAssistantResponse && finalResponse && finalResponse.trim()) {
await handleTitleGeneration(finalResponse, llmApi, model);
}
- // In headless mode, only print the final response using safe stdout
- if (isHeadless && finalResponse && finalResponse.trim()) {
- let processedResponse = finalResponse;
-
- // Strip think tags if --silent flag is enabled
- if (silent) {
- processedResponse = stripThinkTags(processedResponse);
- }
-
- // Process output based on format
- const outputResponse =
- format === "json"
- ? processJsonOutput(processedResponse)
- : processedResponse;
-
- safeStdout(outputResponse + "\n");
- }
+ // Process and output response in headless mode
+ processAndOutputResponse(finalResponse, isHeadless, silent, format);
// Save session after each successful response
updateSessionHistory(services.chatHistory.getHistory());
} catch (e: any) {
const error = e instanceof Error ? e : new Error(String(e));
- if (model.provider === "anthropic") {
- logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
- } else {
- logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
- }
-
- sentryService.captureException(error, {
- context: "chat_response",
- isHeadless,
- chatHistoryLength: services.chatHistory.getHistory().length,
- });
+ // In headless mode, don't output JSON here - let error bubble up to main handler
if (!isHeadless) {
+ // Non-headless mode: use colored console output
+ if (model.provider === "anthropic") {
+ logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
+ } else {
+ logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
+ }
+
logger.info(
chalk.dim(
`Chat history:\n${JSON.stringify(
@@ -399,6 +420,18 @@ async function processMessage(
),
);
}
+
+ sentryService.captureException(error, {
+ context: "chat_response",
+ isHeadless,
+ chatHistoryLength: services.chatHistory.getHistory().length,
+ });
+
+ // In headless mode, re-throw the error to bubble up to main error handler
+ // This preserves downstream logic like telemetry cleanup
+ if (isHeadless) {
+ throw error;
+ }
}
}
@@ -425,6 +458,10 @@ async function runHeadlessMode(
throw new Error("No models were found.");
}
+ if (!llmApi) {
+ throw new Error("No LLM API instance found.");
+ }
+
// Initialize service-driven history (resume if requested)
const chatHistory = await initializeChatHistory(options);
let compactionIndex: number | null = null;
@@ -453,7 +490,7 @@ async function runHeadlessMode(
const userInput =
isFirstMessage && initialUserInput
? initialUserInput
- : readlineSync.question(`\n${chalk.bold.green("You:")} `);
+ : await question(`\n${chalk.bold.green("You:")} `);
isFirstMessage = false;
@@ -497,17 +534,12 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
const { permissionOverrides } = processCommandFlags(options);
// Initialize services with onboarding handled internally
- const initResult = await initializeServices({
+ await initializeServices({
options,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
- // If onboarding was completed, show success message
- if (initResult.wasOnboarded) {
- console.log(chalk.green("✓ Setup complete! Starting chat..."));
- }
-
// Start TUI with skipOnboarding since we already handled it
const tuiOptions: any = {
initialPrompt: prompt,
@@ -539,15 +571,30 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
await runHeadlessMode(prompt, options);
} catch (error: any) {
const err = error instanceof Error ? error : new Error(String(error));
- // Use headless-aware error logging to ensure fatal errors are shown in headless mode
- logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
+
+ // In headless mode, output error as JSON to stdout
+ if (options.headless) {
+ const errorOutput = {
+ status: "error",
+ message: err.message || String(err),
+ };
+ safeStderr(JSON.stringify(errorOutput) + "\n");
+ } else {
+ // Use headless-aware error logging for non-headless mode
+ logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
+ }
+
sentryService.captureException(err, {
context: "chat_command_fatal",
headless: options.headless,
});
- process.exit(1);
+
+ // Stop active time tracking BEFORE graceful exit
+ telemetryService.stopActiveTime();
+
+ await gracefulExit(1);
} finally {
- // Stop active time tracking
+ // Stop active time tracking for normal completion
telemetryService.stopActiveTime();
}
}
diff --git a/extensions/cli/src/commands/commands.integration.test.ts b/extensions/cli/src/commands/commands.integration.test.ts
index 17bf24428..59984fc9f 100644
--- a/extensions/cli/src/commands/commands.integration.test.ts
+++ b/extensions/cli/src/commands/commands.integration.test.ts
@@ -71,15 +71,17 @@ describe("Slash Commands Integration", () => {
});
});
- it("should only show exit command in remote mode", () => {
+ it("should only show remote mode commands in remote mode", () => {
const commands = getAllSlashCommands(mockAssistant, {
isRemoteMode: true,
});
const commandNames = commands.map((cmd) => cmd.name);
- // In remote mode, only exit command should be available
+ // In remote mode, only remote commands should be available
expect(commandNames).toContain("exit");
- expect(commandNames).toHaveLength(1);
+ expect(commandNames).toContain("diff");
+ expect(commandNames).toContain("apply");
+ expect(commandNames).toHaveLength(3);
});
});
});
diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts
index 419241100..bf19c099f 100644
--- a/extensions/cli/src/commands/commands.ts
+++ b/extensions/cli/src/commands/commands.ts
@@ -40,6 +40,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Sign out of your current session",
category: "system",
},
+ {
+ name: "update",
+ description: "Update the Continue CLI",
+ category: "system",
+ },
{
name: "whoami",
description: "Check who you're currently logged in as",
@@ -65,7 +70,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Manage MCP server connections",
category: "system",
},
-
+ {
+ name: "init",
+ description: "Create an AGENTS.md file",
+ category: "system",
+ },
{
name: "compact",
description: "Summarize chat history into a compact form",
@@ -81,6 +90,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Start a forked chat session from the current history",
category: "system",
},
+ {
+ name: "title",
+ description: "Set the title for the current session",
+ category: "system",
+ },
{
name: "exit",
description: "Exit the chat",
@@ -95,6 +109,16 @@ export const REMOTE_MODE_SLASH_COMMANDS: SlashCommand[] = [
description: "Exit the remote environment",
category: "system",
},
+ {
+ name: "diff",
+ description: "Show the current diff from the remote environment",
+ category: "system",
+ },
+ {
+ name: "apply",
+ description: "Apply the current diff to the local working tree",
+ category: "system",
+ },
];
/**
diff --git a/extensions/cli/src/commands/init.ts b/extensions/cli/src/commands/init.ts
new file mode 100644
index 000000000..f4c31e614
--- /dev/null
+++ b/extensions/cli/src/commands/init.ts
@@ -0,0 +1,45 @@
+import { type AssistantConfig } from "@continuedev/sdk";
+
+import { SlashCommandResult } from "../ui/hooks/useChat.types.js";
+
+function createInitPrompt(): string {
+ return `Please analyze this repository and create a comprehensive AGENTS.md file. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup.
+
+Create an AGENTS.md file with the following structure:
+
+# Repository Overview
+
+## Project Description
+- What this project does
+- Main purpose and goals
+- Key technologies used
+
+## Architecture Overview
+- High-level architecture
+- Main components and their relationships
+- Data flow and system interactions
+
+## Directory Structure
+- Important directories and their purposes
+- Key files and configuration
+- Entry points and main modules
+
+## Development Workflow
+- How to build/run the project
+- Testing approach
+- Development environment setup
+- Lint and format commands
+
+Please create the AGENTS.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the file concise but informational.`;
+}
+
+export async function handleInit(
+ _args: string[],
+ _assistant: AssistantConfig,
+): Promise {
+ const prompt = createInitPrompt();
+
+ return {
+ newInput: prompt,
+ };
+}
diff --git a/extensions/cli/src/commands/login.ts b/extensions/cli/src/commands/login.ts
index 5786904ae..a1c6cc4f8 100644
--- a/extensions/cli/src/commands/login.ts
+++ b/extensions/cli/src/commands/login.ts
@@ -1,6 +1,7 @@
import chalk from "chalk";
import { login as workosLogin } from "../auth/workos.js";
+import { gracefulExit } from "../util/exit.js";
export async function login() {
console.info(chalk.yellow("Logging in to Continue..."));
@@ -10,6 +11,6 @@ export async function login() {
console.info(chalk.green("Successfully logged in!"));
} catch (error: any) {
console.error(chalk.red(`Login failed: ${error.message}`));
- process.exit(1);
+ await gracefulExit(1);
}
}
diff --git a/extensions/cli/src/commands/ls.test.ts b/extensions/cli/src/commands/ls.test.ts
index a7d84d058..c56b7eb8c 100644
--- a/extensions/cli/src/commands/ls.test.ts
+++ b/extensions/cli/src/commands/ls.test.ts
@@ -20,16 +20,26 @@ vi.mock("ink", () => ({
render: vi.fn(() => ({ unmount: vi.fn() })),
}));
-// Mock react
-vi.mock("react", () => ({
- createElement: vi.fn(),
-}));
+// Mock react with createContext
+vi.mock("react", async (importOriginal) => {
+ const actual: any = await importOriginal();
+ return {
+ ...actual,
+ createElement: vi.fn(),
+ createContext: vi.fn(() => ({ Provider: vi.fn(), Consumer: vi.fn() })),
+ };
+});
// Mock the chat command
vi.mock("./chat.js", () => ({
chat: vi.fn(),
}));
+// Mock the remote command
+vi.mock("./remote.js", () => ({
+ remote: vi.fn(),
+}));
+
describe("listSessionsCommand", () => {
const mockListSessions = vi.mocked(sessionModule.listSessions);
@@ -49,6 +59,7 @@ describe("listSessionsCommand", () => {
dateCreated: "2023-01-01T10:00:00.000Z",
workspaceDirectory: "/workspace",
firstUserMessage: "Hello world",
+ isRemote: false,
},
{
sessionId: "session-2",
@@ -56,10 +67,12 @@ describe("listSessionsCommand", () => {
dateCreated: "2023-01-01T09:00:00.000Z",
workspaceDirectory: "/workspace",
firstUserMessage: "Test message",
+ isRemote: true,
+ remoteId: "agent-123",
},
];
- mockListSessions.mockReturnValue(mockSessions);
+ mockListSessions.mockResolvedValue(mockSessions);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
@@ -75,6 +88,8 @@ describe("listSessionsCommand", () => {
workspaceDirectory: "/workspace",
title: "Session 1",
firstUserMessage: "Hello world",
+ isRemote: false,
+ remoteId: undefined,
},
{
id: "session-2",
@@ -82,6 +97,8 @@ describe("listSessionsCommand", () => {
workspaceDirectory: "/workspace",
title: "Session 2",
firstUserMessage: "Test message",
+ isRemote: true,
+ remoteId: "agent-123",
},
],
},
@@ -93,20 +110,23 @@ describe("listSessionsCommand", () => {
consoleSpy.mockRestore();
});
- it("should use limit of 10 for JSON and 20 for TUI", async () => {
- mockListSessions.mockReturnValue([]);
+ it("should call listSessions without limit restrictions", async () => {
+ mockListSessions.mockResolvedValue([]);
- // JSON mode should fetch 10
+ // JSON mode - should call listSessions (implementation decides limit)
await listSessionsCommand({ format: "json" });
- expect(mockListSessions).toHaveBeenCalledWith(10);
+ expect(mockListSessions).toHaveBeenCalled();
- // TUI mode should fetch 20 (so UI can choose how many to display)
+ // TUI mode - should call listSessions (implementation decides limit)
await listSessionsCommand({});
- expect(mockListSessions).toHaveBeenCalledWith(20);
+ expect(mockListSessions).toHaveBeenCalled();
+
+ // Verify it was called twice total
+ expect(mockListSessions).toHaveBeenCalledTimes(2);
});
it("should handle empty sessions gracefully in JSON mode", async () => {
- mockListSessions.mockReturnValue([]);
+ mockListSessions.mockResolvedValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
@@ -120,7 +140,7 @@ describe("listSessionsCommand", () => {
});
it("should handle empty sessions gracefully in TUI mode", async () => {
- mockListSessions.mockReturnValue([]);
+ mockListSessions.mockResolvedValue([]);
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
diff --git a/extensions/cli/src/commands/ls.ts b/extensions/cli/src/commands/ls.ts
index 1962e5ac3..d78ae162d 100644
--- a/extensions/cli/src/commands/ls.ts
+++ b/extensions/cli/src/commands/ls.ts
@@ -1,11 +1,14 @@
import { render } from "ink";
import React from "react";
-import { loadSessionById, listSessions } from "../session.js";
+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 { logger } from "../util/logger.js";
import { chat } from "./chat.js";
+import { remote } from "./remote.js";
interface ListSessionsOptions {
format?: "json";
@@ -23,18 +26,38 @@ 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()}`,
+ );
+ }
+ const data = await resp.json();
+ return data.url;
+}
+
/**
* List recent chat sessions and allow selection
*/
export async function listSessionsCommand(
options: ListSessionsOptions = {},
): Promise {
- // Fetch more sessions than we might display so the UI can choose based on screen height
- // But still limit for JSON output to keep it reasonable
- const sessions = listSessions(options.format === "json" ? 10 : 20);
-
- // Handle JSON format output
+ // Handle JSON format output first
if (options.format === "json") {
+ const sessions = await listSessions();
console.log(
JSON.stringify(
{
@@ -44,6 +67,8 @@ export async function listSessionsCommand(
workspaceDirectory: session.workspaceDirectory,
title: session.title,
firstUserMessage: session.firstUserMessage,
+ isRemote: session.isRemote,
+ remoteId: session.remoteId,
})),
},
null,
@@ -53,6 +78,9 @@ export async function listSessionsCommand(
return;
}
+ // For TUI mode, fetch more sessions than we might display so the UI can choose based on screen height
+ const sessions = await listSessions();
+
// Handle empty sessions case
if (sessions.length === 0) {
console.log(
@@ -67,25 +95,37 @@ export async function listSessionsCommand(
try {
app.unmount();
- // Verify the session exists before trying to load it
- const sessionHistory = loadSessionById(sessionId);
- if (!sessionHistory) {
- console.error(`Session ${sessionId} could not be loaded.`);
- resolve();
- return;
+ // Find the selected session to check if it's remote
+ const selectedSession = sessions.find((s) => s.sessionId === sessionId);
+
+ if (selectedSession?.isRemote && selectedSession.remoteId) {
+ // Handle remote session - use the remote command with the agent URL
+ logger.info(`Opening remote session: ${selectedSession.remoteId}`);
+
+ const tunnelUrl = await getTunnelForAgent(selectedSession.remoteId);
+
+ await remote(undefined, { url: tunnelUrl });
+ } else {
+ // Handle local session
+ const sessionHistory = loadSessionById(sessionId);
+ if (!sessionHistory) {
+ logger.error(`Session ${sessionId} could not be loaded.`);
+ resolve();
+ return;
+ }
+
+ logger.info(`Loading session: ${sessionId}`);
+
+ // Set the session ID so that when chat() runs, it will load this session
+ setSessionId(sessionId);
+
+ // Start chat with resume flag to load the selected session
+ await chat(undefined, {
+ resume: true,
+ headless: false,
+ });
}
- logger.info(`Loading session: ${sessionId}`);
-
- // Set the session ID so that when chat() runs, it will load this session
- setSessionId(sessionId);
-
- // Start chat with resume flag to load the selected session
- await chat(undefined, {
- resume: true,
- headless: false,
- });
-
resolve();
} catch (error) {
logger.error("Error loading session:", error);
diff --git a/extensions/cli/src/commands/remote-test.ts b/extensions/cli/src/commands/remote-test.ts
index e3404c86f..dc5e016e3 100644
--- a/extensions/cli/src/commands/remote-test.ts
+++ b/extensions/cli/src/commands/remote-test.ts
@@ -2,6 +2,7 @@ import chalk from "chalk";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startRemoteTUIChat } from "../ui/index.js";
+import { gracefulExit } from "../util/exit.js";
import { logger } from "../util/logger.js";
export async function remoteTest(
@@ -25,6 +26,6 @@ export async function remoteTest(
logger.error(
chalk.red(`Failed to connect to remote environment: ${error.message}`),
);
- process.exit(1);
+ await gracefulExit(1);
}
}
diff --git a/extensions/cli/src/commands/remote.test.ts b/extensions/cli/src/commands/remote.test.ts
index 5fb3e87f3..d0a1bff50 100644
--- a/extensions/cli/src/commands/remote.test.ts
+++ b/extensions/cli/src/commands/remote.test.ts
@@ -78,7 +78,7 @@ describe("remote command", () => {
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -96,7 +96,7 @@ describe("remote command", () => {
await remote("test prompt", {});
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -190,7 +190,7 @@ describe("remote command", () => {
await remote("test prompt", { branch: testBranch });
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -206,7 +206,7 @@ describe("remote command", () => {
await remote("test prompt", {});
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
@@ -236,6 +236,71 @@ describe("remote command", () => {
prompt: "test prompt",
idempotencyKey: testIdempotencyKey,
branchName: testBranch,
+ agent: undefined,
+ config: undefined,
+ });
+ });
+
+ it("should include config in request body when config option is provided", async () => {
+ const testConfig = "test-config-path";
+
+ await remote("test prompt", { config: testConfig });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL("agents", mockEnv.env.apiBase),
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer test-token",
+ },
+ body: expect.stringContaining(`"config":"${testConfig}"`),
+ }),
+ );
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ new URL("agents", mockEnv.env.apiBase),
+ expect.objectContaining({
+ body: expect.stringContaining(`"agent":"${testConfig}"`),
+ }),
+ );
+ });
+
+ it("should handle proper request body structure with config field", async () => {
+ const testConfig = "my-agent-config";
+ const testIdempotencyKey = "test-with-config";
+
+ await remote("test prompt", {
+ config: testConfig,
+ idempotencyKey: testIdempotencyKey,
+ });
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const requestBody = JSON.parse(fetchCall[1].body);
+
+ expect(requestBody).toEqual({
+ repoUrl: "https://github.com/user/test-repo.git",
+ name: expect.stringMatching(/^devbox-\d+$/),
+ prompt: "test prompt",
+ idempotencyKey: testIdempotencyKey,
+ agent: testConfig,
+ config: testConfig,
+ });
+ });
+
+ it("should not include config in request body when config option is not provided", async () => {
+ await remote("test prompt", {});
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const requestBody = JSON.parse(fetchCall[1].body);
+
+ expect(requestBody).toEqual({
+ repoUrl: "https://github.com/user/test-repo.git",
+ name: expect.stringMatching(/^devbox-\d+$/),
+ prompt: "test prompt",
+ idempotencyKey: undefined,
+ agent: undefined,
+ config: undefined,
});
});
@@ -267,7 +332,7 @@ describe("remote command", () => {
// Should make POST request to create environment
expect(mockFetch).toHaveBeenCalledWith(
- new URL("agents/devboxes", mockEnv.env.apiBase),
+ new URL("agents", mockEnv.env.apiBase),
expect.objectContaining({
method: "POST",
headers: {
diff --git a/extensions/cli/src/commands/remote.ts b/extensions/cli/src/commands/remote.ts
index 1d0594dcb..4608d469c 100644
--- a/extensions/cli/src/commands/remote.ts
+++ b/extensions/cli/src/commands/remote.ts
@@ -4,6 +4,7 @@ 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 { gracefulExit } from "../util/exit.js";
import { getRepoUrl } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
@@ -16,6 +17,7 @@ export async function remote(
start?: boolean;
branch?: string;
repo?: string;
+ config?: string;
} = {},
) {
// Check if prompt should come from stdin instead of parameter
@@ -74,7 +76,7 @@ export async function remote(
console.error(
chalk.red("Not authenticated. Please run 'cn login' first."),
);
- process.exit(1);
+ await gracefulExit(1);
}
const accessToken = getAccessToken(authConfig);
@@ -84,6 +86,8 @@ export async function remote(
name: `devbox-${Date.now()}`,
prompt: actualPrompt,
idempotencyKey: options.idempotencyKey,
+ agent: options.config,
+ config: options.config,
};
// Add branchName to request body if branch option is provided
@@ -91,7 +95,7 @@ export async function remote(
requestBody.branchName = options.branch;
}
- const response = await fetch(new URL("agents/devboxes", env.apiBase), {
+ const response = await fetch(new URL("agents", env.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -154,6 +158,6 @@ export async function remote(
logger.error(
chalk.red(`Failed to create remote environment: ${error.message}`),
);
- process.exit(1);
+ await gracefulExit(1);
}
}
diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts
index 82ca902ea..51db4d9d0 100644
--- a/extensions/cli/src/commands/serve.helpers.ts
+++ b/extensions/cli/src/commands/serve.helpers.ts
@@ -119,9 +119,7 @@ export interface ServerState {
model: any;
isProcessing: boolean;
lastActivity: number;
- messageQueue: string[];
currentAbortController: AbortController | null;
- shouldInterrupt: boolean;
serverRunning: boolean;
pendingPermission: PendingPermission | null;
systemMessage?: string;
diff --git a/extensions/cli/src/commands/serve.test.ts b/extensions/cli/src/commands/serve.test.ts
index 2bc8428bd..87487dc32 100644
--- a/extensions/cli/src/commands/serve.test.ts
+++ b/extensions/cli/src/commands/serve.test.ts
@@ -25,6 +25,7 @@ describe("serve command", () => {
ensureOrganization: vi.fn(),
getOrganizationId: vi.fn(),
isAuthenticated: vi.fn(() => false),
+ isAuthenticatedConfig: vi.fn(() => false),
}));
vi.mock("../onboarding.js", () => ({
diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts
index 5be1eda05..cd23d5919 100644
--- a/extensions/cli/src/commands/serve.ts
+++ b/extensions/cli/src/commands/serve.ts
@@ -1,11 +1,8 @@
-import { exec } from "child_process";
-import { promisify } from "util";
-
import chalk from "chalk";
import type { ChatHistoryItem } from "core/index.js";
import express, { Request, Response } from "express";
-import { getAssistantSlug } from "../auth/workos.js";
+import { getAccessToken, getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
@@ -19,10 +16,13 @@ import {
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
-import { createSession } from "../session.js";
+import { createSession, getCompleteStateSnapshot } from "../session.js";
+import { messageQueue } from "../stream/messageQueue.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
+import { gracefulExit } from "../util/exit.js";
import { formatError } from "../util/formatError.js";
+import { getGitDiffSnapshot } from "../util/git.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
@@ -32,11 +32,11 @@ import {
type ServerState,
} from "./serve.helpers.js";
-const execAsync = promisify(exec);
-
interface ServeOptions extends ExtendedCommandOptions {
timeout?: string;
port?: string;
+ /** Storage identifier for remote sync */
+ id?: string;
}
// eslint-disable-next-line max-statements
@@ -85,6 +85,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
if (authState.organizationId) {
telemetryService.updateOrganization(authState.organizationId);
}
+ const accessToken = getAccessToken(authState.authConfig);
// Log configuration information
const organizationId = authState.organizationId || "personal";
@@ -138,13 +139,43 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
model,
isProcessing: false,
lastActivity: Date.now(),
- messageQueue: [],
currentAbortController: null,
- shouldInterrupt: false,
serverRunning: true,
pendingPermission: null,
};
+ const syncSessionHistory = () => {
+ try {
+ state.session.history = services.chatHistory.getHistory();
+ } catch (e) {
+ logger.debug(
+ `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
+ );
+ }
+ };
+
+ const storageSyncService = services.storageSync;
+ let storageSyncActive = await storageSyncService.startFromOptions({
+ storageOption: options.id,
+ accessToken,
+ syncSessionHistory,
+ getCompleteStateSnapshot: () =>
+ getCompleteStateSnapshot(
+ state.session,
+ state.isProcessing,
+ messageQueue.getQueueLength(),
+ state.pendingPermission,
+ ),
+ isActive: () => state.serverRunning,
+ });
+
+ const stopStorageSync = () => {
+ if (storageSyncActive) {
+ storageSyncService.stop();
+ storageSyncActive = false;
+ }
+ };
+
// Record session start
telemetryService.recordSessionStart();
telemetryService.startActiveTime();
@@ -155,20 +186,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// GET /state - Return the current state
app.get("/state", (_req: Request, res: Response) => {
state.lastActivity = Date.now();
- // Ensure session history reflects ChatHistoryService state
- try {
- state.session.history = services.chatHistory.getHistory();
- } catch (e) {
- logger.debug(
- `Failed to sync session history from ChatHistoryService: ${formatError(e)}`,
- );
- }
- res.json({
- session: state.session, // Return session directly instead of converting
- isProcessing: state.isProcessing,
- messageQueueLength: state.messageQueue.length,
- pendingPermission: state.pendingPermission,
- });
+ syncSessionHistory();
+ const stateSnapshot = getCompleteStateSnapshot(
+ state.session,
+ state.isProcessing,
+ messageQueue.getQueueLength(),
+ state.pendingPermission,
+ );
+ res.json(stateSnapshot);
});
// POST /message - Queue a message and potentially interrupt
@@ -181,17 +206,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Queue the message
- state.messageQueue.push(message);
-
- // If currently processing, set interrupt flag
- if (state.isProcessing && state.currentAbortController) {
- state.shouldInterrupt = true;
- }
+ await messageQueue.enqueueMessage(message);
res.json({
queued: true,
- position: state.messageQueue.length,
- willInterrupt: state.shouldInterrupt,
+ position: messageQueue.getQueueLength(),
});
// Process messages if not already processing
@@ -238,34 +257,25 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state.lastActivity = Date.now();
try {
- // First check if we're in a git repository
- await execAsync("git rev-parse --git-dir");
+ const diffResult = await getGitDiffSnapshot();
- // Get the diff against main branch
- const { stdout } = await execAsync("git diff main");
-
- res.json({
- diff: stdout,
- });
- } catch (error: any) {
- // Git diff returns exit code 1 when there are differences, which is normal
- if (error.code === 1 && error.stdout) {
- res.json({
- diff: error.stdout,
- });
- } else if (error.code === 128) {
- // Handle case where we're not in a git repo or main branch doesn't exist
+ if (!diffResult.repoFound) {
res.status(404).json({
error: "Not in a git repository or main branch doesn't exist",
diff: "",
});
- } else {
- logger.error(`Git diff error: ${formatError(error)}`);
- res.status(500).json({
- error: `Failed to get git diff: ${formatError(error)}`,
- diff: "",
- });
+ return;
}
+
+ res.json({
+ diff: diffResult.diff,
+ });
+ } catch (error) {
+ logger.error(`Git diff error: ${formatError(error)}`);
+ res.status(500).json({
+ error: `Failed to get git diff: ${formatError(error)}`,
+ diff: "",
+ });
}
});
@@ -286,15 +296,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Set server running flag to false to stop processing
state.serverRunning = false;
+ stopStorageSync();
// Abort any current processing
if (state.currentAbortController) {
state.currentAbortController.abort();
}
- // Clear the message queue
- state.messageQueue = [];
-
// Clean up intervals
if (inactivityChecker) {
clearInterval(inactivityChecker);
@@ -302,15 +310,19 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Give a moment for the response to be sent
- setTimeout(() => {
+ const handleExitResponse = () => {
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
- }, 100);
+ };
+ setTimeout(handleExitResponse, 100);
});
- const server = app.listen(port, () => {
+ const server = app.listen(port, async () => {
console.log(chalk.green(`Server started on http://localhost:${port}`));
console.log(chalk.dim("Endpoints:"));
console.log(chalk.dim(" GET /state - Get current agent state"));
@@ -339,7 +351,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// If initial prompt provided, queue it for processing
if (actualPrompt) {
console.log(chalk.dim("\nProcessing initial prompt..."));
- state.messageQueue.push(actualPrompt);
+ await messageQueue.enqueueMessage(actualPrompt);
processMessages(state, llmApi);
}
});
@@ -367,11 +379,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
async function processMessages(state: ServerState, llmApi: any) {
- while (state.messageQueue.length > 0 && state.serverRunning) {
- const userMessage = state.messageQueue.shift()!;
+ let processedMessage = false;
+ while (state.serverRunning) {
+ const queuedMessage = messageQueue.getNextMessage();
+ if (!queuedMessage) {
+ break;
+ }
+
+ const userMessage = queuedMessage.message;
state.isProcessing = true;
- state.shouldInterrupt = false;
state.lastActivity = Date.now();
+ processedMessage = true;
// Add user message via ChatHistoryService (single source of truth)
try {
@@ -393,7 +411,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state,
llmApi,
state.currentAbortController,
- () => state.shouldInterrupt,
+ () => false,
);
// No direct persistence here; ChatHistoryService handles persistence when appropriate
@@ -422,6 +440,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state.isProcessing = false;
}
}
+
+ if (
+ processedMessage &&
+ state.serverRunning &&
+ messageQueue.getQueueLength() === 0
+ ) {
+ await storageSyncService.markAgentStatusUnread();
+ }
}
// Check for inactivity and shutdown
@@ -433,9 +459,13 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
),
);
state.serverRunning = false;
+ stopStorageSync();
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
if (inactivityChecker) {
clearInterval(inactivityChecker);
@@ -448,13 +478,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
process.on("SIGINT", () => {
console.log(chalk.yellow("\nShutting down server..."));
state.serverRunning = false;
+ stopStorageSync();
if (inactivityChecker) {
clearInterval(inactivityChecker);
inactivityChecker = null;
}
server.close(() => {
telemetryService.stopActiveTime();
- process.exit(0);
+ gracefulExit(0).catch((err) => {
+ logger.error(`Graceful exit failed: ${formatError(err)}`);
+ process.exit(1);
+ });
});
});
}
diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts
index 8513b1405..2205e7976 100644
--- a/extensions/cli/src/compaction.ts
+++ b/extensions/cli/src/compaction.ts
@@ -28,6 +28,7 @@ export interface CompactionCallbacks {
* @param model The model configuration
* @param llmApi The LLM API instance
* @param callbacks Optional callbacks for streaming updates
+ * @param abortController Optional abort controller for cancellation
* @returns The compacted history with compaction index
*/
export async function compactChatHistory(
@@ -35,6 +36,7 @@ export async function compactChatHistory(
model: ModelConfig,
llmApi: BaseLlmApi,
callbacks?: CompactionCallbacks,
+ abortController?: AbortController,
): Promise {
// Create a prompt to summarize the conversation
const compactionPrompt: ChatHistoryItem = {
@@ -81,7 +83,7 @@ export async function compactChatHistory(
}
// Stream the compaction response (service drives updates; this collects content locally)
- const controller = new AbortController();
+ const controller = abortController || new AbortController();
let compactionContent = "";
const streamCallbacks: StreamCallbacks = {
diff --git a/extensions/cli/src/config.ts b/extensions/cli/src/config.ts
index 6ff59e327..6c97767bc 100644
--- a/extensions/cli/src/config.ts
+++ b/extensions/cli/src/config.ts
@@ -19,6 +19,43 @@ 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
+ * Handles special logic for continue-proxy provider and constructs the API
+ */
+export function createLlmApi(
+ model: ModelConfig,
+ authConfig: AuthConfig | null,
+): BaseLlmApi | null {
+ const accessToken = getAccessToken(authConfig);
+ const organizationId = getOrganizationId(authConfig);
+
+ const config: LLMConfig =
+ model.provider === "continue-proxy"
+ ? {
+ provider: model.provider,
+ requestOptions: model.requestOptions,
+ apiBase: model.apiBase,
+ apiKey: accessToken ?? undefined,
+ env: {
+ apiKeyLocation: (model as any).apiKeyLocation,
+ orgScopeId: organizationId ?? null,
+ proxyUrl:
+ (model as { onPremProxyUrl: string | undefined })
+ .onPremProxyUrl ?? undefined,
+ },
+ }
+ : {
+ provider: model.provider as any,
+ apiKey: model.apiKey,
+ apiBase: model.apiBase,
+ requestOptions: model.requestOptions,
+ env: model.env,
+ };
+
+ return constructLlmApi(config) ?? null;
+}
+
export function getLlmApi(
assistant: AssistantUnrolled,
authConfig: AuthConfig,
@@ -38,32 +75,7 @@ export function getLlmApi(
);
}
- const accessToken = getAccessToken(authConfig);
- const organizationId = getOrganizationId(authConfig);
-
- const config: LLMConfig =
- model.provider === "continue-proxy"
- ? {
- provider: model.provider,
- requestOptions: model.requestOptions,
- apiBase: model.apiBase,
- apiKey: accessToken ?? undefined,
- env: {
- apiKeyLocation: (model as any).apiKeyLocation,
- // envSecretLocations: model.env,
- orgScopeId: organizationId,
- proxyUrl: undefined, // TODO
- },
- }
- : {
- provider: model.provider as any,
- apiKey: model.apiKey,
- apiBase: model.apiBase,
- requestOptions: model.requestOptions,
- env: model.env,
- };
-
- const llmApi = constructLlmApi(config);
+ const llmApi = createLlmApi(model, authConfig);
if (!llmApi) {
throw new Error(
diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts
index 3fe00fd21..423875312 100644
--- a/extensions/cli/src/configLoader.ts
+++ b/extensions/cli/src/configLoader.ts
@@ -55,7 +55,7 @@ export async function loadConfiguration(
const config = await loadFromSource(
configSource,
accessToken,
- organizationId,
+ organizationId ?? null,
apiClient,
);
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 a13823c69..a5ccf0970 100644
--- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts
+++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts
@@ -8,8 +8,8 @@ import {
} from "../test-helpers/cli-helpers.js";
import {
cleanupMockLLMServer,
- type MockLLMServer,
createMockLLMServer,
+ type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => {
@@ -80,9 +80,9 @@ models:
expect(userMessage.content).toBe("Hi there");
}, 20000);
- it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => {
+ it("should create config but fail with invalid API key when no config exists", async () => {
// This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY
- // when no config file exists in headless mode
+ // when no config file exists, but fails when the API key is invalid
const result = await runCLI(context, {
args: ["-p", "test prompt"],
@@ -90,13 +90,17 @@ models:
ANTHROPIC_API_KEY: "TEST-test-invalid-key-format",
CONTINUE_GLOBAL_DIR: context.testDir + "/.continue",
},
- expectError: false, // Config creation succeeds even with invalid key
+ expectError: true, // API call should fail with invalid key
timeout: 15000,
});
- // The CLI should create config and exit successfully in headless mode
- // (it doesn't actually make API calls unless there's a valid provider setup)
- expect(result.exitCode).toBe(0);
+ // The CLI should create config but fail due to invalid API key
+ // This is expected behavior - invalid API keys should cause authentication errors
+ expect(result.exitCode).toBe(1);
+
+ // Should contain authentication error (not service initialization error)
+ expect(result.stderr).toContain("authentication_error");
+ expect(result.stderr).toContain("invalid x-api-key");
// Should NOT contain the old error about service initialization
expect(result.stderr).not.toContain("Failed to initialize ConfigService");
diff --git a/extensions/cli/src/e2e/home-directory-warning.test.ts b/extensions/cli/src/e2e/home-directory-warning.test.ts
deleted file mode 100644
index a5caf9d52..000000000
--- a/extensions/cli/src/e2e/home-directory-warning.test.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-import * as fs from "node:fs";
-import * as path from "node:path";
-
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-
-import {
- cleanupTestContext,
- createTestConfig,
- createTestContext,
- runCLI,
- type CLITestContext,
-} from "../test-helpers/cli-helpers.js";
-import { HOME_DIRECTORY_WARNING } from "../ui/IntroMessage.js";
-
-describe("E2E: Home Directory Warning", () => {
- let context: CLITestContext;
-
- const testConfig = `name: Test Assistant
-version: 1.0.0
-schema: v1
-models:
- - model: gpt-4
- provider: openai
- apiKey: test-key
- roles:
- - chat`;
-
- beforeEach(async () => {
- context = await createTestContext();
- });
-
- afterEach(async () => {
- await cleanupTestContext(context);
- });
-
- describe("home directory detection", () => {
- it("should NOT show warning in headless mode even when running from home directory", async () => {
- await createTestConfig(context, testConfig);
-
- // Simulate running from home directory using the isolated test dir
- const result = await runCLI(context, {
- args: ["-p", "--config", context.configPath!, "test prompt"],
- env: {
- OPENAI_API_KEY: "test-key",
- // Ensure home vars point to the isolated test dir
- HOME: context.testDir,
- USERPROFILE: context.testDir,
- HOMEDRIVE: path.parse(context.testDir).root,
- HOMEPATH: path.relative(
- path.parse(context.testDir).root,
- context.testDir,
- ),
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- },
- timeout: 5000,
- expectError: true,
- });
-
- // Should NOT contain the home directory warning in headless mode
- const output = result.stdout + result.stderr;
- expect(output).not.toContain(HOME_DIRECTORY_WARNING);
- });
-
- it("should show warning when running from home directory in TUI mode", async () => {
- await createTestConfig(context, testConfig);
-
- // Test TUI mode (without -p flag) from an isolated "home" directory
- const result = await runCLI(context, {
- args: ["--config", context.configPath!],
- env: {
- OPENAI_API_KEY: "test-key",
- HOME: context.testDir,
- USERPROFILE: context.testDir,
- HOMEDRIVE: path.parse(context.testDir).root,
- HOMEPATH: path.relative(
- path.parse(context.testDir).root,
- context.testDir,
- ),
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- },
- timeout: 3000,
- expectError: true,
- });
-
- // In TUI mode, if we get any meaningful output, check for warning
- const output = result.stdout + result.stderr;
- if (
- output.includes("Continue") ||
- output.includes("Agent") ||
- output.includes("Model")
- ) {
- expect(output).toContain(HOME_DIRECTORY_WARNING);
- } else {
- // TUI mode likely failed to start in test environment, which is expected
- // The important thing is that it attempted TUI mode, not headless mode
- expect(result.exitCode).toBeDefined();
- }
- });
-
- it("should NOT show warning in headless mode regardless of platform", async () => {
- await createTestConfig(context, testConfig);
-
- // Test with different platform-specific environment variables
- const platformEnvs: Record[] = [
- // Unix-style
- {
- HOME: context.testDir,
- OPENAI_API_KEY: "test-key",
- },
- // Windows-style
- {
- USERPROFILE: context.testDir,
- HOMEDRIVE: path.parse(context.testDir).root,
- HOMEPATH: path.relative(
- path.parse(context.testDir).root,
- context.testDir,
- ),
- OPENAI_API_KEY: "test-key",
- },
- ];
-
- for (const env of platformEnvs) {
- const result = await runCLI(context, {
- args: ["-p", "--config", context.configPath!, "test prompt"],
- env: {
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- ...env,
- },
- timeout: 5000,
- expectError: true,
- });
-
- // Should NOT contain warning in headless mode regardless of platform
- const output = result.stdout + result.stderr;
- expect(output).not.toContain(HOME_DIRECTORY_WARNING);
- }
- });
-
- it("should NOT show warning in headless mode with symlinked home directories", async () => {
- await createTestConfig(context, testConfig);
-
- // Create a symlink to the isolated home directory to simulate symlinked home paths
- const realHome = fs.realpathSync(context.testDir);
- const linkPath = path.join(
- path.dirname(realHome),
- `${path.basename(realHome)}-link`,
- );
- try {
- if (!fs.existsSync(linkPath)) {
- fs.symlinkSync(realHome, linkPath, "dir");
- }
- } catch {
- // If symlink creation fails (e.g., on Windows without privileges), skip this specific scenario
- }
-
- const result = await runCLI(context, {
- args: ["-p", "--config", context.configPath!, "test prompt"],
- env: {
- OPENAI_API_KEY: "test-key",
- // Point HOME to the symlink while cwd remains the real path
- HOME: fs.existsSync(linkPath) ? linkPath : realHome,
- USERPROFILE: fs.existsSync(linkPath) ? linkPath : realHome,
- HOMEDRIVE: path.parse(realHome).root,
- HOMEPATH: path.relative(path.parse(realHome).root, realHome),
- CONTINUE_GLOBAL_DIR: path.join(realHome, ".continue-global"),
- },
- timeout: 5000,
- expectError: true,
- });
-
- // Should NOT detect home directory warning in headless mode even with resolved paths
- const output = result.stdout + result.stderr;
- expect(output).not.toContain(HOME_DIRECTORY_WARNING);
- });
-
- it("should work in TUI mode (when available)", async () => {
- await createTestConfig(context, testConfig);
-
- // Test TUI mode behavior (though it may fail in test environment)
- const result = await runCLI(context, {
- args: ["--config", context.configPath!],
- env: {
- OPENAI_API_KEY: "test-key",
- HOME: context.testDir,
- USERPROFILE: context.testDir,
- HOMEDRIVE: path.parse(context.testDir).root,
- HOMEPATH: path.relative(
- path.parse(context.testDir).root,
- context.testDir,
- ),
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- },
- timeout: 3000,
- expectError: true,
- });
-
- // Even if TUI fails to start properly in test environment,
- // the warning should still be present in any output
- const output = result.stdout + result.stderr;
- if (output.includes("Continue")) {
- // If we got any meaningful output, check for warning
- expect(output).toContain(HOME_DIRECTORY_WARNING);
- }
- });
- });
-
- describe("edge cases", () => {
- it("should handle case where home directory cannot be determined", async () => {
- await createTestConfig(context, testConfig);
-
- const result = await runCLI(context, {
- args: ["-p", "--config", context.configPath!, "test prompt"],
- env: {
- OPENAI_API_KEY: "test-key",
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- // Mask home directory environment variables so os.homedir() cannot derive a value
- HOME: "",
- USERPROFILE: "",
- HOMEDRIVE: "",
- HOMEPATH: "",
- },
- timeout: 5000,
- expectError: true,
- });
-
- // Should not crash when home directory cannot be determined
- expect(result.exitCode).toBeDefined();
- const output = result.stdout + result.stderr;
- // Should not show warning if home cannot be determined (and we're in headless mode anyway)
- expect(output).not.toContain(HOME_DIRECTORY_WARNING);
- });
-
- it("should handle relative vs absolute path comparisons", async () => {
- await createTestConfig(context, testConfig);
-
- // Use a HOME that is equivalent but not identical (e.g., with './')
- const altHome = path.join(context.testDir, ".");
- const result = await runCLI(context, {
- args: ["-p", "--config", context.configPath!, "test prompt"],
- env: {
- OPENAI_API_KEY: "test-key",
- HOME: altHome,
- USERPROFILE: altHome,
- HOMEDRIVE: path.parse(altHome).root,
- HOMEPATH: path.relative(path.parse(altHome).root, altHome),
- CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
- },
- timeout: 5000,
- expectError: true,
- });
-
- // Should handle path resolution correctly (no crash)
- expect(result.exitCode).toBeDefined();
- });
- });
-});
diff --git a/extensions/cli/src/flags/flagValidator.ts b/extensions/cli/src/flags/flagValidator.ts
index fb9b29195..2c5790b5a 100644
--- a/extensions/cli/src/flags/flagValidator.ts
+++ b/extensions/cli/src/flags/flagValidator.ts
@@ -219,5 +219,7 @@ export function handleValidationErrors(errors: ValidationError[]): never {
safeStderr(`\nFound ${errors.length} validation errors.\n`);
}
- process.exit(1);
+ // Use async graceful exit without awaiting (we must satisfy never)
+ import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
+ throw new Error("Exiting due to validation errors");
}
diff --git a/extensions/cli/src/freeTrialTransition.ts b/extensions/cli/src/freeTrialTransition.ts
index 2a2514c89..f7b7eee69 100644
--- a/extensions/cli/src/freeTrialTransition.ts
+++ b/extensions/cli/src/freeTrialTransition.ts
@@ -4,13 +4,14 @@ import * as path from "path";
import chalk from "chalk";
import open from "open";
-import * as readlineSync from "readline-sync";
import { env } from "./env.js";
import {
- isValidAnthropicApiKey,
getApiKeyValidationError,
+ isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
+import { gracefulExit } from "./util/exit.js";
+import { question, questionWithChoices } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@@ -51,10 +52,12 @@ export async function handleMaxedOutFreeTrial(
console.log(chalk.white("1. 💳 Sign up for models add-on"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
- const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
- limit: ["1", "2", ""],
- limitMessage: chalk.dim("Please enter 1 or 2"),
- });
+ const choice = await questionWithChoices(
+ chalk.yellow("\nEnter choice (1): "),
+ ["1", "2", ""],
+ "1",
+ chalk.dim("Please enter 1 or 2"),
+ );
if (choice === "1" || choice === "") {
// Option 1: Open models setup page
@@ -80,20 +83,17 @@ export async function handleMaxedOutFreeTrial(
}
// Wait for user to acknowledge
- readlineSync.question(chalk.dim("\nPress Enter to exit..."));
- process.exit(0);
+ await question(chalk.dim("\nPress Enter to exit..."));
+ await gracefulExit(0);
} else if (choice === "2") {
// Option 2: Enter Anthropic API key
- const apiKey = readlineSync.question(
+ const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
- {
- hideEchoBack: true,
- },
);
if (!isValidAnthropicApiKey(apiKey)) {
console.log(chalk.red(`❌ ${getApiKeyValidationError(apiKey)}`));
- process.exit(1);
+ await gracefulExit(1);
}
try {
@@ -108,7 +108,7 @@ export async function handleMaxedOutFreeTrial(
}
} catch (error) {
console.log(chalk.red(`❌ Error saving API key: ${error}`));
- process.exit(1);
+ await gracefulExit(1);
}
}
@@ -137,5 +137,5 @@ export async function handleMaxedOutFreeTrial(
child.unref();
// Exit the current process
- process.exit(0);
+ await gracefulExit(0);
}
diff --git a/extensions/cli/src/hubLoader.test.ts b/extensions/cli/src/hubLoader.test.ts
index b19d32f97..542f34556 100644
--- a/extensions/cli/src/hubLoader.test.ts
+++ b/extensions/cli/src/hubLoader.test.ts
@@ -1,12 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
+import * as hubLoader from "./hubLoader.js";
+
+const {
loadPackageFromHub,
mcpProcessor,
modelProcessor,
promptProcessor,
ruleProcessor,
-} from "./hubLoader.js";
+ processRule,
+} = hubLoader;
// Store the original fetch before any mocking
const originalFetch = global.fetch;
@@ -136,6 +139,46 @@ describe("hubLoader", () => {
});
});
+ describe("processRule", () => {
+ beforeEach(() => {
+ // Ensure mocks are set up properly for processRule tests
+ global.fetch = mockFetch;
+ });
+
+ it("should treat multi-line strings as inline rules", async () => {
+ const loadRuleSpy = vi
+ .spyOn(hubLoader, "loadRuleFromHub")
+ .mockResolvedValue("hub-content");
+
+ const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line";
+ const result = await processRule(multilineRule);
+
+ expect(result).toBe(multilineRule);
+ expect(loadRuleSpy).not.toHaveBeenCalled();
+
+ loadRuleSpy.mockRestore();
+ });
+
+ it("should still treat owner/package strings as hub slugs", async () => {
+ // Mock fetch to return a proper response for this test
+ const JSZip = (await import("jszip")).default;
+ const zip = new JSZip();
+ zip.file("rule.md", "hub-content");
+ const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
+
+ mockFetch.mockResolvedValueOnce({
+ ok: true,
+ arrayBuffer: () => Promise.resolve(zipBuffer),
+ } as Response);
+
+ const slug = "owner/package";
+ const result = await processRule(slug);
+
+ expect(result).toBe("hub-content");
+ expect(mockFetch).toHaveBeenCalled();
+ });
+ });
+
describe("processors", () => {
it("should define rule processor correctly", () => {
expect(ruleProcessor.type).toBe("rule");
diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts
index 0a6e39756..533980541 100644
--- a/extensions/cli/src/hubLoader.ts
+++ b/extensions/cli/src/hubLoader.ts
@@ -3,6 +3,11 @@ import JSZip from "jszip";
import { env } from "./env.js";
import { logger } from "./util/logger.js";
+/**
+ * Pattern to match valid hub slugs (owner/package format)
+ */
+const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
+
/**
* Hub package type definitions
*/
@@ -220,28 +225,23 @@ export const loadPromptFromHub = (slug: string) =>
* Process a rule specification - supports file paths, hub slugs, or direct content
*/
export async function processRule(ruleSpec: string): Promise {
- // If it looks like a hub slug (contains / but doesn't start with . or /)
- if (
- ruleSpec.includes("/") &&
- !ruleSpec.startsWith(".") &&
- !ruleSpec.startsWith("/")
- ) {
- return await loadRuleFromHub(ruleSpec);
- }
+ const trimmedRuleSpec = ruleSpec.trim();
+ const hasNewline = /[\r\n]/.test(ruleSpec);
- // If it looks like a file path
- if (
- ruleSpec.startsWith(".") ||
- ruleSpec.startsWith("/") ||
- ruleSpec.includes("/") ||
- ruleSpec.includes("\\") ||
- /\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end
- ) {
+ // If it looks like a file path (single line, typical path indicators)
+ const looksLikePath =
+ !hasNewline &&
+ (trimmedRuleSpec.startsWith(".") ||
+ trimmedRuleSpec.startsWith("/") ||
+ trimmedRuleSpec.includes("\\") ||
+ /\.[a-zA-Z]+$/.test(trimmedRuleSpec));
+
+ if (looksLikePath) {
const fs = await import("fs");
const path = await import("path");
try {
- const absolutePath = path.resolve(ruleSpec);
+ const absolutePath = path.resolve(trimmedRuleSpec);
if (!fs.existsSync(absolutePath)) {
throw new Error(`Rule file not found: ${ruleSpec}`);
}
@@ -253,6 +253,23 @@ export async function processRule(ruleSpec: string): Promise {
}
}
+ // Check if it might be a hub slug (contains "/" and is a single line)
+ if (!hasNewline && trimmedRuleSpec.includes("/")) {
+ const parts = trimmedRuleSpec.split("/");
+
+ // If it's exactly 2 parts and matches hub slug pattern, treat as hub slug
+ if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) {
+ return await loadRuleFromHub(trimmedRuleSpec);
+ }
+
+ // If it has more than 2 parts, it's an invalid hub slug
+ if (parts.length > 2) {
+ throw new Error(
+ `Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`,
+ );
+ }
+ }
+
// Otherwise, treat it as direct string content
return ruleSpec;
}
diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts
index cd7f34704..392acf02e 100644
--- a/extensions/cli/src/index.ts
+++ b/extensions/cli/src/index.ts
@@ -19,6 +19,8 @@ import {
import { configureConsoleForHeadless, safeStderr } from "./init.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
+import { posthogService } from "./telemetry/posthogService.js";
+import { gracefulExit } from "./util/exit.js";
import { logger } from "./util/logger.js";
import { readStdinSync } from "./util/stdin.js";
import { getVersion } from "./version.js";
@@ -62,8 +64,7 @@ export function enableSigintHandler() {
if (tuiUnmount) {
tuiUnmount();
}
- await sentryService.flush();
- process.exit(0);
+ await gracefulExit(0);
} else {
// First Ctrl+C or too much time elapsed - show exit message
lastCtrlCTime = now;
@@ -106,6 +107,11 @@ process.on("uncaughtException", (error) => {
// Don't exit the process, just log the error
});
+// keyboard interruption handler for non-TUI flows
+process.on("SIGINT", async () => {
+ await gracefulExit(130);
+});
+
const program = new Command();
program
@@ -113,7 +119,7 @@ program
.description(
"Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.",
)
- .version(getVersion());
+ .version(getVersion(), "-v, --version", "Display version number");
// Root command - chat functionality (default)
// Add common options to the root command
@@ -131,6 +137,8 @@ addCommonOptions(program)
.option("--resume", "Resume from last session")
.option("--fork ", "Fork from an existing session ID")
.action(async (prompt, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "cn" });
// Handle piped input - detect it early and decide on mode
let stdinInput = null;
@@ -217,7 +225,7 @@ addCommonOptions(program)
safeStderr(' cn -p "please review my current git diff"\n');
safeStderr(' echo "hello" | cn -p\n');
safeStderr(' cn -p "analyze the code in src/"\n');
- process.exit(1);
+ await gracefulExit(1);
}
// Map --print to headless mode
@@ -231,6 +239,8 @@ program
.command("login")
.description("Authenticate with Continue")
.action(async () => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "login" });
await login();
});
@@ -239,6 +249,8 @@ program
.command("logout")
.description("Log out from Continue")
.action(async () => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "logout" });
await logout();
});
@@ -248,15 +260,19 @@ program
.description("List recent chat sessions and select one to resume")
.option("--json", "Output in JSON format")
.action(async (options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "ls" });
await listSessionsCommand({
format: options.json ? "json" : undefined,
});
});
// Remote subcommand
-program
- .command("remote [prompt]", { hidden: true })
- .description("Launch a remote instance of the cn agent")
+addCommonOptions(
+ program
+ .command("remote [prompt]", { hidden: true })
+ .description("Launch a remote instance of the cn agent"),
+)
.option(
"--url ",
"Connect directly to the specified URL instead of creating a new remote environment",
@@ -278,6 +294,11 @@ program
"Specify the repository URL to use in the remote environment",
)
.action(async (prompt: string | undefined, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", {
+ command: "remote",
+ flagS: options.start,
+ });
await remote(prompt, options);
});
@@ -291,7 +312,13 @@ program
"300",
)
.option("--port ", "Port to run the server on (default: 8000)", "8000")
+ .option(
+ "--id ",
+ "Upload session snapshots to Continue-managed storage using the provided identifier",
+ )
.action(async (prompt, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "serve" });
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
@@ -309,6 +336,8 @@ program
.description("Test remote TUI mode with a local server")
.option("--url ", "Server URL (default: http://localhost:8000)")
.action(async (prompt: string | undefined, options) => {
+ // Telemetry: record command invocation
+ await posthogService.capture("cliCommand", { command: "remote-test" });
await remoteTest(prompt, options.url);
});
@@ -316,21 +345,22 @@ program
program.on("command:*", () => {
console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
program.outputHelp();
- process.exit(1);
+ void gracefulExit(1);
});
-// Parse arguments and handle errors
-try {
- program.parse();
-} catch (error) {
- console.error(error);
- sentryService.captureException(
- error instanceof Error ? error : new Error(String(error)),
- );
- process.exit(1);
+export async function runCli(): Promise {
+ // Parse arguments and handle errors
+ try {
+ program.parse();
+ } catch (error) {
+ console.error(error);
+ sentryService.captureException(
+ error instanceof Error ? error : new Error(String(error)),
+ );
+ process.exit(1);
+ }
+
+ process.on("SIGTERM", async () => {
+ await gracefulExit(0);
+ });
}
-
-process.on("SIGTERM", async () => {
- await sentryService.flush();
- process.exit(0);
-});
diff --git a/extensions/cli/src/infoScreen.ts b/extensions/cli/src/infoScreen.ts
index 2a95bf363..fc495c94c 100644
--- a/extensions/cli/src/infoScreen.ts
+++ b/extensions/cli/src/infoScreen.ts
@@ -9,13 +9,10 @@ import {
} from "./auth/workos.js";
import { services } from "./services/index.js";
import { getCurrentSession, getSessionFilePath } from "./session.js";
-import { posthogService } from "./telemetry/posthogService.js";
import { logger } from "./util/logger.js";
import { getVersion } from "./version.js";
export async function handleInfoSlashCommand() {
- posthogService.capture("useSlashCommand", { name: "info" });
-
const infoLines = [];
// Version and working directory info
diff --git a/extensions/cli/src/init.ts b/extensions/cli/src/init.ts
index 47766c0bb..809400492 100644
--- a/extensions/cli/src/init.ts
+++ b/extensions/cli/src/init.ts
@@ -3,10 +3,11 @@
* This file intercepts console and stdout/stderr to prevent dependency logging
*/
+import { isHeadlessMode as checkIsHeadlessMode } from "./util/cli.js";
+
// Check if we're in headless mode by looking at process arguments
// We need to do this before any imports to catch early logging
-const args = process.argv.slice(2);
-const isHeadlessMode = args.includes("-p") || args.includes("--print");
+const isHeadlessMode = checkIsHeadlessMode();
// Store original methods before ANY dependencies can use them
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts
index 7eb59d89a..fa5b094b4 100644
--- a/extensions/cli/src/onboarding.ts
+++ b/extensions/cli/src/onboarding.ts
@@ -5,7 +5,6 @@ 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 * as readlineSync from "readline-sync";
import { processPromptOrRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
@@ -16,6 +15,7 @@ import {
getApiKeyValidationError,
isValidAnthropicApiKey,
} from "./util/apiKeyValidation.js";
+import { question, questionWithChoices } from "./util/prompt.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
@@ -97,22 +97,24 @@ async function runOnboardingFlow(
console.log(chalk.white("1. ⏩ Log in with Continue"));
console.log(chalk.white("2. 🔑 Enter your Anthropic API key"));
- const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
- limit: ["1", "2", ""],
- limitMessage: chalk.dim("Please enter 1 or 2"),
- });
+ const choice = await questionWithChoices(
+ chalk.yellow("\nEnter choice (1): "),
+ ["1", "2", ""],
+ "1",
+ chalk.dim("Please enter 1 or 2"),
+ );
if (choice === "1" || choice === "") {
const newAuthConfig = await login();
- const result = await initialize(newAuthConfig, undefined);
+ const { ensureOrganization } = await import("./auth/workos.js");
+ const finalAuthConfig = await ensureOrganization(newAuthConfig);
+
+ const result = await initialize(finalAuthConfig, undefined);
return { ...result, wasOnboarded: true };
} else if (choice === "2") {
- const apiKey = readlineSync.question(
+ const apiKey = await question(
chalk.white("\nEnter your Anthropic API key: "),
- {
- hideEchoBack: true,
- },
);
if (!isValidAnthropicApiKey(apiKey)) {
diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts
index b28034b40..259dd06c5 100644
--- a/extensions/cli/src/permissions/permissionChecker.test.ts
+++ b/extensions/cli/src/permissions/permissionChecker.test.ts
@@ -1,4 +1,4 @@
-import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as toolsModule from "../tools/index.js";
@@ -604,7 +604,10 @@ describe("Permission Checker", () => {
name: "Bash",
displayName: "Bash",
description: "Execute bash commands",
- parameters: {},
+ parameters: {
+ type: "object" as const,
+ properties: {},
+ },
isBuiltIn: true,
evaluateToolCallPolicy: vi.fn(),
run: vi.fn(),
@@ -882,7 +885,10 @@ describe("Permission Checker", () => {
name: "Read",
displayName: "Read",
description: "Read files",
- parameters: {},
+ parameters: {
+ type: "object" as const,
+ properties: {},
+ },
isBuiltIn: true,
run: vi.fn(),
// No evaluateToolCallPolicy
diff --git a/extensions/cli/src/services/FileIndexService.test.ts b/extensions/cli/src/services/FileIndexService.test.ts
index 9d5afb23a..193ca8b15 100644
--- a/extensions/cli/src/services/FileIndexService.test.ts
+++ b/extensions/cli/src/services/FileIndexService.test.ts
@@ -59,24 +59,25 @@ describe("FileIndexService", () => {
expect(filePaths).toContain("README.md");
});
- it("should filter files correctly", async () => {
+ it("should filter files correctly with fzf", async () => {
// Create test files
fs.writeFileSync("component.tsx", "export default () => ");
fs.writeFileSync("utils.ts", "export const util = () => {}");
- fs.writeFileSync("styles.css", ".test { color: red; }");
+ fs.writeFileSync("readme.md", "# Documentation");
await service.initialize();
- // Test filtering by extension
- const tsFiles = service.filterFiles("ts");
- expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true);
- expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true);
- expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false);
+ // Test filtering with more specific terms that won't fuzzy match
+ const tsxFiles = await service.filterFiles("tsx");
+ expect(tsxFiles.some((f) => f.path === "component.tsx")).toBe(true);
+ expect(tsxFiles.some((f) => f.path === "utils.ts")).toBe(false);
+ expect(tsxFiles.some((f) => f.path === "readme.md")).toBe(false);
// Test filtering by name
- const componentFiles = service.filterFiles("component");
+ const componentFiles = await service.filterFiles("component");
expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true);
expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false);
+ expect(componentFiles.some((f) => f.path === "readme.md")).toBe(false);
});
it("should handle empty directory", async () => {
@@ -123,7 +124,7 @@ describe("FileIndexService", () => {
await service.initialize();
- const files = service.filterFiles("");
+ const files = await service.filterFiles("");
expect(files[0].path).toBe("alpha.js");
expect(files[1].path).toBe("beta.js");
expect(files[2].path).toBe("zebra.js");
@@ -137,7 +138,7 @@ describe("FileIndexService", () => {
await service.initialize();
- const filtered = service.filterFiles("test");
+ const filtered = await service.filterFiles("test");
// Should include both files that match the filter
expect(filtered.length).toBeGreaterThanOrEqual(2);
@@ -155,7 +156,7 @@ describe("FileIndexService", () => {
await service.initialize();
- const files = service.filterFiles("", 5);
+ const files = await service.filterFiles("", 5);
expect(files.length).toBe(5);
});
@@ -173,4 +174,36 @@ describe("FileIndexService", () => {
await service.refreshIndex();
expect(service.getFiles().length).toBe(2);
});
+
+ it("should handle fuzzy search with AsyncFzf", async () => {
+ // Create test files for fuzzy matching
+ fs.writeFileSync("user-service.ts", "export class UserService {}");
+ fs.writeFileSync("user-model.ts", "export interface User {}");
+ fs.writeFileSync("config.json", "{}");
+
+ await service.initialize();
+
+ // Test fuzzy search (should match both user files)
+ const userFiles = await service.filterFiles("usmo"); // us(er) mo(del)
+ expect(userFiles.length).equal(1);
+ expect(userFiles.some((f) => f.path === "user-model.ts")).toBe(true);
+ });
+
+ it("should find files with @ symbols when searched with @ pattern", async () => {
+ // Create test file with @ symbols in the name
+ fs.writeFileSync("test@123.txt", "test content");
+ fs.writeFileSync("regular-file.js", "normal file");
+ fs.writeFileSync("other@456.md", "other content");
+
+ await service.initialize();
+
+ // Search for "test@123" - should match "test@123.txt"
+ const results = await service.filterFiles("test@123");
+
+ expect(results.length).equal(1);
+ expect(results.some((f) => f.path === "test@123.txt")).toBe(true);
+
+ // Should not match files that don't contain the @ pattern
+ expect(results.some((f) => f.path === "regular-file.js")).toBe(false);
+ });
});
diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts
index 3ef74c021..518ffe9c4 100644
--- a/extensions/cli/src/services/FileIndexService.ts
+++ b/extensions/cli/src/services/FileIndexService.ts
@@ -1,9 +1,7 @@
-import { glob, GlobOptionsWithFileTypesFalse } from "glob";
+import { fdir } from "fdir";
+import { AsyncFzf, FzfResultItem } from "fzf";
-import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
-import { getFileWatcher } from "../util/fileWatcher.js";
-import { isGitRepo } from "../util/git.js";
-import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
+import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
@@ -12,6 +10,7 @@ import { serviceContainer } from "./ServiceContainer.js";
export interface FileItem {
path: string;
displayName: string;
+ positions?: Set;
}
export interface FileIndexServiceState {
@@ -21,9 +20,79 @@ export interface FileIndexServiceState {
}
export class FileIndexService extends BaseService {
- private fileSet = new Set();
- private fileWatcherInitialized = false;
- private fileWatcherUnsubscribe: (() => void) | null = null;
+ private fzf: AsyncFzf | null = null;
+
+ // Helper to check if a file should be included based on FILE_PATTERNS
+ private shouldIncludeFile(filePath: string): boolean {
+ const fileName = filePath.split("/").pop()?.toLowerCase() || "";
+ const ext = fileName.split(".").pop();
+
+ // Check if file matches any of the original FILE_PATTERNS
+ const supportedExtensions = [
+ "ts",
+ "tsx",
+ "js",
+ "jsx",
+ "py",
+ "java",
+ "cpp",
+ "c",
+ "h",
+ "hpp",
+ "cs",
+ "go",
+ "rs",
+ "rb",
+ "php",
+ "swift",
+ "kt",
+ "scala",
+ "md",
+ "json",
+ "yaml",
+ "yml",
+ "xml",
+ "html",
+ "css",
+ "scss",
+ "sass",
+ "less",
+ "sql",
+ "sh",
+ "dockerfile",
+ "makefile",
+ "cmake",
+ "gradle",
+ "toml",
+ "ini",
+ "env",
+ "txt",
+ "log",
+ ];
+
+ // Check extension match
+ if (ext && supportedExtensions.includes(ext)) {
+ return true;
+ }
+
+ // Check special file patterns
+ if (
+ fileName.startsWith("readme") ||
+ fileName.startsWith("license") ||
+ fileName.startsWith("changelog") ||
+ fileName === "package.json" ||
+ fileName === "cargo.toml" ||
+ fileName === "pyproject.toml" ||
+ fileName === "composer.json" ||
+ fileName === "gemfile" ||
+ fileName === ".gitignore" ||
+ fileName.startsWith(".env")
+ ) {
+ return true;
+ }
+
+ return false;
+ }
constructor() {
super("FileIndexService", {
@@ -35,23 +104,11 @@ export class FileIndexService extends BaseService {
async doInitialize(): Promise {
await this.performFullIndex();
- this.setupFileWatcher();
return this.getState();
}
async cleanup(): Promise {
- if (this.fileWatcherUnsubscribe) {
- this.fileWatcherUnsubscribe();
- this.fileWatcherUnsubscribe = null;
- }
-
- // Stop the file watcher to prevent resource leaks
- if (this.fileWatcherInitialized) {
- const watcher = getFileWatcher();
- watcher.stopWatching();
- }
-
- this.fileWatcherInitialized = false;
+ // No cleanup needed - no file watchers or subscriptions
}
/**
@@ -65,37 +122,74 @@ export class FileIndexService extends BaseService {
serviceContainer.set("fileIndex", currentState);
}
- private async performFullIndex(): Promise {
+ private async performFullIndex(
+ bypassTimeout: boolean = false,
+ ): Promise {
this.setState({ isIndexing: true, error: null });
try {
- const inGitRepo = isGitRepo();
+ const currentDir = process.cwd();
+ logger.debug(`Starting file index in directory: ${currentDir}`);
- if (isInHomeDirectory()) {
- this.setState({
- isIndexing: false,
- error: "Skipping full index as in home directory",
+ // Create file indexing promise
+ const fileIndexPromise = new fdir()
+ .withFullPaths()
+ .withRelativePaths()
+ .filter((path) => {
+ // Use the helper function that implements original FILE_PATTERNS logic
+ return this.shouldIncludeFile(path);
+ })
+ .exclude((dirName) => {
+ // Exclude directories based on FILE_IGNORE_PATTERNS
+ for (const pattern of FILE_IGNORE_PATTERNS) {
+ if (pattern.startsWith("**/") && pattern.endsWith("/**")) {
+ const excludeDirName = pattern.slice(3, -3);
+ if (dirName === excludeDirName) {
+ return true;
+ }
+ }
+ }
+ return false;
+ })
+ .crawl(currentDir)
+ .withPromise();
+
+ let allFiles: string[];
+
+ if (bypassTimeout) {
+ // Manual refresh - wait for completion regardless of time
+ allFiles = await fileIndexPromise;
+ } else {
+ // Automatic indexing - race against 1-second timeout
+ const timeoutPromise = new Promise<"timeout">((resolve) => {
+ setTimeout(() => {
+ resolve("timeout");
+ }, 1000);
});
- return;
+
+ const result = await Promise.race([fileIndexPromise, timeoutPromise]);
+
+ if (result === "timeout") {
+ this.setState({
+ files: [],
+ isIndexing: false,
+ error: "directory-too-large",
+ });
+ return;
+ }
+
+ allFiles = result as string[];
}
- const allMatches = await this.throttledGlob(FILE_PATTERNS, {
- maxDepth: inGitRepo ? 15 : 3,
- ignore: FILE_IGNORE_PATTERNS,
- dot: true,
- absolute: false,
- });
-
- const uniqueFiles = [...new Set(allMatches)];
- this.fileSet.clear();
- uniqueFiles.forEach((file) => this.fileSet.add(file));
-
- const files = uniqueFiles.map((path) => ({
+ const fileItems = allFiles.map((path) => ({
path,
displayName: path,
}));
- this.setState({ files, isIndexing: false });
+ this.rebuildFzf(fileItems);
+ this.setState({ files: fileItems, isIndexing: false });
+
+ logger.debug(`Indexed ${fileItems.length} files`);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
@@ -104,116 +198,10 @@ export class FileIndexService extends BaseService {
}
}
- private setupFileWatcher(): void {
- if (this.fileWatcherInitialized) {
- return;
- }
-
- // Only enable file watching in git repositories
- // Outside git repos (like home directory), file watching causes performance issues
- // and provides little value since files change less predictably
- const inGitRepo = isGitRepo();
- if (!inGitRepo) {
- logger.debug("Skipping file watcher: not in a git repository");
- return;
- }
-
- this.fileWatcherInitialized = true;
- const watcher = getFileWatcher();
-
- // Start watching the current directory
- watcher.startWatching();
-
- // Set up callback for incremental updates
- this.fileWatcherUnsubscribe = watcher.onChange(() => {
- this.handleFileSystemChange();
- });
- }
-
- private async handleFileSystemChange(): Promise {
- try {
- // Get current files from file system
- const inGitRepo = isGitRepo();
- const allMatches = await this.throttledGlob(FILE_PATTERNS, {
- maxDepth: inGitRepo ? 15 : 3,
- ignore: FILE_IGNORE_PATTERNS,
- dot: true,
- absolute: false,
- });
-
- const currentFiles = new Set(allMatches);
- const previousFiles = this.fileSet;
-
- // Find added and removed files
- const addedFiles = [...currentFiles].filter(
- (file) => !previousFiles.has(file),
- );
- const removedFiles = [...previousFiles].filter(
- (file) => !currentFiles.has(file),
- );
-
- // Only update if there are actual changes
- if (addedFiles.length > 0 || removedFiles.length > 0) {
- // Update internal file set
- this.fileSet = currentFiles;
-
- // Create new files array
- const files = [...currentFiles].map((path) => ({
- path,
- displayName: path,
- }));
-
- this.setState({ files });
- }
- } catch (error) {
- logger.error("Error handling file system change:", error);
- const errorMessage =
- error instanceof Error ? error.message : String(error);
- this.setState({ error: errorMessage });
- }
- }
-
- private async throttledGlob(
- patterns: string[],
- options: GlobOptionsWithFileTypesFalse,
- batchSize = 100,
- delay = 20,
- ): Promise {
- return new Promise((resolve, reject) => {
- const allMatches: string[] = [];
- let processed = 0;
- let streamEnded = false;
-
- const globStream = glob.stream(patterns, options);
-
- globStream.on("data", (file: string) => {
- allMatches.push(file);
- processed++;
-
- if (processed % batchSize === 0) {
- if (streamEnded) {
- return;
- }
- globStream.pause();
-
- setTimeout(() => {
- if (streamEnded) {
- return;
- }
- globStream.resume();
- }, delay);
- }
- });
-
- globStream.on("end", () => {
- streamEnded = true;
- resolve(allMatches);
- });
-
- globStream.on("error", (err) => {
- streamEnded = true;
- reject(err);
- });
+ private rebuildFzf(files: FileItem[]): void {
+ this.fzf = new AsyncFzf(files, {
+ selector: (item: FileItem) => item.path,
+ casing: "case-insensitive",
});
}
@@ -230,11 +218,14 @@ export class FileIndexService extends BaseService {
return this.getState().error;
}
- public async refreshIndex(): Promise {
- await this.performFullIndex();
+ public async refreshIndex(bypassTimeout: boolean = false): Promise {
+ await this.performFullIndex(bypassTimeout);
}
- public filterFiles(filterText: string, limit: number = 10): FileItem[] {
+ public async filterFiles(
+ filterText: string,
+ limit: number = 10,
+ ): Promise {
const files = this.getFiles();
if (filterText.length === 0) {
@@ -248,36 +239,16 @@ export class FileIndexService extends BaseService {
.slice(0, limit);
}
- const lowerFilter = filterText.toLowerCase();
+ // Use fzf for fuzzy search
+ if (!this.fzf) {
+ this.rebuildFzf(files);
+ }
- return files
- .filter((file) => {
- return (
- file.displayName.toLowerCase().includes(lowerFilter) ||
- file.path.toLowerCase().includes(lowerFilter)
- );
- })
- .sort((a, b) => {
- const aFileName = a.path.split("/").pop() || a.path;
- const bFileName = b.path.split("/").pop() || b.path;
-
- // Prioritize exact matches in file name
- const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
- const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
-
- if (aNameMatch && !bNameMatch) return -1;
- if (!aNameMatch && bNameMatch) return 1;
-
- // Then prioritize files that start with the filter
- const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
- const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
-
- if (aStartsWith && !bStartsWith) return -1;
- if (!aStartsWith && bStartsWith) return 1;
-
- // Finally, sort by file name
- return aFileName.localeCompare(bFileName);
- })
- .slice(0, limit);
+ const results = await this.fzf!.find(filterText);
+ return results.slice(0, limit).map((entry: FzfResultItem) => ({
+ path: entry.item.path,
+ displayName: entry.item.displayName,
+ positions: entry.positions,
+ }));
}
}
diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts
index 32932e4df..9dff62d2f 100644
--- a/extensions/cli/src/services/ModelService.test.ts
+++ b/extensions/cli/src/services/ModelService.test.ts
@@ -1,9 +1,7 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
-import * as openaiAdapters from "@continuedev/openai-adapters";
import { describe, expect, beforeEach, vi, test } from "vitest";
// Mock dependencies before imports
-vi.mock("@continuedev/openai-adapters");
vi.mock("../config.js");
vi.mock("../auth/workos.js");
@@ -81,9 +79,7 @@ describe("ModelService", () => {
test("should initialize with persisted model if valid", async () => {
vi.mocked(workos.getModelName).mockReturnValue("Claude 3");
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
- mockLlmApi as any,
- );
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
const state = await service.initialize(mockAssistant, mockAuthConfig);
@@ -152,9 +148,7 @@ describe("ModelService", () => {
await service.initialize(mockAssistant, mockAuthConfig);
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
- newLlmApi as any,
- );
+ vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any);
const state = await service.switchModel(1);
@@ -204,24 +198,14 @@ describe("ModelService", () => {
]);
await service.initialize(mockAssistant, mockAuthConfig);
- vi.mocked(workos.getAccessToken).mockReturnValue("proxy-token");
- vi.mocked(workos.getOrganizationId).mockReturnValue("org-123");
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
- mockLlmApi as any,
- );
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
await service.switchModel(0);
- expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({
- provider: "continue-proxy",
- apiBase: "https://proxy.continue.dev",
- apiKey: "proxy-token",
- env: {
- apiKeyLocation: "env.PROXY_KEY",
- orgScopeId: "org-123",
- proxyUrl: undefined,
- },
- });
+ expect(vi.mocked(config.createLlmApi)).toHaveBeenCalledWith(
+ proxyModel,
+ mockAuthConfig,
+ );
});
});
@@ -292,9 +276,7 @@ describe("ModelService", () => {
expect(service.getCurrentModelIndex()).toBe(0);
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
- mockLlmApi as any,
- );
+ vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
await service.switchModel(1);
expect(service.getCurrentModelIndex()).toBe(1);
});
@@ -392,9 +374,7 @@ describe("ModelService", () => {
service.on("stateChanged", listener);
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
- newLlmApi as any,
- );
+ vi.mocked(config.createLlmApi).mockReturnValue(newLlmApi as any);
await service.switchModel(1);
expect(listener).toHaveBeenCalledWith(
@@ -419,7 +399,7 @@ describe("ModelService", () => {
const errorListener = vi.fn();
service.on("error", errorListener);
- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any);
+ vi.mocked(config.createLlmApi).mockReturnValue(null as any);
await expect(service.switchModel(1)).rejects.toThrow(
"Failed to initialize LLM",
diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts
index e4b9a88cb..313f2afc1 100644
--- a/extensions/cli/src/services/ModelService.ts
+++ b/extensions/cli/src/services/ModelService.ts
@@ -1,13 +1,7 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
-import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
-import {
- AuthConfig,
- getAccessToken,
- getModelName,
- getOrganizationId,
-} from "../auth/workos.js";
-import { getLlmApi } from "../config.js";
+import { AuthConfig, getModelName } from "../auth/workos.js";
+import { createLlmApi, getLlmApi } from "../config.js";
import { logger } from "../util/logger.js";
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
@@ -89,31 +83,7 @@ export class ModelService
name: (selectedModel as any).name || "unnamed",
});
- const accessToken = getAccessToken(authConfig);
- const organizationId = getOrganizationId(authConfig);
-
- const config: LLMConfig =
- selectedModel.provider === "continue-proxy"
- ? {
- provider: selectedModel.provider,
- requestOptions: selectedModel.requestOptions,
- apiBase: selectedModel.apiBase,
- apiKey: accessToken ?? undefined,
- env: {
- apiKeyLocation: (selectedModel as any).apiKeyLocation,
- orgScopeId: organizationId,
- proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined,
- },
- }
- : {
- provider: selectedModel.provider as any,
- apiKey: selectedModel.apiKey,
- apiBase: selectedModel.apiBase,
- requestOptions: selectedModel.requestOptions,
- env: selectedModel.env,
- };
-
- const llmApi = constructLlmApi(config);
+ const llmApi = createLlmApi(selectedModel, authConfig);
if (!llmApi) {
throw new Error("Failed to initialize LLM with persisted model");
@@ -288,31 +258,7 @@ export class ModelService
});
try {
- const accessToken = getAccessToken(authConfig);
- const organizationId = getOrganizationId(authConfig);
-
- const config: LLMConfig =
- selectedModel.provider === "continue-proxy"
- ? {
- provider: selectedModel.provider,
- requestOptions: selectedModel.requestOptions,
- apiBase: selectedModel.apiBase,
- apiKey: accessToken ?? undefined,
- env: {
- apiKeyLocation: (selectedModel as any).apiKeyLocation,
- orgScopeId: organizationId,
- proxyUrl: (selectedModel as any).onPremProxyUrl ?? undefined,
- },
- }
- : {
- provider: selectedModel.provider as any,
- apiKey: selectedModel.apiKey,
- apiBase: selectedModel.apiBase,
- requestOptions: selectedModel.requestOptions,
- env: selectedModel.env,
- };
-
- const llmApi = constructLlmApi(config);
+ const llmApi = createLlmApi(selectedModel, authConfig);
if (!llmApi) {
throw new Error("Failed to initialize LLM with selected model");
diff --git a/extensions/cli/src/services/ServiceContainer.test.ts b/extensions/cli/src/services/ServiceContainer.test.ts
index c693138be..f5e23a2d0 100644
--- a/extensions/cli/src/services/ServiceContainer.test.ts
+++ b/extensions/cli/src/services/ServiceContainer.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test, beforeEach, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { ServiceContainer } from "./ServiceContainer.js";
@@ -10,6 +10,11 @@ describe("ServiceContainer", () => {
vi.clearAllMocks();
});
+ afterEach(() => {
+ // Clean up listeners to prevent memory leaks
+ container?.removeAllListeners();
+ });
+
describe("Dependency Cascade Reloading", () => {
test("should automatically reload all transitive dependents", async () => {
// Setup service dependency chain: auth -> apiClient -> config -> model
diff --git a/extensions/cli/src/services/StorageSyncService.test.ts b/extensions/cli/src/services/StorageSyncService.test.ts
new file mode 100644
index 000000000..1e67a6c2e
--- /dev/null
+++ b/extensions/cli/src/services/StorageSyncService.test.ts
@@ -0,0 +1,279 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { getGitDiffSnapshot } from "../util/git.js";
+import { logger } from "../util/logger.js";
+
+import { StorageSyncService } from "./StorageSyncService.js";
+
+vi.mock("../util/logger.js", () => ({
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+vi.mock("../env.js", () => ({
+ env: { apiBase: "https://api.test/" },
+}));
+
+vi.mock("../util/git.js", () => ({
+ getGitDiffSnapshot: vi.fn(),
+}));
+
+describe("StorageSyncService", () => {
+ const fetchMock = vi.fn();
+ const gitDiffMock = vi.mocked(getGitDiffSnapshot);
+ let service: StorageSyncService;
+ let originalFetch: typeof fetch | undefined;
+ let hadFetch = false;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ fetchMock.mockReset();
+ hadFetch = "fetch" in globalThis;
+ originalFetch = globalThis.fetch;
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+ gitDiffMock.mockReset();
+
+ service = new StorageSyncService();
+ await service.initialize();
+ });
+
+ afterEach(() => {
+ service.stop();
+ if (hadFetch) {
+ globalThis.fetch = originalFetch!;
+ } else {
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
+ }
+ });
+
+ it("returns false when no storage option provided", async () => {
+ const result = await service.startFromOptions({
+ storageOption: undefined,
+ accessToken: "token",
+ syncSessionHistory: vi.fn(),
+ getCompleteStateSnapshot: vi.fn(),
+ });
+
+ expect(result).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("warns when storage identifier trims to empty", async () => {
+ const warnSpy = vi.spyOn(logger, "warn");
+
+ const result = await service.startFromOptions({
+ storageOption: " ",
+ accessToken: "token",
+ syncSessionHistory: vi.fn(),
+ getCompleteStateSnapshot: vi.fn(),
+ });
+
+ expect(result).toBe(false);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("storage identifier was empty"),
+ );
+ warnSpy.mockRestore();
+ });
+
+ it("warns when storage requested without access token", async () => {
+ const warnSpy = vi.spyOn(logger, "warn");
+
+ const result = await service.startFromOptions({
+ storageOption: "session-123",
+ accessToken: null,
+ syncSessionHistory: vi.fn(),
+ getCompleteStateSnapshot: vi.fn(),
+ });
+
+ expect(result).toBe(false);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("no Continue API key"),
+ );
+ warnSpy.mockRestore();
+ });
+
+ it("starts syncing when presign succeeds", async () => {
+ const syncSessionHistory = vi.fn();
+ const getCompleteStateSnapshot = vi.fn().mockReturnValue({ foo: "bar" });
+
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ session: { putUrl: "https://upload/session", key: "session.json" },
+ diff: { putUrl: "https://upload/diff", key: "diff.txt" },
+ }),
+ });
+ fetchMock.mockResolvedValue({ ok: true });
+ gitDiffMock.mockResolvedValue({ diff: "diff", repoFound: true });
+
+ const result = await service.startFromOptions({
+ storageOption: "session-123",
+ accessToken: "token",
+ syncSessionHistory,
+ getCompleteStateSnapshot,
+ isActive: () => true,
+ });
+
+ expect(result).toBe(true);
+ expect(syncSessionHistory).toHaveBeenCalledTimes(1);
+ expect(getCompleteStateSnapshot).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ const [presignUrl, presignOptions] = fetchMock.mock.calls[0];
+ expect(presignUrl).toBeInstanceOf(URL);
+ expect((presignUrl as URL).toString()).toBe(
+ "https://api.test/agents/storage/presigned-url",
+ );
+ expect(presignOptions).toMatchObject({ method: "POST" });
+
+ const [sessionUrl, sessionOptions] = fetchMock.mock.calls[1];
+ expect(sessionUrl).toBe("https://upload/session");
+ expect(sessionOptions).toMatchObject({
+ method: "PUT",
+ body: expect.any(String),
+ });
+
+ service.stop();
+ expect(service.getState().isEnabled).toBe(false);
+ });
+
+ it("returns false when presign request fails", async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: false,
+ status: 500,
+ statusText: "Server Error",
+ });
+
+ const warnSpy = vi.spyOn(logger, "warn");
+ const result = await service.startFromOptions({
+ storageOption: "session-123",
+ accessToken: "token",
+ syncSessionHistory: vi.fn(),
+ getCompleteStateSnapshot: vi.fn(),
+ });
+
+ expect(result).toBe(false);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("presign request failed"),
+ );
+ expect(service.getState().lastError).toBe(
+ "Failed to obtain presigned URLs",
+ );
+ warnSpy.mockRestore();
+ });
+
+ it("records upload error details when PUT fails", async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ session: { putUrl: "https://upload/session", key: "session.json" },
+ diff: { putUrl: "https://upload/diff", key: "diff.txt" },
+ }),
+ });
+ fetchMock.mockResolvedValueOnce({
+ ok: false,
+ status: 403,
+ statusText: "Forbidden",
+ text: async () => "Access denied",
+ });
+ gitDiffMock.mockResolvedValue({ diff: "", repoFound: true });
+
+ const warnSpy = vi.spyOn(logger, "warn");
+
+ const result = await service.startFromOptions({
+ storageOption: "session-123",
+ accessToken: "token",
+ syncSessionHistory: vi.fn(),
+ getCompleteStateSnapshot: vi.fn().mockReturnValue({}),
+ });
+
+ expect(result).toBe(true);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Storage sync upload failed"),
+ );
+ const state = service.getState();
+ expect(state.isEnabled).toBe(true);
+ expect(state.lastError).toContain("Storage upload failed");
+
+ service.stop();
+ warnSpy.mockRestore();
+ });
+
+ it("does nothing when markAgentStatusUnread has no storage context", async () => {
+ await service.markAgentStatusUnread();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("marks the agent session as unread", async () => {
+ (service as unknown as { options: any }).options = {
+ storageId: "session-123",
+ accessToken: "token",
+ };
+
+ fetchMock.mockResolvedValueOnce({ ok: true });
+
+ await service.markAgentStatusUnread();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBeInstanceOf(URL);
+ expect((url as URL).toString()).toBe(
+ "https://api.test/agents/session-123/read-status",
+ );
+ expect(init).toMatchObject({
+ method: "POST",
+ body: JSON.stringify({ unread: true }),
+ headers: {
+ Authorization: "Bearer token",
+ "Content-Type": "application/json",
+ },
+ });
+ });
+
+ it("includes server-side encryption header when required by signed headers", async () => {
+ const syncSessionHistory = vi.fn();
+ const getCompleteStateSnapshot = vi.fn().mockReturnValue({ test: "data" });
+
+ // Mock presign response with server-side encryption in signed headers
+ const sessionUrlWithSSE =
+ "https://upload/session?X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption";
+ const diffUrl = "https://upload/diff";
+
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ session: { putUrl: sessionUrlWithSSE, key: "session.json" },
+ diff: { putUrl: diffUrl, key: "diff.txt" },
+ }),
+ });
+ fetchMock.mockResolvedValue({ ok: true });
+ gitDiffMock.mockResolvedValue({ diff: "test diff", repoFound: true });
+
+ const result = await service.startFromOptions({
+ storageOption: "session-123",
+ accessToken: "token",
+ syncSessionHistory,
+ getCompleteStateSnapshot,
+ isActive: () => true,
+ });
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+
+ // Check session upload includes server-side encryption header
+ const sessionCall = fetchMock.mock.calls[1];
+ expect(sessionCall[0]).toBe(sessionUrlWithSSE);
+ expect(sessionCall[1]).toMatchObject({
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ "x-amz-server-side-encryption": "AES256",
+ },
+ });
+
+ service.stop();
+ });
+});
diff --git a/extensions/cli/src/services/StorageSyncService.ts b/extensions/cli/src/services/StorageSyncService.ts
new file mode 100644
index 000000000..52f0be59d
--- /dev/null
+++ b/extensions/cli/src/services/StorageSyncService.ts
@@ -0,0 +1,334 @@
+import chalk from "chalk";
+
+import { env } from "../env.js";
+import { formatError } from "../util/formatError.js";
+import { getGitDiffSnapshot } from "../util/git.js";
+import { logger } from "../util/logger.js";
+
+import type { StorageSyncServiceState } from "./types.js";
+
+const DEFAULT_UPLOAD_INTERVAL_MS = 30_000;
+
+type StoragePresignedLocation = {
+ key: string;
+ putUrl: string;
+};
+
+type StoragePresignResponse = {
+ session?: StoragePresignedLocation;
+ diff?: StoragePresignedLocation;
+};
+
+type StorageTargets = {
+ sessionUrl: string;
+ diffUrl: string;
+};
+
+export interface StorageSyncStartOptions {
+ storageId: string;
+ accessToken: string;
+ intervalMs?: number;
+ syncSessionHistory: () => void;
+ getCompleteStateSnapshot: () => unknown;
+ isActive?: () => boolean;
+}
+
+export class StorageSyncService {
+ private state: StorageSyncServiceState = {
+ isEnabled: false,
+ lastError: null,
+ };
+
+ private intervalHandle: NodeJS.Timeout | null = null;
+ private stopped = true;
+ private uploadInFlight = false;
+ private missingRepoLogged = false;
+ private targets: StorageTargets | null = null;
+ private options: StorageSyncStartOptions | null = null;
+
+ async initialize(): Promise {
+ this.stop();
+ return this.getState();
+ }
+
+ getState(): StorageSyncServiceState {
+ return { ...this.state };
+ }
+
+ getDefaultInterval(): number {
+ return DEFAULT_UPLOAD_INTERVAL_MS;
+ }
+
+ async startFromOptions(
+ options: {
+ storageOption?: string;
+ accessToken?: string | null;
+ } & Omit,
+ ): Promise {
+ const { storageOption, accessToken, ...rest } = options;
+
+ if (!storageOption) {
+ return false;
+ }
+
+ const storageId = storageOption.trim();
+ if (!storageId) {
+ logger.warn(
+ "Storage sync requested but the provided storage identifier was empty; skipping uploads.",
+ );
+ return false;
+ }
+
+ if (!accessToken) {
+ logger.warn(
+ "Storage sync requested but no Continue API key is available; skipping uploads.",
+ );
+ return false;
+ }
+
+ return this.start({
+ storageId,
+ accessToken,
+ ...rest,
+ });
+ }
+
+ async start(options: StorageSyncStartOptions): Promise {
+ // Ensure any existing sync loop is stopped before starting a new one
+ this.stop();
+
+ const targets = await this.requestStorageTargets(
+ options.storageId,
+ options.accessToken,
+ );
+
+ if (!targets) {
+ this.setState({
+ isEnabled: false,
+ storageId: options.storageId,
+ lastError: "Failed to obtain presigned URLs",
+ });
+ return false;
+ }
+
+ this.targets = targets;
+ this.options = options;
+ this.stopped = false;
+ this.uploadInFlight = false;
+ this.missingRepoLogged = false;
+ this.setState({
+ isEnabled: true,
+ storageId: options.storageId,
+ lastError: null,
+ lastUploadAt: undefined,
+ });
+
+ const intervalMs = options.intervalMs ?? DEFAULT_UPLOAD_INTERVAL_MS;
+ logger.info(
+ chalk.dim(
+ `Storage sync enabled (uploading every ${Math.round(intervalMs / 1000)}s)`,
+ ),
+ );
+
+ await this.performUpload();
+
+ this.intervalHandle = setInterval(() => {
+ void this.performUpload();
+ }, intervalMs);
+
+ return true;
+ }
+
+ async markAgentStatusUnread(): Promise {
+ const storageId = this.options?.storageId;
+ const accessToken = this.options?.accessToken;
+
+ if (!storageId || !accessToken) {
+ return;
+ }
+
+ const url = new URL(
+ `agents/${encodeURIComponent(storageId)}/read-status`,
+ env.apiBase,
+ );
+
+ try {
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ body: JSON.stringify({ unread: true }),
+ });
+
+ if (!response.ok) {
+ const statusText = `${response.status} ${response.statusText}`.trim();
+ logger.debug(
+ `Failed to mark agent session unread (${statusText || "unknown error"}).`,
+ );
+ }
+ } catch (error) {
+ logger.debug(
+ `Failed to mark agent session unread: ${formatError(error)}`,
+ );
+ }
+ }
+
+ stop(): void {
+ this.stopped = true;
+ this.targets = null;
+ this.options = null;
+ this.uploadInFlight = false;
+
+ if (this.intervalHandle) {
+ clearInterval(this.intervalHandle);
+ this.intervalHandle = null;
+ }
+
+ if (this.state.isEnabled) {
+ this.setState({
+ isEnabled: false,
+ storageId: this.state.storageId,
+ lastError: null,
+ lastUploadAt: this.state.lastUploadAt,
+ });
+ }
+ }
+
+ private setState(next: StorageSyncServiceState): void {
+ this.state = { ...next };
+ }
+
+ private async requestStorageTargets(
+ storageId: string,
+ accessToken: string,
+ ): Promise {
+ const url = new URL("agents/storage/presigned-url", env.apiBase);
+
+ try {
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ body: JSON.stringify({ storageId }),
+ });
+
+ if (!response.ok) {
+ const statusText = `${response.status} ${response.statusText}`.trim();
+ logger.warn(
+ `Storage sync presign request failed (${statusText}). Storage uploads disabled for this session.`,
+ );
+ return null;
+ }
+
+ const body = (await response.json()) as StoragePresignResponse;
+
+ if (!body.session?.putUrl || !body.diff?.putUrl) {
+ logger.warn(
+ "Storage sync presign response missing required URLs. Storage uploads disabled for this session.",
+ );
+ return null;
+ }
+
+ return {
+ sessionUrl: body.session.putUrl,
+ diffUrl: body.diff.putUrl,
+ };
+ } catch (error) {
+ logger.warn(
+ `Storage sync presign request failed: ${formatError(error)}. Storage uploads disabled for this session.`,
+ );
+ return null;
+ }
+ }
+
+ private async uploadToPresignedUrl(
+ url: string,
+ body: string,
+ contentType: string,
+ ): Promise {
+ // Parse the URL to extract any required headers from the query parameters
+ const parsedUrl = new URL(url);
+ const headers: Record = {
+ "Content-Type": contentType,
+ };
+
+ // Check if the presigned URL includes server-side encryption in signed headers
+ const signedHeaders = parsedUrl.searchParams.get("X-Amz-SignedHeaders");
+ if (signedHeaders?.includes("x-amz-server-side-encryption")) {
+ headers["x-amz-server-side-encryption"] = "AES256";
+ }
+
+ const response = await fetch(url, {
+ method: "PUT",
+ headers,
+ body,
+ });
+
+ if (!response.ok) {
+ const statusText = `${response.status} ${response.statusText}`.trim();
+ const responseBody = await response.text();
+ throw new Error(`Storage upload failed (${statusText}): ${responseBody}`);
+ }
+ }
+
+ private async performUpload(): Promise {
+ if (this.stopped || this.uploadInFlight || !this.targets || !this.options) {
+ return;
+ }
+
+ if (this.options.isActive && !this.options.isActive()) {
+ return;
+ }
+
+ // Capture references to prevent race condition with stop()
+ const targets = this.targets;
+ const options = this.options;
+
+ this.uploadInFlight = true;
+
+ try {
+ options.syncSessionHistory();
+ const snapshot = options.getCompleteStateSnapshot();
+ const sessionPayload = JSON.stringify(snapshot, null, 2);
+ await this.uploadToPresignedUrl(
+ targets.sessionUrl,
+ sessionPayload,
+ "application/json",
+ );
+
+ const diffResult = await getGitDiffSnapshot();
+ if (!diffResult.repoFound && !this.missingRepoLogged) {
+ logger.debug(
+ "Storage sync diff upload skipped: not in a git repository or main branch missing.",
+ );
+ this.missingRepoLogged = true;
+ }
+ await this.uploadToPresignedUrl(
+ targets.diffUrl,
+ diffResult.diff,
+ "text/plain",
+ );
+
+ this.setState({
+ isEnabled: true,
+ storageId: this.state.storageId,
+ lastUploadAt: Date.now(),
+ lastError: null,
+ });
+ } catch (error) {
+ this.setState({
+ isEnabled: true,
+ storageId: this.state.storageId,
+ lastUploadAt: this.state.lastUploadAt,
+ lastError: formatError(error),
+ });
+ logger.warn(`Storage sync upload failed: ${formatError(error)}`);
+ } finally {
+ this.uploadInFlight = false;
+ }
+ }
+}
diff --git a/extensions/cli/src/services/UpdateService.ts b/extensions/cli/src/services/UpdateService.ts
new file mode 100644
index 000000000..6d1c893bc
--- /dev/null
+++ b/extensions/cli/src/services/UpdateService.ts
@@ -0,0 +1,241 @@
+import { exec, spawn } from "child_process";
+import { promisify } from "util";
+
+import { GlobalContext } from "core/util/GlobalContext.js";
+
+import { logger } from "src/util/logger.js";
+
+import { compareVersions, getLatestVersion, getVersion } from "../version.js";
+
+import { BaseService } from "./BaseService.js";
+import { serviceContainer } from "./ServiceContainer.js";
+import { UpdateServiceState, UpdateStatus } from "./types.js";
+const execAsync = promisify(exec);
+
+/**
+ * Service for checking and performing CLI updates
+ */
+export class UpdateService extends BaseService {
+ constructor() {
+ super("update", {
+ autoUpdate: true,
+ isAutoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: null,
+ currentVersion: getVersion(),
+ });
+ }
+
+ /**
+ * Initialize the update service
+ */
+ async doInitialize(headless?: boolean) {
+ // Don't automatically check in tests/headless
+ if (!headless && process.env.NODE_ENV !== "test") {
+ void this.checkAndAutoUpdate();
+ }
+
+ return this.currentState;
+ }
+
+ private async checkAndAutoUpdate() {
+ // First get auto update setting from global context
+ const globalContext = new GlobalContext();
+ const autoUpdate = globalContext.get("autoUpdateCli") ?? true;
+ this.setState({
+ autoUpdate,
+ });
+
+ try {
+ // Check for updates
+ this.setState({
+ status: UpdateStatus.CHECKING,
+ message: "Checking for updates",
+ });
+
+ const latestVersion = await getLatestVersion();
+ this.setState({
+ latestVersion,
+ });
+
+ if (!latestVersion) {
+ this.setState({
+ status: UpdateStatus.IDLE,
+ message: "Continue CLI",
+ isUpdateAvailable: false,
+ });
+ return;
+ }
+
+ const comparison = compareVersions(
+ this.currentState.currentVersion,
+ latestVersion,
+ );
+ const isUpdateAvailable = comparison === "older";
+ this.setState({
+ isUpdateAvailable,
+ });
+
+ if (this.currentState.currentVersion === "0.0.0-dev") {
+ this.setState({
+ status: UpdateStatus.IDLE,
+ message: `Continue CLI`,
+ isUpdateAvailable,
+ latestVersion,
+ });
+ return; // Uncomment to test auto-update behavior in dev
+ }
+
+ // If update is available, automatically update
+ if (
+ autoUpdate &&
+ isUpdateAvailable &&
+ this.currentState.status !== "updating" &&
+ !process.env.CONTINUE_CLI_AUTO_UPDATED //Already auto updated, preventing sequential auto-update
+ ) {
+ await this.performUpdate(true);
+ } else {
+ this.setState({
+ status: UpdateStatus.IDLE,
+ message: isUpdateAvailable
+ ? `Update available: v${latestVersion}`
+ : `Continue CLI v${this.currentState.currentVersion}`,
+ isUpdateAvailable,
+ latestVersion,
+ });
+ }
+ } catch (error: any) {
+ logger.error("Error checking for updates:", error);
+ this.setState({
+ status: UpdateStatus.ERROR,
+ message: `Continue CLI v${this.currentState.currentVersion}`,
+ error,
+ });
+ }
+ }
+
+ public async setAutoUpdate(value: boolean) {
+ const globalContext = new GlobalContext();
+ globalContext.update("autoUpdateCli", value);
+ this.setState({
+ autoUpdate: value,
+ });
+ }
+
+ // TODO this is a hack because our service state update code is broken
+ // Currently all things that need update use serviceContainer.set manually
+ // Rather than actually using the stateChanged event
+ setState(newState: Partial): void {
+ super.setState(newState);
+ serviceContainer.set("update", this.currentState);
+ }
+
+ async performUpdate(isAutoUpdate?: boolean) {
+ if (this.currentState.status === "updating") {
+ return;
+ }
+
+ try {
+ this.setState({
+ isAutoUpdate,
+ status: UpdateStatus.UPDATING,
+ message: `${isAutoUpdate ? "Auto-updating" : "Updating"} to v${this.currentState.latestVersion}`,
+ });
+
+ // Install the update
+ const { stdout, stderr } = await execAsync("npm i -g @continuedev/cli");
+ logger.debug("Update output:", { stdout, stderr });
+
+ if (stderr) {
+ const errLines = stderr.split("\n");
+ for (const line of errLines) {
+ const lower = line.toLowerCase().trim();
+ if (
+ !line ||
+ lower.includes("debugger") ||
+ lower.includes("npm warn")
+ ) {
+ continue;
+ }
+ this.setState({
+ status: UpdateStatus.ERROR,
+ message: `Error updating to v${this.currentState.latestVersion}`,
+ error: new Error(stderr),
+ });
+ return;
+ }
+ }
+
+ this.setState({
+ status: UpdateStatus.UPDATED,
+ message: `${isAutoUpdate ? "Auto-updated to" : "Restart for"} v${this.currentState.latestVersion}`,
+ isUpdateAvailable: false,
+ });
+ if (isAutoUpdate) {
+ this.restartCLI();
+ }
+ } catch (error: any) {
+ logger.error("Error updating CLI:", error);
+ this.setState({
+ status: UpdateStatus.ERROR,
+ message: isAutoUpdate ? "Auto-update failed" : "Update failed",
+ error,
+ });
+ setTimeout(() => {
+ this.setState({
+ status: UpdateStatus.IDLE,
+ message: `/update to v${this.currentState.latestVersion}`,
+ });
+ }, 4000);
+ }
+ }
+
+ private restartCLI(): void {
+ try {
+ const entryPoint = process.argv[1];
+ const cliArgs = process.argv.slice(2);
+ const nodeExecutable = process.execPath;
+
+ logger.debug(
+ `Preparing for CLI restart with: ${nodeExecutable} ${entryPoint} ${cliArgs.join(
+ " ",
+ )}`,
+ );
+
+ // Halt/clean up parent cn process
+ try {
+ // Remove all input listeners
+ global.clearTimeout = () => {};
+ global.clearInterval = () => {};
+ process.stdin.removeAllListeners();
+ process.stdin.pause();
+ // console.clear(); // Don't want to clear things that were in console before cn started
+ } catch (e) {
+ logger.debug("Error cleaning up terminal:", e);
+ }
+
+ // Spawn a new detached cn process
+ const child = spawn(nodeExecutable, [entryPoint, ...cliArgs], {
+ detached: true,
+ stdio: "inherit",
+ env: {
+ ...process.env,
+ CONTINUE_CLI_AUTO_UPDATED: "true",
+ },
+ });
+
+ // I did not find a way on existing to avoid a bug where next process has input glitches without leaving parent in place
+ // So instead of existing, parent will exit when child exits
+ // process.exit(0);
+ child.on("exit", (code) => {
+ process.exit(code);
+ });
+ child.unref();
+ } catch (error) {
+ logger.error("Failed to restart CLI:", error);
+ }
+ }
+}
diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts
index ae53965ab..d46960ddd 100644
--- a/extensions/cli/src/services/index.ts
+++ b/extensions/cli/src/services/index.ts
@@ -12,6 +12,7 @@ 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 {
ApiClientServiceState,
@@ -21,6 +22,7 @@ import {
ServiceInitOptions,
ServiceInitResult,
} from "./types.js";
+import { UpdateService } from "./UpdateService.js";
// Service instances
const authService = new AuthService();
@@ -31,6 +33,8 @@ const mcpService = new MCPService();
const fileIndexService = new FileIndexService();
const resourceMonitoringService = new ResourceMonitoringService();
const chatHistoryService = new ChatHistoryService();
+const updateService = new UpdateService();
+const storageSyncService = new StorageSyncService();
/**
* Initialize all services and register them with the service container
@@ -132,6 +136,12 @@ export async function initializeServices(
[], // No dependencies
);
+ serviceContainer.register(
+ SERVICE_NAMES.UPDATE,
+ () => updateService.initialize(),
+ [], // No dependencies
+ );
+
serviceContainer.register(
SERVICE_NAMES.API_CLIENT,
async () => {
@@ -243,6 +253,12 @@ export async function initializeServices(
[],
);
+ serviceContainer.register(
+ SERVICE_NAMES.STORAGE_SYNC,
+ () => storageSyncService.initialize(),
+ [],
+ );
+
serviceContainer.register(
SERVICE_NAMES.CHAT_HISTORY,
() => chatHistoryService.initialize(undefined, initOptions.headless),
@@ -283,17 +299,9 @@ export function reloadService(serviceName: string) {
* Check if all core services are ready
*/
export function areServicesReady(): boolean {
- return [
- SERVICE_NAMES.TOOL_PERMISSIONS,
- SERVICE_NAMES.AUTH,
- SERVICE_NAMES.API_CLIENT,
- SERVICE_NAMES.CONFIG,
- SERVICE_NAMES.MODEL,
- SERVICE_NAMES.MCP,
- SERVICE_NAMES.FILE_INDEX,
- SERVICE_NAMES.RESOURCE_MONITORING,
- SERVICE_NAMES.CHAT_HISTORY,
- ].every((name) => serviceContainer.isReady(name));
+ return Object.values(SERVICE_NAMES).every((name) =>
+ serviceContainer.isReady(name),
+ );
}
/**
@@ -317,6 +325,8 @@ export const services = {
resourceMonitoring: resourceMonitoringService,
systemMessage: systemMessageService,
chatHistory: chatHistoryService,
+ updateService: updateService,
+ storageSync: storageSyncService,
} 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 18fb2cbae..ae5262cae 100644
--- a/extensions/cli/src/services/types.ts
+++ b/extensions/cli/src/services/types.ts
@@ -81,6 +81,25 @@ export interface MCPServiceState {
prompts: MCPPrompt[];
}
+export enum UpdateStatus {
+ IDLE = "idle",
+ CHECKING = "checking",
+ UPDATING = "updating",
+ UPDATED = "updated",
+ ERROR = "error",
+}
+
+export interface UpdateServiceState {
+ autoUpdate: boolean;
+ isAutoUpdate: boolean;
+ status: UpdateStatus;
+ message: string;
+ error?: Error | null;
+ isUpdateAvailable: boolean;
+ latestVersion: string | null;
+ currentVersion: string;
+}
+
export interface ApiClientServiceState {
apiClient: DefaultApiInterface | null;
}
@@ -92,8 +111,15 @@ export interface ToolPermissionServiceState {
originalPolicies?: ToolPermissions;
}
-export type { FileIndexServiceState } from "./FileIndexService.js";
+export interface StorageSyncServiceState {
+ isEnabled: boolean;
+ storageId?: string;
+ lastUploadAt?: number;
+ lastError?: string | null;
+}
+
export type { ChatHistoryState } from "./ChatHistoryService.js";
+export type { FileIndexServiceState } from "./FileIndexService.js";
/**
* Service names as constants to prevent typos
@@ -109,6 +135,8 @@ export const SERVICE_NAMES = {
RESOURCE_MONITORING: "resourceMonitoring",
SYSTEM_MESSAGE: "systemMessage",
CHAT_HISTORY: "chatHistory",
+ UPDATE: "update",
+ STORAGE_SYNC: "storageSync",
} as const;
/**
diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts
index b6752d617..c22ce9762 100644
--- a/extensions/cli/src/session.ts
+++ b/extensions/cli/src/session.ts
@@ -2,15 +2,32 @@ import fs from "fs";
import os from "os";
import path from "path";
-import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js";
+import type {
+ BaseSessionMetadata,
+ ChatHistoryItem,
+ Session,
+} from "core/index.js";
import historyManager from "core/util/history.js";
import { v4 as uuidv4 } from "uuid";
+import {
+ getAccessToken,
+ isAuthenticatedConfig,
+ loadAuthConfig,
+} from "./auth/workos.js";
import { DEFAULT_SESSION_TITLE } from "./constants/session.js";
+import { env } from "./env.js";
import { logger } from "./util/logger.js";
-// Re-export SessionMetadata for external consumers
-export type { SessionMetadata };
+// Re-export BaseSessionMetadata for external consumers
+export type { BaseSessionMetadata };
+
+// Extended type for sessions that can be local or remote
+export interface ExtendedSessionMetadata extends BaseSessionMetadata {
+ firstUserMessage?: string;
+ isRemote?: boolean;
+ remoteId?: string; // For remote sessions, this is the agent ID
+}
// Note: We now use UUID-based session IDs instead of terminal-based IDs.
// Each new chat session gets a unique UUID.
@@ -140,13 +157,41 @@ function modifySessionBeforeSave(session: Session): Session {
};
}
+export function getSessionPersistenceSnapshot(session: Session): Session {
+ return modifySessionBeforeSave(session);
+}
+
+/**
+ * Get the complete state snapshot that matches the /state endpoint format
+ */
+export interface StateSnapshot {
+ session: Session;
+ isProcessing: boolean;
+ messageQueueLength: number;
+ pendingPermission: any;
+}
+
+export function getCompleteStateSnapshot(
+ session: Session,
+ isProcessing: boolean = false,
+ messageQueueLength: number = 0,
+ pendingPermission: any = null,
+): StateSnapshot {
+ return {
+ session: getSessionPersistenceSnapshot(session),
+ isProcessing,
+ messageQueueLength,
+ pendingPermission,
+ };
+}
+
/**
* Save the current session to file
*/
export function saveSession(): void {
try {
const session = SessionManager.getInstance().getCurrentSession();
- const sessionToSave = modifySessionBeforeSave(session);
+ const sessionToSave = getSessionPersistenceSnapshot(session);
historyManager.save(sessionToSave);
} catch (error) {
logger.error("Error saving session:", error);
@@ -244,7 +289,7 @@ export function hasSession(): boolean {
*/
function getSessionMetadataWithPreview(
filePath: string,
-): (SessionMetadata & { firstUserMessage?: string }) | null {
+): ExtendedSessionMetadata | null {
try {
const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8"));
const stats = fs.statSync(filePath);
@@ -285,20 +330,65 @@ function getSessionMetadataWithPreview(
}
/**
- * List all available sessions with metadata
+ * Fetch remote agents/sessions from the API
*/
-export function listSessions(
- limit: number = 10,
-): (SessionMetadata & { firstUserMessage?: string })[] {
+export async function getRemoteSessions(): Promise {
try {
- const sessions = historyManager.list({ limit });
+ const authConfig = loadAuthConfig();
+ const accessToken = getAccessToken(authConfig);
- // Add first user message preview to each session
- const sessionsWithPreview: (SessionMetadata & {
- firstUserMessage?: string;
- })[] = [];
+ if (
+ !accessToken ||
+ !isAuthenticatedConfig(authConfig) ||
+ !authConfig.userEmail.endsWith("@continue.dev")
+ ) {
+ return [];
+ }
- for (const sessionMeta of sessions) {
+ const response = await fetch(new URL("agents", env.apiBase), {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${accessToken}`,
+ },
+ });
+
+ if (!response.ok) {
+ logger.error(`Failed to fetch remote agents: ${response.status}`);
+ return [];
+ }
+
+ const agents = await response.json();
+
+ return agents.map((agent: any) => ({
+ sessionId: `remote-${agent.id}`,
+ title: agent.name || "Remote Agent",
+ dateCreated: new Date(agent.create_time_ms).toISOString(),
+ workspaceDirectory: "",
+ isRemote: true,
+ remoteId: agent.id,
+ firstUserMessage: "Remote agent session",
+ }));
+ } catch (error) {
+ logger.error("Error fetching remote sessions:", error);
+ return [];
+ }
+}
+
+/**
+ * List all available sessions with metadata (both local and remote)
+ */
+export async function listSessions(
+ limit: number = 100,
+): Promise {
+ try {
+ // Get local sessions
+ const localSessions = historyManager.list({ limit });
+
+ // Add first user message preview to each local session
+ const localSessionsWithPreview: ExtendedSessionMetadata[] = [];
+
+ for (const sessionMeta of localSessions) {
const sessionFilePath = path.join(
getSessionDir(),
`${sessionMeta.sessionId}.json`,
@@ -307,15 +397,32 @@ export function listSessions(
if (fs.existsSync(sessionFilePath)) {
const metadata = getSessionMetadataWithPreview(sessionFilePath);
if (metadata) {
- sessionsWithPreview.push(metadata);
+ localSessionsWithPreview.push({
+ ...metadata,
+ isRemote: false,
+ });
}
} else {
// Fall back to basic metadata if file doesn't exist
- sessionsWithPreview.push(sessionMeta);
+ localSessionsWithPreview.push({
+ ...sessionMeta,
+ isRemote: false,
+ });
}
}
- return sessionsWithPreview;
+ // Get remote sessions
+ const remoteSessions = await getRemoteSessions();
+
+ // Combine and sort by date (most recent first)
+ const allSessions = [...localSessionsWithPreview, ...remoteSessions]
+ .sort(
+ (a, b) =>
+ new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
+ )
+ .slice(0, limit);
+
+ return allSessions;
} catch (error) {
logger.error("Error listing sessions:", error);
return [];
diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts
index 9f220aa36..31572949d 100644
--- a/extensions/cli/src/shared-options.ts
+++ b/extensions/cli/src/shared-options.ts
@@ -13,7 +13,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("-v, --verbose", "Enable verbose logging")
+ .option("--verbose", "Enable verbose logging")
.option(
"--rule ",
"Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.",
diff --git a/extensions/cli/src/slashCommands.remote.test.ts b/extensions/cli/src/slashCommands.remote.test.ts
new file mode 100644
index 000000000..48eebe13e
--- /dev/null
+++ b/extensions/cli/src/slashCommands.remote.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+
+import { handleSlashCommands } from "./slashCommands.js";
+
+describe("Remote mode slash commands", () => {
+ const mockAssistant = {
+ name: "test",
+ version: "1.0.0",
+ prompts: [],
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("/diff and /apply commands", () => {
+ it("should not be handled by handleSlashCommands - these are handled by TUI layer", async () => {
+ // /diff and /apply are handled by handleSpecialCommands in useChat.helpers.ts,
+ // not by the general slash command system. These commands are intercepted
+ // at the TUI layer before reaching handleSlashCommands, so handleSlashCommands
+ // should return null (no match) for these commands.
+
+ const diffResult = await handleSlashCommands("/diff", mockAssistant);
+ expect(diffResult).toBe(null);
+
+ const applyResult = await handleSlashCommands("/apply", mockAssistant);
+ expect(applyResult).toBe(null);
+ });
+
+ it("should return unknown command for remote commands when called directly", async () => {
+ // When called directly (bypassing handleSpecialCommands), /diff and /apply
+ // should return "Unknown command" because they're listed in REMOTE_MODE_SLASH_COMMANDS
+ // for UI display but not implemented as handlers.
+
+ const diffResult = await handleSlashCommands("/diff", mockAssistant, {
+ remoteUrl: "http://localhost:3000",
+ isRemoteMode: true,
+ });
+ expect(diffResult).toEqual({
+ output: "Unknown command: diff",
+ });
+
+ const applyResult = await handleSlashCommands("/apply", mockAssistant, {
+ remoteUrl: "http://localhost:3000",
+ isRemoteMode: true,
+ });
+ expect(applyResult).toEqual({
+ output: "Unknown command: apply",
+ });
+ });
+ });
+});
diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts
index d2fa5c9af..f6db2be36 100644
--- a/extensions/cli/src/slashCommands.test.ts
+++ b/extensions/cli/src/slashCommands.test.ts
@@ -86,6 +86,7 @@ vi.mock("./session.js", () => ({
getCurrentSession: vi.fn(() => {
throw new Error("Session not available");
}),
+ updateSessionTitle: vi.fn(),
}));
describe("slashCommands", () => {
@@ -279,5 +280,60 @@ describe("slashCommands", () => {
expect(result?.output).toContain("/test-home/.continue/cli-sessions/");
expect(result?.output).toContain(".json");
});
+
+ it("should handle /title command with valid title", async () => {
+ const { updateSessionTitle } = await import("./session.js");
+
+ const result = await handleSlashCommands(
+ "/title My New Session Title",
+ mockAssistant,
+ );
+
+ expect(updateSessionTitle).toHaveBeenCalledWith("My New Session Title");
+ expect(result).toBeDefined();
+ expect(result?.output).toContain(
+ 'Session title updated to: "My New Session Title"',
+ );
+ expect(result?.exit).toBe(false);
+ });
+
+ it("should handle /title command with empty title", async () => {
+ const result = await handleSlashCommands("/title", mockAssistant);
+
+ expect(result).toBeDefined();
+ expect(result?.output).toContain(
+ "Please provide a title. Usage: /title ",
+ );
+ expect(result?.exit).toBe(false);
+ });
+
+ it("should handle /title command with whitespace-only title", async () => {
+ const result = await handleSlashCommands("/title ", mockAssistant);
+
+ expect(result).toBeDefined();
+ expect(result?.output).toContain(
+ "Please provide a title. Usage: /title ",
+ );
+ expect(result?.exit).toBe(false);
+ });
+
+ it("should handle /title command when session update fails", async () => {
+ const { updateSessionTitle } = await import("./session.js");
+
+ (updateSessionTitle as any).mockImplementation(() => {
+ throw new Error("Failed to save session");
+ });
+
+ const result = await handleSlashCommands(
+ "/title Test Title",
+ mockAssistant,
+ );
+
+ expect(result).toBeDefined();
+ expect(result?.output).toContain(
+ "Failed to update title: Failed to save session",
+ );
+ expect(result?.exit).toBe(false);
+ });
});
});
diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts
index 5c7d69fa1..69b3f7437 100644
--- a/extensions/cli/src/slashCommands.ts
+++ b/extensions/cli/src/slashCommands.ts
@@ -7,9 +7,10 @@ import {
loadAuthConfig,
} from "./auth/workos.js";
import { getAllSlashCommands } from "./commands/commands.js";
+import { handleInit } from "./commands/init.js";
import { handleInfoSlashCommand } from "./infoScreen.js";
import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
-import { getCurrentSession } from "./session.js";
+import { getCurrentSession, updateSessionTitle } from "./session.js";
import { posthogService } from "./telemetry/posthogService.js";
import { telemetryService } from "./telemetry/telemetryService.js";
import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
@@ -17,6 +18,8 @@ import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
type CommandHandler = (
args: string[],
assistant: AssistantConfig,
+ remoteUrl?: string,
+ options?: { isRemoteMode?: boolean },
) => Promise | SlashCommandResult;
async function handleHelp(_args: string[], _assistant: AssistantConfig) {
@@ -47,12 +50,10 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
` Type ${chalk.cyan("/")} to see available slash commands`,
` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
].join("\n");
- posthogService.capture("useSlashCommand", { name: "help" });
return { output: helpMessage };
}
async function handleLogin() {
- posthogService.capture("useSlashCommand", { name: "login" });
try {
const newAuthState = await services.auth.login();
await reloadService(SERVICE_NAMES.AUTH);
@@ -78,7 +79,6 @@ async function handleLogin() {
}
async function handleLogout() {
- posthogService.capture("useSlashCommand", { name: "logout" });
try {
await services.auth.logout();
return {
@@ -94,7 +94,6 @@ async function handleLogout() {
}
function handleWhoami() {
- posthogService.capture("useSlashCommand", { name: "whoami" });
if (isAuthenticated()) {
const config = loadAuthConfig();
if (config && isAuthenticatedConfig(config)) {
@@ -117,8 +116,6 @@ function handleWhoami() {
}
async function handleFork() {
- posthogService.capture("useSlashCommand", { name: "fork" });
-
try {
const currentSession = getCurrentSession();
const forkCommand = `cn --fork ${currentSession.sessionId}`;
@@ -144,18 +141,42 @@ async function handleFork() {
}
}
+function handleTitle(args: string[]) {
+ posthogService.capture("useSlashCommand", { name: "title" });
+
+ const title = args.join(" ").trim();
+ if (!title) {
+ return {
+ exit: false,
+ output: chalk.yellow(
+ "Please provide a title. Usage: /title ",
+ ),
+ };
+ }
+
+ try {
+ updateSessionTitle(title);
+ return {
+ exit: false,
+ output: chalk.green(`Session title updated to: "${title}"`),
+ };
+ } catch (error: any) {
+ return {
+ exit: false,
+ output: chalk.red(`Failed to update title: ${error.message}`),
+ };
+ }
+}
+
const commandHandlers: Record = {
help: handleHelp,
clear: () => {
- posthogService.capture("useSlashCommand", { name: "clear" });
return { clear: true, output: "Chat history cleared" };
},
exit: () => {
- posthogService.capture("useSlashCommand", { name: "exit" });
return { exit: true, output: "Goodbye!" };
},
config: () => {
- posthogService.capture("useSlashCommand", { name: "config" });
return { openConfigSelector: true };
},
login: handleLogin,
@@ -164,34 +185,30 @@ const commandHandlers: Record = {
info: handleInfoSlashCommand,
model: () => ({ openModelSelector: true }),
compact: () => {
- posthogService.capture("useSlashCommand", { name: "compact" });
return { compact: true };
},
mcp: () => {
- posthogService.capture("useSlashCommand", { name: "mcp" });
return { openMcpSelector: true };
},
resume: () => {
- posthogService.capture("useSlashCommand", { name: "resume" });
return { openSessionSelector: true };
},
fork: handleFork,
+ title: handleTitle,
+ init: (args, assistant) => {
+ posthogService.capture("useSlashCommand", { name: "init" });
+ return handleInit(args, assistant);
+ },
+ update: () => {
+ return { openUpdateSelector: true };
+ },
};
export async function handleSlashCommands(
input: string,
assistant: AssistantConfig,
-): Promise<{
- output?: string;
- exit?: boolean;
- newInput?: string;
- clear?: boolean;
- openConfigSelector?: boolean;
- openModelSelector?: boolean;
- openMCPSelector?: boolean;
- openSessionSelector?: boolean;
- compact?: boolean;
-} | null> {
+ options?: { remoteUrl?: string; isRemoteMode?: boolean },
+): Promise {
// Only trigger slash commands if slash is the very first character
if (!input.startsWith("/") || !input.trim().startsWith("/")) {
return null;
@@ -204,7 +221,7 @@ export async function handleSlashCommands(
const handler = commandHandlers[command];
if (handler) {
- return await handler(args, assistant);
+ return await handler(args, assistant, options?.remoteUrl, options);
}
// Check for custom assistant prompts
@@ -217,7 +234,9 @@ export async function handleSlashCommands(
}
// Check if this command would match any available commands (same logic as UI)
- const allCommands = getAllSlashCommands(assistant);
+ const allCommands = getAllSlashCommands(assistant, {
+ isRemoteMode: options?.isRemoteMode,
+ });
const hasMatches = allCommands.some((cmd) =>
cmd.name.toLowerCase().includes(command.toLowerCase()),
);
diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts
index d5b7b09a7..8cf3352d7 100644
--- a/extensions/cli/src/stream/handleToolCalls.ts
+++ b/extensions/cli/src/stream/handleToolCalls.ts
@@ -233,19 +233,8 @@ export async function getAllTools() {
description: tool.description,
parameters: {
type: "object",
- properties: Object.fromEntries(
- Object.entries(tool.parameters).map(([key, param]) => [
- key,
- {
- type: param.type,
- description: param.description,
- items: param.items,
- },
- ]),
- ),
- required: Object.entries(tool.parameters)
- .filter(([_, param]) => param.required)
- .map(([key, _]) => key),
+ required: tool.parameters.required,
+ properties: tool.parameters.properties,
},
},
}));
diff --git a/extensions/cli/src/stream/messageQueue.test.ts b/extensions/cli/src/stream/messageQueue.test.ts
new file mode 100644
index 000000000..cf34fff70
--- /dev/null
+++ b/extensions/cli/src/stream/messageQueue.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../util/logger.js", () => ({
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ setLevel: vi.fn(),
+ configureHeadlessMode: vi.fn(),
+ getLogPath: vi.fn(),
+ getSessionId: vi.fn(),
+ },
+}));
+
+import { messageQueue } from "./messageQueue.js";
+
+describe("messageQueue", () => {
+ it("enqueues and emits messageQueued", async () => {
+ const event = new Promise((resolve) =>
+ messageQueue.once("messageQueued", resolve),
+ );
+
+ const ok = await messageQueue.enqueueMessage("hello world");
+ expect(ok).toBe(true);
+ expect(messageQueue.getQueueLength()).toBe(1);
+
+ const queued = await event;
+ expect(queued.message).toBe("hello world");
+ });
+});
diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts
new file mode 100644
index 000000000..22041d443
--- /dev/null
+++ b/extensions/cli/src/stream/messageQueue.ts
@@ -0,0 +1,62 @@
+import { EventEmitter } from "events";
+
+import type { InputHistory } from "../util/inputHistory.js";
+import { logger } from "../util/logger.js";
+
+export interface QueuedMessage {
+ message: string;
+ imageMap?: Map;
+ timestamp: number;
+ history?: InputHistory;
+}
+
+export interface MessageProcessor {
+ (message: string, imageMap?: Map): Promise;
+}
+
+/**
+ * A queue to store messages that need to be processed later
+ */
+class MessageQueue extends EventEmitter {
+ private queue: QueuedMessage[] = [];
+
+ constructor() {
+ super();
+ }
+
+ async enqueueMessage(
+ message: string,
+ imageMap?: Map,
+ history?: InputHistory,
+ ): Promise {
+ const queuedMessage: QueuedMessage = {
+ message,
+ imageMap,
+ timestamp: Date.now(),
+ history,
+ };
+
+ this.queue.push(queuedMessage);
+ logger.debug("MessageQueue: Message queued", {
+ queueLength: this.queue.length,
+ });
+
+ // Emit event for UI to show the queued message
+ this.emit("messageQueued", queuedMessage);
+
+ return true;
+ }
+
+ /**
+ * Dequeues and returns the next message to be processed (FIFO - oldest first)
+ */
+ public getNextMessage(): QueuedMessage | undefined {
+ return this.queue.shift();
+ }
+
+ getQueueLength(): number {
+ return this.queue.length;
+ }
+}
+
+export const messageQueue = new MessageQueue();
diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
index 5960a952a..528e28be2 100644
--- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
+++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
@@ -147,7 +147,7 @@ describe("handleAutoCompaction", () => {
"Auto-compacting...",
);
expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
- "✓ Chat history auto-compacted successfully.",
+ "Chat history auto-compacted successfully.",
);
expect(result).toEqual({
diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
index 4e55a2cd5..797cfba2b 100644
--- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
+++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
@@ -55,7 +55,7 @@ function handleCompactionSuccess(
) {
if (isHeadless) return;
- const successMessage = "✓ Chat history auto-compacted successfully.";
+ const successMessage = "Chat history auto-compacted successfully.";
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(successMessage);
diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts
index 06e0a68c0..cc987aecb 100644
--- a/extensions/cli/src/stream/streamChatResponse.helpers.ts
+++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts
@@ -1,11 +1,13 @@
// Helper functions extracted from streamChatResponse.ts to reduce file size
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs";
import { checkToolPermission } from "../permissions/permissionChecker.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import { ToolCallRequest } from "../permissions/types.js";
import { services } from "../services/index.js";
+import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { calculateTokenCost } from "../telemetry/utils.js";
import {
@@ -64,7 +66,11 @@ export function handleHeadlessPermission(
`If you don't want the tool to be included, use --exclude ${toolName}.`,
);
- process.exit(1);
+ // 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
+ throw new Error("Exiting due to headless permission requirement");
}
// Helper function to request user permission
@@ -286,6 +292,17 @@ export function recordStreamTelemetry(options: {
costUsd: cost,
});
+ // Mirror core metrics to PostHog for product analytics
+ try {
+ posthogService.capture("apiRequest", {
+ model: model.model,
+ durationMs: totalDuration,
+ inputTokens,
+ outputTokens,
+ costUsd: cost,
+ });
+ } catch {}
+
return cost;
}
@@ -338,6 +355,11 @@ export async function preprocessStreamedToolCalls(
// Notify the UI about the tool start, even though it failed
callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
+ const errorReason =
+ error instanceof ContinueError
+ ? error.reason
+ : ContinueErrorReason.Unknown;
+
const errorMessage =
error instanceof Error ? error.message : String(error);
@@ -352,6 +374,15 @@ export async function preprocessStreamedToolCalls(
success: false,
durationMs: duration,
error: errorMessage,
+ errorReason,
+ // modelName, TODO
+ });
+ void posthogService.capture("tool_call_outcome", {
+ succeeded: false,
+ toolName: toolCall.name,
+ errorReason,
+ duration_ms: duration,
+ // model: options.modelName, TODO
});
// Add error to chat history
diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts
index 95316e975..a59fa8cf7 100644
--- a/extensions/cli/src/stream/streamChatResponse.ts
+++ b/extensions/cli/src/stream/streamChatResponse.ts
@@ -11,13 +11,16 @@ import type {
import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
import { systemMessageService } from "../services/SystemMessageService.js";
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
+import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { ToolCall } from "../tools/index.js";
import {
chatCompletionStreamWithBackoff,
+ isContextLengthError,
withExponentialBackoff,
} from "../util/exponentialBackoff.js";
import { logger } from "../util/logger.js";
+import { validateContextLength } from "../util/tokenizer.js";
import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
@@ -147,6 +150,12 @@ export async function processStreamingResponse(
tools,
} = options;
+ // Validate context length before making the request
+ const validation = validateContextLength(chatHistory, model);
+ if (!validation.isValid) {
+ throw new Error(`Context length validation failed: ${validation.error}`);
+ }
+
// Get fresh system message and inject it
const systemMessage = await systemMessageService.getSystemMessage();
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
@@ -258,6 +267,15 @@ export async function processStreamingResponse(
error: error.message || String(error),
});
+ try {
+ posthogService.capture("apiRequest", {
+ model: model.model,
+ durationMs: errorDuration,
+ success: false,
+ error: error.message || String(error),
+ });
+ } catch {}
+
if (error.name === "AbortError" || abortController?.signal.aborted) {
logger.debug("Stream aborted by user");
return {
@@ -267,6 +285,13 @@ export async function processStreamingResponse(
shouldContinue: false,
};
}
+
+ // Handle context length errors with helpful message
+ if (isContextLengthError(error)) {
+ logger.debug(`Context length exceeded: ${error}`);
+ throw new Error(`Context length exceeded: ${error}`);
+ }
+
throw error;
}
@@ -333,6 +358,31 @@ export async function streamChatResponse(
}
logger.debug("Starting conversation iteration");
+ // Pre-API auto-compaction checkpoint
+ const { wasCompacted: preCompacted, chatHistory: preCompactHistory } =
+ await handleAutoCompaction(chatHistory, model, llmApi, {
+ isHeadless,
+ callbacks: {
+ onSystemMessage: callbacks?.onSystemMessage,
+ onContent: callbacks?.onContent,
+ },
+ });
+
+ if (preCompacted) {
+ logger.debug("Pre-API compaction occurred, updating chat history");
+ // Update chat history after pre-compaction
+ const chatHistorySvc2 = services.chatHistory;
+ if (
+ typeof chatHistorySvc2?.isReady === "function" &&
+ chatHistorySvc2.isReady()
+ ) {
+ chatHistorySvc2.setHistory(preCompactHistory);
+ chatHistory = chatHistorySvc2.getHistory();
+ } else {
+ chatHistory = [...preCompactHistory];
+ }
+ }
+
// Recompute tools on each iteration to handle mode changes during streaming
const tools = await getAllTools();
diff --git a/extensions/cli/src/telemetry/headerUtils.ts b/extensions/cli/src/telemetry/headerUtils.ts
new file mode 100644
index 000000000..ae09d953b
--- /dev/null
+++ b/extensions/cli/src/telemetry/headerUtils.ts
@@ -0,0 +1,26 @@
+export function parseOtelHeaders(headersStr: string): Record {
+ const headers: Record = {};
+ if (!headersStr) return headers;
+
+ headersStr.split(",").forEach((header) => {
+ const [key, value] = header.split("=");
+ if (key && value) {
+ headers[key.trim()] = value.trim();
+ }
+ });
+
+ return headers;
+}
+
+export function detectTerminalType(): string | undefined {
+ if (process.env.TERM_PROGRAM) {
+ return process.env.TERM_PROGRAM;
+ }
+ if (process.env.VSCODE_PID) {
+ return "vscode";
+ }
+ if (process.env.TMUX) {
+ return "tmux";
+ }
+ return undefined;
+}
diff --git a/extensions/cli/src/telemetry/posthogService.test.ts b/extensions/cli/src/telemetry/posthogService.test.ts
index 1c55826e5..ebd609a3f 100644
--- a/extensions/cli/src/telemetry/posthogService.test.ts
+++ b/extensions/cli/src/telemetry/posthogService.test.ts
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { machineIdSync } from "node-machine-id";
-import { vi, describe, it, beforeEach, afterEach, expect } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// Mock the auth module and node-machine-id
vi.mock("../auth/workos.js", () => ({
@@ -21,9 +21,14 @@ vi.mock("node-machine-id", () => {
};
});
-// Import after mocks are set up
-import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js";
+// Mock dns/promises for connection checks
+vi.mock("dns/promises", () => {
+ const lookup = vi.fn();
+ return { default: { lookup } };
+});
+// eslint-disable-next-line import/order
+import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
import { PosthogService } from "./posthogService.js";
describe("PosthogService", () => {
@@ -117,4 +122,35 @@ describe("PosthogService", () => {
expect(service.isEnabled).toBe(false);
});
});
+
+ describe("hasInternetConnection and offline client", () => {
+ let service: PosthogService;
+
+ beforeEach(() => {
+ service = new PosthogService();
+ });
+
+ it("returns false on DNS error, caches and refetches", async () => {
+ const dns: any = (await import("dns/promises")).default;
+ dns.lookup.mockRejectedValueOnce(new Error("offline"));
+ const first = await (service as any).hasInternetConnection();
+ expect(first).toBe(false);
+ dns.lookup.mockResolvedValueOnce({
+ address: "1.1.1.1",
+ family: 4,
+ } as any);
+ await (service as any).hasInternetConnection();
+ const second = (service as any)._hasInternetConnection;
+ expect(second).toBe(true);
+ expect(dns.lookup).toHaveBeenCalledTimes(2);
+ });
+
+ it("getClient returns undefined when offline", async () => {
+ const dns: any = (await import("dns/promises")).default;
+ dns.lookup.mockRejectedValueOnce(new Error("offline"));
+ const client = await (service as any).getClient();
+ expect(client).toBeUndefined();
+ expect(dns.lookup).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/extensions/cli/src/telemetry/posthogService.ts b/extensions/cli/src/telemetry/posthogService.ts
index 3039a312b..2ec311d51 100644
--- a/extensions/cli/src/telemetry/posthogService.ts
+++ b/extensions/cli/src/telemetry/posthogService.ts
@@ -5,6 +5,7 @@ import node_machine_id from "node-machine-id";
import type { PostHog as PostHogType } from "posthog-node";
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
+import { isHeadlessMode } from "../util/cli.js";
import { isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
@@ -38,14 +39,6 @@ export class PosthogService {
return this._hasInternetConnection;
}
- /**
- * Check if running in headless mode (-p/--print flags)
- */
- private isHeadlessMode(): boolean {
- const args = process.argv.slice(2);
- return args.includes("-p") || args.includes("--print");
- }
-
get isEnabled() {
return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0";
}
@@ -100,7 +93,7 @@ export class PosthogService {
extensionVersion: getVersion(),
ideName: "cn",
ideType: "cli",
- isHeadless: this.isHeadlessMode(),
+ isHeadless: isHeadlessMode(),
isGitHubCI: isGitHubActions(),
};
const payload = {
diff --git a/extensions/cli/src/telemetry/telemetryService.sessionMetadata.test.ts b/extensions/cli/src/telemetry/telemetryService.sessionMetadata.test.ts
new file mode 100644
index 000000000..a3315acb4
--- /dev/null
+++ b/extensions/cli/src/telemetry/telemetryService.sessionMetadata.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { telemetryService } from "./telemetryService.js";
+
+describe("TelemetryService - Session Metadata", () => {
+ let originalEnv: NodeJS.ProcessEnv;
+ let originalArgv: string[];
+
+ beforeEach(() => {
+ // Save original environment and argv
+ originalEnv = { ...process.env };
+ originalArgv = [...process.argv];
+
+ // Mock logger to prevent console output during tests
+ vi.mock("../util/logger.js", () => ({
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ }));
+
+ // Enable telemetry for tests
+ process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "1";
+ process.env.OTEL_METRICS_EXPORTER = "console";
+ });
+
+ afterEach(() => {
+ // Restore original environment and argv
+ process.env = originalEnv;
+ process.argv = originalArgv;
+ vi.clearAllMocks();
+ });
+
+ describe("recordSessionStart", () => {
+ it("should include is_headless=false when not in headless mode", () => {
+ // Set up non-headless mode (no -p or --print flags)
+ process.argv = ["node", "cli.js", "chat"];
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_headless: "false",
+ }),
+ );
+ });
+
+ it("should include is_headless=true when -p flag is present", () => {
+ // Set up headless mode with -p flag
+ process.argv = ["node", "cli.js", "-p", "What is the weather?"];
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_headless: "true",
+ }),
+ );
+ });
+
+ it("should include is_headless=true when --print flag is present", () => {
+ // Set up headless mode with --print flag
+ process.argv = ["node", "cli.js", "--print", "What is the weather?"];
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_headless: "true",
+ }),
+ );
+ });
+
+ it("should include is_github_actions=false when not in GitHub Actions", () => {
+ // Ensure GITHUB_ACTIONS is not set
+ delete process.env.GITHUB_ACTIONS;
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_github_actions: "false",
+ is_continue_remote_agent: "false",
+ }),
+ );
+ });
+
+ it("should include is_github_actions=true when in GitHub Actions", () => {
+ // Set GitHub Actions environment
+ process.env.GITHUB_ACTIONS = "true";
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_github_actions: "true",
+ is_continue_remote_agent: "false",
+ }),
+ );
+ });
+
+ it("should include both headless and GitHub Actions metadata when both are true", () => {
+ // Set both headless mode and GitHub Actions
+ process.argv = ["node", "cli.js", "-p", "What is the weather?"];
+ process.env.GITHUB_ACTIONS = "true";
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_headless: "true",
+ is_github_actions: "true",
+ is_continue_remote_agent: "false",
+ }),
+ );
+ });
+
+ it("should include is_continue_remote_agent=true when in remote agent mode", () => {
+ // Set Continue remote agent environment
+ process.env.CONTINUE_REMOTE = "true";
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_continue_remote_agent: "true",
+ }),
+ );
+ });
+
+ it("should include all environment flags when all are true", () => {
+ // Set all environments
+ process.argv = ["node", "cli.js", "-p", "What is the weather?"];
+ process.env.GITHUB_ACTIONS = "true";
+ process.env.CONTINUE_REMOTE = "true";
+
+ const mockAdd = vi.fn();
+ const mockRecord = vi.fn();
+ const service = telemetryService as any;
+
+ // Mock the session counter and startup time histogram
+ service.sessionCounter = { add: mockAdd };
+ service.startupTimeHistogram = { record: mockRecord };
+ service.config = { enabled: true };
+ service.meter = {};
+
+ service.recordSessionStart();
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ is_headless: "true",
+ is_github_actions: "true",
+ is_continue_remote_agent: "true",
+ }),
+ );
+ });
+ });
+});
diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts
index 00959e408..f81211298 100644
--- a/extensions/cli/src/telemetry/telemetryService.ts
+++ b/extensions/cli/src/telemetry/telemetryService.ts
@@ -12,22 +12,23 @@ import {
SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
SEMRESATTRS_HOST_NAME,
SEMRESATTRS_OS_TYPE,
- SEMRESATTRS_PROCESS_PID,
- SEMRESATTRS_SERVICE_INSTANCE_ID,
SEMRESATTRS_SERVICE_NAME,
SEMRESATTRS_SERVICE_VERSION,
} from "@opentelemetry/semantic-conventions";
import { v4 as uuidv4 } from "uuid";
+import { isHeadlessMode } from "../util/cli.js";
+import { isContinueRemoteAgent, isGitHubActions } from "../util/git.js";
import { logger } from "../util/logger.js";
import { getVersion } from "../version.js";
+import { detectTerminalType, parseOtelHeaders } from "./headerUtils.js";
+
export interface TelemetryConfig {
enabled: boolean;
sessionId: string;
organizationId?: string;
accountUuid?: string;
- includeSessionId: boolean;
includeVersion: boolean;
includeAccountUuid: boolean;
}
@@ -78,7 +79,6 @@ class TelemetryService {
sessionId,
organizationId: process.env.ORGANIZATION_ID,
accountUuid: process.env.ACCOUNT_UUID,
- includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false",
includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true",
includeAccountUuid:
process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false",
@@ -91,12 +91,10 @@ class TelemetryService {
const resource = resourceFromAttributes({
[SEMRESATTRS_SERVICE_NAME]: "continue-cli",
[SEMRESATTRS_SERVICE_VERSION]: getVersion(),
- [SEMRESATTRS_SERVICE_INSTANCE_ID]: uuidv4(),
[SEMRESATTRS_HOST_NAME]: os.hostname(),
[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:
process.env.NODE_ENV || "development",
[SEMRESATTRS_OS_TYPE]: os.type(),
- [SEMRESATTRS_PROCESS_PID]: process.pid.toString(),
});
// Configure exporters
@@ -111,11 +109,20 @@ class TelemetryService {
readers.push(
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({
- url:
- process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
- `${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` ||
- "http://localhost:4318/v1/metrics",
- headers: this.parseHeaders(
+ url: (() => {
+ const metricsEndpoint =
+ process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT;
+ if (metricsEndpoint && metricsEndpoint.trim().length > 0) {
+ return metricsEndpoint;
+ }
+ const base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
+ if (base && base.trim().length > 0) {
+ const normalized = base.replace(/\/$/, "");
+ return `${normalized}/v1/metrics`;
+ }
+ return "http://localhost:4318/v1/metrics";
+ })(),
+ headers: parseOtelHeaders(
process.env.OTEL_EXPORTER_OTLP_HEADERS || "",
),
}),
@@ -181,20 +188,6 @@ class TelemetryService {
this.shutdownHandlersRegistered = true;
}
- private parseHeaders(headersStr: string): Record {
- const headers: Record = {};
- if (!headersStr) return headers;
-
- headersStr.split(",").forEach((header) => {
- const [key, value] = header.split("=");
- if (key && value) {
- headers[key.trim()] = value.trim();
- }
- });
-
- return headers;
- }
-
private initializeMetrics() {
if (!this.meter) return;
@@ -306,10 +299,6 @@ class TelemetryService {
) {
const attributes: Record = { ...additionalAttributes };
- if (this.config.includeSessionId) {
- attributes["session.id"] = this.config.sessionId;
- }
-
if (this.config.includeVersion) {
attributes["app.version"] = getVersion();
}
@@ -323,7 +312,7 @@ class TelemetryService {
}
// Detect terminal type
- const terminalType = this.detectTerminalType();
+ const terminalType = detectTerminalType();
if (terminalType) {
attributes["terminal.type"] = terminalType;
}
@@ -331,26 +320,22 @@ class TelemetryService {
return attributes;
}
- private detectTerminalType(): string | undefined {
- if (process.env.TERM_PROGRAM) {
- return process.env.TERM_PROGRAM;
- }
- if (process.env.VSCODE_PID) {
- return "vscode";
- }
- if (process.env.TMUX) {
- return "tmux";
- }
- return undefined;
- }
-
// Public methods for tracking metrics
public recordSessionStart() {
if (!this.isEnabled()) return;
logger.debug("Recording session start with telemetry");
- this.sessionCounter.add(1, this.getStandardAttributes());
+
+ // Add extra metadata for session breakdown
+ const isGitHubActionsEnv = isGitHubActions();
+ const sessionAttributes = this.getStandardAttributes({
+ is_headless: isHeadlessMode().toString(),
+ is_github_actions: isGitHubActionsEnv.toString(),
+ is_continue_remote_agent: isContinueRemoteAgent().toString(),
+ });
+
+ this.sessionCounter.add(1, sessionAttributes);
this.recordStartupTime(Date.now() - this.startTime);
}
@@ -424,13 +409,12 @@ class TelemetryService {
if (!this.isEnabled()) return;
if (this.activeStartTime !== null) {
- this.totalActiveTime += Date.now() - this.activeStartTime;
+ const deltaMs = Date.now() - this.activeStartTime;
+ this.totalActiveTime += deltaMs;
this.activeStartTime = null;
- this.activeTimeCounter.add(
- this.totalActiveTime / 1000,
- this.getStandardAttributes(),
- );
+ // Record only the delta for this active window (in seconds)
+ this.activeTimeCounter.add(deltaMs / 1000, this.getStandardAttributes());
}
}
@@ -514,9 +498,11 @@ class TelemetryService {
success: boolean;
durationMs: number;
error?: string;
+ errorReason?: string;
decision?: "accept" | "reject";
source?: string;
toolParameters?: string;
+ // modelName: string;
}) {
if (!this.isEnabled()) return;
@@ -533,6 +519,12 @@ class TelemetryService {
if (options.source) attributes.source = options.source;
if (options.toolParameters)
attributes.tool_parameters = options.toolParameters;
+ if (options.errorReason) {
+ attributes.error_reason = options.errorReason;
+ }
+ if (options.error) {
+ attributes.error = options.error;
+ }
// TODO: Implement OTLP logs export
logger.debug("Tool result event", attributes);
diff --git a/extensions/cli/src/test-helpers/cli-helpers.ts b/extensions/cli/src/test-helpers/cli-helpers.ts
index 5d1ffc75f..1814c671c 100644
--- a/extensions/cli/src/test-helpers/cli-helpers.ts
+++ b/extensions/cli/src/test-helpers/cli-helpers.ts
@@ -30,7 +30,8 @@ export interface CLIRunResult {
* Creates a test context with isolated test directory
*/
export async function createTestContext(): Promise {
- const cliPath = path.resolve("dist/index.js");
+ // Use the wrapper script that invokes runCli(), not the raw bundle entry
+ const cliPath = path.resolve("dist/cn.js");
const testDir = await fs.mkdtemp(path.join(os.tmpdir(), "cn-test-"));
// Ensure the CLI file exists before returning the context
@@ -38,7 +39,7 @@ export async function createTestContext(): Promise {
await fs.access(cliPath);
} catch {
throw new Error(
- `CLI file not found at ${cliPath}. Please run 'npm run build' first.`,
+ `CLI wrapper not found at ${cliPath}. Please run 'npm run build' first.`,
);
}
@@ -97,6 +98,7 @@ export async function runCLI(
};
try {
+ // Run the wrapper via Node for cross-platform consistency
const result = await execaNode(context.cliPath, args, execOptions);
return {
diff --git a/extensions/cli/src/tools/edit.test.ts b/extensions/cli/src/tools/edit.test.ts
index 03c58c4ed..d0b265f22 100644
--- a/extensions/cli/src/tools/edit.test.ts
+++ b/extensions/cli/src/tools/edit.test.ts
@@ -1,19 +1,21 @@
import * as fs from "fs";
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ calculateLinesOfCodeDiff,
+ getLanguageFromFilePath,
+} from "../telemetry/utils.js";
+
import { editTool } from "./edit.js";
import { markFileAsRead, readFilesSet } from "./readFile.js";
+import { generateDiff } from "./writeFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
-vi.mock("../telemetry/utils.js", () => ({
- calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }),
- getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"),
-}));
-vi.mock("./writeFile.js", () => ({
- generateDiff: vi.fn().mockReturnValue("mocked diff"),
-}));
+vi.mock("../telemetry/utils.js");
+vi.mock("./writeFile.js");
vi.mock("fs", async () => {
const actual = await vi.importActual("fs");
return {
@@ -37,6 +39,14 @@ describe("editTool", () => {
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
+
+ // Setup utility mocks with proper return values
+ vi.mocked(calculateLinesOfCodeDiff).mockReturnValue({
+ added: 1,
+ removed: 0,
+ });
+ vi.mocked(getLanguageFromFilePath).mockReturnValue("javascript");
+ vi.mocked(generateDiff).mockReturnValue("mocked diff");
});
afterEach(() => {
@@ -52,9 +62,9 @@ describe("editTool", () => {
new_string: "Hi there",
};
- await expect(editTool.preprocess!(args)).rejects.toThrow(
- `You must use the Read tool to read ${testFilePath} before editing it.`,
- );
+ const error = await editTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead);
});
it("should throw error if file does not exist", async () => {
@@ -68,9 +78,9 @@ describe("editTool", () => {
new_string: "Hi",
};
- await expect(editTool.preprocess!(args)).rejects.toThrow(
- `File ${nonExistentFile} does not exist`,
- );
+ const error = await editTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.FileNotFound);
});
it("should throw error if old_string is not found", async () => {
@@ -83,8 +93,10 @@ describe("editTool", () => {
new_string: "Hi there",
};
- await expect(editTool.preprocess!(args)).rejects.toThrow(
- "String not found in file: Not found",
+ const error = await editTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(
+ ContinueErrorReason.FindAndReplaceOldStringNotFound,
);
});
@@ -98,8 +110,10 @@ describe("editTool", () => {
replace_all: false,
};
- await expect(editTool.preprocess!(args)).rejects.toThrow(
- 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
+ const error = await editTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(
+ ContinueErrorReason.FindAndReplaceMultipleOccurrences,
);
});
@@ -112,8 +126,10 @@ describe("editTool", () => {
new_string: "Hello world",
};
- await expect(editTool.preprocess!(args)).rejects.toThrow(
- "old_string and new_string must be different",
+ const error = await editTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(
+ ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
);
});
@@ -194,9 +210,9 @@ describe("editTool", () => {
oldContent: originalContent,
};
- await expect(editTool.run(args)).rejects.toThrow(
- `Error: failed to edit ${testFilePath}: Write failed`,
- );
+ const error = await editTool.run(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.FileWriteError);
});
});
diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts
index 545d14269..a3623361d 100644
--- a/extensions/cli/src/tools/edit.ts
+++ b/extensions/cli/src/tools/edit.ts
@@ -1,6 +1,10 @@
import * as fs from "fs";
+import path from "path";
+import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils.js";
+import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
@@ -8,15 +12,53 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
+import { EditOperation } from "./multiEdit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
-export interface EditArgs {
+export function validateAndResolveFilePath(args: any): {
+ originalPath: string;
+ resolvedPath: string;
+} {
+ const { file_path } = args;
+
+ if (!file_path) {
+ throw new ContinueError(
+ ContinueErrorReason.FindAndReplaceMissingFilepath,
+ "file_path is required",
+ );
+ }
+
+ const absolutePath = path.isAbsolute(file_path)
+ ? file_path
+ : path.resolve(process.cwd(), file_path);
+
+ const resolvedPath = fs.realpathSync(absolutePath);
+
+ throwIfFileIsSecurityConcern(resolvedPath);
+
+ // Check if file exists
+ if (!fs.existsSync(resolvedPath)) {
+ throw new ContinueError(
+ ContinueErrorReason.FileNotFound,
+ `File ${file_path} does not exist`,
+ );
+ }
+
+ // Check if file has been read
+ if (!readFilesSet.has(resolvedPath)) {
+ throw new ContinueError(
+ ContinueErrorReason.EditToolFileNotRead,
+ `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
+ );
+ }
+
+ return { originalPath: file_path, resolvedPath: resolvedPath };
+}
+
+export interface EditArgs extends EditOperation {
file_path: string;
- old_string: string;
- new_string: string;
- replace_all?: boolean;
}
export const editTool: Tool = {
@@ -37,91 +79,45 @@ WARNINGS:
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
- The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`,
parameters: {
- file_path: {
- type: "string",
- description: "The absolute path to the file to modify",
- required: true,
- },
- old_string: {
- type: "string",
- description:
- "The text to replace - must be exact including whitespace/indentation",
- required: true,
- },
- new_string: {
- type: "string",
- description:
- "The text to replace it with (MUST be different from old_string)",
- required: true,
- },
- replace_all: {
- type: "boolean",
- description: "Replace all occurences of old_string (default false)",
- required: false,
+ type: "object",
+ required: ["file_path", "old_string", "new_string"],
+ properties: {
+ file_path: {
+ type: "string",
+ description:
+ "Absolute or relative path to the file to modify. Absolute preferred",
+ },
+ old_string: {
+ type: "string",
+ description:
+ "The text to replace - must be exact including whitespace/indentation",
+ },
+ new_string: {
+ type: "string",
+ description:
+ "The text to replace it with (MUST be different from old_string)",
+ },
+ replace_all: {
+ type: "boolean",
+ description: "Replace all occurrences of old_string (default false)",
+ },
},
},
preprocess: async (args) => {
- const {
- file_path,
+ const { old_string, new_string, replace_all = false } = args as EditArgs;
+
+ const { resolvedPath } = validateAndResolveFilePath(args);
+
+ validateSingleEdit(old_string, new_string);
+
+ const oldContent = fs.readFileSync(resolvedPath, "utf-8");
+ const newContent = executeFindAndReplace(
+ oldContent,
old_string,
new_string,
- replace_all = false,
- } = args as EditArgs;
-
- // Validate arguments
- if (!file_path) {
- throw new Error("file_path is required");
- }
-
- if (!old_string) {
- throw new Error("old_string is required");
- }
- if (new_string === undefined) {
- throw new Error("new_string is required");
- }
- if (old_string === new_string) {
- throw new Error("old_string and new_string must be different");
- }
-
- const resolvedPath = fs.realpathSync(file_path);
-
- // Check if file has been read
- if (!readFilesSet.has(resolvedPath)) {
- throw new Error(
- `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
- );
- }
-
- throwIfFileIsSecurityConcern(resolvedPath);
-
- // Check if file exists
- if (!fs.existsSync(resolvedPath)) {
- throw new Error(`File ${file_path} does not exist`);
- }
-
- // Read current file content
- const oldContent = fs.readFileSync(resolvedPath, "utf-8");
-
- // Check if old_string exists in the file
- if (!oldContent.includes(old_string)) {
- throw new Error(`String not found in file: ${old_string}`);
- }
-
- let newContent: string;
-
- if (replace_all) {
- // Replace all occurrences
- newContent = oldContent.split(old_string).join(new_string);
- } else {
- // Replace only the first occurrence
- const occurrences = oldContent.split(old_string).length - 1;
- if (occurrences > 1) {
- throw new Error(
- `String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
- );
- }
- newContent = oldContent.replace(old_string, new_string);
- }
+ replace_all,
+ 0,
+ );
// Generate diff for preview
const diff = generateDiff(oldContent, newContent, resolvedPath);
@@ -179,7 +175,11 @@ WARNINGS:
return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`;
} catch (error) {
- throw new Error(
+ if (error instanceof ContinueError) {
+ throw error;
+ }
+ throw new ContinueError(
+ ContinueErrorReason.FileWriteError,
`Error: failed to edit ${args.resolvedPath}: ${
error instanceof Error ? error.message : String(error)
}`,
diff --git a/extensions/cli/src/tools/exit.ts b/extensions/cli/src/tools/exit.ts
index ebed5ecde..a6d84bdc3 100644
--- a/extensions/cli/src/tools/exit.ts
+++ b/extensions/cli/src/tools/exit.ts
@@ -5,10 +5,15 @@ export const exitTool: Tool = {
displayName: "Exit",
description:
"Exit the current process with status code 1, indicating a failure or error",
- parameters: {},
+ parameters: {
+ type: "object",
+ properties: {},
+ },
readonly: false,
isBuiltIn: true,
run: async (): Promise => {
- process.exit(1);
+ const { gracefulExit } = await import("../util/exit.js");
+ await gracefulExit(1);
+ return "";
},
};
diff --git a/extensions/cli/src/tools/fetch.test.ts b/extensions/cli/src/tools/fetch.test.ts
new file mode 100644
index 000000000..dc8e84ea6
--- /dev/null
+++ b/extensions/cli/src/tools/fetch.test.ts
@@ -0,0 +1,172 @@
+import type { ContextItem } from "core/index.js";
+import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { fetchTool } from "./fetch.js";
+
+// Mock the core fetchUrlContent implementation
+vi.mock("core/tools/implementations/fetchUrlContent.js", () => ({
+ fetchUrlContentImpl: vi.fn(),
+}));
+
+const mockFetchUrlContentImpl = vi.mocked(fetchUrlContentImpl);
+
+describe("fetchTool", () => {
+ let originalConsoleError: typeof console.error;
+
+ beforeEach(() => {
+ originalConsoleError = console.error;
+ console.error = vi.fn();
+ mockFetchUrlContentImpl.mockReset();
+ });
+
+ afterEach(() => {
+ console.error = originalConsoleError;
+ });
+
+ it("should return clean content from successful fetch", async () => {
+ const mockContextItems: ContextItem[] = [
+ {
+ name: "Example Page",
+ description: "https://example.com",
+ content:
+ "# Example Page\n\nThis is some example content from a webpage.",
+ uri: { type: "url", value: "https://example.com" },
+ },
+ ];
+
+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
+
+ const result = await fetchTool.run({ url: "https://example.com" });
+
+ expect(result).toBe(
+ "# Example Page\n\nThis is some example content from a webpage.",
+ );
+ expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
+ { url: "https://example.com" },
+ { fetch },
+ );
+ });
+
+ it("should handle truncation warnings from core implementation", async () => {
+ const mockContextItems: ContextItem[] = [
+ {
+ name: "Long Page",
+ description: "https://example.com",
+ content: "This is the main content that was truncated.",
+ uri: { type: "url", value: "https://example.com" },
+ },
+ {
+ name: "Truncation warning",
+ description: "",
+ content:
+ "The content from https://example.com was truncated because it exceeded the 20000 character limit.",
+ },
+ ];
+
+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
+
+ const result = await fetchTool.run({ url: "https://example.com" });
+
+ expect(result).toBe(
+ "This is the main content that was truncated.\n\nThe content from https://example.com was truncated because it exceeded the 20000 character limit.",
+ );
+ });
+
+ it("should handle multiple content items", async () => {
+ const mockContextItems: ContextItem[] = [
+ {
+ name: "Page 1",
+ description: "https://example.com",
+ content: "Content from page 1",
+ uri: { type: "url", value: "https://example.com" },
+ },
+ {
+ name: "Page 2",
+ description: "https://example.com",
+ content: "Content from page 2",
+ uri: { type: "url", value: "https://example.com" },
+ },
+ ];
+
+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
+
+ const result = await fetchTool.run({ url: "https://example.com" });
+
+ expect(result).toBe("Content from page 1\n\nContent from page 2");
+ });
+
+ it("should return error message when no content items returned", async () => {
+ mockFetchUrlContentImpl.mockResolvedValue([]);
+
+ const result = await fetchTool.run({ url: "https://example.com" });
+
+ expect(result).toBe(
+ "Error: Could not fetch content from https://example.com",
+ );
+ });
+
+ it("should handle errors from core implementation", async () => {
+ const error = new Error("Network error");
+ mockFetchUrlContentImpl.mockRejectedValue(error);
+
+ const result = await fetchTool.run({ url: "https://example.com" });
+
+ expect(result).toBe("Error: Network error");
+ });
+
+ it("should call fetchUrlContentImpl with correct arguments", async () => {
+ const mockContextItems: ContextItem[] = [
+ {
+ name: "Test Page",
+ description: "https://example.com",
+ content: "Test content",
+ uri: { type: "url", value: "https://example.com" },
+ },
+ ];
+
+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
+
+ await fetchTool.run({ url: "https://example.com" });
+
+ expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
+ { url: "https://example.com" },
+ { fetch },
+ );
+ });
+
+ it("should have correct tool metadata", () => {
+ expect(fetchTool.name).toBe("Fetch");
+ expect(fetchTool.displayName).toBe("Fetch");
+ expect(fetchTool.description).toBe(
+ "Fetches content from a URL, converts to markdown, and handles long content with truncation",
+ );
+ expect(fetchTool.readonly).toBe(true);
+ expect(fetchTool.isBuiltIn).toBe(true);
+ expect(fetchTool.parameters).toEqual({
+ type: "object",
+ required: ["url"],
+ properties: {
+ url: {
+ type: "string",
+ description: "The URL to fetch content from",
+ },
+ },
+ });
+ });
+
+ it("should provide correct preview in preprocess", async () => {
+ const args = { url: "https://example.com" };
+ const result = await fetchTool.preprocess?.(args);
+
+ expect(result).toEqual({
+ preview: [
+ {
+ type: "text",
+ content: "Will fetch: https://example.com",
+ },
+ ],
+ args,
+ });
+ });
+});
diff --git a/extensions/cli/src/tools/fetch.ts b/extensions/cli/src/tools/fetch.ts
index d2ca53bdd..9a04a7a05 100644
--- a/extensions/cli/src/tools/fetch.ts
+++ b/extensions/cli/src/tools/fetch.ts
@@ -1,49 +1,21 @@
-import TurndownService from "turndown";
+import type { ContextItem } from "core/index.js";
+import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
import { Tool } from "./types.js";
-const turndownService = new TurndownService({
- headingStyle: "atx",
- codeBlockStyle: "fenced",
- fence: "```",
- emDelimiter: "*",
- strongDelimiter: "**",
- linkStyle: "inlined",
- linkReferenceStyle: "full",
-});
-
-// Configure turndown for better markdown output
-turndownService.addRule("strikethrough", {
- filter: ["del", "s"],
- replacement: function (content) {
- return "~~" + content + "~~";
- },
-});
-
-// Handle code blocks better
-turndownService.addRule("pre", {
- filter: "pre",
- replacement: function (content, node) {
- const codeEl = node.querySelector("code");
- const language = codeEl?.className.match(/language-(\w+)/)?.[1] || "";
- return "\n\n```" + language + "\n" + content + "\n```\n\n";
- },
-});
-
export const fetchTool: Tool = {
name: "Fetch",
displayName: "Fetch",
- description: "Fetches content from a URL and converts it to markdown format",
+ description:
+ "Fetches content from a URL, converts to markdown, and handles long content with truncation",
parameters: {
- url: {
- type: "string",
- description: "The URL to fetch content from",
- required: true,
- },
- timeout: {
- type: "number",
- description: "Request timeout in milliseconds (default: 10000)",
- required: false,
+ type: "object",
+ required: ["url"],
+ properties: {
+ url: {
+ type: "string",
+ description: "The URL to fetch content from",
+ },
},
},
readonly: true,
@@ -59,76 +31,34 @@ export const fetchTool: Tool = {
args,
};
},
- run: async (args: { url: string; timeout?: number }): Promise => {
- const { url, timeout = 10000 } = args;
+ run: async (args: { url: string }): Promise => {
+ const { url } = args;
try {
- // Validate URL
- const urlObj = new URL(url);
- if (!["http:", "https:"].includes(urlObj.protocol)) {
- return "Error: Only HTTP and HTTPS URLs are supported";
+ // Suppress console errors from JSDOM CSS parsing
+ const originalConsoleError = console.error;
+ console.error = () => {};
+
+ // Use the core fetchUrlContent implementation
+ const contextItems = await fetchUrlContentImpl({ url }, { fetch });
+
+ // Restore console.error
+ console.error = originalConsoleError;
+
+ if (contextItems.length === 0) {
+ return `Error: Could not fetch content from ${url}`;
}
- // Fetch the content
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), timeout);
-
- const response = await fetch(url, {
- signal: controller.signal,
- headers: {
- "User-Agent": "Continue-CLI/1.0 (https://continue.dev)",
- Accept:
- "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- "Accept-Language": "en-US,en;q=0.5",
- "Accept-Encoding": "gzip, deflate",
- "Cache-Control": "no-cache",
- },
- });
-
- clearTimeout(timeoutId);
-
- if (!response.ok) {
- return `Error: HTTP ${response.status} - ${response.statusText}`;
- }
-
- const contentType = response.headers.get("content-type") || "";
-
- // Handle different content types
- if (contentType.includes("application/json")) {
- const json = await response.json();
- return "```json\n" + JSON.stringify(json, null, 2) + "\n```";
- }
-
- if (contentType.includes("text/plain")) {
- const text = await response.text();
- return text;
- }
-
- if (!contentType.includes("text/html")) {
- return `Error: Unsupported content type: ${contentType}`;
- }
-
- // Process HTML content
- const html = await response.text();
-
- // Convert HTML to markdown
- const markdown = turndownService.turndown(html);
-
- // Clean up the markdown
- const cleanedMarkdown = markdown
- .replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines
- .replace(/^\s+|\s+$/g, "") // Trim whitespace
- .replace(/\\\[/g, "[") // Unescape brackets
- .replace(/\\\]/g, "]");
-
- return `# Content from ${url}\n\n${cleanedMarkdown}`;
+ // Format the results for CLI display
+ return contextItems
+ .map((item: ContextItem) => {
+ if (item.name === "Truncation warning") {
+ return item.content;
+ }
+ return item.content;
+ })
+ .join("\n\n");
} catch (error) {
- if (error instanceof TypeError && error.message.includes("fetch")) {
- return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`;
- }
- if (error instanceof Error && error.name === "AbortError") {
- return `Error: Request timed out after ${timeout}ms`;
- }
return `Error: ${error instanceof Error ? error.message : String(error)}`;
}
},
diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx
index a4cb3dcb7..fda429563 100644
--- a/extensions/cli/src/tools/index.tsx
+++ b/extensions/cli/src/tools/index.tsx
@@ -1,4 +1,8 @@
// @ts-ignore
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
+
+import { posthogService } from "src/telemetry/posthogService.js";
+
import {
getServiceSync,
MCPServiceState,
@@ -6,8 +10,10 @@ import {
serviceContainer,
} 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";
+import { isModelCapable } from "../utils/index.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
@@ -20,13 +26,14 @@ import { searchCodeTool } from "./searchCode.js";
import {
type Tool,
type ToolCall,
- type ToolParameters,
+ type ToolParametersSchema,
+ ParameterSchema,
PreprocessedToolCall,
} from "./types.js";
import { writeChecklistTool } from "./writeChecklist.js";
import { writeFileTool } from "./writeFile.js";
-export type { Tool, ToolCall, ToolParameters };
+export type { Tool, ToolCall, ToolParametersSchema };
// Base tools that are always available
const BASE_BUILTIN_TOOLS: Tool[] = [
@@ -66,9 +73,53 @@ function getDynamicTools(): Tool[] {
return dynamicTools;
}
-// Get all builtin tools including dynamic ones
+// Check if the current model is capable and should exclude Edit tool
+function shouldExcludeEditTool(): boolean {
+ try {
+ const modelServiceResult = getServiceSync(
+ SERVICE_NAMES.MODEL,
+ );
+
+ if (
+ modelServiceResult.state === "ready" &&
+ modelServiceResult.value?.model
+ ) {
+ const { name, provider, model } = modelServiceResult.value.model;
+
+ // Check if model is capable
+ const isCapable = isModelCapable(provider, name, model);
+
+ logger.debug("Capability-based tool filtering", {
+ provider,
+ name,
+ isCapable,
+ willExcludeEdit: isCapable,
+ });
+
+ return isCapable;
+ }
+ } catch (error) {
+ logger.debug("Error checking model capability for tool filtering", {
+ error,
+ });
+ }
+ return false;
+}
+
+// Get all builtin tools including dynamic ones, with capability-based filtering
export function getAllBuiltinTools(): Tool[] {
- return [...BUILTIN_TOOLS, ...getDynamicTools()];
+ let builtinTools = [...BUILTIN_TOOLS];
+
+ // Apply capability-based filtering for edit tools
+ // If model is capable, exclude editTool in favor of multiEditTool
+ if (shouldExcludeEditTool()) {
+ builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name);
+ logger.debug(
+ "Excluded Edit tool for capable model - MultiEdit will be used instead",
+ );
+ }
+
+ return [...builtinTools, ...getDynamicTools()];
}
export function getToolDisplayName(toolName: string): string {
@@ -102,22 +153,6 @@ export function extractToolCalls(
return toolCalls;
}
-function convertInputSchemaToParameters(inputSchema: any): ToolParameters {
- const parameters: Record<
- string,
- { type: string; description: string; required: boolean }
- > = {};
- for (const [key, value] of Object.entries(inputSchema.properties)) {
- const val = value as any;
- parameters[key] = {
- type: val.type,
- description: val.description || "",
- required: inputSchema.required?.includes(key) || false,
- };
- }
- return parameters;
-}
-
export async function getAvailableTools() {
// Load MCP tools
const mcpState = await serviceContainer.get(
@@ -129,7 +164,14 @@ export async function getAvailableTools() {
name: t.name,
displayName: t.name.replace("mcp__", "").replace("ide__", ""),
description: t.description ?? "",
- parameters: convertInputSchemaToParameters(t.inputSchema),
+ parameters: {
+ type: "object",
+ properties: (t.inputSchema.properties ?? {}) as Record<
+ string,
+ ParameterSchema
+ >,
+ required: t.inputSchema.required,
+ },
readonly: undefined, // MCP tools don't have readonly property
isBuiltIn: false,
run: async (args: any) => {
@@ -166,6 +208,11 @@ export async function executeToolCall(
durationMs: duration,
toolParameters: JSON.stringify(toolCall.arguments),
});
+ void posthogService.capture("tool_call_outcome", {
+ succeeded: true,
+ toolName: toolCall.name,
+ duration_ms: duration,
+ });
logger.debug("Tool execution completed", {
toolName: toolCall.name,
@@ -176,23 +223,36 @@ export async function executeToolCall(
} catch (error) {
const duration = Date.now() - startTime;
const errorMessage = error instanceof Error ? error.message : String(error);
+ const errorReason =
+ error instanceof ContinueError
+ ? error.reason
+ : ContinueErrorReason.Unknown;
telemetryService.logToolResult({
toolName: toolCall.name,
success: false,
durationMs: duration,
error: errorMessage,
+ errorReason,
toolParameters: JSON.stringify(toolCall.arguments),
});
+ void posthogService.capture("tool_call_outcome", {
+ succeeded: false,
+ toolName: toolCall.name,
+ duration_ms: duration,
+ errorReason,
+ });
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
}
}
+// Only checks top-level required
export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) {
- for (const [paramName, paramDef] of Object.entries(tool.parameters)) {
+ const requiredParams = tool.parameters.required ?? [];
+ for (const [paramName] of Object.entries(tool.parameters)) {
if (
- paramDef.required &&
+ requiredParams.includes(paramName) &&
(toolCall.arguments[paramName] === undefined ||
toolCall.arguments[paramName] === null)
) {
diff --git a/extensions/cli/src/tools/listFiles.ts b/extensions/cli/src/tools/listFiles.ts
index 181d4a9f1..3d14e2d9b 100644
--- a/extensions/cli/src/tools/listFiles.ts
+++ b/extensions/cli/src/tools/listFiles.ts
@@ -10,10 +10,13 @@ export const listFilesTool: Tool = {
displayName: "List",
description: "List files in a directory",
parameters: {
- dirpath: {
- type: "string",
- description: "The path to the directory to list",
- required: true,
+ type: "object",
+ required: ["dirpath"],
+ properties: {
+ dirpath: {
+ type: "string",
+ description: "The path to the directory to list",
+ },
},
},
readonly: true,
diff --git a/extensions/cli/src/tools/multiEdit.test.ts b/extensions/cli/src/tools/multiEdit.test.ts
index 597cab767..1f6d9cfde 100644
--- a/extensions/cli/src/tools/multiEdit.test.ts
+++ b/extensions/cli/src/tools/multiEdit.test.ts
@@ -1,10 +1,17 @@
import * as fs from "fs";
import * as path from "path";
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ calculateLinesOfCodeDiff,
+ getLanguageFromFilePath,
+} from "../telemetry/utils.js";
+
import { multiEditTool } from "./multiEdit.js";
import { markFileAsRead } from "./readFile.js";
+import { generateDiff } from "./writeFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
@@ -15,6 +22,7 @@ vi.mock("../telemetry/utils.js", () => ({
vi.mock("./writeFile.js", () => ({
generateDiff: vi.fn().mockReturnValue("mocked diff"),
}));
+
vi.mock("fs", async () => {
const actual = await vi.importActual("fs");
return {
@@ -27,7 +35,7 @@ vi.mock("fs", async () => {
};
});
-describe("multiEditTool", () => {
+describe("multiEditTool CLI specific", () => {
const testFilePath = "/tmp/test-multi-edit-file.txt";
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
@@ -38,13 +46,21 @@ describe("multiEditTool", () => {
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
+
+ // Setup utility mocks with proper return values
+ vi.mocked(calculateLinesOfCodeDiff).mockReturnValue({
+ added: 1,
+ removed: 0,
+ });
+ vi.mocked(getLanguageFromFilePath).mockReturnValue("javascript");
+ vi.mocked(generateDiff).mockReturnValue("mocked diff");
});
afterEach(() => {
vi.clearAllMocks();
});
- describe("preprocess", () => {
+ describe("file system validation", () => {
it("should throw error if file has not been read", async () => {
const args = {
file_path: testFilePath,
@@ -56,9 +72,9 @@ describe("multiEditTool", () => {
],
};
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- `You must use the Read tool to read ${testFilePath} before editing it.`,
- );
+ const error = await multiEditTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.EditToolFileNotRead);
});
it("should throw error if file does not exist", async () => {
@@ -76,117 +92,31 @@ describe("multiEditTool", () => {
],
};
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- `File ${nonExistentFile} does not exist`,
- );
+ const error = await multiEditTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.FileNotFound);
});
- it("should throw error if edits array is empty", async () => {
- markFileAsRead(testFilePath);
-
+ it("should throw error if file_path is missing", async () => {
const args = {
- file_path: testFilePath,
- edits: [],
- };
-
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- "edits array is required and must contain at least one edit",
- );
- });
-
- it("should throw error if edit has missing old_string", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
edits: [
{
- old_string: undefined as any,
- new_string: "Hi there",
+ old_string: "Hello",
+ new_string: "Hi",
},
],
};
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- "Edit 1: old_string is required",
+ const error = await multiEditTool.preprocess!(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(
+ ContinueErrorReason.FindAndReplaceMissingFilepath,
);
});
+ });
- it("should throw error if edit has missing new_string", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "Hello world",
- new_string: undefined as any,
- },
- ],
- };
-
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- "Edit 1: new_string is required",
- );
- });
-
- it("should throw error if old_string and new_string are the same", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "Hello world",
- new_string: "Hello world",
- },
- ],
- };
-
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- "Edit 1: old_string and new_string must be different",
- );
- });
-
- it("should throw error if old_string is not found", async () => {
- markFileAsRead(testFilePath);
- vi.mocked(fs.readFileSync).mockReturnValue("Different content");
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "Not found",
- new_string: "Hi there",
- },
- ],
- };
-
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- 'Edit 1: String not found in file: "Not found"',
- );
- });
-
- it("should throw error if old_string appears multiple times and replace_all is false", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "world",
- new_string: "universe",
- replace_all: false,
- },
- ],
- };
-
- await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
- 'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
- );
- });
-
- it("should successfully preprocess single edit", async () => {
+ describe("preprocess CLI specific", () => {
+ it("should generate preview with diff", async () => {
markFileAsRead(testFilePath);
const args = {
@@ -201,120 +131,16 @@ describe("multiEditTool", () => {
const result = await multiEditTool.preprocess!(args);
- expect(result.args).toEqual({
- file_path: testFilePath,
- newContent: "Hi there\nThis is a test file\nGoodbye world",
- originalContent: originalContent,
- isCreatingNewFile: false,
- editCount: 1,
- });
expect(result.preview).toHaveLength(2);
expect(result.preview?.[0]).toEqual({
type: "text",
- content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:",
+ content: "Will apply 1 edit to /tmp/test-multi-edit-file.txt:",
});
expect(result.preview?.[1]).toEqual({
type: "diff",
content: "mocked diff",
});
});
-
- it("should successfully preprocess multiple edits", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "Hello world",
- new_string: "Hi there",
- },
- {
- old_string: "Goodbye world",
- new_string: "See you later",
- },
- ],
- };
-
- const result = await multiEditTool.preprocess!(args);
-
- expect(result.args.newContent).toBe(
- "Hi there\nThis is a test file\nSee you later",
- );
- expect(result.args.editCount).toBe(2);
- expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
- });
-
- it("should successfully preprocess replace_all edit", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "world",
- new_string: "universe",
- replace_all: true,
- },
- ],
- };
-
- const result = await multiEditTool.preprocess!(args);
-
- expect(result.args.newContent).toBe(
- "Hello universe\nThis is a test file\nGoodbye universe",
- );
- });
-
- it("should handle new file creation with empty old_string", async () => {
- const newFilePath = "/tmp/new-file.txt";
- vi.mocked(fs.existsSync).mockImplementation((path) => {
- // Parent directory exists, but file doesn't
- if (path === "/tmp") return true;
- if (path === newFilePath) return false;
- return true;
- });
-
- const args = {
- file_path: newFilePath,
- edits: [
- {
- old_string: "",
- new_string: "New file content\nSecond line",
- },
- ],
- };
-
- const result = await multiEditTool.preprocess!(args);
-
- expect(result.args.newContent).toBe("New file content\nSecond line");
- expect(result.args.isCreatingNewFile).toBe(true);
- expect(result.preview?.[0]?.content).toContain("create");
- });
-
- it("should apply edits sequentially", async () => {
- markFileAsRead(testFilePath);
-
- const args = {
- file_path: testFilePath,
- edits: [
- {
- old_string: "Hello world",
- new_string: "Hi universe",
- },
- {
- old_string: "Hi universe",
- new_string: "Greetings cosmos",
- },
- ],
- };
-
- const result = await multiEditTool.preprocess!(args);
-
- expect(result.args.newContent).toBe(
- "Greetings cosmos\nThis is a test file\nGoodbye world",
- );
- });
});
describe("run", () => {
@@ -324,7 +150,6 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent,
originalContent: originalContent,
- isCreatingNewFile: false,
editCount: 1,
};
@@ -345,7 +170,6 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent: "New content",
originalContent: originalContent,
- isCreatingNewFile: false,
editCount: 3,
};
@@ -356,22 +180,6 @@ describe("multiEditTool", () => {
);
});
- it("should return correct message for new file creation", async () => {
- const args = {
- file_path: "/tmp/new-file.txt",
- newContent: "New file content",
- originalContent: "",
- isCreatingNewFile: true,
- editCount: 1,
- };
-
- const result = await multiEditTool.run(args);
-
- expect(result).toBe(
- `Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`,
- );
- });
-
it("should throw error if file write fails", async () => {
vi.mocked(fs.writeFileSync).mockImplementation(() => {
throw new Error("Write failed");
@@ -381,13 +189,12 @@ describe("multiEditTool", () => {
file_path: testFilePath,
newContent: "new content",
originalContent: originalContent,
- isCreatingNewFile: false,
editCount: 1,
};
- await expect(multiEditTool.run(args)).rejects.toThrow(
- `Error: failed to edit ${testFilePath}: Write failed`,
- );
+ const error = await multiEditTool.run(args).catch((e) => e);
+ expect(error).toBeInstanceOf(ContinueError);
+ expect(error.reason).toBe(ContinueErrorReason.FileWriteError);
});
});
@@ -473,34 +280,6 @@ describe("multiEditTool", () => {
expect(result.args.file_path).toBe(absolutePath);
});
-
- it("should handle relative path for new file creation", async () => {
- const relativePath = "new-file.txt";
- const absolutePath = path.resolve(process.cwd(), relativePath);
-
- vi.mocked(fs.existsSync).mockImplementation((path) => {
- // Parent directory (cwd) exists, but file doesn't
- if (path === process.cwd()) return true;
- if (path === absolutePath) return false;
- return true;
- });
-
- const args = {
- file_path: relativePath,
- edits: [
- {
- old_string: "",
- new_string: "New file content",
- },
- ],
- };
-
- const result = await multiEditTool.preprocess!(args);
-
- expect(result.args.file_path).toBe(absolutePath);
- expect(result.args.newContent).toBe("New file content");
- expect(result.args.isCreatingNewFile).toBe(true);
- });
});
describe("markFileAsRead", () => {
@@ -518,7 +297,9 @@ describe("multiEditTool", () => {
};
const result = await multiEditTool.preprocess!(args);
- expect(result.args.newContent).toContain("Hi there");
+ expect(result.args.newContent).toBe(
+ "Hi there\nThis is a test file\nGoodbye world",
+ );
});
});
});
diff --git a/extensions/cli/src/tools/multiEdit.ts b/extensions/cli/src/tools/multiEdit.ts
index 2164c6742..270c77934 100644
--- a/extensions/cli/src/tools/multiEdit.ts
+++ b/extensions/cli/src/tools/multiEdit.ts
@@ -1,7 +1,8 @@
import * as fs from "fs";
-import * as path from "path";
-import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
+import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation.js";
+import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
+import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
@@ -9,8 +10,8 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
-import { editTool } from "./edit.js";
-import { readFilesSet, readFileTool } from "./readFile.js";
+import { validateAndResolveFilePath } from "./edit.js";
+import { readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@@ -25,123 +26,20 @@ export interface MultiEditArgs {
edits: EditOperation[];
}
-// Helper functions for multiEdit validation
-function validateMultiEditArgs(args: any): {
- original_path: string;
- resolved_path: string;
- edits: EditOperation[];
-} {
- const { file_path, edits } = args as MultiEditArgs;
-
- if (!file_path) {
- throw new Error("file_path is required");
- }
- if (!edits || !Array.isArray(edits) || edits.length === 0) {
- throw new Error(
- "edits array is required and must contain at least one edit",
- );
- }
-
- // Convert relative paths to absolute paths
- const absolutePath = path.isAbsolute(file_path)
- ? file_path
- : path.resolve(process.cwd(), file_path);
-
- const resolvedPath = fs.realpathSync(absolutePath);
-
- return { original_path: file_path, resolved_path: resolvedPath, edits };
-}
-
-function validateEdits(edits: EditOperation[]): void {
- for (let i = 0; i < edits.length; i++) {
- const edit = edits[i];
- if (!edit.old_string && edit.old_string !== "") {
- throw new Error(`Edit ${i + 1}: old_string is required`);
- }
- if (edit.new_string === undefined) {
- throw new Error(`Edit ${i + 1}: new_string is required`);
- }
- if (edit.old_string === edit.new_string) {
- throw new Error(
- `Edit ${i + 1}: old_string and new_string must be different`,
- );
- }
- }
-}
-
-function validateFileAccess(
- resolvedPath: string,
- isCreatingNewFile: boolean,
-): void {
- if (isCreatingNewFile) {
- // For new file creation, check if parent directory exists
- const parentDir = path.dirname(resolvedPath);
- if (parentDir && !fs.existsSync(parentDir)) {
- throw new Error(`Parent directory does not exist: ${parentDir}`);
- }
- } else {
- // For existing files, check if file has been read
- // Check with the original path first, then with absolute path
- if (!readFilesSet.has(resolvedPath)) {
- throw new Error(
- `You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`,
- );
- }
- if (!fs.existsSync(resolvedPath)) {
- throw new Error(`File ${resolvedPath} does not exist`);
- }
- }
-}
-
-function applyEdit(
- content: string,
- edit: EditOperation,
- editIndex: number,
- isFirstEditOfNewFile: boolean,
-): string {
- const { old_string, new_string, replace_all = false } = edit;
-
- // For new file creation, the first edit can have empty old_string
- if (isFirstEditOfNewFile && old_string === "") {
- return new_string;
- }
-
- // Check if old_string exists in current content
- if (!content.includes(old_string)) {
- throw new Error(
- `Edit ${editIndex + 1}: String not found in file: "${old_string}"`,
- );
- }
-
- if (replace_all) {
- // Replace all occurrences
- return content.split(old_string).join(new_string);
- } else {
- // Replace only the first occurrence, but check for uniqueness
- const occurrences = content.split(old_string).length - 1;
- if (occurrences > 1) {
- throw new Error(
- `Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
- );
- }
- return content.replace(old_string, new_string);
- }
-}
-
export const multiEditTool: Tool = {
name: "MultiEdit",
displayName: "MultiEdit",
readonly: false,
isBuiltIn: true,
- description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently.
-Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
+ description: `This is a tool for making multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
+This tool is ideal when you need to make multiple edits to the same file.
To make multiple edits to a file, provide the following:
-1. file_path: The absolute path to the file to modify (must be absolute, not relative)
+1. file_path: The absolute path to the file to modify. Relative paths can also be used (resolved against cwd) but absolute is preferred
2. edits: An array of edit operations to perform, where each edit contains:
- old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.
+ - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
- All edits are applied in sequence, in the order they are provided
@@ -157,79 +55,74 @@ CRITICAL REQUIREMENTS:
- Always use absolute file paths (starting with /)
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
-
-If you want to create a new file, use:
-- A new file path, including new directory if needed
-- First edit: empty old_string and the new file's contents as new_string
-- Subsequent edits: normal edit operations on the created content
-- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
+- Empty old_string can be used to insert content at the beginning of a file
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
-- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`,
+- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session
+- The tool will fail if the file does not exist - it cannot create new files
+- This tool cannot create new files - the file must already exist`,
parameters: {
- file_path: {
- type: "string",
- description: "The absolute path to the file to modify",
- required: true,
- },
- edits: {
- type: "array",
- description:
- "Array of edit operations to perform sequentially on the file",
- required: true,
- items: {
- type: "object",
+ type: "object",
+ required: ["file_path", "edits"],
+ properties: {
+ file_path: {
+ type: "string",
+ description:
+ "Absolute or relative path to the file to modify. Absolute preferred",
+ },
+ edits: {
+ type: "array",
+ description:
+ "Array of edit operations to perform sequentially on the file",
+ items: {
+ type: "object",
+ required: ["old_string", "new_string"],
+ properties: {
+ old_string: {
+ type: "string",
+ description:
+ "The text to replace (exact match including whitespace/indentation)",
+ },
+ new_string: {
+ type: "string",
+ description:
+ "The text to replace it with. MUST be different than old_string.",
+ },
+ replace_all: {
+ type: "boolean",
+ description:
+ "Replace all occurrences of old_string (default false) in the file",
+ },
+ },
+ },
},
},
},
preprocess: async (args) => {
- // Validate and extract arguments
- const { resolved_path, edits } = validateMultiEditArgs(args);
+ const { resolvedPath } = validateAndResolveFilePath(args);
- throwIfFileIsSecurityConcern(resolved_path);
+ const { edits } = validateMultiEdit(args);
- // Validate each edit operation
- validateEdits(edits);
-
- // Check if this is creating a new file (first edit has empty old_string)
- const isCreatingNewFile = edits[0].old_string === "";
-
- // Validate file access
- validateFileAccess(resolved_path, isCreatingNewFile);
-
- // Read current file content (or start with empty for new files)
- let currentContent = "";
- if (!isCreatingNewFile) {
- currentContent = fs.readFileSync(resolved_path, "utf-8");
- }
-
- const originalContent = currentContent;
- let newContent = currentContent;
-
- // Apply all edits sequentially
- for (let i = 0; i < edits.length; i++) {
- const isFirstEditOfNewFile = i === 0 && isCreatingNewFile;
- newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile);
- }
+ const currentContent = fs.readFileSync(resolvedPath, "utf-8");
+ const newContent = executeMultiFindAndReplace(currentContent, edits);
// Generate diff for preview
- const diff = generateDiff(originalContent, newContent, resolved_path);
+ const diff = generateDiff(currentContent, newContent, resolvedPath);
return {
args: {
- file_path: resolved_path,
+ file_path: resolvedPath,
newContent,
- originalContent,
- isCreatingNewFile,
+ originalContent: currentContent,
editCount: edits.length,
},
preview: [
{
type: "text",
- content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`,
+ content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`,
},
{
type: "diff",
@@ -242,7 +135,6 @@ WARNINGS:
file_path: string;
newContent: string;
originalContent: string;
- isCreatingNewFile: boolean;
editCount: number;
}) => {
try {
@@ -273,10 +165,13 @@ WARNINGS:
args.file_path,
);
- const action = args.isCreatingNewFile ? "created" : "edited";
- return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
+ return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
} catch (error) {
- throw new Error(
+ if (error instanceof ContinueError) {
+ throw error;
+ }
+ throw new ContinueError(
+ ContinueErrorReason.FileWriteError,
`Error: failed to edit ${args.file_path}: ${
error instanceof Error ? error.message : String(error)
}`,
diff --git a/extensions/cli/src/tools/preprocess.test.ts b/extensions/cli/src/tools/preprocess.test.ts
index 787b8d5ef..eb38b91d4 100644
--- a/extensions/cli/src/tools/preprocess.test.ts
+++ b/extensions/cli/src/tools/preprocess.test.ts
@@ -1,7 +1,7 @@
import * as fs from "fs";
import * as diff from "diff";
-import { describe, it, expect, beforeEach, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
// Mock fs module
vi.mock("fs", async () => {
@@ -30,7 +30,6 @@ import { fetchTool } from "./fetch.js";
import { listFilesTool } from "./listFiles.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
-import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js";
import { searchCodeTool } from "./searchCode.js";
import { viewDiffTool } from "./viewDiff.js";
import { writeFileTool } from "./writeFile.js";
@@ -346,123 +345,4 @@ describe.skip("Tool preprocess functions", () => {
});
});
});
-
- describe("searchAndReplaceInFileTool.preprocess", () => {
- it("should process simple search and replace", async () => {
- // Setup mocks
- mockExistsSync.mockReturnValue(true);
- mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
-
- const args = {
- filepath: "path/to/file.txt",
- diffs: [
- `------- SEARCH
-old line 2
-=======
-new line 2
-+++++++ REPLACE`,
- ],
- };
-
- const result = await searchAndReplaceInFileTool.preprocess!(args);
-
- expect(mockExistsSync).toHaveBeenCalled();
- expect(mockReadFileSync).toHaveBeenCalled();
- expect(mockCreateTwoFilesPatch).toHaveBeenCalled();
-
- expect(result.args).toEqual({
- filepath: expect.any(String),
- newContent: "old line 1\nnew line 2\nold line 3",
- oldContent: "old line 1\nold line 2\nold line 3",
- });
-
- expect(result.preview).toEqual([
- {
- type: "text",
- content: "Will make the following changes:",
- },
- {
- type: "diff",
- content: "mock diff content",
- },
- ]);
- });
-
- it("should throw error when file doesn't exist", async () => {
- mockExistsSync.mockReturnValue(false);
-
- const args = {
- filepath: "/nonexistent/file.txt",
- diffs: ["some diff"],
- };
-
- await expect(
- searchAndReplaceInFileTool.preprocess!(args),
- ).rejects.toThrowError(/file .* does not exist/);
- });
-
- it("should throw error when no search/replace blocks found", async () => {
- mockExistsSync.mockReturnValue(true);
- mockReadFileSync.mockReturnValue("file content");
-
- const args = {
- filepath: "path/to/file.txt",
- diffs: ["invalid diff format"],
- };
-
- await expect(
- searchAndReplaceInFileTool.preprocess!(args),
- ).rejects.toThrowError(
- "No complete search/replace blocks found in any diffs",
- );
- });
-
- it("should throw error when search content not found", async () => {
- mockExistsSync.mockReturnValue(true);
- mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
-
- const args = {
- filepath: "path/to/file.txt",
- diffs: [
- `------- SEARCH
-nonexistent content
-=======
-replacement
-+++++++ REPLACE`,
- ],
- };
-
- await expect(
- searchAndReplaceInFileTool.preprocess!(args),
- ).rejects.toThrowError(/Search content not found in block 1:/);
- });
-
- it("should process multiple search/replace blocks", async () => {
- mockExistsSync.mockReturnValue(true);
- mockReadFileSync.mockReturnValue("line 1\nline 2\nline 3\nline 4");
-
- const args = {
- filepath: "path/to/file.txt",
- diffs: [
- `------- SEARCH
-line 1
-=======
-modified line 1
-+++++++ REPLACE
-
-------- SEARCH
-line 3
-=======
-modified line 3
-+++++++ REPLACE`,
- ],
- };
-
- const result = await searchAndReplaceInFileTool.preprocess!(args);
-
- expect(result.args.newContent).toBe(
- "modified line 1\nline 2\nmodified line 3\nline 4",
- );
- });
- });
});
diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts
index 9f270ae30..e62413e46 100644
--- a/extensions/cli/src/tools/readFile.ts
+++ b/extensions/cli/src/tools/readFile.ts
@@ -16,10 +16,13 @@ export const readFileTool: Tool = {
displayName: "Read",
description: "Read the contents of a file at the specified path",
parameters: {
- filepath: {
- type: "string",
- description: "The path to the file to read",
- required: true,
+ type: "object",
+ required: ["filepath"],
+ properties: {
+ filepath: {
+ type: "string",
+ description: "The path to the file to read",
+ },
},
},
readonly: true,
diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts
index 726c86501..00204d55b 100644
--- a/extensions/cli/src/tools/runTerminalCommand.ts
+++ b/extensions/cli/src/tools/runTerminalCommand.ts
@@ -36,10 +36,13 @@ export const runTerminalCommandTool: Tool = {
Commands are automatically executed from the current working directory (${process.cwd()}), so there's no need to change directories with 'cd' commands.
`,
parameters: {
- command: {
- type: "string",
- description: "The command to execute in the terminal.",
- required: true,
+ type: "object",
+ required: ["command"],
+ properties: {
+ command: {
+ type: "string",
+ description: "The command to execute in the terminal.",
+ },
},
},
readonly: false,
diff --git a/extensions/cli/src/tools/searchAndReplace/index.ts b/extensions/cli/src/tools/searchAndReplace/index.ts
deleted file mode 100644
index ddcffc7a7..000000000
--- a/extensions/cli/src/tools/searchAndReplace/index.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import * as fs from "fs";
-
-import { telemetryService } from "../../telemetry/telemetryService.js";
-import {
- calculateLinesOfCodeDiff,
- getLanguageFromFilePath,
-} from "../../telemetry/utils.js";
-import { Tool } from "../types.js";
-import { generateDiff } from "../writeFile.js";
-
-import { findSearchMatch } from "./findSearchMatch.js";
-import { parseSearchAndReplaceArgs } from "./parseArgs.js";
-import { parseAllSearchReplaceBlocks } from "./parseBlock.js";
-
-export interface SearchAndReplaceInFileArgs {
- filepath: string;
- diffs: string[];
-}
-
-// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
-export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
- "Note this tool CANNOT be called in parallel.";
-
-/**
- * This tool is in an experimental state.
- * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
- */
-export const searchAndReplaceInFileTool: Tool = {
- name: "Edit",
- displayName: "Edit",
- readonly: false,
- isBuiltIn: true,
- description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
- parameters: {
- filepath: {
- type: "string",
- description: "The path to the file to edit",
- required: true,
- },
- diffs: {
- type: "array",
- items: {
- type: "string",
- },
- description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
-\`\`\`
-------- SEARCH
-[exact content to find]
-=======
-[new content to replace with]
-+++++++ REPLACE
-\`\`\`
-
-Critical rules:
-1. SEARCH content must match the associated file section to find EXACTLY:
- * Match character-for-character including whitespace, indentation, line endings
- * Include all comments, docstrings, etc.
-2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
- * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
- * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
- * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
-3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
-4. Keep SEARCH/REPLACE blocks concise:
- * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
- * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
- * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
- * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
-5. Splitting up tool calls:
- * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
- * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
- * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
-6. Special operations:
- * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
- * To delete code: Use empty REPLACE section
-
-Usage:
-\`\`\`
-------- SEARCH
-[exact content to find]
-=======
-[new content to replace with]
-+++++++ REPLACE
-
-------- SEARCH
-[exact content to find]
-=======
-[new content to replace with]
-+++++++ REPLACE
- \`\`\`
-
-Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
- required: true,
- },
- },
- preprocess: async (args) => {
- // Get and validate args
- const { filepath, diffs } = parseSearchAndReplaceArgs(args);
-
- // Get current file contents
- if (!fs.existsSync(filepath)) {
- throw new Error(`file ${filepath} does not exist`);
- }
- const oldContent = fs.readFileSync(filepath, "utf-8");
- let newContent = oldContent;
-
- // Parse blocks
- const blocks = diffs.map(parseAllSearchReplaceBlocks).flat();
- if (blocks.length === 0) {
- throw new Error("No complete search/replace blocks found in any diffs");
- }
-
- // Apply all replacements sequentially to build the final content
- for (let i = 0; i < blocks.length; i++) {
- const block = blocks[i];
- const { searchContent, replaceContent } = block;
-
- if (typeof searchContent === "undefined") {
- throw new Error(`No search content defined for block ${i + 1}`);
- }
- if (typeof replaceContent === "undefined") {
- throw new Error(`No replace content defined for block ${i + 1}`);
- }
-
- const match = findSearchMatch(newContent, searchContent);
-
- if (!match) {
- throw new Error(
- `Search content not found in block ${i + 1}:\n${searchContent}`,
- );
- }
-
- newContent =
- newContent.substring(0, match.startIndex) +
- replaceContent +
- newContent.substring(match.endIndex);
- }
-
- const diff = generateDiff(oldContent, newContent, filepath);
-
- return {
- args: {
- filepath,
- newContent,
- oldContent, // Just for telemetry later
- },
- preview: [
- {
- type: "text",
- content: "Will make the following changes:",
- },
- {
- type: "diff",
- content: diff,
- },
- ],
- };
- },
- run: async (args) => {
- try {
- fs.writeFileSync(args.filepath, args.newContent, "utf-8");
-
- // Get lines for telemetry
- const { added, removed } = calculateLinesOfCodeDiff(
- args.oldContent,
- args.newContent,
- );
- const language = getLanguageFromFilePath(args.filepath);
-
- if (added > 0) {
- telemetryService.recordLinesOfCodeModified("added", added, language);
- }
- if (removed > 0) {
- telemetryService.recordLinesOfCodeModified(
- "removed",
- removed,
- language,
- );
- }
-
- // Record file operation
- return `Successfully edited ${args.filepath}`;
- } catch (error) {
- throw new Error(
- `Error: failed to edit ${args.filepath}:\n ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
- }
- },
-};
diff --git a/extensions/cli/src/tools/searchAndReplace/parseArgs.ts b/extensions/cli/src/tools/searchAndReplace/parseArgs.ts
deleted file mode 100644
index 7fed362bd..000000000
--- a/extensions/cli/src/tools/searchAndReplace/parseArgs.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import * as path from "path";
-
-export function parseSearchAndReplaceArgs(args: any): {
- filepath: string;
- diffs: string[];
-} {
- const { filepath, diffs: diffsArg } = args;
-
- if (!filepath || !diffsArg) {
- throw new Error("filepath and diffs args are required");
- }
-
- if (typeof filepath !== "string") {
- throw new Error("filepath must be a string");
- }
-
- const diffs: string[] = [];
- if (!Array.isArray(diffsArg)) {
- throw new Error("diffs must be an array of string search/replace blocks");
- }
- diffsArg.forEach((diff, i) => {
- if (typeof diff !== "string") {
- throw new Error(`Diff at ${i + 1} is not a string`);
- }
- diffs.push(diff);
- });
-
- const fixedPath = filepath.replace(/\/|\\/g, path.sep);
-
- return {
- filepath: fixedPath,
- diffs,
- };
-}
diff --git a/extensions/cli/src/tools/searchAndReplace/parseBlock.ts b/extensions/cli/src/tools/searchAndReplace/parseBlock.ts
deleted file mode 100644
index 64fa901a2..000000000
--- a/extensions/cli/src/tools/searchAndReplace/parseBlock.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-// Search and replace block markers using flexible regex patterns
-const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
-const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
-const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
-
-export interface SearchReplaceBlockResult {
- /** Whether a complete search/replace block has been parsed */
- isComplete: boolean;
- /** The content to search for in the file */
- searchContent?: string;
- /** The content to replace the search content with */
- replaceContent?: string;
- /** Error message if parsing failed */
- error?: string;
-}
-
-/**
- * Parses a search and replace block from content.
- *
- * Expected format:
- * ------- SEARCH
- * [content to find]
- * =======
- * [content to replace with]
- * +++++++ REPLACE
- *
- * @param content - The content to parse
- * @returns ParseResult with completion status and extracted content
- */
-export function parseSearchReplaceBlock(
- content: string,
-): SearchReplaceBlockResult {
- const lines = content.split("\n");
-
- let currentSearchContent = "";
- let currentReplaceContent = "";
- let inSearch = false;
- let inReplace = false;
-
- for (const line of lines) {
- if (SEARCH_BLOCK_START_REGEX.test(line)) {
- inSearch = true;
- inReplace = false;
- currentSearchContent = "";
- currentReplaceContent = "";
- continue;
- }
-
- if (SEARCH_BLOCK_END_REGEX.test(line)) {
- if (!inSearch) {
- return {
- isComplete: false,
- error: "Found search block end marker without matching start marker",
- };
- }
- inSearch = false;
- inReplace = true;
- continue;
- }
-
- if (REPLACE_BLOCK_END_REGEX.test(line)) {
- if (!inReplace) {
- return {
- isComplete: false,
- error:
- "Found replace block end marker without matching replace start marker",
- };
- }
-
- // Complete block found
- return {
- isComplete: true,
- searchContent: currentSearchContent.trim(),
- replaceContent: currentReplaceContent.trim(),
- };
- }
-
- // Accumulate content
- if (inSearch) {
- currentSearchContent += line + "\n";
- } else if (inReplace) {
- currentReplaceContent += line + "\n";
- }
- }
-
- // Block is not yet complete
- return {
- isComplete: false,
- searchContent: currentSearchContent.trim(),
- replaceContent: currentReplaceContent.trim(),
- };
-}
-
-/**
- * Parses all complete search and replace blocks from content.
- *
- * @param content - The content containing multiple search/replace blocks
- * @returns Array of complete search/replace blocks found
- * @throws Error if any malformed blocks are encountered
- */
-export function parseAllSearchReplaceBlocks(
- content: string,
-): SearchReplaceBlockResult[] {
- const blocks: SearchReplaceBlockResult[] = [];
- const lines = content.split("\n");
-
- let currentBlockLines: string[] = [];
- let inBlock = false;
-
- for (const line of lines) {
- if (SEARCH_BLOCK_START_REGEX.test(line)) {
- // Start of new block
- if (inBlock && currentBlockLines.length > 0) {
- // Process previous incomplete block if any
- const blockContent = currentBlockLines.join("\n");
- const result = parseSearchReplaceBlock(blockContent);
- if (result.isComplete) {
- blocks.push(result);
- } else if (result.error) {
- // Fail fast on any parsing error
- throw new Error(result.error);
- }
- // If incomplete but no error, it's just a partial block - continue processing
- }
- currentBlockLines = [line];
- inBlock = true;
- } else if (inBlock) {
- currentBlockLines.push(line);
-
- // Check if this line completes the current block
- if (REPLACE_BLOCK_END_REGEX.test(line)) {
- const blockContent = currentBlockLines.join("\n");
- const result = parseSearchReplaceBlock(blockContent);
- if (result.isComplete) {
- blocks.push(result);
- } else if (result.error) {
- // Fail fast on any parsing error
- throw new Error(result.error);
- }
- currentBlockLines = [];
- inBlock = false;
- }
- }
- }
-
- return blocks;
-}
diff --git a/extensions/cli/src/tools/searchCode.ts b/extensions/cli/src/tools/searchCode.ts
index 3eefe6434..53e0f7a30 100644
--- a/extensions/cli/src/tools/searchCode.ts
+++ b/extensions/cli/src/tools/searchCode.ts
@@ -14,20 +14,21 @@ export const searchCodeTool: Tool = {
displayName: "Search",
description: "Search the codebase using ripgrep (rg) for a specific pattern",
parameters: {
- pattern: {
- type: "string",
- description: "The search pattern to look for",
- required: true,
- },
- path: {
- type: "string",
- description: "The path to search in (defaults to current directory)",
- required: false,
- },
- file_pattern: {
- type: "string",
- description: "Optional file pattern to filter results (e.g., '*.ts')",
- required: false,
+ type: "object",
+ required: ["pattern"],
+ properties: {
+ pattern: {
+ type: "string",
+ description: "The search pattern to look for",
+ },
+ path: {
+ type: "string",
+ description: "The path to search in (defaults to current directory)",
+ },
+ file_pattern: {
+ type: "string",
+ description: "Optional file pattern to filter results (e.g., '*.ts')",
+ },
},
},
readonly: true,
diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts
index 04c164ad4..5adb45a92 100644
--- a/extensions/cli/src/tools/types.ts
+++ b/extensions/cli/src/tools/types.ts
@@ -1,16 +1,23 @@
import type { ToolPolicy } from "@continuedev/terminal-security";
-export type ToolParameters = Record<
- string,
- {
+// JSON Schema compatible parameter definition
+export interface ParameterSchema {
+ type: string;
+ description: string;
+ required?: string[];
+ properties?: Record;
+ items?: {
type: string;
- description: string;
- required: boolean;
- items?: {
- type: string;
- };
- }
->;
+ properties?: Record;
+ required?: string[];
+ };
+}
+
+export interface ToolParametersSchema {
+ type: "object";
+ required?: string[];
+ properties: Record;
+}
export interface ToolCallPreview {
type: "text" | "diff" | "checklist";
@@ -28,7 +35,7 @@ export interface Tool {
name: string;
displayName: string;
description: string;
- parameters: ToolParameters;
+ parameters: ToolParametersSchema;
preprocess?: (args: any) => Promise;
run: (args: any) => Promise;
readonly?: boolean; // Indicates if the tool is readonly
diff --git a/extensions/cli/src/tools/viewDiff.ts b/extensions/cli/src/tools/viewDiff.ts
index f8c9d2ff3..8b9f12d1d 100644
--- a/extensions/cli/src/tools/viewDiff.ts
+++ b/extensions/cli/src/tools/viewDiff.ts
@@ -11,11 +11,13 @@ export const viewDiffTool: Tool = {
displayName: "Diff",
description: "View all uncommitted changes in the git repository",
parameters: {
- path: {
- type: "string",
- description:
- "The path to the git repository (defaults to current directory)",
- required: false,
+ type: "object",
+ properties: {
+ path: {
+ type: "string",
+ description:
+ "The path to the git repository (defaults to current directory)",
+ },
},
},
readonly: true,
diff --git a/extensions/cli/src/tools/writeChecklist.test.ts b/extensions/cli/src/tools/writeChecklist.test.ts
index 5040acfd0..f7638442f 100644
--- a/extensions/cli/src/tools/writeChecklist.test.ts
+++ b/extensions/cli/src/tools/writeChecklist.test.ts
@@ -16,7 +16,8 @@ describe("writeChecklistTool", () => {
expect(writeChecklistTool.displayName).toBe("Checklist");
expect(writeChecklistTool.readonly).toBe(false);
expect(writeChecklistTool.isBuiltIn).toBe(true);
- expect(writeChecklistTool.parameters.checklist.required).toBe(true);
- expect(writeChecklistTool.parameters.checklist.type).toBe("string");
+ expect(writeChecklistTool.parameters.required?.includes("checklist")).toBe(
+ true,
+ );
});
});
diff --git a/extensions/cli/src/tools/writeChecklist.ts b/extensions/cli/src/tools/writeChecklist.ts
index 264fbfcd8..d2ca3b2c8 100644
--- a/extensions/cli/src/tools/writeChecklist.ts
+++ b/extensions/cli/src/tools/writeChecklist.ts
@@ -8,11 +8,14 @@ export const writeChecklistTool: Tool = {
readonly: false,
isBuiltIn: true,
parameters: {
- checklist: {
- type: "string",
- description:
- "The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes. Try to keep the list short, and make each item specific and actionable.",
- required: true,
+ type: "object",
+ required: ["checklist"],
+ properties: {
+ checklist: {
+ type: "string",
+ description:
+ "The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes. Try to keep the list short, and make each item specific and actionable.",
+ },
},
},
preprocess: async (args: { checklist: string }) => {
diff --git a/extensions/cli/src/tools/writeFile.ts b/extensions/cli/src/tools/writeFile.ts
index f1404386f..55ef4f44c 100644
--- a/extensions/cli/src/tools/writeFile.ts
+++ b/extensions/cli/src/tools/writeFile.ts
@@ -32,15 +32,17 @@ export const writeFileTool: Tool = {
displayName: "Write",
description: "Write content to a file at the specified path",
parameters: {
- filepath: {
- type: "string",
- description: "The path to the file to write",
- required: true,
- },
- content: {
- type: "string",
- description: "The content to write to the file",
- required: true,
+ type: "object",
+ required: ["filepath", "content"],
+ properties: {
+ filepath: {
+ type: "string",
+ description: "The path to the file to write",
+ },
+ content: {
+ type: "string",
+ description: "The content to write to the file",
+ },
},
},
readonly: false,
diff --git a/extensions/cli/src/ui/ColoredDiff.tsx b/extensions/cli/src/ui/ColoredDiff.tsx
index a0c7b8d98..f1ca6c321 100644
--- a/extensions/cli/src/ui/ColoredDiff.tsx
+++ b/extensions/cli/src/ui/ColoredDiff.tsx
@@ -8,7 +8,7 @@ const COLORS = {
DELETION_BG: "#712f37",
ADDITION_HIGHLIGHT: "#59a467",
DELETION_HIGHLIGHT: "#a75e6d",
- LINE_NUMBER: "gray",
+ LINE_NUMBER: "dim",
} as const;
interface DiffLine {
@@ -179,7 +179,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({
const parsedLines = parseDiffWithLineNumbers(diffContent);
if (parsedLines.length === 0) {
- return No changes detected.;
+ return No changes detected.;
}
const displayableLines = parsedLines.filter(
@@ -269,7 +269,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({
}
})}
{isTruncated && (
-
+
... ({displayableLines.length - 16} more lines)
)}
diff --git a/extensions/cli/src/ui/DiffViewer.tsx b/extensions/cli/src/ui/DiffViewer.tsx
new file mode 100644
index 000000000..0703297d1
--- /dev/null
+++ b/extensions/cli/src/ui/DiffViewer.tsx
@@ -0,0 +1,65 @@
+import { Box, Text, useInput } from "ink";
+import React, { useEffect } from "react";
+
+import { ColoredDiff } from "./ColoredDiff.js";
+
+interface DiffViewerProps {
+ diffContent: string;
+ onClose: () => void;
+}
+
+/**
+ * Full-screen diff viewer overlay
+ * Shows diff content with syntax highlighting and allows closing with ESC
+ */
+export const DiffViewer: React.FC = ({
+ diffContent,
+ onClose,
+}) => {
+ // Handle ESC key to close the diff viewer
+ useInput((input, key) => {
+ if (key.escape) {
+ onClose();
+ }
+ });
+
+ // Auto-focus when component mounts
+ useEffect(() => {
+ // Component is already focused by default in Ink
+ }, []);
+
+ return (
+
+ {/* Header */}
+
+
+ Git Diff (Press ESC to close)
+
+
+
+ {/* Diff content - scrollable */}
+
+ {diffContent.trim() ? (
+
+ ) : (
+
+ No changes to display
+
+ )}
+
+
+ {/* Footer */}
+
+
+ ESC to close
+
+
+
+ );
+};
diff --git a/extensions/cli/src/ui/FileSearchUI.tsx b/extensions/cli/src/ui/FileSearchUI.tsx
index 6c4d2c266..866c0af17 100644
--- a/extensions/cli/src/ui/FileSearchUI.tsx
+++ b/extensions/cli/src/ui/FileSearchUI.tsx
@@ -1,8 +1,12 @@
-import { Box, Text } from "ink";
+import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import { useServices } from "../hooks/useService.js";
-import { FileIndexServiceState } from "../services/FileIndexService.js";
+import {
+ FileIndexServiceState,
+ FileItem,
+} from "../services/FileIndexService.js";
+import { services } from "../services/index.js";
interface FileSearchUIProps {
filter: string;
@@ -11,10 +15,45 @@ interface FileSearchUIProps {
onFilesUpdated?: (files: FileItem[]) => void;
}
-interface FileItem {
- path: string;
- displayName: string;
-}
+// Highlighting component for matched characters
+const HighlightedText: React.FC<{ text: string; positions?: Set }> = ({
+ text,
+ positions,
+}) => {
+ if (!positions || positions.size === 0) {
+ return <>{text}>;
+ }
+
+ const chars = text.split("");
+ const elements: React.ReactNode[] = [];
+
+ chars.forEach((char, index) => {
+ if (positions.has(index)) {
+ elements.push(
+
+ {char}
+ ,
+ );
+ } else {
+ elements.push(char);
+ }
+ });
+
+ return <>{elements}>;
+};
+
+// Reusable container for consistent layout
+const FileSearchContainer: React.FC<{ children: React.ReactNode }> = ({
+ children,
+}) => (
+
+ {children}
+
+);
+
+// Keyboard navigation shortcuts help text
+const KEYBOARD_SHORTCUTS =
+ "↑/↓ to navigate, Enter to select, Tab to complete, Ctrl+r to refresh list";
const FileSearchUI: React.FC = ({
filter,
@@ -23,89 +62,97 @@ const FileSearchUI: React.FC = ({
}) => {
const [files, setFiles] = useState([]);
- // Get file index service
- const { services } = useServices<{
+ // Get file index service state for reactive updates
+ const { services: serviceStates } = useServices<{
fileIndex: FileIndexServiceState;
}>(["fileIndex"]);
- const fileIndexService = services.fileIndex;
+ const fileIndexServiceState = serviceStates.fileIndex;
useEffect(() => {
- if (!fileIndexService) {
+ if (!fileIndexServiceState) {
return;
}
- // Get filtered files from the service
- const filteredFiles = fileIndexService.files
- .filter((file) => {
- if (filter.length === 0) {
- return true;
+ // Use the FileIndexService's filterFiles method which includes fzf fuzzy matching
+ const fetchFilteredFiles = async () => {
+ try {
+ // console.log(`FileSearchUI: Filtering files with "${filter}", total files in state:`, fileIndexServiceState?.files?.length);
+ const filteredFiles = await services.fileIndex.filterFiles(filter, 10);
+ // console.log(`FileSearchUI: Filtered to ${filteredFiles.length} files`);
+ setFiles(filteredFiles);
+
+ if (onFilesUpdated) {
+ onFilesUpdated(filteredFiles);
}
- const lowerFilter = filter.toLowerCase();
- return (
- file.displayName.toLowerCase().includes(lowerFilter) ||
- file.path.toLowerCase().includes(lowerFilter)
- );
- })
- .sort((a, b) => {
- if (filter.length === 0) {
- // Sort alphabetically when no filter
- const aFileName = a.path.split("/").pop() || a.path;
- const bFileName = b.path.split("/").pop() || b.path;
- return aFileName.localeCompare(bFileName);
+ } catch (error) {
+ // Suppress expected "search cancelled" errors from AsyncFzf when typing fast
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+ if (!errorMessage.includes("search cancelled")) {
+ console.error("Error filtering files:", error);
}
+ setFiles([]);
+ }
+ };
- const lowerFilter = filter.toLowerCase();
- const aFileName = a.path.split("/").pop() || a.path;
- const bFileName = b.path.split("/").pop() || b.path;
+ fetchFilteredFiles();
+ }, [fileIndexServiceState?.files, filter, onFilesUpdated]);
- // Prioritize exact matches in file name
- const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
- const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
-
- if (aNameMatch && !bNameMatch) return -1;
- if (!aNameMatch && bNameMatch) return 1;
-
- // Then prioritize files that start with the filter
- const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
- const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
-
- if (aStartsWith && !bStartsWith) return -1;
- if (!aStartsWith && bStartsWith) return 1;
-
- // Finally, sort by file name
- return aFileName.localeCompare(bFileName);
- })
- .slice(0, 10);
-
- setFiles(filteredFiles);
-
- if (onFilesUpdated) {
- onFilesUpdated(filteredFiles);
+ // Handle Ctrl+R to refresh file index
+ useInput((input, key) => {
+ if (key.ctrl && input === "r") {
+ services.fileIndex.refreshIndex(true); // Bypass timeout for manual refresh
}
- }, [fileIndexService?.files, filter, onFilesUpdated]);
+ });
- if (fileIndexService?.isIndexing) {
+ if (fileIndexServiceState?.error) {
+ // Special handling for directory too large error
+ if (fileIndexServiceState.error === "directory-too-large") {
+ return (
+
+
+ Ctrl+r to refresh list (this may take several seconds)
+
+
+ );
+ }
+
+ // Other errors
return (
-
- Indexing files...
-
+
+
+ Error indexing files: {fileIndexServiceState.error}
+
+
);
}
- if (fileIndexService?.error) {
- return (
-
- Error indexing files: {fileIndexService.error}
-
- );
- }
+ if (files.length === 0 && !fileIndexServiceState?.isIndexing) {
+ // Only show "No matching files found" if:
+ // 1. There are files in the index (so it's not a system issue)
+ // 2. There's actually a search filter (not just "@")
+ if (
+ fileIndexServiceState?.files &&
+ fileIndexServiceState.files.length > 0 &&
+ filter.length > 0
+ ) {
+ return (
+
+
+ No matching files found
+
+
+ );
+ }
- if (files.length === 0) {
+ // Show keyboard navigation hints
return (
-
- No matching files found
-
+
+
+ {KEYBOARD_SHORTCUTS}
+
+
);
}
@@ -118,7 +165,13 @@ const FileSearchUI: React.FC = ({
{" "}
- @{file.displayName}
+
+ @
+
+
);
@@ -126,7 +179,7 @@ const FileSearchUI: React.FC = ({
- ↑/↓ to navigate, Enter to select, Tab to complete
+ {KEYBOARD_SHORTCUTS}
diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx
index 3adfc6a5a..e26448479 100644
--- a/extensions/cli/src/ui/IntroMessage.tsx
+++ b/extensions/cli/src/ui/IntroMessage.tsx
@@ -4,16 +4,11 @@ import React, { useMemo } from "react";
import { getDisplayableAsciiArt } from "../asciiArt.js";
import { MCPService } from "../services/MCPService.js";
-import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
import { isModelCapable } from "../utils/modelCapability.js";
import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
import { TipsDisplay, shouldShowTip } from "./TipsDisplay.js";
-// Export the warning message for testing
-export const HOME_DIRECTORY_WARNING =
- "Run cn in a project directory for the best experience (currently in home directory)";
-
interface IntroMessageProps {
config?: AssistantUnrolled;
model?: ModelConfig;
@@ -27,8 +22,6 @@ const extractRuleNames = (rules: any[] = []): string[] => {
);
};
-const userInHomeDirectory = isInHomeDirectory();
-
const IntroMessage: React.FC = ({
config,
model,
@@ -59,7 +52,7 @@ const IntroMessage: React.FC = ({
{mcpPrompts.map((prompt, index) => (
- /{prompt.name}:{" "}
- {prompt.description}
+ {prompt.description}
))}
@@ -120,7 +113,7 @@ const IntroMessage: React.FC = ({
) : (
- Model: Loading...
+ Model: Loading...
)}
@@ -139,14 +132,6 @@ const IntroMessage: React.FC = ({
{renderMcpPrompts()}
{renderRules()}
{renderMcpServers()}
-
- {/* Home directory warning */}
- {userInHomeDirectory && (
- <>
- {HOME_DIRECTORY_WARNING}
-
- >
- )}
);
};
diff --git a/extensions/cli/src/ui/LoadingText.tsx b/extensions/cli/src/ui/LoadingText.tsx
new file mode 100644
index 000000000..e7663ab76
--- /dev/null
+++ b/extensions/cli/src/ui/LoadingText.tsx
@@ -0,0 +1,33 @@
+import { Text } from "ink";
+import React, { useEffect, useState } from "react";
+
+interface LoadingTextProps {
+ text: string;
+ color?: string;
+ interval?: number;
+}
+
+export const LoadingText: React.FC = ({
+ text,
+ color = "dim",
+ interval = 300,
+}) => {
+ const [dotsCount, setDotsCount] = useState(1);
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setDotsCount((current) => (current % 3) + 1);
+ }, interval);
+
+ return () => clearInterval(timer);
+ }, [interval]);
+
+ const dots = ".".repeat(dotsCount);
+
+ return (
+
+ {text}
+ {dots}
+
+ );
+};
diff --git a/extensions/cli/src/ui/MarkdownRenderer.thinking.test.tsx b/extensions/cli/src/ui/MarkdownRenderer.thinking.test.tsx
new file mode 100644
index 000000000..b8af07bca
--- /dev/null
+++ b/extensions/cli/src/ui/MarkdownRenderer.thinking.test.tsx
@@ -0,0 +1,36 @@
+import { render } from "ink-testing-library";
+import React from "react";
+
+import { MarkdownRenderer } from "./MarkdownRenderer.js";
+
+describe("MarkdownRenderer - thinking tags", () => {
+ it("handles multiple thinking tags", () => {
+ const content =
+ "Text First thought middle Second thought end";
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("First thought");
+ expect(lastFrame()).toContain("Second thought");
+ });
+
+ it("handles thinking tags with multiline content", () => {
+ const content = `
+ This is a multiline
+ thinking block
+ `;
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("This is a multiline");
+ expect(lastFrame()).toContain("thinking block");
+ });
+
+ it("ignores thinking tags inside code blocks", () => {
+ const content = "```\nThis should not be processed\n```";
+ const { lastFrame } = render();
+
+ // The thinking tag should appear as literal text within the code block
+ expect(lastFrame()).toContain(
+ "This should not be processed",
+ );
+ });
+});
diff --git a/extensions/cli/src/ui/MarkdownRenderer.tsx b/extensions/cli/src/ui/MarkdownRenderer.tsx
index 12d4d17bc..8cc2d2223 100644
--- a/extensions/cli/src/ui/MarkdownRenderer.tsx
+++ b/extensions/cli/src/ui/MarkdownRenderer.tsx
@@ -2,10 +2,10 @@ import { Text } from "ink";
import React from "react";
import {
- highlightCode,
- detectLanguage,
- SyntaxHighlighterTheme,
defaultTheme,
+ detectLanguage,
+ highlightCode,
+ SyntaxHighlighterTheme,
} from "./SyntaxHighlighter.js";
interface MarkdownRendererProps {
@@ -28,6 +28,14 @@ const MarkdownRenderer: React.FC = React.memo(
return null; // This will be handled separately
},
},
+ {
+ regex: /([\s\S]*?)<\/think>/g,
+ render: (content, key) => (
+
+ {content.trim()}
+
+ ),
+ },
{
regex: /^(#{1,6})\s+(.+)$/gm,
render: (content, key) => (
@@ -225,6 +233,5 @@ const MarkdownRenderer: React.FC = React.memo(
MarkdownRenderer.displayName = "MarkdownRenderer";
-export { MarkdownRenderer };
+export { defaultTheme, MarkdownRenderer };
export type { SyntaxHighlighterTheme };
-export { defaultTheme };
diff --git a/extensions/cli/src/ui/SessionSelector.test.tsx b/extensions/cli/src/ui/SessionSelector.test.tsx
index 0844e27d4..6a7143bb7 100644
--- a/extensions/cli/src/ui/SessionSelector.test.tsx
+++ b/extensions/cli/src/ui/SessionSelector.test.tsx
@@ -1,9 +1,9 @@
-import { subDays, subMonths, subYears, startOfDay, addHours } from "date-fns";
+import { addHours, startOfDay, subDays, subMonths, subYears } from "date-fns";
import { render } from "ink-testing-library";
import React from "react";
-import { describe, expect, it, vi, beforeEach } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { SessionMetadata } from "../session.js";
+import type { BaseSessionMetadata } from "../session.js";
import { SessionSelector } from "./SessionSelector.js";
@@ -23,7 +23,7 @@ describe("SessionSelector", () => {
const thisYear = subMonths(new Date(today), 2).toISOString(); // 2 months ago (this year)
const lastYear = subYears(new Date(today), 1).toISOString(); // 1 year ago
- const sessions: SessionMetadata[] = [
+ const sessions: BaseSessionMetadata[] = [
{
sessionId: "session-1",
title: "Today's session",
@@ -93,7 +93,7 @@ describe("SessionSelector", () => {
});
it("handles sessions without first user message", () => {
- const sessions: SessionMetadata[] = [
+ const sessions: BaseSessionMetadata[] = [
{
sessionId: "session-1",
workspaceDirectory: "/test",
diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx
index 2cf4927a4..eb224fb88 100644
--- a/extensions/cli/src/ui/SessionSelector.tsx
+++ b/extensions/cli/src/ui/SessionSelector.tsx
@@ -2,13 +2,13 @@ import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns";
import { Box, Text, useInput } from "ink";
import React, { useMemo, useState } from "react";
-import { SessionMetadata } from "../session.js";
+import { ExtendedSessionMetadata } from "../session.js";
import { useTerminalSize } from "./hooks/useTerminalSize.js";
import { defaultBoxStyles } from "./styles.js";
interface SessionSelectorProps {
- sessions: SessionMetadata[];
+ sessions: ExtendedSessionMetadata[];
onSelect: (sessionId: string) => void;
onExit: () => void;
}
@@ -42,27 +42,49 @@ export function SessionSelector({
const [selectedIndex, setSelectedIndex] = useState(0);
const { rows: terminalHeight } = useTerminalSize();
- // Calculate how many sessions we can display based on terminal height
- const displaySessions = useMemo(() => {
- // Reserve 5 lines for header and instructions, each session takes 3 lines (2 content + 1 spacer)
- const availableHeight = Math.max(1, terminalHeight - 5);
+ // Calculate how many sessions we can display based on terminal height and scrolling
+ const { displaySessions, scrollOffset } = useMemo(() => {
+ // Account for:
+ // - Box border (top + bottom): 2 lines
+ // - Box padding (top + bottom): 2 lines
+ // - Header "Recent Sessions": 1 line
+ // - Instructions line: 1 line
+ // - Empty line after instructions: 1 line
+ // - Potential scroll indicators: up to 2 lines (1 above, 1 below)
+ // Total overhead: ~9 lines
+ const MAGIC_NUMBER = 9;
+ const availableHeight = Math.max(1, terminalHeight - MAGIC_NUMBER);
const maxDisplayableSessions = Math.floor(availableHeight / 3);
- return sessions.slice(0, maxDisplayableSessions);
- }, [sessions, terminalHeight]);
+ // If we can display all sessions, no need to scroll
+ if (sessions.length <= maxDisplayableSessions) {
+ return { displaySessions: sessions, scrollOffset: 0 };
+ }
+
+ // Calculate scroll offset to keep selected item visible
+ let scrollOffset = 0;
+ if (selectedIndex >= maxDisplayableSessions) {
+ scrollOffset = Math.min(
+ selectedIndex - maxDisplayableSessions + 1,
+ sessions.length - maxDisplayableSessions,
+ );
+ }
+
+ const displaySessions = sessions.slice(
+ scrollOffset,
+ scrollOffset + maxDisplayableSessions,
+ );
+ return { displaySessions, scrollOffset };
+ }, [sessions, terminalHeight, selectedIndex]);
useInput((input, key) => {
if (key.upArrow || input === "k") {
- setSelectedIndex((prev) =>
- prev > 0 ? prev - 1 : displaySessions.length - 1,
- );
+ setSelectedIndex((prev) => (prev > 0 ? prev - 1 : sessions.length - 1));
} else if (key.downArrow || input === "j") {
- setSelectedIndex((prev) =>
- prev < displaySessions.length - 1 ? prev + 1 : 0,
- );
+ setSelectedIndex((prev) => (prev < sessions.length - 1 ? prev + 1 : 0));
} else if (key.return) {
- if (displaySessions[selectedIndex]) {
- onSelect(displaySessions[selectedIndex].sessionId);
+ if (sessions[selectedIndex]) {
+ onSelect(sessions[selectedIndex].sessionId);
}
} else if (key.escape || (key.ctrl && input === "d")) {
onExit();
@@ -79,16 +101,28 @@ export function SessionSelector({
);
}
+ const hasMoreAbove = scrollOffset > 0;
+ const hasMoreBelow = scrollOffset + displaySessions.length < sessions.length;
+
return (
- Recent Sessions
+ Recent Sessions{" "}
+ {sessions.length > displaySessions.length &&
+ `(${selectedIndex + 1}/${sessions.length})`}
↑/↓ to navigate, Enter to select, Esc to exit
+ {hasMoreAbove && (
+
+ ⬆ {scrollOffset} more sessions above...
+
+ )}
+
{displaySessions.map((session, index) => {
- const isSelected = index === selectedIndex;
+ const globalIndex = index + scrollOffset;
+ const isSelected = globalIndex === selectedIndex;
const indicator = isSelected ? "➤ " : " ";
const color = isSelected ? "blue" : "white";
@@ -103,6 +137,7 @@ export function SessionSelector({
{formatTimestamp(new Date(session.dateCreated))}
+ {session.isRemote ? " (remote)" : " (local)"}
{index < displaySessions.length - 1 && (
@@ -111,6 +146,13 @@ export function SessionSelector({
);
})}
+
+ {hasMoreBelow && (
+
+ ⬇ {sessions.length - scrollOffset - displaySessions.length} more
+ sessions below...
+
+ )}
);
}
diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx
index a60ec85b4..e7714fbc7 100644
--- a/extensions/cli/src/ui/TUIChat.tsx
+++ b/extensions/cli/src/ui/TUIChat.tsx
@@ -14,9 +14,11 @@ import {
ConfigServiceState,
MCPServiceState,
ModelServiceState,
+ UpdateServiceState,
} from "../services/types.js";
import { logger } from "../util/logger.js";
+import { ActionStatus } from "./components/ActionStatus.js";
import { BottomStatusBar } from "./components/BottomStatusBar.js";
import { ResourceDebugBar } from "./components/ResourceDebugBar.js";
import { ScreenContent } from "./components/ScreenContent.js";
@@ -31,8 +33,6 @@ import {
useLoginHandlers,
useSelectors,
} from "./hooks/useTUIChatHooks.js";
-import { LoadingAnimation } from "./LoadingAnimation.js";
-import { Timer } from "./Timer.js";
interface TUIChatProps {
// Remote mode props
@@ -94,7 +94,8 @@ function useTUIChatServices(remoteUrl?: string) {
model: ModelServiceState;
mcp: MCPServiceState;
apiClient: ApiClientServiceState;
- }>(["auth", "config", "model", "mcp", "apiClient"]);
+ update: UpdateServiceState;
+ }>(["auth", "config", "model", "mcp", "apiClient", "update"]);
return { services, allServicesReady, isRemoteMode };
}
@@ -180,14 +181,41 @@ const TUIChat: React.FC = ({
setStaticRefreshTrigger,
);
+ // State for diff content overlay
+ const [diffContent, setDiffContent] = useState("");
+
+ // State for temporary status message
+ const [statusMessage, setStatusMessage] = useState("");
+
+ // Handler to show diff overlay
+ const handleShowDiff = useCallback(
+ (content: string) => {
+ setDiffContent(content);
+ navigateTo("diff");
+ },
+ [navigateTo],
+ );
+
+ // Handler to show temporary status message
+ const handleShowStatusMessage = useCallback((message: string) => {
+ setStatusMessage(message);
+ // Clear after 3 seconds
+ setTimeout(() => {
+ setStatusMessage("");
+ }, 3000);
+ }, []);
+
const {
chatHistory,
setChatHistory,
isWaitingForResponse,
responseStartTime,
+ isCompacting,
+ compactionStartTime,
inputMode,
activePermissionRequest,
wasInterrupted,
+ queuedMessages,
handleUserMessage,
handleInterrupt,
handleFileAttached,
@@ -205,6 +233,7 @@ const TUIChat: React.FC = ({
onShowConfigSelector: () => navigateTo("config"),
onShowModelSelector: () => navigateTo("model"),
onShowMCPSelector: () => navigateTo("mcp"),
+ onShowUpdateSelector: () => navigateTo("update"),
onShowSessionSelector: () => navigateTo("session"),
onLoginPrompt: handleLoginPrompt,
onReload: handleReload,
@@ -212,6 +241,8 @@ const TUIChat: React.FC = ({
// Remote mode configuration
isRemoteMode,
remoteUrl,
+ onShowDiff: handleShowDiff,
+ onShowStatusMessage: handleShowStatusMessage,
});
// Update ref after useChat returns
@@ -282,6 +313,7 @@ const TUIChat: React.FC = ({
model={services.model?.model || undefined}
mcpService={services.mcp?.mcpService || undefined}
chatHistory={chatHistory}
+ queuedMessages={queuedMessages}
renderMessage={renderMessage}
refreshTrigger={staticRefreshTrigger}
/>
@@ -290,16 +322,26 @@ const TUIChat: React.FC = ({
{/* Fixed bottom section */}
{/* Status */}
- {isWaitingForResponse && responseStartTime && (
-
-
-
- (
-
-
-
- • esc to interrupt )
-
+
+
+ {/* Compaction Status */}
+
+
+ {/* Temporary status message */}
+ {statusMessage && (
+
+ {statusMessage}
)}
@@ -318,6 +360,7 @@ const TUIChat: React.FC = ({
handleToolPermissionResponse={handleToolPermissionResponse}
handleUserMessage={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
+ isCompacting={isCompacting}
inputMode={inputMode}
handleInterrupt={handleInterrupt}
handleFileAttached={handleFileAttached}
@@ -325,6 +368,7 @@ const TUIChat: React.FC = ({
wasInterrupted={wasInterrupted}
isRemoteMode={isRemoteMode}
onImageInClipboardChange={setHasImageInClipboard}
+ diffContent={diffContent}
/>
{/* Resource debug bar - only in verbose mode */}
diff --git a/extensions/cli/src/ui/TextBuffer.test.ts b/extensions/cli/src/ui/TextBuffer.test.ts
index 27ae83f61..4d88015af 100644
--- a/extensions/cli/src/ui/TextBuffer.test.ts
+++ b/extensions/cli/src/ui/TextBuffer.test.ts
@@ -1,7 +1,7 @@
import {
- TextBuffer,
COLLAPSE_SIZE,
RAPID_INPUT_THRESHOLD,
+ TextBuffer,
} from "./TextBuffer.js";
describe("TextBuffer", () => {
@@ -313,231 +313,255 @@ describe("TextBuffer", () => {
});
});
- describe("paste collapse", () => {
- it("should not collapse short pasted text", () => {
- const shortText = "hello world";
- buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
+ describe("paste detection and collapse", () => {
+ describe("basic collapse behavior", () => {
+ it("should not collapse short content", () => {
+ const shortText = "hello world";
+ buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
+ expect(buffer.text).toBe("hello world");
+ });
- expect(buffer.text).toBe("hello world");
+ it("should collapse content exceeding threshold", () => {
+ const longText = "a".repeat(COLLAPSE_SIZE + 1);
+ buffer.handleInput(longText, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+ expect(buffer.text).toBe("[Paste #1]");
+ });
+
+ it("should count lines correctly in placeholders", () => {
+ const multiLineText =
+ "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
+ buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+ expect(buffer.text).toBe("[Paste #1, 4 lines]");
+ });
});
- it("should collapse long pasted text exceeding collapse threshold", () => {
- const longText = "a".repeat(COLLAPSE_SIZE + 1);
- buffer.handleInput(longText, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
+ describe("expansion and state management", () => {
+ it("should expand collapsed content on demand", () => {
+ const longText = "content " + "a".repeat(COLLAPSE_SIZE);
+ buffer.handleInput(longText, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+
+ expect(buffer.text).toBe("[Paste #1]");
+ buffer.expandAllPasteBlocks();
+ expect(buffer.text).toBe(longText);
+ });
+
+ it("should increment paste counter for multiple pastes", () => {
+ const text1 = "a".repeat(COLLAPSE_SIZE + 1);
+ const text2 = "b".repeat(COLLAPSE_SIZE + 1);
+
+ buffer.handleInput(text1, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+ buffer.insertText(" ");
+ buffer.handleInput(text2, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+
+ expect(buffer.text).toBe("[Paste #1] [Paste #2]");
+ });
+
+ it("should normalize line endings when expanding", () => {
+ const textWithMixedEndings =
+ "line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
+ buffer.handleInput(textWithMixedEndings, {
+ ctrl: false,
+ meta: false,
+ } as any);
+ buffer.flushPendingInput();
+
+ buffer.expandAllPasteBlocks();
+ const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
+ expect(buffer.text).toBe(expected);
+ });
+
+ it("should clear paste map after expansion", () => {
+ const longText = "a".repeat(COLLAPSE_SIZE + 1);
+ buffer.handleInput(longText, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+
+ buffer.expandAllPasteBlocks();
+ buffer.expandAllPasteBlocks(); // Second call should be no-op
+ expect(buffer.text).toBe(longText);
+ });
+ });
+
+ describe("rapid input detection (Terminal.app/Ghostty)", () => {
+ it("should detect large single input as rapid paste", () => {
+ const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
+ buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
+
+ expect(buffer.text).toBe(""); // Should be buffered
+ expect(buffer.isInRapidInputMode()).toBe(true);
+
+ buffer.flushPendingInput();
+ expect(buffer.text).toBe(rapidText); // < COLLAPSE_SIZE, so not collapsed
+ });
+
+ it("should combine multiple chunks into single paste", () => {
+ const chunk1 = "a".repeat(200);
+ const chunk2 = "b".repeat(700); // Combined > COLLAPSE_SIZE
+
+ buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
+ buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+
+ expect(buffer.text).toBe("[Paste #1]");
+ buffer.expandAllPasteBlocks();
+ expect(buffer.text).toBe(chunk1 + chunk2);
+ });
+
+ it("should detect 50+ char chunks as start of paste session", () => {
+ const smallChunk = "x".repeat(60); // >= 50, should trigger
+ const largeChunk = "y".repeat(800);
+
+ buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any);
+ expect(buffer.text).toBe("");
+
+ buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any);
+ buffer.flushPendingInput();
+
+ expect(buffer.text).toBe("[Paste #1]");
+ buffer.expandAllPasteBlocks();
+ expect(buffer.text).toBe(smallChunk + largeChunk);
+ });
+ });
+
+ describe("bracketed paste (iTerm2)", () => {
+ it("should handle bracketed paste sequences", () => {
+ const content = "function test() { return 'hello'; }" + "x".repeat(800);
+
+ buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
+ expect(buffer.isInPasteMode()).toBe(true);
+ expect(buffer.text).toBe("");
+
+ buffer.handleInput(content, { ctrl: false, meta: false } as any);
+ expect(buffer.text).toBe(""); // Nothing visible during paste
+
+ buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
+ expect(buffer.isInPasteMode()).toBe(false);
+ expect(buffer.text).toBe("[Paste #1]");
+
+ buffer.expandAllPasteBlocks();
+ expect(buffer.text).toBe(content);
+ });
+
+ it("should not collapse short bracketed content", () => {
+ const shortContent = "Hello world!";
+
+ buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
+ buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
+ buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
+
+ expect(buffer.text).toBe(shortContent);
+ });
+
+ it("should prioritize bracketed paste over rapid input", () => {
+ const largeContent = "x".repeat(1000);
+
+ buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
+ buffer.handleInput(largeContent, { ctrl: false, meta: false } as any);
+
+ expect(buffer.isInPasteMode()).toBe(true);
+ expect(buffer.isInRapidInputMode()).toBe(false);
+
+ buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
+ expect(buffer.text).toBe("[Paste #1]");
+ });
+ });
+ });
+
+ describe("timing behavior", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("should combine chunks within 200ms timing window", () => {
+ const chunk1 = "x".repeat(100);
+ const chunk2 = "y".repeat(800);
+
+ buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
+
+ vi.advanceTimersByTime(100); // Within 200ms window
+ buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
+
+ vi.advanceTimersByTime(250); // Finalize
expect(buffer.text).toBe("[Paste #1]");
- });
-
- it("should count lines correctly in collapsed text", () => {
- const multiLineText = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
- buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
-
- expect(buffer.text).toBe("[Paste #1, 4 lines]");
- });
-
- it("should expand collapsed content on expandAllPasteBlocks", () => {
- const longText = "hello " + "a".repeat(COLLAPSE_SIZE);
- buffer.handleInput(longText, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
-
- // Verify it was collapsed
- expect(buffer.text).toBe("[Paste #1]");
-
- // Expand it
buffer.expandAllPasteBlocks();
-
- // Verify it was expanded with normalized line endings
- expect(buffer.text).toBe(longText);
+ expect(buffer.text).toBe(chunk1 + chunk2);
});
- it("should handle typing before and after collapsed content", () => {
- buffer.setText("before ");
- buffer.setCursor(7);
+ it("should finalize buffered content after 200ms timeout", () => {
+ const chunk = "x".repeat(100);
+
+ buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
+ expect(buffer.text).toBe("");
+
+ vi.advanceTimersByTime(250);
+ expect(buffer.text).toBe(chunk);
+ });
+
+ it("should separate sessions when timing window expires", () => {
+ const chunk1 = "a".repeat(60);
+ const chunk2 = "b".repeat(900);
+
+ buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
+ vi.advanceTimersByTime(300); // Exceed timing window
+ expect(buffer.text).toBe(chunk1);
+
+ buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
+ vi.advanceTimersByTime(250);
+ expect(buffer.text).toBe(chunk1 + "[Paste #1]");
+ });
+ });
+
+ describe("regression tests", () => {
+ it("should prevent typing during paste accumulation (Terminal.app fix)", () => {
+ const largeChunk = "x".repeat(100);
+ 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 longText = "a".repeat(COLLAPSE_SIZE + 1);
- buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
-
- expect(buffer.text).toBe("before [Paste #1]");
-
- // Type after collapsed content
- buffer.insertText(" after");
- expect(buffer.text).toBe("before [Paste #1] after");
-
- // Move cursor to beginning and type
- buffer.setCursor(0);
- buffer.insertText("start ");
- expect(buffer.text).toBe("start before [Paste #1] after");
+ expect(buffer.text).toBe("a" + largeChunk);
});
- it("should handle exactly collapse threshold without collapsing", () => {
- const exactText = "a".repeat(COLLAPSE_SIZE); // exactly at threshold
- buffer.handleInput(exactText, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput(); // This will go into rapid input mode due to size
-
- expect(buffer.text).toBe(exactText); // Should not be collapsed
- });
-
- it("should handle paste operations as single large inputs", () => {
- // This simulates the most common paste scenario: a single large input
- const longText = "x".repeat(COLLAPSE_SIZE + 1);
-
- expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE);
-
- buffer.handleInput(longText, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
-
- // Should be collapsed
- expect(buffer.text).toBe("[Paste #1]");
- });
-
- it("should handle bracketed paste mode", () => {
- // Simulate bracketed paste: start sequence, content, end sequence
-
- // Start paste mode
- buffer.handleInput("\u001b[200~", {} as any);
- expect(buffer.isInPasteMode()).toBe(true);
-
- // Add some content (in chunks like real paste)
- const chunks = [
- "Hello ",
- "world! ",
- "This is a long piece of text. ".repeat(30),
- ];
- const totalContent = chunks.join("");
+ it("should preserve all chunks when expanding (content loss fix)", () => {
+ const chunks = ["a".repeat(1000), "b".repeat(1000), "c".repeat(1000)];
chunks.forEach((chunk) => {
buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
});
-
- // Text should NOT be visible during paste mode (to avoid visual bugs)
- expect(buffer.text).toBe("");
-
- // End paste mode
- buffer.handleInput("\u001b[201~", {} as any);
- expect(buffer.isInPasteMode()).toBe(false);
-
- // Now should be collapsed if > COLLAPSE_SIZE
- if (totalContent.length > COLLAPSE_SIZE) {
- expect(buffer.text).toBe("[Paste #1]");
- }
- });
-
- it("should not collapse short bracketed paste content", () => {
- // Start paste mode
- buffer.handleInput("\u001b[200~", {} as any);
-
- // Add short content
- const shortContent = "Hello world!";
- buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
-
- // End paste mode
- buffer.handleInput("\u001b[201~", {} as any);
-
- // Should not be collapsed
- expect(buffer.text).toBe(shortContent);
- });
-
- it("should normalize line endings when expanding", () => {
- const textWithCarriageReturns =
- "line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
- buffer.handleInput(textWithCarriageReturns, {
- ctrl: false,
- meta: false,
- } as any);
buffer.flushPendingInput();
- expect(buffer.text).toBe("[Paste #1, 4 lines]");
-
- buffer.expandAllPasteBlocks();
-
- // Should have normalized line endings
- const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
- expect(buffer.text).toBe(expected);
- });
-
- it("should increment paste counter for multiple pastes", () => {
- const longText1 = "a".repeat(COLLAPSE_SIZE + 1);
- const longText2 = "b".repeat(COLLAPSE_SIZE + 1);
-
- buffer.handleInput(longText1, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
- buffer.insertText(" ");
- buffer.handleInput(longText2, { ctrl: false, meta: false } as any);
- buffer.flushPendingInput();
- expect(buffer.text).toBe("[Paste #1] [Paste #2]");
- });
-
- it("should detect rapid input above threshold", () => {
- // Test that input above RAPID_INPUT_THRESHOLD triggers rapid input detection
- const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
- buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
-
- // Should go into rapid input buffer (not displayed yet)
- expect(buffer.text).toBe("");
- expect(buffer.isInRapidInputMode()).toBe(true);
-
- // Flush to finalize
- buffer.flushPendingInput();
-
- // Now should be displayed (but not collapsed since < COLLAPSE_SIZE)
- expect(buffer.text).toBe(rapidText);
- });
-
- it("should combine split paste chunks", () => {
- // Simulate macOS Terminal splitting paste
- const firstChunk = "a".repeat(COLLAPSE_SIZE + 200); // Large first chunk
- buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any);
-
- // First chunk goes into rapid input mode - no placeholder yet
- expect(buffer.text).toBe("");
-
- // Second chunk should be combined with the first (needs to be > 50 chars)
- const secondChunk = "b".repeat(100); // Large enough to trigger split paste detection
- buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any);
-
- // Flush to finalize the rapid input synchronously
- buffer.flushPendingInput();
-
- // Should show only one placeholder with combined content
- expect(buffer.text).toBe("[Paste #1]");
-
- // Verify the combined content is stored correctly
buffer.expandAllPasteBlocks();
- const expectedContent = firstChunk + secondChunk;
- expect(buffer.text).toBe(expectedContent);
+ expect(buffer.text).toBe(chunks.join(""));
+ expect(buffer.text.length).toBe(3000);
});
- it("should expand paste blocks on submission (simulating Enter key behavior)", () => {
- // Add some text before the paste
- buffer.insertText("Command: ");
+ it("should handle complete paste-to-submit workflow", () => {
+ const pastedCode = 'console.log("test");' + "x".repeat(800);
- // Add a large paste that gets collapsed
- const pastedCode =
- 'function example() {\n console.log("hello");\n ' +
- "x".repeat(COLLAPSE_SIZE);
buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
+ expect(buffer.text).toBe("[Paste #1]");
- // Verify it's collapsed
- expect(buffer.text).toBe("Command: [Paste #1, 3 lines]");
-
- // Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks()
+ // Simulate Enter key - expand before submission
buffer.expandAllPasteBlocks();
+ expect(buffer.text).toBe(pastedCode);
- // Should now show the full content with normalized line endings
- const expectedFullText =
- 'Command: function example() {\n console.log("hello");\n ' +
- "x".repeat(COLLAPSE_SIZE);
- expect(buffer.text).toBe(expectedFullText);
-
- // Verify paste map is cleared after expansion
- buffer.expandAllPasteBlocks(); // Should be no-op now
- expect(buffer.text).toBe(expectedFullText); // Should remain the same
+ buffer.clear();
+ expect(buffer.text).toBe("");
});
});
diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts
index 25723ae8f..103b48571 100644
--- a/extensions/cli/src/ui/TextBuffer.ts
+++ b/extensions/cli/src/ui/TextBuffer.ts
@@ -305,7 +305,13 @@ export class TextBuffer {
const timeSinceLastInput = now - this._lastInputTime;
// If we're already in rapid input mode and this comes quickly, add to buffer
- if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 100) {
+ // 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;
@@ -323,8 +329,11 @@ export class TextBuffer {
// Fallback paste detection: some terminals send large pastes as rapid chunks
// instead of using bracketed paste mode. We detect this by timing between inputs.
- // Only trigger for actually large chunks to avoid interfering with normal typing
- if (input.length > RAPID_INPUT_THRESHOLD) {
+ // The >= 50 char threshold was restored to detect Terminal.app/Ghostty split pastes
+ if (
+ input.length > RAPID_INPUT_THRESHOLD ||
+ (input.length >= 50 && this._rapidInputBuffer.length === 0)
+ ) {
this._rapidInputStartPos = this._cursor;
// Accumulate chunks without inserting to avoid visual flicker
@@ -511,8 +520,7 @@ export class TextBuffer {
}
// Fallback: detect chunked paste operations
- // Don't trigger rapid input detection for small inputs (e.g. single characters like "/" or "@")
- if (input.length > 50 && this.handleRapidInput(input)) {
+ if (this.handleRapidInput(input)) {
return true;
}
diff --git a/extensions/cli/src/ui/Timer.tsx b/extensions/cli/src/ui/Timer.tsx
index 87744ce92..35ae5077d 100644
--- a/extensions/cli/src/ui/Timer.tsx
+++ b/extensions/cli/src/ui/Timer.tsx
@@ -6,7 +6,7 @@ interface TimerProps {
color?: string;
}
-const Timer: React.FC = ({ startTime, color = "gray" }) => {
+const Timer: React.FC = ({ startTime, color = "dim" }) => {
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
diff --git a/extensions/cli/src/ui/TipsDisplay.tsx b/extensions/cli/src/ui/TipsDisplay.tsx
index 148e06583..4b4975e3d 100644
--- a/extensions/cli/src/ui/TipsDisplay.tsx
+++ b/extensions/cli/src/ui/TipsDisplay.tsx
@@ -9,6 +9,7 @@ const CONTINUE_CLI_TIPS = [
'Multi-line input is supported by typing "\\" and pressing enter',
"Use `cn ls` or `/resume` to resume a previous conversation",
'Run `cn` with the `-p` flag for headless mode. For example: `cn -p "Generate a commit message for the current changes. Output _only_ the commit message and nothing else."`',
+ "Use the /init slash command to generate an AGENTS.md file. This will help `cn` understand your codebase and generate better responses.",
];
interface TipsDisplayProps {
@@ -32,7 +33,7 @@ const TipsDisplay: React.FC = () => {
* Tip:
-
+
{" "}
{randomTip}
diff --git a/extensions/cli/src/ui/ToolResultSummary.tsx b/extensions/cli/src/ui/ToolResultSummary.tsx
index 152a6121f..9e2de0824 100644
--- a/extensions/cli/src/ui/ToolResultSummary.tsx
+++ b/extensions/cli/src/ui/ToolResultSummary.tsx
@@ -22,8 +22,8 @@ const ToolResultSummary: React.FC = ({
if (!content) {
return (
- ⎿
- No output
+ ⎿
+ No output
);
}
@@ -37,7 +37,7 @@ const ToolResultSummary: React.FC = ({
return (
- ⎿
+ ⎿
Task List Updated
@@ -55,7 +55,7 @@ const ToolResultSummary: React.FC = ({
return (
- ⎿
+ ⎿
{toolName === "Edit"
? " File edited successfully"
@@ -81,8 +81,8 @@ const ToolResultSummary: React.FC = ({
return (
- ⎿
- Terminal output:
+ ⎿
+ Terminal output:
@@ -97,8 +97,8 @@ const ToolResultSummary: React.FC = ({
return (
- ⎿
- Terminal output:
+ ⎿
+ Terminal output:
@@ -106,7 +106,7 @@ const ToolResultSummary: React.FC = ({
-
+
... +{outputLines.length - MAX_BASH_OUTPUT_LINES} lines
@@ -183,8 +183,8 @@ const ToolResultSummary: React.FC = ({
return (
- ⎿
- {getSummary()}
+ ⎿
+ {getSummary()}
);
};
diff --git a/extensions/cli/src/ui/UpdateNotification.test.tsx b/extensions/cli/src/ui/UpdateNotification.test.tsx
index f4670dbda..5dc4c89a0 100644
--- a/extensions/cli/src/ui/UpdateNotification.test.tsx
+++ b/extensions/cli/src/ui/UpdateNotification.test.tsx
@@ -1,10 +1,3 @@
-// Mock the version module before any other imports
-vi.mock("../version.js", () => ({
- getVersion: vi.fn(),
- getLatestVersion: vi.fn(),
- compareVersions: vi.fn(),
-}));
-
// Mock useTerminalSize hook
vi.mock("./hooks/useTerminalSize.js", () => ({
useTerminalSize: () => ({ columns: 80, rows: 24 }),
@@ -30,93 +23,202 @@ import { render } from "ink-testing-library";
import React from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import * as versionModule from "../version.js";
+import { UpdateStatus } from "../services/types.js";
import { UpdateNotification } from "./UpdateNotification.js";
-const mockVersionModule = vi.mocked(versionModule);
+// Mock useServices hook
+const mockUseServices = vi.fn();
+vi.mock("../hooks/useService.js", () => ({
+ useServices: () => mockUseServices(),
+}));
describe("UpdateNotification", () => {
- let originalNodeEnv: string | undefined;
-
beforeEach(() => {
vi.clearAllMocks();
- originalNodeEnv = process.env.NODE_ENV;
- // Default mock implementations
- mockVersionModule.getLatestVersion.mockResolvedValue("1.0.1");
- mockVersionModule.compareVersions.mockReturnValue("older");
+ // Default mock implementation - no update available
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "Continue CLI v1.0.0",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: null,
+ currentVersion: "1.0.0",
+ },
+ },
+ });
});
afterEach(() => {
- // Restore original NODE_ENV
- if (originalNodeEnv === undefined) {
- delete process.env.NODE_ENV;
- } else {
- process.env.NODE_ENV = originalNodeEnv;
- }
+ vi.clearAllMocks();
});
- it("should not check for updates when version ends with -dev", async () => {
- // Set NODE_ENV to non-test value to enable update checks
- process.env.NODE_ENV = "development";
- mockVersionModule.getVersion.mockReturnValue("1.0.0-dev");
+ it("should show default message when no update is available", () => {
+ const { lastFrame } = render();
- render();
-
- // Wait a bit to ensure useEffect has run
- await new Promise((resolve) => setTimeout(resolve, 50));
-
- // getLatestVersion should not have been called for dev versions
- expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
+ expect(lastFrame()).toContain("◉ Continue CLI v1.0.0");
});
- it("should check for updates when version does not end with -dev", async () => {
- // Set NODE_ENV to non-test value to enable update checks
- process.env.NODE_ENV = "development";
- mockVersionModule.getVersion.mockReturnValue("1.0.0");
+ it("should show update available message when update is available", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "Update available: v1.0.1",
+ error: null,
+ isUpdateAvailable: true,
+ latestVersion: "1.0.1",
+ currentVersion: "1.0.0",
+ },
+ },
+ });
- render();
+ const { lastFrame } = render();
- // Wait a bit to ensure useEffect has run
- await new Promise((resolve) => setTimeout(resolve, 50));
-
- // getLatestVersion should have been called for non-dev versions
- expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
+ expect(lastFrame()).toContain("◉ Update available: v1.0.1");
});
- it("should handle various dev version formats", async () => {
- // Set NODE_ENV to non-test value to enable update checks
- process.env.NODE_ENV = "development";
- const devVersions = ["1.0.0-dev", "2.1.3-dev", "0.5.0-dev"];
+ it("should show checking message when checking for updates", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.CHECKING,
+ message: "Checking for updates",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: null,
+ currentVersion: "1.0.0",
+ },
+ },
+ });
- for (const version of devVersions) {
- vi.clearAllMocks();
- mockVersionModule.getVersion.mockReturnValue(version);
+ const { lastFrame } = render();
- render();
-
- // Wait a bit to ensure useEffect has run
- await new Promise((resolve) => setTimeout(resolve, 50));
-
- expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled();
- }
+ expect(lastFrame()).toContain("◉ Checking for updates");
});
- it("should still check for updates with other version suffixes", async () => {
- // Set NODE_ENV to non-test value to enable update checks
- process.env.NODE_ENV = "development";
- const nonDevVersions = ["1.0.0-beta", "1.0.0-alpha", "1.0.0-rc1"];
+ it("should show updating message when updating", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.UPDATING,
+ message: "Updating to v1.0.1",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: "1.0.1",
+ currentVersion: "1.0.0",
+ },
+ },
+ });
- for (const version of nonDevVersions) {
- vi.clearAllMocks();
- mockVersionModule.getVersion.mockReturnValue(version);
+ const { lastFrame } = render();
- render();
+ expect(lastFrame()).toContain("◉ Updating to v1.0.1");
+ });
- // Wait a bit to ensure useEffect has run
- await new Promise((resolve) => setTimeout(resolve, 50));
+ it("should show updated message when update completes", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.UPDATED,
+ message: "Auto-updated to v1.0.1",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: "1.0.1",
+ currentVersion: "1.0.0",
+ },
+ },
+ });
- expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
- }
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("◉ Auto-updated to v1.0.1");
+ });
+
+ it("should show error message when update fails", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.ERROR,
+ message: "Update failed",
+ error: new Error("Update error"),
+ isUpdateAvailable: true,
+ latestVersion: "1.0.1",
+ currentVersion: "1.0.0",
+ },
+ },
+ });
+
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("◉ Update failed");
+ });
+
+ it("should show remote mode when in remote mode and no update available", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "Continue CLI v1.0.0",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: null,
+ currentVersion: "1.0.0",
+ },
+ },
+ });
+
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("◉ Remote Mode");
+ });
+
+ it("should show update message even in remote mode when update is available", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "Update available: v1.0.1",
+ error: null,
+ isUpdateAvailable: true,
+ latestVersion: "1.0.1",
+ currentVersion: "1.0.0",
+ },
+ },
+ });
+
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("◉ Update available: v1.0.1");
+ });
+
+ it("should show default message when update service has no message", () => {
+ mockUseServices.mockReturnValue({
+ services: {
+ update: {
+ autoUpdate: true,
+ status: UpdateStatus.IDLE,
+ message: "",
+ error: null,
+ isUpdateAvailable: false,
+ latestVersion: null,
+ currentVersion: "1.0.0",
+ },
+ },
+ });
+
+ const { lastFrame } = render();
+
+ expect(lastFrame()).toContain("◉ Continue CLI");
});
});
diff --git a/extensions/cli/src/ui/UpdateNotification.tsx b/extensions/cli/src/ui/UpdateNotification.tsx
index 8f1c47738..833422692 100644
--- a/extensions/cli/src/ui/UpdateNotification.tsx
+++ b/extensions/cli/src/ui/UpdateNotification.tsx
@@ -1,79 +1,54 @@
import { Text } from "ink";
-import React, { useEffect, useMemo, useState } from "react";
+import React, { useMemo } from "react";
-import { compareVersions, getLatestVersion, getVersion } from "../version.js";
+import { useServices } from "../hooks/useService.js";
+import {
+ SERVICE_NAMES,
+ UpdateServiceState,
+ UpdateStatus,
+} from "../services/types.js";
import { useTerminalSize } from "./hooks/useTerminalSize.js";
interface UpdateNotificationProps {
isRemoteMode?: boolean;
}
-
const UpdateNotification: React.FC = ({
isRemoteMode = false,
}) => {
- const [updateAvailable, setUpdateAvailable] = useState(false);
- const [latestVersion, setLatestVersion] = useState("");
- const [currentVersion] = useState(getVersion());
const { columns } = useTerminalSize();
- useEffect(() => {
- // Skip update check in test environment
- if (process.env.NODE_ENV === "test") {
- return;
+ const { services } = useServices<{
+ update: UpdateServiceState;
+ }>([SERVICE_NAMES.UPDATE]);
+
+ const color = useMemo(() => {
+ switch (services.update?.status) {
+ case UpdateStatus.UPDATING:
+ case UpdateStatus.CHECKING:
+ return "yellow";
+ case UpdateStatus.UPDATED:
+ return "green";
+ case UpdateStatus.ERROR:
+ return "red";
+ default:
+ return "dim";
}
-
- // Skip update check for development versions
- if (currentVersion.endsWith("-dev")) {
- return;
- }
-
- const abortController = new AbortController();
-
- const checkForUpdate = async () => {
- try {
- const latest = await getLatestVersion(abortController.signal);
- if (latest) {
- setLatestVersion(latest);
- const comparison = compareVersions(currentVersion, latest);
- setUpdateAvailable(comparison === "older");
- }
- } catch (error) {
- // Silently fail - we don't want to interrupt the user experience
- if (error instanceof Error && error.name !== "AbortError") {
- console.debug("Failed to check for updates:", error);
- }
- }
- };
-
- // Check for updates but don't block
- checkForUpdate();
-
- // Cleanup function to abort the request when component unmounts
- return () => {
- abortController.abort();
- };
- }, [currentVersion]);
+ }, [services.update?.status]);
const text = useMemo(() => {
- if (columns < 75) {
- return `v${latestVersion} available`;
+ if (!services.update?.message) {
+ return "Continue CLI";
}
- return `Update available: v${latestVersion} (npm i -g @continuedev/cli)`;
- }, [columns, latestVersion]);
- if (!updateAvailable) {
- if (isRemoteMode) {
- return ◉ Remote Mode;
- }
- return (
-
- ● Continue CLI
-
- );
+ return services.update.message;
+ }, [columns, services.update?.message]);
+
+ if (!services.update?.isUpdateAvailable && isRemoteMode) {
+ return ◉ Remote Mode;
}
- return {text};
+ return {`◉ ${text}`};
};
export { UpdateNotification };
diff --git a/extensions/cli/src/ui/UpdateSelector.tsx b/extensions/cli/src/ui/UpdateSelector.tsx
new file mode 100644
index 000000000..ce795046f
--- /dev/null
+++ b/extensions/cli/src/ui/UpdateSelector.tsx
@@ -0,0 +1,93 @@
+import React, { useMemo, useState } from "react";
+
+import { useService } from "../hooks/useService.js";
+import { services } from "../services/index.js";
+import type { UpdateServiceState } from "../services/types.js";
+import { SERVICE_NAMES } from "../services/types.js";
+
+import { Selector, SelectorOption } from "./Selector.js";
+
+interface UpdateSelectorProps {
+ onCancel: () => void;
+}
+
+interface UpdateOption extends SelectorOption {
+ action: "run" | "toggle-auto" | "back";
+}
+
+export const UpdateSelector: React.FC = ({ onCancel }) => {
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const updateServiceState = useService(
+ SERVICE_NAMES.UPDATE,
+ );
+
+ const updateState = updateServiceState.value;
+
+ const isWorking =
+ updateServiceState.state === "loading" ||
+ updateState?.status === "checking" ||
+ updateState?.status === "updating";
+
+ const error: string | null = useMemo(() => {
+ if (updateServiceState.state === "error") {
+ return updateServiceState.error?.message || "Update service error";
+ }
+ if (updateState?.status === "error") {
+ return updateState.message || "Update failed";
+ }
+ return null;
+ }, [updateServiceState.state, updateServiceState.error, updateState]);
+
+ const loadingMessage = useMemo(() => {
+ if (!updateState) return "Preparing update...";
+ return updateState.message || "Working...";
+ }, [updateState]);
+
+ const options: UpdateOption[] = useMemo(() => {
+ const runLabel = updateState?.latestVersion
+ ? `Run update to v${updateState.latestVersion}`
+ : "Run update";
+
+ const autoUpdateLabel = updateState?.autoUpdate
+ ? "Turn off auto-updates"
+ : "Turn on auto-updates";
+
+ return [
+ { id: "run-update", name: runLabel, action: "run" },
+ { id: "toggle-auto", name: autoUpdateLabel, action: "toggle-auto" },
+ { id: "back", name: "Back", action: "back" },
+ ];
+ }, [updateState?.latestVersion, updateState?.autoUpdate]);
+
+ const handleSelect = async (option: UpdateOption) => {
+ switch (option.action) {
+ case "run":
+ // Perform a manual update (not auto-update)
+ await services.updateService.performUpdate(false);
+ return; // Keep selector open to show status changes
+ case "toggle-auto":
+ // Toggle auto-update setting
+ const newValue = !updateState?.autoUpdate;
+ await services.updateService.setAutoUpdate(newValue);
+ return; // Keep selector open to show updated label
+ case "back":
+ onCancel();
+ return;
+ }
+ };
+
+ return (
+
+ );
+};
diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx
index 4b5deb5bc..f1726f457 100644
--- a/extensions/cli/src/ui/UserInput.tsx
+++ b/extensions/cli/src/ui/UserInput.tsx
@@ -9,6 +9,7 @@ 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 { messageQueue } from "../stream/messageQueue.js";
import { InputHistory } from "../util/inputHistory.js";
import { FileSearchUI } from "./FileSearchUI.js";
@@ -94,6 +95,7 @@ const FileSearchMaybe: React.FC<{
interface UserInputProps {
onSubmit: (message: string, imageMap?: Map) => void;
isWaitingForResponse: boolean;
+ isCompacting?: boolean;
inputMode: boolean;
onInterrupt?: () => void;
assistant?: AssistantConfig;
@@ -109,6 +111,7 @@ interface UserInputProps {
const UserInput: React.FC = ({
onSubmit,
isWaitingForResponse,
+ isCompacting = false,
inputMode,
onInterrupt,
assistant,
@@ -164,8 +167,8 @@ const UserInput: React.FC = ({
>([]);
const { exit } = useApp();
- // Get file index service
- const { services } = useServices<{
+ // Get file index service state for reactive updates (unused but needed for service initialization)
+ useServices<{
fileIndex: FileIndexServiceState;
}>(["fileIndex"]);
@@ -240,20 +243,24 @@ const UserInput: React.FC = ({
return;
}
- // Get the complete slash command, not just the part before cursor
+ // Get the complete slash command from the text (not just before cursor)
const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0];
// We're in a slash command context - check if it's a complete command
const allCommands = getSlashCommands();
const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash);
- // Hide selector if we have an exact match and there's a space after cursor
+ // Hide selector if we have an exact match and there's any additional content
if (exactMatch) {
- const restOfText = text.slice(cursor);
- // Only hide if there's a space or newline immediately after cursor
- const shouldHide =
- restOfText.startsWith(" ") || restOfText.startsWith("\n");
- if (shouldHide) {
+ // Check if there's anything after the command name (space + args)
+ const commandWithSlash = "/" + exactMatch.name;
+ const textAfterCommand = trimmedText.slice(commandWithSlash.length);
+
+ // If there's any content after the command name (space + args), hide dropdown
+ if (
+ textAfterCommand.trim().length > 0 &&
+ beforeCursor.length >= commandWithSlash.length
+ ) {
setShowSlashCommands(false);
return;
}
@@ -294,45 +301,39 @@ const UserInput: React.FC = ({
// Check if we're in a file search context
const beforeCursor = text.slice(0, cursor);
- const lastAtIndex = beforeCursor.lastIndexOf("@");
- if (lastAtIndex === -1) {
- setShowFileSearch(false);
- } else {
- // Check if there's any whitespace between the last @ and cursor
- const afterAt = beforeCursor.slice(lastAtIndex + 1);
-
- if (afterAt.includes(" ") || afterAt.includes("\n")) {
- setShowFileSearch(false);
- } else {
- // We're in a file search context - check if there are matching files
- const fileIndexService = services.fileIndex;
- if (fileIndexService) {
- const filteredFiles = fileIndexService.files.filter((file) => {
- if (afterAt.length === 0) {
- return true;
- }
- const lowerFilter = afterAt.toLowerCase();
- return (
- file.displayName.toLowerCase().includes(lowerFilter) ||
- file.path.toLowerCase().includes(lowerFilter)
- );
- });
-
- // If no files match, hide the dropdown to allow normal Enter behavior
- if (filteredFiles.length === 0 && afterAt.length > 0) {
- setShowFileSearch(false);
- return;
+ // Find the first @ symbol that starts a file search context
+ // We need to find the last @ that has no space before it (or is at word boundary)
+ let firstAtIndex = -1;
+ for (let i = beforeCursor.length - 1; i >= 0; i--) {
+ if (beforeCursor[i] === "@") {
+ // Check if this @ is at the start of a word (preceded by space/newline or start of string)
+ const beforeAt = beforeCursor.slice(0, i);
+ const lastChar = beforeAt[beforeAt.length - 1];
+ if (i === 0 || lastChar === " " || lastChar === "\n") {
+ // Check if there's any space/newline between this @ and cursor
+ const afterThis = beforeCursor.slice(i + 1);
+ if (!afterThis.includes(" ") && !afterThis.includes("\n")) {
+ firstAtIndex = i;
+ break;
}
}
-
- setShowFileSearch(true);
- setFileSearchFilter(afterAt);
- setSelectedFileIndex(0);
- setShowSlashCommands(false);
- setShowBashMode(false);
}
}
+
+ if (firstAtIndex === -1) {
+ setShowFileSearch(false);
+ } else {
+ // Get ALL text after the @ symbol (including subsequent @ symbols)
+ const afterAt = beforeCursor.slice(firstAtIndex + 1);
+
+ // We're in a file search context
+ setShowFileSearch(true);
+ setFileSearchFilter(afterAt);
+ setSelectedFileIndex(0);
+ setShowSlashCommands(false);
+ setShowBashMode(false);
+ }
};
// Get filtered commands for navigation - using the same sorting logic as SlashCommandUI
@@ -382,15 +383,32 @@ const UserInput: React.FC = ({
// Handle file selection
const selectFile = async (filePath: string) => {
const beforeCursor = inputText.slice(0, cursorPosition);
- const lastAtIndex = beforeCursor.lastIndexOf("@");
- if (lastAtIndex !== -1) {
- const beforeAt = inputText.slice(0, lastAtIndex);
+ // Find the first @ symbol that starts a file search context (same logic as updateFileSearchState)
+ let firstAtIndex = -1;
+ for (let i = beforeCursor.length - 1; i >= 0; i--) {
+ if (beforeCursor[i] === "@") {
+ // Check if this @ is at the start of a word (preceded by space/newline or start of string)
+ const beforeAt = beforeCursor.slice(0, i);
+ const lastChar = beforeAt[beforeAt.length - 1];
+ if (i === 0 || lastChar === " " || lastChar === "\n") {
+ // Check if there's any space/newline between this @ and cursor
+ const afterThis = beforeCursor.slice(i + 1);
+ if (!afterThis.includes(" ") && !afterThis.includes("\n")) {
+ firstAtIndex = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if (firstAtIndex !== -1) {
+ const beforeAt = inputText.slice(0, firstAtIndex);
const afterCursor = inputText.slice(cursorPosition);
// Replace the partial file reference with the full file path
const newText = beforeAt + "@" + filePath + " " + afterCursor;
- const newCursorPos = lastAtIndex + 1 + filePath.length + 1;
+ const newCursorPos = firstAtIndex + 1 + filePath.length + 1;
textBuffer.setText(newText);
textBuffer.setCursor(newCursorPos);
@@ -407,7 +425,14 @@ const UserInput: React.FC = ({
const content = await fs.readFile(absolutePath, "utf-8");
onFileAttached(absolutePath, content);
} catch (error) {
- console.error(`Error reading file ${filePath}:`, error);
+ // If file doesn't exist, just attach the filename without content
+ if (error instanceof Error && (error as any).code === "ENOENT") {
+ const path = await import("path");
+ const absolutePath = path.resolve(filePath);
+ onFileAttached(absolutePath, filePath);
+ } else {
+ console.error(`Error reading file ${filePath}:`, error);
+ }
}
}
}
@@ -515,7 +540,7 @@ const UserInput: React.FC = ({
}
// Normal Enter behavior - submit if there's content
- if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
+ if (textBuffer.text.trim() || wasInterrupted) {
// Get images before expanding paste blocks
const imageMap = textBuffer.getAllImages();
@@ -523,13 +548,16 @@ const UserInput: React.FC = ({
textBuffer.expandAllPasteBlocks();
const submittedText = textBuffer.text.trim();
- // Only add to history if there's actual text (not when resuming)
- if (submittedText) {
- inputHistory.addEntry(submittedText);
- }
+ inputHistory.addEntry(submittedText);
- // Submit with images
- onSubmit(submittedText, imageMap);
+ // We don't queue, we just send in remote mode because the server handles queueing
+ if (!isRemoteMode && (isWaitingForResponse || isCompacting)) {
+ // Process message later when LLM has responded or compaction is complete
+ void messageQueue.enqueueMessage(submittedText, imageMap);
+ } else {
+ // Submit with images
+ onSubmit(submittedText, imageMap);
+ }
textBuffer.clear();
setInputText("");
@@ -570,6 +598,12 @@ const UserInput: React.FC = ({
return true;
}
+ // Handle escape key to interrupt compaction (higher priority)
+ if (isCompacting && onInterrupt) {
+ onInterrupt();
+ return true;
+ }
+
// Handle escape key to interrupt streaming
if (isWaitingForResponse && onInterrupt) {
onInterrupt();
@@ -647,15 +681,6 @@ const UserInput: React.FC = ({
return;
}
- // Allow typing during streaming, but block submission
- if (!inputMode) {
- // Block only Enter key submission during streaming
- if (key.return && !key.shift) {
- return;
- }
- // Allow all other input (typing, navigation, etc.)
- }
-
// Handle slash command navigation
if (showSlashCommands) {
if (handleSlashCommandNavigation(key)) {
diff --git a/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx
index b2c4033b6..4f53e2727 100644
--- a/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx
+++ b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx
@@ -13,6 +13,13 @@ vi.mock("../../index.js", () => ({
setExitMessageCallback: vi.fn(),
}));
+// Mock git utility functions
+vi.mock("../../util/git.js", () => ({
+ isGitRepo: vi.fn(() => false),
+ getGitRemoteUrl: vi.fn(() => null),
+ getGitBranch: vi.fn(() => null),
+}));
+
describe("BottomStatusBar Ctrl+C message", () => {
const defaultProps: BottomStatusBarProps = {
currentMode: "normal" as const,
diff --git a/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx
new file mode 100644
index 000000000..59152b7e0
--- /dev/null
+++ b/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx
@@ -0,0 +1,214 @@
+import { render } from "ink-testing-library";
+import React from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createUITestContext } from "../../test-helpers/ui-test-context.js";
+import { AppRoot } from "../AppRoot.js";
+
+// Mock the useChat hook to control state
+const mockUseChat = vi.fn();
+
+vi.mock("../hooks/useChat.js", () => ({
+ useChat: () => mockUseChat(),
+}));
+
+describe("TUIChat - ActionStatus", () => {
+ let context: any;
+
+ beforeEach(() => {
+ context = createUITestContext({
+ allServicesReady: true,
+ serviceState: "ready",
+ });
+
+ // Default mock return value
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: false,
+ compactionStartTime: null,
+ inputMode: true,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+ });
+
+ afterEach(() => {
+ context.cleanup();
+ vi.clearAllMocks();
+ });
+
+ it("shows only response status when waiting for response", () => {
+ const responseStartTime = Date.now();
+
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: true,
+ responseStartTime,
+ isCompacting: false,
+ compactionStartTime: null,
+ inputMode: false,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ const frame = lastFrame();
+ expect(frame).toBeDefined();
+
+ // Should show spinner/response indicator but not compaction message
+ expect(frame).toContain("esc to interrupt");
+ expect(frame).not.toContain("Compacting history");
+ } finally {
+ unmount();
+ }
+ });
+
+ it("shows only compaction status when compacting", () => {
+ const compactionStartTime = Date.now();
+
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: true,
+ compactionStartTime,
+ inputMode: true,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ const frame = lastFrame();
+ expect(frame).toBeDefined();
+
+ // Should show compaction message but not spinner
+ expect(frame).toContain("Compacting history");
+ expect(frame).toContain("esc to interrupt");
+ } finally {
+ unmount();
+ }
+ });
+
+ it("shows neither status when both states are false", () => {
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: false,
+ compactionStartTime: null,
+ inputMode: true,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ const frame = lastFrame();
+ expect(frame).toBeDefined();
+
+ // Should not show any status messages
+ expect(frame).not.toContain("Compacting history");
+ // The basic UI should still be there
+ expect(frame).toContain("Ask anything");
+ } finally {
+ unmount();
+ }
+ });
+
+ it("handles state transitions correctly", () => {
+ const { lastFrame, rerender, unmount } = render(
+ React.createElement(AppRoot, {}),
+ );
+
+ // Start with compaction
+ const compactionStartTime = Date.now();
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: true,
+ compactionStartTime,
+ inputMode: true,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ try {
+ rerender(React.createElement(AppRoot, {}));
+
+ let frame = lastFrame();
+ expect(frame).toContain("Compacting history");
+ expect(frame).not.toContain("⠀⠁⠃⠇⠏⠟⠿⣿"); // No spinner chars when only compacting
+
+ // Transition to response waiting
+ const responseStartTime = Date.now();
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: true,
+ responseStartTime,
+ isCompacting: false,
+ compactionStartTime: null,
+ inputMode: false,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: vi.fn(),
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ rerender(React.createElement(AppRoot, {}));
+
+ frame = lastFrame();
+ expect(frame).not.toContain("Compacting history");
+ expect(frame).toContain("esc to interrupt");
+ } finally {
+ unmount();
+ }
+ });
+});
diff --git a/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx
new file mode 100644
index 000000000..81d0843da
--- /dev/null
+++ b/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx
@@ -0,0 +1,141 @@
+import { render } from "ink-testing-library";
+import React from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createUITestContext } from "../../test-helpers/ui-test-context.js";
+import { AppRoot } from "../AppRoot.js";
+
+// Mock the useChat hook to control state
+const mockUseChat = vi.fn();
+const mockHandleInterrupt = vi.fn();
+
+vi.mock("../hooks/useChat.js", () => ({
+ useChat: () => mockUseChat(),
+}));
+
+describe("TUIChat - Compaction Cancellation", () => {
+ let context: any;
+
+ beforeEach(() => {
+ context = createUITestContext({
+ allServicesReady: true,
+ serviceState: "ready",
+ });
+
+ // Reset the mock
+ mockHandleInterrupt.mockClear();
+ });
+
+ afterEach(() => {
+ context.cleanup();
+ vi.clearAllMocks();
+ });
+
+ it("calls handleInterrupt when ESC is pressed during compaction", () => {
+ const compactionStartTime = Date.now();
+
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: true,
+ compactionStartTime,
+ inputMode: true, // Changed to true so ESC handling is active
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: mockHandleInterrupt,
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { stdin, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ // Give some time for the component to render and set up input handling
+ setTimeout(() => {
+ // Simulate ESC key press during compaction
+ stdin.write("\x1b"); // ESC key
+
+ // The handleInterrupt should be called
+ expect(mockHandleInterrupt).toHaveBeenCalledTimes(1);
+ }, 100);
+ } finally {
+ unmount();
+ }
+ });
+
+ it("shows compaction status with esc to interrupt message", () => {
+ const compactionStartTime = Date.now();
+
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: false,
+ responseStartTime: null,
+ isCompacting: true,
+ compactionStartTime,
+ inputMode: false,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: mockHandleInterrupt,
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ const frame = lastFrame();
+ expect(frame).toBeDefined();
+
+ // Should show compaction message with interrupt option
+ expect(frame).toContain("Compacting history");
+ expect(frame).toContain("esc to interrupt");
+ } finally {
+ unmount();
+ }
+ });
+
+ it("prioritizes compaction cancellation over response cancellation", () => {
+ // This tests the case where both might be true (theoretical edge case)
+ const compactionStartTime = Date.now();
+ const responseStartTime = Date.now();
+
+ mockUseChat.mockReturnValue({
+ chatHistory: [],
+ setChatHistory: vi.fn(),
+ isWaitingForResponse: true,
+ responseStartTime,
+ isCompacting: true,
+ compactionStartTime,
+ inputMode: false,
+ attachedFiles: [],
+ activePermissionRequest: null,
+ wasInterrupted: false,
+ handleUserMessage: vi.fn(),
+ handleInterrupt: mockHandleInterrupt,
+ handleFileAttached: vi.fn(),
+ resetChatHistory: vi.fn(),
+ handleToolPermissionResponse: vi.fn(),
+ });
+
+ const { stdin, unmount } = render(React.createElement(AppRoot, {}));
+
+ try {
+ // Simulate ESC key press when both states are active
+ stdin.write("\x1b"); // ESC key
+
+ // Should still call handleInterrupt (which will prioritize compaction)
+ expect(mockHandleInterrupt).toHaveBeenCalledTimes(1);
+ } finally {
+ unmount();
+ }
+ });
+});
diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx
index b41fcdebb..9e67826c5 100644
--- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx
+++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx
@@ -105,4 +105,75 @@ describe("TUIChat - Slash Commands Tests", () => {
expect(hasSlash).toBe(true);
}
});
+
+ testBothModes(
+ "hides slash command dropdown when typing complete command with arguments",
+ async (mode) => {
+ const { lastFrame, stdin } = renderInMode(mode);
+
+ // Type a complete command name first
+ stdin.write("/title");
+
+ await new Promise((resolve) => setTimeout(resolve, 200));
+
+ const frameAfterCommand = lastFrame();
+ if (mode === "remote") {
+ // In remote mode, /title might not be a valid command, so just check we're in remote mode
+ expect(frameAfterCommand).toContain("Remote Mode");
+ } else {
+ // In local mode, check for /title
+ expect(frameAfterCommand).toContain("/title");
+ }
+
+ // Now add a space and arguments
+ stdin.write(" My Session Title");
+
+ await new Promise((resolve) => setTimeout(resolve, 200));
+
+ const frameAfterArgs = lastFrame();
+
+ // Check that the UI is still functional after adding arguments
+ if (mode === "remote") {
+ expect(frameAfterArgs).toContain("Remote Mode");
+ // In remote mode, /title might not be available, so just check the UI is working
+ } else {
+ expect(frameAfterArgs).toContain("Continue CLI");
+ // In local mode, we should see the /title command
+ expect(frameAfterArgs).toContain("/title");
+ }
+ },
+ );
+
+ testBothModes(
+ "allows Enter key to execute command when dropdown is hidden",
+ async (mode) => {
+ const { lastFrame, stdin } = renderInMode(mode);
+
+ // Type a complete command with arguments
+ stdin.write("/title Test Session");
+
+ await new Promise((resolve) => setTimeout(resolve, 200));
+
+ const frameBeforeEnter = lastFrame();
+ expect(frameBeforeEnter).toContain("/title");
+ expect(frameBeforeEnter).toContain("Test Session");
+
+ // Press Enter - this should execute the command, not try to autocomplete
+ stdin.write("\r");
+
+ await new Promise((resolve) => setTimeout(resolve, 300));
+
+ const frameAfterEnter = lastFrame();
+
+ // Should not crash and should clear the input (or show command execution)
+ expect(frameAfterEnter).toBeDefined();
+
+ // Mode-specific checks
+ if (mode === "remote") {
+ expect(frameAfterEnter).toContain("Remote Mode");
+ } else {
+ expect(frameAfterEnter).toContain("Continue CLI");
+ }
+ },
+ );
});
diff --git a/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx
new file mode 100644
index 000000000..a0f6c41c6
--- /dev/null
+++ b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx
@@ -0,0 +1,36 @@
+import * as path from "path";
+
+import { describe, expect, it, vi } from "vitest";
+
+// Test the missing file handling logic directly
+describe("UserInput - Missing File Handling", () => {
+ it("should handle selecting non-existent files gracefully", async () => {
+ const mockOnFileAttached = vi.fn();
+
+ // Simulate the selectFile logic for a missing file
+ const filePath = "missing-file.txt";
+
+ try {
+ const fs = await import("fs/promises");
+ const path = await import("path");
+ const absolutePath = path.resolve(filePath);
+ const content = await fs.readFile(absolutePath, "utf-8");
+ mockOnFileAttached(absolutePath, content);
+ } catch (error) {
+ // If file doesn't exist, just attach the filename without content
+ if (error instanceof Error && (error as any).code === "ENOENT") {
+ const path = await import("path");
+ const absolutePath = path.resolve(filePath);
+ mockOnFileAttached(absolutePath, filePath); // Just the filename for missing file
+ } else {
+ console.error(`Error reading file ${filePath}:`, error);
+ }
+ }
+
+ // Should have called onFileAttached with filename as content
+ expect(mockOnFileAttached).toHaveBeenCalledWith(
+ path.resolve(filePath),
+ filePath,
+ );
+ });
+});
diff --git a/extensions/cli/src/ui/components/ActionStatus.tsx b/extensions/cli/src/ui/components/ActionStatus.tsx
new file mode 100644
index 000000000..a12b3d649
--- /dev/null
+++ b/extensions/cli/src/ui/components/ActionStatus.tsx
@@ -0,0 +1,37 @@
+import { Box, Text } from "ink";
+import React from "react";
+
+import { LoadingAnimation } from "../LoadingAnimation.js";
+import { Timer } from "../Timer.js";
+
+interface ActionStatusProps {
+ visible: boolean;
+ startTime: number;
+ message: string;
+ showSpinner?: boolean;
+ color?: string;
+ loadingColor?: string;
+}
+
+const ActionStatus: React.FC = ({
+ visible,
+ startTime,
+ message,
+ showSpinner = false,
+ color = "dim",
+ loadingColor = "green",
+}) => {
+ if (!visible) return null;
+
+ return (
+
+ {showSpinner && }
+ {message}
+ (
+
+ • esc to interrupt )
+
+ );
+};
+
+export { ActionStatus };
diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx
index ebec26450..64dd99da9 100644
--- a/extensions/cli/src/ui/components/MemoizedMessage.tsx
+++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx
@@ -44,10 +44,11 @@ function formatMessageContentForDisplay(
interface MemoizedMessageProps {
item: ChatHistoryItem;
index: number;
+ hideBullet?: boolean;
}
export const MemoizedMessage = memo(
- ({ item, index }) => {
+ ({ item, index, hideBullet = false }) => {
const { message, toolCallStates, conversationSummary } = item;
const isUser = message.role === "user";
const isSystem = message.role === "system";
@@ -64,7 +65,7 @@ export const MemoizedMessage = memo(
return (
-
+
{message.content}
@@ -93,7 +94,7 @@ export const MemoizedMessage = memo(
{/* Render assistant message content if any */}
{message.content && (
- ●
+ {hideBullet ? " " : "●"}
(
return (
- ●
+ {hideBullet ? " " : "●"}
{isUser ? (
-
+
{formatMessageContentForDisplay(message.content)}
) : (
@@ -177,7 +178,7 @@ export const MemoizedMessage = memo(
content={formatMessageContentForDisplay(message.content)}
/>
)}
- {isStreaming && ▋}
+ {isStreaming && ▋}
);
},
@@ -195,7 +196,8 @@ export const MemoizedMessage = memo(
JSON.stringify(prevToolStates) === JSON.stringify(nextToolStates) &&
prevProps.item.conversationSummary ===
nextProps.item.conversationSummary &&
- prevProps.index === nextProps.index
+ prevProps.index === nextProps.index &&
+ prevProps.hideBullet === nextProps.hideBullet
);
},
);
diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx
index 1af22c91a..977d6954a 100644
--- a/extensions/cli/src/ui/components/ScreenContent.tsx
+++ b/extensions/cli/src/ui/components/ScreenContent.tsx
@@ -1,16 +1,19 @@
import { Box, Text } from "ink";
import React from "react";
-import { listSessions } from "../../session.js";
+import { UpdateServiceState } from "src/services/types.js";
+
import { ConfigSelector } from "../ConfigSelector.js";
import type { NavigationScreen } from "../context/NavigationContext.js";
+import { DiffViewer } from "../DiffViewer.js";
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
import { MCPSelector } from "../MCPSelector.js";
import { ModelSelector } from "../ModelSelector.js";
-import { SessionSelector } from "../SessionSelector.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
+import { UpdateSelector } from "../UpdateSelector.js";
import { UserInput } from "../UserInput.js";
+import { SessionSelectorWithLoading } from "./SessionSelectorWithLoading.js";
import { ToolPermissionSelector } from "./ToolPermissionSelector.js";
interface ScreenContentProps {
@@ -32,6 +35,7 @@ interface ScreenContentProps {
) => void;
handleUserMessage: (message: string, imageMap?: Map) => void;
isWaitingForResponse: boolean;
+ isCompacting: boolean;
inputMode: boolean;
handleInterrupt: () => void;
handleFileAttached: (filePath: string, content: string) => void;
@@ -39,6 +43,15 @@ interface ScreenContentProps {
wasInterrupted?: boolean;
isRemoteMode: boolean;
onImageInClipboardChange?: (hasImage: boolean) => void;
+ diffContent?: string;
+}
+
+function hideScreenContent(state?: UpdateServiceState) {
+ return (
+ (state?.status === "checking" && state?.autoUpdate) ||
+ (state?.isAutoUpdate &&
+ (state?.status === "updating" || state?.status === "updated"))
+ );
}
export const ScreenContent: React.FC = ({
@@ -55,6 +68,7 @@ export const ScreenContent: React.FC = ({
handleToolPermissionResponse,
handleUserMessage,
isWaitingForResponse,
+ isCompacting,
inputMode,
handleInterrupt,
handleFileAttached,
@@ -62,7 +76,12 @@ export const ScreenContent: React.FC = ({
wasInterrupted = false,
isRemoteMode,
onImageInClipboardChange,
+ diffContent,
}) => {
+ if (hideScreenContent(services.update)) {
+ return null;
+ }
+
// Login prompt
if (isScreenActive("login") && navState.screenData) {
return (
@@ -104,6 +123,10 @@ export const ScreenContent: React.FC = ({
return ;
}
+ if (isScreenActive("update")) {
+ return ;
+ }
+
// Model selector
if (isScreenActive("model")) {
return (
@@ -116,10 +139,8 @@ export const ScreenContent: React.FC = ({
// Session selector
if (isScreenActive("session")) {
- const sessions = listSessions(20);
return (
-
@@ -131,6 +152,16 @@ export const ScreenContent: React.FC = ({
return ;
}
+ // Diff viewer overlay
+ if (isScreenActive("diff")) {
+ return (
+
+ );
+ }
+
// Chat screen with input area
if (isScreenActive("chat")) {
if (activePermissionRequest) {
@@ -149,6 +180,7 @@ export const ScreenContent: React.FC = ({
Promise;
+ onExit: () => void;
+}
+
+export const SessionSelectorWithLoading: React.FC<
+ SessionSelectorWithLoadingProps
+> = ({ onSelect, onExit }) => {
+ const [sessions, setSessions] = React.useState([]);
+ const [isLoading, setIsLoading] = React.useState(true);
+
+ React.useEffect(() => {
+ let isMounted = true;
+
+ const loadSessions = async () => {
+ try {
+ if (!isMounted) return;
+ setIsLoading(true);
+ const sessionList = await listSessions();
+ if (!isMounted) return;
+ setSessions(sessionList);
+ } catch (error) {
+ if (!isMounted) return;
+ logger.error("Error loading sessions:", error);
+ setSessions([]);
+ } finally {
+ if (isMounted) {
+ setIsLoading(false);
+ }
+ }
+ };
+
+ loadSessions();
+
+ return () => {
+ isMounted = false;
+ };
+ }, []);
+
+ if (isLoading) {
+ return (
+
+ Loading sessions...
+
+ );
+ }
+
+ return (
+
+ );
+};
diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx
index 4c1c9f133..5cb553762 100644
--- a/extensions/cli/src/ui/components/StaticChatContent.tsx
+++ b/extensions/cli/src/ui/components/StaticChatContent.tsx
@@ -1,11 +1,13 @@
import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
-import { Box, Static, useStdout } from "ink";
+import { Box, Static, Text, useStdout } from "ink";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import type { MCPService } from "../../services/MCPService.js";
+import type { QueuedMessage } from "../../stream/messageQueue.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { IntroMessage } from "../IntroMessage.js";
+import { splitChatHistory } from "../utils/historySplitting.js";
interface StaticChatContentProps {
showIntroMessage: boolean;
@@ -13,8 +15,13 @@ interface StaticChatContentProps {
model?: ModelConfig;
mcpService?: MCPService;
chatHistory: ChatHistoryItem[];
- renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
- refreshTrigger?: number; // Add a prop to trigger refresh from parent
+ queuedMessages?: QueuedMessage[];
+ renderMessage: (
+ item: ChatHistoryItem,
+ index: number,
+ allMessages?: ChatHistoryItem[],
+ ) => React.ReactElement;
+ refreshTrigger?: number;
}
export const StaticChatContent: React.FC = ({
@@ -23,13 +30,14 @@ export const StaticChatContent: React.FC = ({
model,
mcpService,
chatHistory,
+ queuedMessages = [],
renderMessage,
refreshTrigger,
}) => {
const { columns, rows } = useTerminalSize();
const { stdout } = useStdout();
- // State for managing static refresh with key-based remounting (gemini-cli approach)
+ // State for managing static refresh with key-based remounting
const [staticKey, setStaticKey] = useState(0);
const isInitialMount = useRef(true);
@@ -66,15 +74,18 @@ export const StaticChatContent: React.FC = ({
}
}, [refreshTrigger, refreshStatic]);
- // Filter out system messages without content
- const filteredChatHistory = React.useMemo(() => {
- return chatHistory.filter(
+ // Filter out system messages without content and split large messages
+ const processedChatHistory = React.useMemo(() => {
+ const filtered = chatHistory.filter(
(item) => item.message.role !== "system" || item.message.content,
);
- }, [chatHistory]);
+
+ // Split large messages into multiple history items
+ return splitChatHistory(filtered, columns);
+ }, [chatHistory, columns]);
// Split chat history into stable and pending items
- // The last two items may have pending tool calls
+ // Keep more items static now that we've split large messages
const { staticItems, pendingItems } = React.useMemo(() => {
// Add intro message as first item if it should be shown
const staticItems: React.ReactElement[] = [];
@@ -89,22 +100,24 @@ export const StaticChatContent: React.FC = ({
);
}
- const PENDING_ITEMS_COUNT = 2;
+ // Since messages are now split into reasonably-sized chunks,
+ // we can keep more items static (only last 1-2 items dynamic)
+ const PENDING_ITEMS_COUNT = 1;
const stableCount = Math.max(
0,
- filteredChatHistory.length - PENDING_ITEMS_COUNT,
+ processedChatHistory.length - PENDING_ITEMS_COUNT,
);
- const stableHistory = filteredChatHistory.slice(0, stableCount);
- const pendingHistory = filteredChatHistory.slice(stableCount);
+ const stableHistory = processedChatHistory.slice(0, stableCount);
+ const pendingHistory = processedChatHistory.slice(stableCount);
// Add stable messages to static items
stableHistory.forEach((item, index) => {
- staticItems.push(renderMessage(item, index));
+ staticItems.push(renderMessage(item, index, processedChatHistory));
});
// Pending items will be rendered dynamically outside Static
const pendingItems = pendingHistory.map((item, index) =>
- renderMessage(item, stableCount + index),
+ renderMessage(item, stableCount + index, processedChatHistory),
);
return {
@@ -116,7 +129,7 @@ export const StaticChatContent: React.FC = ({
config,
model,
mcpService,
- filteredChatHistory,
+ processedChatHistory,
renderMessage,
]);
@@ -140,6 +153,15 @@ export const StaticChatContent: React.FC = ({
{item}
))}
+
+ {/* Queued messages - show at bottom with queue indicators */}
+ {queuedMessages.length > 0 && (
+
+
+ {queuedMessages.map((msg) => msg.message).join("\n")}
+
+
+ )}
);
};
diff --git a/extensions/cli/src/ui/components/ToolPreview.tsx b/extensions/cli/src/ui/components/ToolPreview.tsx
index 43145b6eb..a5557f5f7 100644
--- a/extensions/cli/src/ui/components/ToolPreview.tsx
+++ b/extensions/cli/src/ui/components/ToolPreview.tsx
@@ -28,8 +28,8 @@ export const ToolPreview: React.FC = ({
if (preview.type === "text") {
return (
- {index === 0 && ⎿ }
- {preview.content}
+ {index === 0 && ⎿ }
+ {preview.content}
);
} else if (preview.type === "checklist") {
@@ -56,8 +56,8 @@ export const ToolPreview: React.FC = ({
return (
- ⎿
- {message}
+ ⎿
+ {message}
);
};
diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx
index 1742d8ee8..fd922ca51 100644
--- a/extensions/cli/src/ui/context/NavigationContext.tsx
+++ b/extensions/cli/src/ui/context/NavigationContext.tsx
@@ -1,9 +1,9 @@
import React, {
createContext,
+ ReactNode,
+ useCallback,
useContext,
useReducer,
- useCallback,
- ReactNode,
} from "react";
/**
@@ -17,6 +17,9 @@ export type NavigationScreen =
| "free-trial" // Free trial transition UI
| "login" // Login prompt
| "mcp" // MCP selector
+ | "session" // Session selector
+ | "diff" // Full-screen diff overlay
+ | "update" // Update selector
| "session"; // Session selector
interface NavigationState {
diff --git a/extensions/cli/src/ui/hooks/useChat.compaction.ts b/extensions/cli/src/ui/hooks/useChat.compaction.ts
index 8952f7643..df0132246 100644
--- a/extensions/cli/src/ui/hooks/useChat.compaction.ts
+++ b/extensions/cli/src/ui/hooks/useChat.compaction.ts
@@ -14,6 +14,9 @@ interface HandleCompactCommandOptions {
setCompactionIndex: React.Dispatch>;
currentSession: Session;
setCurrentSession: React.Dispatch>;
+ setIsCompacting: (value: boolean) => void;
+ setCompactionStartTime: (time: number | null) => void;
+ setCompactionAbortController: (controller: AbortController | null) => void;
}
/**
@@ -27,22 +30,32 @@ export async function handleCompactCommand({
setCompactionIndex,
currentSession,
setCurrentSession,
+ setIsCompacting,
+ setCompactionStartTime,
+ setCompactionAbortController,
}: HandleCompactCommandOptions): Promise {
- // Add compacting message
- setChatHistory((prev) => [
- ...prev,
- {
- message: {
- role: "system",
- content: "Compacting chat history...",
- },
- contextItems: [],
- },
- ]);
+ // Create abort controller for cancellation support
+ const compactionController = new AbortController();
+ setCompactionAbortController(compactionController);
+
+ // Start compaction status display
+ setIsCompacting(true);
+ setCompactionStartTime(Date.now());
try {
- // Compact the chat history directly (already in unified format)
- const result = await compactChatHistory(chatHistory, model, llmApi);
+ // Compact the chat history directly (already in unified format) with abort controller
+ const result = await compactChatHistory(
+ chatHistory,
+ model,
+ llmApi,
+ undefined,
+ compactionController,
+ );
+
+ // Check if operation was aborted before proceeding with success actions
+ if (compactionController.signal.aborted) {
+ return;
+ }
// Replace chat history with compacted version
setChatHistory(result.compactedHistory);
@@ -56,6 +69,7 @@ export async function handleCompactCommand({
updateSessionHistory(result.compactedHistory);
setCurrentSession(updatedSession);
+ // Add success message to chat
setChatHistory((prev) => [
...prev,
{
@@ -67,17 +81,37 @@ export async function handleCompactCommand({
},
]);
} catch (error) {
- logger.error("Compaction failed:", error);
- setChatHistory((prev) => [
- ...prev,
- {
- message: {
- role: "system",
- content: `Compaction failed: ${formatError(error)}`,
+ // Check if the error was due to abortion
+ if (compactionController.signal.aborted) {
+ logger.info("Manual compaction was cancelled by user");
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ message: {
+ role: "system",
+ content: "Compaction cancelled.",
+ },
+ contextItems: [],
},
- contextItems: [],
- },
- ]);
+ ]);
+ } else {
+ logger.error("Compaction failed:", error);
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ message: {
+ role: "system",
+ content: `Compaction failed: ${formatError(error)}`,
+ },
+ contextItems: [],
+ },
+ ]);
+ }
+ } finally {
+ // Stop compaction status display
+ setIsCompacting(false);
+ setCompactionStartTime(null);
+ setCompactionAbortController(null);
}
}
@@ -88,6 +122,7 @@ interface HandleAutoCompactionOptions {
compactionIndex: number | null;
setChatHistory: React.Dispatch>;
setCompactionIndex: React.Dispatch>;
+ abortController?: AbortController;
}
/**
@@ -100,6 +135,7 @@ export async function handleAutoCompaction({
compactionIndex: _compactionIndex,
setChatHistory,
setCompactionIndex,
+ abortController,
}: HandleAutoCompactionOptions): Promise<{
currentChatHistory: ChatHistoryItem[];
currentCompactionIndex: number | null;
@@ -116,20 +152,14 @@ export async function handleAutoCompaction({
logger.info("Auto-compaction triggered for TUI mode");
- // Add compacting message
- setChatHistory((prev) => [
- ...prev,
- {
- message: {
- role: "system",
- content: "Auto-compacting chat history...",
- },
- contextItems: [],
- },
- ]);
-
// Compact the unified history
- const result = await compactChatHistory(chatHistory, model, llmApi);
+ const result = await compactChatHistory(
+ chatHistory,
+ model,
+ llmApi,
+ undefined,
+ abortController,
+ );
// Keep the system message and append the compaction summary
// This replaces the old messages with a summary to reduce context size
@@ -151,23 +181,22 @@ export async function handleAutoCompaction({
? [systemMessage, compactedMessage]
: [compactedMessage];
- setChatHistory(updatedHistory);
+ // Add success message to the history that will be returned
+ const successMessage: ChatHistoryItem = {
+ message: {
+ role: "system",
+ content: "Chat history auto-compacted successfully.",
+ },
+ contextItems: [],
+ };
+
+ const finalHistory = [...updatedHistory, successMessage];
+
+ setChatHistory(finalHistory);
setCompactionIndex(updatedHistory.length - 1);
- // Add success message
- setChatHistory((prev) => [
- ...prev,
- {
- message: {
- role: "system",
- content: "✓ Chat history auto-compacted successfully.",
- },
- contextItems: [],
- },
- ]);
-
return {
- currentChatHistory: updatedHistory,
+ currentChatHistory: finalHistory,
currentCompactionIndex: updatedHistory.length - 1,
};
} catch (error) {
diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts
index 1c289e5c7..a453b7066 100644
--- a/extensions/cli/src/ui/hooks/useChat.helpers.ts
+++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts
@@ -48,6 +48,7 @@ interface ProcessSlashCommandResultOptions {
setChatHistory: React.Dispatch>;
onShowConfigSelector: () => void;
onShowModelSelector?: () => void;
+ onShowUpdateSelector?: () => void;
onShowMCPSelector?: () => void;
onShowSessionSelector?: () => void;
onClear?: () => void;
@@ -61,13 +62,14 @@ export function processSlashCommandResult({
chatHistory,
setChatHistory,
onShowConfigSelector,
+ onShowUpdateSelector,
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
onClear,
}: ProcessSlashCommandResultOptions): string | null {
if (result.exit) {
- process.exit(0);
+ import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
}
if (result.openMcpSelector) {
@@ -75,6 +77,11 @@ export function processSlashCommandResult({
return null;
}
+ if (result.openUpdateSelector) {
+ onShowUpdateSelector?.();
+ return null;
+ }
+
if (result.openConfigSelector) {
onShowConfigSelector();
return null;
@@ -120,7 +127,19 @@ export function processSlashCommandResult({
return null;
}
- if (result.output) {
+ if (result.diffContent) {
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ message: {
+ role: "system",
+ content: `Diff:\n${result.diffContent}`,
+ },
+ contextItems: [],
+ },
+ ]);
+ return null;
+ } else if (result.output) {
setChatHistory((prev) => [
...prev,
{
@@ -131,6 +150,7 @@ export function processSlashCommandResult({
contextItems: [],
},
]);
+ return null;
}
return result.newInput || null;
@@ -218,6 +238,85 @@ interface HandleSpecialCommandsOptions {
remoteUrl?: string;
onShowConfigSelector: () => void;
exit: () => void;
+ onShowDiff?: (diffContent: string) => void;
+ onShowStatusMessage?: (message: string) => void;
+}
+
+/**
+ * Handle /diff command in remote mode
+ */
+async function handleRemoteDiffCommand(
+ remoteUrl: string,
+ onShowDiff?: (diffContent: string) => void,
+): Promise {
+ try {
+ const response = await fetch(`${remoteUrl}/diff`);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch diff: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ const diffContent = responseData.diff || "";
+
+ if (onShowDiff) {
+ onShowDiff(diffContent);
+ }
+ } catch (error: any) {
+ logger.error("Failed to fetch diff from remote server:", error);
+ if (onShowDiff) {
+ onShowDiff(`Error: Failed to fetch diff - ${error.message}`);
+ }
+ }
+}
+
+/**
+ * Handle /apply command in remote mode
+ */
+async function handleRemoteApplyCommand(
+ remoteUrl: string,
+ onShowStatusMessage?: (message: string) => void,
+): Promise {
+ try {
+ const response = await fetch(`${remoteUrl}/diff`);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch diff: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ const diffContent = responseData.diff || "";
+
+ if (!diffContent || diffContent.trim() === "") {
+ if (onShowStatusMessage) {
+ onShowStatusMessage("No changes to apply");
+ }
+ return;
+ }
+
+ // Apply the diff using git apply
+ const { execFileSync } = await import("child_process");
+
+ try {
+ execFileSync("git", ["apply"], {
+ input: diffContent,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ if (onShowStatusMessage) {
+ onShowStatusMessage(
+ "✓ Successfully applied diff to local working tree",
+ );
+ }
+ } catch (gitError: any) {
+ if (onShowStatusMessage) {
+ onShowStatusMessage(`✗ Failed to apply diff: ${gitError.message}`);
+ }
+ }
+ } catch (error: any) {
+ logger.error("Failed to fetch diff from remote server:", error);
+ if (onShowStatusMessage) {
+ onShowStatusMessage(`✗ Failed to fetch diff: ${error.message}`);
+ }
+ }
}
/**
@@ -229,6 +328,8 @@ export async function handleSpecialCommands({
remoteUrl,
onShowConfigSelector,
exit,
+ onShowDiff,
+ onShowStatusMessage,
}: HandleSpecialCommandsOptions): Promise {
const trimmedMessage = message.trim();
@@ -245,6 +346,26 @@ export async function handleSpecialCommands({
return true;
}
+ // Handle /diff command in remote mode - show overlay instead of adding to history
+ if (
+ isRemoteMode &&
+ remoteUrl &&
+ (trimmedMessage === "/diff" || trimmedMessage.startsWith("/diff "))
+ ) {
+ await handleRemoteDiffCommand(remoteUrl, onShowDiff);
+ return true;
+ }
+
+ // Handle /apply command in remote mode - show temporary status message
+ if (
+ isRemoteMode &&
+ remoteUrl &&
+ (trimmedMessage === "/apply" || trimmedMessage.startsWith("/apply "))
+ ) {
+ await handleRemoteApplyCommand(remoteUrl, onShowStatusMessage);
+ return true;
+ }
+
return false;
}
diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
index c173d3ae3..9d2809d40 100644
--- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
+++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
@@ -211,3 +211,87 @@ export async function handleRemoteMessage({
} catch {}
}
}
+
+/**
+ * Handle /diff command in remote mode
+ */
+export async function handleRemoteDiff(remoteUrl: string): Promise {
+ try {
+ const response = await fetch(`${remoteUrl}/diff`);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch diff: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ const diffContent = responseData.diff || "";
+
+ if (!diffContent || diffContent.trim() === "") {
+ try {
+ services.chatHistory.addSystemMessage("No changes to display");
+ } catch {}
+ return;
+ }
+
+ try {
+ services.chatHistory.addSystemMessage(`Diff:\n${diffContent}`);
+ } catch {}
+ } catch (error: any) {
+ logger.error("Failed to fetch diff from remote server:", error);
+ try {
+ services.chatHistory.addSystemMessage(
+ `Failed to fetch diff: ${error.message}`,
+ );
+ } catch {}
+ }
+}
+
+/**
+ * Handle /apply command in remote mode
+ */
+export async function handleRemoteApply(remoteUrl: string): Promise {
+ try {
+ const response = await fetch(`${remoteUrl}/diff`);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch diff: ${response.statusText}`);
+ }
+
+ const responseData = await response.json();
+ const diffContent = responseData.diff || "";
+
+ if (!diffContent || diffContent.trim() === "") {
+ try {
+ services.chatHistory.addSystemMessage("No changes to apply");
+ } catch {}
+ return;
+ }
+
+ // Apply the diff using git apply
+ const { execFileSync } = await import("child_process");
+
+ try {
+ execFileSync("git", ["apply"], {
+ input: diffContent,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ try {
+ services.chatHistory.addSystemMessage(
+ "Successfully applied diff to local working tree",
+ );
+ } catch {}
+ } catch (gitError: any) {
+ try {
+ services.chatHistory.addSystemMessage(
+ `Failed to apply diff: ${gitError.message}`,
+ );
+ } catch {}
+ }
+ } catch (error: any) {
+ logger.error("Failed to fetch diff from remote server:", error);
+ try {
+ services.chatHistory.addSystemMessage(
+ `Failed to fetch diff: ${error.message}`,
+ );
+ } catch {}
+ }
+}
diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts
index 9b9cc5871..5cb661333 100644
--- a/extensions/cli/src/ui/hooks/useChat.ts
+++ b/extensions/cli/src/ui/hooks/useChat.ts
@@ -1,3 +1,5 @@
+/* eslint-disable max-lines */
+/* eslint-disable max-statements */
import type { ChatHistoryItem, Session } from "core/index.js";
import { useApp } from "ink";
import { useEffect, useRef, useState } from "react";
@@ -11,6 +13,7 @@ import {
updateSessionHistory,
} from "../../session.js";
import { handleSlashCommands } from "../../slashCommands.js";
+import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
import { logger } from "../../util/logger.js";
@@ -52,12 +55,15 @@ export function useChat({
additionalPrompts,
onShowConfigSelector,
onShowModelSelector,
+ onShowUpdateSelector,
onShowMCPSelector,
onShowSessionSelector,
onLoginPrompt: _onLoginPrompt,
onClear,
isRemoteMode = false,
remoteUrl,
+ onShowDiff,
+ onShowStatusMessage,
}: UseChatProps) {
const { exit } = useApp();
@@ -138,9 +144,15 @@ export function useChat({
const [responseStartTime, setResponseStartTime] = useState(
null,
);
+ const [isCompacting, setIsCompacting] = useState(false);
+ const [compactionStartTime, setCompactionStartTime] = useState(
+ null,
+ );
const [inputMode, setInputMode] = useState(true);
const [abortController, setAbortController] =
useState(null);
+ const [compactionAbortController, setCompactionAbortController] =
+ useState(null);
const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState(
// If we're resuming and found a saved session, we're already initialized
// If we're forking and found a session to fork from, we're already initialized
@@ -166,6 +178,22 @@ export function useChat({
// Track interrupted state for resume functionality
const [wasInterrupted, setWasInterrupted] = useState(false);
+ // Track queued messages for immediate display
+ const [queuedMessages, setQueuedMessages] = useState([]);
+
+ // Set up message queue listeners
+ useEffect(() => {
+ const onMessageQueued = (queuedMessage: QueuedMessage) => {
+ setQueuedMessages((prev) => [...prev, queuedMessage]);
+ };
+
+ messageQueue.on("messageQueued", onMessageQueued);
+
+ return () => {
+ messageQueue.off("messageQueued", onMessageQueued);
+ };
+ }, []);
+
// Clean up abort controller on unmount
useEffect(() => {
return () => {
@@ -306,6 +334,23 @@ export function useChat({
setIsWaitingForResponse(false);
setResponseStartTime(null);
setInputMode(true);
+
+ // Check if there are queued messages and process them after a microtask delay
+ // This ensures the GUI state has been updated before processing the next message
+ const queuedMessageData = messageQueue.getNextMessage();
+ if (queuedMessageData) {
+ const { message: latestQueuedMessage, imageMap } = queuedMessageData;
+ logger.debug("processing queued message", { latestQueuedMessage });
+
+ // Clear queued messages from display since they're about to be processed
+ // Note: messageQueue.getNextMessage() already cleared the actual queue
+ setQueuedMessages([]);
+
+ await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
+
+ // Process the queued message - it will handle adding to history and compaction display
+ await processQueuedMessage(latestQueuedMessage, imageMap);
+ }
}
};
@@ -343,12 +388,16 @@ export function useChat({
const handleSlashCommandProcessing = async (
message: string,
): Promise => {
- // Handle slash commands (skip in remote mode except for /exit which we handled above)
- if (isRemoteMode || !assistant) {
+ // Handle slash commands
+ if (!assistant) {
return message;
}
- const commandResult = await handleSlashCommands(message, assistant);
+ const commandResult = await handleSlashCommands(message, assistant, {
+ remoteUrl,
+ isRemoteMode,
+ });
+
if (!commandResult) {
return message;
}
@@ -362,6 +411,9 @@ export function useChat({
setCompactionIndex,
currentSession,
setCurrentSession,
+ setIsCompacting,
+ setCompactionStartTime,
+ setCompactionAbortController,
});
return null;
}
@@ -374,6 +426,7 @@ export function useChat({
onShowModelSelector,
onShowMCPSelector,
onShowSessionSelector,
+ onShowUpdateSelector,
onClear,
});
@@ -398,6 +451,191 @@ export function useChat({
.join("");
};
+ const processMessage = async (
+ message: string,
+ imageMap?: Map,
+ isQueuedMessage: boolean = false,
+ ) => {
+ // Handle special commands
+ const handled = await handleSpecialCommands({
+ message,
+ isRemoteMode,
+ remoteUrl,
+ onShowConfigSelector,
+ exit,
+ onShowDiff,
+ onShowStatusMessage,
+ });
+
+ if (handled) return;
+
+ // Handle shell mode commands (before slash commands)
+ const bashProcessedMessage = await handleBashModeProcessing(message);
+ if (bashProcessedMessage === null) {
+ return; // Bash command was handled and no further processing needed
+ }
+ message = bashProcessedMessage;
+
+ // Handle slash commands (MUST happen before remote message handling)
+ const processedMessage = await handleSlashCommandProcessing(message);
+ if (processedMessage === null) {
+ return; // Command was handled and no further processing needed
+ }
+ message = processedMessage;
+
+ // Track telemetry
+ trackUserMessage(message, model);
+
+ // In remote mode, send message to server instead of processing locally
+ if (isRemoteMode && remoteUrl) {
+ const messageContentString = convertMessageContentToString(message);
+
+ await handleRemoteMessage({
+ remoteUrl,
+ messageContent: messageContentString,
+ });
+ return;
+ }
+
+ // For non-queued messages, format and add to chat history
+ if (isQueuedMessage) {
+ // For queued messages, we need to format and add to history after compaction
+ // First, format the message
+ const formattedQueuedMessage = await formatMessageWithFiles(
+ message,
+ [], // No attached files for queued messages
+ imageMap,
+ );
+
+ // Check if auto-compacting is needed with current history
+ const compactionController = new AbortController();
+ setCompactionAbortController(compactionController);
+ setIsCompacting(true);
+ setCompactionStartTime(Date.now());
+
+ // Add the queued message to queue display during compaction
+ const queuedMessageForDisplay: QueuedMessage = {
+ message,
+ imageMap,
+ timestamp: Date.now(),
+ };
+ setQueuedMessages((prev) => [...prev, queuedMessageForDisplay]);
+
+ let currentChatHistory, currentCompactionIndex;
+ try {
+ const result = await handleAutoCompaction({
+ chatHistory,
+ model,
+ llmApi,
+ compactionIndex,
+ setChatHistory: setChatHistory,
+ setCompactionIndex,
+ abortController: compactionController,
+ });
+ currentChatHistory = result.currentChatHistory;
+ currentCompactionIndex = result.currentCompactionIndex;
+ } catch (error) {
+ // If compaction fails, remove the queued message from display
+ setQueuedMessages((prev) =>
+ prev.filter((msg) => msg !== queuedMessageForDisplay),
+ );
+ throw error; // Re-throw to maintain error handling
+ } finally {
+ setIsCompacting(false);
+ setCompactionStartTime(null);
+ setCompactionAbortController(null);
+ }
+
+ // Add the formatted queued message to history after compaction completes
+ const newHistory = [...currentChatHistory, formattedQueuedMessage];
+ setChatHistory(newHistory);
+
+ // Remove the queued message from display since it's now in chat history
+ setQueuedMessages((prev) =>
+ prev.filter((msg) => msg !== queuedMessageForDisplay),
+ );
+
+ // Execute the streaming response with the updated history
+ await executeStreamingResponse(newHistory, currentCompactionIndex);
+ } else {
+ // Format message with attached files and images
+ logger.debug("Processing message with images", {
+ hasImages: !!(imageMap && imageMap.size > 0),
+ imageCount: imageMap?.size || 0,
+ });
+ const newUserMessage = await formatMessageWithFiles(
+ message,
+ attachedFiles,
+ imageMap,
+ );
+ logger.debug("Message formatted successfully");
+
+ if (attachedFiles.length > 0) {
+ setAttachedFiles([]);
+ }
+
+ // Check if auto-compacting is needed BEFORE adding user message
+ const compactionController = new AbortController();
+ setCompactionAbortController(compactionController);
+ setIsCompacting(true);
+ setCompactionStartTime(Date.now());
+
+ // Add the triggering message to queue display during compaction
+ const compactionQueuedMessage: QueuedMessage = {
+ message,
+ imageMap,
+ timestamp: Date.now(),
+ };
+ setQueuedMessages((prev) => [...prev, compactionQueuedMessage]);
+
+ let currentChatHistory, currentCompactionIndex;
+ try {
+ const result = await handleAutoCompaction({
+ chatHistory,
+ model,
+ llmApi,
+ compactionIndex,
+ setChatHistory: setChatHistory,
+ setCompactionIndex,
+ abortController: compactionController,
+ });
+ currentChatHistory = result.currentChatHistory;
+ currentCompactionIndex = result.currentCompactionIndex;
+ } catch (error) {
+ // If compaction fails, remove the triggering message from queue display
+ setQueuedMessages((prev) =>
+ prev.filter((msg) => msg !== compactionQueuedMessage),
+ );
+ throw error; // Re-throw to maintain error handling
+ } finally {
+ setIsCompacting(false);
+ setCompactionStartTime(null);
+ setCompactionAbortController(null);
+ }
+
+ // Add the formatted user message to history
+ const newHistory = [...currentChatHistory, newUserMessage];
+ setChatHistory(newHistory);
+
+ // Remove the triggering message from queue display since it's now in chat history
+ setQueuedMessages((prev) =>
+ prev.filter((msg) => msg !== compactionQueuedMessage),
+ );
+
+ // Execute the streaming response
+ await executeStreamingResponse(newHistory, currentCompactionIndex);
+ }
+ };
+
+ const processQueuedMessage = async (
+ message: string,
+ imageMap?: Map,
+ ) => {
+ // For queued messages, we can reuse the core message processing logic
+ // by calling the internal processing function directly
+ await processMessage(message, imageMap, true);
+ };
+
const handleUserMessage = async (
message: string,
imageMap?: Map,
@@ -412,80 +650,8 @@ export function useChat({
setWasInterrupted(false);
}
- // Handle special commands
- const handled = await handleSpecialCommands({
- message,
- isRemoteMode,
- remoteUrl,
- onShowConfigSelector,
- exit,
- });
-
- if (handled) return;
-
- // Handle shell mode commands (before slash commands)
- const bashProcessedMessage = await handleBashModeProcessing(message);
- if (bashProcessedMessage === null) {
- return; // Bash command was handled and no further processing needed
- }
- message = bashProcessedMessage;
-
- // Handle slash commands
- const processedMessage = await handleSlashCommandProcessing(message);
- if (processedMessage === null) {
- return; // Command was handled and no further processing needed
- }
- message = processedMessage;
-
- // Track telemetry
- trackUserMessage(message, model);
-
- // Format message with attached files and images
- logger.debug("Processing message with images", {
- hasImages: !!(imageMap && imageMap.size > 0),
- imageCount: imageMap?.size || 0,
- });
- const newUserMessage = await formatMessageWithFiles(
- message,
- attachedFiles,
- imageMap,
- );
- logger.debug("Message formatted successfully");
-
- if (attachedFiles.length > 0) {
- setAttachedFiles([]);
- }
-
- // In remote mode, send message to server instead of processing locally
- if (isRemoteMode && remoteUrl) {
- const messageContentString = convertMessageContentToString(
- newUserMessage.message.content,
- );
-
- await handleRemoteMessage({
- remoteUrl,
- messageContent: messageContentString,
- });
- return;
- }
-
- // Check if auto-compacting is needed BEFORE adding user message
- const { currentChatHistory, currentCompactionIndex } =
- await handleAutoCompaction({
- chatHistory,
- model,
- llmApi,
- compactionIndex,
- setChatHistory: setChatHistory,
- setCompactionIndex,
- });
-
- // Add the formatted user message to history
- const newHistory = [...currentChatHistory, newUserMessage];
- setChatHistory(newHistory);
-
- // Execute the streaming response
- await executeStreamingResponse(newHistory, currentCompactionIndex);
+ // Use the common message processing logic
+ await processMessage(message, imageMap, false);
};
const handleInterrupt = () => {
@@ -504,7 +670,21 @@ export function useChat({
return;
}
- // Local mode: abort the controller
+ // Local mode: abort the appropriate controller
+
+ // If compaction is running, abort compaction
+ if (compactionAbortController && isCompacting) {
+ compactionAbortController.abort();
+ setIsCompacting(false);
+ setCompactionStartTime(null);
+ setCompactionAbortController(null);
+ setInputMode(true);
+ // Clear any queued messages (including the triggering message) when compaction is interrupted
+ setQueuedMessages([]);
+ return;
+ }
+
+ // If response is running, abort response
if (abortController && isWaitingForResponse) {
abortController.abort();
@@ -537,6 +717,8 @@ export function useChat({
additionalRules,
);
setChatHistory(newHistory);
+ // Clear any queued messages when resetting chat
+ setQueuedMessages([]);
};
const handleToolPermissionResponse = async (
@@ -610,10 +792,13 @@ export function useChat({
setChatHistory: setChatHistory,
isWaitingForResponse,
responseStartTime,
+ isCompacting,
+ compactionStartTime,
inputMode,
attachedFiles,
activePermissionRequest,
wasInterrupted,
+ queuedMessages,
handleUserMessage,
handleInterrupt,
handleFileAttached,
diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts
index a9a840184..bf449191b 100644
--- a/extensions/cli/src/ui/hooks/useChat.types.ts
+++ b/extensions/cli/src/ui/hooks/useChat.types.ts
@@ -15,6 +15,7 @@ export interface UseChatProps {
additionalPrompts?: string[];
onShowConfigSelector: () => void;
onShowMCPSelector: () => void;
+ onShowUpdateSelector: () => void;
onShowModelSelector?: () => void;
onShowSessionSelector?: () => void;
onLoginPrompt?: (promptText: string) => Promise;
@@ -23,6 +24,8 @@ export interface UseChatProps {
// Remote mode props
isRemoteMode?: boolean;
remoteUrl?: string;
+ onShowDiff?: (diffContent: string) => void;
+ onShowStatusMessage?: (message: string) => void;
}
export interface AttachedFile {
@@ -57,6 +60,8 @@ export interface SlashCommandResult {
openConfigSelector?: boolean;
openModelSelector?: boolean;
openMcpSelector?: boolean;
+ openUpdateSelector?: boolean;
openSessionSelector?: boolean;
compact?: boolean;
+ diffContent?: string;
}
diff --git a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx
index 06caf3fc9..3f48d16a5 100644
--- a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx
+++ b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx
@@ -4,22 +4,38 @@ import type { ChatHistoryItem } from "../../../../../core/index.js";
import { MemoizedMessage } from "../components/MemoizedMessage.js";
export function useMessageRenderer() {
- const renderMessage = useCallback((item: ChatHistoryItem, index: number) => {
- // Generate a unique key by combining message role, content hash, and timestamp
- // This provides a stable identifier that won't change during re-renders
- const messageContent =
- typeof item.message.content === "string"
- ? item.message.content
- : JSON.stringify(item.message.content);
+ const renderMessage = useCallback(
+ (item: ChatHistoryItem, index: number, allMessages?: ChatHistoryItem[]) => {
+ // Generate a unique key by combining message role, content hash, and timestamp
+ // This provides a stable identifier that won't change during re-renders
+ const messageContent =
+ typeof item.message.content === "string"
+ ? item.message.content
+ : JSON.stringify(item.message.content);
- const toolCallsKey = item.toolCallStates
- ? item.toolCallStates.map((tc) => tc.toolCallId).join("-")
- : "";
+ const toolCallsKey = item.toolCallStates
+ ? item.toolCallStates.map((tc) => tc.toolCallId).join("-")
+ : "";
- const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`;
+ // Check if this is a continuation of the previous message (same role)
+ const previousMessage =
+ allMessages && index > 0 ? allMessages[index - 1] : null;
+ const isContinuation =
+ previousMessage?.message.role === item.message.role;
- return ;
- }, []);
+ const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`;
+
+ return (
+
+ );
+ },
+ [],
+ );
return { renderMessage };
}
diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts
index c5945bbf3..334d23fc3 100644
--- a/extensions/cli/src/ui/hooks/useUserInput.ts
+++ b/extensions/cli/src/ui/hooks/useUserInput.ts
@@ -76,7 +76,7 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
// Handle Ctrl+D to exit
if (key.ctrl && input === "d") {
exit();
- process.exit(0);
+ import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0));
}
// Handle Ctrl+L to refresh screen (clear terminal artifacts)
diff --git a/extensions/cli/src/ui/utils/historySplitting.test.ts b/extensions/cli/src/ui/utils/historySplitting.test.ts
new file mode 100644
index 000000000..f4f860b1c
--- /dev/null
+++ b/extensions/cli/src/ui/utils/historySplitting.test.ts
@@ -0,0 +1,58 @@
+import type { ChatHistoryItem } from "core";
+import { describe, expect, it } from "vitest";
+
+import { splitChatHistory } from "./historySplitting.js";
+
+// Helper to create a mock chat history item
+function createMockChatHistoryItem(
+ content: string,
+ role: "user" | "assistant" = "assistant",
+): ChatHistoryItem {
+ return {
+ message: {
+ role,
+ content,
+ },
+ } as ChatHistoryItem;
+}
+
+describe("messageHistorySplitting", () => {
+ describe("splitChatHistory", () => {
+ it("should split multiple large messages in chat history", () => {
+ const chatHistory = [
+ createMockChatHistoryItem("Short message 1"),
+ createMockChatHistoryItem(
+ Array(30).fill("Long message 1").join("\n\n"),
+ ),
+ createMockChatHistoryItem("Short message 2"),
+ createMockChatHistoryItem(
+ Array(25).fill("Long message 2").join("\n\n"),
+ ),
+ ];
+
+ const result = splitChatHistory(chatHistory, 80);
+
+ // Should have more items than the original (due to splits)
+ expect(result.length).toBeGreaterThan(chatHistory.length);
+
+ // First and third messages should remain unchanged
+ expect(result[0].message.content).toBe("Short message 1");
+ });
+
+ it("should maintain order after splitting", () => {
+ const chatHistory = [
+ createMockChatHistoryItem("First"),
+ createMockChatHistoryItem(Array(30).fill("Long middle").join("\n\n")),
+ createMockChatHistoryItem("Last"),
+ ];
+
+ const result = splitChatHistory(chatHistory, 80);
+
+ // First message should still be first
+ expect(result[0].message.content).toBe("First");
+
+ // Last message should still be last
+ expect(result[result.length - 1].message.content).toBe("Last");
+ });
+ });
+});
diff --git a/extensions/cli/src/ui/utils/historySplitting.ts b/extensions/cli/src/ui/utils/historySplitting.ts
new file mode 100644
index 000000000..c5854746e
--- /dev/null
+++ b/extensions/cli/src/ui/utils/historySplitting.ts
@@ -0,0 +1,170 @@
+import type { ChatHistoryItem } from "core";
+
+import { findLastSafeSplitPoint } from "./messageSplitting.js";
+
+const MAX_HEIGHT_BEFORE_SPLIT = 20;
+
+/**
+ * Splits a chat history item into multiple items if its content is too large.
+ *
+ * This function prevents UI flickering by breaking large messages into manageable chunks.
+ * It only splits at safe markdown boundaries (paragraph breaks: \n\n) to preserve formatting.
+ *
+ * Splitting behavior:
+ * - User messages: Split only when they have natural paragraph breaks (\n\n)
+ * - Assistant messages: Split when content exceeds height threshold
+ * - System messages: Never split
+ * - Messages with tool calls: Never split
+ *
+ * Common use cases:
+ * - User pastes multiple paragraphs of text -> Split at paragraph boundaries
+ * - User writes one long paragraph -> Keep as single message
+ * - Assistant generates long response -> Split at paragraph breaks (\n\n)
+ */
+function splitChatHistoryItem(
+ item: ChatHistoryItem,
+ terminalWidth: number,
+): ChatHistoryItem[] {
+ // Don't split non-text messages or messages with tool calls
+ if (item.toolCallStates?.length || typeof item.message.content !== "string") {
+ return [item];
+ }
+
+ // Don't split system messages
+ if (item.message.role === "system") {
+ return [item];
+ }
+
+ const content = item.message.content;
+
+ if (!shouldSplitContent(content, terminalWidth)) {
+ return [item];
+ }
+
+ return splitContentIntoHistoryItems(item, content, terminalWidth);
+}
+
+/**
+ * Splits content into multiple chat history items at safe markdown boundaries.
+ */
+function splitContentIntoHistoryItems(
+ originalItem: ChatHistoryItem,
+ content: string,
+ terminalWidth: number,
+): ChatHistoryItem[] {
+ const items: ChatHistoryItem[] = [];
+ let remainingContent = content;
+ let itemIndex = 0;
+
+ while (remainingContent.length > 0) {
+ if (!shouldSplitContent(remainingContent, terminalWidth)) {
+ // Remaining content is small enough, add it as the final item
+ if (remainingContent.trim()) {
+ items.push({
+ ...originalItem,
+ message: {
+ ...originalItem.message,
+ content: remainingContent,
+ },
+ });
+ }
+ break;
+ }
+
+ // Find safe split point
+ const splitPoint = findLastSafeSplitPoint(remainingContent);
+
+ if (splitPoint === remainingContent.length) {
+ // No safe split point found, add as single large item
+ if (remainingContent.trim()) {
+ items.push({
+ ...originalItem,
+ message: {
+ ...originalItem.message,
+ content: remainingContent,
+ },
+ });
+ }
+ break;
+ }
+
+ // Split at the safe point
+ const beforeText = remainingContent.slice(0, splitPoint).trim();
+ remainingContent = remainingContent.slice(splitPoint).trim();
+
+ if (beforeText) {
+ items.push({
+ ...originalItem,
+ message: {
+ ...originalItem.message,
+ content: beforeText,
+ },
+ });
+ }
+
+ itemIndex++;
+
+ // Prevent infinite loops
+ if (itemIndex > 50) {
+ console.warn("Message splitting exceeded maximum iterations, stopping");
+ if (remainingContent.trim()) {
+ items.push({
+ ...originalItem,
+ message: {
+ ...originalItem.message,
+ content: remainingContent,
+ },
+ });
+ }
+ break;
+ }
+ }
+
+ return items;
+}
+
+/**
+ * Processes an entire chat history array, splitting large items into multiple items.
+ */
+export function splitChatHistory(
+ chatHistory: ChatHistoryItem[],
+ terminalWidth: number,
+): ChatHistoryItem[] {
+ const result: ChatHistoryItem[] = [];
+
+ for (const item of chatHistory) {
+ const splitItems = splitChatHistoryItem(item, terminalWidth);
+ result.push(...splitItems);
+ }
+
+ return result;
+}
+
+/**
+ * Estimates the height in terminal rows that content will take when rendered.
+ */
+function estimateContentHeight(content: string, terminalWidth: number): number {
+ if (!content) return 0;
+
+ const lines = content.split("\n");
+ let totalHeight = 0;
+
+ for (const line of lines) {
+ if (line.length === 0) {
+ totalHeight += 1; // Empty line
+ } else {
+ // Account for line wrapping
+ totalHeight += Math.ceil(line.length / Math.max(terminalWidth - 2, 40));
+ }
+ }
+
+ return totalHeight;
+}
+
+/**
+ * Determines if content should be split based on its estimated height.
+ */
+function shouldSplitContent(content: string, terminalWidth: number): boolean {
+ const estimatedHeight = estimateContentHeight(content, terminalWidth);
+ return estimatedHeight > MAX_HEIGHT_BEFORE_SPLIT;
+}
diff --git a/extensions/cli/src/ui/utils/messageSplitting.test.ts b/extensions/cli/src/ui/utils/messageSplitting.test.ts
new file mode 100644
index 000000000..b98a549de
--- /dev/null
+++ b/extensions/cli/src/ui/utils/messageSplitting.test.ts
@@ -0,0 +1,54 @@
+/**
+ * @license
+ * Copyright 2025 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * NOTICE: This file has been modified from the original Gemini CLI source
+ * for integration with Continue CLI (cn)
+ */
+
+import { describe, expect, it } from "vitest";
+
+import { findLastSafeSplitPoint } from "./messageSplitting.js";
+
+describe("markdownUtilities", () => {
+ describe("findLastSafeSplitPoint", () => {
+ it("should split at the last double newline if not in a code block", () => {
+ const content = "paragraph1\n\nparagraph2\n\nparagraph3";
+ expect(findLastSafeSplitPoint(content)).toBe(24); // After the second \n\n
+ });
+
+ it("should return content.length if no safe split point is found", () => {
+ const content = "longstringwithoutanysafesplitpoint";
+ expect(findLastSafeSplitPoint(content)).toBe(content.length);
+ });
+
+ it("should prioritize splitting at \n\n over being at the very end of the string if the end is not in a code block", () => {
+ const content = "Some text here.\n\nAnd more text here.";
+ expect(findLastSafeSplitPoint(content)).toBe(17); // after the \n\n
+ });
+
+ it("should return content.length if the only \n\n is inside a code block and the end of content is not", () => {
+ const content = "```\nignore this\n\nnewline\n```KeepThis";
+ expect(findLastSafeSplitPoint(content)).toBe(content.length);
+ });
+
+ it("should correctly identify the last \n\n even if it is followed by text not in a code block", () => {
+ const content =
+ "First part.\n\nSecond part.\n\nThird part, then some more text.";
+ // Split should be after "Second part.\n\n"
+ // "First part.\n\n" is 13 chars. "Second part.\n\n" is 14 chars. Total 27.
+ expect(findLastSafeSplitPoint(content)).toBe(27);
+ });
+
+ it("should return content.length if content is empty", () => {
+ const content = "";
+ expect(findLastSafeSplitPoint(content)).toBe(0);
+ });
+
+ it("should return content.length if content has no newlines and no code blocks", () => {
+ const content = "Single line of text";
+ expect(findLastSafeSplitPoint(content)).toBe(content.length);
+ });
+ });
+});
diff --git a/extensions/cli/src/ui/utils/messageSplitting.ts b/extensions/cli/src/ui/utils/messageSplitting.ts
new file mode 100644
index 000000000..73cdb26c3
--- /dev/null
+++ b/extensions/cli/src/ui/utils/messageSplitting.ts
@@ -0,0 +1,128 @@
+/**
+ * @license
+ * Copyright 2025 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * NOTICE: This file has been modified from the original Gemini CLI source
+ * for integration with Continue CLI (cn)
+ */
+
+/*
+**Background & Purpose:**
+
+The `findSafeSplitPoint` function is designed to address the challenge of displaying or processing large, potentially streaming, pieces of Markdown text. When content (e.g., from an LLM like Gemini) arrives in chunks or grows too large for a single display unit (like a message bubble), it needs to be split. A naive split (e.g., just at a character limit) can break Markdown formatting, especially critical for multi-line elements like code blocks, lists, or blockquotes, leading to incorrect rendering.
+
+This function aims to find an *intelligent* or "safe" index within the provided `content` string at which to make such a split, prioritizing the preservation of Markdown integrity.
+
+**Key Expectations & Behavior (Prioritized):**
+
+1. **No Split if Short Enough:**
+ * If `content.length` is less than or equal to `idealMaxLength`, the function should return `content.length` (indicating no split is necessary for length reasons).
+
+2. **Code Block Integrity (Highest Priority for Safety):**
+ * The function must try to avoid splitting *inside* a fenced code block (i.e., between ` ``` ` and ` ``` `).
+ * If `idealMaxLength` falls within a code block:
+ * The function will attempt to return an index that splits the content *before* the start of that code block.
+ * If a code block starts at the very beginning of the `content` and `idealMaxLength` falls within it (meaning the block itself is too long for the first chunk), the function might return `0`. This effectively makes the first chunk empty, pushing the entire oversized code block to the second part of the split.
+ * When considering splits near code blocks, the function prefers to keep the entire code block intact in one of the resulting chunks.
+
+3. **Markdown-Aware Newline Splitting (If Not Governed by Code Block Logic):**
+ * If `idealMaxLength` does not fall within a code block (or after code block considerations have been made), the function will look for natural break points by scanning backwards from `idealMaxLength`:
+ * **Paragraph Breaks:** It prioritizes splitting after a double newline (`\n\n`), as this typically signifies the end of a paragraph or a block-level element.
+ * **Single Line Breaks:** If no double newline is found in a suitable range, it will look for a single newline (`\n`).
+ * Any newline chosen as a split point must also not be inside a code block.
+
+4. **Fall back to `idealMaxLength`:**
+ * If no "safer" split point (respecting code blocks or finding suitable newlines) is identified before or at `idealMaxLength`, and `idealMaxLength` itself is not determined to be an unsafe split point (e.g., inside a code block), the function may return a length larger than `idealMaxLength`, again it CANNOT break markdown formatting. This could happen with very long lines of text without Markdown block structures or newlines.
+
+**In essence, `findSafeSplitPoint` tries to be a good Markdown citizen when forced to divide content, preferring structural boundaries over arbitrary character limits, with a strong emphasis on not corrupting code blocks.**
+*/
+
+/**
+ * Checks if a given character index within a string is inside a fenced (```) code block.
+ * @param content The full string content.
+ * @param indexToTest The character index to test.
+ * @returns True if the index is inside a code block's content, false otherwise.
+ */
+const isIndexInsideCodeBlock = (
+ content: string,
+ indexToTest: number,
+): boolean => {
+ let fenceCount = 0;
+ let searchPos = 0;
+ while (searchPos < content.length) {
+ const nextFence = content.indexOf("```", searchPos);
+ if (nextFence === -1 || nextFence >= indexToTest) {
+ break;
+ }
+ fenceCount++;
+ searchPos = nextFence + 3;
+ }
+ return fenceCount % 2 === 1;
+};
+
+/**
+ * Finds the starting index of the code block that encloses the given index.
+ * Returns -1 if the index is not inside a code block.
+ * @param content The markdown content.
+ * @param index The index to check.
+ * @returns Start index of the enclosing code block or -1.
+ */
+const findEnclosingCodeBlockStart = (
+ content: string,
+ index: number,
+): number => {
+ if (!isIndexInsideCodeBlock(content, index)) {
+ return -1;
+ }
+ let currentSearchPos = 0;
+ while (currentSearchPos < index) {
+ const blockStartIndex = content.indexOf("```", currentSearchPos);
+ if (blockStartIndex === -1 || blockStartIndex >= index) {
+ break;
+ }
+ const blockEndIndex = content.indexOf("```", blockStartIndex + 3);
+ if (blockStartIndex < index) {
+ if (blockEndIndex === -1 || index < blockEndIndex + 3) {
+ return blockStartIndex;
+ }
+ }
+ if (blockEndIndex === -1) break;
+ currentSearchPos = blockEndIndex + 3;
+ }
+ return -1;
+};
+
+export const findLastSafeSplitPoint = (content: string): number => {
+ const enclosingBlockStart = findEnclosingCodeBlockStart(
+ content,
+ content.length,
+ );
+ if (enclosingBlockStart !== -1) {
+ // The end of the content is contained in a code block. Split right before.
+ return enclosingBlockStart;
+ }
+
+ // Search for the last double newline (\n\n) not in a code block.
+ let searchStartIndex = content.length;
+ while (searchStartIndex >= 0) {
+ const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex);
+ if (dnlIndex === -1) {
+ // No more double newlines found.
+ break;
+ }
+
+ const potentialSplitPoint = dnlIndex + 2;
+ if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
+ return potentialSplitPoint;
+ }
+
+ // If potentialSplitPoint was inside a code block,
+ // the next search should start *before* the \n\n we just found to ensure progress.
+ searchStartIndex = dnlIndex - 1;
+ }
+
+ // If no safe double newline is found, return content.length
+ // to keep the entire content as one piece.
+ return content.length;
+};
diff --git a/extensions/cli/src/util/cli.ts b/extensions/cli/src/util/cli.ts
new file mode 100644
index 000000000..a2b276343
--- /dev/null
+++ b/extensions/cli/src/util/cli.ts
@@ -0,0 +1,11 @@
+/**
+ * Utility functions for CLI operations
+ */
+
+/**
+ * Check if running in headless mode (-p/--print flags)
+ */
+export function isHeadlessMode(): boolean {
+ const args = process.argv.slice(2);
+ return args.includes("-p") || args.includes("--print");
+}
diff --git a/extensions/cli/src/util/exit.ts b/extensions/cli/src/util/exit.ts
new file mode 100644
index 000000000..31ec02652
--- /dev/null
+++ b/extensions/cli/src/util/exit.ts
@@ -0,0 +1,27 @@
+import { sentryService } from "../sentry.js";
+import { telemetryService } from "../telemetry/telemetryService.js";
+
+import { logger } from "./logger.js";
+
+/**
+ * Exit the process after flushing telemetry and error reporting.
+ * Use this instead of process.exit() to avoid losing metrics/logs.
+ */
+export async function gracefulExit(code: number = 0): Promise {
+ try {
+ // Flush metrics (forceFlush + shutdown inside service)
+ await telemetryService.shutdown();
+ } catch (err) {
+ logger.debug("Telemetry shutdown error (ignored)", err as any);
+ }
+
+ try {
+ // Flush Sentry (best effort)
+ await sentryService.flush();
+ } catch (err) {
+ logger.debug("Sentry flush error (ignored)", err as any);
+ }
+
+ // Exit the process
+ process.exit(code);
+}
diff --git a/extensions/cli/src/util/exponentialBackoff.ts b/extensions/cli/src/util/exponentialBackoff.ts
index 1f3ae4e32..926049efa 100644
--- a/extensions/cli/src/util/exponentialBackoff.ts
+++ b/extensions/cli/src/util/exponentialBackoff.ts
@@ -77,10 +77,40 @@ function isConnectionError(errorMessage: string): boolean {
);
}
+/**
+ * Checks if the error indicates a context length issue (non-retryable)
+ */
+export function isContextLengthError(error: any): boolean {
+ const errorMessage = error.message?.toLowerCase() || "";
+ const contextLengthPatterns = [
+ // Anthropic Claude
+ "input length and max_tokens exceed context limit",
+ "decrease input length or max_tokens",
+ // OpenAI
+ "maximum context length",
+ "reduce the length of the messages",
+ // Mistral
+ "tokens in the prompt exceeds",
+ "use a shorter prompt",
+ // Generic patterns
+ "context_length_exceeded",
+ "invalid_request_error",
+ ];
+
+ return contextLengthPatterns.some((pattern) =>
+ errorMessage.includes(pattern),
+ );
+}
+
/**
* Determines if an error is retryable based on the error type and status code
*/
function isRetryableError(error: any): boolean {
+ // Context length errors are never retryable - they need user intervention
+ if (isContextLengthError(error)) {
+ return false;
+ }
+
// Network errors are retryable
if (isNetworkError(error)) {
return true;
diff --git a/extensions/cli/src/util/fileWatcher.test.ts b/extensions/cli/src/util/fileWatcher.test.ts
index 6e8153434..1cff4db80 100644
--- a/extensions/cli/src/util/fileWatcher.test.ts
+++ b/extensions/cli/src/util/fileWatcher.test.ts
@@ -143,6 +143,12 @@ describe("FileWatcher", () => {
watcher.onChange(callback);
watcher.startWatching(tempDir);
+ // If the environment prevents watching (e.g., EMFILE), skip to avoid false negatives
+ const lastError = (watcher as any).getLastErrorCode?.();
+ if (lastError === "EMFILE") {
+ return;
+ }
+
// Wait for watcher to initialize with longer timeout for CI
// Account for the 50ms initialization delay plus extra time for CI
await new Promise((resolve) => setTimeout(resolve, 600));
@@ -155,8 +161,13 @@ describe("FileWatcher", () => {
// Wait for debounce with longer timeout for CI
await new Promise((resolve) => setTimeout(resolve, 500));
- // Should have been called because .js files are not in ignore patterns
- expect(callback).toHaveBeenCalled();
+ // If watchers are active and no EMFILE error occurred, the callback should be called
+ if (
+ (watcher as any).isActive?.() &&
+ (watcher as any).getLastErrorCode?.() === null
+ ) {
+ expect(callback).toHaveBeenCalled();
+ }
});
it("should allow unsubscribing from callbacks", async () => {
diff --git a/extensions/cli/src/util/fileWatcher.ts b/extensions/cli/src/util/fileWatcher.ts
index 7f1dd1d2b..904317e9a 100644
--- a/extensions/cli/src/util/fileWatcher.ts
+++ b/extensions/cli/src/util/fileWatcher.ts
@@ -16,6 +16,7 @@ export class FileWatcher {
private options: Required;
private watchedDirs: Set = new Set();
private isInitializing: boolean = false;
+ private lastErrorCode: string | null = null;
constructor(options: FileWatcherOptions = {}) {
this.options = {
@@ -112,19 +113,26 @@ export class FileWatcher {
}
private setupWatcher(dirPath: string, depth: number): void {
- const watcher = fs.watch(
- dirPath,
- { persistent: false },
- (eventType, filename) => {
- this.handleFileChange(eventType, filename, dirPath, depth);
- },
- );
+ try {
+ const watcher = fs.watch(
+ dirPath,
+ { persistent: false },
+ (eventType, filename) => {
+ this.handleFileChange(eventType, filename, dirPath, depth);
+ },
+ );
- watcher.on("error", (error) => {
- console.error(`File watcher error for ${dirPath}:`, error);
- });
+ watcher.on("error", (error: any) => {
+ this.lastErrorCode = error?.code || null;
+ console.error(`File watcher error for ${dirPath}:`, error);
+ });
- this.watchers.push(watcher);
+ this.watchers.push(watcher);
+ } catch (error: any) {
+ // Gracefully handle environments that restrict fs.watch (e.g., low descriptor limits)
+ this.lastErrorCode = error?.code || null;
+ console.error(`Failed to create watcher for ${dirPath}:`, error);
+ }
}
private watchSubdirectories(dirPath: string, depth: number): void {
@@ -217,6 +225,15 @@ export class FileWatcher {
this.stopWatching();
this.callbacks.clear();
}
+
+ // Expose watcher health for tests and diagnostics
+ public isActive(): boolean {
+ return this.watchers.length > 0;
+ }
+
+ public getLastErrorCode(): string | null {
+ return this.lastErrorCode;
+ }
}
// Singleton instance for the entire application
diff --git a/extensions/cli/src/util/git.ts b/extensions/cli/src/util/git.ts
index 66d71f47f..e2602a3c6 100644
--- a/extensions/cli/src/util/git.ts
+++ b/extensions/cli/src/util/git.ts
@@ -1,4 +1,8 @@
-import { execSync } from "child_process";
+import { exec, execSync } from "child_process";
+import { promisify } from "util";
+
+const execAsync = promisify(exec);
+const LARGE_STDIO_BUFFER_BYTES = 10 * 1024 * 1024; // bump buffer for large git output
/**
* Get the git remote URL for the current repository
@@ -57,6 +61,13 @@ export function isGitHubActions(): boolean {
return process.env.GITHUB_ACTIONS === "true";
}
+/**
+ * Check if running in Continue remote agents
+ */
+export function isContinueRemoteAgent(): boolean {
+ return process.env.CONTINUE_REMOTE === "true";
+}
+
/**
* Get repository URL from GitHub Actions environment variables
* @returns GitHub repository URL or null if not available
@@ -103,3 +114,49 @@ export function getRepoUrl(): string {
const url = remoteUrl || process.cwd();
return url.endsWith(".git") ? url.slice(0, -4) : url;
}
+
+export interface GitDiffSnapshot {
+ diff: string;
+ repoFound: boolean;
+}
+
+function isExecError(
+ error: unknown,
+): error is { code?: number; stdout?: string } {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ ("code" in error || "stdout" in error)
+ );
+}
+
+export async function getGitDiffSnapshot(): Promise {
+ try {
+ await execAsync("git rev-parse --git-dir", {
+ maxBuffer: LARGE_STDIO_BUFFER_BYTES,
+ });
+ } catch (error) {
+ if (isExecError(error) && error.code === 128) {
+ return { diff: "", repoFound: false };
+ }
+ throw error;
+ }
+
+ try {
+ const { stdout } = await execAsync("git diff main", {
+ maxBuffer: LARGE_STDIO_BUFFER_BYTES,
+ });
+ return { diff: stdout, repoFound: true };
+ } catch (error) {
+ if (isExecError(error)) {
+ if (error.code === 1 && error.stdout) {
+ return { diff: error.stdout, repoFound: true };
+ }
+
+ if (error.code === 128) {
+ return { diff: "", repoFound: false };
+ }
+ }
+ throw error;
+ }
+}
diff --git a/extensions/cli/src/util/prompt.test.ts b/extensions/cli/src/util/prompt.test.ts
new file mode 100644
index 000000000..be758e11a
--- /dev/null
+++ b/extensions/cli/src/util/prompt.test.ts
@@ -0,0 +1,277 @@
+import * as readline from "readline";
+
+import {
+ describe,
+ expect,
+ it,
+ vi,
+ beforeEach,
+ afterEach,
+ MockInstance,
+} from "vitest";
+
+// Mock readline module
+vi.mock("readline", () => ({
+ createInterface: vi.fn(),
+}));
+
+import { question, questionWithChoices } from "./prompt.js";
+
+describe("prompt utilities", () => {
+ let mockInterface: any;
+ let consoleLogSpy: MockInstance;
+ let processExitSpy: MockInstance;
+
+ beforeEach(() => {
+ // Create a mock readline interface
+ mockInterface = {
+ question: vi.fn(),
+ close: vi.fn(),
+ on: vi.fn(),
+ };
+
+ // Mock readline.createInterface to return our mock interface
+ (readline.createInterface as any).mockReturnValue(mockInterface);
+
+ // Mock console.log for limit messages
+ consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+
+ // Mock process.exit
+ processExitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
+ throw new Error("Process exit");
+ }) as any);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ consoleLogSpy.mockRestore();
+ processExitSpy.mockRestore();
+ });
+
+ describe("question", () => {
+ it("should return user input", async () => {
+ const promptText = "What is your name? ";
+ const userInput = "John Doe";
+
+ // Setup mock to call the callback with user input
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(userInput), 0);
+ },
+ );
+
+ const result = await question(promptText);
+
+ expect(mockInterface.question).toHaveBeenCalledWith(
+ promptText,
+ expect.any(Function),
+ );
+ expect(mockInterface.close).toHaveBeenCalled();
+ expect(result).toBe(userInput);
+ });
+
+ it("should handle empty input", async () => {
+ const promptText = "Enter something: ";
+
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(""), 0);
+ },
+ );
+
+ const result = await question(promptText);
+
+ expect(result).toBe("");
+ });
+
+ it("should handle special characters in input", async () => {
+ const promptText = "Enter special chars: ";
+ const userInput = "!@#$%^&*()_+-=[]{}|;':\",./<>?";
+
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(userInput), 0);
+ },
+ );
+
+ const result = await question(promptText);
+
+ expect(result).toBe(userInput);
+ });
+
+ it.skip("should handle SIGINT (Ctrl+C) by exiting process", async () => {
+ const promptText = "Enter something: ";
+ let sigintHandler: (() => void) | null = null;
+
+ // Setup mock to capture SIGINT handler
+ mockInterface.on.mockImplementation(
+ (event: string, handler: () => void) => {
+ if (event === "SIGINT") {
+ sigintHandler = handler;
+ }
+ return mockInterface;
+ },
+ );
+
+ // Setup question mock that doesn't resolve immediately
+ mockInterface.question.mockImplementation(() => {
+ // Trigger SIGINT after question is called
+ setTimeout(() => {
+ if (sigintHandler) {
+ sigintHandler();
+ }
+ }, 10);
+ });
+
+ // The promise should reject when SIGINT is triggered
+ await expect(question(promptText)).rejects.toThrow("Process exit");
+ expect(processExitSpy).toHaveBeenCalledWith(0);
+ });
+ });
+
+ describe("questionWithChoices", () => {
+ it("should accept valid choice", async () => {
+ const promptText = "Choose (1): ";
+ const choices = ["1", "2", "3"];
+ const userChoice = "2";
+
+ mockInterface.question.mockImplementationOnce(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(userChoice), 0);
+ },
+ );
+
+ const result = await questionWithChoices(promptText, choices);
+ expect(result).toBe(userChoice);
+ });
+
+ it("should use default choice when empty input is provided", async () => {
+ const promptText = "Choose (1): ";
+ const choices = ["1", "2", "3"];
+ const defaultChoice = "1";
+
+ mockInterface.question.mockImplementationOnce(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(""), 0);
+ },
+ );
+
+ const result = await questionWithChoices(
+ promptText,
+ choices,
+ defaultChoice,
+ );
+ expect(result).toBe(defaultChoice);
+ });
+
+ it("should reject invalid choice and ask again", async () => {
+ const promptText = "Choose (1 or 2): ";
+ const choices = ["1", "2"];
+ const limitMessage = "Please enter 1 or 2";
+
+ let callCount = 0;
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => {
+ if (callCount === 0) {
+ callCount++;
+ callback("3"); // Invalid choice
+ } else {
+ callback("1"); // Valid choice
+ }
+ }, 0);
+ },
+ );
+
+ const result = await questionWithChoices(
+ promptText,
+ choices,
+ undefined,
+ limitMessage,
+ );
+ expect(result).toBe("1");
+ expect(consoleLogSpy).toHaveBeenCalledWith(limitMessage);
+ });
+
+ it("should handle multiple invalid attempts before valid choice", async () => {
+ const promptText = "Choose: ";
+ const choices = ["yes", "no"];
+ const limitMessage = "Invalid choice";
+
+ let callCount = 0;
+ const invalidAnswers = ["maybe", "perhaps"];
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => {
+ if (callCount < invalidAnswers.length) {
+ callback(invalidAnswers[callCount++]);
+ } else {
+ callback("yes");
+ }
+ }, 0);
+ },
+ );
+
+ const result = await questionWithChoices(
+ promptText,
+ choices,
+ undefined,
+ limitMessage,
+ );
+ expect(result).toBe("yes");
+ expect(consoleLogSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it("should not show limit message when none provided", async () => {
+ const promptText = "Choose: ";
+ const choices = ["a", "b"];
+
+ let callCount = 0;
+ mockInterface.question.mockImplementation(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => {
+ if (callCount === 0) {
+ callCount++;
+ callback("c"); // Invalid
+ } else {
+ callback("a"); // Valid
+ }
+ }, 0);
+ },
+ );
+
+ const result = await questionWithChoices(promptText, choices);
+ expect(result).toBe("a");
+ expect(consoleLogSpy).not.toHaveBeenCalled();
+ });
+
+ it("should handle empty string as valid choice", async () => {
+ const promptText = "Press Enter to continue or type 'cancel': ";
+ const choices = ["", "cancel"];
+
+ mockInterface.question.mockImplementationOnce(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(""), 0);
+ },
+ );
+
+ const result = await questionWithChoices(promptText, choices);
+ expect(result).toBe("");
+ });
+
+ it("should handle choice with spaces", async () => {
+ const promptText = "Choose an option: ";
+ const choices = ["option one", "option two", "option three"];
+ const userChoice = "option two";
+
+ mockInterface.question.mockImplementationOnce(
+ (prompt: string, callback: (answer: string) => void) => {
+ setTimeout(() => callback(userChoice), 0);
+ },
+ );
+
+ const result = await questionWithChoices(promptText, choices);
+ expect(result).toBe(userChoice);
+ });
+ });
+});
diff --git a/extensions/cli/src/util/prompt.ts b/extensions/cli/src/util/prompt.ts
new file mode 100644
index 000000000..a691f89f4
--- /dev/null
+++ b/extensions/cli/src/util/prompt.ts
@@ -0,0 +1,60 @@
+import * as readline from "readline";
+
+/**
+ * Creates a promise-based question prompt using readline
+ * Properly handles backspace and Ctrl+C
+ */
+export function question(prompt: string): Promise {
+ return new Promise((resolve) => {
+ const rl = readline.createInterface({
+ input: process.stdin,
+ output: process.stdout,
+ terminal: true,
+ });
+
+ // Handle Ctrl+C properly
+ rl.on("SIGINT", () => {
+ console.log("\n");
+ rl.close();
+ process.exit(0);
+ });
+
+ rl.question(prompt, (answer) => {
+ rl.close();
+ resolve(answer);
+ });
+ });
+}
+
+/**
+ * Creates a prompt with limited choices
+ * @param prompt The prompt to display
+ * @param choices Array of valid choices
+ * @param defaultChoice Default choice if user presses enter
+ * @param limitMessage Message to show when invalid choice is entered
+ */
+export async function questionWithChoices(
+ prompt: string,
+ choices: string[],
+ defaultChoice?: string,
+ limitMessage?: string,
+): Promise {
+ while (true) {
+ const answer = await question(prompt);
+
+ // Handle default choice
+ if (answer === "" && defaultChoice !== undefined) {
+ return defaultChoice;
+ }
+
+ // Check if answer is valid
+ if (choices.includes(answer)) {
+ return answer;
+ }
+
+ // Show limit message if provided
+ if (limitMessage) {
+ console.log(limitMessage);
+ }
+ }
+}
diff --git a/extensions/cli/src/util/tokenizer.contextValidation.test.ts b/extensions/cli/src/util/tokenizer.contextValidation.test.ts
new file mode 100644
index 000000000..79377ab48
--- /dev/null
+++ b/extensions/cli/src/util/tokenizer.contextValidation.test.ts
@@ -0,0 +1,62 @@
+import { ModelConfig } from "@continuedev/config-yaml";
+import { describe, expect, it } from "vitest";
+
+import { validateContextLength } from "./tokenizer.js";
+
+describe("validateContextLength", () => {
+ const createMockModel = (
+ contextLength: number,
+ maxTokens?: number,
+ ): ModelConfig => ({
+ name: "test-model",
+ model: "test",
+ provider: "openai",
+ defaultCompletionOptions: {
+ contextLength,
+ maxTokens,
+ },
+ });
+
+ const createMockHistory = (messageCount: number, contentLength = 100) => {
+ return Array.from({ length: messageCount }, (_, i) => ({
+ message: {
+ role: "user" as const,
+ content: "x".repeat(contentLength), // Roughly contentLength/4 tokens
+ },
+ contextItems: [],
+ }));
+ };
+
+ it("should pass validation when within context limits", () => {
+ const model = createMockModel(1000, 200);
+ const chatHistory = createMockHistory(5, 40); // ~50 tokens total
+
+ const result = validateContextLength(chatHistory, model);
+
+ expect(result.isValid).toBe(true);
+ expect(result.error).toBeUndefined();
+ });
+
+ it("should fail validation when input + maxTokens exceeds context limit", () => {
+ const model = createMockModel(1000, 800);
+ const chatHistory = createMockHistory(20, 100); // ~500+ tokens
+
+ const result = validateContextLength(chatHistory, model);
+
+ expect(result.isValid).toBe(false);
+ expect(result.error).toContain("Context length exceeded");
+ expect(result.error).toContain("input");
+ expect(result.error).toContain("max_tokens");
+ expect(result.error).toContain("context_limit");
+ });
+
+ it("should handle large models with appropriate scaling", () => {
+ const model = createMockModel(200_000, 64_000); // Claude-like model
+ const chatHistory = createMockHistory(100, 1000); // Large conversation
+
+ const result = validateContextLength(chatHistory, model);
+
+ expect(result.contextLimit).toBe(200_000);
+ expect(result.maxTokens).toBe(64_000);
+ });
+});
diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts
index ac24a56a6..1ceccafe6 100644
--- a/extensions/cli/src/util/tokenizer.test.ts
+++ b/extensions/cli/src/util/tokenizer.test.ts
@@ -78,14 +78,14 @@ describe("tokenizer", () => {
role: "user",
content: [
{ type: "text", text: "Hello" }, // 5 chars -> ~2 tokens
- { type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +85 tokens
+ { type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +1024 tokens
],
},
contextItems: [],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
- expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens
+ expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens
});
it("should count tokens for tool calls", () => {
diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts
index 229e5dfef..df9754967 100644
--- a/extensions/cli/src/util/tokenizer.ts
+++ b/extensions/cli/src/util/tokenizer.ts
@@ -47,7 +47,7 @@ export function countChatHistoryItemTokens(
// Images and other content types have their own token costs
// but we'll use a rough estimate for now
if (part.type === "imageUrl") {
- tokenCount += 85; // Rough estimate for image tokens
+ tokenCount += 1024; // Rough estimate for image tokens
}
}
}
@@ -192,3 +192,46 @@ export function getAutoCompactMessage(model: ModelConfig): string {
const limit = getModelContextLimit(model);
return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`;
}
+
+/**
+ * Validates that the input tokens + max_tokens don't exceed context limit
+ * @param chatHistory The chat history to validate
+ * @param model The model configuration
+ * @returns Validation result with error details if invalid
+ */
+export function validateContextLength(
+ chatHistory: ChatHistoryItem[],
+ model: ModelConfig,
+): {
+ isValid: boolean;
+ error?: string;
+ inputTokens?: number;
+ contextLimit?: number;
+ maxTokens?: number;
+} {
+ const inputTokens = countChatHistoryTokens(chatHistory);
+ const contextLimit = getModelContextLimit(model);
+ const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
+
+ // If maxTokens is not set, use 35% default reservation for output
+ const reservedForOutput =
+ maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
+ const totalRequired = inputTokens + reservedForOutput;
+
+ if (totalRequired > contextLimit) {
+ return {
+ isValid: false,
+ error: `Context length exceeded: input (${inputTokens.toLocaleString()}) + max_tokens (${reservedForOutput.toLocaleString()}) = ${totalRequired.toLocaleString()} > context_limit (${contextLimit.toLocaleString()})`,
+ inputTokens,
+ contextLimit,
+ maxTokens: reservedForOutput,
+ };
+ }
+
+ return {
+ isValid: true,
+ inputTokens,
+ contextLimit,
+ maxTokens: reservedForOutput,
+ };
+}
diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore
index 147aaa022..9619f5d1f 100644
--- a/extensions/intellij/.gitignore
+++ b/extensions/intellij/.gitignore
@@ -5,5 +5,5 @@ src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json
video
.intellijPlatform
-src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
-!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json
\ No newline at end of file
+src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/*
+!src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/config.json
\ No newline at end of file
diff --git a/extensions/intellij/.run/Run Test IDE.run.xml b/extensions/intellij/.run/Run Test IDE.run.xml
deleted file mode 100644
index 94ab5809f..000000000
--- a/extensions/intellij/.run/Run Test IDE.run.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- true
- true
- false
- false
-
-
-
-
-
\ No newline at end of file
diff --git a/extensions/intellij/.run/Run e2e tests.run.xml b/extensions/intellij/.run/Run e2e tests.run.xml
deleted file mode 100644
index 2280aece0..000000000
--- a/extensions/intellij/.run/Run e2e tests.run.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md
index fc1fdaa24..c9d05b502 100644
--- a/extensions/intellij/CONTRIBUTING.md
+++ b/extensions/intellij/CONTRIBUTING.md
@@ -179,55 +179,29 @@ This will generate a .zip file in `./build/distributions` with the version defin
## Testing
-### e2e testing
+Test commands:
-#### Overview
+- `./gradlew test` - to run **unit tests**
+- `./gradlew testIntegration` - to run **e2e tests**
-The e2e tests are written using [intellij-ui-test-robot](`https://github.com/JetBrains/intellij-ui-test-robot`). The
-README for this project has a lot of helpful info on how to use the library.
+### About e2e tests
-Note that these tests fully take control of your mouse while executing.
+The e2e tests are written using [intellij-ide-starter](https://github.com/JetBrains/intellij-ide-starter).
+The first run of the e2e tests may take a while because the required IDE needs
+to be downloaded. Note that these tests
+fully take control of your mouse while executing.
#### Setup
If you are on macOS, you'll need to give IntelliJ permission to control your computer in order to run the e2e tests.
-Open _System Settings_ and select `Privacy & Security` -> `Accessibility` and toggle the switch for IntelliJ.
+Open `System Settings > Privacy & Security > Accessibility` and toggle the switch for IntelliJ.
-#### Running the tests
+#### Working with Intellij IDE Starter
-Instantiate the test IDE as a background task:
+The testing platform provides a rich DSL for most UI components in IntelliJ. However, if you want to interact with a
+custom element, you can define your own XPath selector.
-```sh
-./gradlew clean runIdeForUiTests &
-```
-
-Once the IDE has loaded, you can run the tests. Note that you need to have the test IDE focused in order for the tests
-to run.
-
-```sh
-./gradlew test
-```
-
-Run a single test
-
-```sh
-./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
-```
-
-#### Identifying selectors
-
-While the `runIdeForUiTests` task is running, you can visit the following URL
-to view the UI hierarchy of the running IDE:
-
-
-
-#### Rebuilding the extension
-
-To rebuild the extension with the latest source code, run the following:
-
-```sh
-./gradlew buildPlugin
-```
-
-This will update the contents of the extension that is loaded into the test IDE from
-`build/idea-sandbox/plugins-uiTest/continue-intellij-extension`
+To do this, run an e2e test and visit [localhost:63343/api/remote-driver/](http://localhost:63343/api/remote-driver/) to
+view an HTML representation of the IDE's Swing component tree.
+See [Integration Tests](https://plugins.jetbrains.com/docs/intellij/integration-tests-ui.html#searching-components) for
+more details about this workflow.
diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts
index 49f4d1f2d..86231350f 100644
--- a/extensions/intellij/build.gradle.kts
+++ b/extensions/intellij/build.gradle.kts
@@ -1,17 +1,17 @@
import org.jetbrains.changelog.markdownToHTML
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
+import org.gradle.kotlin.dsl.intellijPlatform
fun environment(key: String) = providers.environmentVariable(key)
-val remoteRobotVersion = "0.11.23"
val platformVersion: String by project
val pluginGroup: String by project
val pluginVersion: String by project
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
plugins {
- kotlin("jvm") version "1.9.22"
+ kotlin("jvm") version "2.1.0"
id("org.jetbrains.intellij.platform") version "2.7.2"
id("org.jetbrains.changelog") version "2.1.2"
id("org.jetbrains.qodana") version "0.1.13"
@@ -28,17 +28,28 @@ repositories {
}
}
+sourceSets {
+ val testIntegration = create("testIntegration")
+ testIntegration.apply {
+ compileClasspath += sourceSets.main.get().output
+ runtimeClasspath += sourceSets.main.get().output
+ }
+}
+
+val testIntegrationImplementation: Configuration by configurations.getting {
+ extendsFrom(configurations.testImplementation.get())
+}
+
dependencies {
intellijPlatform {
- create("IC", platformVersion)
+ intellijIdeaCommunity(platformVersion)
plugins(listOf("org.jetbrains.plugins.terminal:241.14494.150"))
testFramework(TestFrameworkType.Platform)
+ testFramework(TestFrameworkType.Starter, "243.21565.193", configurationName = "testIntegrationImplementation")
}
implementation("com.posthog.java:posthog:1.2.0")
testImplementation("junit:junit:4.13.2")
- testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
- testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
testImplementation("io.mockk:mockk:1.14.2") {
// this transitive dependency (1.6.4) conflicts with built-in version (1.7.3)
// otherwise e2e tests (runIdeForUiTests) will have linkage errors
@@ -47,6 +58,10 @@ dependencies {
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
+
+ testIntegrationImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
+ testIntegrationImplementation("org.kodein.di:kodein-di-jvm:7.20.2")
+ testIntegrationImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.10.1")
}
kotlin {
@@ -88,36 +103,6 @@ qodana {
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
}
-intellijPlatformTesting {
- runIde {
- register("runIdeForUiTests") {
- task {
- environment(
- "CONTINUE_GLOBAL_DIR",
- "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
- )
- jvmArgumentProviders += CommandLineArgumentProvider {
- listOf(
- "-Drobot-server.port=8082",
- "-Dide.mac.message.dialogs.as.sheets=false",
- "-Djb.privacy.policy.text=",
- "-Djb.consents.confirmation.enabled=false",
- "-Dide.mac.file.chooser.native=false",
- "-DjbScreenMenuBar.enabled=false",
- "-Dapple.laf.useScreenMenuBar=false",
- "-Didea.trust.all.projects=true",
- "-Dide.show.tips.on.startup.default.value=false",
- "-Dide.browser.jcef.sandbox.enable=false"
- )
- }
- }
- plugins {
- robotServerPlugin()
- }
- }
- }
-}
-
tasks {
withType {
from("../../binary/bin") {
@@ -142,6 +127,17 @@ tasks {
test {
useJUnitPlatform()
+ environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/test-continue")
jvmArgumentProviders += CommandLineArgumentProvider { listOf("-Dide.browser.jcef.sandbox.enable=false") }
}
}
+
+val testIntegration = task("testIntegration") {
+ val integrationTestSourceSet = sourceSets.getByName("testIntegration")
+ testClassesDirs = integrationTestSourceSet.output.classesDirs
+ classpath = integrationTestSourceSet.runtimeClasspath
+ systemProperty("CONTINUE_PLUGIN_DIR", tasks.prepareSandbox.get().pluginDirectory.get().asFile)
+ environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue")
+ useJUnitPlatform()
+ dependsOn(tasks.prepareSandbox)
+}
diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties
index e22fce5dc..92258d32c 100644
--- a/extensions/intellij/gradle.properties
+++ b/extensions/intellij/gradle.properties
@@ -1,5 +1,5 @@
pluginGroup=com.github.continuedev.continueintellijextension
-pluginVersion=1.0.42
+pluginVersion=1.0.45
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/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
index 05aa69bb6..d28d8258a 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
@@ -61,26 +61,13 @@ class RejectDiffAction : AnAction() {
class FocusContinueInputWithoutClearAction : ContinueToolbarAction() {
override fun toolbarActionPerformed(project: Project) {
- project.getBrowser()?.sendToWebview("focusContinueInputWithoutClear")
- project.getBrowser()?.focusOnInput()
+ FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithoutClear")
}
}
class FocusContinueInputAction : ContinueToolbarAction() {
- override fun toolbarActionPerformed(project: Project) =
- focusContinueInput(project)
-
- companion object {
- fun focusContinueInput(project: Project?) {
- val browser = project?.getBrowser()
- ?: return
- browser.sendToWebview("focusContinueInputWithNewSession")
- browser.focusOnInput()
- val rif = EditorUtils.getEditor(project)?.getHighlightedRIF()
- ?: return
- val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents))
- browser.sendToWebview("highlightedCode", code)
- }
+ override fun toolbarActionPerformed(project: Project) {
+ FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithNewSession")
}
}
@@ -115,5 +102,16 @@ class OpenLogsAction : AnAction() {
}
}
-
+object FocusActionUtil {
+ fun sendHighlightedCodeWithMessageToWebview(project: Project?, messageType: String) {
+ val browser = project?.getBrowser()
+ ?: return
+ browser.sendToWebview(messageType)
+ browser.focusOnInput()
+ val rif = EditorUtils.getEditor(project)?.getHighlightedRIF()
+ ?: return
+ val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents))
+ browser.sendToWebview("highlightedCode", code)
+ }
+}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt
index 4eae86f8d..6fbb2fbee 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt
@@ -16,7 +16,7 @@ class ContinueCompletionService(private val project: Project) : CompletionServic
override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? {
val requestInput = getCompletionInput(uuid, url, line, column)
val modelTimeout = project.service().fetchModelTimeoutOrNull() ?: 1000.0
- return withTimeoutOrNull(modelTimeout.milliseconds) {
+ return withTimeoutOrNull(modelTimeout.milliseconds * 3) {
suspendCancellableCoroutine { continuation ->
project.service().coreMessenger?.request(
"autocomplete/complete",
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 15d131f92..63484d9eb 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
@@ -146,6 +146,7 @@ class MessageTypes {
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
+ "process/killTerminalProcess"
)
}
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
index c0cadd26a..a5ae5eb67 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
@@ -46,7 +46,7 @@ class ApplyToFileHandler(
}
// Handle search/replace mode
- if (params.isSearchReplace == true) {
+ if (params.isSearchAndReplace == true) {
handleSearchReplace(editorUtils)
return
}
@@ -91,7 +91,8 @@ class ApplyToFileHandler(
highlighted = currentContent, // Current file content
suffix = "", // No suffix since we're rewriting the whole file
modelTitle = null, // No model needed for search/replace instant apply
- includeRulesInSystemMessage = false // No LLM involved, just diff generation
+ includeRulesInSystemMessage = false, // No LLM involved, just diff generation
+ isApply = true
)
}
@@ -145,7 +146,7 @@ class ApplyToFileHandler(
// Stream the diffs
diffStreamHandler.streamDiffLinesToEditor(
- prompt, prefix, highlighted, suffix, llmTitle, false
+ prompt, prefix, highlighted, suffix, llmTitle, false, true
)
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
index ba1f4a571..97230ebdb 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
@@ -45,6 +45,76 @@ class IntelliJIDE(
private val continuePluginService: ContinuePluginService,
) : IDE {
+
+ // Security-focused ignore patterns - should always be excluded for security reasons
+ private val DEFAULT_SECURITY_IGNORE_FILETYPES = listOf(
+ // Environment and configuration files with secrets
+ "*.env", "*.env.*", ".env*", "config.json", "config.yaml", "config.yml",
+ "settings.json", "appsettings.json", "appsettings.*.json",
+
+ // Certificate and key files
+ "*.key", "*.pem", "*.p12", "*.pfx", "*.crt", "*.cer", "*.jks",
+ "*.keystore", "*.truststore",
+
+ // Database files that may contain sensitive data
+ "*.db", "*.sqlite", "*.sqlite3", "*.mdb", "*.accdb",
+
+ // Credential and secret files
+ "*.secret", "*.secrets", "credentials", "credentials.*", "auth.json",
+ "token", "token.*", "*.token",
+
+ // Backup files that might contain sensitive data
+ "*.bak", "*.backup", "*.old", "*.orig",
+
+ // Docker secrets
+ "docker-compose.override.yml", "docker-compose.override.yaml",
+
+ // SSH and GPG
+ "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "*.ppk", "*.gpg"
+ )
+
+ private val DEFAULT_SECURITY_IGNORE_DIRS = listOf(
+ // Environment and configuration directories
+ ".env/", "env/",
+
+ // Cloud provider credential directories
+ ".aws/", ".gcp/", ".azure/", ".kube/", ".docker/",
+
+ // Secret directories
+ "secrets/", ".secrets/", "private/", ".private/", "certs/",
+ "certificates/", "keys/", ".ssh/", ".gnupg/", ".gpg/",
+
+ // Temporary directories that might contain sensitive data
+ "tmp/secrets/", "temp/secrets/", ".tmp/"
+ )
+
+ // Additional non-security patterns for general indexing exclusion
+ private val ADDITIONAL_SEARCH_IGNORE_FILETYPES = listOf(
+ "*.DS_Store", "*-lock.json", "*.lock", "*.log", "*.ttf", "*.png",
+ "*.jpg", "*.jpeg", "*.gif", "*.mp4", "*.svg", "*.ico", "*.pdf",
+ "*.zip", "*.gz", "*.tar", "*.dmg", "*.tgz", "*.rar", "*.7z",
+ "*.exe", "*.dll", "*.obj", "*.o", "*.o.d", "*.a", "*.lib",
+ "*.so", "*.dylib", "*.ncb", "*.sdf", "*.woff", "*.woff2",
+ "*.eot", "*.cur", "*.avi", "*.mpg", "*.mpeg", "*.mov", "*.mp3",
+ "*.mkv", "*.webm", "*.jar", "*.onnx", "*.parquet", "*.pqt",
+ "*.wav", "*.webp", "*.wasm", "*.plist", "*.profraw", "*.gcda",
+ "*.gcno", "go.sum", "*.gitignore", "*.gitkeep", "*.continueignore",
+ "*.csv", "*.uasset", "*.pdb", "*.bin", "*.pag", "*.swp", "*.jsonl"
+ )
+
+ private val ADDITIONAL_SEARCH_IGNORE_DIRS = listOf(
+ ".git/", ".svn/", "node_modules/", "dist/", "build/", "Build/",
+ "target/", "out/", "bin/", ".pytest_cache/", ".vscode-test/",
+ "__pycache__/", "site-packages/", ".gradle/", ".mvn/", ".cache/",
+ "gems/", "vendor/", ".venv/", "venv/", ".vscode/", ".idea/", ".vs/",
+ ".continue/"
+ )
+
+ // Combined patterns for use in ripgrep
+ private val DEFAULT_IGNORES = DEFAULT_SECURITY_IGNORE_FILETYPES +
+ DEFAULT_SECURITY_IGNORE_DIRS +
+ ADDITIONAL_SEARCH_IGNORE_FILETYPES +
+ ADDITIONAL_SEARCH_IGNORE_DIRS
private val gitService = GitService(project, continuePluginService)
private val fileUtils = FileUtils(project)
@@ -335,6 +405,9 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
+ // Create a single combined ignore pattern using glob brace expansion
+ val defaultIgnorePattern = DEFAULT_IGNORES.joinToString(",") { it }
+
var commandArgs = mutableListOf(
ripgrep,
"--files",
@@ -343,7 +416,9 @@ class IntelliJIDE(
"--ignore-file",
".continueignore",
"--ignore-file",
- ".gitignore"
+ ".gitignore",
+ "--glob",
+ "!{${defaultIgnorePattern}}"
)
if (maxResults != null) {
commandArgs.add("--max-count")
@@ -370,6 +445,9 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
+ // Create a single combined ignore pattern for ripgrep
+ val defaultIgnorePattern = DEFAULT_IGNORES.joinToString(",") { it }
+
val commandArgs = mutableListOf(
ripgrep,
"-i",
@@ -379,7 +457,9 @@ class IntelliJIDE(
".gitignore",
"-C",
"2",
- "--heading"
+ "--heading",
+ "--glob",
+ "!{${defaultIgnorePattern}}" // Exclude all default ignores using brace expansion
)
// Conditionally add maxResults flag
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt
index ba351ab02..ea7accbb7 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt
@@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FileStats
import com.github.continuedev.continueintellijextension.FileType
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
+import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
@@ -24,10 +25,11 @@ class FileUtils(
fun writeFile(fileUri: String, content: String) {
val path = VfsUtilCore.urlToPath(fileUri)
val pathDirectory = VfsUtil.getParentDir(path)
- ?: return
+ ?: return LOG.warn("Parent directory is null for $path")
val vfsDirectory = VfsUtil.createDirectories(pathDirectory)
+ ?: return LOG.warn("Could not create directories for $path")
val pathFilename = VfsUtil.extractFileName(path)
- ?: return
+ ?: return LOG.warn("Could not get filename for $path")
runWriteAction {
val newFile = vfsDirectory.createChildData(this, pathFilename)
VfsUtil.saveText(newFile, content)
@@ -107,4 +109,8 @@ class FileUtils(
}
return fileUri
}
+
+ private companion object {
+ private val LOG = Logger.getInstance(FileUtils::class.java)
+ }
}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt
index 274b2d458..7792397e3 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt
@@ -97,7 +97,8 @@ class DiffStreamHandler(
highlighted: String,
suffix: String,
modelTitle: String?,
- includeRulesInSystemMessage: Boolean
+ includeRulesInSystemMessage: Boolean,
+ isApply: Boolean
) {
isRunning = true
sendUpdate(ApplyStateStatus.STREAMING)
@@ -112,7 +113,8 @@ class DiffStreamHandler(
language = virtualFile?.fileType?.name,
modelTitle = modelTitle,
includeRulesInSystemMessage = includeRulesInSystemMessage,
- fileUri = virtualFile?.url
+ fileUri = virtualFile?.url,
+ isApply = isApply
),
null
) { response ->
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt
index e0dbcb0c2..914f70552 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt
@@ -205,7 +205,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
- textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
+ textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true, false
)
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt
index 902d522f4..6ac0b0a6b 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt
@@ -1,4 +1,4 @@
-import com.github.continuedev.continueintellijextension.actions.FocusContinueInputAction
+import com.github.continuedev.continueintellijextension.actions.FocusActionUtil
import com.github.continuedev.continueintellijextension.editor.openInlineEdit
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
@@ -92,7 +92,7 @@ class ToolTipComponent(editor: Editor, x: Int, y: Int) :
editButton = StyledButton("Edit (${cmdCtrlChar}+I)")
addToChatButton.addActionListener { e: ActionEvent? ->
- FocusContinueInputAction.focusContinueInput(editor.project)
+ FocusActionUtil.sendHighlightedCodeWithMessageToWebview(editor.project, "focusContinueInputWithNewSession")
editor.contentComponent.remove(this)
}
editButton.addActionListener { e: ActionEvent? ->
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt
index 7ed69f6eb..64bef7ba9 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt
@@ -9,7 +9,7 @@ data class ApplyToFileParams(
val streamId: String,
val filepath: String?,
val toolCallId: String?,
- val isSearchReplace: Boolean? = null
+ val isSearchAndReplace: Boolean? = null
)
data class InsertAtCursorParams(
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
index cddcd035b..d937b0add 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
@@ -306,7 +306,8 @@ data class StreamDiffLinesPayload(
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean,
- val fileUri: String?
+ val fileUri: String?,
+ val isApply: Boolean
)
data class AcceptOrRejectDiffPayload(
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt
deleted file mode 100644
index 44171e581..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.github.continuedev.continueintellijextension.e2e
-
-import com.automation.remarks.junit5.Video
-import com.github.continuedev.continueintellijextension.fixtures.dialog
-import com.github.continuedev.continueintellijextension.fixtures.idea
-import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
-import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
-import com.github.continuedev.continueintellijextension.utils.StepsLogger
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.fixtures.ComponentFixture
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.steps.CommonSteps
-import com.intellij.remoterobot.utils.keyboard
-import com.intellij.remoterobot.utils.waitFor
-import com.intellij.remoterobot.utils.waitForIgnoringError
-import org.junit.jupiter.api.AfterEach
-import org.junit.jupiter.api.BeforeEach
-import org.junit.jupiter.api.Test
-import org.junit.jupiter.api.extension.ExtendWith
-import java.time.Duration.ofMinutes
-import java.time.Duration.ofSeconds
-
-@ExtendWith(RemoteRobotExtension::class)
-class Autocomplete {
- init {
- StepsLogger.init()
- }
-
- @BeforeEach
- fun waitForIde(remoteRobot: RemoteRobot) {
- waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
- }
-
- @AfterEach
- fun closeProject(remoteRobot: RemoteRobot) {
- CommonSteps(remoteRobot).closeProject()
- }
-
- @Test
- @Video
- fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
- welcomeFrame {
- createNewProjectLink.click()
- dialog("New Project") {
- findText("Java").click()
- checkBox("Add sample code").select()
- button("Create").click()
- }
- }
-
- // Wait for the default "Main.java" tab to load
- // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
- waitFor(ofSeconds(20)) {
- findAll(
- byXpath("//div[@visible_text='Main.java']")
- ).isNotEmpty()
- }
-
- idea {
- with(textEditor()) {
- val userMsg = "TEST_USER_MESSAGE_0"
- editor.insertTextAtLine(0, 0, userMsg)
- editor.clickOnOffset(userMsg.length)
-
- keyboard {
- enterText(" ")
- }
-
- waitFor(ofSeconds(20)) {
- editor.hasText("TEST_LLM_RESPONSE_0")
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt
deleted file mode 100644
index 44b205134..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/GUI.kt
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * Currently we can't test any actions in the GUI that involve clicks.
- * See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491
- */
-package com.github.continuedev.continueintellijextension.e2e
-
-import com.automation.remarks.junit5.Video
-import com.github.continuedev.continueintellijextension.fixtures.*
-import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
-import com.github.continuedev.continueintellijextension.utils.StepsLogger
-import com.github.continuedev.continueintellijextension.utils.getMetaKey
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.fixtures.ComponentFixture
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.steps.CommonSteps
-import com.intellij.remoterobot.stepsProcessing.step
-import com.intellij.remoterobot.utils.keyboard
-import com.intellij.remoterobot.utils.waitFor
-import com.intellij.remoterobot.utils.waitForIgnoringError
-import org.junit.jupiter.api.AfterEach
-import org.junit.jupiter.api.BeforeEach
-import org.junit.jupiter.api.Test
-import org.junit.jupiter.api.extension.ExtendWith
-import java.awt.event.KeyEvent.*
-import java.time.Duration.ofMinutes
-import java.time.Duration.ofSeconds
-
-@ExtendWith(RemoteRobotExtension::class)
-class GUI {
- init {
- StepsLogger.init()
- }
-
- @BeforeEach
- fun waitForIde(remoteRobot: RemoteRobot) {
- waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
- }
-
- @AfterEach
- fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
-
- // @Test
- @Video
- fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
- welcomeFrame {
- createNewProjectLink.click()
- dialog("New Project") {
- findText("Java").click()
- checkBox("Add sample code").select()
- button("Create").click()
- }
- }
-
- // Wait for the default "Main.java" tab to load
- // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
- // If we don't wait for this, clicking on the GUI may fail because a popup displays
- // while the `continue_tutorial.java` is loading.
- waitFor(ofSeconds(20)) {
- findAll(
- byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
- ).isNotEmpty()
- }
-
- idea {
- step("Manually open the webview") {
- // Manually open the webview
- find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
-
- waitFor(ofSeconds(10)) {
- browser().isShowing
- }
-
- // Arbitrary timeout due to a bug where the webview will refresh
- // and clear the editor state on first load
- Thread.sleep(5000)
- }
-
- step("Verify we can highlight code and add to webview") {
- val textToInsert = "Hello world!"
-
- with(textEditor()) {
- editor.insertTextAtLine(0, 0, textToInsert)
- editor.selectText(textToInsert)
-
- keyboard {
- hotKey(getMetaKey(), VK_J)
- }
- }
-
- waitFor(ofSeconds(10)) {
- browser().findElementByContainsText(textToInsert).html.isNotEmpty()
- }
- }
- }
- }
-}
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt
deleted file mode 100644
index e668bd4b1..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/InlineEdit.kt
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.github.continuedev.continueintellijextension.e2e
-
-import com.automation.remarks.junit5.Video
-import com.github.continuedev.continueintellijextension.fixtures.dialog
-import com.github.continuedev.continueintellijextension.fixtures.idea
-import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
-import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
-import com.github.continuedev.continueintellijextension.utils.StepsLogger
-import com.github.continuedev.continueintellijextension.utils.*
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.fixtures.ComponentFixture
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.steps.CommonSteps
-import com.intellij.remoterobot.utils.keyboard
-import com.intellij.remoterobot.utils.waitFor
-import com.intellij.remoterobot.utils.waitForIgnoringError
-import org.junit.jupiter.api.AfterEach
-import org.junit.jupiter.api.BeforeEach
-import org.junit.jupiter.api.Disabled
-import org.junit.jupiter.api.Test
-import org.junit.jupiter.api.extension.ExtendWith
-import java.awt.event.KeyEvent.VK_I
-import java.time.Duration.ofMinutes
-import java.time.Duration.ofSeconds
-
-@ExtendWith(RemoteRobotExtension::class)
-class InlineEdit {
- init {
- StepsLogger.init()
- }
-
- @BeforeEach
- fun waitForIde(remoteRobot: RemoteRobot) {
- waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
- }
-
- @AfterEach
- fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
-
- @Test
- @Disabled("Failing in CI, seems like the timeout just needs to be increased")
- @Video
- fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
- welcomeFrame {
- createNewProjectLink.click()
- dialog("New Project") {
- findText("Java").click()
- checkBox("Add sample code").select()
- button("Create").click()
- }
- }
-
- // Wait for the default "Main.java" tab to load
- // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
- waitFor(ofSeconds(20)) {
- findAll(
- byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
- ).isNotEmpty()
- }
-
- idea {
- with(textEditor()) {
- val userMsg = "TEST_USER_MESSAGE_0"
- editor.insertTextAtLine(0, 0, userMsg)
- editor.selectText(userMsg)
-
- keyboard {
- hotKey(getMetaKey(), VK_I)
- }
-
- val textArea = find(byXpath("//div[@class='CustomTextArea']"))
- textArea.hasText("Enter instructions...")
-
- val modelSelect = find(byXpath("//div[@class='JComboBox']"))
- modelSelect.hasText("TEST LLM")
-
- keyboard {
- enterText("Hello world!")
- }
-
- val enterBtn = find(byXpath("//div[@class='CustomButton']"))
- enterBtn.click()
-
- val rejectText = "${getAltKeyLabel()}${getShiftKeyLabel()}N"
- val acceptText = "${getAltKeyLabel()}${getShiftKeyLabel()}Y"
- val acceptAllText = "Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)"
- val rejectAllText = "Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)"
-
- find(byXpath("//div[@text='$rejectText']")).isShowing
- find(byXpath("//div[@text='$acceptText']")).isShowing
- find(byXpath("//div[@text='$acceptAllText']")).isShowing
- find(byXpath("//div[@text='$rejectAllText']")).isShowing
- }
- }
- }
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt
deleted file mode 100644
index 30306b7ba..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Onboarding.kt
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.github.continuedev.continueintellijextension.e2e
-
-import com.automation.remarks.junit5.Video
-import com.github.continuedev.continueintellijextension.fixtures.dialog
-import com.github.continuedev.continueintellijextension.fixtures.idea
-import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
-import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
-import com.github.continuedev.continueintellijextension.utils.StepsLogger
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.fixtures.ComponentFixture
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.steps.CommonSteps
-import com.intellij.remoterobot.stepsProcessing.step
-import com.intellij.remoterobot.utils.waitFor
-import com.intellij.remoterobot.utils.waitForIgnoringError
-import org.junit.jupiter.api.AfterEach
-import org.junit.jupiter.api.BeforeEach
-import org.junit.jupiter.api.Test
-import org.junit.jupiter.api.extension.ExtendWith
-import java.time.Duration.ofMinutes
-import java.time.Duration.ofSeconds
-
-@ExtendWith(RemoteRobotExtension::class)
-class Onboarding {
- init {
- StepsLogger.init()
- }
-
- @BeforeEach
- fun waitForIde(remoteRobot: RemoteRobot) {
- waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
- }
-
- @AfterEach
- fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
-
-
- // @Test
- @Video
- fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
- welcomeFrame {
- createNewProjectLink.click()
- dialog("New Project") {
- findText("Java").click()
- checkBox("Add sample code").select()
- button("Create").click()
- }
- }
-
- idea {
- // Wait for the default "Main.java" tab to load
- // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
- // So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
- waitFor(ofSeconds(20)) {
- findAll(
- byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
- ).isNotEmpty()
- }
-
- // TODO: Need a good way to ensure this is the first test ran in the entire suite
-// step("Verify Continue tutorial file is loaded") {
-// find(byXpath("//div[@visible_text='continue_tutorial.java']"))
-// }
-
- step("Manually open the webview") {
- // Manually open the webview
- find(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
-
- waitFor(ofSeconds(10)) {
- browser().isShowing
- }
- }
-
- step("Verify the onboarding card is present") {
- waitFor(ofSeconds(30)) {
- try {
- browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty()
- } catch (e: Exception) {
- false
- }
- }
- }
- }
- }
-}
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt
deleted file mode 100644
index d9643a96b..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/DialogFixture.kt
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.github.continuedev.continueintellijextension.fixtures
-
-/*
- * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt
- */
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.data.RemoteComponent
-import com.intellij.remoterobot.fixtures.CommonContainerFixture
-import com.intellij.remoterobot.fixtures.ContainerFixture
-import com.intellij.remoterobot.fixtures.FixtureName
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.stepsProcessing.step
-import java.time.Duration
-
-fun ContainerFixture.dialog(
- title: String,
- timeout: Duration = Duration.ofSeconds(30),
- function: DialogFixture.() -> Unit = {}
-): DialogFixture = step("Search for dialog with title $title") {
- find(DialogFixture.byTitle(title), timeout).apply(function)
-}
-
-@FixtureName("Dialog")
-class DialogFixture(
- remoteRobot: RemoteRobot,
- remoteComponent: RemoteComponent
-) : CommonContainerFixture(remoteRobot, remoteComponent) {
-
- companion object {
- @JvmStatic
- fun byTitle(title: String) = byXpath("title $title", "//div[@title='$title' and @class='MyDialog']")
- }
-
- val title: String
- get() = callJs("component.getTitle();")
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt
deleted file mode 100644
index 141677c15..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/IdeaFrame.kt
+++ /dev/null
@@ -1,92 +0,0 @@
-package com.github.continuedev.continueintellijextension.fixtures
-
-/*
- * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt
- */
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.data.RemoteComponent
-import com.intellij.remoterobot.fixtures.*
-import com.intellij.remoterobot.search.locators.byXpath
-import com.intellij.remoterobot.stepsProcessing.step
-import com.intellij.remoterobot.utils.waitFor
-import java.time.Duration
-
-fun RemoteRobot.idea(function: IdeaFrame.() -> Unit) {
- find(timeout = Duration.ofSeconds(10)).apply(function)
-}
-
-@FixtureName("Idea frame")
-@DefaultXpath("IdeFrameImpl type", "//div[@class='IdeFrameImpl']")
-class IdeaFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
- CommonContainerFixture(remoteRobot, remoteComponent) {
-
- val projectViewTree
- get() = find(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']"))
-
- val projectName
- get() = step("Get project name") { return@step callJs("component.getProject().getName()") }
-
- val menuBar: JMenuBarFixture
- get() = step("Menu...") {
- return@step remoteRobot.find(JMenuBarFixture::class.java, JMenuBarFixture.byType())
- }
-
- @JvmOverloads
- fun dumbAware(timeout: Duration = Duration.ofMinutes(5), function: () -> Unit) {
- step("Wait for smart mode") {
- waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
- runCatching { isDumbMode().not() }.getOrDefault(false)
- }
- function()
- step("..wait for smart mode again") {
- waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
- isDumbMode().not()
- }
- }
- }
- }
-
- fun isDumbMode(): Boolean {
- return callJs(
- """
- const frameHelper = com.intellij.openapi.wm.impl.ProjectFrameHelper.getFrameHelper(component)
- if (frameHelper) {
- const project = frameHelper.getProject()
- project ? com.intellij.openapi.project.DumbService.isDumb(project) : true
- } else {
- true
- }
- """, true
- )
- }
-
- fun openFile(path: String) {
- runJs(
- """
- importPackage(com.intellij.openapi.fileEditor)
- importPackage(com.intellij.openapi.vfs)
- importPackage(com.intellij.openapi.wm.impl)
- importClass(com.intellij.openapi.application.ApplicationManager)
-
- const path = '$path'
- const frameHelper = ProjectFrameHelper.getFrameHelper(component)
- if (frameHelper) {
- const project = frameHelper.getProject()
- const projectPath = project.getBasePath()
- const file = LocalFileSystem.getInstance().findFileByPath(projectPath + '/' + path)
- const openFileFunction = new Runnable({
- run: function() {
- FileEditorManager.getInstance(project).openTextEditor(
- new OpenFileDescriptor(
- project,
- file
- ), true
- )
- }
- })
- ApplicationManager.getApplication().invokeLater(openFileFunction)
- }
- """, true
- )
- }
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt
deleted file mode 100644
index 70029fdaf..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/fixtures/WelcomeFrame.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.github.continuedev.continueintellijextension.fixtures
-
-/*
- * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt
- */
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.data.RemoteComponent
-import com.intellij.remoterobot.fixtures.*
-import com.intellij.remoterobot.search.locators.byXpath
-import java.time.Duration
-
-fun RemoteRobot.welcomeFrame(function: WelcomeFrame.() -> Unit) {
- find(WelcomeFrame::class.java, Duration.ofSeconds(20)).apply(function)
-}
-
-@FixtureName("Welcome Frame")
-@DefaultXpath("type", "//div[@class='FlatWelcomeFrame']")
-class WelcomeFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
- CommonContainerFixture(remoteRobot, remoteComponent) {
- val createNewProjectLink
- get() = actionLink(
- byXpath(
- "New Project",
- "//div[(@class='MainButton' and @text='New Project') or (@accessiblename='New Project' and @class='JButton')]"
- )
- )
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt
deleted file mode 100644
index 51868f031..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Notes:
- * - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement
- * - Below is an AI generated summary of what the problem might be based on troubleshooting attempts
- * - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491
- *
- *
- * The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution.
- * When trying to call window.postIntellijMessage, we're encountering these challenges:
- *
- * 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally.
- * When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection
- * mechanism, creating nested injections that break.
- *
- * 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax
- * errors in the final JavaScript that gets executed.
- *
- * 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the
- * function was defined, causing scope/reference issues.
- *
- * The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test
- * framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser
- * context, not through another layer of script injection.
- */
-package com.github.continuedev.continueintellijextension.utils
-
-import com.intellij.remoterobot.fixtures.JCefBrowserFixture
-
-/**
- * Utility functions for interacting with browser components in tests
- */
-object BrowserUtils {
-
- /**
- * Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser
- *
- * @param browser The JCefBrowserFixture to execute JavaScript in
- * @param messageType The type of message to send
- * @param messageData The data object to send as message payload
- * @param messageId A unique ID for the message
- */
- fun sendIntellijMessage(
- browser: JCefBrowserFixture,
- messageType: String,
- messageData: Any,
- messageId: String = "test-message-id"
- ) {
- // Convert the messageData to a JSON string
- val dataJson = when (messageData) {
- is String -> "\"$messageData\""
- else -> messageData.toString()
- }
-
- val jsCode = """
- (function() {
- window.postIntellijMessage(
- "$messageType",
- $dataJson,
- "$messageId"
- );
- return true;
- })();
- """.trimIndent()
-
- browser.executeJsInBrowser(jsCode)
- }
-}
-
-// Extension function for JCefBrowserFixture for easier usage
-fun JCefBrowserFixture.sendIntellijMessage(
- messageType: String,
- messageData: Any,
- messageId: String = "test-message-id"
-) {
- BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId)
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt
deleted file mode 100644
index 0ae25a389..000000000
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/RemoteRobotExtension.kt
+++ /dev/null
@@ -1,138 +0,0 @@
-package com.github.continuedev.continueintellijextension.utils
-
-/**
- * Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/utils/RemoteRobotExtension.kt
- */
-import com.intellij.remoterobot.RemoteRobot
-import com.intellij.remoterobot.fixtures.ContainerFixture
-import com.intellij.remoterobot.search.locators.byXpath
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import okhttp3.logging.HttpLoggingInterceptor
-import org.junit.jupiter.api.extension.AfterTestExecutionCallback
-import org.junit.jupiter.api.extension.ExtensionContext
-import org.junit.jupiter.api.extension.ParameterContext
-import org.junit.jupiter.api.extension.ParameterResolver
-import java.awt.image.BufferedImage
-import java.io.ByteArrayOutputStream
-import java.io.File
-import java.lang.IllegalStateException
-import java.lang.reflect.Method
-import javax.imageio.ImageIO
-
-class RemoteRobotExtension : AfterTestExecutionCallback, ParameterResolver {
- private val url: String = System.getProperty("remote-robot-url") ?: "http://127.0.0.1:8082"
- private val remoteRobot: RemoteRobot = if (System.getProperty("debug-retrofit")?.equals("enable") == true) {
- val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
- this.level = HttpLoggingInterceptor.Level.BODY
- }
- val client = OkHttpClient.Builder().apply {
- this.addInterceptor(interceptor)
- }.build()
- RemoteRobot(url, client)
- } else {
- RemoteRobot(url)
- }
- private val client = OkHttpClient()
-
- override fun supportsParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Boolean {
- return parameterContext?.parameter?.type?.equals(RemoteRobot::class.java) ?: false
- }
-
- override fun resolveParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Any {
- return remoteRobot
- }
-
- override fun afterTestExecution(context: ExtensionContext?) {
- val testMethod: Method = context?.requiredTestMethod ?: throw IllegalStateException("test method is null")
- val testMethodName = testMethod.name
- val testFailed: Boolean = context.executionException?.isPresent ?: false
- if (testFailed) {
-// saveScreenshot(testMethodName)
- saveIdeaFrames(testMethodName)
- saveHierarchy(testMethodName)
- }
- }
-
- private fun saveScreenshot(testName: String) {
- fetchScreenShot().save(testName)
- }
-
- private fun saveHierarchy(testName: String) {
- val hierarchySnapshot =
- saveFile(url, "build/reports", "hierarchy-$testName.html")
- if (File("build/reports/styles.css").exists().not()) {
- saveFile("$url/styles.css", "build/reports", "styles.css")
- }
- println("Hierarchy snapshot: ${hierarchySnapshot.absolutePath}")
- }
-
- private fun saveFile(url: String, folder: String, name: String): File {
- val response = client.newCall(Request.Builder().url(url).build()).execute()
- return File(folder).apply {
- mkdirs()
- }.resolve(name).apply {
- writeText(response.body?.string() ?: "")
- }
- }
-
- private fun BufferedImage.save(name: String) {
- val bytes = ByteArrayOutputStream().use { b ->
- ImageIO.write(this, "png", b)
- b.toByteArray()
- }
- File("build/reports").apply { mkdirs() }.resolve("$name.png").writeBytes(bytes)
- }
-
- private fun saveIdeaFrames(testName: String) {
- remoteRobot.findAll