Merge branch 'main' into dependent-context-indexing

This commit is contained in:
uinstinct 2025-07-29 00:31:35 +05:30
commit ec8ec6b36d
1115 changed files with 71516 additions and 33410 deletions

View file

@ -0,0 +1,9 @@
---
name: Add Continue pun easter eggs
description: Adds an easter egg whenever the "continue" keyword
pattern: "continue"
---
Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
Do not add a comment if the use of "continue" is not in a code continue statement

View file

@ -0,0 +1,5 @@
---
globs: "gui/**/*.tsx"
---
You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`.

View file

@ -0,0 +1,200 @@
---
alwaysApply: false
---
# Continue Development Data (Dev Data) Guide
## Overview
Development data (dev data) captures detailed information about how developers interact with LLM-aided development tools. Unlike basic telemetry, dev data includes lots of details into the complete software development workflow, including code context, user interactions, and development patterns.
## Core Architecture
### Primary Implementation Files
- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission
- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types
### Storage Locations
- **Default storage**: `~/.continue/dev_data/`
- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl`
## Event Types and Schemas
### Core Event Types
1. **`tokensGenerated`**: LLM token usage tracking
2. **`autocomplete`**: Code completion interactions
3. **`chatInteraction`**: Chat-based development assistance
4. **`editInteraction`**: Code editing sessions
5. **`editOutcome`**: Results of edit operations
6. **`nextEditOutcome`**: Next Edit feature outcomes
7. **`chatFeedback`**: User feedback on AI responses
8. **`toolUsage`**: Tool interaction statistics
9. **`quickEdit`**: Quick edit functionality usage
### Schema Versioning
- **Version 0.1.0**: Initial schema implementation
- **Version 0.2.0**: Current schema with expanded fields and metadata
- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/`
### Base Schema Structure
All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`):
```typescript
{
eventName: string,
schema: string,
timestamp: string,
userId: string,
userAgent: string,
selectedProfileId: string
}
```
## Key Integration Points
### Autocomplete System
- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts`
- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits
- **Integration**: Called from autocomplete engine when completions are shown/accepted
### Chat Interface
- **Integration**: Chat interactions logged through `DataLogger.logDevData()`
- **Data**: Includes prompts, responses, context, and user feedback
- **Privacy**: Can be configured to exclude code content
### Edit Features
- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts`
- **Purpose**: Track edit suggestions, acceptance rates, and outcomes
- **Integration**: Embedded in edit workflow to capture user decisions
### LLM Token Tracking
- **File**: `/core/llm/index.ts`
- **Purpose**: Track token usage across all LLM providers
- **Storage**: SQLite database for efficient querying and reporting
## Configuration and Customization
### Configuration Structure
Dev data is configured through `data` blocks in your Continue config:
```yaml
data:
- name: "Local Development Data"
destination: "file:///Users/developer/.continue/dev_data"
schema: "0.2.0"
level: "all"
events: ["autocomplete", "chatInteraction", "editOutcome"]
- name: "Team Analytics"
destination: "https://analytics.yourcompany.com/api/events"
schema: "0.2.0"
level: "noCode"
apiKey: "your-api-key-here"
events: ["tokensGenerated", "toolUsage"]
```
### Configuration Options
- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote)
- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`)
- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content)
- **`events`**: Array of event types to collect
- **`apiKey`**: Authentication for remote endpoints
### Privacy Controls
- **`"all"` level**: Includes code content (prefixes, suffixes, completions)
- **`"noCode"` level**: Excludes code content, only metadata and metrics
- **Local-first**: Data is always stored locally, remote transmission is optional
## Making Changes to Dev Data
### Adding New Event Types
1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/`
2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts`
3. **Implement logging**: Add logging calls in relevant service files
4. **Update version**: Consider schema version bump if breaking changes
### Modifying Existing Events
1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/`
2. **Backward compatibility**: Ensure changes don't break existing data consumers
3. **Version management**: Increment schema version for breaking changes
4. **Test thoroughly**: Validate schema changes with existing data
### Adding New Logging Points
1. **Import DataLogger**: `import { DataLogger } from "core/data/log"`
2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)`
3. **Follow patterns**: Use existing logging services as examples
4. **Validate data**: Ensure logged data matches schema requirements
### Debugging Dev Data Issues
1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/`
2. **Validate schemas**: Ensure event data matches expected schema format
3. **Review configuration**: Check `data` blocks in Continue config
4. **Test endpoints**: Verify remote endpoints are reachable and accepting data
## Best Practices
### When Adding New Events
- Follow existing naming conventions for event types
- Include sufficient context for analysis without oversharing sensitive data
- Consider privacy implications and respect user configuration levels
- Add appropriate error handling and logging
### When Modifying Schemas
- Maintain backward compatibility when possible
- Document schema changes thoroughly
- Consider impact on existing data consumers
- Test with real development data
### When Integrating Logging
- Use the singleton pattern: `DataLogger.getInstance()`
- Log events at appropriate points in user workflow
- Respect user privacy settings and configuration
- Handle errors gracefully without disrupting user experience
## Common Patterns
### Service-Based Logging
Most dev data logging follows a service pattern:
```typescript
export class FeatureLoggingService {
private dataLogger = DataLogger.getInstance();
logFeatureUsage(data: FeatureUsageData) {
this.dataLogger.logDevData("featureUsage", data);
}
}
```
### Event-Driven Logging
Events are typically logged at key interaction points:
```typescript
// When user accepts autocomplete
onAutocompleteAccepted(completion: CompletionData) {
AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion);
}
```
This guide provides the foundation for understanding and working with Continue's dev data system. Always prioritize user privacy and follow established patterns when making changes.

View file

@ -0,0 +1,8 @@
---
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,5 @@
---
alwaysApply: false
---
Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}`. For ternaries, you could use @cn.ts.

View file

@ -0,0 +1,25 @@
---
globs: ["gui/**/*", "core/**/*"]
description: Provides test running instructions for GUI and core folders
alwaysApply: false
---
When working with test files, use the following commands to run tests:
GUI folder tests:
- Run all tests: `cd gui && npm test`
Core folder tests:
- Run Jest tests: `cd core && npm test`
- Run Vitest tests: `cd core && npm run vitest`
Test file patterns:
- GUI: _.test.ts or_.test.tsx files use Vitest
- Core: _.test.ts files use Jest,_.vitest.ts files use Vitest
Best practices:
- We are transitioning to vitest, so use that when creating new tests

View file

@ -0,0 +1,6 @@
---
globs: "**/*.{ts,tsx}"
alwaysApply: false
---
Use enums instead of simple string unions when possible in TypeScript code

View file

@ -11,6 +11,8 @@ body:
attributes:
label: Before submitting your bug report
options:
- label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer
required: false
- label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
required: false
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug

View file

@ -8,9 +8,9 @@
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created
## Screenshots
## Screen recording or screenshot
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ]
## Tests

View file

@ -24,7 +24,8 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
branch: cla-signatures
allowlist: dependabot[bot]
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
signed-commit-message: "CLA signed in $pullRequestNo"

199
.github/workflows/compliance.yaml vendored Normal file
View file

@ -0,0 +1,199 @@
name: PR Compliance Checks
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
conventional-commits:
name: Validate Conventional Commits (Warning Only)
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
continue-on-error: true
permissions:
pull-requests: write
issues: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validate conventional commits
id: commitlint
uses: wagoid/commitlint-github-action@v6
with:
configFile: .commitlintrc.warning.json
# Only check the last commit instead of all commits in the PR
commitDepth: 1
continue-on-error: true
- name: Add commit message guidance comment
if: steps.commitlint.outcome == 'failure'
uses: actions/github-script@v7
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('Conventional Commit Format')
);
if (!botComment) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: [
"## ⚠️ Conventional Commit Format",
"",
"Your latest commit message doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
"",
"### Expected Format:",
"```",
"<type>[optional scope]: <description>",
"",
"[optional body]",
"",
"[optional footer(s)]",
"```",
"",
"### Examples:",
"- `feat: add changelog generation support`",
"- `fix: resolve login redirect issue`",
"- `docs: update README with new instructions`",
"- `chore: update dependencies`",
"",
"### Valid Types:",
"`feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`",
"",
"This helps with:",
"- 📝 Automatic changelog generation",
"- 🚀 Automated semantic versioning",
"- 📊 Better project history tracking",
"",
"*This is a non-blocking warning - your PR can still be merged without fixing this.*"
].join('\n')
});
}
security-audit:
name: Security Audit
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
permissions:
security-events: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Fix vulnerabilities
run: npm audit fix
- name: Run npm audit
run: npm audit --audit-level=moderate
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
# Use this for any files that we want to be certain exist
# Basically creates a forcing function to discuss were anyone to want to remove them
file-validation:
name: Required Files Check
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check required files
run: |
required_files=(
"package.json"
"package-lock.json"
"README.md"
"LICENSE"
".gitignore"
"tsconfig.json"
"SECURITY.md"
"CONTRIBUTING.md"
".nvmrc"
".prettierrc"
".prettierignore"
)
missing_files=()
for file in "${required_files[@]}"; do
if [[ ! -f "$file" ]]; then
missing_files+=("$file")
fi
done
if [[ ${#missing_files[@]} -gt 0 ]]; then
echo "❌ Missing required files:"
printf '%s\n' "${missing_files[@]}"
exit 1
else
echo "✅ All required files present"
fi
compliance-summary:
name: Compliance Summary
runs-on: ubuntu-latest
needs: [conventional-commits, security-audit, file-validation]
if: always() && !github.event.pull_request.draft
steps:
- name: Check compliance status
run: |
echo "## 🔍 Compliance Check Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ needs.conventional-commits.result }}" == "success" ]]; then
echo "✅ Conventional Commits: PASSED" >> $GITHUB_STEP_SUMMARY
elif [[ "${{ needs.conventional-commits.result }}" == "failure" ]]; then
echo "⚠️ Conventional Commits: WARNING (non-blocking)" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Conventional Commits: SKIPPED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.security-audit.result }}" == "success" ]]; then
echo "✅ Security Audit: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Security Audit: FAILED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.file-validation.result }}" == "success" ]]; then
echo "✅ File Validation: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ File Validation: FAILED" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "📊 **Overall Status**: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY

32
.github/workflows/docs.yml vendored Normal file
View file

@ -0,0 +1,32 @@
name: Docs Check
on:
push:
paths:
- 'docs2/**'
pull_request:
paths:
- 'docs2/**'
jobs:
check-broken-links:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: docs2/package-lock.json
- name: Install dependencies
working-directory: ./docs2
run: npm ci
- name: Check for broken links
working-directory: ./docs2
run: npx mintlify broken-links

View file

@ -63,7 +63,6 @@ jobs:
- name: Bump version in gradle.properties
run: |
cd extensions/intellij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
@ -167,20 +166,8 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd ../../packages/config-yaml
npm i
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
- name: Build packages (Unix)
run: cd ../.. && ./scripts/build-packages.sh
# npm install core
- name: Install core node_modules
@ -236,10 +223,6 @@ jobs:
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build plugin
- name: Build plugin
run: ./gradlew buildPlugin
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -249,7 +232,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -259,7 +242,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact

View file

@ -50,7 +50,7 @@ jobs:
echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
- name: Post a message in a channel
uses: slackapi/slack-github-action@v2.1.0
uses: slackapi/slack-github-action@v2.1.1
with:
webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
webhook-type: incoming-webhook

View file

@ -50,7 +50,10 @@ jobs:
install-config-yaml:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -77,7 +80,10 @@ jobs:
install-openai-adapters:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -133,7 +139,10 @@ jobs:
install-core:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -381,7 +390,10 @@ jobs:
install-vscode:
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -572,6 +584,43 @@ jobs:
cd packages/config-yaml
npm test
openai-adapters-tests:
needs: install-openai-adapters
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Run openai-adapters tests
run: |
cd packages/openai-adapters
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode, install-config-yaml]
@ -613,13 +662,19 @@ jobs:
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Debug Outputs
run: |
echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}"
vscode-package-extension:
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
needs:
[
install-vscode,
@ -676,7 +731,7 @@ jobs:
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: vscode-extension-build
name: vscode-extension-build-${{ runner.os }}
path: extensions/vscode/build
vscode-download-e2e-dependencies:
@ -772,7 +827,7 @@ jobs:
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: vscode-extension-build
name: vscode-extension-build-Linux
path: extensions/vscode/build
- name: Download e2e dependencies
@ -1068,6 +1123,7 @@ jobs:
- config-yaml-checks
- install-config-yaml
- install-openai-adapters
- openai-adapters-tests
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/config-yaml/**"
- ".github/workflows/release-config-yaml.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/fetch/**"
- ".github/workflows/release-fetch.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -16,3 +16,11 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/openai-adapters/**"
- ".github/workflows/release-openai-adapters.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -14,6 +14,24 @@ on:
required: true
SEMANTIC_RELEASE_NPM_TOKEN:
required: true
OPENAI_API_KEY:
required: false
ANTHROPIC_API_KEY:
required: false
GEMINI_API_KEY:
required: false
MISTRAL_API_KEY:
required: false
AZURE_OPENAI_API_KEY:
required: false
AZURE_FOUNDRY_CODESTRAL_API_KEY:
required: false
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY:
required: false
AZURE_OPENAI_GPT41_API_KEY:
required: false
VOYAGE_API_KEY:
required: false
permissions:
contents: write
@ -46,10 +64,20 @@ jobs:
- name: Run tests
run: npm test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npx semantic-release
run: npx semantic-release

3
.gitignore vendored
View file

@ -67,8 +67,9 @@ instance/
# Scrapy stuff:
.scrapy
# Sphinx documentation
# docusaurus
docs/_build/
docs/.docusaurus
# PyBuilder
target/

2
.idea/gradle.xml generated
View file

@ -5,7 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="homebrew-17" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

2
.idea/kotlinc.xml generated
View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.0" />
<option name="version" value="1.8.0" />
</component>
</project>

View file

@ -17,12 +17,12 @@ past and future “Contributions” submitted to **Continue (the “Project”)*
## 2. Copyright License
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
license to reproduce, prepare derivative works of, publicly display, publicly
perform, sublicense, and distribute Your Contributions and derivative works.
## 3. Patent License
## 3. Patent License
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent

View file

@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example
- Open a PR against the `main` branch. Make sure to fill in the PR template
### Formatting

View file

@ -36,27 +36,27 @@ and [hub of models, rules, prompts, docs, and other building blocks](https://hub
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
![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](docs/static/img/chat.gif)
![chat](docs/images/chat.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
![autocomplete](docs/static/img/autocomplete.gif)
![autocomplete](docs/images/autocomplete.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](docs/static/img/edit.gif)
![edit](docs/images/edit.gif)
</div>

1
binary/.gitignore vendored
View file

@ -3,3 +3,4 @@ bin
data
out
tmp
tree-sitter

View file

@ -21,6 +21,7 @@ function cleanSlate() {
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
rimrafSync(path.join(__dirname, "tree-sitter"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
@ -142,6 +143,25 @@ async function buildWithEsbuild() {
);
});
// copy tree-sitter colder to binary folder to make it available when running in intellij debug mode
const treeSitterDir = path.join(__dirname, "tree-sitter");
fs.mkdirSync(treeSitterDir);
await new Promise((resolve, reject) => {
ncp(
path.join(__dirname, "..", "extensions", "vscode", "tree-sitter"),
treeSitterDir,
{ dereference: true },
(error) => {
if (error) {
console.warn("[error] Error copying tree-sitter files", error);
reject(error);
} else {
resolve();
}
},
);
});
const filesToCopy = [
"../core/vendor/tree-sitter.wasm",
"../core/llm/llamaTokenizerWorkerPool.mjs",

View file

@ -121,6 +121,8 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@shikijs/colorized-brackets": "^3.7.0",
"@shikijs/transformers": "^3.7.0",
"@types/diff": "^7.0.1",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
@ -144,6 +146,7 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"shiki": "^3.6.0",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3",
"vitest": "^3.1.4"

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe",

View file

@ -19,5 +19,19 @@
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-params": ["error", { "max": 8 }]
}
},
"overrides": [
{
"files": [
"**/*.test.ts",
"**/*.test.tsx",
"**/*.spec.ts",
"**/*.spec.tsx",
"**/*.vitest.ts"
],
"rules": {
"max-lines-per-function": "off"
}
}
]
}

