Merge branch 'main' into func-max-chunk-size

This commit is contained in:
uinstinct 2025-08-18 18:20:53 +05:30
commit 46724aa3e6
325 changed files with 10868 additions and 2498 deletions

View file

@ -0,0 +1,19 @@
---
name: Bigger Picture Description Rules
description: Guidelines for explaining how code works in context
alwaysApply: false
---
When a user asks how a certain part of the code works:
## 1. Describe what the code does in isolation
Explain the functionality of the code without considering its interactions with other parts of the codebase.
## 2. Describe interactions with other parts of the codebase
If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
## 3. Include parent function for clarity
When describing each use-case, include the parent function for clarity.

View file

@ -1,13 +0,0 @@
name: bigger-picture-description-rules
version: 0.0.1
schema: v1
rules:
- name: bigger-picture-description-rules
rule: >-
When a user asks how a certain part of the code works:
1. Describe what the code does in isolation.
2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
3. When describing each use-case, include the parent function for clarity.

63
.continue/rules/colors.md Normal file
View file

@ -0,0 +1,63 @@
---
name: Extension Color Themes
description: Guidelines for using theme colors in GUI components
alwaysApply: false
globs: "gui/**/*.tsx"
---
When adding colors to components, use tailwind color classes.
Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
## Available theme colors
### Normal text
- `foreground`, `description`, `description-muted`
### Other text, icons, etc
- `success`, `warning`, `error`, `accent`, `link`
### General components
- `background`, `border`, `border-focus`
### Specific components
#### Button
- `primary`, `primary-foreground`, `primary-hover`
- `secondary`, `secondary-foreground`, `secondary-hover`
#### Input
- `input`, `input-foreground`, `input-border`, `input-placeholder`
#### Badge
- `badge`, `badge-foreground`
#### List/Dropdown items
- `list-hover`, `list-active`, `list-active-foreground`
#### Code Editor
- `editor`, `editor-foreground`
## Usage examples
Any of these colors can be used in tailwind classes:
- `bg-primary`
- `text-success`
- `border-error`
- `hover:bg-list-hover`
## Excluded colors
The following less-used colors are excluded from this guide:
- Command (only used by tip-tap): `command`, `command-foreground`, `command-border`, `command-border-focus`
- Find widget colors: `find-match`, `find-match-selected`
- `table-oddRow`

View file

@ -1,27 +0,0 @@
name: GUI
version: 0.0.1
schema: v1
rules:
- name: Extension Color Themes
rule: |
When adding colors to components, use tailwind color classes.
Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
The common available theme colors are:
- For normal text: foreground, description, description-muted
- For other text, icons, etc: success, warning, error, accent, link
- For general components background, border, border-focus
- For specific components:
- Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover
- Input: input, input-foreground, input-border, input-placeholder
- Badge: badge, badge-foreground
- List/Dropdown items: list-hover, list-active, list-active-foreground
- Code Editor: editor, editor-foreground
Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc.
globs: "gui/**/*.tsx"
# Excluding the following less-used colors:
# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus
# Find widget colors: find-match, find-match-selected
# table-oddRow

View file

@ -0,0 +1,8 @@
---
globs: docs/**/*.{md,mdx}
description: This rule applies to all documentation files to ensure consistent
SEO optimization and improve discoverability. It helps users and search
engines understand the content of each page before reading it.
---
Every file in the docs folder must include a 'description' field in its frontmatter that accurately summarizes the content of the page in 100-160 characters. The description should be concise, keyword-rich, and explain what users will learn or accomplish from the page.

View file

@ -1,8 +0,0 @@
---
patterns: ["EditAggregator", "processEdit"]
glob: "**/*.tsx"
name: "Enforce EditAggregator Singleton"
description: "Ensure that EditAggregator is used as a singleton in the codebase."
---
When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator.

View file

@ -0,0 +1,20 @@
---
name: IntelliJ Plugin Test Execution
description: Guidelines for running IntelliJ plugin tests with Gradle
alwaysApply: false
globs: extensions/intellij/**/*Test.kt
---
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
## Run test class
```bash
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
```
## Run specific test method
```bash
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
```

View file

@ -1,15 +0,0 @@
name: IntelliJ Plugin Test Execution
version: 0.0.1
schema: v1
rules:
- name: IntelliJ Plugin Test Execution
rule: |-
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
```bash
# Run test class
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
# Run specific test method
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
```
globs: extensions/intellij/**/*Test.kt

View file

@ -1,10 +0,0 @@
name: IntelliJ Test Standards
version: 0.0.1
schema: v1
rules:
- name: IntelliJ Test Standards
rule: When writing tests for the IntelliJ plugin, use the mockk library for
mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
Always structure tests with clear Arrange-Act-Assert patterns and use
descriptive test names that indicate the scenario being tested.
globs: "**/test/**/*.kt"

View file

@ -1,6 +1,7 @@
---
name: New protocol message
description: Create a new protocol message from core/gui/ide to core/gui/ide
alwaysApply: false
---
Create a new protocol message by taking the following steps:

View file

@ -0,0 +1,37 @@
---
name: Unit Testing Rules
description: Guidelines for unit testing in this project
alwaysApply: false
---
For unit testing in this project:
## 1. Testing frameworks
The project uses Vitest and Jest for testing. Prefer Vitest.
## 2. Test execution location
Run tests from within the specific package directory (e.g., `cd core && ..`).
## 3. Vitest tests
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module directory:
```bash
cd [directory] && vitest -- [test file path]
```
## 4. Jest tests
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module directory:
```bash
cd [directory] && npm test -- [test file path]
```
- The test script uses experimental VM modules via NODE_OPTIONS flag
## 5. Test structure
- Write tests as top-level `test()` functions - DO NOT use `describe()` blocks
- Include the function name being tested in the test description for clarity

View file

@ -1,28 +0,0 @@
name: unit-testing-rules
version: 0.0.1
schema: v1
rules:
- name: unit-testing-rules
rule: >-
For unit testing in this project:
1. The project uses Vitest and Jest for testing. Prefer Vitest
2. Run tests from within the specific package directory (e.g., `cd core && ..`
3. For vitest tests,
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module
directory: `cd [directory] && vitest -- [test file path]`
4. For jest tests,
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module
directory: `cd [directory] && npm test -- [test file path]`
- The test script uses experimental VM modules via NODE_OPTIONS flag
5. For both
- Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
- Include the function name being tested in the test description for
clarity

View file

@ -105,7 +105,9 @@ runs:
shell: bash
run: |
cd gui
npm run build
npm run build --max-old-space-size=4096
env:
NODE_OPTIONS: "--max-old-space-size=4096"
- name: Prepackage the extension
shell: bash
@ -156,4 +158,4 @@ runs:
npx vsce package --pre-release --no-dependencies --target ${{ steps.set-target.outputs.target }}
else
npx vsce package --no-dependencies --target ${{ steps.set-target.outputs.target }}
fi
fi

View file

@ -2,6 +2,11 @@
[ What changed? Feel free to be brief. ]
## AI Code Review
- **Team members only**: AI review runs automatically when PR is opened or marked ready for review
- Team members can also trigger a review by commenting `@continue-general-review` or `@continue-detailed-review`
## Checklist
- [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)

View file

@ -14,7 +14,7 @@ jobs:
uses: pozil/auto-assign-issue@v2
with:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai
assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai,uinstinct
numOfAssignee: 1
# - name: "Add default labels"
# uses: actions-ecosystem/action-add-labels@v1

View file

@ -16,7 +16,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get version from package.json
id: get_version
@ -45,7 +45,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -101,7 +101,7 @@ jobs:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
@ -134,7 +134,7 @@ jobs:
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check required files
run: |

View file

@ -0,0 +1,25 @@
name: Continue Detailed Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
detailed-code-review:
name: Continue Detailed Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev
continue-config: continuedev/review-bot

View file

@ -0,0 +1,25 @@
name: Continue General Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-code-review:
name: Continue General Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
continue-config: "continuedev/review-bot"

View file

@ -14,7 +14,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4

View file

@ -56,7 +56,7 @@ jobs:
# steps:
# # 0. Setup git
# - name: Checkout
# uses: actions/checkout@v4
# uses: actions/checkout@v5
# - name: Set up Git
# run: |
@ -102,7 +102,7 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
ref: ${{ github.event.release.tag_name }}
@ -362,7 +362,7 @@ jobs:
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
uses: actions/checkout@v5
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
@ -429,7 +429,7 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
@ -482,7 +482,7 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
@ -493,7 +493,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2025.1.1
uses: JetBrains/qodana-action@v2025.2.1
with:
cache-default-branch-only: true
@ -513,7 +513,7 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java

View file

@ -13,7 +13,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check if author is in tier list
id: check-author

View file

@ -18,7 +18,7 @@ jobs:
matrix:
platform: [Linux, macOS]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 2 # Get the last 2 commits to find the merge commit

View file

@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
@ -112,7 +112,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -145,7 +145,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -24,7 +24,7 @@ jobs:
runner: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -14,7 +14,7 @@ jobs:
prettier-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -35,7 +35,7 @@ jobs:
core-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -71,7 +71,7 @@ jobs:
gui-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -101,7 +101,7 @@ jobs:
binary-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -123,7 +123,7 @@ jobs:
vscode-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -156,7 +156,7 @@ jobs:
outputs:
packages: ${{ steps.get-packages.outputs.packages }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get package list
id: get-packages
run: |
@ -171,7 +171,7 @@ jobs:
matrix:
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
@ -197,7 +197,7 @@ jobs:
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -257,7 +257,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -289,7 +289,7 @@ jobs:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run VS Code E2E test
uses: ./.github/actions/run-vscode-e2e-test
with:
@ -303,7 +303,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run JetBrains tests
uses: ./.github/actions/run-jetbrains-tests
with:
@ -312,6 +312,32 @@ jobs:
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
# This action at least lets us manage the list of required tests via source control
pr-review-action-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Cache PR review action node modules
uses: actions/cache@v4
id: pr-review-cache
with:
path: actions/detailed-review/node_modules
key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }}
- name: Install dependencies
if: steps.pr-review-cache.outputs.cache-hit != 'true'
run: |
cd actions/detailed-review
npm install
- name: Run tests
run: |
cd actions/detailed-review
npm test
# so that creators of new jobs can add them to this list
require-all-checks-to-pass:
if: always()
@ -328,6 +354,7 @@ jobs:
- vscode-package-extension-linux
- vscode-e2e-tests
- jetbrains-tests
- pr-review-action-tests
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -96,7 +96,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -131,7 +131,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -47,7 +47,7 @@ jobs:
working-directory: ${{ inputs.package-path }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -7,6 +7,8 @@ on:
jobs:
analyze:
# Disabling for now due to bugs
if: false
runs-on: ubuntu-latest
permissions:
issues: write
@ -14,30 +16,30 @@ jobs:
steps:
- name: Checkout deja-view
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: 'bdougie/deja-view'
repository: "bdougie/deja-view"
# Option 1: Pin to specific commit (most secure)
ref: '45e7696' # Pin to specific commit for stability
ref: "45e7696" # Pin to specific commit for stability
# Option 2: Use a tag (recommended after creating releases)
# ref: 'v1.0.0'
# Option 3: Use main branch (least secure, gets latest changes)
# ref: 'main'
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
python-version: "3.11"
- name: Install dependencies
run: |
cd deja-view
pip install -r requirements.txt
- name: Index repository if needed
env:
CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }}
@ -46,10 +48,10 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Index the repository (this will update existing index)
python cli.py index "${{ github.repository }}" --max-issues 200 || true
- name: Search for similar issues
id: search
env:
@ -59,7 +61,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Determine if this is an issue or PR
if [ "${{ github.event_name }}" = "pull_request" ]; then
ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
@ -70,26 +72,26 @@ jobs:
THRESHOLD="0.7"
TOP_K="5"
fi
# Create a Python script to search and format as JSON
cat << 'PYTHON_SCRIPT' > search_similar.py
import sys
import json
import os
from github_similarity_service import SimilarityService
issue_url = sys.argv[1]
threshold = float(sys.argv[2])
top_k = int(sys.argv[3])
# Parse issue number from URL
issue_number = int(issue_url.split('/')[-1])
repo_parts = issue_url.split('/')
owner = repo_parts[3]
repo = repo_parts[4]
service = SimilarityService()
# Find similar issues
similar = service.find_similar_issues(
owner=owner,
@ -98,26 +100,26 @@ jobs:
top_k=top_k,
min_similarity=threshold
)
# Format as JSON
print(json.dumps(similar))
PYTHON_SCRIPT
# Search for similar issues
SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K")
# Save to output
echo "similar_issues<<EOF" >> $GITHUB_OUTPUT
echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Check if any similar issues found
if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then
echo "has_similar=true" >> $GITHUB_OUTPUT
else
echo "has_similar=false" >> $GITHUB_OUTPUT
fi
- name: Check if issue should be a discussion
id: discussion_check
if: github.event_name == 'issues'
@ -128,19 +130,19 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Create a Python script to analyze the issue
cat << 'PYTHON_SCRIPT' > check_discussion.py
import os
import json
import re
from github_similarity_service import SimilarityService
# Get issue details from environment
issue_title = os.environ.get('ISSUE_TITLE', '')
issue_body = os.environ.get('ISSUE_BODY', '')
issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]'))
# Mock Issue object for analysis
class MockIssue:
def __init__(self):
@ -152,41 +154,41 @@ jobs:
self.created_at = ''
self.updated_at = ''
self.url = ''
service = SimilarityService()
issue = MockIssue()
score, reasons = service._calculate_discussion_score(issue)
result = {
'score': score,
'reasons': reasons,
'should_be_discussion': score >= 0.5,
'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low'
}
print(json.dumps(result))
PYTHON_SCRIPT
# Run the analysis
DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \
ISSUE_BODY='${{ github.event.issue.body }}' \
ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \
ISSUE_NUMBER="${{ github.event.issue.number }}" \
python check_discussion.py)
echo "analysis<<EOF" >> $GITHUB_OUTPUT
echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Extract whether it should be a discussion
SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion')
echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT
# Extract confidence level
CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence')
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
with:
@ -195,7 +197,7 @@ jobs:
const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true';
const isPR = '${{ github.event_name }}' === 'pull_request';
const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true';
// Add similar issues section if found
if (hasSimilar) {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -243,7 +245,7 @@ jobs:
comment += '\n';
}
}
// Add discussion suggestion if applicable
if (shouldBeDiscussion) {
const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`);
@ -280,7 +282,7 @@ jobs:
comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n';
}
// Only comment if we have something to say
if (comment) {
comment += '\n---\n';
@ -302,14 +304,14 @@ jobs:
});
}
}
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
with:
script: |
const labels = [];
// Check for duplicate
if ('${{ steps.search.outputs.has_similar }}' === 'true') {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -319,7 +321,7 @@ jobs:
labels.push('potential-duplicate');
}
}
// Check for discussion suggestion
if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') {
const confidence = '${{ steps.discussion_check.outputs.confidence }}';
@ -330,7 +332,7 @@ jobs:
labels.push('discussion');
}
}
// Add labels if any
if (labels.length > 0) {
await github.rest.issues.addLabels({

View file

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Java
uses: actions/setup-java@v4
with:

View file

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # Fetch all history and tags

View file

@ -8,15 +8,6 @@
<div align="center">
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our
open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue)
and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
and [hub of models, rules, and MCP tools](https://hub.continue.dev)**
</div>
<div align="center">
<a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
<img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
</a>
@ -32,38 +23,42 @@ and [hub of models, rules, and MCP tools](https://hub.continue.dev)**
<p></p>
<div align="center">
**Ship faster with Continuous AI**
**Build and run custom agents across your IDE, terminal, and CI**
</div>
Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli)
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
[Agent](/features/agent/quick-start) to work on development tasks together with AI
![agent](docs/images/agent.gif)
## Chat
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
the IDE
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
![chat](docs/images/chat.gif)
## Edit
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
file
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
![autocomplete](docs/images/autocomplete.gif)
</div>
## Getting Started
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install)
## Contributing
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and

251
actions/README.md Normal file
View file

@ -0,0 +1,251 @@
# Continue PR Review Actions
GitHub Actions that provide automated code reviews for pull requests using Continue CLI.
## Available Actions
This repository provides two GitHub Actions for different review styles:
### 1. General Review Action
Provides high-level PR assessment with overall feedback and recommendations.
- **Path:** `continuedev/continue/actions/general-review@<commit-sha>`
- **Trigger:** `@continue-general-review`
- **Output:** Summary comment with strengths, issues, and recommendations
### 2. Detailed Review Action
Provides line-by-line inline comments on specific code changes.
- **Path:** `continuedev/continue/actions/detailed-review@<commit-sha>`
- **Trigger:** `@continue-detailed-review`
- **Output:** Inline review comments on specific lines of code
## Quick Start
### Using Both Actions Together
```yaml
name: PR Reviews
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/general-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
detailed-review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
### General Review Only
```yaml
name: PR General Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/general-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
### Detailed Review Only
```yaml
name: PR Detailed Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
## Inputs
Both actions accept the same inputs:
| Input | Description | Required |
| ------------------ | -------------------------------------- | -------- |
| `continue-api-key` | API key for Continue service | Yes |
| `continue-org` | Organization for Continue config | Yes |
| `continue-config` | Config path (e.g., "myorg/review-bot") | Yes |
## Setup Requirements
### 1. Continue API Key
Add your Continue API key as a secret named `CONTINUE_API_KEY` in your repository:
1. Go to your repository's Settings
2. Navigate to Secrets and variables → Actions
3. Click "New repository secret"
4. Name: `CONTINUE_API_KEY`
5. Value: Your Continue API key
### 2. Continue Configuration
Set up your review bot configuration in Continue:
1. Create a configuration for your organization
2. Configure the review bot settings
3. Note your organization name and config path
### 3. Workflow Permissions
The workflow requires these permissions:
- `contents: read` - To checkout and read repository code
- `pull-requests: write` - To post review comments on PRs
- `issues: write` - To respond to comment triggers
## Triggering Reviews
Both actions can be triggered in two ways:
### Automatic Triggers
- When a PR is opened by a team member (OWNER, MEMBER, or COLLABORATOR)
- When a PR is marked as "ready for review" by a team member
### Manual Triggers
Team members can trigger reviews by commenting on any pull request:
- `@continue-general-review` - Triggers a general review
- `@continue-detailed-review` - Triggers a detailed inline review
## Review Outputs
### General Review Output
The general review provides a structured comment that includes:
- **Strengths**: What was done well in the PR
- **Issues Found**: Categorized by severity (Critical, High, Medium, Low)
- **Suggestions**: Improvement recommendations
- **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT)
### Detailed Review Output
The detailed review provides:
- **Inline Comments**: Specific feedback on individual lines of code
- **Position Markers**: Comments appear directly on the changed lines
- **Review Summary**: Overall assessment of the changes
- **Actionable Feedback**: Specific suggestions for each issue found
## How It Works
### General Review Process
1. Checks out repository code
2. Fetches PR diff using GitHub CLI
3. Generates a comprehensive review prompt
4. Runs Continue CLI with specified configuration
5. Posts review as a PR comment
### Detailed Review Process
1. Checks out repository code
2. Fetches PR diff with GitHub API positions
3. Annotates diff with position markers
4. Generates inline review prompt
5. Runs Continue CLI for detailed analysis
6. Posts inline comments using GitHub's review API
## Versioning
We recommend using a specific commit SHA for stability and predictability:
- `@<commit-sha>` - Pins to a specific commit for maximum stability (recommended)
- `@main` - Uses the latest code from the main branch (for bleeding edge)
- `@v1` - Uses a version tag when available
Example:
```yaml
uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266
```
## Troubleshooting
### Review not triggering
- Ensure the PR author or commenter has appropriate permissions (OWNER, MEMBER, or COLLABORATOR)
- Check that the workflow file is in the default branch
- Verify the Continue API key is correctly set as a repository secret
### No review output generated
- Check the action logs for any errors
- Verify your Continue configuration is correct
- Ensure your Continue API key is valid
### Inline comments not appearing (Detailed Review)
- Check that the PR has a valid diff
- Verify GitHub API permissions are correct
- Review action logs for position calculation errors
## Support
For issues or questions:
- [Continue Documentation](https://docs.continue.dev)
- [GitHub Issues](https://github.com/continuedev/continue/issues)
- [Discord Community](https://discord.gg/vapESyrFmJ)

View file

@ -0,0 +1,350 @@
name: 'Continue Detailed PR Review'
description: 'Automated inline code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
inputs:
continue-api-key:
description: 'API key for Continue service'
required: true
continue-org:
description: 'Organization for Continue config'
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check Authorization
shell: bash
env:
# Only move the dangerous check to env to prevent shell injection
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }}
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 PR author association
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
fi
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
# Check if it's a PR comment with the trigger phrase
if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
fi
else
echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR"
fi
else
echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported"
fi
if [ "$SHOULD_RUN" != "true" ]; then
echo "SKIP_REVIEW=true" >> $GITHUB_ENV
exit 0
fi
echo "SKIP_REVIEW=false" >> $GITHUB_ENV
- name: Setup Node.js
if: env.SKIP_REVIEW != 'true'
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Continue CLI
if: env.SKIP_REVIEW != 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
- name: Build Inline Review Prompt
if: env.SKIP_REVIEW != 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
# Get PR number based on event type
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_NUMBER="${{ github.event.number }}"
else
# For issue_comment event on a PR
PR_NUMBER="${{ github.event.issue.number }}"
fi
# Get PR files with line numbers
gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json
# Get PR diff with context
gh pr diff $PR_NUMBER --color=never > pr_diff.txt
# Annotate diff with GitHub API positions
node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt
# Debug: Show sample of annotated diff
echo "=== SAMPLE OF ANNOTATED DIFF ==="
head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt
echo "=== END SAMPLE ==="
# Create review prompt for inline comments
cat > inline_review_prompt.txt << 'EOF'
You are conducting a detailed inline code review for a pull request.
Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code.
IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line.
Example of how to use the position markers:
```
diff --git a/src/app.js b/src/app.js
index abc123..def456 100644
--- a/src/app.js
+++ b/src/app.js
@@ -10,4 +10,6 @@ function example() {
[POS:1] console.log("context");
[POS:2] - const old = "remove this";
[POS:3] + const new = "add this";
[POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4
[POS:5] return result;
[POS:6] + console.log("done");
@@ -20,3 +22,4 @@ function another() {
[POS:1] let x = 1;
[POS:2] + let y = 2; <-- To comment here, use position: 2
```
To comment on a line, simply use the number from its [POS:N] marker as the position value.
For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"}
Below is the annotated PR diff:
EOF
cat pr_diff_annotated.txt >> inline_review_prompt.txt
cat >> inline_review_prompt.txt << 'EOF'
Please analyze these changes and provide inline review comments in the following JSON format:
{
"review_summary": "Overall assessment of the PR",
"comments": [
{
"path": "path/to/file.js",
"position": 4,
"body": "Brief, specific comment about this line or section"
}
]
}
Focus on:
1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality
2. **High Priority**: Performance problems, incorrect logic, missing error handling
3. **Medium Priority**: Code style violations, potential edge cases, unclear code
4. **Low Priority**: Suggestions for improvement, refactoring opportunities
Guidelines for comments:
- Be specific and actionable
- Use the [POS:N] number shown in the diff as the position value
- Keep comments concise but informative
- Suggest concrete improvements when pointing out issues
- Only comment on actual problems or important improvements
Important:
- Output ONLY valid JSON, no markdown code blocks or backticks
- Start your response with { and end with }
- Use the exact number from [POS:N] markers as the position
- Only comment on changed lines (lines with + or - prefix)
- Comment on the most important issues first
- Limit to maximum 20 most relevant comments
EOF
- name: Run Continue CLI Inline Review
if: env.SKIP_REVIEW != 'true'
shell: bash
env:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
run: |
echo "Running Continue CLI for inline review..."
# Validate required inputs
if [ -z "${{ inputs.continue-org }}" ]; then
echo "Error: continue-org input is required"
exit 1
fi
if [ -z "${{ inputs.continue-config }}" ]; then
echo "Error: continue-config input is required"
exit 1
fi
# Log the prompt for debugging
echo "===== START REVIEW PROMPT ====="
head -n 50 inline_review_prompt.txt
echo "... [diff content] ..."
tail -n 20 inline_review_prompt.txt
echo "===== END REVIEW PROMPT ====="
# Run the CLI and capture JSON output
cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
# Log the output for debugging
echo "Initial Continue CLI output:"
cat inline_review_raw.json
# Validate JSON output and use it directly
if ! jq empty inline_review_raw.json 2>/dev/null; then
echo "Error: Invalid JSON output from Continue CLI"
exit 1
fi
# Use the JSON output directly
cp inline_review_raw.json inline_review.json
echo "Review output:"
cat inline_review.json
- name: Post Inline Review Comments
if: env.SKIP_REVIEW != 'true'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
try {
// Read the review output
let reviewData;
try {
const reviewContent = fs.readFileSync('inline_review.json', 'utf8');
reviewData = JSON.parse(reviewContent);
} catch (parseError) {
console.log('Failed to parse review JSON:', parseError);
reviewData = {
review_summary: 'AI review completed but failed to parse output',
comments: []
};
}
// Get PR number
let prNumber;
if (context.eventName === 'pull_request') {
prNumber = context.payload.pull_request.number;
} else {
prNumber = context.payload.issue.number;
}
// Get the latest commit SHA
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber
});
const commitSha = pr.head.sha;
// Prepare review comments - filter out comments without required fields
const allComments = reviewData.comments || [];
const validComments = allComments.filter(comment =>
comment.position &&
comment.path &&
comment.body &&
typeof comment.position === 'number' &&
comment.position > 0
);
if (validComments.length < allComments.length) {
console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`);
const invalidComments = allComments.filter(c => !validComments.includes(c));
console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
}
const comments = validComments.map(comment => ({
path: comment.path,
position: comment.position,
body: comment.body
}));
// Debug: Log the positions we're trying to use
console.log('Attempting to post comments with positions:');
comments.forEach(c => {
console.log(` ${c.path}: position ${c.position}`);
});
// Create the review
if (comments.length > 0) {
try {
await github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber,
commit_id: commitSha,
body: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`,
event: 'COMMENT',
comments: comments
});
console.log(`Successfully created review with ${comments.length} inline comments`);
} catch (reviewError) {
console.log('Failed to create review:', reviewError.message);
// Fallback: post as a regular comment if review creation fails
const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` +
`*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` +
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: fallbackBody
});
}
} else {
// No inline comments, just post the summary
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`
});
}
// Add triggered by note if from comment
if (context.eventName === 'issue_comment') {
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: `*Inline review triggered by @${context.payload.comment.user.login}*`
});
}
} catch (error) {
console.log('Failed to post review:', error.message);
console.log('Error details:', error);
}
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload Review Artifacts
if: env.SKIP_REVIEW != 'true' && always()
uses: actions/upload-artifact@v4
with:
name: inline-review-results
path: |
inline_review_raw.json
inline_review.json
inline_review_prompt.txt
pr_diff.txt
pr_diff_annotated.txt
retention-days: 7