View file

@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { getAllSnippets } from "./snippets/index.js";
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
import { renderPrompt } from "./templating/index.js";
import { GetLspDefinitionsFunction } from "./types.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
@ -121,6 +121,12 @@ export class CompletionProvider {
...config?.tabAutocompleteOptions,
...llm.autocompleteOptions,
};
// Enable static contextualization if defined.
if (config?.experimental?.enableStaticContextualization) {
options.experimental_enableStaticContextualization = true;
}
return options;
}
@ -171,7 +177,7 @@ export class CompletionProvider {
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
getAllSnippetsWithoutRace({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@ -254,10 +260,14 @@ export class CompletionProvider {
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
timestamp: new Date().toISOString(),
...helper.options,
};
if (options.experimental_enableStaticContextualization) {
outcome.enabledStaticContextualization = true;
}
//////////
// Save to cache

View file

@ -6,12 +6,36 @@ import {
} from "../filtering/streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
/**
* The display name of the language
*/
name: string;
/**
* Keywords that show up at the top-level of files. We often use these as stop words or soft breaks
*/
topLevelKeywords: string[];
/**
* The character that prefixes a single line comment
* We use this to format snippets from other files as large comment blocks
*/
singleLineComment?: string;
/**
* Semi-colon or other end of line indicator that may be used as a stop char
* or other parsing
*/
endOfLine: string[];
/**
* Strings that indicate we should filter out a line from completion
* Primarily currently used for .ipynb files
*/
lineFilters?: LineFilter[];
/**
* Similar to line filters, but characters. I think.
*/
charFilters?: CharacterFilter[];
/**
* Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis
*/
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
}
@ -23,6 +47,14 @@ export const Typescript = {
endOfLine: [";"],
};
// JavaScript
export const JavaScript = {
name: "JavaScript",
topLevelKeywords: ["function", "class", "module", "export", "import"],
singleLineComment: "//",
endOfLine: [";"],
};
// Python
export const Python = {
name: "Python",
@ -336,7 +368,7 @@ export const Markdown: AutocompleteLanguageInfo = {
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
ts: Typescript,
js: Typescript,
js: JavaScript,
tsx: Typescript,
json: Json,
jsx: Typescript,

View file

@ -2,16 +2,19 @@ import { IDE } from "../..";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
import { StaticContextService } from "./static-context/StaticContextService";
export class ContextRetrievalService {
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private staticContextService: StaticContextService;
constructor(private readonly ide: IDE) {
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
@ -19,6 +22,7 @@ export class ContextRetrievalService {
this.importDefinitionsService,
this.ide,
);
this.staticContextService = new StaticContextService(this.ide);
}
public async getSnippetsFromImportDefinitions(
@ -70,4 +74,26 @@ export class ContextRetrievalService {
helper.treePath,
);
}
public async getStaticContextSnippets(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
return this.staticContextService.getContext(helper);
}
/**
* Initialize the import definitions cache for a file.
* This is normally done automatically when the active text editor changes,
* but needs to be called manually when using context fetching outside the normal flow.
*/
public async initializeForFile(filepath: string): Promise<void> {
try {
await (this.importDefinitionsService as any).cache.initKey(filepath);
} catch (e) {
console.warn(
`Failed to initialize import definitions cache for ${filepath}:`,
e,
);
}
}
}

View file

@ -0,0 +1,888 @@
import * as fs from "fs/promises";
import path from "path";
import { pathToFileURL } from "url";
import Parser from "web-tree-sitter";
import { IDE, Position } from "../../..";
import { localPathOrUriToPath } from "../../../util/pathToUri";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import {
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../../snippets/types";
import { getAst } from "../../util/ast";
import { HelperVars } from "../../util/HelperVars";
import {
extractFunctionTypeFromDecl,
extractTopLevelDecls,
findEnclosingTypeDeclaration,
unwrapToBaseType,
} from "./tree-sitter-utils";
import {
HoleContext,
RelevantHeaders,
RelevantTypes,
StaticContext,
TypeSpanAndSourceFile,
TypeSpanAndSourceFileAndAst,
} from "./types";
export class StaticContextService {
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
}
public logAutocompleteStaticSnippet(
ctx: StaticContext,
label = "Static Snippet",
) {
console.log(`=== ${label} ===`);
console.log("Hole Type:", ctx.holeType);
console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
ctx.relevantTypes.forEach((types, filepath) => {
console.log(` 📁 ${filepath}`);
types.forEach((type) => console.log(` • ${type}`));
});
console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
ctx.relevantHeaders.forEach((headers, filepath) => {
console.log(` 📁 ${filepath}`);
headers.forEach((header) => console.log(` • ${header}`));
});
}
public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
let output = `AutocompleteStaticSnippet:\n`;
output += ` holeType: ${ctx.holeType}\n`;
output += ` relevantTypes:\n`;
if (ctx.relevantTypes.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantTypes.forEach((types, filepath) => {
output += ` ${filepath}: [${types.join(", ")}]\n`;
});
}
output += ` relevantHeaders:\n`;
if (ctx.relevantHeaders.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantHeaders.forEach((headers, filepath) => {
output += ` ${filepath}: [${headers.join(", ")}]\n`;
});
}
return output;
}
public async getContext(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
const start = Date.now();
const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
helper.workspaceUris,
);
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
const holeContext = await this.getHoleContext(
helper.fileContents,
helper.filepath,
helper.pos,
);
const relevantTypes = await this.extractRelevantTypes(
holeContext.fullHoverResult,
holeContext.functionName,
holeContext.range.start.line,
holeContext.source,
new Map<string, string>(),
);
// if (this.language === "typescript") {
// repo = getAllTSFiles(this.repoPath);
// } else if (this.language === "ocaml") {
// repo = getAllOCamlFiles(this.repoPath);
// }
//
const relevantHeaders = await this.extractRelevantHeaders(
tsFiles,
relevantTypes,
holeContext.functionTypeSpan,
helper.pos,
holeContext.returnTypeIsAny,
);
const relevantTypesToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
if (relevantTypesToReturn.has(src)) {
const updated = relevantTypesToReturn.get(src)!;
updated.push(v);
relevantTypesToReturn.set(src, updated);
} else {
relevantTypesToReturn.set(src, [v]);
}
});
const relevantHeadersToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
if (relevantHeadersToReturn.has(src)) {
const updated = relevantHeadersToReturn.get(src)!;
if (!updated.includes(v)) {
updated.push(v);
}
relevantHeadersToReturn.set(src, updated);
} else {
relevantHeadersToReturn.set(src, [v]);
}
});
const ctx = {
holeType: holeContext.functionTypeSpan,
relevantTypes: relevantTypesToReturn,
relevantHeaders: relevantHeadersToReturn,
};
const end = Date.now();
this.logAutocompleteStaticSnippet(ctx);
// console.log(end - start);
const snippets: AutocompleteStaticSnippet[] = [];
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
content: holeContext.fullHoverResult,
});
for (const [filepath, typs] of ctx.relevantTypes.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: typs.join("\n"),
});
}
for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: headers.join("\n"),
});
}
return snippets;
}
private async getHoleContext(
sketchFileContent: string,
sketchFilePath: string,
cursorPosition: Position,
): Promise<HoleContext> {
// We need to inject the hole @ to trigger a treesitter error node.
sketchFilePath = localPathOrUriToPath(sketchFilePath);
// const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
const injectedContent = this.insertAtPosition(
sketchFileContent,
cursorPosition,
"@;",
);
// The hole's position is cursorPosition.
// Use treesitter to parse.
const ast = await getAst(sketchFilePath, injectedContent);
if (!ast) {
throw new Error("failed to get ast");
}
const language = getFullLanguageName(sketchFilePath);
const query = await getQueryForFile(
sketchFilePath,
`static-context-queries/hole-queries/${language}.scm`,
);
if (!query) {
throw new Error(
`getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
);
}
const captures = query.captures(ast.rootNode);
const res: HoleContext = {
fullHoverResult: "",
functionName: "",
functionTypeSpan: "",
returnTypeIsAny: false,
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
source: `file://${sketchFilePath}`,
};
let paramsTypes = "";
for (const c of captures) {
const { name, node } = c;
// console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
switch (name) {
case "function.decl": {
res.fullHoverResult = node.text;
break;
}
case "function.name": {
res.functionName = node.text;
break;
}
case "function.params": {
paramsTypes = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
case "function.type": {
res.functionTypeSpan = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
}
}
if (res.functionTypeSpan === "") {
res.functionTypeSpan = `${paramsTypes} => any`;
res.returnTypeIsAny = true;
}
return res;
}
private async extractRelevantTypes(
declText: string,
typeName: string,
startLine: number,
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
): Promise<RelevantTypes> {
const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
await this.extractRelevantTypesHelper(
declText,
typeName,
startLine,
foundSoFar,
currentFile,
foundContents,
);
return foundSoFar;
}
private async extractRelevantTypesHelper(
declText: string,
typeName: string,
startLine: number,
foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
) {
if (!foundSoFar.has(typeName)) {
const ast = await getAst(currentFile, declText);
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
foundSoFar.set(typeName, {
typeSpan: declText,
sourceFile: currentFile.slice(7),
ast: ast,
});
const language = getFullLanguageName(currentFile);
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const identifiers = query.captures(ast.rootNode);
for (const { name, node } of identifiers) {
if (foundSoFar.has(node.text)) continue;
try {
const typeDefinitionResult = await this.ide.gotoTypeDefinition({
filepath: currentFile,
position: {
character: node.startPosition.column,
line: startLine + node.startPosition.row,
},
});
if (typeDefinitionResult.length > 0) {
const tdLocation = typeDefinitionResult[0];
let content = "";
if (foundContents.has(tdLocation.filepath)) {
content = foundContents.get(tdLocation.filepath)!;
} else {
content = await fs.readFile(
localPathOrUriToPath(tdLocation.filepath),
"utf8",
);
foundContents.set(tdLocation.filepath, content);
}
const ast = await getAst(tdLocation.filepath, content);
if (!ast) {
throw new Error(
`failed to get ast for file ${tdLocation.filepath}`,
);
}
const decl = findEnclosingTypeDeclaration(
content,
tdLocation.range.start.line,
tdLocation.range.start.character,
ast,
);
if (!decl) {
// throw new Error(`failed to get decl for file ${tdLocation.uri}`);
console.error(
`failed to get decl for file ${tdLocation.filepath}`,
);
}
if (decl) {
await this.extractRelevantTypesHelper(
decl.fullText,
node.text,
tdLocation.range.start.line,
foundSoFar,
tdLocation.filepath,
foundContents,
);
} else {
// console.log("decl not found");
}
} else {
// console.log("td not found");
}
} catch (err) {
console.log(err);
}
}
}
}
private async extractRelevantHeaders(
sources: string[],
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
cursorPosition: Position,
returnTypeIsAny: boolean,
): Promise<RelevantHeaders> {
const relevantContext = new Set<TypeSpanAndSourceFile>();
if (returnTypeIsAny) return relevantContext;
// NOTE: This is necessary because TypeScript sucks.
// There is no way to compare objects by value,
// so sets of objects starts to accumulate tons of duplicates.
const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
const foundNormalForms = new Map<string, string>();
const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
for (const source of sources) {
const topLevelDecls = await extractTopLevelDecls(source);
for (const tld of topLevelDecls) {
// pattern 0 is let/const, 1 is var, 2 is fun
// if (!seenDecls.has(JSON.stringify()) {
const originalDeclText =
tld.pattern === 2
? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
: tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
if (tld.pattern === 2) {
// build a type span
// TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
// most likely due to my scm query and how I'm not attaching param name along with param type
let funcType = "";
try {
funcType = extractFunctionTypeFromDecl(tld);
} catch (err) {
// Most likely is the case that there is no explicit return type annotation.
const sigHelp = await this.ide.getSignatureHelp({
filepath: source,
position: cursorPosition,
});
if (!sigHelp) continue;
funcType = sigHelp.signatures[0].label;
// TODO: This only works for TypeScript.
function convertToArrowType(signature: string): string {
// Handle various function declaration formats.
const patterns = [
// Standard: functionName(params): returnType.
/^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
// With generics: functionName<T>(params): returnType.
/^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
// With modifiers: export function functionName(params): returnType.
/^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
];
for (const pattern of patterns) {
const match = signature.match(pattern);
if (match) {
const [, , parameters, returnType] = match;
return `(${parameters}) => ${returnType}`;
}
}
return signature;
}
funcType = convertToArrowType(funcType);
}
const wrapped = `type __TMP = ${funcType};`;
const ast = await getAst("file.ts", wrapped);
if (!ast) {
throw new Error(`failed to generate ast for ${wrapped}`);
}
// console.log(ast.rootNode);
const alias = ast.rootNode.namedChild(0);
// console.log(alias);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error(
"extractRelevantHeaders: Failed to parse type alias",
);
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.extractRelevantHeadersHelper(
originalDeclText,
baseNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
} else {
const varTypNode = tld.captures.find(
(d) => d.name === "top.var.type",
)!.node;
await this.extractRelevantHeadersHelper(
originalDeclText,
varTypNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
for (const v of relevantContextMap.values()) {
relevantContext.add(v);
}
return relevantContext;
}
private async extractRelevantHeadersHelper(
originalDeclText: string,
node: Parser.SyntaxNode,
targetTypes: Set<Parser.SyntaxNode>,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
relevantContext: Set<TypeSpanAndSourceFile>,
relevantContextMap: Map<string, TypeSpanAndSourceFile>,
foundNormalForms: Map<string, string>,
source: string,
) {
for (const typ of targetTypes) {
if (
await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
) {
const ctx = { typeSpan: originalDeclText, sourceFile: source };
relevantContextMap.set(JSON.stringify(ctx), ctx);
}
if (node.type === "function_type") {
const retTypeNode = node.namedChildren.find(
(c) => c && c.type === "return_type",
);
if (retTypeNode) {
await this.extractRelevantHeadersHelper(
originalDeclText,
retTypeNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
} else if (node.type === "tuple_type") {
for (const c of node.namedChildren) {
await this.extractRelevantHeadersHelper(
originalDeclText,
c!,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
}
private async generateTargetTypes(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
) {
const targetTypes = new Set<Parser.SyntaxNode>();
// const ast = relevantTypes.get(holeIdentifier)!.ast;
const ast = await getAst("file.ts", `type T = ${holeType};`);
if (!ast) {
throw new Error(`failed to generate ast for ${holeType}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error("generateTargetTypes: Failed to parse type alias");
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
targetTypes.add(baseNode);
await this.generateTargetTypesHelper(
relevantTypes,
holeType,
targetTypes,
baseNode,
);
return targetTypes;
}
private async generateTargetTypesHelper(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
currType: string,
targetTypes: Set<Parser.SyntaxNode>,
node: Parser.SyntaxNode | null,
): Promise<void> {
if (!node) return;
if (node.type === "function_type") {
const returnType = node.childForFieldName("return_type");
if (returnType) {
targetTypes.add(returnType);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
returnType,
);
}
}
if (node.type === "tuple_type") {
for (const child of node.namedChildren) {
if (child) {
targetTypes.add(child);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
child,
);
}
}
}
if (relevantTypes.has(node.text)) {
// const ast = relevantTypes.get(node.text)!.ast;
const typeSpan = relevantTypes.get(node.text)?.typeSpan;
// const ast = await getAst("file.ts", `type T = ${typeSpan}`);
const ast = await getAst("file.ts", typeSpan!);
if (!ast) {
throw new Error(`failed to generate ast for ${typeSpan}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
console.error("generateTargetTypesHelper: Failed to parse type alias");
return;
// throw new Error(
// "generateTargetTypesHelper: Failed to parse type alias",
// );
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
baseNode,
);
}
// if (node.type === "type_identifier" || node.type === "predefined_type") {
// return [node.text];
// }
return;
}
private async isTypeEquivalent(
node: Parser.SyntaxNode,
typ: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
foundNormalForms: Map<string, string>,
): Promise<boolean> {
if (!node || !typ) {
return false;
}
let normT1 = "";
let normT2 = "";
if (foundNormalForms.has(node.text)) {
// console.log("found t1", true)
normT1 = foundNormalForms.get(node.text)!;
} else {
// console.log("not found t1", false)
normT1 = await this.normalize(node, relevantTypes);
foundNormalForms.set(node.text, normT1);
}
if (foundNormalForms.has(typ.text)) {
// console.log("found t2", true)
normT2 = foundNormalForms.get(typ.text)!;
} else {
// console.log("not found t2", false)
normT2 = await this.normalize(typ, relevantTypes);
foundNormalForms.set(typ.text, normT2);
}
// const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
// const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
// console.log(`normal forms: ${normT1} {}{} ${normT2}`)
return normT1 === normT2;
}
private async normalize(
node: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
): Promise<string> {
if (!node) return "";
switch (node.type) {
case "function_type": {
const params = node.child(0); // formal_parameters
const returnType =
node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
const paramTypes =
params?.namedChildren
.map((param) =>
this.normalize(
param!.childForFieldName("type")! ||
param!.namedChildren.at(-1),
relevantTypes,
),
)
.join(", ") || "";
const ret = this.normalize(returnType!, relevantTypes);
return `(${paramTypes}) => ${ret}`;
}
case "tuple_type": {
const elements = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return `[${elements.join(", ")}]`;
}
case "union_type": {
const parts = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return parts.join(" | ");
}
case "type_identifier": {
const alias = relevantTypes.get(node.text);
if (!alias) return node.text;
// Parse the alias's type span
const wrapped = `type __TMP = ${alias};`;
const tree = await getAst("file.ts", wrapped);
const valueNode = tree!.rootNode
.descendantsOfType("type_alias_declaration")[0]
?.childForFieldName("value");
return this.normalize(valueNode!, relevantTypes);
}
case "predefined_type":
case "number":
case "string":
return node.text;
default:
// Fallback for types like array, etc.
return node.text;
}
}
private insertAtPosition = (
contents: string,
cursorPosition: { line: number; character: number },
insertText: string,
): string => {
const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
const { line, character } = cursorPosition;
if (line < 0 || line >= lines.length) {
throw new Error("Invalid line number");
}
const targetLine = lines[line];
if (character < 0 || character > targetLine.length) {
throw new Error("Invalid character index");
}
// Insert the text
lines[line] =
targetLine.slice(0, character) + insertText + targetLine.slice(character);
return lines.join("\n"); // Reconstruct the file
};
private async getTypeScriptFilesFromWorkspaces(
workspaceUris: string[],
): Promise<string[]> {
const tsExtensions = [".ts"];
const allTsFiles: string[] = [];
for (const workspaceUri of workspaceUris) {
try {
// Convert URI to file path
const folderPath = workspaceUri.startsWith("file://")
? new URL(workspaceUri).pathname
: workspaceUri;
const tsFiles = await this.scanDirectoryForTypeScriptFiles(
folderPath,
tsExtensions,
);
allTsFiles.push(...tsFiles);
} catch (error) {
console.error(`Error scanning workspace ${workspaceUri}:`, error);
}
}
return allTsFiles;
}
private async scanDirectoryForTypeScriptFiles(
dirPath: string,
tsExtensions: string[],
): Promise<string[]> {
const tsFiles: string[] = [];
const shouldSkipDirectory = (dirName: string): boolean => {
const skipDirs = [
"node_modules",
".git",
".vscode",
"dist",
"build",
"out",
".next",
"coverage",
".nyc_output",
"tmp",
"temp",
".cache",
];
return skipDirs.includes(dirName) || dirName.startsWith(".");
};
async function scanRecursively(currentPath: string): Promise<void> {
try {
const entries = await fs.readdir(currentPath, {
withFileTypes: true,
});
for (const entry of entries) {
const fullPath = localPathOrUriToPath(
path.join(currentPath, entry.name),
);
if (entry.isDirectory()) {
// Skip common directories that typically don't contain source files
if (!shouldSkipDirectory(entry.name)) {
await scanRecursively(fullPath);
}
} else if (entry.isFile()) {
const extension = path.extname(entry.name).toLowerCase();
if (tsExtensions.includes(extension)) {
tsFiles.push(fullPath);
}
}
}
} catch (error) {
console.error(`Error reading directory ${currentPath}:`, error);
}
}
await scanRecursively(dirPath);
return tsFiles;
}
}

View file

@ -0,0 +1,222 @@
import * as fs from "fs/promises";
import Parser from "web-tree-sitter";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import { getAst } from "../../util/ast";
export interface TypeDeclarationResult {
name: string;
fullText: string;
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
kind: string;
}
export function findEnclosingTypeDeclaration(
sourceCode: string,
cursorLine: number,
cursorColumn: number,
ast: Parser.Tree,
): TypeDeclarationResult | null {
const point = { row: cursorLine, column: cursorColumn };
let node = ast.rootNode.descendantForPosition(point);
while (
node &&
![
"type_alias_declaration",
"interface_declaration",
"enum_declaration",
].includes(node.type)
) {
if (!node.parent) return null;
node = node.parent;
}
if (!node) return null;
const nameNode = node.childForFieldName("name");
const name = nameNode?.text ?? "<anonymous>";
const fullText = sourceCode.slice(node.startIndex, node.endIndex);
return {
name,
fullText,
startLine: node.startPosition.row,
startColumn: node.startPosition.column,
endLine: node.endPosition.row,
endColumn: node.endPosition.column,
kind: node.type,
};
}
export async function extractTopLevelDecls(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
return query.matches(ast.rootNode);
}
export async function extractTopLevelDeclsWithFormatting(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const matches = query.matches(ast.rootNode);
const results = [];
for (const match of matches) {
const item: {
declaration: string;
nodeType: string;
name: string;
declaredType: string;
returnType?: string;
} = {
declaration: "",
nodeType: "",
name: "",
declaredType: "",
};
for (const { name, node } of match.captures) {
if (name === "top.var.decl") {
item.nodeType = "variable";
item.declaration = node.text;
// Attempt to get the declared type (e.g., const x: string = ...)
const typeNode = node.descendantsOfType("type_annotation")[0];
if (typeNode) {
item.declaredType = typeNode.text.replace(/^:\s*/, "");
}
} else if (name === "top.var.name" || name === "top.fn.name") {
item.name = node.text;
} else if (name === "top.fn.decl") {
item.nodeType = "function";
item.declaration = node.text;
// Get the return type (e.g., function foo(): string)
const returnTypeNode = node.childForFieldName("return_type");
if (returnTypeNode) {
item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
}
// Get declaredType if needed (TypeScript style)
const nameNode = node.childForFieldName("name");
if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
}
}
}
if (item.name && item.declaration) {
results.push(item);
}
}
return results;
}
export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
let paramsNode: Parser.SyntaxNode | undefined = undefined;
let returnNode: Parser.SyntaxNode | undefined = undefined;
for (const capture of match.captures) {
if (capture.name === "top.fn.param.type") {
paramsNode = capture.node;
} else if (capture.name === "top.fn.type") {
returnNode = capture.node;
}
}
if (!paramsNode) {
console.error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
}
if (!returnNode) {
console.error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
}
return `(${paramsNode!.text}) => ${returnNode!.text}`;
}
export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
if (
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(node.type)
) {
return node;
}
for (const child of node.namedChildren) {
const unwrapped = unwrapToBaseType(child!);
if (
unwrapped !== child ||
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(unwrapped.type)
) {
return unwrapped;
}
}
return node;
}

View file

@ -0,0 +1,33 @@
import { Tree } from "web-tree-sitter";
import { Range } from "../../..";
export interface TypeSpanAndSourceFile {
typeSpan: string;
sourceFile: string;
}
export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
ast: Tree;
}
export interface HoleContext {
fullHoverResult: string;
functionName: string;
functionTypeSpan: string;
returnTypeIsAny: boolean;
range: Range;
source: string;
}
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
export type Filepath = string;
export type RelevantType = string;
export type RelevantHeader = string;
export interface StaticContext {
holeType: string;
relevantTypes: Map<Filepath, RelevantType[]>;
relevantHeaders: Map<Filepath, RelevantHeader[]>;
}

View file

@ -0,0 +1,146 @@
import { LineStream } from "../../../diff/util";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import {
processBlockNesting,
shouldStopAtMarkdownBlock,
} from "../../../utils/streamMarkdownUtils";
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
* Now includes markdown-aware processing to handle nested markdown blocks properly.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @param {string} filepath - Optional filepath to determine if this is a markdown file.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. For markdown files, applies nested markdown block logic to avoid premature termination.
* 3. For mixed content, uses simplified processing to avoid premature termination.
* 4. For traditional code blocks, uses original logic.
* 5. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(
rawLines: LineStream,
filepath?: string,
): LineStream {
// Collect all lines for analysis
const allLines = await collectAllLines(rawLines);
// Check if it has nested markdown blocks (like ```markdown or ```md)
const firstLine = allLines[0] || "";
const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath);
// TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks)
// But exclude cases where we have nested markdown blocks
const hasMarkdownHeaders = allLines.some(
(line) => line.trim().startsWith("#") && !line.trim().startsWith("```"),
);
const hasCodeBlocks = allLines.some(
(line) => line.trim().startsWith("```") && line.trim().length >= 3,
);
const isMixedContent =
hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown;
// If this is mixed content, use simplified processing
if (isMixedContent) {
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Skip initial wrapper lines if they exist
if (i === 0 && shouldRemoveLineBeforeStart(line)) {
continue;
}
yield line;
}
return;
}
// Original logic for non-mixed content
let seenFirstFence = false;
let nestCount = 0;
// Create optimized state tracker for markdown block analysis if needed
let markdownStateTracker: MarkdownBlockStateTracker | undefined;
if (hasNestedMarkdown) {
markdownStateTracker = new MarkdownBlockStateTracker(allLines);
}
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Process block nesting logic for the first fence
const nesting = processBlockNesting(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
if (nesting.shouldSkip) {
continue; // Filter out starting ``` or START block
}
if (!seenFirstFence && nesting.newSeenFirstFence) {
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
// For markdown files with nested markdown blocks, apply special logic
if (
hasNestedMarkdown &&
line.trim() === "```" &&
markdownStateTracker
) {
if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) {
return; // Stop without yielding the final closing ```
} else {
// This is an inner block delimiter, yield it as content
yield line;
continue;
}
}
// Original logic for non-markdown files or simple cases
nestCount--;
if (nestCount === 0) {
// We've closed the outer wrapper - stop without yielding the closing ```
return;
} else {
// This is a nested block closing, yield it as content
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// Otherwise just yield the line as content
yield line;
}
}
}
}
function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
line.trim() === "[CODE]" ||
line.trim() === "<COMPLETION>" ||
line.trim() === "<START EDITING HERE>" ||
line.trim() === "{{FILL_HERE}}"
);
}

View file

@ -0,0 +1,452 @@
// eslint-disable-next-line max-lines-per-function
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import * as lineStream from "./lineStream";
describe("filterCodeBlock", () => {
let mockFullStop: Mock;
async function getLineGenerator(lines: any) {
return (async function* () {
for (const line of lines) {
yield line;
}
})();
}
async function getFilteredLines(results: any) {
const output = [];
for await (const line of results) {
output.push(line);
}
return output;
}
beforeEach(() => {
mockFullStop = vi.fn();
});
it("should handle unfenced code", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should handle unfenced code with a complex code block", async () => {
const linesGenerator = await getLineGenerator([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
});
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator([
"```ts",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"echo ```test```",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"echo ```test```",
"```",
]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator([
"[CODE]",
"const x = 5;",
"```bash",
"ls -al",
"```",
"[/CODE]",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});

View file

@ -3,6 +3,11 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
export { filterCodeBlockLines } from "./filterCodeBlock";
export type LineFilter = (args: {
lines: LineStream;
fullStop: () => void;
@ -50,13 +55,72 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
);
}
function shouldChangeLineAndStop(line: string): string | undefined {
/**
* Shared utility for validating patterns in lines to avoid code duplication.
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
*/
export function validatePatternInLine(
line: string,
pattern: string,
): {
isValid: boolean;
patternIndex: number;
beforePattern: string;
} {
const patternIndex = line.indexOf(pattern);
if (patternIndex === -1) {
return { isValid: false, patternIndex: -1, beforePattern: "" };
}
// Check if pattern is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (patternIndex > 0) {
const charBefore = line[patternIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
return { isValid: false, patternIndex, beforePattern: "" };
}
}
// Check if pattern appears to be inside quotes
// Simple heuristic: count unmatched quotes before the pattern
const beforePattern = line.substring(0, patternIndex);
const singleQuotes = (beforePattern.match(/'/g) || []).length;
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
// If there's an odd number of quotes before pattern, we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return { isValid: false, patternIndex, beforePattern };
}
return { isValid: true, patternIndex, beforePattern };
}
export function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
}
// Check if [/CODE] appears in the line
if (line.includes(CODE_STOP_BLOCK)) {
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
if (!validation.isValid) {
return undefined;
}
// Get the trimmed line to check if [/CODE] is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(CODE_STOP_BLOCK)) {
// [/CODE] is at the logical start (after whitespace only)
if (trimmedLine === CODE_STOP_BLOCK) {
return line; // Return the whole line including leading whitespace
}
}
// [/CODE] appears after some content (separated by whitespace) - return part before
return validation.beforePattern.trimEnd();
}
return undefined;
@ -71,6 +135,32 @@ function isUselessLine(line: string): boolean {
return hasUselessLine || trimmed.startsWith("// end");
}
/**
* Determines if the code block has nested markdown blocks.
*/
export function hasNestedMarkdownBlocks(
firstLine: string,
filepath?: string,
): boolean {
return (
(firstLine.startsWith("```") &&
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
Boolean(filepath && isMarkdownFile(filepath))
);
}
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
export function processBlockNesting(
line: string,
seenFirstFence: boolean,
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
return processBlockNestingUtil(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
}
export const USELESS_LINES = [""];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
@ -138,7 +228,7 @@ export async function* avoidPathLine(
// Sometimes the model with copy this pattern, which is unwanted
for await (const line of stream) {
if (line.startsWith(`${comment} Path: `)) {
continue;
continue; // continue in the Continue codebase! How meta!
}
yield line;
}
@ -261,7 +351,40 @@ export async function* stopAtLines(
linesToStopAt: string[] = LINES_TO_STOP_AT,
): LineStream {
for await (const line of stream) {
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
let shouldStop = false;
// Check each stop phrase
for (const stopAt of linesToStopAt) {
if (line.includes(stopAt)) {
const validation = validatePatternInLine(line, stopAt);
if (!validation.isValid) {
continue;
}
// Get the trimmed line to check if stop phrase is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(stopAt)) {
// Stop phrase is at the logical start (after whitespace only) - should stop
shouldStop = true;
break;
} else {
// Stop phrase appears after some content - check if it's separated by whitespace
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
if (
contentBeforeStopPhrase.length < validation.beforePattern.length
) {
// There's whitespace before the stop phrase, so it's properly separated
shouldStop = true;
break;
}
// If no whitespace separation, it's part of larger text, so continue
}
}
}
if (shouldStop) {
fullStop();
break;
}
@ -329,64 +452,6 @@ export async function* removeTrailingWhitespace(
}
}
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. Filters out ending code block markers (```) unless they are the last line.
* 3. Handles special cases where lines should be changed and the stream should stop.
* 4. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let seenFirstFence = false;
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
let nestCount = 0;
for await (const line of rawLines) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
// Filter out starting ``` or START block
continue;
}
// Regardless of a fence or START block start tracking the nesting level
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
nestCount--;
if (nestCount === 0) {
// if we are closing the outer block then exit early
// only exit early if the outer block was started with a block
// it it was text, we will never exit early
return;
} else {
// otherwise just yield the line
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// otherwise just yield the line
yield line;
}
}
}
}
/**
* Filters out English explanations at the start of a code block.
*

View file

@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
import * as lineStream from "./lineStream";
// eslint-disable-next-line max-lines-per-function
@ -174,6 +179,93 @@ describe("lineStream", () => {
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should stop at lines with leading whitespace", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
` ${lineStream.LINES_TO_STOP_AT[0]}`,
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should NOT stop when stop phrase is inside quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
// Should not stop, should yield all lines
expect(filteredLines).toEqual([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is inside single quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is part of larger text", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should stop when stop phrase appears properly at start of content", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
"# End of file. Done here",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
describe("skipPrefixes", () => {
@ -301,6 +393,37 @@ describe("lineStream", () => {
]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
@ -395,6 +518,119 @@ describe("lineStream", () => {
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});
describe("filterEnglishLinesAtStart", () => {
@ -613,4 +849,453 @@ describe("lineStream", () => {
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
// Tests for new helper functions
describe("hasNestedMarkdownBlocks", () => {
it("should detect nested markdown blocks from first line", () => {
expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe(
true,
);
expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true);
expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe(
true,
);
});
it("should detect nested markdown blocks from filepath", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"),
).toBe(true);
});
it("should return false for non-markdown scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"),
).toBe(false);
expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe(
false,
);
expect(
lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined),
).toBe(false);
});
it("should handle complex first line scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined),
).toBe(true);
});
});
describe("collectAllLines", () => {
it("should collect all lines from a stream", async () => {
const linesGenerator = await getLineGenerator([
"line1",
"line2",
"line3",
]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["line1", "line2", "line3"]);
});
it("should handle empty stream", async () => {
const linesGenerator = await getLineGenerator([]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual([]);
});
it("should handle stream with empty lines", async () => {
const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["", "line2", "", "line4"]);
});
});
describe("shouldStopAtMarkdownBlock", () => {
it("should return false when current line is not closing backticks", () => {
const allLines = ["```markdown", "content", "more content"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
});
it("should handle simple nested markdown case", () => {
const allLines = ["```markdown", "# Title", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true);
});
it("should handle complex nested markdown with inner code blocks", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('hello');",
"```",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 4 (first inner closing), should not stop
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false);
// At index 5 (outer closing), should stop
expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true);
});
it("should handle multiple bare backticks scenario", () => {
const allLines = [
"```markdown",
"Content with ```inline code```",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 2, should not stop (not the last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
// At index 4, should stop (last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true);
});
});
describe("shouldChangeLineAndStop", () => {
it("should handle [/CODE] at start of line", () => {
const result = lineStream.shouldChangeLineAndStop("[/CODE]");
expect(result).toBe("[/CODE]");
});
it("should handle [/CODE] with leading whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(" [/CODE]");
expect(result).toBe(" [/CODE]");
});
it("should return partial line before [/CODE] when at start/after whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(
"some code [/CODE] more text",
);
expect(result).toBe("some code");
});
it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => {
// This test demonstrates the current bug - it WILL fail initially
const result = lineStream.shouldChangeLineAndStop(
'console.log("test [/CODE] end");',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should NOT trigger on [/CODE] in middle of identifier", () => {
// Another case that shows the bug
const result = lineStream.shouldChangeLineAndStop(
'const var[/CODE]Name = "test";',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should handle ``` with trimStart correctly", () => {
const result = lineStream.shouldChangeLineAndStop(" ```");
expect(result).toBe(" ```");
});
it("should NOT handle ``` in middle of line", () => {
const result = lineStream.shouldChangeLineAndStop(
'console.log("test ``` end");',
);
expect(result).toBeUndefined();
});
});
describe("MarkdownBlockState", () => {
it("should initialize with correct state", () => {
const allLines = ["```markdown", "content", "```", "more content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Test basic initialization - we can't directly test private properties,
// but we can test the behavior through shouldStopAtPosition
expect(state).toBeDefined();
});
it("should correctly identify bare backticks positions", () => {
const allLines = ["```markdown", "```", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// At position 1 (first bare backticks), should not stop
expect(state.shouldStopAtPosition(1)).toBe(false);
// At position 3 (last bare backticks), should stop
expect(state.shouldStopAtPosition(3)).toBe(true);
});
it("should maintain state across multiple calls", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('test');",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Process positions incrementally
expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block
expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block
expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block
});
it("should handle complex nesting scenarios efficiently", () => {
const allLines = [
"```markdown",
"# Documentation",
"```typescript",
"interface Config {",
" name: string;",
"}",
"```",
"",
"```bash",
"npm install",
"```",
"",
"Final notes",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Test multiple positions in sequence
expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block
expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block
expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block
});
it("should handle non-backtick lines correctly", () => {
const allLines = ["```markdown", "regular content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Position 1 is not backticks, should return false
expect(state.shouldStopAtPosition(1)).toBe(false);
});
it("should handle empty lines and edge cases", () => {
const allLines = ["```markdown", "", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line
expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks
});
it("should reset nest count when reaching final bare backticks", () => {
const allLines = ["```markdown", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// First call should stop and reset count
expect(state.shouldStopAtPosition(2)).toBe(true);
// If we had more content, it should start fresh
// (This tests the internal state management)
});
});
describe("shouldStopAtMarkdownBlock optimization", () => {
it("should maintain performance benefits with state reuse", () => {
const allLines = Array.from({ length: 100 }, (_, i) => {
if (i === 0) return "```markdown";
if (i === 99) return "```";
if (i % 10 === 0) return "```javascript";
if (i % 10 === 5) return "```";
return `line ${i}`;
});
const state = new MarkdownBlockStateTracker(allLines);
// Test that we can call multiple times without recomputing everything
const start = performance.now();
// Test several positions in sequence
for (let i = 10; i < 90; i += 10) {
if (allLines[i].trim() === "```") {
shouldStopAtMarkdownBlock(state, i);
}
}
const duration = performance.now() - start;
expect(duration).toBeLessThan(10); // Should be very fast due to state caching
});
});
describe("filterCodeBlockLines with optimized MarkdownBlockState", () => {
it("should use optimized state tracker for markdown files", async () => {
const linesGenerator = await getLineGenerator([
"```markdown",
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
]);
});
it("should fall back to legacy behavior when no markdown nesting detected", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"script.ts",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle mixed markdown and code scenarios with optimization", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
]);
});
});
describe("validatePatternInLine", () => {
it("should return false when pattern is not found", () => {
const result = lineStream.validatePatternInLine(
"const x = 5;",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(-1);
expect(result.beforePattern).toBe("");
});
it("should return false when pattern is preceded by non-whitespace", () => {
const result = lineStream.validatePatternInLine(
'const var[/CODE]Name = "test";',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(9);
});
it("should return false when pattern is inside double quotes", () => {
const result = lineStream.validatePatternInLine(
'console.log("test [/CODE] end");',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(18);
});
it("should return false when pattern is inside single quotes", () => {
const result = lineStream.validatePatternInLine(
"const message = 'test [/CODE] end';",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(22);
});
it("should return true when pattern is properly separated by whitespace", () => {
const result = lineStream.validatePatternInLine(
"some code [/CODE] more text",
"[/CODE]",
);
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(10);
expect(result.beforePattern).toBe("some code ");
});
it("should return true when pattern is at start of line", () => {
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(0);
expect(result.beforePattern).toBe("");
});
it("should return true when pattern has only whitespace before it", () => {
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(4);
expect(result.beforePattern).toBe(" ");
});
it("should handle complex quote scenarios correctly", () => {
// Unmatched quote should make it invalid
const result1 = lineStream.validatePatternInLine(
'const x = "unclosed quote [/CODE]',
"[/CODE]",
);
expect(result1.isValid).toBe(false);
// Matched quotes should make it valid
const result2 = lineStream.validatePatternInLine(
'const x = "closed"; [/CODE]',
"[/CODE]",
);
expect(result2.isValid).toBe(true);
});
it("should work with different patterns", () => {
const result1 = lineStream.validatePatternInLine(
"# End of file. Done",
"# End of file.",
);
expect(result1.isValid).toBe(true);
const result2 = lineStream.validatePatternInLine(" ```", "```");
expect(result2.isValid).toBe(true);
});
});
});

View file

@ -103,6 +103,16 @@ export function postprocessCompletion({
}
}
if (llm.model.includes("qwen3")) {
// Qwen3 always starts from special thinking markers, and we don't want them to output these contents
// Remove all content from "
completion = completion.replace(/<think>.*?<\/think>/s, "");
completion = completion.replace(/<\/think>/, "");
// Remove any number of newline characters at the beginning and end
completion = completion.replace(/^\n+|\n+$/g, "");
}
if (llm.model.includes("mercury") || llm.model.includes("granite")) {
// Granite tends to repeat the start of the line in the completion output
let prefixEnd = prefix.split("\n").pop();
@ -132,6 +142,14 @@ export function postprocessCompletion({
completion = "\n" + completion;
}
if (
(llm.model.includes("gemini") || llm.model.includes("gemma")) &&
completion.endsWith("<|file_separator|>")
) {
// "<|file_separator|>" is 18 characters long
completion = completion.slice(0, -18);
}
// If prefix ends with space and so does completion, then remove the space from completion
if (prefix.endsWith(" ") && completion.startsWith(" ")) {

View file

@ -11,6 +11,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "./types";
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
@ -24,6 +25,7 @@ export interface SnippetPayload {
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
staticSnippet: AutocompleteStaticSnippet[];
}
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@ -185,6 +187,7 @@ export const getAllSnippets = async ({
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
@ -196,6 +199,9 @@ export const getAllSnippets = async ({
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
racePromise(getClipboardSnippets(ide)),
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
helper.options.experimental_enableStaticContextualization
? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
: [],
]);
return {
@ -207,5 +213,55 @@ export const getAllSnippets = async ({
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};
export const getAllSnippetsWithoutRace = async ({
helper,
ide,
getDefinitionsFromLsp,
contextRetrievalService,
}: {
helper: HelperVars;
ide: IDE;
getDefinitionsFromLsp: GetLspDefinitionsFunction;
contextRetrievalService: ContextRetrievalService;
}): Promise<SnippetPayload> => {
const recentlyEditedRangeSnippets =
getSnippetsFromRecentlyEditedRanges(helper);
const [
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
contextRetrievalService.getRootPathSnippets(helper),
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
IDE_SNIPPETS_ENABLED
? getIdeSnippets(helper, ide, getDefinitionsFromLsp)
: [],
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
getClipboardSnippets(ide),
getSnippetsFromRecentlyOpenedFiles(helper, ide),
helper.options.experimental_enableStaticContextualization
? contextRetrievalService.getStaticContextSnippets(helper)
: [],
]);
return {
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
recentlyEditedRangeSnippets,
diffSnippets,
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};

View file

@ -2,6 +2,7 @@ export enum AutocompleteSnippetType {
Code = "code",
Diff = "diff",
Clipboard = "clipboard",
Static = "static",
}
interface BaseAutocompleteSnippet {
@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
copiedAt: string;
}
export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
type: AutocompleteSnippetType.Static;
filepath: string;
}
export type AutocompleteSnippet =
| AutocompleteCodeSnippet
| AutocompleteDiffSnippet
| AutocompleteClipboardSnippet;
| AutocompleteClipboardSnippet
| AutocompleteStaticSnippet;

View file

@ -4,6 +4,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
@ -32,9 +33,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
};
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteCodeSnippet[],
snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
caretWindow: string,
): AutocompleteCodeSnippet[] {
): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
return snippets.filter(
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
);
@ -52,7 +53,11 @@ export const getSnippets = (
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),
@ -107,7 +112,11 @@ export const getSnippets = (
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),

View file

@ -5,6 +5,7 @@ import {
AutocompleteDiffSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
@ -51,6 +52,12 @@ const formatDiffSnippet = (
return snippet;
};
const formatStaticSnippet = (
snippet: AutocompleteStaticSnippet,
): AutocompleteStaticSnippet => {
return snippet;
};
const commentifySnippet = (
helper: HelperVars,
snippet: AutocompleteSnippet,
@ -81,6 +88,8 @@ export const formatSnippets = (
return formatDiffSnippet(snippet);
case AutocompleteSnippetType.Clipboard:
return formatClipboardSnippet(snippet, workspaceDirs);
case AutocompleteSnippetType.Static:
return formatStaticSnippet(snippet);
}
})
.map((item) => {

View file

@ -105,24 +105,27 @@ export class AutocompleteLoggingService {
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
{
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);
const toLog = {
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
};
outcome.enabledStaticContextualization
? void Telemetry.capture("autocomplete", {
...toLog,
enabledStaticContextualization: true,
})
: void Telemetry.capture("autocomplete", toLog);
}
}

View file

@ -41,5 +41,6 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
gitRepo?: string;
completionId: string;
uniqueId: string;
timestamp: number;
timestamp: string;
enabledStaticContextualization?: boolean;
}

View file

@ -0,0 +1,399 @@
/**
* CodeRenderer is a class that, when given a code string,
* highlights the code string using shiki and
* returns a svg representation of it.
* We could technically just call shiki's methods to do a
* one-liner syntax highlighting code, but
* a separate class for this is useful because
* we rarely ever need syntax highlighting outside of
* creating a render of it.
*/
import {
transformerNotationDiff,
transformerNotationHighlight,
} from "@shikijs/transformers";
import { JSDOM } from "jsdom";
import {
BundledLanguage,
BundledTheme,
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { escapeForSVG, kebabOfStr } from "../util/text";
interface CodeRendererOptions {
themesDir?: string;
theme?: string;
}
interface HTMLOptions {
theme?: string;
customCSS?: string;
containerClass?: string;
}
interface ConversionOptions extends HTMLOptions {
transparent?: boolean;
imageType: "svg";
fontSize: number;
fontFamily: string;
dimensions: Dimensions;
lineHeight: number;
}
interface Dimensions {
width: number;
height: number;
}
type DataUri = PngUri | SvgUri;
type PngUri = string;
type SvgUri = string;
export class CodeRenderer {
private static instance: CodeRenderer;
private currentTheme: string = "dark-plus";
private editorBackground: string = "#000000";
private editorForeground: string = "#FFFFFF";
private editorLineHighlight: string = "#000000";
private highlighter: Highlighter | null = null;
private constructor() {}
static getInstance(): CodeRenderer {
if (!CodeRenderer.instance) {
CodeRenderer.instance = new CodeRenderer();
}
return CodeRenderer.instance;
}
public async setTheme(themeName: string): Promise<void> {
if (
this.themeExists(kebabOfStr(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";
} else {
this.currentTheme = "dark-plus";
}
}
async init(): Promise<void> {}
async close(): Promise<void> {}
themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
const themeArray: BundledTheme[] = [
"andromeeda",
"aurora-x",
"ayu-dark",
"catppuccin-frappe",
"catppuccin-latte",
"catppuccin-macchiato",
"catppuccin-mocha",
"dark-plus",
"dracula",
"dracula-soft",
"everforest-dark",
"everforest-light",
"github-dark",
"github-dark-default",
"github-dark-dimmed",
"github-dark-high-contrast",
"github-light",
"github-light-default",
"github-light-high-contrast",
"gruvbox-dark-hard",
"gruvbox-dark-medium",
"gruvbox-dark-soft",
"gruvbox-light-hard",
"gruvbox-light-medium",
"gruvbox-light-soft",
"houston",
"kanagawa-dragon",
"kanagawa-lotus",
"kanagawa-wave",
"laserwave",
"light-plus",
"material-theme",
"material-theme-darker",
"material-theme-lighter",
"material-theme-ocean",
"material-theme-palenight",
"min-dark",
"min-light",
"monokai",
"night-owl",
"nord",
"one-dark-pro",
"one-light",
"plastic",
"poimandres",
"red",
"rose-pine",
"rose-pine-dawn",
"rose-pine-moon",
"slack-dark",
"slack-ochin",
"snazzy-light",
"solarized-dark",
"solarized-light",
"synthwave-84",
"tokyo-night",
"vesper",
"vitesse-black",
"vitesse-dark",
"vitesse-light",
];
return themeArray.includes(themeNameKebab as BundledTheme);
}
async highlightCode(
code: string,
language: string = "javascript",
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<string> {
const lines = code.split("\n");
const newDiffLineMap = new Set();
if (newDiffLines) {
newDiffLines.forEach((diffLine) => {
if (diffLine.type === "new") {
newDiffLineMap.add(diffLine.line);
}
});
}
const annotatedLines = [];
// NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
// If you are transforming an empty line, make sure that
// the transformation is applied to a non-empty line first.
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Add highlight comment before target line.
if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
annotatedLines.push("// [!code highlight:1]");
}
// Handle diff lines
if (newDiffLineMap.has(line)) {
if (line.trim() === "") {
// For empty lines, add the magic comment on a separate line before.
annotatedLines.push("// [!code ++]");
annotatedLines.push(line); // The empty line itself.
} else {
// For non-empty lines, append the magic comment.
annotatedLines.push(line + "// [!code ++]");
}
newDiffLineMap.delete(line);
} else {
annotatedLines.push(line);
}
}
const annotatedCode = annotatedLines.join("\n");
await this.highlighter!.loadLanguage(language as BundledLanguage);
return this.highlighter!.codeToHtml(annotatedCode, {
lang: language,
theme: this.currentTheme,
transformers: [transformerNotationHighlight(), transformerNotationDiff()],
});
}
async convertToSVG(
code: string,
language: string = "javascript",
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
code,
language,
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
options,
);
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">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</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" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
convertShikiHtmlToSvgGut(
shikiHtml: string,
options: ConversionOptions,
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
if (node.nodeType === 3) {
return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
}
const el = node as HTMLElement;
const style = el.getAttribute("style") || "";
const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
const classes = el.getAttribute("class") || "";
let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
if (classes.includes("highlighted")) {
fill = ` fill="${this.editorLineHighlight}"`;
}
const content = el.textContent || "";
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
})
.join("");
// Typography notes:
// Each line of code is a <text> inside a <rect>.
// Math becomes interesting here; the y value is actually aligned to the topmost border.
// So y = 0 will have the rect be flush with the top border.
// More importantly, text will also be positioned that way.
// Since y = 0 is the axis the text will align itself to, the default settings will actually have the text sitting "on top of" the y = 0 axis, which effectively shifts them up.
// To prevent this, we want the alignment axis to be at the middle of each rect, and have the text align itself vertically to the center (skwered by the axis).
// The first step is to add lineHeight / 2 to move the axis down.
// The second step is to add 'dominant-baseline="central"' to vertically center the text.
// Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
const y = index * options.lineHeight + options.lineHeight / 2;
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const radius = 10;
// 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}" />`
: 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}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");
return {
guts: svgLines.join("\n"),
lineBackgrounds,
};
}
getBackgroundColor(shikiHtml: string): string {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const preElement = document.querySelector("pre");
let backgroundColor = "#333333"; // Default white background
if (preElement) {
const style = preElement.getAttribute("style") || "";
const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
if (bgColorMatch) {
backgroundColor = bgColorMatch[1];
}
}
return backgroundColor;
}
async getDataUri(
code: string,
language: string = "javascript",
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
// const pngBuffer = await this.convertToPNG(
// code,
// language,
// fontSize,
// dimensions,
// lineHeight,
// options,
// );
// return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
case "svg":
const svgBuffer = await this.convertToSVG(
code,
language,
options,
currLineOffsetFromTop,
newDiffLines,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}
}
}

View file

@ -11,5 +11,6 @@ export function convertCustomCommandToSlashCommand(
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
};
}

View file

@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand(
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
promptFile: prompt.sourceFile, // Align with the sourceFile property
};
}

View file

@ -11,12 +11,14 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
import EventEmitter from "node:events";
import {
AuthType,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import { Telemetry } from "../util/posthog.js";
import {
ASSISTANTS,
getAllDotContinueDefinitionFiles,
@ -44,6 +46,16 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
totalConfigLoads: number = 0;
public isInitialized: Promise<void>;
private initter: EventEmitter;
cascadeAbortController: AbortController;
private abortCascade() {
this.cascadeAbortController.abort();
this.cascadeAbortController = new AbortController();
}
constructor(
private readonly ide: IDE,
@ -53,9 +65,11 @@ export class ConfigHandler {
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
this.ide.getIdeInfo(),
);
// This profile manager will always be available
@ -80,7 +94,13 @@ export class ConfigHandler {
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
void this.cascadeInit();
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
this.initter.on("init", resolve);
});
this.cascadeAbortController = new AbortController();
void this.cascadeInit("Config handler initialization");
}
private workspaceDirs: string[] | null = null;
@ -96,54 +116,71 @@ export class ConfigHandler {
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit() {
private async cascadeInit(reason: string) {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
const orgs = await this.getOrgs();
try {
const orgs = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
}
this.initter.emit("init");
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig(reason);
} catch (e) {
if (e instanceof Error && e.message.includes("AbortError")) {
return;
} else {
this.initter.emit("init"); // Error case counts for initialization
throw e;
}
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig();
}
private async getOrgs(): Promise<OrgWithProfiles[]> {
if (await this.controlPlaneClient.isSignedIn()) {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
return orgs;
} else {
return [await this.getLocalOrg()];
}
@ -312,13 +349,14 @@ export class ConfigHandler {
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit();
await this.cascadeInit("External refresh all");
}
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("IDE settings update");
}
// Session change: refresh session and cascade refresh from the top
@ -328,8 +366,10 @@ export class ConfigHandler {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
this.ide.getIdeInfo(),
);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("Control plane session info update");
}
// Org id: check id validity, save selection, switch and reload
@ -356,7 +396,7 @@ export class ConfigHandler {
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig();
await this.reloadConfig("Selected org changed");
}
}
@ -384,18 +424,21 @@ export class ConfigHandler {
});
this.currentProfile = profile;
await this.reloadConfig();
await this.reloadConfig("Selected profile changed");
}
// Bottom level of cascade: refresh the current profile
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig() {
async reloadConfig(reason: string) {
const startTime = performance.now();
this.totalConfigLoads += 1;
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
@ -415,6 +458,17 @@ export class ConfigHandler {
await this.currentProfile.reloadConfig(this.additionalContextProviders);
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
duration,
reason,
totalConfigLoads: this.totalConfigLoads,
configLoadInterrupted,
});
return { config, errors, configLoadInterrupted };
}
@ -440,7 +494,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
@ -453,10 +507,11 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
await this.isInitialized;
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -467,7 +522,10 @@ export class ConfigHandler {
return config;
}
async openConfigProfile(profileId?: string) {
async openConfigProfile(
profileId?: string,
element?: { sourceFile?: string },
) {
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
if (!openProfileId) {
return;
@ -475,8 +533,10 @@ export class ConfigHandler {
const profile = this.currentOrg.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
await this.ide.openFile(profile.profileDescription.uri);
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
@ -487,7 +547,7 @@ export class ConfigHandler {
private additionalContextProviders: IContextProvider[] = [];
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig();
void this.reloadConfig("Custom context provider registered");
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".

View file

@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { testConfigHandler } from "../test/fixtures";
import { TEST_DIR } from "../test/testDir";
import { getConfigTsPath } from "../util/paths";
@ -24,14 +25,14 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
);
});
test.skip("should add a system message from config.ts", async () => {
test("should add a system message from config.ts", async () => {
const configTs = `export function modifyConfig(config: Config): Config {
config.systemMessage = "SYSTEM";
return config;
}`;
fs.writeFileSync(getConfigTsPath(), configTs);
await new Promise((resolve) => setTimeout(resolve, 1000));
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/
@ -39,12 +40,12 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
expect(config.systemMessage).toBe("SYSTEM");
});
test.skip("should acknowledge override from .continuerc.json", async () => {
test("should acknowledge override from .continuerc.json", async () => {
fs.writeFileSync(
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),
);
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/

View file

@ -36,7 +36,6 @@ import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/b
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
@ -63,7 +62,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { getToolsForIde } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
@ -398,13 +397,7 @@ async function intermediateToFinalConfig({
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
];
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
@ -532,7 +525,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: [...baseToolDefinitions],
tools: await getToolsForIde(ide),
mcpServerStatuses: [],
slashCommands: [],
modelsByRole: {
@ -650,6 +643,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
template: llm.template,
completionOptions: llm.completionOptions,
baseAgentSystemMessage: llm.baseAgentSystemMessage,
basePlanSystemMessage: llm.basePlanSystemMessage,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
@ -657,6 +651,8 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
sourceFile: llm.sourceFile,
};
}

View file

@ -1,3 +1,4 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { walkDirCache } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";

View file

@ -7,6 +7,43 @@ import { walkDirs } from "../../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
import { getUriPathBasename } from "../../util/uri";
export class CodebaseRulesCache {
private static instance: CodebaseRulesCache | null = null;
private constructor() {}
public static getInstance(): CodebaseRulesCache {
if (CodebaseRulesCache.instance === null) {
CodebaseRulesCache.instance = new CodebaseRulesCache();
}
return CodebaseRulesCache.instance;
}
rules: RuleWithSource[] = [];
errors: ConfigValidationError[] = [];
async refresh(ide: IDE) {
const { rules, errors } = await loadCodebaseRules(ide);
this.rules = rules;
this.errors = errors;
}
async update(ide: IDE, uri: string) {
const content = await ide.readFile(uri);
const rule = markdownToRule(content, { uriType: "file", filePath: uri });
const ruleWithSource: RuleWithSource = {
...rule,
source: "colocated-markdown",
ruleFile: uri,
};
const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
if (matchIdx === -1) {
this.rules.push(ruleWithSource);
} else {
this.rules[matchIdx] = ruleWithSource;
}
}
remove(uri: string) {
this.rules = this.rules.filter((r) => r.ruleFile !== uri);
}
}
/**
* Loads rules from rules.md files colocated in the codebase
*/
@ -33,7 +70,11 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
const content = await ide.readFile(filePath);
const rule = markdownToRule(content, { uriType: "file", filePath });
rules.push({ ...rule, source: "rules-block" });
rules.push({
...rule,
source: "colocated-markdown",
ruleFile: filePath,
});
} catch (e) {
errors.push({
fatal: false,

View file

@ -45,27 +45,27 @@ describe("loadCodebaseRules", () => {
"src/rules.md": {
name: "General Rules",
rule: "Follow coding standards",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/rules.md",
},
"src/redux/rules.md": {
name: "Redux Rules",
rule: "Use Redux Toolkit",
globs: "**/*.{ts,tsx}",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
},
"src/components/rules.md": {
name: "Component Rules",
rule: "Use functional components",
globs: ["**/*.tsx", "**/*.jsx"],
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
},
".continue/rules.md": {
name: "Global Rules",
rule: "Follow project guidelines",
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
};

View file

@ -33,7 +33,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
uriType: "file",
filePath: file.path,
});
rules.push({ ...rule, source: "rules-block" });
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
} catch (e) {
errors.push({
fatal: false,

View file

@ -16,7 +16,7 @@ describe("Rule Colocation Application", () => {
{
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
@ -24,7 +24,7 @@ describe("Rule Colocation Application", () => {
{
name: "React Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
// No explicit globs - should implicitly only apply to files in that directory
},
@ -34,7 +34,7 @@ describe("Rule Colocation Application", () => {
name: "Redux Rule",
rule: "Use Redux Toolkit for state management",
globs: "src/redux/**/*.{ts,tsx}",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
},
@ -43,7 +43,7 @@ describe("Rule Colocation Application", () => {
name: "TypeScript Components Rule",
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
},
@ -52,7 +52,7 @@ describe("Rule Colocation Application", () => {
name: "API Utils Rule",
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
},
];
@ -183,7 +183,7 @@ describe("Rule Colocation Application", () => {
const impliedComponentRule: RuleWithSource = {
name: "Implied Components Rule",
rule: "Use React component best practices",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
// No explicit globs - should infer from directory
};
@ -233,7 +233,7 @@ describe("Rule Colocation Application", () => {
name: "TypeScript Component Rule",
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
};
@ -280,7 +280,7 @@ describe("Rule Colocation Application", () => {
name: "API Utils Rule",
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
};
@ -323,7 +323,7 @@ describe("Rule Colocation Application", () => {
return {
name: `Inferred Rule for ${directory}`,
rule: `Follow standards for ${directory}`,
source: "rules-block",
source: "colocated-markdown",
ruleFile: ruleFilePath,
// In a fixed implementation, these globs would be automatically inferred
// globs: expectedGlob,

View file

@ -20,6 +20,7 @@ import {
Tool,
} from "../../";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
@ -36,7 +37,7 @@ import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
import { CodebaseRulesCache } from "../markdown/loadCodebaseRules";
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
@ -152,11 +153,21 @@ export default async function doLoadConfig(options: {
newConfig.rules.unshift(...rules);
newConfig.contextProviders.push(new RulesContextProvider({}));
// Add current file as context if setting is enabled
if (
newConfig.experimental?.useCurrentFileAsContext === true &&
!newConfig.contextProviders.find(
(c) =>
c.description.title === CurrentFileContextProvider.description.title,
)
) {
newConfig.contextProviders.push(new CurrentFileContextProvider({}));
}
// Add rules from colocated rules.md files in the codebase
const { rules: codebaseRules, errors: codebaseRulesErrors } =
await loadCodebaseRules(ide);
newConfig.rules.unshift(...codebaseRules);
errors.push(...codebaseRulesErrors);
const codebaseRulesCache = CodebaseRulesCache.getInstance();
newConfig.rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -230,6 +241,8 @@ export default async function doLoadConfig(options: {
newConfig.tools.push(
...getConfigDependentToolDefinitions({
rules: newConfig.rules,
enableExperimentalTools:
newConfig.experimental?.enableExperimentalTools ?? false,
}),
);

View file

@ -19,6 +19,10 @@ export const sharedConfigSchema = z
readResponseTTS: z.boolean(),
promptPath: z.string(),
useCurrentFileAsContext: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
enableStaticContextualization: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -157,6 +161,12 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental = {
...configCopy.experimental,
};
if (sharedConfig.enableExperimentalTools !== undefined) {
configCopy.experimental.enableExperimentalTools =
sharedConfig.enableExperimentalTools;
}
if (sharedConfig.promptPath !== undefined) {
configCopy.experimental.promptPath = sharedConfig.promptPath;
}
@ -171,6 +181,18 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.useCurrentFileAsContext =
sharedConfig.useCurrentFileAsContext;
}
if (sharedConfig.optInNextEditFeature !== undefined) {
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;
}
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
if (sharedConfig.enableStaticContextualization !== undefined) {
configCopy.experimental.enableStaticContextualization =
sharedConfig.enableStaticContextualization;
}
return configCopy;
}

View file

@ -1004,6 +1004,8 @@ declare global {
type: "stdio";
command: string;
args: string[];
env?: Record<string, string>;
cwd?: string;
}
interface WebSocketOptions {
@ -1055,6 +1057,7 @@ declare global {
numDiffs?: number;
filepath?: string;
fileContent?: string;
originalFileContent?: string;
}
export interface RangeInFileWithContents {

View file

@ -1,344 +0,0 @@
import { jest } from "@jest/globals";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = jest.fn();
// Mock the module
jest.unstable_mockModule("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
// Import after mocking
const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
const { SecretType } = await import("@continuedev/config-yaml");
beforeEach(() => {
mockDecodeSecretLocation.mockReset();
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,348 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = vi.fn();
// Mock the module
vi.mock("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesFreeTrialApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});
});

View file

@ -10,7 +10,7 @@ import {
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import { PromptTemplate } from "..";
import { serializePromptTemplates } from "./util";

View file

@ -1,5 +1,5 @@
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { describe, expect, test } from "vitest";
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
describe("getFileContent", () => {

View file

@ -26,7 +26,6 @@ import {
RuleWithSource,
} from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
@ -57,6 +56,8 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
ruleFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
};
}
}
@ -70,6 +71,7 @@ function convertYamlMcpToContinueMcp(
command: server.command,
args: server.args ?? [],
env: server.env,
cwd: server.cwd,
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};
@ -235,6 +237,8 @@ async function configYamlToContinueConfig(options: {
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
useLocalCrawling: doc.useLocalCrawling,
sourceFile: doc.sourceFile,
}));
config.mcpServers?.forEach((mcpServer) => {
@ -385,13 +389,7 @@ async function configYamlToContinueConfig(options: {
}
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
{};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
];
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
@ -433,6 +431,7 @@ async function configYamlToContinueConfig(options: {
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],

View file

@ -0,0 +1,128 @@
import { describe, it, expect } from "vitest";
import {
validateConfigYaml,
AssistantUnrolledNonNullable,
} from "@continuedev/config-yaml";
describe("MCP Server cwd configuration", () => {
describe("YAML schema validation", () => {
it("should accept valid MCP server with cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "node",
args: ["server.js"],
env: { NODE_ENV: "production" },
cwd: "/path/to/project",
connectionTimeout: 5000,
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept MCP server without cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "python",
args: ["-m", "server"],
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept relative paths in cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "cargo",
args: ["run"],
cwd: "./rust-project",
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept empty string cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "deno",
args: ["run", "server.ts"],
cwd: "",
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
});
describe("MCP server configuration examples", () => {
it("should support common MCP server patterns with cwd", () => {
const configs = [
{
name: "Local project MCP server",
server: {
name: "project-mcp",
command: "npm",
args: ["run", "mcp-server"],
cwd: "/Users/developer/my-project",
},
},
{
name: "Python MCP with virtual environment",
server: {
name: "python-mcp",
command: "python",
args: ["-m", "my_mcp_server"],
env: { PYTHONPATH: "./src" },
cwd: "/home/user/python-project",
},
},
{
name: "Relative path MCP server",
server: {
name: "relative-mcp",
command: "node",
args: ["index.js"],
cwd: "../mcp-servers/filesystem",
},
},
];
configs.forEach(({ name, server }) => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [server],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
});
});
});

View file

@ -63,6 +63,7 @@ async function modelConfigToBaseLLM({
template: model.promptTemplates?.chat,
promptTemplates: model.promptTemplates,
baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
basePlanSystemMessage: model.chatOptions?.basePlanSystemMessage,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
@ -126,6 +127,12 @@ async function modelConfigToBaseLLM({
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("accessKeyId" in env && typeof env.accessKeyId === "string") {
options.accessKeyId = env.accessKeyId;
}
if ("secretAccessKey" in env && typeof env.secretAccessKey === "string") {
options.secretAccessKey = env.secretAccessKey;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}

View file

@ -47,7 +47,8 @@ class MCPConnection {
};
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
// Don't construct transport in constructor to avoid blocking
this.transport = {} as Transport; // Will be set in connectClient
this.client = new Client(
{
@ -132,7 +133,8 @@ class MCPConnection {
});
}),
(async () => {
this.transport = this.constructTransport(this.options);
this.transport = await this.constructTransportAsync(this.options);
try {
await this.client.connect(this.transport);
} catch (error) {
@ -295,7 +297,9 @@ class MCPConnection {
};
}
private constructTransport(options: MCPOptions): Transport {
private async constructTransportAsync(
options: MCPOptions,
): Promise<Transport> {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
@ -309,7 +313,7 @@ class MCPConnection {
// For non-Windows platforms, try to get the PATH from user shell
if (process.platform !== "win32") {
try {
const shellEnvPath = getEnvPathFromUserShell();
const shellEnvPath = await getEnvPathFromUserShell();
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
env.PATH = shellEnvPath;
}
@ -329,6 +333,7 @@ class MCPConnection {
command,
args,
env,
cwd: options.transport.cwd,
stderr: "pipe",
});

View file

@ -1,10 +1,18 @@
import { jest } from "@jest/globals";
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", () => ({
getEnvPathFromUserShell: vi
.fn()
.mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
}));
describe("MCPConnection", () => {
beforeEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("constructor", () => {
@ -25,6 +33,27 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("not-connected");
});
it("should create instance with stdio transport including cwd", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
cwd: "/path/to/working/directory",
},
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
if (conn.options.transport.type === "stdio") {
expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
}
});
it("should create instance with websocket transport", () => {
const options = {
name: "test-mcp",
@ -76,7 +105,7 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("not-connected");
});
it("should throw on invalid transport type", () => {
it("should throw on invalid transport type", async () => {
const options = {
name: "test-mcp",
id: "test-id",
@ -85,9 +114,14 @@ describe("MCPConnection", () => {
} as any,
};
expect(() => new MCPConnection(options)).toThrow(
"Unsupported transport type: invalid",
);
const conn = new MCPConnection(options);
const abortController = new AbortController();
// The validation now happens during connectClient, not constructor
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
});
});
@ -131,10 +165,10 @@ describe("MCPConnection", () => {
it("should connect successfully", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockResolvedValue(undefined);
const mockGetServerCapabilities = jest
const mockGetServerCapabilities = vi
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
@ -142,12 +176,12 @@ describe("MCPConnection", () => {
prompts: {},
});
const mockListResources = jest
const mockListResources = vi
.spyOn(Client.prototype, "listResources")
.mockResolvedValue({
resources: [{ name: "test-resource", uri: "test-uri" }],
});
const mockListTools = jest
const mockListTools = vi
.spyOn(Client.prototype, "listTools")
.mockResolvedValue({
tools: [
@ -159,7 +193,7 @@ describe("MCPConnection", () => {
},
],
});
const mockListPrompts = jest
const mockListPrompts = vi
.spyOn(Client.prototype, "listPrompts")
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
@ -175,12 +209,21 @@ describe("MCPConnection", () => {
it("should handle custom connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1500 });
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 1000)),
);
// Mock the required methods for successful connection
const mockGetServerCapabilities = vi
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
tools: {},
prompts: {},
});
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
@ -189,8 +232,8 @@ describe("MCPConnection", () => {
});
it("should handle connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1 });
const mockConnect = jest
const conn = new MCPConnection({ ...options, timeout: 50 });
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100)),
@ -201,14 +244,16 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain("Failed to connect");
expect(mockConnect).toHaveBeenCalled();
// The connection should timeout before connect is called due to transport construction
// Since transport construction happens first, and we're not mocking that,
// the timeout will happen during transport construction or connect attempt
});
it("should handle already connected state", async () => {
const conn = new MCPConnection(options);
conn.status = "connected";
const mockConnect = jest.spyOn(Client.prototype, "connect");
const mockConnect = vi.spyOn(Client.prototype, "connect");
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
@ -219,7 +264,7 @@ describe("MCPConnection", () => {
it("should handle transport errors", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
@ -233,7 +278,7 @@ describe("MCPConnection", () => {
it.skip("should include stderr output in error message when stdio command fails", async () => {
// Clear any existing mocks to ensure we get real behavior
jest.restoreAllMocks();
vi.restoreAllMocks();
// Use a command that will definitely fail and produce stderr output
const failingOptions = {

View file

@ -1,3 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MCPOptions } from "../..";
import MCPConnection from "./MCPConnection";
import { MCPManagerSingleton } from "./MCPManagerSingleton";
@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection {
} as any;
this.abortController = new AbortController();
this.connectClient = jest.fn().mockResolvedValue(undefined);
this.getStatus = jest
this.connectClient = vi.fn().mockResolvedValue(undefined);
this.getStatus = vi
.fn()
.mockReturnValue({ status: "connected", errors: [] });
}
@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => {
id: string,
options: MCPOptions,
): MCPConnection {
if (!this.connections.has(id)) {
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
if (this.connections.has(id)) {
return this.connections.get(id)!;
}
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
};
});
@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const closeSpy = jest.spyOn(connection.client, "close");
const closeSpy = vi.spyOn(connection.client, "close");
await manager.removeConnection("test-id");
@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const abortSpy = jest.spyOn(connection.abortController, "abort");
const closeSpy = jest.spyOn(connection.client, "close");
const abortSpy = vi.spyOn(connection.abortController, "abort");
const closeSpy = vi.spyOn(connection.client, "close");
// Remove it by setting empty server list
manager.setConnections([], false);
@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => {
});
it("should call onConnectionsRefreshed if defined", async () => {
const mockCallback = jest.fn();
const mockCallback = vi.fn();
manager.onConnectionsRefreshed = mockCallback;
manager.createConnection("test-id", testOptions);
@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => {
testOptions,
) as TestMCPConnection;
const mockStatus = { status: "connected", errors: [] };
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
connection.getStatus = vi.fn().mockReturnValue(mockStatus);
const statuses = manager.getStatuses();
expect(statuses).toHaveLength(1);

View file

@ -145,6 +145,11 @@ class DocsContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const { config } = args;
// This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
const configDocsSet = new Set(
config.docs?.map((doc) => doc.startUrl) || [],
);
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
@ -159,12 +164,14 @@ class DocsContextProvider extends BaseContextProvider {
// Get all indexed docs from the database
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
if (configDocsSet.has(startUrl)) {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
}
// Sort alphabetically

View file

@ -72,6 +72,10 @@ class HttpContextProvider extends BaseContextProvider {
description: item.description ?? "HTTP Context Item",
content: item.content ?? "",
name: item.name ?? this.options.title ?? "HTTP",
uri: {
type: item.uri.type,
value: item.uri.value,
},
});
return Array.isArray(json)

View file

@ -1,5 +1,6 @@
import fetch from "node-fetch";
import { afterAll, describe, expect, test } from "vitest";
import { contextProviderClassFromName } from ".";
import {
ContextProviderExtras,
@ -8,7 +9,7 @@ import {
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { LLMLogger } from "../../llm/logger";
import { TEST_DIR } from "../../test/testDir";
import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
async function getContextProviderExtras(
fullInput: string,
): Promise<ContextProviderExtras> {
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
@ -48,10 +50,15 @@ async function getContextProviderExtras(
llm: config.modelsByRole.chat[0],
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
isInAgentMode: true,
};
}
describe.skip("Should successfully run all context providers", () => {
afterAll(() => {
tearDownTestDir();
});
const extrasPromise = getContextProviderExtras("Test");
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {

View file

@ -1,7 +1,9 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import { Telemetry } from "../../util/posthog";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
@ -56,6 +58,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
JiraIssuesContextProvider,
PostgresContextProvider,
DatabaseContextProvider,
CodebaseContextProvider,
CodeContextProvider,
CurrentFileContextProvider,
URLContextProvider,
@ -73,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [
export function contextProviderClassFromName(
name: ContextProviderName,
): typeof BaseContextProvider | undefined {
return Providers.find((cls) => cls.description.title === name);
const provider = Providers.find((cls) => cls.description.title === name);
void Telemetry.capture("context_provider_load", {
providerName: name,
found: !!provider, // also capture those which user expected to be present
});
return provider;
}

View file

@ -1,14 +1,40 @@
// @ts-ignore
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import {
BranchAndDir,
Chunk,
ContextItem,
ContinueConfig,
IDE,
ILLM,
Tool,
ToolExtras,
} from "../../../";
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { BuiltInToolNames } from "../../../tools/builtIn";
import { callBuiltInTool } from "../../../tools/callTool";
import { globSearchTool } from "../../../tools/definitions/globSearch";
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
import { lsTool } from "../../../tools/definitions/ls";
import { readFileTool } from "../../../tools/definitions/readFile";
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
const DEFAULT_CHUNK_SIZE = 384;
const AVAILABLE_TOOLS: Tool[] = [
globSearchTool,
grepSearchTool,
lsTool,
readFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
];
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -34,12 +60,13 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex | null = null;
private lanceDbInitPromise: Promise<void> | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
void this.initLanceDb();
}
private async initLanceDb() {
protected async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
@ -51,6 +78,23 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
protected async ensureLanceDbInitialized(): Promise<boolean> {
if (this.lanceDbIndex) {
return true;
}
if (this.lanceDbInitPromise) {
await this.lanceDbInitPromise;
return this.lanceDbIndex !== null;
}
this.lanceDbInitPromise = this.initLanceDb();
await this.lanceDbInitPromise;
this.lanceDbInitPromise = null; // clear after init
return this.lanceDbIndex !== null;
}
private getCleanedTrigrams(
query: RetrievalPipelineRunArguments["query"],
): string[] {
@ -137,7 +181,9 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
const initialized = await this.ensureLanceDbInitialized();
if (!initialized || !this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);
@ -155,4 +201,107 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
throw new Error("Not implemented");
}
protected async retrieveWithTools(input: string): Promise<Chunk[]> {
const toolSelectionPrompt = `Given the following user input: "${input}"
Available tools:
${AVAILABLE_TOOLS.map((tool) => {
const requiredParams = tool.function.parameters?.required || [];
const properties = tool.function.parameters?.properties || {};
const paramDescriptions = requiredParams
.map(
(param: any) => `${param}: ${properties[param]?.description || "string"}`,
)
.join(", ");
return `- ${tool.function.name}: ${tool.function.description}
Required arguments: ${paramDescriptions || "none"}`;
}).join("\n")}
Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
{
"tools": [
{
"name": "<tool_name>",
"args": { "<required_parameter_name>": "<required_parameter_value>" }
}
]
}`;
// Get LLM response for tool selection
const toolSelectionResponse = await this.options.llm.chat(
[{ role: "user", content: toolSelectionPrompt }],
new AbortController().signal,
);
let toolCalls: { name: string; args: any }[] = [];
try {
const responseContent =
typeof toolSelectionResponse.content === "string"
? toolSelectionResponse.content
: toolSelectionResponse.content
.map((part) => (part.type === "text" ? part.text : ""))
.join("");
const parsed = JSON.parse(responseContent);
toolCalls = parsed.tools || [];
} catch (e) {
console.log(
`Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`,
e,
);
return [];
}
// Execute tools and collect results
const allContextItems: ContextItem[] = [];
const toolExtras: ToolExtras = {
ide: this.options.ide,
llm: this.options.llm,
fetch: fetch,
tool: grepSearchTool,
config: this.options.config,
};
for (const toolCall of toolCalls) {
const tool = AVAILABLE_TOOLS.find(
(t) => t.function.name === toolCall.name,
)!;
const args = toolCall.args;
if (toolCall.name === BuiltInToolNames.GrepSearch) {
args.splitByFile = true;
}
toolExtras.tool = tool;
const contextItems = await callBuiltInTool(
toolCall.name,
args,
toolExtras,
);
allContextItems.push(...contextItems);
}
const chunks: Chunk[] = [];
// Transform ContextItem[] to Chunk[]
for (let i = 0; i < allContextItems.length; i++) {
const contextItem = allContextItems[i];
const filepath = contextItem.uri?.value || contextItem.name || "unknown";
const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
chunks.push({
content: contextItem.content,
startLine: -1,
endLine: -1,
digest: `file:///${cleanedFilepath}`,
filepath: `file:///${cleanedFilepath}`,
index: i,
});
}
console.log("retrieveWithTools chunks", chunks);
return chunks;
}
}

View file

@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (this.options.config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen

View file

@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
@ -107,15 +117,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(-this.options.nFinal);
return results;
} catch (e) {
void this.options.ide.showToast(
"warning",
`Failed to rerank retrieval results\n${e}`,
);
console.warn(`Failed to rerank retrieval results\n${e}`);
return chunks.slice(-this.options.nFinal);
}
}

View file

@ -79,14 +79,19 @@ export async function retrieveContextItemsFromEmbeddings(
if (results.length === 0) {
if (extras.config.disableIndexing) {
void extras.ide.showToast("warning", "No results found.");
return [];
} else {
void extras.ide.showToast(
"warning",
"No results found. If you think this is an error, re-index your codebase.",
"No results found (Indexing disabled).",
);
// TODO - add "re-index" option to warning message which clears and reindexes codebase
return [];
}
if (extras.isInAgentMode) {
return [
{
...INSTRUCTIONS_BASE_ITEM,
content: "No results were found. Try using other tools.",
},
];
}
return [];
}
@ -108,7 +113,11 @@ export async function retrieveContextItemsFromEmbeddings(
}
return {
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
// Don't show line numbers for tool calls where startLine = -1
name:
r.startLine === -1
? baseName
: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
uri: {

View file

@ -1,6 +1,6 @@
// Generated by Continue
import { describe, expect, it } from "vitest";
import { Chunk } from "../../index";
import { deduplicateChunks } from "./util";
describe("deduplicateChunks", () => {

View file

@ -10,7 +10,7 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
@ -40,6 +40,7 @@ export class ControlPlaneClient {
ControlPlaneSessionInfo | undefined
>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
private readonly ideInfoPromise: Promise<IdeInfo>,
) {}
async resolveFQSNs(
@ -86,11 +87,17 @@ export class ControlPlaneClient {
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ideInfoPromise;
const resp = await fetch(url, {
...init,
headers: {
...init.headers,
Authorization: `Bearer ${accessToken}`,
...{
"x-extension-version": ideInfo.extensionVersion,
"x-is-prerelease": String(ideInfo.isPrerelease),
},
},
});

View file

@ -132,7 +132,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
try {
// Use REG QUERY command to read registry values
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {
@ -145,7 +148,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
try {
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {

View file

@ -10,9 +10,7 @@ import {
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
@ -21,10 +19,12 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
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";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
@ -38,13 +38,14 @@ import { TTS } from "./util/tts";
import {
CompleteOnboardingPayload,
ContextItemId,
ContextItemWithId,
IdeSettings,
ModelDescription,
Position,
RangeInFile,
ToolCall,
type ContextItem,
type ContextItemId,
type IDE,
} from ".";
@ -52,6 +53,7 @@ import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
import {
setupLocalConfig,
setupProviderConfig,
@ -67,6 +69,9 @@ import { walkDirCache } from "./indexing/walkDir";
import { LLMLogger } from "./llm/logger";
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 { NextEditProvider } from "./nextEdit/NextEditProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
@ -86,6 +91,7 @@ export class Core {
configHandler: ConfigHandler;
codeBaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
nextEditProvider: NextEditProvider;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
@ -148,7 +154,7 @@ export class Core {
);
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("MCP Connections refreshed");
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
@ -199,11 +205,6 @@ export class Core {
dataLogger.ideSettingsPromise = ideSettingsPromise;
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
@ -236,6 +237,24 @@ export class Core {
(..._) => 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",
);
});
this.nextEditProvider = NextEditProvider.initialize(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
"fineTuned",
);
this.registerMessageHandlers(ideSettingsPromise);
}
@ -302,32 +321,47 @@ export class Core {
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model added (config/addModel message)",
);
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model removed (config/deleteModel message)",
);
});
on("config/newPromptFile", async (msg) => {
const { config } = await this.configHandler.loadConfig();
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Prompt file created (config/newPromptFile message)",
);
});
on("config/addLocalWorkspaceBlock", async (msg) => {
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Local block created (config/addLocalWorkspaceBlock message)",
);
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
await this.configHandler.openConfigProfile(
msg.data.profileId,
msg.data?.element,
);
});
on("config/reload", async (msg) => {
void this.configHandler.reloadConfig();
return await this.configHandler.getSerializedConfig();
// User force reloading will retrigger colocated rules
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
void this.configHandler.reloadConfig(
"Force reloaded (config/reload message)",
);
});
on("config/ideSettingsUpdate", async (msg) => {
@ -346,7 +380,9 @@ export class Core {
on("config/updateSharedConfig", async (msg) => {
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Shared config update (config/updateSharedConfig message)",
);
return newSharedConfig;
});
@ -356,13 +392,18 @@ export class Core {
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Selected model update (config/updateSelectedModel message)",
);
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
let url = `${env.APP_URL}${msg.data.path}`;
const urlPath = msg.data.path.startsWith("/")
? msg.data.path.slice(1)
: msg.data.path;
let url = `${env.APP_URL}${urlPath}`;
if (msg.data.orgSlug) {
url += `?org=${msg.data.orgSlug}`;
}
@ -484,6 +525,18 @@ export class Core {
});
on("llm/listModels", this.handleListModels.bind(this));
on("llm/compileChat", async (msg) => {
const { messages, options } = msg.data;
const model = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
return model.compileChatMessages(messages, options);
});
// Provide messenger to utils so they can interact with GUI + state
TTS.messenger = this.messenger;
ChatDescriber.messenger = this.messenger;
@ -503,6 +556,28 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
on("conversation/compact", async (msg) => {
const currentModel = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!currentModel) {
throw new Error("No chat model selected");
}
try {
await compactConversation({
sessionId: msg.data.sessionId,
index: msg.data.index,
historyManager,
currentModel,
});
return undefined;
} catch (error) {
console.error("Error compacting conversation:", error);
return undefined;
}
});
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =
@ -519,6 +594,21 @@ export class Core {
this.completionProvider.cancel();
});
// Next Edit
on("nextEdit/predict", async (msg) => {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
undefined,
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
});
on("nextEdit/accept", async (msg) => {
this.nextEditProvider.accept(msg.data.completionId);
});
on("nextEdit/reject", async (msg) => {
this.nextEditProvider.reject(msg.data.completionId);
});
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
@ -555,7 +645,6 @@ export class Core {
: undefined,
input: data.input,
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortController,
});
@ -634,9 +723,12 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
const rulesCache = CodebaseRulesCache.getInstance();
await Promise.all(
data.uris.map((uri) => rulesCache.update(this.ide, uri)),
);
await this.configHandler.reloadConfig("Rules file created");
}
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
let localAssistantCreated = false;
for (const uri of data.uris) {
@ -656,7 +748,9 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
const rulesCache = CodebaseRulesCache.getInstance();
data.uris.forEach((uri) => rulesCache.remove(uri));
await this.configHandler.reloadConfig("Codebase rule file deleted");
}
}
});
@ -716,6 +810,52 @@ export class Core {
}
});
on("files/smallEdit", async ({ data }) => {
const EDIT_AGGREGATION_OPTIONS = {
deltaT: 1.0,
deltaL: 5,
maxEdits: 500,
maxDuration: 120.0,
contextSize: 5,
};
EditAggregator.getInstance(
EDIT_AGGREGATION_OPTIONS,
(
beforeAfterdiff: BeforeAfterDiff,
cursorPosBeforeEdit: Position,
cursorPosAfterPrevEdit: Position,
) => {
void processSmallEdit(
beforeAfterdiff,
cursorPosBeforeEdit,
cursorPosAfterPrevEdit,
data.configHandler,
data.getDefsFromLspFunction,
this.ide,
);
},
);
const workspaceDir =
data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
// Store the latest context data
const instance = EditAggregator.getInstance();
(instance as any).latestContextData = {
configHandler: data.configHandler,
getDefsFromLspFunction: data.getDefsFromLspFunction,
recentlyEditedRanges: data.recentlyEditedRanges,
recentlyVisitedRanges: data.recentlyVisitedRanges,
workspaceDir: workspaceDir,
};
// queueMicrotask prevents blocking the UI thread during typing
queueMicrotask(() => {
void EditAggregator.getInstance().processEdits(data.actions);
});
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
if (msg.data.type === "docs") {
@ -823,7 +963,7 @@ export class Core {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
const result = await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
@ -834,6 +974,8 @@ export class Core {
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
return result;
}
private async isItemTooBig(item: ContextItemWithId) {
@ -884,7 +1026,7 @@ export class Core {
],
}),
);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Autocomplete model added");
}
private async handleFilesChanged({
@ -914,7 +1056,9 @@ export class Core {
this.globalContext.update("showConfigUpdateToast", false);
}
}
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Current profile config file updated",
);
continue;
}
@ -922,15 +1066,24 @@ export class Core {
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
uri.endsWith(RULES_MARKDOWN_FILENAME) ||
BLOCK_TYPES.some(
(blockType) =>
uri.includes(`.continue/${blockType}`) ||
uri.includes(`.continue\\${blockType}`),
(uri.includes(".continue") &&
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
BLOCK_TYPES.some((blockType) =>
uri.includes(`.continue/${blockType}`),
)
) {
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Config-related file updated: continuerc, prompt, local block, etc",
);
} else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
try {
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache.update(this.ide, uri).then(() => {
void this.configHandler.reloadConfig("Codebase rule update");
});
} catch (e) {
console.error("Failed to update codebase rule", e);
}
} else if (
uri.endsWith(".continueignore") ||
uri.endsWith(".gitignore")
@ -1012,7 +1165,7 @@ export class Core {
editConfigFile((c) => c, editConfigYamlCallback);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Onboarding completed");
}
private getContextItems = async (
@ -1021,6 +1174,7 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
isInAgentMode: boolean;
}>,
) => {
const { config } = await this.configHandler.loadConfig();
@ -1045,18 +1199,15 @@ export class Core {
// user doesn't need these in their config.json for the shortcuts to work
// option+enter
new CurrentFileContextProvider({}),
// cmd+enter
new CodebaseContextProvider({}),
].find((provider) => provider.description.title === name);
if (!provider) {
return [];
}
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
@ -1068,6 +1219,7 @@ export class Core {
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});
void Telemetry.capture(
@ -1078,10 +1230,14 @@ export class Core {
true,
);
return items.map((item) => ({
...item,
id,
}));
return items.map((item) => {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
return { ...item, id };
});
} catch (e) {
let knownError = false;

View file

View file

@ -1,6 +1,6 @@
import { diffLines, type Change } from "diff";
import { diffChars, diffLines, type Change } from "diff";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
const type: DiffLine["type"] = change.added
@ -55,3 +55,157 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
return ourFormat;
}
export function myersCharDiff(
oldContent: string,
newContent: string,
): DiffChar[] {
// Process the content character by character.
// We will handle newlines separately,
// because diffChars does not have an option to ignore eol newlines.
const theirFormat = diffChars(oldContent, newContent);
// Track indices as we process the diff.
let oldIndex = 0;
let newIndex = 0;
let oldLineIndex = 0;
let newLineIndex = 0;
let oldCharIndexInLine = 0;
let newCharIndexInLine = 0;
const result: DiffChar[] = [];
for (const change of theirFormat) {
// Split the change value by newlines to handle them separately.
if (change.value.includes("\n")) {
const parts = change.value.split(/(\n)/g); // This keeps the newlines as separate entries.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part === "") continue;
if (part === "\n") {
// Handle newline.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newLineIndex++;
newCharIndexInLine = 0; // Reset when moving to a new line.
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldLineIndex++;
oldCharIndexInLine = 0; // Reset when moving to a new line.
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldLineIndex++;
newLineIndex++;
oldCharIndexInLine = 0;
newCharIndexInLine = 0;
}
} else {
// Handle regular text.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newCharIndexInLine += part.length;
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldCharIndexInLine += part.length;
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldCharIndexInLine += part.length;
newCharIndexInLine += part.length;
}
}
}
} else {
// No newlines, handle as a simple change.
if (change.added) {
result.push({
type: "new",
char: change.value,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += change.value.length;
newCharIndexInLine += change.value.length;
} else if (change.removed) {
result.push({
type: "old",
char: change.value,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += change.value.length;
oldCharIndexInLine += change.value.length;
} else {
result.push({
type: "same",
char: change.value,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += change.value.length;
newIndex += change.value.length;
oldCharIndexInLine += change.value.length;
newCharIndexInLine += change.value.length;
}
}
}
return result;
}

View file

@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";
import { myersCharDiff, myersDiff } from "./myers";
describe("Test myers diff function", () => {
test("should ...", () => {
@ -56,3 +56,589 @@ describe("Test myers diff function", () => {
]);
});
});
describe("Test myersCharDiff function on the same line", () => {
test("should differentiate character changes", () => {
const oldContent = "hello world";
const newContent = "hello earth";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "wo",
oldIndex: 6,
oldCharIndexInLine: 6,
oldLineIndex: 0,
},
{
type: "new",
char: "ea",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "r",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "ld",
oldIndex: 9,
oldCharIndexInLine: 9,
oldLineIndex: 0,
},
{
type: "new",
char: "th",
newIndex: 9,
newCharIndexInLine: 9,
newLineIndex: 0,
},
]);
});
test("should handle insertions", () => {
const oldContent = "abc";
const newContent = "abxyzc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "xyz",
newIndex: 2,
newCharIndexInLine: 2,
newLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 2,
newIndex: 5,
oldCharIndexInLine: 2,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle deletions", () => {
const oldContent = "abxyzc";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "xyz",
oldIndex: 2,
oldCharIndexInLine: 2,
oldLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 5,
newIndex: 2,
oldCharIndexInLine: 5,
newCharIndexInLine: 2,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle empty strings", () => {
const oldContent = "";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "new",
char: "abc",
newIndex: 0,
newCharIndexInLine: 0,
newLineIndex: 0,
},
]);
});
test("should handle identical strings", () => {
const content = "no changes here";
const diffChars = myersCharDiff(content, content);
expect(diffChars).toEqual([
{
type: "same",
char: "no changes here",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle whitespace changes", () => {
const oldContent = "hello world";
const newContent = "hello world";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: " ",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "world",
oldIndex: 6,
newIndex: 7,
oldCharIndexInLine: 6,
newCharIndexInLine: 7,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle complex changes", () => {
const oldContent = "The quick brown fox jumps over the lazy dog";
const newContent = "The fast brown fox leaps over the sleeping dog";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "The ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "quick",
oldIndex: 4,
oldCharIndexInLine: 4,
oldLineIndex: 0,
},
{
type: "new",
char: "fast",
newIndex: 4,
newCharIndexInLine: 4,
newLineIndex: 0,
},
{
type: "same",
char: " brown fox ",
oldIndex: 9,
newIndex: 8,
oldCharIndexInLine: 9,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "jum",
oldIndex: 20,
oldCharIndexInLine: 20,
oldLineIndex: 0,
},
{
type: "new",
char: "lea",
newIndex: 19,
newCharIndexInLine: 19,
newLineIndex: 0,
},
{
type: "same",
char: "ps over the ",
oldIndex: 23,
newIndex: 22,
oldCharIndexInLine: 23,
newCharIndexInLine: 22,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "s",
newIndex: 34,
newCharIndexInLine: 34,
newLineIndex: 0,
},
{
type: "same",
char: "l",
oldIndex: 35,
newIndex: 35,
oldCharIndexInLine: 35,
newCharIndexInLine: 35,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "azy",
oldIndex: 36,
oldCharIndexInLine: 36,
oldLineIndex: 0,
},
{
type: "new",
char: "eeping",
newIndex: 36,
newCharIndexInLine: 36,
newLineIndex: 0,
},
{
type: "same",
char: " dog",
oldIndex: 39,
newIndex: 42,
oldCharIndexInLine: 39,
newCharIndexInLine: 42,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
});
describe("Test myersCharDiff function on different lines", () => {
test("should track line indices for multi-line changes", () => {
const oldContent = ["Line one", "Line two", "Line three"].join("\n");
const newContent = ["Line one", "Modified line", "Line three"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Line one",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "L",
oldIndex: 9,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "new",
char: "Mod",
newIndex: 9,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
char: "i",
newCharIndexInLine: 3,
newIndex: 12,
newLineIndex: 1,
oldCharIndexInLine: 1,
oldIndex: 10,
oldLineIndex: 1,
type: "same",
},
{
char: "n",
oldCharIndexInLine: 2,
oldIndex: 11,
oldLineIndex: 1,
type: "old",
},
{
char: "fi",
newCharIndexInLine: 4,
newIndex: 13,
newLineIndex: 1,
type: "new",
},
{
char: "e",
newCharIndexInLine: 6,
newIndex: 15,
newLineIndex: 1,
oldCharIndexInLine: 3,
oldIndex: 12,
oldLineIndex: 1,
type: "same",
},
{
char: "d",
newCharIndexInLine: 7,
newIndex: 16,
newLineIndex: 1,
type: "new",
},
{
char: " ",
newCharIndexInLine: 8,
newIndex: 17,
newLineIndex: 1,
oldCharIndexInLine: 4,
oldIndex: 13,
oldLineIndex: 1,
type: "same",
},
{
type: "old",
char: "two",
oldCharIndexInLine: 5,
oldIndex: 14,
oldLineIndex: 1,
},
{
type: "new",
char: "line",
newCharIndexInLine: 9,
newIndex: 18,
newLineIndex: 1,
},
{
type: "same",
char: "\n",
oldIndex: 17,
oldCharIndexInLine: 8,
oldLineIndex: 1,
newIndex: 22,
newCharIndexInLine: 13,
newLineIndex: 1,
},
{
type: "same",
char: "Line three",
oldIndex: 18,
newIndex: 23,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 2,
newLineIndex: 2,
},
]);
});
test("should track line indices when adding new lines", () => {
const oldContent = ["First line", "Last line"].join("\n");
const newContent = [
"First line",
"Middle line",
"Another middle",
"Last line",
].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "First line",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 10,
newIndex: 10,
oldCharIndexInLine: 10,
newCharIndexInLine: 10,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "Middle line",
newIndex: 11,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
type: "new",
char: "\n",
newIndex: 22,
newCharIndexInLine: 11,
newLineIndex: 1,
},
{
type: "new",
char: "Another middle",
newCharIndexInLine: 0,
newIndex: 23,
newLineIndex: 2,
},
{
type: "new",
char: "\n",
newCharIndexInLine: 14,
newIndex: 37,
newLineIndex: 2,
},
{
type: "same",
char: "Last line",
oldIndex: 11,
oldCharIndexInLine: 0,
oldLineIndex: 1,
newIndex: 38,
newCharIndexInLine: 0,
newLineIndex: 3,
},
]);
});
test("should track line indices when removing lines", () => {
const oldContent = [
"Start",
"Line to remove",
"Another to remove",
"End",
].join("\n");
const newContent = ["Start", "End"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Start",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 5,
newIndex: 5,
oldCharIndexInLine: 5,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "Line to remove",
oldIndex: 6,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 14,
oldIndex: 20,
oldLineIndex: 1,
},
{
type: "old",
char: "Another to remove",
oldCharIndexInLine: 0,
oldIndex: 21,
oldLineIndex: 2,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 17,
oldIndex: 38,
oldLineIndex: 2,
},
{
type: "same",
char: "End",
oldIndex: 39,
newIndex: 6,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 3,
newLineIndex: 1,
},
]);
});
});

View file

@ -1,4 +1,4 @@
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { LineStream, matchLine } from "./util.js";
@ -33,7 +33,7 @@ export async function* streamDiff(
seenIndentationMistake = true;
}
let type: DiffLineType;
let type: DiffType;
const isNewLine = matchIndex === -1;

View file

@ -6,11 +6,11 @@ import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { generateLines } from "./util.js";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
type MyersDiffTypes = Extract<DiffType, "new" | "old"> | "modification";
const UNIFIED_DIFF_SYMBOLS = {
same: "",

View file

@ -1,8 +1,5 @@
import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream";
import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";
@ -90,11 +87,18 @@ export async function* getReplacementWithLlm(
{ role: "assistant", content: assistantPrompt },
],
abortController.signal,
{
raw: true,
prediction: undefined,
reasoning: false,
},
);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);
lines = stopAtLines(lines, () => {}, ["```"]);
// We want to retrive everything from the llm
// then let the filterCodeBlocks function clean up for any trailing text.
// if we stop here early, we run the risk of loosing inner markdown content.
for await (const line of lines) {
yield line;

View file

@ -0,0 +1,459 @@
import { streamLazyApply } from "./streamLazyApply";
// Mock LLM for testing
class MockLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for markdown file with nested blocks
const lines = [
"# Project Structure",
"",
"```markdown README.md",
"# Project Structure",
"",
"```",
".",
"├── src/",
"│ └── main.js",
"└── package.json",
"```",
"```",
];
// Yield each line separately (more realistic streaming)
for (const line of lines) {
yield line;
}
}
}
class MockJavaScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for JavaScript file
const lines = [
"function calculateSum(a, b) {",
" return a + b;",
"}",
"",
"function calculateProduct(a, b) {",
" return a * b;",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockPythonLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for Python file
const lines = [
"def calculate_sum(a, b):",
" return a + b",
"",
"def calculate_product(a, b):",
" return a * b",
];
for (const line of lines) {
yield line;
}
}
}
class MockWithUnchangedCodeLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response with UNCHANGED_CODE markers
const lines = [
"function newFunction() {",
" return 'new';",
"}",
"",
"// ... unchanged code ...",
"",
"function anotherFunction() {",
" return 'updated';",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockTypeScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = [
"interface User {",
" id: number;",
" name: string;",
"}",
"",
"function getUser(id: number): User {",
" return { id, name: 'Test User' };",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockEmptyLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Empty response
return;
}
}
class MockSimpleLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = ["function test() {", " return true;", "}"];
for (const line of lines) {
yield line;
}
}
}
class MockRegularMarkdownLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate regular markdown with simple code block
const lines = [
"# Debug Test Folder",
"The sole purpose of this folder is to open it when debugging.",
"",
"## File Structure",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"├── Dockerfile",
"└── test.ts",
"```",
];
for (const line of lines) {
yield line;
}
}
}
describe("streamLazyApply", () => {
test("should handle markdown files with nested blocks without stopping early", async () => {
const oldCode = "# Project\n\nBasic readme content.";
const newCode = `# Project Structure
\`\`\`markdown README.md
# Project Structure
\`\`\`
.
├── src/
│ └── main.js
└── package.json
\`\`\`
\`\`\``;
const filename = "README.md";
const llm = new MockLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the nested markdown content
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("```markdown README.md");
expect(allContent).toContain("└── package.json");
// Should not have been truncated at the first ```
expect(allContent).toContain("src/");
});
test("should handle JavaScript files correctly", async () => {
const oldCode = "function calculateSum(a, b) {\n return a + b;\n}";
const newCode = `function calculateSum(a, b) {
return a + b;
}
function calculateProduct(a, b) {
return a * b;
}`;
const filename = "calculator.js";
const llm = new MockJavaScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the JavaScript functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculateSum");
expect(allContent).toContain("calculateProduct");
});
test("should handle Python files correctly", async () => {
const oldCode = "def calculate_sum(a, b):\n return a + b";
const newCode = `def calculate_sum(a, b):
return a + b
def calculate_product(a, b):
return a * b`;
const filename = "calculator.py";
const llm = new MockPythonLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the Python functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculate_sum");
expect(allContent).toContain("calculate_product");
});
test("should handle UNCHANGED_CODE markers in responses", async () => {
const oldCode = `function oldFunction() {
return 'old';
}
function existingFunction() {
return 'existing';
}`;
const newCode = `function newFunction() {
return 'new';
}
function existingFunction() {
return 'existing';
}
function anotherFunction() {
return 'updated';
}`;
const filename = "example.js";
const llm = new MockWithUnchangedCodeLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain new and updated functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("newFunction");
expect(allContent).toContain("anotherFunction");
});
test("should handle TypeScript files correctly", async () => {
const oldCode = "interface User {\n id: number;\n}";
const newCode = `interface User {
id: number;
name: string;
}
function getUser(id: number): User {
return { id, name: 'Test User' };
}`;
const filename = "user.ts";
const llm = new MockTypeScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain TypeScript interface and function
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("interface User");
expect(allContent).toContain("getUser");
expect(allContent).toContain("name: string");
});
test("should work with empty LLM responses", async () => {
const oldCode = "function test() { return 1; }";
const newCode = "function test() { return 2; }";
const filename = "test.js";
const llm = new MockEmptyLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should handle empty response gracefully
expect(diffLines).toBeDefined();
});
test("should correctly identify markdown vs non-markdown files", async () => {
// Test that our isMarkdownFile logic works
const markdownFiles = ["README.md", "docs.markdown", "example.gfm"];
const nonMarkdownFiles = [
"script.js",
"code.py",
"style.css",
"component.tsx",
];
// This is more of a unit test, but verifies our file detection logic
// We can test this indirectly by checking that different file types
// are processed through different code paths
const oldCode = "function test() { return false; }";
const newCode = "function test() { return true; }";
const llm = new MockSimpleLLM() as any;
// Test each file type
for (const filename of [...markdownFiles, ...nonMarkdownFiles]) {
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should work for all file types
expect(diffLines.length).toBeGreaterThan(0);
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("test");
}
});
test("should handle regular markdown files with simple code blocks", async () => {
const oldCode = "# Old Content";
const newCode = `# Debug Test Folder
The sole purpose of this folder is to open it when debugging.
## File Structure
\`\`\`
debug-test-folder/
├── AdvancedPage.tsx
├── Calculator.java
├── Dockerfile
└── test.ts
\`\`\``;
const filename = "README.md";
const llm = new MockRegularMarkdownLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the full file structure
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("Debug Test Folder");
expect(allContent).toContain("File Structure");
expect(allContent).toContain("debug-test-folder/");
expect(allContent).toContain("├── AdvancedPage.tsx");
expect(allContent).toContain("└── test.ts");
// Should not have been truncated at the opening ```
expect(allContent).toContain("Calculator.java");
expect(allContent).toContain("Dockerfile");
});
});

View file

@ -2,11 +2,11 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
removeTrailingWhitespace,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
@ -44,9 +44,12 @@ export async function* streamLazyApply(
}
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = stopAtLinesWithMarkdownSupport(
lazyCompletionLines,
filename,
);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
@ -92,7 +95,6 @@ async function* streamFillUnchangedCode(
newLines.push(replacementLine);
replacement += replacementLine + "\n";
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;

View file

@ -63,7 +63,8 @@ export async function* recursiveStream(
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
raw: true,
prediction: undefined,
reasoning: false,
});

View file

@ -0,0 +1,768 @@
import { findSearchMatch } from "./findSearchMatch";
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}
const b = 2;`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b = 2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2;`;
const result = findSearchMatch(fileContent, searchContent);
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
strategyName: "trimmedMatch",
});
});
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
function hello() {
return "world";
}
const b = 2;`;
const searchContent = `\nfunction hello() {
return "world";
}\n`;
const result = findSearchMatch(fileContent, searchContent);
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `\n const b = 2; \n`;
const result = findSearchMatch(fileContent, searchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
strategyName: "trimmedMatch",
});
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("No matches", () => {
it("should return null when search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function goodbye() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
it("should return only fuzzy result when trimmed search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction goodbye() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();
const unicode = "🚀 Hello 世界";`;
const searchContent = `const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
const x = 1;
}
function test() {
const x = 1;
}`;
const searchContent = `function test() {
const x = 1;
}`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Whitespace-ignored matches", () => {
it("should match code with different indentation", () => {
const fileContent = `function example() {
const x = 1;
const y = 2;
return x + y;
}`;
const searchContent = `const x=1;
const y=2;
return x+y;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(20); // After "function example() {\n"
expect(result!.endIndex).toBe(72); // End of " return x + y;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content contains the original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const x = 1;
const y = 2;
return x + y;`);
});
it("should match single line with different spacing", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b=2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(12); // After "const a = 1;"
expect(result!.endIndex).toBe(32); // End of "const b = 2;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original spacing
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const b = 2;`);
});
it("should match with tabs vs spaces", () => {
const fileContent = `function test() {
\tif (condition) {
\t\treturn true;
\t}
}`;
const searchContent = `if (condition) {
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function test() {"
expect(result!.endIndex).toBe(53); // End of "\t}"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original tabs
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
\tif (condition) {
\t\treturn true;
\t}`);
});
it("should match complex whitespace patterns", () => {
const fileContent = `const obj = {
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'
};`;
const searchContent = `key1:'value1',
key2:'value2',
key3:'value3'`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(13); // After "const obj = {"
expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'`);
});
it("should handle newlines and mixed whitespace", () => {
const fileContent = `function calc() {
let result = 0;
result += 5;
return result;
}`;
const searchContent = `let result=0;result+=5;return result;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
expect(result!.endIndex).toBe(78); // End of " return result;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content includes all original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
let result = 0;
result += 5;
return result;`);
});
it("should prefer exact match over whitespace-ignored match", () => {
const fileContent = `const x=1;
const x = 1;`;
const searchContent = `const x=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the exact match first (at index 0), not the whitespace-ignored match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
it("should handle empty content after whitespace removal", () => {
const fileContent = `function test() {
return 1;
}`;
const searchContent = `\n\n \t \n`;
const result = findSearchMatch(fileContent, searchContent);
// Should match at beginning for empty/whitespace-only content
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex code blocks with different formatting", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.value = 0;
}
getValue() {
return this.value;
}
}`;
const searchContent = `constructor(name){
this.name=name;
this.value=0;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(15); // After "class Example {"
expect(result!.endIndex).toBe(95); // End of " }"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
constructor(name) {
this.name = name;
this.value = 0;
}`);
});
it("should return null when no close match exists", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `this has nothing to do with the other option`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiple potential matches and return first", () => {
const fileContent = `const a=1;
const a = 1;
const a = 1;`;
const searchContent = `const a=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
reset() {
this.result = 0;
return this;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = ` reset() {
this.result = 0;
return this;
}`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match import statement", () => {
const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return <div>Hello World</div>;
}`;
const searchContent = `import { useState, useEffect } from 'react';`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match comment block", () => {
const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
function test() {
// Single line comment
return true;
}`;
const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
describe("Jaro-Winkler fuzzy matching", () => {
describe("Basic fuzzy matching", () => {
it("should find fuzzy match for similar strings", () => {
const fileContent = `function calculateSum(a, b) {
return a + b;
}`;
const searchContent = `function calculateSum(x, y) {
return x + y;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match with minor typos", () => {
const fileContent = `const message = "Hello World";`;
const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should find fuzzy match with different variable names", () => {
const fileContent = `let userAge = 25;
let userName = "John";`;
const searchContent = `let age = 25;
let name = "John";`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for similar function signature", () => {
const fileContent = `function processUserData(userData) {
validateInput(userData);
return formatOutput(userData);
}`;
const searchContent = `function processData(data) {
validateInput(data);
return formatOutput(data);
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Multi-line fuzzy matching", () => {
it("should find fuzzy match for multi-line blocks", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = `class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this;
}
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for partial blocks", () => {
const fileContent = `function processData(input) {
const validated = validateInput(input);
const processed = transformData(validated);
const result = formatOutput(processed);
return result;
}`;
const searchContent = `const validated = validateInput(input);
const processed = transformData(validated);`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Edge cases with fuzzy matching", () => {
it("should handle empty search content with fuzzy matching enabled", () => {
const fileContent = `function test() {}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle empty file content with fuzzy matching enabled", () => {
const fileContent = "";
const searchContent = "function test() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should prefer exact match over fuzzy match", () => {
const fileContent = `function test() { return true; }
function test() { return false; }`;
const searchContent = `function test() { return true; }`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should handle very short strings", () => {
const fileContent = `a b c`;
const searchContent = `a c`;
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity
expect(result).toBeNull();
});
it("should handle special characters in fuzzy matching", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();`;
const searchContent = `const regex = /[a-zA-Z0-9]+/g;
const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
});
});

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