View file

@ -0,0 +1,96 @@
#!/usr/bin/env node
/**
* Annotates a git diff with GitHub API positions
*
* Takes a raw diff and adds [POS:N] markers with the correct
* GitHub API positions (cumulative, with +1 between hunks)
*/
const fs = require("fs");
function annotateDiff(diffContent) {
const lines = diffContent.split("\n");
const output = [];
let githubPos = 0;
let inHunk = false;
for (const line of lines) {
// Handle new file - reset position counter
if (line.startsWith("diff --git")) {
githubPos = 0;
inHunk = false;
output.push(line);
continue;
}
// Pass through other git headers unchanged
if (
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++") ||
line.startsWith("rename ") ||
line.startsWith("similarity ") ||
line.startsWith("new file") ||
line.startsWith("deleted file") ||
line.startsWith("old mode") ||
line.startsWith("new mode") ||
line.startsWith("Binary files")
) {
output.push(line);
continue;
}
// Handle hunk headers
if (line.startsWith("@@")) {
if (inHunk) {
githubPos++; // GitHub's +1 between hunks
}
inHunk = true;
output.push(line);
continue;
}
// Handle "no newline" marker - it counts as a position but isn't annotated
if (line.startsWith("\\ No newline")) {
if (inHunk) {
githubPos++; // GitHub counts this as a position
}
output.push(line); // Don't annotate it
continue;
}
// Annotate actual diff lines with GitHub positions
if (inHunk) {
githubPos++;
output.push(`[POS:${githubPos}] ${line}`);
} else {
output.push(line);
}
}
return output.join("\n");
}
// Main
function main() {
// Read diff from stdin or file
let input = "";
if (process.argv.length > 2) {
// Read from file
input = fs.readFileSync(process.argv[2], "utf8");
} else {
// Read from stdin
input = fs.readFileSync(0, "utf8");
}
const annotated = annotateDiff(input);
console.log(annotated);
}
if (require.main === module) {
main();
}
module.exports = { annotateDiff };

View file

@ -0,0 +1,363 @@
const { annotateDiff } = require("./annotate-diff.js");
describe("annotateDiff", () => {
test("single file, single hunk", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,4 @@
line1
line2
+added line
line3`;
const result = annotateDiff(diff);
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] line2");
expect(result).toContain("[POS:3] +added line");
expect(result).toContain("[POS:4] line3");
});
test("single file, multiple hunks with +1 between", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,3 @@
line1
-old line
+new line
line3
@@ -10,3 +10,3 @@
line10
-old line 11
+new line 11
line12`;
const result = annotateDiff(diff);
// First hunk
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
expect(result).toContain("[POS:3] +new line");
expect(result).toContain("[POS:4] line3");
// Second hunk (should start at 6, because 4 lines + 1 for between hunks)
expect(result).toContain("[POS:6] line10");
expect(result).toContain("[POS:7] -old line 11");
expect(result).toContain("[POS:8] +new line 11");
expect(result).toContain("[POS:9] line12");
});
test("multiple files reset position counter", () => {
const diff = `diff --git a/file1.js b/file1.js
index abc123..def456 100644
--- a/file1.js
+++ b/file1.js
@@ -1,2 +1,2 @@
line1
-old
+new
diff --git a/file2.js b/file2.js
index abc123..def456 100644
--- a/file2.js
+++ b/file2.js
@@ -1,2 +1,2 @@
first
-old2
+new2`;
const result = annotateDiff(diff);
// File 1
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old");
expect(result).toContain("[POS:3] +new");
// File 2 - positions should reset
const file2Section = result.split("diff --git a/file2.js")[1];
expect(file2Section).toContain("[POS:1] first");
expect(file2Section).toContain("[POS:2] -old2");
expect(file2Section).toContain("[POS:3] +new2");
});
test("handles new file", () => {
const diff = `diff --git a/newfile.js b/newfile.js
new file mode 100644
index 0000000..abc123
--- /dev/null
+++ b/newfile.js
@@ -0,0 +1,3 @@
+line1
+line2
+line3`;
const result = annotateDiff(diff);
expect(result).toContain("new file mode 100644");
expect(result).toContain("[POS:1] +line1");
expect(result).toContain("[POS:2] +line2");
expect(result).toContain("[POS:3] +line3");
});
test("handles deleted file", () => {
const diff = `diff --git a/deleted.js b/deleted.js
deleted file mode 100644
index abc123..0000000
--- a/deleted.js
+++ /dev/null
@@ -1,3 +0,0 @@
-line1
-line2
-line3`;
const result = annotateDiff(diff);
expect(result).toContain("deleted file mode 100644");
expect(result).toContain("[POS:1] -line1");
expect(result).toContain("[POS:2] -line2");
expect(result).toContain("[POS:3] -line3");
});
test("handles renamed file with changes", () => {
const diff = `diff --git a/old-name.js b/new-name.js
similarity index 95%
rename from old-name.js
rename to new-name.js
index abc123..def456 100644
--- a/old-name.js
+++ b/new-name.js
@@ -1,3 +1,3 @@
line1
-old line
+new line
line3`;
const result = annotateDiff(diff);
expect(result).toContain("rename from old-name.js");
expect(result).toContain("rename to new-name.js");
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
expect(result).toContain("[POS:3] +new line");
});
test("handles no newline at end of file", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,2 +1,2 @@
line1
-old line
\\ No newline at end of file
+new line
\\ No newline at end of file`;
const result = annotateDiff(diff);
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
// Position 3 is the first "No newline" marker (not annotated but counted)
expect(result).toContain("\\ No newline at end of file");
expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3
// Position 5 is the second "No newline" marker (not annotated but counted)
expect(result).toContain("\\ No newline at end of file");
// No newline markers should not get [POS:N] annotations
expect(result).not.toContain("[POS:3] \\");
expect(result).not.toContain("[POS:5] \\");
});
test("handles file mode changes", () => {
const diff = `diff --git a/script.sh b/script.sh
old mode 100644
new mode 100755
index abc123..def456 100644
--- a/script.sh
+++ b/script.sh
@@ -1,2 +1,2 @@
#!/bin/bash
-echo "old"
+echo "new"`;
const result = annotateDiff(diff);
expect(result).toContain("old mode 100644");
expect(result).toContain("new mode 100755");
expect(result).toContain("[POS:1] #!/bin/bash");
expect(result).toContain('[POS:2] -echo "old"');
expect(result).toContain('[POS:3] +echo "new"');
});
test("empty diff returns empty", () => {
const diff = "";
const result = annotateDiff(diff);
expect(result).toBe("");
});
test("handles binary files - modified", () => {
const diff = `diff --git a/image.png b/image.png
index abc123..def456 100644
Binary files a/image.png and b/image.png differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/image.png b/image.png");
expect(result).toContain("Binary files a/image.png and b/image.png differ");
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles binary files - added", () => {
const diff = `diff --git a/newimage.png b/newimage.png
new file mode 100644
index 0000000..abc123
Binary files /dev/null and b/newimage.png differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/newimage.png b/newimage.png");
expect(result).toContain("new file mode 100644");
expect(result).toContain(
"Binary files /dev/null and b/newimage.png differ",
);
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles binary files - deleted", () => {
const diff = `diff --git a/oldimage.png b/oldimage.png
deleted file mode 100644
index abc123..0000000
Binary files a/oldimage.png and /dev/null differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/oldimage.png b/oldimage.png");
expect(result).toContain("deleted file mode 100644");
expect(result).toContain(
"Binary files a/oldimage.png and /dev/null differ",
);
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles mixed text and binary files", () => {
const diff = `diff --git a/text.js b/text.js
index abc123..def456 100644
--- a/text.js
+++ b/text.js
@@ -1,2 +1,2 @@
line1
-old
+new
diff --git a/image.png b/image.png
index 111111..222222 100644
Binary files a/image.png and b/image.png differ
diff --git a/another.js b/another.js
index 333333..444444 100644
--- a/another.js
+++ b/another.js
@@ -1,1 +1,1 @@
-foo
+bar`;
const result = annotateDiff(diff);
// First file (text)
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old");
expect(result).toContain("[POS:3] +new");
// Second file (binary) - no positions
expect(result).toContain("Binary files a/image.png and b/image.png differ");
// Third file (text) - positions reset
const lastFileSection = result.split("diff --git a/another.js")[1];
expect(lastFileSection).toContain("[POS:1] -foo");
expect(lastFileSection).toContain("[POS:2] +bar");
});
test("multiple no newline markers accumulate positions", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,3 @@
line1
-old1
\\ No newline at end of file
+new1
\\ No newline at end of file
@@ -10,3 +10,3 @@
line10
-old2
\\ No newline at end of file
+new2
\\ No newline at end of file`;
const result = annotateDiff(diff);
// First hunk
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old1");
// Position 3 is the first "No newline" marker
expect(result).toContain("[POS:4] +new1");
// Position 5 is the second "No newline" marker
// Second hunk (starts at position 7 = 5 + 1 for between hunks + 1)
expect(result).toContain("[POS:7] line10");
expect(result).toContain("[POS:8] -old2");
// Position 9 is the third "No newline" marker
expect(result).toContain("[POS:10] +new2");
// Position 11 is the fourth "No newline" marker
// Verify "No newline" markers are not annotated
expect(result).not.toContain("[POS:3] \\");
expect(result).not.toContain("[POS:5] \\");
expect(result).not.toContain("[POS:9] \\");
expect(result).not.toContain("[POS:11] \\");
});
test("complex multi-file, multi-hunk diff", () => {
const diff = `diff --git a/src/app.js b/src/app.js
index abc123..def456 100644
--- a/src/app.js
+++ b/src/app.js
@@ -10,4 +10,5 @@ function example() {
console.log("start");
const x = 1;
- const y = 2;
+ const y = 3;
+ const z = 4;
return x + y;
@@ -20,3 +21,4 @@ function another() {
let a = 1;
let b = 2;
+ let c = 3;
return a + b;
diff --git a/src/util.js b/src/util.js
index 111111..222222 100644
--- a/src/util.js
+++ b/src/util.js
@@ -1,2 +1,3 @@
+import fs from 'fs';
export function util() {
return true;`;
const result = annotateDiff(diff);
// src/app.js - first hunk
expect(result).toContain('[POS:1] console.log("start");');
expect(result).toContain("[POS:2] const x = 1;");
expect(result).toContain("[POS:3] - const y = 2;");
expect(result).toContain("[POS:4] + const y = 3;");
expect(result).toContain("[POS:5] + const z = 4;");
expect(result).toContain("[POS:6] return x + y;");
// src/app.js - second hunk (7 = 6 + 1 for between hunks)
expect(result).toContain("[POS:8] let a = 1;");
expect(result).toContain("[POS:9] let b = 2;");
expect(result).toContain("[POS:10] + let c = 3;");
expect(result).toContain("[POS:11] return a + b;");
// src/util.js - new file, positions reset
const utilSection = result.split("diff --git a/src/util.js")[1];
expect(utilSection).toContain("[POS:1] +import fs from 'fs';");
expect(utilSection).toContain("[POS:2] export function util() {");
expect(utilSection).toContain("[POS:3] return true;");
});
});

View file

@ -0,0 +1,19 @@
{
"name": "@continue/pr-review-scripts",
"version": "1.0.0",
"private": true,
"description": "Scripts for Continue PR Review Action",
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
},
"devDependencies": {
"jest": "^29.7.0"
},
"jest": {
"testEnvironment": "node",
"testMatch": [
"**/*.test.js"
]
}
}

View file

@ -0,0 +1,228 @@
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'
required: true
continue-org:
description: 'Organization for Continue config'
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check Authorization
shell: bash
env:
# Only move the dangerous check to env to prevent shell injection
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }}
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 PR author association
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
fi
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
# Check if it's a PR comment with the trigger phrase
if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
fi
else
echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR"
fi
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
if: env.SHOULD_RUN == 'true'
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Continue CLI
if: env.SHOULD_RUN == 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
- name: Build PR Review Prompt
if: env.SHOULD_RUN == 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
# Get PR number based on event type
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_NUMBER="${{ github.event.number }}"
else
# For issue_comment event on a PR
PR_NUMBER="${{ github.event.issue.number }}"
fi
# Get PR diff
gh pr diff $PR_NUMBER > pr_diff.txt
# Create review prompt
cat > review_prompt.txt << 'EOF'
You are conducting a code review for a pull request. Below is the git diff showing all the changes:
EOF
echo "--- PR DIFF START ---" >> review_prompt.txt
cat pr_diff.txt >> review_prompt.txt
echo "--- PR DIFF END ---" >> review_prompt.txt
cat >> review_prompt.txt << 'EOF'
Please analyze these changes and provide a comprehensive code review. Consider:
1. **Code Quality**: Are there any bugs, performance issues, or code smells?
2. **Best Practices**: Does the code follow established patterns and conventions?
3. **Security**: Are there any potential security vulnerabilities?
4. **Testing**: Are appropriate tests included or updated?
5. **Documentation**: Is documentation adequate for the changes?
6. **Architecture**: Do the changes fit well with the existing codebase structure?
You can use the available tools to explore the codebase and understand context better.
Format your response as a markdown code review with the following structure:
## Code Review Summary
### ✅ Strengths
- **[Aspect]**: [Description of what was done well]
### ⚠️ Issues Found
Only include the severity subheaders below if you actually found issues at that level:
#### Critical
- **[Issue Title]**: [Description of critical issues that must be fixed before merging]
#### High
- **[Issue Title]**: [Description of high-priority issues that should be fixed]
#### Medium
- **[Issue Title]**: [Description of issues that should be addressed]
#### Low
- **[Issue Title]**: [Description of minor issues or nice-to-have improvements]
### 💡 Suggestions
- **[Suggestion Title]**: [Description of improvement recommendations]
### 🚀 Overall Assessment
[Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT]
Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
EOF
- name: Run Continue CLI Review
if: env.SHOULD_RUN == 'true'
shell: bash
env:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
CONTINUE_ORG: ${{ inputs.continue-org }}
CONTINUE_CONFIG: ${{ inputs.continue-config }}
run: |
echo "Running Continue CLI with prompt:"
echo "=================================="
cat review_prompt.txt
echo "=================================="
echo ""
# Validate inputs to prevent command injection
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
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
fi
# Run the CLI with validated config
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
- name: Upload Review Results
if: env.SHOULD_RUN == 'true' && always()
uses: actions/upload-artifact@v4
with:
name: code-review-results
path: |
code_review.md
review_prompt.txt
pr_diff.txt
retention-days: 30
- name: Comment PR with Review
if: env.SHOULD_RUN == 'true' && always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
try {
let reviewContent = '';
if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
reviewContent = fs.readFileSync('code_review.md', 'utf8');
} else {
reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.';
}
// Get PR number based on event type
let prNumber;
if (context.eventName === 'pull_request') {
prNumber = context.payload.pull_request.number;
} else {
// For issue_comment event
prNumber = context.payload.issue.number;
}
// Add a header if triggered by comment
if (context.eventName === 'issue_comment') {
reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`;
}
// Add instructions for re-review
reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*';
// Create new comment
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: reviewContent
});
console.log(`Successfully created new comment on PR #${prNumber}`);
} catch (error) {
console.log('Failed to post comment:', error.message);
console.log('Error details:', error);
}
branding:
icon: 'code'
color: 'blue'

4
core/.gitignore vendored
View file

@ -4,4 +4,6 @@ target
npm-debug.log*
.env
test/.continue-test
coverage
coverage
# Sentry Config File
.sentryclirc

View file

@ -20,7 +20,7 @@ import {
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { escapeForSVG, kebabOfStr } from "../util/text";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
themesDir?: string;
@ -70,28 +70,29 @@ export class CodeRenderer {
public async setTheme(themeName: string): Promise<void> {
if (
this.themeExists(kebabOfStr(themeName)) ||
this.themeExists(kebabOfThemeStr(themeName)) ||
themeName === "Default Dark Modern"
) {
this.currentTheme =
themeName === "Default Dark Modern"
? "dark-plus"
: kebabOfStr(themeName);
this.highlighter = await getSingletonHighlighter({
langs: ["typescript"],
themes: [this.currentTheme],
});
const th = this.highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
this.editorLineHighlight =
th.colors!["editor.lineHighlightBackground"] ?? "#000000";
: kebabOfThemeStr(themeName);
} else {
// Fallback to default theme for unsupported themes.
this.currentTheme = "dark-plus";
}
// Always initialize the highlighter with the current theme.
this.highlighter = await getSingletonHighlighter({
langs: ["typescript"],
themes: [this.currentTheme],
});
const th = this.highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
this.editorLineHighlight =
th.colors!["editor.lineHighlightBackground"] ?? "#000000";
}
async init(): Promise<void> {}
@ -243,7 +244,10 @@ export class CodeRenderer {
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${actualHeight}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
@ -252,7 +256,7 @@ export class CodeRenderer {
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
@ -317,29 +321,46 @@ export class CodeRenderer {
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const isSingleLine = isFirst && isLast;
const radius = 10;
// Handle single line case (both first and last)
if (isSingleLine) {
return `<path d="M ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight - radius}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
L ${radius} ${y + options.lineHeight}
Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
Z"
fill="${bgColor}" />`;
}
// 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
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");

View file

@ -17,7 +17,8 @@ import {
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import { PolicySingleton } from "../control-plane/PolicySingleton.js";
import { Logger } from "../util/Logger.js";
import { Telemetry } from "../util/posthog.js";
import {
ASSISTANTS,
@ -45,7 +46,7 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
currentOrg: OrgWithProfiles | null;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
@ -83,16 +84,9 @@ export class ConfigHandler {
this.ide,
);
// Just to be safe, always force a default personal org with local profile manager
this.currentProfile = this.globalLocalProfileManager;
const personalOrg: OrgWithProfiles = {
currentProfile: this.globalLocalProfileManager,
profiles: [this.globalLocalProfileManager],
...this.PERSONAL_ORG_DESC,
};
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
this.currentOrg = null;
this.currentProfile = null;
this.organizations = [];
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
@ -132,10 +126,10 @@ export class ConfigHandler {
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
const fallback: OrgWithProfiles | null =
firstNonPersonal ?? orgs[0] ?? null;
let selectedOrg: OrgWithProfiles;
let selectedOrg: OrgWithProfiles | null;
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
@ -153,12 +147,12 @@ export class ConfigHandler {
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
[workspaceId]: selectedOrg?.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
this.currentProfile = selectedOrg?.currentProfile;
await this.reloadConfig(reason, errors);
} catch (e) {
@ -179,10 +173,27 @@ export class ConfigHandler {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
try {
const orgDescs = await this.controlPlaneClient.listOrganizations();
// TODO use policy returned with org, not policy endpoint
const policyResponse = await this.controlPlaneClient.getPolicy();
PolicySingleton.getInstance().policy = policyResponse;
const orgDescriptions =
await this.controlPlaneClient.listOrganizations();
const orgsWithPolicy = orgDescriptions.map((d) => ({
...d,
policy: policyResponse?.policy,
}));
if (policyResponse?.policy?.allowOtherOrgs === false) {
if (orgsWithPolicy.length === 0) {
return { orgs: [] };
} else {
const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
return { orgs: [firstOrg] };
}
}
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
]);
// TODO make try/catch more granular here, to catch specific org errors
return { orgs };
@ -426,7 +437,7 @@ export class ConfigHandler {
// Org id: check id validity, save selection, switch and reload
async setSelectedOrgId(orgId: string, profileId?: string) {
if (orgId === this.currentOrg.id) {
if (orgId === this.currentOrg?.id) {
return;
}
const org = this.organizations.find((org) => org.id === orgId);
@ -454,6 +465,9 @@ export class ConfigHandler {
// Profile id: check id validity, save selection, switch and reload
async setSelectedProfileId(profileId: string) {
if (!this.currentOrg) {
throw new Error(`No org selected`);
}
if (
this.currentProfile &&
profileId === this.currentProfile.profileDescription.id
@ -490,10 +504,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [
{ message: "Current profile not found", fatal: true },
...(injectErrors ?? []),
],
errors: injectErrors,
configLoadInterrupted: true,
};
}
@ -562,7 +573,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: undefined,
configLoadInterrupted: true,
};
}
@ -575,7 +586,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: undefined,
configLoadInterrupted: true,
};
}
@ -585,7 +596,7 @@ export class ConfigHandler {
);
if (config.errors?.length) {
logger.warn("Errors loading config: ", config.errors);
Logger.error("Errors loading config: ", config.errors);
}
return config;
}
@ -598,11 +609,15 @@ export class ConfigHandler {
if (!openProfileId) {
return;
}
const profile = this.currentOrg.profiles.find(
const profile = this.currentOrg?.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (!profile) {
console.error(`Profile ${profileId} not found`);
return;
}
if (profile?.profileDescription.profileType === "local") {
if (profile.profileDescription.profileType === "local") {
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {

View file

@ -10,7 +10,7 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.currentOrg.profiles;
const profiles = testConfigHandler.currentOrg?.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].profileDescription.id).toBe("local");

View file

@ -2,6 +2,7 @@ import {
ConfigResult,
ConfigValidationError,
FullSlug,
Policy,
} from "@continuedev/config-yaml";
import {
@ -11,6 +12,7 @@ import {
IDE,
} from "../index.js";
import { Logger } from "../util/Logger.js";
import { finalToBrowserConfig } from "./load.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
@ -30,6 +32,7 @@ export interface OrganizationDescription {
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
policy?: Policy;
}
export type OrgWithProfiles = OrganizationDescription & {
@ -96,6 +99,11 @@ export class ProfileLifecycleManager {
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
// Capture config loading system failures to Sentry
Logger.error(e, {
context: "profile_config_loading",
});
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`

View file

@ -5,7 +5,7 @@ import {
import { IDE, RuleWithSource } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
import { getUriPathBasename } from "../../util/uri";
import { findUriInDirs, getUriPathBasename } from "../../util/uri";
export class CodebaseRulesCache {
private static instance: CodebaseRulesCache | null = null;
@ -26,7 +26,14 @@ export class CodebaseRulesCache {
}
async update(ide: IDE, uri: string) {
const content = await ide.readFile(uri);
const rule = markdownToRule(content, { uriType: "file", filePath: uri });
const { relativePathOrBasename } = findUriInDirs(
uri,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
const ruleWithSource: RuleWithSource = {
...rule,
source: "colocated-markdown",
@ -68,7 +75,14 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
for (const filePath of rulesMdFiles) {
try {
const content = await ide.readFile(filePath);
const rule = markdownToRule(content, { uriType: "file", filePath });
const { relativePathOrBasename } = findUriInDirs(
filePath,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
rules.push({
...rule,

View file

@ -2,6 +2,7 @@ import { markdownToRule } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IDE } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { findUriInDirs, getUriPathBasename } from "../../util/uri";
import { loadCodebaseRules } from "./loadCodebaseRules";
// Mock dependencies
@ -13,12 +14,20 @@ vi.mock("@continuedev/config-yaml", () => ({
markdownToRule: vi.fn(),
}));
vi.mock("../../util/uri", () => ({
findUriInDirs: vi.fn(),
getUriPathBasename: vi.fn(),
}));
describe("loadCodebaseRules", () => {
// Mock IDE with properly typed mock functions
const mockIde = {
readFile: vi.fn() as unknown as IDE["readFile"] & {
mockImplementation: Function;
},
getWorkspaceDirs: vi.fn() as unknown as IDE["getWorkspaceDirs"] & {
mockImplementation: Function;
},
} as unknown as IDE;
// Setup test files
@ -77,6 +86,19 @@ describe("loadCodebaseRules", () => {
// Mock walkDirs to return our test files
(walkDirs as any).mockResolvedValue(mockFiles);
// Mock getWorkspaceDirs to return a workspace directory
(mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]);
// Mock getUriPathBasename to return just the filename
(getUriPathBasename as any).mockImplementation((path: string) => {
return path.split("/").pop() || "";
});
// Mock findUriInDirs to return relative path
(findUriInDirs as any).mockImplementation((uri: string) => {
return { relativePathOrBasename: uri };
});
// Mock readFile to return content based on path
(mockIde.readFile as any).mockImplementation((path: string) => {
return Promise.resolve(mockRuleContent[path] || "");
@ -85,7 +107,7 @@ describe("loadCodebaseRules", () => {
// Mock markdownToRule to return converted rules
(markdownToRule as any).mockImplementation(
(content: string, options: any) => {
return mockConvertedRules[options.filePath];
return mockConvertedRules[options.fileUri];
},
);
});

View file

@ -3,6 +3,7 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
/**
@ -29,9 +30,13 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
// Process each markdown file
for (const file of mdFiles) {
try {
const { relativePathOrBasename } = findUriInDirs(
file.path,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(file.content, {
uriType: "file",
filePath: file.path,
fileUri: relativePathOrBasename,
});
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
} catch (e) {

View file

@ -65,8 +65,7 @@ export default class LocalProfileLoader implements IProfileLoader {
orgScopeId: null,
packageIdentifier: {
uriType: "file",
filePath:
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
fileUri: this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
},
});

View file

@ -109,7 +109,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: iconUrl,
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
uri: `${controlPlaneEnv.APP_URL}${ownerSlug}/${packageSlug}`,
rawYaml,
};

View file

@ -26,6 +26,7 @@ import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigDependentToolDefinitions } from "../../tools";
@ -35,6 +36,7 @@ import { GlobalContext } from "../../util/GlobalContext";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { SentryLogger } from "../../util/sentry/SentryLogger";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
@ -60,6 +62,11 @@ async function loadRules(ide: IDE) {
rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
// Add colocated rules from CodebaseRulesCache
const codebaseRulesCache = CodebaseRulesCache.getInstance();
rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
return { rules, errors };
}
export default async function doLoadConfig(options: {
@ -180,11 +187,6 @@ export default async function doLoadConfig(options: {
}
});
// Add rules from colocated rules.md files in the codebase
const codebaseRulesCache = CodebaseRulesCache.getInstance();
newConfig.rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -325,8 +327,18 @@ export default async function doLoadConfig(options: {
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
if (newConfig.allowAnonymousTelemetry !== false) {
if ((await ide.isTelemetryEnabled()) === false) {
newConfig.allowAnonymousTelemetry = false;
}
}
if (
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
false
) {
newConfig.allowAnonymousTelemetry = false;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
@ -335,6 +347,24 @@ export default async function doLoadConfig(options: {
ideInfo,
);
// Setup Sentry logger with same telemetry settings
// TODO: Remove Continue team member check once Sentry is ready for all users
let userEmail: string | undefined;
try {
// Access the session info to get user email for Continue team member check
const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
userEmail = sessionInfo?.account?.id;
} catch (error) {
// Ignore errors getting session info, will default to no Sentry
}
await SentryLogger.setup(
newConfig.allowAnonymousTelemetry ?? false,
await ide.getUniqueId(),
ideInfo,
userEmail,
);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();

View file

@ -387,6 +387,7 @@ declare global {
export interface PromptLog {
modelTitle: string;
modelProvider: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;

View file

@ -10,7 +10,6 @@ import {
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";
@ -80,12 +79,6 @@ export function addModel(
maxStopWords: model.maxStopWords,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {
desc.chatOptions = {
baseSystemMessage:
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
};
}
config.models.push(desc);
return config;
},

View file

@ -23,7 +23,7 @@ export async function unrollLocalYamlBlocks(
const unrollResult = await unrollAssistantFromContent(
{
uriType: "file",
filePath: "",
fileUri: "",
},
"name: FILLER\nschema: v1\nversion: 0.0.1",
registryClient,

View file

@ -72,7 +72,7 @@ async function loadConfigYaml(options: {
);
return localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
fileUri: b.path,
}));
});
const localPackageIdentifiers: PackageIdentifier[] = (
@ -87,7 +87,7 @@ async function loadConfigYaml(options: {
const getRegistryClient = async () => {
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
? dirname(getCleanUriPath(packageIdentifier.fileUri))
: undefined;
return new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
@ -428,6 +428,7 @@ async function configYamlToContinueConfig(options: {
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
return { config: continueConfig, errors: localErrors };

View file

@ -1,12 +1,16 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
SSEClientTransport,
SseError,
} from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
IDE,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
@ -16,6 +20,7 @@ import {
MCPTool,
} from "../..";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
@ -30,10 +35,23 @@ const WINDOWS_BATCH_COMMANDS = [
"bunx",
];
function is401Error(error: unknown) {
return (
(error instanceof SseError && error.code === 401) ||
(error instanceof Error && error.message.includes("401")) ||
(error instanceof Error && error.message.includes("Unauthorized"))
);
}
export type MCPExtras = {
ide: IDE;
};
class MCPConnection {
public client: Client;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
@ -46,7 +64,10 @@ class MCPConnection {
stderr: "",
};
constructor(public options: MCPOptions) {
constructor(
public options: MCPOptions,
public extras?: MCPExtras,
) {
// Don't construct transport in constructor to avoid blocking
this.transport = {} as Transport; // Will be set in connectClient
@ -78,6 +99,7 @@ class MCPConnection {
resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
isProtectedResource: this.isProtectedResource,
};
}
@ -106,6 +128,26 @@ class MCPConnection {
this.abortController.abort();
this.abortController = new AbortController();
// currently support oauth for sse transports only
if (this.options.transport.type === "sse") {
if (!this.options.transport.requestOptions) {
this.options.transport.requestOptions = {
headers: {},
};
}
const accessToken = await getOauthToken(
this.options.transport.url,
this.extras?.ide!,
);
if (accessToken) {
this.isProtectedResource = true;
this.options.transport.requestOptions.headers = {
...this.options.transport.requestOptions.headers,
Authorization: `Bearer ${accessToken}`,
};
}
}
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
@ -244,6 +286,10 @@ class MCPConnection {
}
}
if (is401Error(error)) {
this.isProtectedResource = true;
}
// Include stdio output if available for stdio transport
if (
this.options.transport.type === "stdio" &&

View file

@ -1,7 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
import { StdioOptions } from "../../index.d.js";
// Mock the shell path utility
vi.mock("../../util/shellPath", () => ({
@ -143,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
isProtectedResource: false,
prompts: [],
resources: [],
resourceTemplates: [],

View file

@ -6,7 +6,7 @@ import {
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
import MCPConnection, { MCPExtras } from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
@ -26,12 +26,12 @@ export class MCPManagerSingleton {
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
if (this.connections.has(id)) {
return this.connections.get(id)!;
} else {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
@ -48,7 +48,11 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
setConnections(
servers: MCPOptions[],
forceRefresh: boolean,
extras?: MCPExtras,
) {
let refresh = false;
// Remove any connections that are no longer in config
@ -73,15 +77,15 @@ export class MCPManagerSingleton {
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
if (this.connections.has(server.id)) {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
} else {
refresh = true;
this.connections.set(server.id, new MCPConnection(server, extras));
}
});
@ -162,6 +166,10 @@ export class MCPManagerSingleton {
}));
}
setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
this.connections.get(server.id)!.status = status;
}
async getPrompt(
serverName: string,
promptName: string,

View file

@ -0,0 +1,227 @@
import {
OAuthClientProvider,
auth,
} from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthClientInformationFull,
OAuthClientInformationSchema,
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { IDE, MCPServerStatus, SSEOptions } from "../..";
import http from "http";
import url from "url";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
let authenticatingMCPContext = null as {
authenticatingServer: MCPServerStatus;
ide: IDE;
} | null;
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const html = `
<!DOCTYPE html>
<html>
<head><title>Authentication Complete</title></head>
<body>Authentication Complete. You can close this page now.</body>
</html>`;
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;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
}
get redirectUrl() {
return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
}
get clientMetadata() {
return {
redirect_uris: [this.redirectUrl],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
client_name: "Continue Dev, Inc", // get this from package.json?
client_uri: "https://continue.dev", // get this from package.json?
};
}
private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
key
];
}
private _updateOauthStorage<K extends MCPOauthStorageKey>(
key: K,
value: MCPOauthStorage[K],
) {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
this.globalContext.update("mcpOauthStorage", {
...existingStorage,
[this.oauthServerUrl]: {
...existingServerStorage,
[key]: value,
},
});
}
private _clearOauthStorage() {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
delete existingStorage[this.oauthServerUrl];
this.globalContext.update("mcpOauthStorage", existingStorage);
}
saveClientInformation(clientInformation: OAuthClientInformationFull) {
this._updateOauthStorage("clientInformation", clientInformation);
}
async clientInformation() {
const existingClientInformation =
this._getOauthStorage("clientInformation");
if (!existingClientInformation) {
return undefined;
}
return await OAuthClientInformationSchema.parseAsync(
existingClientInformation,
);
}
async tokens() {
const existingTokens = this._getOauthStorage("tokens");
if (!existingTokens) {
return undefined;
}
return await OAuthTokensSchema.parseAsync(existingTokens);
}
saveTokens(tokens: OAuthTokens) {
this._updateOauthStorage("tokens", tokens);
}
codeVerifier(): string | Promise<string> {
const existingCodeVerifier = this._getOauthStorage("codeVerifier");
if (!existingCodeVerifier) {
return "";
}
return existingCodeVerifier;
}
saveCodeVerifier(codeVerifier: string) {
this._updateOauthStorage("codeVerifier", codeVerifier);
}
clear() {
this._clearOauthStorage();
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
}
void this.ide.openUrl(authorizationUrl.toString());
}
}
export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
const tokens = await authProvider.tokens();
return tokens?.access_token;
}
/**
* checks if the authentication is already done for the current server
* if not, starts the authentication process by opening a webpage url
*/
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authenticatingMCPContext = {
authenticatingServer: mcpServer,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
});
}
/**
* 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;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
}
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) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authProvider.clear();
}

View file

@ -0,0 +1,181 @@
import fs from "node:fs";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { GlobalContext } from "../../util/GlobalContext";
import { getGlobalContextFilePath } from "../../util/paths";
import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
// Mock the MCP SDK auth module
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
auth: vi.fn(),
}));
// Mock the MCPManagerSingleton to avoid circular imports
vi.mock("./MCPManagerSingleton", () => ({
MCPManagerSingleton: {
getInstance: vi.fn(() => ({
refreshConnection: vi.fn(),
})),
},
}));
describe("MCPOauth", () => {
let globalContextFilePath: string;
let mockIde: any;
let mockMcpServer: any;
beforeEach(() => {
// file is present in the core/test directory
globalContextFilePath = getGlobalContextFilePath();
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
};
mockMcpServer = {
id: "test-server",
transport: {
type: "sse",
url: "https://test-server.com",
},
};
vi.clearAllMocks();
});
afterEach(() => {
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
});
describe("getOauthToken", () => {
test("should return undefined when no tokens are stored", async () => {
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBeUndefined();
});
test("should return access token when tokens are stored", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
},
});
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBe("test-access-token");
});
test("should handle different server URLs independently", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://server1.com": {
tokens: {
access_token: "token1",
token_type: "Bearer",
},
},
"https://server2.com": {
tokens: {
access_token: "token2",
token_type: "Bearer",
},
},
});
const result1 = await getOauthToken("https://server1.com", mockIde);
const result2 = await getOauthToken("https://server2.com", mockIde);
const result3 = await getOauthToken("https://server3.com", mockIde);
expect(result1).toBe("token1");
expect(result2).toBe("token2");
expect(result3).toBeUndefined();
});
});
describe("performAuth", () => {
test("should call auth with correct parameters and return auth result", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
expect(mockAuth).toHaveBeenCalledWith(
expect.any(Object), // MCPConnectionOauthProvider instance
{
serverUrl: "https://test-server.com",
},
);
expect(result).toBe("AUTHORIZED");
});
});
describe("removeMCPAuth", () => {
test("should clear oauth storage for the server", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
clientInformation: {
client_id: "test-client-id",
redirect_uris: ["http://localhost:3000"],
},
codeVerifier: "test-code-verifier",
},
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
test("should handle non-existent server gracefully", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
});
});

View file

@ -18,6 +18,10 @@ class ClipboardContextProvider extends BaseContextProvider {
type: "submenu",
};
get deprecationMessage() {
return "The clipboard context provider is deprecated as it is not used. It will be removed in a future version.";
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

View file

@ -43,9 +43,13 @@ class DocsContextProvider extends BaseContextProvider {
try {
const scores = await reranker.rerank(fullInput, chunksCopy);
chunksCopy.sort(
(a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
if (Array.isArray(scores)) {
// reranker model has returned a valid array
chunksCopy.sort(
(a, b) =>
scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
}
chunksCopy = chunksCopy.splice(
0,

View file

@ -18,7 +18,7 @@ class MCPContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "mcp",
displayTitle: "MCP",
description: "Model Context Protocol",
description: "MCP Resources",
type: "submenu",
renderInlineAs: "",
};
@ -29,7 +29,7 @@ class MCPContextProvider extends BaseContextProvider {
? `${this.options["serverName"]} resources`
: "MCP",
renderInlineAs: "",
description: "Model Context Protocol",
description: "MCP Resources",
type: "submenu",
};
}

View file

@ -36,6 +36,7 @@ async function getContextProviderExtras(
llmLogger,
Promise.resolve(undefined),
);
await configHandler.isInitialized;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
@ -54,7 +55,7 @@ async function getContextProviderExtras(
};
}
describe.skip("Should successfully run all context providers", () => {
describe("Should successfully run all context providers", () => {
afterAll(() => {
tearDownTestDir();
});

View file

@ -27,7 +27,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
embeddingsChunks = Boolean(config.selectedModelByRole.embed)
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
@ -116,7 +116,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
results?.sort(
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(0, this.options.nFinal);

View file

@ -0,0 +1,15 @@
import { PolicyResponse } from "./client.js";
export class PolicySingleton {
private static instance: PolicySingleton;
public policy: PolicyResponse | null = null;
private constructor() {}
public static getInstance(): PolicySingleton {
if (!PolicySingleton.instance) {
PolicySingleton.instance = new PolicySingleton();
}
return PolicySingleton.instance;
}
}

View file

@ -4,6 +4,7 @@ import {
ConfigResult,
FQSN,
FullSlug,
Policy,
SecretResult,
SecretType,
} from "@continuedev/config-yaml";
@ -11,10 +12,16 @@ import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import { Logger } from "../util/Logger.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface PolicyResponse {
orgSlug?: string;
policy?: Policy;
}
export interface ControlPlaneWorkspace {
id: string;
name: string;
@ -140,6 +147,11 @@ export class ControlPlaneClient {
});
return (await resp.json()) as any;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_list_assistants",
organizationId,
});
return [];
}
}
@ -210,6 +222,26 @@ export class ControlPlaneClient {
});
const { fullSlugs } = (await resp.json()) as any;
return fullSlugs;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_list_assistant_slugs",
organizationId,
});
return null;
}
}
public async getPolicy(): Promise<PolicyResponse | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.request(`ide/policy`, {
method: "GET",
});
return (await resp.json()) as PolicyResponse;
} catch (e) {
return null;
}
@ -226,6 +258,10 @@ export class ControlPlaneClient {
});
return (await resp.json()) as FreeTrialStatus;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_free_trial_status",
});
return null;
}
}
@ -260,6 +296,11 @@ export class ControlPlaneClient {
);
return (await resp.json()) as { url: string };
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_models_checkout_url",
vsCodeUriScheme,
});
return null;
}
}

View file

@ -23,7 +23,6 @@ import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
@ -61,6 +60,7 @@ import {
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
@ -71,10 +71,12 @@ import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
import { llmStreamChat } from "./llm/streamChat";
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue";
import { NextEditProvider } from "./nextEdit/NextEditProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { Logger } from "./util/Logger.js";
import { getUriPathBasename } from "./util/uri";
const hasRulesFiles = (uris: string[]): boolean => {
@ -130,114 +132,143 @@ export class Core {
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
private readonly ide: IDE,
) {
// Ensure .continue directory is created
migrateV1DevDataFiles();
try {
// Ensure .continue directory is created
migrateV1DevDataFiles();
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
useOnboarding: false,
});
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.llmLogger,
sessionInfoPromise,
);
this.docsService = DocsService.createSingleton(
this.configHandler,
this.ide,
this.messenger,
);
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig("MCP Connections refreshed");
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
(mcpId) => `mcp-${mcpId}`,
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request(
"getControlPlaneSessionInfo",
{
silent: true,
useOnboarding: false,
},
);
if (mcpProviderNames.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: mcpProviderNames,
});
}
};
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.llmLogger,
sessionInfoPromise,
);
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
this.docsService = DocsService.createSingleton(
this.configHandler,
this.ide,
this.messenger,
);
this.configHandler.onConfigUpdate((result) => {
void (async () => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
});
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig("MCP Connections refreshed");
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
(mcpId) => `mcp-${mcpId}`,
);
if (mcpProviderNames.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
providers: mcpProviderNames,
});
}
})();
});
};
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
this.configHandler.onConfigUpdate((result) => {
void (async () => {
const serializedResult =
await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
});
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
);
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache
.refresh(ide)
.catch((e) => console.error("Failed to initialize colocated rules cache"))
.then(() => {
void this.configHandler.reloadConfig(
"Initial codebase rules post-walkdir/load reload",
);
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
});
}
})();
});
this.nextEditProvider = NextEditProvider.initialize(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
"fineTuned",
);
this.registerMessageHandlers(ideSettingsPromise);
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
void ideSettingsPromise.then((ideSettings) => {
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
this.codeBaseIndexer.paused = true;
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Initial Indexing Skipped",
status: "paused",
});
return;
}
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
);
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache
.refresh(ide)
.catch((e) =>
Logger.error("Failed to initialize colocated rules cache"),
)
.then(() => {
void this.configHandler.reloadConfig(
"Initial codebase rules post-walkdir/load reload",
);
});
this.nextEditProvider = NextEditProvider.initialize(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
"fineTuned",
);
this.registerMessageHandlers(ideSettingsPromise);
} catch (error) {
Logger.error(error);
throw error; // Re-throw to prevent partially initialized core
}
}
/* eslint-disable max-lines-per-function */
@ -417,6 +448,19 @@ export class Core {
description: prompt.description,
};
});
on("mcp/startAuthentication", async (msg) => {
await new Promise((resolve) => setTimeout(resolve, 5000));
MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
const status = await performAuth(msg.data, this.ide);
if (status === "AUTHORIZED") {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
}
});
on("mcp/removeAuthentication", async (msg) => {
removeMCPAuth(msg.data, this.ide);
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -447,7 +491,7 @@ export class Core {
});
return items || [];
} catch (e) {
console.error(e);
Logger.error(e);
return [];
}
});
@ -465,19 +509,10 @@ export class Core {
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
};
});
on("clipboardCache/add", (msg) => {
const added = clipboardCache.add(uuidv4(), msg.data.content);
if (added) {
this.messenger.send("refreshSubmenuItems", {
providers: ["clipboard"],
});
}
});
on("llm/streamChat", (msg) => {
const abortController = this.addMessageAbortController(msg.messageId);
return llmStreamChat(
@ -554,7 +589,7 @@ export class Core {
});
return undefined;
} catch (error) {
console.error("Error compacting conversation:", error);
Logger.error(`Error compacting conversation: ${error}`);
return undefined;
}
});
@ -578,18 +613,80 @@ export class Core {
// Next Edit
on("nextEdit/predict", async (msg) => {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
msg.data.input,
undefined,
{ withChain: false, usingFullFileDiff: true },
{
withChain: msg.data.options?.withChain ?? false,
usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true,
},
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
return outcome;
// ? [outcome.completion, outcome.originalEditableRange]
});
on("nextEdit/accept", async (msg) => {
console.log("nextEdit/accept");
this.nextEditProvider.accept(msg.data.completionId);
});
on("nextEdit/reject", async (msg) => {
console.log("nextEdit/reject");
this.nextEditProvider.reject(msg.data.completionId);
});
on("nextEdit/startChain", async (msg) => {
console.log("nextEdit/startChain");
NextEditProvider.getInstance().startChain();
return;
});
on("nextEdit/deleteChain", async (msg) => {
console.log("nextEdit/deleteChain");
await NextEditProvider.getInstance().deleteChain();
return;
});
on("nextEdit/isChainAlive", async (msg) => {
console.log("nextEdit/isChainAlive");
return NextEditProvider.getInstance().chainExists();
});
on("nextEdit/queue/getProcessedCount", async (msg) => {
console.log("nextEdit/queue/getProcessedCount");
const queue = PrefetchQueue.getInstance();
console.log(queue.processedCount);
return queue.processedCount;
});
on("nextEdit/queue/dequeueProcessed", async (msg) => {
console.log("nextEdit/queue/dequeueProcessed");
const queue = PrefetchQueue.getInstance();
return queue.dequeueProcessed() || null;
});
on("nextEdit/queue/processOne", async (msg) => {
console.log("nextEdit/queue/processOne");
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
const queue = PrefetchQueue.getInstance();
await queue.process({
...ctx,
recentlyVisitedRanges,
recentlyEditedRanges,
});
return;
});
on("nextEdit/queue/clear", async (msg) => {
console.log("nextEdit/queue/clear");
const queue = PrefetchQueue.getInstance();
queue.clear();
return;
});
on("nextEdit/queue/abort", async (msg) => {
console.log("nextEdit/queue/abort");
const queue = PrefetchQueue.getInstance();
queue.abort();
return;
});
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
@ -762,7 +859,7 @@ export class Core {
prevFilepaths.filepaths = filepaths;
}
} catch (e) {
console.error(
Logger.error(
`didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
);
}
@ -787,7 +884,7 @@ export class Core {
openedFilesLruCache.set(filepath, filepath);
}
} catch (e) {
console.error(
Logger.error(
`files/opened: failed to update openedFiles cache for ${filepath}`,
);
}
@ -1067,7 +1164,7 @@ export class Core {
void this.configHandler.reloadConfig("Codebase rule update");
});
} catch (e) {
console.error("Failed to update codebase rule", e);
Logger.error(`Failed to update codebase rule: ${e}`);
}
} else if (
uri.endsWith(".continueignore") ||
@ -1144,7 +1241,7 @@ export class Core {
break;
default:
console.error(`Invalid mode: ${mode}`);
Logger.error(`Invalid mode: ${mode}`);
editConfigYamlCallback = (config) => config;
}

View file

@ -34,6 +34,7 @@ const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = {
prompt: "Hello, world!",
completion: "Hello, world!",
modelProvider: "openai",
modelName: "gpt-4",
modelTitle: "gpt-4",
sessionId: "1234",
tools: ["test-tool1"],

View file

@ -7,6 +7,7 @@ const INFINITE_STREAM_SAFETY = 0.9;
const DUD_PROMPT_LOG: PromptLog = {
modelTitle: "",
modelProvider: "",
completionOptions: { model: "" },
prompt: "",
completion: "",

3
core/index.d.ts vendored
View file

@ -455,6 +455,7 @@ export type FileSymbolMap = Record<string, SymbolWithRange[]>;
export interface PromptLog {
modelTitle: string;
modelProvider: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
@ -1278,6 +1279,7 @@ export type MCPConnectionStatus =
| "connecting"
| "connected"
| "error"
| "authenticating"
| "not-connected";
export type MCPPromptArgs = {
@ -1323,6 +1325,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
tools: MCPTool[];

View file

@ -10,6 +10,7 @@ import {
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { Logger } from "../util/Logger.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
@ -56,7 +57,7 @@ export class CodebaseIndexer {
// and only need to `await` it for tests.
public initPromise: Promise<void>;
private config!: ContinueConfig;
private indexingCancellationController: AbortController | undefined;
private indexingCancellationController: AbortController;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -97,6 +98,9 @@ export class CodebaseIndexer {
this.pauseToken = new PauseToken(initialPaused);
this.initPromise = this.init(configHandler);
this.indexingCancellationController = new AbortController();
this.indexingCancellationController.abort(); // initialize and abort so that a new one can be created
}
// Initialization - load config and attach config listener
@ -123,12 +127,20 @@ export class CodebaseIndexer {
try {
await fs.unlink(sqliteFilepath);
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
filepath: sqliteFilepath,
});
console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
}
try {
await fs.rm(lanceDbFolder, { recursive: true, force: true });
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
folderPath: lanceDbFolder,
});
console.error(`Error deleting ${lanceDbFolder}: ${error}`);
}
}
@ -693,7 +705,7 @@ export class CodebaseIndexer {
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
if (!this.indexingCancellationController.signal.aborted) {
this.indexingCancellationController.abort();
}
const localController = new AbortController();
@ -735,16 +747,13 @@ export class CodebaseIndexer {
});
}
if (this.indexingCancellationController === localController) {
this.indexingCancellationController = undefined;
this.indexingCancellationController.abort();
}
}
public async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
if (!this.indexingCancellationController.signal.aborted) {
return;
}
const localController = new AbortController();
@ -770,7 +779,7 @@ export class CodebaseIndexer {
});
}
if (this.indexingCancellationController === localController) {
this.indexingCancellationController = undefined;
this.indexingCancellationController.abort();
}
}

View file

@ -1,25 +0,0 @@
import OpenAI from "../../llm/llms/OpenAI";
import { DocsCache } from "./DocsCache"; // adjust import path as needed
describe("DocsCache", () => {
let openAIEmbeddings: OpenAI;
beforeAll(() => {
openAIEmbeddings = new OpenAI({
apiKey: "",
model: "text-embedding-ada-002",
});
});
test("normalizeEmbeddingId() produces a valid ID without constructor name", async () => {
// Get the embedding ID from OpenAI embeddings provider
const embeddingId = DocsCache.normalizeEmbeddingId(
openAIEmbeddings.embeddingId,
);
// The ID should not contain the constructor name (OpenAI)
expect(embeddingId).toEqual(
`${openAIEmbeddings.model}::${openAIEmbeddings.maxEmbeddingChunkSize}`,
);
});
});

View file

@ -1,93 +0,0 @@
import request from "request";
import { Chunk } from "../..";
export interface SiteIndexingResults {
chunks: (Chunk & { embedding: number[] })[];
url: string;
title: string;
}
/**
* Strip off the trailing forward slash from the given URL
* @param url The URL of the document
* @returns A sanitized URL without trailing forward slash
*/
const stripTrailingSlash = (url: string): string => {
return url.replace(/\/+$/, "");
};
export class DocsCache {
static readonly AWS_REGION: string = "us-west-1";
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
/**
* Normalizes an embedding ID by stripping the constructor name part.
* This is done because we don't care about the provider, just the
* model and the max embedding chunk size.
*/
static normalizeEmbeddingId(embeddingId: string): string {
// Split by "::" and remove the first part (constructor name)
const parts = embeddingId.split("::");
if (parts.length <= 1) return embeddingId; // Return original if no "::" found
// Return everything except the first part, joining with "::"
return parts.slice(1).join("::");
}
/**
* Gets the filepath for a given embedding ID and URL
*/
static getFilepathForEmbeddingIdAndUrl(
embeddingId: string,
url: string,
): string {
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
const sanitizedUrl = stripTrailingSlash(url);
const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
return normalizedEmbeddingId + "/" + normalizedUrl;
}
/**
* Gets the fully qualified S3 URL for a given filepath
*/
private static getS3Url(filepath: string): string {
const pathname = filepath.split("/").map(encodeURIComponent).join("/");
return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`;
}
/**
* Downloads cached site indexing results from S3 for a given embedding ID and URL
* @param embeddingId The embedding ID
* @param url The URL of the document
* @returns The downloaded data as a string
*/
static async getDocsCacheForUrl(
embeddingId: string,
url: string,
): Promise<string> {
const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl(
embeddingId,
url,
);
return new Promise<string>((resolve, reject) => {
let data = "";
const url = this.getS3Url(filepath);
const download = request({
url,
});
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
reject(
new Error("There was an error retrieving the pre-indexed doc"),
);
}
});
download.on("error", (err: any) => reject(err));
download.on("data", (chunk: any) => (data += chunk));
download.on("end", () => resolve(data));
});
}
}

View file

@ -37,7 +37,6 @@ import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import type * as LanceType from "vectordb";
import { LLMError } from "../../llm";
import { DocsCache, SiteIndexingResults } from "./DocsCache";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -433,60 +432,6 @@ export default class DocsService {
}
}
/**
* Attempt to load document embeddings from cache
* @returns true if cache was successfully loaded, false otherwise
*/
private async tryLoadFromCache(
startUrl: string,
embeddingId: string,
siteIndexingConfig: SiteIndexingConfig,
): Promise<boolean> {
try {
// Set a initial status when retrieving cache
this.handleStatusUpdate({
type: "docs",
id: startUrl,
embeddingsProviderId: embeddingId,
isReindexing: false,
title: siteIndexingConfig.title,
debugInfo: "Loaded from cache",
icon: siteIndexingConfig.faviconUrl,
url: startUrl,
progress: 0,
description: "Try to retrieve cache",
status: "indexing",
});
const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
if (cacheHit) {
console.log(`Successfully loaded cached embeddings for ${startUrl}`);
// Update status to complete
this.handleStatusUpdate({
type: "docs",
id: startUrl,
embeddingsProviderId: embeddingId,
isReindexing: false,
title: siteIndexingConfig.title,
debugInfo: "Loaded from cache",
icon: siteIndexingConfig.faviconUrl,
url: startUrl,
progress: 1,
description: "Complete",
status: "complete",
});
return true;
}
} catch (e) {
console.log(`Error trying to fetch from cache: ${e}`);
// Continue with regular indexing
}
return false;
}
// eslint-disable-next-line max-statements
async indexAndAdd(
siteIndexingConfig: SiteIndexingConfig,
@ -508,19 +453,6 @@ export default class DocsService {
return;
}
// Try to fetch from cache first before crawling
if (!forceReindex) {
const cacheLoaded = await this.tryLoadFromCache(
startUrl,
provider.embeddingId,
siteIndexingConfig,
);
if (cacheLoaded) {
return;
}
}
const startedWithEmbedder = provider.embeddingId;
// Check if doc has been successfully indexed with the given embedder
@ -811,52 +743,6 @@ export default class DocsService {
}
}
/**
* Try to fetch embeddings from the S3 cache for any document URL
* @param startUrl The URL of the documentation site
* @param embeddingsProviderId The ID of the embeddings provider
* @returns True if cache hit and successfully loaded, false otherwise
*/
private async tryFetchFromCache(
startUrl: string,
embeddingId: string,
): Promise<boolean> {
try {
const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl);
// Parse the cached data
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
// Try to get a favicon for the site
const favicon =
this.statuses.get(startUrl)?.icon ||
(await fetchFavicon(new URL(startUrl)));
// Always try to make the title match what users set in the config
const title =
this.statuses.get(startUrl)?.title ||
siteEmbeddings.title ||
new URL(startUrl).hostname;
// Add the cached embeddings to our database
await this.add({
favicon,
siteIndexingConfig: {
startUrl,
title,
},
chunks: siteEmbeddings.chunks,
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
});
return true;
} catch (e) {
// Cache miss or error - silently fail
console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`);
return false;
}
}
// Retrieve docs embeds based on user input
async retrieveChunksFromQuery(
query: string,
@ -940,7 +826,6 @@ export default class DocsService {
}
}
// This function attempts to retrieve chunks by vector similarity
// It will also attempt to fetch from cache if no results are found
async retrieveChunks(
startUrl: string,
vector: number[],
@ -970,28 +855,6 @@ export default class DocsService {
console.warn("Error retrieving chunks from LanceDB", e);
}
// If no docs are found and this isn't a retry, try fetching from cache
if (docs.length === 0 && !isRetry) {
try {
// Try to fetch the document from the S3 cache
const cacheHit = await this.tryFetchFromCache(
startUrl,
provider.embeddingId,
);
if (cacheHit) {
// If cache hit, refresh the submenu items for docs
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
// If cache hit, retry the search once
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
}
} catch (e) {
console.warn("Error trying to fetch from cache:", e);
}
}
return docs.map(this.lanceDBRowToChunk);
}

View file

@ -178,7 +178,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.MODEL_1,
NEXT_EDIT_MODELS.INSTINCT,
];
function modelSupportsNextEdit(

View file

@ -245,8 +245,10 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true for model-1", () => {
expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
it("should return true for instinct", () => {
expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe(
true,
);
});
it("should return true when model contains supported model name as substring", () => {
@ -269,9 +271,9 @@ describe("modelSupportsNextEdit", () => {
).toBe(true);
});
it("should return true when title contains model-1", () => {
it("should return true when title contains instinct", () => {
expect(
modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
modelSupportsNextEdit(undefined, "some-model", "instinct deployment"),
).toBe(true);
});
@ -317,7 +319,7 @@ describe("modelSupportsNextEdit", () => {
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
).toBe(true);
});

View file

@ -21,7 +21,7 @@ export enum LLMConfigurationStatuses {
export enum NEXT_EDIT_MODELS {
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
MODEL_1 = "model-1",
INSTINCT = "instinct",
}
export {

View file

@ -9,6 +9,7 @@ import {
import Handlebars from "handlebars";
import { DevDataSqliteDb } from "../data/devdataSqlite.js";
import { Logger } from "../util/Logger.js";
import { DataLogger } from "../data/log.js";
import {
CacheBehavior,
@ -471,6 +472,15 @@ export abstract class BaseLLM implements ILLM {
return resp;
} catch (e: any) {
// Capture all fetch errors to Sentry for monitoring
Logger.error(e, {
context: "llm_fetch",
url: String(input),
method: init?.method || "GET",
model: this.model,
provider: this.providerName,
});
// Errors to ignore
if (e.message.includes("/api/tags")) {
throw new Error(`Error fetching tags: ${e.message}`);
@ -635,6 +645,14 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture FIM (Fill-in-the-Middle) completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_fim",
model: completionOptions.model,
provider: this.providerName,
useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamFim"),
});
status = this._logEnd(
completionOptions.model,
fimLog,
@ -753,6 +771,15 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture streaming completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_complete",
model: completionOptions.model,
provider: this.providerName,
useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamComplete"),
streamEnabled: completionOptions.stream !== false,
});
status = this._logEnd(
completionOptions.model,
prompt,
@ -779,6 +806,7 @@ export abstract class BaseLLM implements ILLM {
return {
modelTitle: this.title ?? completionOptions.model,
modelProvider: this.underlyingProviderName,
prompt,
completion,
completionOptions,
@ -850,6 +878,14 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture completion failures to Sentry
Logger.error(e as Error, {
context: "llm_complete",
model: completionOptions.model,
provider: this.providerName,
useOpenAIAdapter: this.shouldUseOpenAIAdapter("complete"),
});
status = this._logEnd(
completionOptions.model,
prompt,
@ -1059,6 +1095,16 @@ export abstract class BaseLLM implements ILLM {
usage,
);
} catch (e) {
// Capture chat streaming failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_chat",
model: completionOptions.model,
provider: this.providerName,
useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamChat"),
streamEnabled: completionOptions.stream !== false,
templateMessages: !!this.templateMessages,
});
status = this._logEnd(
completionOptions.model,
prompt,
@ -1094,6 +1140,7 @@ export abstract class BaseLLM implements ILLM {
return {
modelTitle: this.title ?? completionOptions.model,
modelProvider: this.underlyingProviderName,
prompt,
completion,
completionOptions,

View file

@ -23,6 +23,7 @@ async function dudLLMCall(llm: ILLM, messages: ChatMessage[]) {
model: "",
},
modelTitle: "",
modelProvider: "",
prompt: "",
});
abortController.abort();

View file

@ -1,7 +1,21 @@
import { Chunk, LLMOptions } from "../../index.js";
import { z } from "zod";
import { Chunk, LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
/**used to check a valid response from voyage is received
* reference: https://docs.voyageai.com/reference/reranker-api
*/
const VoyageRerankSuccessResponseSchema = z.object({
data: z.array(
z.object({
index: z.number(),
relevance_score: z.number(),
document: z.string(),
}),
),
});
class Voyage extends OpenAI {
static providerName = "voyage";
static defaultOptions: Partial<LLMOptions> | undefined = {
@ -36,7 +50,10 @@ class Voyage extends OpenAI {
const data = (await resp.json()) as {
data: Array<{ index: number; relevance_score: number }>;
};
const results = data.data.sort((a, b) => a.index - b.index);
const parsedData = VoyageRerankSuccessResponseSchema.parse(data);
const results = parsedData.data.sort((a, b) => a.index - b.index);
return results.map((result) => result.relevance_score);
}
}

View file

@ -40,6 +40,7 @@ export async function* llmStreamChat(
// Log to return in case of error
const errorPromptLog = {
modelTitle: model?.title ?? model?.model,
modelProvider: model?.underlyingProviderName ?? "unknown",
completion: "",
prompt: "",
completionOptions: {
@ -48,114 +49,136 @@ export async function* llmStreamChat(
},
};
if (legacySlashCommandData) {
const { command, contextItems, historyIndex, input, selectedCode } =
legacySlashCommandData;
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === command.name,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${command.name}`);
}
void Telemetry.capture(
"useSlashCommand",
{
name: command.name,
},
true,
);
if (!slashCommand.run) {
console.error(
`Slash command ${command.name} (${command.source}) has no run function`,
try {
if (legacySlashCommandData) {
const { command, contextItems, historyIndex, input, selectedCode } =
legacySlashCommandData;
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === command.name,
);
throw new Error(`Slash command not found`);
}
const gen = slashCommand.run({
input,
history: messages,
llm: model,
contextItems,
params: command.params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(
url,
{
...init,
signal: abortController.signal,
},
config.requestOptions,
),
completionOptions,
abortController,
});
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
if (!slashCommand) {
throw new Error(`Unknown slash command ${command.name}`);
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} else {
const gen = model.streamChat(
messages,
abortController.signal,
completionOptions,
messageOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
void Telemetry.capture(
"useSlashCommand",
{
name: command.name,
},
true,
);
if (!slashCommand.run) {
console.error(
`Slash command ${command.name} (${command.source}) has no run function`,
);
throw new Error(`Slash command not found`);
}
const chunk = next.value;
const gen = slashCommand.run({
input,
history: messages,
llm: model,
contextItems,
params: command.params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(
url,
{
...init,
signal: abortController.signal,
},
config.requestOptions,
),
completionOptions,
abortController,
});
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
yield chunk;
next = await gen.next();
return next.value;
} else {
const gen = model.streamChat(
messages,
abortController.signal,
completionOptions,
messageOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}
const chunk = next.value;
yield chunk;
next = await gen.next();
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
void checkForFreeTrialExceeded(configHandler, messenger);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
void TTS.read(next.value?.completion);
} catch (error) {
if (
error instanceof Error &&
error.message.toLowerCase().includes("premature close")
) {
void Telemetry.capture(
"stream_premature_close_error",
{
model: model.model,
provider: model.providerName,
errorMessage: error.message,
context: legacySlashCommandData ? "slash_command" : "regular_chat",
...(legacySlashCommandData && {
command: legacySlashCommandData.command.name,
}),
},
false,
);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
void checkForFreeTrialExceeded(configHandler, messenger);
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
throw error;
}
}

View file

@ -1,11 +1,9 @@
import Parser from "web-tree-sitter";
import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from "..";
import { getAst } from "../autocomplete/util/ast";
import { NEXT_EDIT_MODELS } from "../llm/constants";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker";
import {
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "./constants";
import { MODEL_WINDOW_SIZES } from "./constants";
export enum EditableRegionStrategy {
Naive = "naive",
@ -60,16 +58,16 @@ function naiveJump(ctx: any): RangeInFile[] | null {
// Sliding splits the file using into sliding window.
function slidingJump(ctx: any): RangeInFile[] | null {
const { fileLines, filepath } = ctx;
if (!fileLines || !filepath) {
console.warn("Missing required context for naive jump");
const { fileLines, filepath, modelName, currentCursorPos } = ctx;
if (!fileLines || !filepath || !modelName || !currentCursorPos) {
console.warn("Missing required context for sliding jump");
return null;
}
const windowSize =
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN +
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN +
1; // 1 for current line;
const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin;
const bottomMargin =
MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin;
const windowSize = topMargin + bottomMargin + 1; // 1 for current line
if (fileLines.length <= windowSize) {
return [
@ -86,29 +84,74 @@ function slidingJump(ctx: any): RangeInFile[] | null {
];
}
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
const ranges: RangeInFile[] = [];
const cursorLine = currentCursorPos.line;
for (
let startLine = 0;
startLine < fileLines.length;
startLine += slidingStep
) {
const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1);
// Create the first window centered around the cursor position
const firstWindowStart = Math.max(0, cursorLine - topMargin);
const firstWindowEnd = Math.min(
fileLines.length - 1,
cursorLine + bottomMargin,
);
ranges.push({
filepath,
range: {
start: { line: startLine, character: 0 },
end: {
line: endLine,
character: fileLines[endLine].length,
},
ranges.push({
filepath,
range: {
start: { line: firstWindowStart, character: 0 },
end: {
line: firstWindowEnd,
character: fileLines[firstWindowEnd].length,
},
});
},
});
if (endLine >= fileLines.length - 1) {
break;
// Alternating pattern: down once, up once, repeat
const slidingStep = Math.max(1, Math.floor(windowSize / 2));
let currentStartDown = firstWindowEnd + 1;
let currentStartUp = firstWindowStart - slidingStep;
while (currentStartDown < fileLines.length || currentStartUp >= 0) {
// Go down once
if (currentStartDown < fileLines.length) {
const windowStart = currentStartDown;
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartDown += slidingStep;
}
// Go up once
if (currentStartUp >= 0) {
const windowStart = Math.max(0, currentStartUp);
const windowEnd = Math.min(
windowStart + windowSize - 1,
fileLines.length - 1,
);
ranges.push({
filepath,
range: {
start: { line: windowStart, character: 0 },
end: {
line: windowEnd,
character: fileLines[windowEnd].length,
},
},
});
currentStartUp -= slidingStep;
}
}

View file

@ -2,7 +2,7 @@ import { RangeInFile } from "..";
import { NextEditProvider } from "./NextEditProvider";
import { NextEditOutcome } from "./types";
interface ProcessedItem {
export interface ProcessedItem {
location: RangeInFile;
outcome: NextEditOutcome; // Result from the model
}
@ -59,6 +59,11 @@ export class PrefetchQueue {
!this.abortController.signal.aborted
) {
const location = this.dequeueUnprocessed();
console.log("processing:");
console.log(
location?.range.start.line + " to " + location?.range.end.line,
);
if (!location) break;
try {
@ -70,12 +75,20 @@ export class PrefetchQueue {
this.usingFullFileDiff,
);
if (!outcome) continue;
if (!outcome) {
console.log("outcome is undefined");
continue;
}
this.enqueueProcessed({
location,
outcome,
});
console.log(
"the length of processed queue after processing is:",
this.processedQueue.length,
);
} catch (error) {
if (!this.abortController.signal.aborted) {
// Handle error
@ -115,6 +128,16 @@ export class PrefetchQueue {
return this.processedQueue[0];
}
peekThreeProcessed(): void {
const count = Math.min(3, this.processedQueue.length);
const firstThree = this.processedQueue.slice(0, count);
firstThree.forEach((item, index) => {
console.log(
`Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`,
);
});
}
setPreetchLimit(limit: number): void {
this.prefetchLimit = limit;
}

View file

@ -33,12 +33,11 @@ import { myersDiff } from "../diff/myers.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { replaceEscapedCharacters } from "../util/text.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_SYSTEM_PROMPT,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
MODEL_WINDOW_SIZES,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
@ -60,6 +59,7 @@ import {
PromptMetadata,
RecentlyEditedRange,
} from "./types.js";
import { isWhitespaceOnlyDeletion } from "./utils.js";
const autocompleteCache = AutocompleteLruCache.get();
@ -82,7 +82,8 @@ export class NextEditProvider {
private loggingService: NextEditLoggingService;
private contextRetrievalService: ContextRetrievalService;
private endpointType: "default" | "fineTuned";
private diffContext: string = "";
private diffContext: string[] = [];
private autocompleteContext: string = "";
private promptMetadata: PromptMetadata | null = null;
private currentEditChainId: string | null = null;
private previousRequest: AutocompleteInput | null = null;
@ -134,7 +135,14 @@ export class NextEditProvider {
}
public addDiffToContext(diff: string): void {
this.diffContext = diff;
this.diffContext.push(diff);
if (this.diffContext.length > 5) {
this.diffContext.shift();
}
}
public addAutocompleteContext(ctx: string): void {
this.autocompleteContext = ctx;
}
private async _prepareLlm(): Promise<ILLM | undefined> {
@ -384,16 +392,20 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes("mercury-coder-nextedit")
? "mercury-coder-nextedit"
: "instinct";
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
? this._calculateOptimalEditableRegion(helper, "tokenizer")
: {
editableRegionStartLine: Math.max(
helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
0,
),
editableRegionEndLine: Math.min(
helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
helper.fileLines.length - 1,
),
};
@ -552,11 +564,40 @@ export class NextEditProvider {
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes("model-1")) {
} else if (modelName.includes("instinct")) {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, helper.pos.line - 25);
const windowEnd = Math.min(
helper.fileLines.length - 1,
helper.pos.line + 25,
);
// // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
// const actualEditableStart = Math.max(
// 0,
// helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
// );
// const actualEditableEnd = Math.min(
// helper.fileLines.length - 1,
// helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
// );
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(
windowStart,
editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
ctx = {
userEdits: historyDiff ?? this.diffContext,
contextSnippets: this.autocompleteContext,
currentFileContent: helper.fileContents,
windowStart,
windowEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
languageShorthand: helper.lang.name,
userExcerpts: helper.fileContents,
};
} else {
ctx = {};
@ -567,7 +608,9 @@ export class NextEditProvider {
const systemPrompt: Prompt = {
role: "system",
content: MERCURY_SYSTEM_PROMPT,
content: modelName.includes("mercury-coder-nextedit")
? MERCURY_SYSTEM_PROMPT
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
@ -635,27 +678,34 @@ export class NextEditProvider {
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
console.log("message");
console.log(msg.content);
if (typeof msg.content !== "string") {
return undefined;
}
const nextCompletion = msg.content.split(
`${MERCURY_CODE_TO_EDIT_OPEN}\n`,
)[1]
? replaceEscapedCharacters(
msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
).replace(/\n$/, "")
: "";
// const nextCompletion = msg.content.split(
// `${MERCURY_CODE_TO_EDIT_OPEN}\n`,
// )[1]
// ? replaceEscapedCharacters(
// msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
// ).replace(/\n$/, "")
// : replaceEscapedCharacters(msg.content);
const nextCompletion =
msg.content
.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
.replace(/\n$/, "") ?? msg.content;
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(
// we could use fillFileDiff
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
editableRegionStartLine,
editableRegionEndLine,
);
} else {
return await this._handleFullFileDiff(
@ -671,11 +721,11 @@ export class NextEditProvider {
private async _handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
editableRegionStartLine: number,
editableRegionEndLine: number,
): Promise<NextEditOutcome | undefined> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
@ -727,13 +777,16 @@ export class NextEditProvider {
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const diffLines = myersDiff(fileSlice, nextCompletion);
const diffGroups = groupDiffLines(diffLines, editableRegionStartLine, 5);
const diffGroups = groupDiffLines(
diffLines,
editableRegionStartLine,
5,
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
const currentLine = helper.pos.line;
let cursorLocalDiffGroup: DiffGroup | undefined;
const prefetchQueue = PrefetchQueue.getInstance();
// Process diff groups and find the one containing the cursor
await this._processDiffGroups(
const cursorLocalDiffGroup = await this._processDiffGroups(
diffGroups,
currentLine,
helper,
@ -752,16 +805,16 @@ export class NextEditProvider {
helper.input.completionId,
true,
);
} else if (diffGroups.length > 0) {
// Fallback to first diff group if cursor's group not found
return await this._createOutcomeFromDiffGroup(
diffGroups[0],
helper,
startTime,
llm,
helper.input.completionId,
false,
);
// } else if (diffGroups.length > 0) {
// // Fallback to first diff group if cursor's group not found
// return await this._createOutcomeFromDiffGroup(
// diffGroups[0],
// helper,
// startTime,
// llm,
// helper.input.completionId,
// false,
// );
}
return undefined;
@ -985,6 +1038,7 @@ export class NextEditProvider {
try {
const previousOutcome = this.getPreviousCompletion();
if (!previousOutcome) {
console.log("previousOutcome is undefined");
return undefined;
}
@ -995,6 +1049,7 @@ export class NextEditProvider {
ctx,
);
if (!input) {
console.log("input is undefined");
return undefined;
}

View file

@ -1,11 +1,51 @@
import { NEXT_EDIT_MODELS } from "../llm/constants";
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const MODEL_WINDOW_SIZES: Record<
NEXT_EDIT_MODELS,
{ topMargin: number; bottomMargin: number }
> = {
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
instinct: { topMargin: 1, bottomMargin: 5 },
};
// Model 1-specific tokens.
export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>";
export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>";
export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
You have access to the following information to help you make informed suggestions:
- Context: In the section marked "### Context", there are context items from potentially relevant files in the developer's codebase. Each context item consists of a <|context_file|> marker, the filepath, a <|snippet|> marker, and then some content from that file, in that order. Keep in mind that not all of the context information may be relevant to the task, so use your judgement to determine which parts to consider.
- User Edits: In the section marked "### User Edits:", there is a record of the most recent changes made to the code, helping you understand the evolution of the code and the developer's intentions. These changes are listed from most recent to least recent. It's possible that some of the edit diff history is entirely irrelevant to the developer's change. The changes are provided in a unified line-diff format, i.e. with pluses and minuses for additions and deletions to the code.
- User Excerpt: In the section marked "### User Excerpt:", there is a filepath to the developer's current file, and then an excerpt from that file. The <|editable_region_start|> and <|editable_region_end|> markers are within this excerpt. Your job is to rewrite only this editable region, not the whole excerpt. The excerpt provides additional context on the surroundings of the developer's edit.
- Cursor Position: Within the user excerpt's editable region, the <|user_cursor_is_here|> flag indicates where the developer's cursor is currently located, which can be crucial for understanding what part of the code they are focusing on. Do not produce this marker in your output; simply take it into account.
Your task is to predict and complete the changes the developer would have made next in the editable region. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they're following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn't get distracted by ensuring your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.
# Steps
1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.
2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.
3. **Suggest Edits**: If changes are required, ensure they align with the developer's patterns and improve code quality.
4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.
# Output Format
- Provide only the revised code within the tags. Do not include the tags in your output.
- Ensure that you do not output duplicate code that exists outside of these tags.
- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`;
export const INSTINCT_USER_PROMPT_PREFIX =
"Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code.";
// Mercury Coder Next Edit-specific tokens.
export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN =

View file

@ -95,3 +95,139 @@ const createTokenLineDiff = (
// TODO: Implement token line diff
return "";
};
export interface DiffMetadata {
oldFilename?: string; // Filename in the original version
newFilename?: string; // Filename in the modified version
oldTimestamp?: string; // Timestamp of the original file
newTimestamp?: string; // Timestamp of the modified file
hunks?: Array<{
// Information about each change hunk
oldStart: number; // Starting line in original file
oldCount: number; // Number of lines in original file
newStart: number; // Starting line in modified file
newCount: number; // Number of lines in modified file
header?: string; // Optional section header
lines: Array<{
type: "context" | "addition" | "deletion";
content: string;
oldLineNumber?: number;
newLineNumber?: number;
}>;
}>;
isBinary?: boolean; // Whether this is a binary file diff
isNew?: boolean; // Whether this is a new file
isDeleted?: boolean; // Whether this file was deleted
isRename?: boolean; // Whether this file was renamed
}
export function extractMetadataFromUnifiedDiff(
unifiedDiff: string,
): DiffMetadata {
const metadata: DiffMetadata = {};
const lines = unifiedDiff.split("\n");
// Parse the header lines (first two lines)
if (lines.length >= 2) {
// Parse original file info (--- line)
const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/);
if (oldFileMatch) {
metadata.oldFilename = oldFileMatch[2];
metadata.oldTimestamp = oldFileMatch[3];
// Check if this is a new file
if (metadata.oldFilename === "/dev/null") {
metadata.isNew = true;
}
}
// Parse modified file info (+++ line)
const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/);
if (newFileMatch) {
metadata.newFilename = newFileMatch[2];
metadata.newTimestamp = newFileMatch[3];
// Check if this file was deleted
if (metadata.newFilename === "/dev/null") {
metadata.isDeleted = true;
}
}
// Check if this is a rename (different old and new names)
if (
metadata.oldFilename &&
metadata.newFilename &&
metadata.oldFilename !== "/dev/null" &&
metadata.newFilename !== "/dev/null" &&
metadata.oldFilename !== metadata.newFilename
) {
metadata.isRename = true;
}
}
// Parse hunk headers and content
metadata.hunks = [];
const hunkHeaderRegex =
/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/;
let currentHunk: NonNullable<DiffMetadata["hunks"]>[0] | null = null;
let oldLineNumber = 0;
let newLineNumber = 0;
for (let i = 2; i < lines.length; i++) {
const line = lines[i];
const hunkMatch = line.match(hunkHeaderRegex);
if (hunkMatch) {
currentHunk = {
oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file
oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified
newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file
newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified
header: hunkMatch[5], // the line starting with @@
lines: [], // the actual line changes
};
oldLineNumber = currentHunk.oldStart;
newLineNumber = currentHunk.newStart;
metadata.hunks.push(currentHunk);
} else if (
currentHunk &&
(line.startsWith(" ") || line.startsWith("+") || line.startsWith("-"))
) {
// Process hunk content lines.
const lineType = line[0];
const content = line.slice(1);
if (lineType === " ") {
// Context line (unchanged).
currentHunk.lines.push({
type: "context",
content,
oldLineNumber: oldLineNumber++,
newLineNumber: newLineNumber++,
});
} else if (lineType === "+") {
currentHunk.lines.push({
type: "addition",
content,
newLineNumber: newLineNumber++,
});
} else if (lineType === "-") {
currentHunk.lines.push({
type: "deletion",
content,
oldLineNumber: oldLineNumber++,
});
}
}
// Check for binary file marker
if (line.includes("Binary files") || line.includes("GIT binary patch")) {
metadata.isBinary = true;
}
}
return metadata;
}

View file

@ -0,0 +1,462 @@
import { describe, expect, it } from "vitest";
import {
BeforeAfterDiff,
createBeforeAfterDiff,
createDiff,
CreateDiffArgs,
DiffFormatType,
DiffMetadata,
extractMetadataFromUnifiedDiff,
} from "./diffFormatting";
describe("diffFormatting", () => {
const sampleFilePath = "test/sample.js";
const beforeContent = "const a = 1;\nconst b = 2;";
const afterContent = "const a = 1;\nconst b = 3;\nconst c = 4;";
describe("createDiff", () => {
it("should create unified diff when specified", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: sampleFilePath,
diffType: DiffFormatType.Unified,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toContain("---");
expect(result).toContain("+++");
expect(result).toContain("@@");
expect(result).toContain("-const b = 2;");
expect(result).toContain("+const b = 3;");
expect(result).toContain("+const c = 4;");
});
it("should create token line diff when specified", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: sampleFilePath,
diffType: DiffFormatType.TokenLineDiff,
contextLines: 3,
};
const result = createDiff(args);
// Currently returns empty string as TODO
expect(result).toBe("");
});
it("should return empty string for unsupported diff types", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: sampleFilePath,
diffType: DiffFormatType.RawBeforeAfter,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toBe("");
});
it("should handle empty content", () => {
const args: CreateDiffArgs = {
beforeContent: "",
afterContent: "new content",
filePath: sampleFilePath,
diffType: DiffFormatType.Unified,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toContain("+++");
expect(result).toContain("+new content");
});
it("should handle deletion", () => {
const args: CreateDiffArgs = {
beforeContent: "old content",
afterContent: "",
filePath: sampleFilePath,
diffType: DiffFormatType.Unified,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toContain("---");
expect(result).toContain("-old content");
});
it("should handle content without newlines", () => {
const args: CreateDiffArgs = {
beforeContent: "line1",
afterContent: "line2",
filePath: sampleFilePath,
diffType: DiffFormatType.Unified,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toContain("-line1");
expect(result).toContain("+line2");
});
it("should respect contextLines parameter", () => {
const multiLineContent = Array(10)
.fill("line")
.map((l, i) => `${l}${i}`)
.join("\n");
const modifiedContent = multiLineContent.replace("line5", "modified5");
const args: CreateDiffArgs = {
beforeContent: multiLineContent,
afterContent: modifiedContent,
filePath: sampleFilePath,
diffType: DiffFormatType.Unified,
contextLines: 2,
};
const result = createDiff(args);
expect(result).toContain("@@ -4,5 +4,5 @@");
});
});
describe("createBeforeAfterDiff", () => {
it("should return BeforeAfterDiff with normalized content", () => {
const result: BeforeAfterDiff = createBeforeAfterDiff(
beforeContent,
afterContent,
sampleFilePath,
);
expect(result).toEqual({
filePath: sampleFilePath,
beforeContent: beforeContent + "\n",
afterContent: afterContent + "\n",
});
});
it("should not add extra newline if content already ends with one", () => {
const contentWithNewline = "const a = 1;\n";
const result: BeforeAfterDiff = createBeforeAfterDiff(
contentWithNewline,
contentWithNewline,
sampleFilePath,
);
expect(result.beforeContent).toBe(contentWithNewline);
expect(result.afterContent).toBe(contentWithNewline);
});
it("should handle empty content", () => {
const result: BeforeAfterDiff = createBeforeAfterDiff(
"",
"",
sampleFilePath,
);
expect(result).toEqual({
filePath: sampleFilePath,
beforeContent: "\n",
afterContent: "\n",
});
});
it("should handle mixed newline scenarios", () => {
const beforeWithNewline = "line1\n";
const afterWithoutNewline = "line2";
const result: BeforeAfterDiff = createBeforeAfterDiff(
beforeWithNewline,
afterWithoutNewline,
sampleFilePath,
);
expect(result.beforeContent).toBe("line1\n");
expect(result.afterContent).toBe("line2\n");
});
});
describe("extractMetadataFromUnifiedDiff", () => {
it("should extract basic file information", () => {
const unifiedDiff = `--- a/old.js\ttimestamp1
+++ b/new.js\ttimestamp2
@@ -1,3 +1,3 @@
line1
-line2
+modified2
line3`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.oldFilename).toBe("old.js");
expect(metadata.newFilename).toBe("new.js");
expect(metadata.oldTimestamp).toBe("timestamp1");
expect(metadata.newTimestamp).toBe("timestamp2");
expect(metadata.isNew).toBeFalsy();
expect(metadata.isDeleted).toBeFalsy();
expect(metadata.isRename).toBeTruthy();
});
it("should detect new files", () => {
const unifiedDiff = `--- /dev/null
+++ b/new.js
@@ -0,0 +1,2 @@
+line1
+line2`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.oldFilename).toBe("/dev/null");
expect(metadata.newFilename).toBe("new.js");
expect(metadata.isNew).toBeTruthy();
expect(metadata.isDeleted).toBeFalsy();
expect(metadata.isRename).toBeFalsy();
});
it("should detect deleted files", () => {
const unifiedDiff = `--- a/old.js
+++ /dev/null
@@ -1,2 +0,0 @@
-line1
-line2`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.oldFilename).toBe("old.js");
expect(metadata.newFilename).toBe("/dev/null");
expect(metadata.isNew).toBeFalsy();
expect(metadata.isDeleted).toBeTruthy();
expect(metadata.isRename).toBeFalsy();
});
it("should parse hunk information", () => {
const unifiedDiff = `--- a/file.js
+++ b/file.js
@@ -1,5 +1,6 @@ function header
line1
-line2
+modified2
+newline
line3
@@ -10,3 +11,3 @@
line10
-line11
+modified11
line12`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.hunks).toHaveLength(2);
expect(metadata.hunks![0]).toEqual({
oldStart: 1,
oldCount: 5,
newStart: 1,
newCount: 6,
header: "function header",
lines: [
{
content: "line1",
newLineNumber: 1,
oldLineNumber: 1,
type: "context",
},
{
content: "line2",
oldLineNumber: 2,
type: "deletion",
},
{
content: "modified2",
newLineNumber: 2,
type: "addition",
},
{
content: "newline",
newLineNumber: 3,
type: "addition",
},
{
content: "line3",
newLineNumber: 4,
oldLineNumber: 3,
type: "context",
},
],
});
expect(metadata.hunks![1]).toEqual({
oldStart: 10,
oldCount: 3,
newStart: 11,
newCount: 3,
header: undefined,
lines: [
{
content: "line10",
newLineNumber: 11,
oldLineNumber: 10,
type: "context",
},
{
content: "line11",
oldLineNumber: 11,
type: "deletion",
},
{
content: "modified11",
newLineNumber: 12,
type: "addition",
},
{
content: "line12",
newLineNumber: 13,
oldLineNumber: 12,
type: "context",
},
],
});
});
it("should handle single line hunks", () => {
const unifiedDiff = `--- a/file.js
+++ b/file.js
@@ -1 +1 @@
-old
+new`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.hunks).toHaveLength(1);
expect(metadata.hunks![0]).toEqual({
oldStart: 1,
oldCount: 1,
newStart: 1,
newCount: 1,
header: undefined,
lines: [
{
content: "old",
oldLineNumber: 1,
type: "deletion",
},
{
content: "new",
newLineNumber: 1,
type: "addition",
},
],
});
});
it("should detect binary files", () => {
const unifiedDiff = `--- a/image.png
+++ b/image.png
Binary files a/image.png and b/image.png differ`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.isBinary).toBeTruthy();
});
it("should detect git binary patches", () => {
const unifiedDiff = `--- a/file.bin
+++ b/file.bin
GIT binary patch
delta 123
...`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.isBinary).toBeTruthy();
});
it("should handle files without a/ b/ prefixes", () => {
const unifiedDiff = `--- old.js
+++ new.js
@@ -1,2 +1,2 @@
-line1
+modified1
line2`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.oldFilename).toBe("old.js");
expect(metadata.newFilename).toBe("new.js");
});
it("should handle empty diff", () => {
const metadata: DiffMetadata = extractMetadataFromUnifiedDiff("");
expect(metadata.oldFilename).toBeUndefined();
expect(metadata.newFilename).toBeUndefined();
expect(metadata.hunks).toEqual([]);
expect(metadata.isBinary).toBeFalsy();
});
it("should handle malformed diff gracefully", () => {
const malformedDiff = `not a diff
random text`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(malformedDiff);
expect(metadata.oldFilename).toBeUndefined();
expect(metadata.newFilename).toBeUndefined();
expect(metadata.hunks).toEqual([]);
});
it("should not consider same filenames as rename", () => {
const unifiedDiff = `--- a/file.js
+++ b/file.js
@@ -1,2 +1,2 @@
-line1
+modified1
line2`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.isRename).toBeFalsy();
});
it("should handle files with spaces in names", () => {
const unifiedDiff = `--- a/my file.js\t2023-01-01 00:00:00
+++ b/my new file.js\t2023-01-01 00:01:00
@@ -1,1 +1,1 @@
-content
+new content`;
const metadata: DiffMetadata =
extractMetadataFromUnifiedDiff(unifiedDiff);
expect(metadata.oldFilename).toBe("my file.js");
expect(metadata.newFilename).toBe("my new file.js");
expect(metadata.oldTimestamp).toBe("2023-01-01 00:00:00");
expect(metadata.newTimestamp).toBe("2023-01-01 00:01:00");
expect(metadata.isRename).toBeTruthy();
});
});
describe("DiffFormatType enum", () => {
it("should have correct enum values", () => {
expect(DiffFormatType.Unified).toBe("unified");
expect(DiffFormatType.RawBeforeAfter).toBe("beforeAfter");
expect(DiffFormatType.TokenLineDiff).toBe("linediff");
});
});
});

View file

@ -3,6 +3,7 @@ import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
import { ConfigHandler } from "../../config/ConfigHandler";
import { DataLogger } from "../../data/log";
import { NextEditProvider } from "../NextEditProvider";
import { RecentlyEditedRange } from "../types";
import { getAutocompleteContext } from "./autocompleteContextFetching";
import { createDiff, DiffFormatType } from "./diffFormatting";
@ -60,6 +61,7 @@ export const processNextEditData = async ({
// undefined;
const modelName = "Codestral";
const modelProvider = "mistral";
const maxPromptTokens = randomNumberBetween(500, 12000);
const autocompleteContext = await getAutocompleteContext(
@ -75,6 +77,8 @@ export const processNextEditData = async ({
modelName,
);
NextEditProvider.getInstance().addAutocompleteContext(autocompleteContext);
// console.log(
// createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
// );
@ -121,6 +125,9 @@ export const processNextEditData = async ({
beforeCursorPos: cursorPosBeforeEdit,
afterCursorPos: cursorPosAfterPrevEdit,
context: autocompleteContext,
modelProvider,
modelName,
modelTitle: modelName,
},
});
}

View file

@ -20,7 +20,7 @@ export const processSmallEdit = async (
afterContent: beforeAfterdiff.afterContent,
filePath: beforeAfterdiff.filePath,
diffType: DiffFormatType.Unified,
contextLines: 3, // NOTE: This can change depending on experiments!
contextLines: 5, // NOTE: This can change depending on experiments!
}),
);

View file

@ -2,25 +2,30 @@ import Handlebars from "handlebars";
import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import {
InstinctTemplateVars,
MercuryTemplateVars,
Model1TemplateVars,
NextEditTemplate,
PromptMetadata,
SystemPrompt,
TemplateVars,
UserPrompt,
} from "../types";
import {
contextSnippetsBlock,
currentFileContentBlock as instinctCurrentFileContentBlock,
editHistoryBlock as instinctEditHistoryBlock,
} from "./instinct";
import {
currentFileContentBlock,
editHistoryBlock,
@ -30,7 +35,6 @@ import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
} from "./utils";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
type TemplateRenderer = (vars: TemplateVars) => string;
@ -38,9 +42,8 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
},
"model-1": {
template:
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
@ -90,11 +93,11 @@ export async function renderPrompt(
case "mercury-coder-nextedit": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MERCURY_CURSOR,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
@ -112,24 +115,37 @@ export async function renderPrompt(
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case "model-1": {
userEdits = ctx.userEdits;
case "instinct": {
userEdits = ctx.editDiffHistory;
editedCodeWithTokens = insertTokens(
helper.fileContents.split("\n"),
helper.pos,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
);
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
// );
const model1Ctx: Model1TemplateVars = {
userEdits: ctx.userEdits,
const instinctCtx: InstinctTemplateVars = {
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
currentFileContent: instinctCurrentFileContentBlock(
ctx.currentFileContent,
ctx.windowStart,
ctx.windowEnd,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
languageShorthand: ctx.languageShorthand,
userExcerpts: ctx.userExcerpts,
};
tv = model1Ctx;
tv = instinctCtx;
editedCodeWithTokens = instinctCtx.currentFileContent;
break;
}

View file

@ -3,7 +3,10 @@ import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
@ -11,19 +14,17 @@ import {
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import {
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./NextEditPromptEngine";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
let mercuryHelper: HelperVars;
let model1Helper: HelperVars;
let instinctHelper: HelperVars;
let testHelper: HelperVars;
let unsupportedHelper: HelperVars;
let ctx: any;
@ -35,8 +36,8 @@ describe("NextEditPromptEngine", () => {
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
model1Helper = {
modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
instinctHelper = {
modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -53,7 +54,7 @@ describe("NextEditPromptEngine", () => {
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",
@ -80,17 +81,35 @@ describe("NextEditPromptEngine", () => {
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
it("should render model-1 prompt correctly", async () => {
const result = await renderPrompt(model1Helper, ctx);
it("should render instinct prompt correctly", async () => {
// Create proper instinct context structure matching NextEditProvider.ts
const instinctCtx = {
contextSnippets:
"+++++ /path/to/context.ts\nconst contextVar = 'test';",
currentFileContent: instinctHelper.fileContents,
windowStart: 0, // Math.max(0, helper.pos.line - 25)
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory: [
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
], // unified diff
currentFilePath: "/path/to/file.ts",
languageShorthand: "ts",
};
const result = await renderPrompt(instinctHelper, instinctCtx);
console.log(result);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain("### Context:");
expect(result.prompt.content).toContain("### User Edits:");
expect(result.prompt.content).toContain("### User Excerpts:");
expect(result.prompt.content).toContain("```ts");
expect(result.userEdits).toBe(ctx.userEdits);
expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
});
it("should throw error for unsupported model name", async () => {
@ -204,7 +223,7 @@ describe("NextEditPromptEngine", () => {
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",

View file

@ -0,0 +1,129 @@
import { Position } from "../..";
import {
INSTINCT_CONTEXT_FILE_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
INSTINCT_SNIPPET_TOKEN,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
} from "../constants";
import { insertCursorToken } from "./utils";
/**
* @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
*/
export function contextSnippetsBlock(contextSnippets: string) {
const headerRegex = /^(\+\+\+\+\+ )(.*)/;
const lines = contextSnippets.split("\n");
return lines
.reduce<string[]>((acc, line) => {
const matches = line.match(headerRegex);
if (matches) {
const filename = matches[2];
acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`);
} else {
if (
acc.length > 0 &&
acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before
) {
acc.push(`${INSTINCT_SNIPPET_TOKEN}`);
}
acc.push(line);
}
return acc;
}, [])
.join("\n");
}
export function currentFileContentBlock(
currentFileContent: string,
windowStart: number,
windowEnd: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
cursorPosition: Position,
) {
const currentFileContentLines = currentFileContent.split("\n");
const insertedCursorLines = insertCursorToken(
currentFileContentLines,
cursorPosition,
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
);
const instrumentedLines = [
...insertedCursorLines.slice(windowStart, editableRegionStartLine),
INSTINCT_EDITABLE_REGION_START_TOKEN,
...insertedCursorLines.slice(
editableRegionStartLine,
editableRegionEndLine + 1,
),
INSTINCT_EDITABLE_REGION_END_TOKEN,
...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
];
return instrumentedLines.join("\n");
}
export function editHistoryBlock(
editDiffHistories: string[], // array of unified diffs with Index headers
) {
if (!editDiffHistories.length) {
return "";
}
const blocks: string[] = [];
for (const editDiffHistory of editDiffHistories) {
if (!editDiffHistory.trim()) {
continue;
}
// Split on Index: lines to get the unified diff.
const diffSections = editDiffHistory
.split(/^Index: /m)
.filter((section) => section.trim());
for (const section of diffSections) {
const lines = section.split("\n");
// Extract filename from the first line (after "Index: " was split off).
const filename = lines[0];
// Find the start of the actual diff content (skip ---, +++, and === lines).
const diffLines = lines
.filter(
(line) =>
!line.startsWith("---") &&
!line.startsWith("+++") &&
!line.startsWith("===") &&
line.trim() !== "", // remove empty lines from header section
)
.slice(1); // remove the filename line
// Only include lines that are actual diff content (@@, +, -, or context lines).
const actualDiffContent = diffLines.filter(
(line) =>
line.startsWith("@@") ||
line.startsWith("+") ||
line.startsWith("-") ||
line.startsWith(" "), // context lines
);
if (actualDiffContent.length === 0) continue;
const diffBlock = [
`User edited file "${filename}"`,
"",
"```diff",
actualDiffContent.join("\n"),
"```",
].join("\n");
blocks.push(diffBlock);
}
}
return blocks.join("\n");
}

View file

@ -0,0 +1,483 @@
import { describe, expect, test } from "vitest";
import { Position } from "../..";
import {
contextSnippetsBlock,
currentFileContentBlock,
editHistoryBlock,
} from "./instinct";
describe("contextSnippetsBlock", () => {
test("should format empty context snippets", () => {
const result = contextSnippetsBlock("");
expect(result).toBe("");
});
test("should format single context snippet with codestral style header", () => {
const input = `+++++ src/utils.ts
function helper() {
return "test";
}`;
const expected = `<|context_file|>: src/utils.ts
<|snippet|>
function helper() {
return "test";
}`;
const result = contextSnippetsBlock(input);
expect(result).toBe(expected);
});
test("should format multiple context snippets", () => {
const input = `+++++ src/file1.ts
const var1 = "value1";
+++++ src/file2.ts
const var2 = "value2";
function test() {}`;
const expected = `<|context_file|>: src/file1.ts
<|snippet|>
const var1 = "value1";
<|context_file|>: src/file2.ts
<|snippet|>
const var2 = "value2";
function test() {}`;
const result = contextSnippetsBlock(input);
expect(result).toBe(expected);
});
test("should handle context snippet without content", () => {
const input = "+++++ src/empty.ts";
const expected = `<|context_file|>: src/empty.ts`;
const result = contextSnippetsBlock(input);
expect(result).toBe(expected);
});
test("should handle malformed headers gracefully", () => {
const input = `not a header
+++++ src/valid.ts
valid content`;
const expected = `not a header
<|context_file|>: src/valid.ts
<|snippet|>
valid content`;
const result = contextSnippetsBlock(input);
expect(result).toBe(expected);
});
test("should handle multiple consecutive headers", () => {
const input = `+++++ src/file1.ts
+++++ src/file2.ts
content after headers`;
const expected = `<|context_file|>: src/file1.ts
<|context_file|>: src/file2.ts
<|snippet|>
content after headers`;
const result = contextSnippetsBlock(input);
expect(result).toBe(expected);
});
});
describe("currentFileContentBlock", () => {
test("should insert cursor and editable region tokens correctly", () => {
const content = `line 0
line 1
line 2
line 3
line 4`;
const windowStart = 0;
const windowEnd = 4;
const cursorPosition: Position = { line: 2, character: 4 };
const editableRegionStartLine = 1;
const editableRegionEndLine = 3;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `line 0
<|editable_region_start|>
line 1
line<|user_cursor_is_here|> 2
line 3
<|editable_region_end|>
line 4`;
expect(result).toBe(expected);
});
test("should handle cursor at beginning of line", () => {
const content = `line 0
line 1
line 2`;
const windowStart = 0;
const windowEnd = 2;
const cursorPosition: Position = { line: 1, character: 0 };
const editableRegionStartLine = 0;
const editableRegionEndLine = 2;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `<|editable_region_start|>
line 0
<|user_cursor_is_here|>line 1
line 2
<|editable_region_end|>`;
expect(result).toBe(expected);
});
test("should handle cursor at end of line", () => {
const content = `line 0
line 1
line 2`;
const windowStart = 0;
const windowEnd = 2;
const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1"
const editableRegionStartLine = 0;
const editableRegionEndLine = 2;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `<|editable_region_start|>
line 0
line 1<|user_cursor_is_here|>
line 2
<|editable_region_end|>`;
expect(result).toBe(expected);
});
test("should handle single line editable region", () => {
const content = `line 0
line 1
line 2`;
const windowStart = 0;
const windowEnd = 2;
const cursorPosition: Position = { line: 1, character: 2 };
const editableRegionStartLine = 1;
const editableRegionEndLine = 1;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `line 0
<|editable_region_start|>
li<|user_cursor_is_here|>ne 1
<|editable_region_end|>
line 2`;
expect(result).toBe(expected);
});
test("should handle cursor outside bounds gracefully (this shouldn't happen)", () => {
const content = `line 0
line 1`;
const windowStart = 0;
const windowEnd = 1;
const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds
const editableRegionStartLine = 0;
const editableRegionEndLine = 1;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `<|editable_region_start|>
line 0
line 1
<|editable_region_end|>`;
expect(result).toBe(expected);
});
test("should handle editable region covering entire file", () => {
const content = `line 0
line 1
line 2`;
const windowStart = 0;
const windowEnd = 2;
const cursorPosition: Position = { line: 1, character: 0 };
const editableRegionStartLine = 0;
const editableRegionEndLine = 2;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `<|editable_region_start|>
line 0
<|user_cursor_is_here|>line 1
line 2
<|editable_region_end|>`;
expect(result).toBe(expected);
});
test("should handle windowing - content outside window not included", () => {
const content = `line 0
line 1
line 2
line 3
line 4`;
const windowStart = 1;
const windowEnd = 3;
const cursorPosition: Position = { line: 2, character: 2 };
const editableRegionStartLine = 2;
const editableRegionEndLine = 2;
const result = currentFileContentBlock(
content,
windowStart,
windowEnd,
editableRegionStartLine,
editableRegionEndLine,
cursorPosition,
);
const expected = `line 1
<|editable_region_start|>
li<|user_cursor_is_here|>ne 2
<|editable_region_end|>
line 3`;
expect(result).toBe(expected);
});
});
describe("editHistoryBlock", () => {
test("should format empty edit history", () => {
const result = editHistoryBlock([]);
expect(result).toBe("");
});
test("should format single diff history entry", () => {
const diff = `Index: test.js
===================================================================
--- a/test.js 2023-01-01 10:00:00.000000000 +0000
+++ b/test.js 2023-01-01 10:01:00.000000000 +0000
@@ -1,3 +1,3 @@
function test() {
- console.log("old");
+ console.log("new");
}`;
const result = editHistoryBlock([diff]);
const expected = `User edited file "test.js"
\`\`\`diff
@@ -1,3 +1,3 @@
function test() {
- console.log("old");
+ console.log("new");
}
\`\`\``;
expect(result).toBe(expected);
});
test("should format multiple diff history entries in unified format", () => {
// Multiple diffs should be concatenated into a single string
const unifiedDiff = `Index: file1.js
===================================================================
--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
@@ -1 +1 @@
-const old = 1;
+const new = 1;
Index: file2.js
===================================================================
--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
@@ -1 +1 @@
-let x = "old";
+let x = "new";`;
const result = editHistoryBlock([unifiedDiff]);
const expected = `User edited file "file1.js"
\`\`\`diff
@@ -1 +1 @@
-const old = 1;
+const new = 1;
\`\`\`
User edited file "file2.js"
\`\`\`diff
@@ -1 +1 @@
-let x = "old";
+let x = "new";
\`\`\``;
expect(result).toBe(expected);
});
test("should format multiple diff history entries", () => {
// Multiple diffs should be concatenated into a single string
const unifiedDiffs = [
`Index: file1.js
===================================================================
--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
@@ -1 +1 @@
-const old = 1;
+const new = 1;`,
`Index: file2.js
===================================================================
--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
@@ -1 +1 @@
-let x = "old";
+let x = "new";`,
];
const result = editHistoryBlock(unifiedDiffs);
const expected = `User edited file "file1.js"
\`\`\`diff
@@ -1 +1 @@
-const old = 1;
+const new = 1;
\`\`\`
User edited file "file2.js"
\`\`\`diff
@@ -1 +1 @@
-let x = "old";
+let x = "new";
\`\`\``;
expect(result).toBe(expected);
});
// Fix remaining tests to pass strings instead of arrays
test("should handle diff with complex filename paths", () => {
const diff = `Index: src/components/Button/Button.tsx
===================================================================
--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000
+++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000
@@ -1,2 +1,2 @@
-export const Button = () => <button>Old</button>;
+export const Button = () => <button>New</button>;`;
const result = editHistoryBlock([diff]);
const expected = `User edited file "src/components/Button/Button.tsx"
\`\`\`diff
@@ -1,2 +1,2 @@
-export const Button = () => <button>Old</button>;
+export const Button = () => <button>New</button>;
\`\`\``;
expect(result).toBe(expected);
});
test("should handle diff with new file creation", () => {
const diff = `Index: newfile.js
===================================================================
--- /dev/null 2023-01-01 10:00:00.000000000 +0000
+++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000
@@ -0,0 +1,3 @@
+function newFunction() {
+ return "hello world";
+}`;
const result = editHistoryBlock([diff]);
const expected = `User edited file "newfile.js"
\`\`\`diff
@@ -0,0 +1,3 @@
+function newFunction() {
+ return "hello world";
+}
\`\`\``;
expect(result).toBe(expected);
});
test("should handle diff with file deletion", () => {
const diff = `Index: deletedfile.js
===================================================================
--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000
+++ /dev/null 2023-01-01 10:01:00.000000000 +0000
@@ -1,3 +0,0 @@
-function deletedFunction() {
- return "goodbye";
-}`;
const result = editHistoryBlock([diff]);
const expected = `User edited file "deletedfile.js"
\`\`\`diff
@@ -1,3 +0,0 @@
-function deletedFunction() {
- return "goodbye";
-}
\`\`\``;
expect(result).toBe(expected);
});
test("should handle minimal diff format", () => {
const diff = `Index: simple.txt
===================================================================
@@ -1 +1 @@
-old text
+new text`;
const result = editHistoryBlock([diff]);
const expected = `User edited file "simple.txt"
\`\`\`diff
@@ -1 +1 @@
-old text
+new text
\`\`\``;
expect(result).toBe(expected);
});
});

View file

@ -50,12 +50,15 @@ export function currentFileContentBlock(
}
export function editHistoryBlock(
editDiffHistory: string, // could be a singe large unified diff
editDiffHistory: string[], // could be a singe large unified diff
) {
// diffHistory is made from createDiff.
// This uses createPatch from npm diff library, which includes an index line and a separator.
// We get rid of these first two lines.
return editDiffHistory.split("\n").slice(2).join("\n");
return editDiffHistory
.map((diff) => diff.split("\n").slice(2).join("\n"))
.join("\n");
// return editDiffHistory.split("\n").slice(2).join("\n");
}
function mercuryNextEditTemplateBuilder(

View file

@ -108,12 +108,12 @@ describe("mercuryCoderNextEdit", () => {
it("should return the edit diff history unchanged", () => {
const diffHistory =
"diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@";
const result = editHistoryBlock(diffHistory);
const result = editHistoryBlock([diffHistory]);
expect(result).toBe("@@ -1,3 +1,4 @@");
});
it("should handle empty diff history", () => {
const result = editHistoryBlock("");
const result = editHistoryBlock([]);
expect(result).toBe("");
});
});

View file

@ -1,7 +1,7 @@
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange(
const instrumentedLines = [
...lines.slice(0, editableRegionStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(editableRegionStart, editableRegionEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(editableRegionEnd + 1),
];

View file

@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import { Position } from "../..";
import {
MODEL_1_EDITABLE_REGION_END_TOKEN,
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
} from "../constants";
@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
...lines.slice(0, expectedStart),
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
...lines.slice(expectedStart, expectedEnd + 1),
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
...lines.slice(expectedEnd + 1),
];
@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => {
const expected = [
"line 0",
MODEL_1_EDITABLE_REGION_START_TOKEN,
INSTINCT_EDITABLE_REGION_START_TOKEN,
"line 1",
"line 2",
"line 3",
MODEL_1_EDITABLE_REGION_END_TOKEN,
INSTINCT_EDITABLE_REGION_END_TOKEN,
"line 4",
];

View file

@ -90,10 +90,12 @@ export interface NextEditTemplate {
export interface TemplateVars {}
export interface Model1TemplateVars extends TemplateVars {
userEdits: string;
export interface InstinctTemplateVars extends TemplateVars {
contextSnippets: string;
currentFileContent: string;
editDiffHistory: string; // could be a singe large unified diff
currentFilePath: string;
languageShorthand: string;
userExcerpts: string;
}
export interface MercuryTemplateVars extends TemplateVars {

View file

@ -1,3 +1,5 @@
import { DiffLine } from "..";
export function isNextEditTest(): boolean {
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
@ -11,3 +13,11 @@ export function isNextEditTest(): boolean {
return false;
}
export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean {
return diffLines.every(
(diff) =>
diff.type === "old" &&
(diff.line.trim() === "" || /^\s+$/.test(diff.line)),
);
}

View file

@ -0,0 +1,59 @@
import { describe, expect, test, vi } from "vitest";
import { DiffLine } from "..";
import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
describe("isNextEditTest", () => {
test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
vi.stubEnv("NEXT_EDIT_TEST_ENABLED", "true");
expect(isNextEditTest()).toBe(true);
});
test("returns false when NEXT_EDIT_TEST_ENABLED is 'false'", () => {
vi.stubEnv("NEXT_EDIT_TEST_ENABLED", "false");
expect(isNextEditTest()).toBe(false);
});
test("returns false when NEXT_EDIT_TEST_ENABLED is undefined", () => {
vi.stubEnv("NEXT_EDIT_TEST_ENABLED", undefined);
expect(isNextEditTest()).toBe(false);
});
});
describe("isWhitespaceOnlyDeletion", () => {
test("returns true for whitespace-only deletions", () => {
const diffLines: DiffLine[] = [
{ type: "old", line: " " },
{ type: "old", line: "\t" },
];
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
});
test("returns false for non-whitespace deletions", () => {
const diffLines: DiffLine[] = [
{ type: "old", line: "code" },
{ type: "old", line: " " },
];
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
});
test("returns false for mixed content", () => {
const diffLines: DiffLine[] = [
{ type: "old", line: " " },
{ type: "old", line: "code" },
];
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
});
test("returns false for mixed type", () => {
const diffLines: DiffLine[] = [
{ type: "old", line: " " },
{ type: "new", line: "" },
];
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
});
test("returns true for empty array", () => {
const diffLines: DiffLine[] = [];
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
});
});

1328
core/package-lock.json generated

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more