Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into func-max-chunk-size
Changesetddc8b505712b1811c56c9d250f9bc4f3e66abb67cc6c59300f8debd84beb3ad3
Authoruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-08-18 18:20 +05:30
Committeruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-08-18 18:20 +05:30
Parentsb68735bd51e5, 5ce6c52445c2

Browse the files at this changeset

More than 300 files changed

added .continue/rules/bigger-picture-description-rules.md +19 −0
@@ -0,0 +1,19 @@
1+---
2+name: Bigger Picture Description Rules
3+description: Guidelines for explaining how code works in context
4+alwaysApply: false
5+---
6+
7+When a user asks how a certain part of the code works:
8+
9+## 1. Describe what the code does in isolation
10+
11+Explain the functionality of the code without considering its interactions with other parts of the codebase.
12+
13+## 2. Describe interactions with other parts of the codebase
14+
15+If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
16+
17+## 3. Include parent function for clarity
18+
19+When describing each use-case, include the parent function for clarity.
deleted .continue/rules/bigger-picture-description-rules.yaml +0 −13
@@ -1,13 +0,0 @@
1-name: bigger-picture-description-rules
2-version: 0.0.1
3-schema: v1
4-rules:
5- - name: bigger-picture-description-rules
6- rule: >-
7- When a user asks how a certain part of the code works:
8-
9- 1. Describe what the code does in isolation.
10-
11- 2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
12-
13- 3. When describing each use-case, include the parent function for clarity.
added .continue/rules/colors.md +63 −0
@@ -0,0 +1,63 @@
1+---
2+name: Extension Color Themes
3+description: Guidelines for using theme colors in GUI components
4+alwaysApply: false
5+globs: "gui/**/*.tsx"
6+---
7+
8+When adding colors to components, use tailwind color classes.
9+Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
10+
11+## Available theme colors
12+
13+### Normal text
14+
15+- `foreground`, `description`, `description-muted`
16+
17+### Other text, icons, etc
18+
19+- `success`, `warning`, `error`, `accent`, `link`
20+
21+### General components
22+
23+- `background`, `border`, `border-focus`
24+
25+### Specific components
26+
27+#### Button
28+
29+- `primary`, `primary-foreground`, `primary-hover`
30+- `secondary`, `secondary-foreground`, `secondary-hover`
31+
32+#### Input
33+
34+- `input`, `input-foreground`, `input-border`, `input-placeholder`
35+
36+#### Badge
37+
38+- `badge`, `badge-foreground`
39+
40+#### List/Dropdown items
41+
42+- `list-hover`, `list-active`, `list-active-foreground`
43+
44+#### Code Editor
45+
46+- `editor`, `editor-foreground`
47+
48+## Usage examples
49+
50+Any of these colors can be used in tailwind classes:
51+
52+- `bg-primary`
53+- `text-success`
54+- `border-error`
55+- `hover:bg-list-hover`
56+
57+## Excluded colors
58+
59+The following less-used colors are excluded from this guide:
60+
61+- Command (only used by tip-tap): `command`, `command-foreground`, `command-border`, `command-border-focus`
62+- Find widget colors: `find-match`, `find-match-selected`
63+- `table-oddRow`
deleted .continue/rules/colors.yaml +0 −27
@@ -1,27 +0,0 @@
1-name: GUI
2-version: 0.0.1
3-schema: v1
4-rules:
5- - name: Extension Color Themes
6- rule: |
7- When adding colors to components, use tailwind color classes.
8- Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
9-
10- The common available theme colors are:
11- - For normal text: foreground, description, description-muted
12- - For other text, icons, etc: success, warning, error, accent, link
13- - For general components background, border, border-focus
14- - For specific components:
15- - Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover
16- - Input: input, input-foreground, input-border, input-placeholder
17- - Badge: badge, badge-foreground
18- - List/Dropdown items: list-hover, list-active, list-active-foreground
19- - Code Editor: editor, editor-foreground
20-
21- Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc.
22- globs: "gui/**/*.tsx"
23-# Excluding the following less-used colors:
24-# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus
25-# Find widget colors: find-match, find-match-selected
26-# table-oddRow
27-
added .continue/rules/documentation-description-rule.md +8 −0
@@ -0,0 +1,8 @@
1+---
2+globs: docs/**/*.{md,mdx}
3+description: This rule applies to all documentation files to ensure consistent
4+ SEO optimization and improve discoverability. It helps users and search
5+ engines understand the content of each page before reading it.
6+---
7+
8+Every file in the docs folder must include a 'description' field in its frontmatter that accurately summarizes the content of the page in 100-160 characters. The description should be concise, keyword-rich, and explain what users will learn or accomplish from the page.
deleted .continue/rules/edit-aggregator-singleton-rule.md +0 −8
@@ -1,8 +0,0 @@
1----
2-patterns: ["EditAggregator", "processEdit"]
3-glob: "**/*.tsx"
4-name: "Enforce EditAggregator Singleton"
5-description: "Ensure that EditAggregator is used as a singleton in the codebase."
6----
7-
8-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.
added .continue/rules/intellij-plugin-test-execution.md +20 −0
@@ -0,0 +1,20 @@
1+---
2+name: IntelliJ Plugin Test Execution
3+description: Guidelines for running IntelliJ plugin tests with Gradle
4+alwaysApply: false
5+globs: extensions/intellij/**/*Test.kt
6+---
7+
8+Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
9+
10+## Run test class
11+
12+```bash
13+./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
14+```
15+
16+## Run specific test method
17+
18+```bash
19+./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
20+```
deleted .continue/rules/intellij-plugin-test-execution.yaml +0 −15
@@ -1,15 +0,0 @@
1-name: IntelliJ Plugin Test Execution
2-version: 0.0.1
3-schema: v1
4-rules:
5- - name: IntelliJ Plugin Test Execution
6- rule: |-
7- Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
8- ```bash
9- # Run test class
10- ./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
11-
12- # Run specific test method
13- ./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
14- ```
15- globs: extensions/intellij/**/*Test.kt
deleted .continue/rules/intellij-test-standards.yaml +0 −10
@@ -1,10 +0,0 @@
1-name: IntelliJ Test Standards
2-version: 0.0.1
3-schema: v1
4-rules:
5- - name: IntelliJ Test Standards
6- rule: When writing tests for the IntelliJ plugin, use the mockk library for
7- mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
8- Always structure tests with clear Arrange-Act-Assert patterns and use
9- descriptive test names that indicate the scenario being tested.
10- globs: "**/test/**/*.kt"
modified .continue/rules/new-protocol-message.md +1 −0
@@ -1,6 +1,7 @@
11 ---
22 name: New protocol message
33 description: Create a new protocol message from core/gui/ide to core/gui/ide
4+alwaysApply: false
45 ---
56
67 Create a new protocol message by taking the following steps:
added .continue/rules/unit-testing-rules.md +37 −0
@@ -0,0 +1,37 @@
1+---
2+name: Unit Testing Rules
3+description: Guidelines for unit testing in this project
4+alwaysApply: false
5+---
6+
7+For unit testing in this project:
8+
9+## 1. Testing frameworks
10+
11+The project uses Vitest and Jest for testing. Prefer Vitest.
12+
13+## 2. Test execution location
14+
15+Run tests from within the specific package directory (e.g., `cd core && ..`).
16+
17+## 3. Vitest tests
18+
19+- Test files follow the pattern `*.vitest.ts`
20+- Run tests using `vitest` from within the specific package/module directory:
21+ ```bash
22+ cd [directory] && vitest -- [test file path]
23+ ```
24+
25+## 4. Jest tests
26+
27+- Test files follow the pattern `*.test.ts`
28+- Run tests using `npm test` from within the specific package/module directory:
29+ ```bash
30+ cd [directory] && npm test -- [test file path]
31+ ```
32+- The test script uses experimental VM modules via NODE_OPTIONS flag
33+
34+## 5. Test structure
35+
36+- Write tests as top-level `test()` functions - DO NOT use `describe()` blocks
37+- Include the function name being tested in the test description for clarity
deleted .continue/rules/unit-testing-rules.yaml +0 −28
@@ -1,28 +0,0 @@
1-name: unit-testing-rules
2-version: 0.0.1
3-schema: v1
4-rules:
5- - name: unit-testing-rules
6- rule: >-
7- For unit testing in this project:
8-
9- 1. The project uses Vitest and Jest for testing. Prefer Vitest
10-
11- 2. Run tests from within the specific package directory (e.g., `cd core && ..`
12-
13- 3. For vitest tests,
14- - Test files follow the pattern `*.vitest.ts`
15- - Run tests using `vitest` from within the specific package/module
16- directory: `cd [directory] && vitest -- [test file path]`
17-
18- 4. For jest tests,
19- - Test files follow the pattern `*.test.ts`
20- - Run tests using `npm test` from within the specific package/module
21- directory: `cd [directory] && npm test -- [test file path]`
22- - The test script uses experimental VM modules via NODE_OPTIONS flag
23-
24- 5. For both
25- - Write tests as top-level `test()` functions - DO NOT use `describe()`
26- blocks
27- - Include the function name being tested in the test description for
28- clarity
modified .github/actions/build-vscode-extension/action.yml +4 −2
@@ -105,7 +105,9 @@
105105 shell: bash
106106 run: |
107107 cd gui
108- npm run build
108+ npm run build --max-old-space-size=4096
109+ env:
110+ NODE_OPTIONS: "--max-old-space-size=4096"
109111
110112 - name: Prepackage the extension
111113 shell: bash
@@ -156,4 +158,4 @@
156158 npx vsce package --pre-release --no-dependencies --target ${{ steps.set-target.outputs.target }}
157159 else
158160 npx vsce package --no-dependencies --target ${{ steps.set-target.outputs.target }}
159- fi
No newline at the end of the file
161+ fi
modified .github/pull_request_template.md +5 −0
@@ -2,6 +2,11 @@
22
33 [ What changed? Feel free to be brief. ]
44
5+## AI Code Review
6+
7+- **Team members only**: AI review runs automatically when PR is opened or marked ready for review
8+- Team members can also trigger a review by commenting `@continue-general-review` or `@continue-detailed-review`
9+
510 ## Checklist
611
712 - [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)
modified .github/workflows/auto-assign-issue.yaml +1 −1
@@ -14,7 +14,7 @@
1414 uses: pozil/auto-assign-issue@v2
1515 with:
1616 repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
17- assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai
17+ assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai,uinstinct
1818 numOfAssignee: 1
1919 # - name: "Add default labels"
2020 # uses: actions-ecosystem/action-add-labels@v1
modified .github/workflows/auto-release.yml +2 −2
@@ -16,7 +16,7 @@
1616 contents: write # Needed for creating releases
1717
1818 steps:
19- - uses: actions/checkout@v4
19+ - uses: actions/checkout@v5
2020
2121 - name: Get version from package.json
2222 id: get_version
@@ -45,7 +45,7 @@
4545 contents: write # Needed for creating releases
4646
4747 steps:
48- - uses: actions/checkout@v4
48+ - uses: actions/checkout@v5
4949 with:
5050 fetch-depth: 0
5151
modified .github/workflows/compliance.yaml +2 −2
@@ -101,7 +101,7 @@
101101 contents: read
102102 steps:
103103 - name: Checkout code
104- uses: actions/checkout@v4
104+ uses: actions/checkout@v5
105105
106106 - name: Setup Node.js
107107 uses: actions/setup-node@v4
@@ -134,7 +134,7 @@
134134 if: ${{ !github.event.pull_request.draft }}
135135 steps:
136136 - name: Checkout code
137- uses: actions/checkout@v4
137+ uses: actions/checkout@v5
138138
139139 - name: Check required files
140140 run: |
added .github/workflows/continue-detailed-review.yaml +25 −0
@@ -0,0 +1,25 @@
1+name: Continue Detailed Review
2+
3+on:
4+ pull_request:
5+ types: [opened, ready_for_review]
6+ issue_comment:
7+ types: [created]
8+
9+permissions:
10+ contents: read
11+ pull-requests: write
12+ issues: write
13+
14+jobs:
15+ detailed-code-review:
16+ name: Continue Detailed Review
17+ runs-on: ubuntu-latest
18+ timeout-minutes: 10
19+ steps:
20+ - name: Run Detailed PR Review
21+ uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070
22+ with:
23+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
24+ continue-org: continuedev
25+ continue-config: continuedev/review-bot
added .github/workflows/continue-general-review.yaml +25 −0
@@ -0,0 +1,25 @@
1+name: Continue General Review
2+
3+on:
4+ pull_request:
5+ types: [opened, ready_for_review]
6+ issue_comment:
7+ types: [created]
8+
9+permissions:
10+ contents: read
11+ pull-requests: write
12+ issues: write
13+
14+jobs:
15+ general-code-review:
16+ name: Continue General Review
17+ runs-on: ubuntu-latest
18+ timeout-minutes: 10
19+ steps:
20+ - name: Run Continue PR Review Action
21+ uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070
22+ with:
23+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
24+ continue-org: "continuedev"
25+ continue-config: "continuedev/review-bot"
modified .github/workflows/docs.yml +1 −1
@@ -14,7 +14,7 @@
1414
1515 steps:
1616 - name: Checkout repository
17- uses: actions/checkout@v4
17+ uses: actions/checkout@v5
1818
1919 - name: Setup Node.js
2020 uses: actions/setup-node@v4
modified .github/workflows/jetbrains-release.yaml +7 −7
@@ -56,7 +56,7 @@
5656 # steps:
5757 # # 0. Setup git
5858 # - name: Checkout
59- # uses: actions/checkout@v4
59+ # uses: actions/checkout@v5
6060
6161 # - name: Set up Git
6262 # run: |
@@ -102,7 +102,7 @@
102102 steps:
103103 # Check out current repository
104104 - name: Fetch Sources
105- uses: actions/checkout@v4
105+ uses: actions/checkout@v5
106106 with:
107107 ref: ${{ github.event.release.tag_name }}
108108
@@ -362,7 +362,7 @@
362362 steps:
363363 # 1. Check-out repository
364364 - name: Check-out repository
365- uses: actions/checkout@v4
365+ uses: actions/checkout@v5
366366
367367 # 2. Install npm dependencies
368368 - name: Use Node.js from .nvmrc
@@ -429,7 +429,7 @@
429429 steps:
430430 # Check out current repository
431431 - name: Fetch Sources
432- uses: actions/checkout@v4
432+ uses: actions/checkout@v5
433433
434434 # Set up Java environment for the next steps
435435 - name: Setup Java
@@ -482,7 +482,7 @@
482482
483483 # Check out current repository
484484 - name: Fetch Sources
485- uses: actions/checkout@v4
485+ uses: actions/checkout@v5
486486
487487 # Set up Java environment for the next steps
488488 - name: Setup Java
@@ -493,7 +493,7 @@
493493
494494 # Run Qodana inspections
495495 - name: Qodana - Code Inspection
496- uses: JetBrains/qodana-action@v2025.1.1
496+ uses: JetBrains/qodana-action@v2025.2.1
497497 with:
498498 cache-default-branch-only: true
499499
@@ -513,7 +513,7 @@
513513
514514 # Check out current repository
515515 - name: Fetch Sources
516- uses: actions/checkout@v4
516+ uses: actions/checkout@v5
517517
518518 # Set up Java environment for the next steps
519519 - name: Setup Java
modified .github/workflows/label-merged-prs.yml +1 −1
@@ -13,7 +13,7 @@
1313
1414 steps:
1515 - name: Checkout repository
16- uses: actions/checkout@v4
16+ uses: actions/checkout@v5
1717
1818 - name: Check if author is in tier list
1919 id: check-author
modified .github/workflows/main-build.yaml +1 −1
@@ -18,7 +18,7 @@
1818 matrix:
1919 platform: [Linux, macOS]
2020 steps:
21- - uses: actions/checkout@v4
21+ - uses: actions/checkout@v5
2222 with:
2323 fetch-depth: 2 # Get the last 2 commits to find the merge commit
2424
modified .github/workflows/main.yaml +4 −4
@@ -66,7 +66,7 @@
6666 arch: arm64
6767 npm_config_arch: arm64
6868 steps:
69- - uses: actions/checkout@v4
69+ - uses: actions/checkout@v5
7070 with:
7171 fetch-depth: 0
7272
@@ -92,7 +92,7 @@
9292 runs-on: ubuntu-latest
9393 steps:
9494 - name: Checkout
95- uses: actions/checkout@v4
95+ uses: actions/checkout@v5
9696 with:
9797 fetch-depth: 0 # This ensures all tags are fetched
9898
@@ -112,7 +112,7 @@
112112 - build
113113 steps:
114114 - name: Checkout
115- uses: actions/checkout@v4
115+ uses: actions/checkout@v5
116116
117117 - name: Set up Git
118118 run: |
@@ -145,7 +145,7 @@
145145 steps:
146146 # 0. Setup git
147147 - name: Checkout
148- uses: actions/checkout@v4
148+ uses: actions/checkout@v5
149149
150150 - name: Set up Git
151151 run: |
modified .github/workflows/pr-build-upload-vsix.yaml +1 −1
@@ -24,7 +24,7 @@
2424 runner: macos-latest
2525
2626 steps:
27- - uses: actions/checkout@v4
27+ - uses: actions/checkout@v5
2828 with:
2929 fetch-depth: 0
3030
modified .github/workflows/pr-checks.yaml +38 −11
@@ -14,7 +14,7 @@
1414 prettier-check:
1515 runs-on: ubuntu-latest
1616 steps:
17- - uses: actions/checkout@v4
17+ - uses: actions/checkout@v5
1818 - uses: actions/setup-node@v4
1919 with:
2020 node-version-file: ".nvmrc"
@@ -35,7 +35,7 @@
3535 core-checks:
3636 runs-on: ubuntu-latest
3737 steps:
38- - uses: actions/checkout@v4
38+ - uses: actions/checkout@v5
3939 - name: Setup packages
4040 uses: ./.github/actions/setup-packages
4141 - name: Setup core component
@@ -71,7 +71,7 @@
7171 gui-checks:
7272 runs-on: ubuntu-latest
7373 steps:
74- - uses: actions/checkout@v4
74+ - uses: actions/checkout@v5
7575 - name: Setup packages
7676 uses: ./.github/actions/setup-packages
7777 - name: Setup core component
@@ -101,7 +101,7 @@
101101 binary-checks:
102102 runs-on: ubuntu-latest
103103 steps:
104- - uses: actions/checkout@v4
104+ - uses: actions/checkout@v5
105105 - name: Setup packages
106106 uses: ./.github/actions/setup-packages
107107 - name: Setup core component
@@ -123,7 +123,7 @@
123123 vscode-checks:
124124 runs-on: ubuntu-latest
125125 steps:
126- - uses: actions/checkout@v4
126+ - uses: actions/checkout@v5
127127 - name: Setup packages
128128 uses: ./.github/actions/setup-packages
129129 - name: Setup core component
@@ -156,7 +156,7 @@
156156 outputs:
157157 packages: ${{ steps.get-packages.outputs.packages }}
158158 steps:
159- - uses: actions/checkout@v4
159+ - uses: actions/checkout@v5
160160 - name: Get package list
161161 id: get-packages
162162 run: |
@@ -171,7 +171,7 @@
171171 matrix:
172172 package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
173173 steps:
174- - uses: actions/checkout@v4
174+ - uses: actions/checkout@v5
175175 - name: Setup packages
176176 uses: ./.github/actions/setup-packages
177177
@@ -197,7 +197,7 @@
197197 outputs:
198198 test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
199199 steps:
200- - uses: actions/checkout@v4
200+ - uses: actions/checkout@v5
201201 - uses: actions/setup-node@v4
202202 with:
203203 node-version-file: ".nvmrc"
@@ -257,7 +257,7 @@
257257 runs-on: ubuntu-latest
258258 timeout-minutes: 15
259259 steps:
260- - uses: actions/checkout@v4
260+ - uses: actions/checkout@v5
261261 with:
262262 fetch-depth: 0
263263
@@ -289,7 +289,7 @@
289289 test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
290290 command: ["e2e:ci:run", "e2e:ci:run-yaml"]
291291 steps:
292- - uses: actions/checkout@v4
292+ - uses: actions/checkout@v5
293293 - name: Run VS Code E2E test
294294 uses: ./.github/actions/run-vscode-e2e-test
295295 with:
@@ -303,7 +303,7 @@
303303 runs-on: ubuntu-latest
304304 timeout-minutes: 15
305305 steps:
306- - uses: actions/checkout@v4
306+ - uses: actions/checkout@v5
307307 - name: Run JetBrains tests
308308 uses: ./.github/actions/run-jetbrains-tests
309309 with:
@@ -312,6 +312,32 @@
312312
313313 # GitHub does not have a way of requiring that all checks pass (you must manually select each job)
314314 # This action at least lets us manage the list of required tests via source control
315+ pr-review-action-tests:
316+ runs-on: ubuntu-latest
317+ steps:
318+ - uses: actions/checkout@v5
319+ - uses: actions/setup-node@v4
320+ with:
321+ node-version: 20
322+
323+ - name: Cache PR review action node modules
324+ uses: actions/cache@v4
325+ id: pr-review-cache
326+ with:
327+ path: actions/detailed-review/node_modules
328+ key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }}
329+
330+ - name: Install dependencies
331+ if: steps.pr-review-cache.outputs.cache-hit != 'true'
332+ run: |
333+ cd actions/detailed-review
334+ npm install
335+
336+ - name: Run tests
337+ run: |
338+ cd actions/detailed-review
339+ npm test
340+
315341 # so that creators of new jobs can add them to this list
316342 require-all-checks-to-pass:
317343 if: always()
@@ -328,6 +354,7 @@
328354 - vscode-package-extension-linux
329355 - vscode-e2e-tests
330356 - jetbrains-tests
357+ - pr-review-action-tests
331358
332359 steps:
333360 - name: Decide whether the needed jobs succeeded or failed
modified .github/workflows/preview.yaml +3 −3
@@ -66,7 +66,7 @@
6666 arch: arm64
6767 npm_config_arch: arm64
6868 steps:
69- - uses: actions/checkout@v4
69+ - uses: actions/checkout@v5
7070 with:
7171 fetch-depth: 0
7272
@@ -96,7 +96,7 @@
9696 - build
9797 steps:
9898 - name: Checkout
99- uses: actions/checkout@v4
99+ uses: actions/checkout@v5
100100
101101 - name: Set up Git
102102 run: |
@@ -131,7 +131,7 @@
131131 steps:
132132 # 0. Setup git
133133 - name: Checkout
134- uses: actions/checkout@v4
134+ uses: actions/checkout@v5
135135
136136 - name: Set up Git
137137 run: |
modified .github/workflows/reusable-release.yml +1 −1
@@ -47,7 +47,7 @@
4747 working-directory: ${{ inputs.package-path }}
4848 steps:
4949 - name: Checkout
50- uses: actions/checkout@v4
50+ uses: actions/checkout@v5
5151 with:
5252 fetch-depth: 0
5353
modified .github/workflows/similar-issues.yml +42 −40
@@ -7,6 +7,8 @@
77
88 jobs:
99 analyze:
10+ # Disabling for now due to bugs
11+ if: false
1012 runs-on: ubuntu-latest
1113 permissions:
1214 issues: write
@@ -14,30 +16,30 @@
1416
1517 steps:
1618 - name: Checkout deja-view
17- uses: actions/checkout@v4
19+ uses: actions/checkout@v5
1820 with:
19- repository: 'bdougie/deja-view'
21+ repository: "bdougie/deja-view"
2022 # Option 1: Pin to specific commit (most secure)
21- ref: '45e7696' # Pin to specific commit for stability
22-
23+ ref: "45e7696" # Pin to specific commit for stability
24+
2325 # Option 2: Use a tag (recommended after creating releases)
2426 # ref: 'v1.0.0'
25-
27+
2628 # Option 3: Use main branch (least secure, gets latest changes)
2729 # ref: 'main'
28-
30+
2931 path: deja-view
3032
3133 - name: Setup Python
3234 uses: actions/setup-python@v5
3335 with:
34- python-version: '3.11'
36+ python-version: "3.11"
3537
3638 - name: Install dependencies
3739 run: |
3840 cd deja-view
3941 pip install -r requirements.txt
40-
42+
4143 - name: Index repository if needed
4244 env:
4345 CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }}
@@ -46,10 +48,10 @@
4648 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
4749 run: |
4850 cd deja-view
49-
51+
5052 # Index the repository (this will update existing index)
5153 python cli.py index "${{ github.repository }}" --max-issues 200 || true
52-
54+
5355 - name: Search for similar issues
5456 id: search
5557 env:
@@ -59,7 +61,7 @@
5961 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
6062 run: |
6163 cd deja-view
62-
64+
6365 # Determine if this is an issue or PR
6466 if [ "${{ github.event_name }}" = "pull_request" ]; then
6567 ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
@@ -70,26 +72,26 @@
7072 THRESHOLD="0.7"
7173 TOP_K="5"
7274 fi
73-
75+
7476 # Create a Python script to search and format as JSON
7577 cat << 'PYTHON_SCRIPT' > search_similar.py
7678 import sys
7779 import json
7880 import os
7981 from github_similarity_service import SimilarityService
80-
82+
8183 issue_url = sys.argv[1]
8284 threshold = float(sys.argv[2])
8385 top_k = int(sys.argv[3])
84-
86+
8587 # Parse issue number from URL
8688 issue_number = int(issue_url.split('/')[-1])
8789 repo_parts = issue_url.split('/')
8890 owner = repo_parts[3]
8991 repo = repo_parts[4]
90-
92+
9193 service = SimilarityService()
92-
94+
9395 # Find similar issues
9496 similar = service.find_similar_issues(
9597 owner=owner,
@@ -98,26 +100,26 @@
98100 top_k=top_k,
99101 min_similarity=threshold
100102 )
101-
103+
102104 # Format as JSON
103105 print(json.dumps(similar))
104106 PYTHON_SCRIPT
105-
107+
106108 # Search for similar issues
107109 SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K")
108-
110+
109111 # Save to output
110112 echo "similar_issues<<EOF" >> $GITHUB_OUTPUT
111113 echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT
112114 echo "EOF" >> $GITHUB_OUTPUT
113-
115+
114116 # Check if any similar issues found
115117 if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then
116118 echo "has_similar=true" >> $GITHUB_OUTPUT
117119 else
118120 echo "has_similar=false" >> $GITHUB_OUTPUT
119121 fi
120-
122+
121123 - name: Check if issue should be a discussion
122124 id: discussion_check
123125 if: github.event_name == 'issues'
@@ -128,19 +130,19 @@
128130 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
129131 run: |
130132 cd deja-view
131-
133+
132134 # Create a Python script to analyze the issue
133135 cat << 'PYTHON_SCRIPT' > check_discussion.py
134136 import os
135137 import json
136138 import re
137139 from github_similarity_service import SimilarityService
138-
140+
139141 # Get issue details from environment
140142 issue_title = os.environ.get('ISSUE_TITLE', '')
141143 issue_body = os.environ.get('ISSUE_BODY', '')
142144 issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]'))
143-
145+
144146 # Mock Issue object for analysis
145147 class MockIssue:
146148 def __init__(self):
@@ -152,41 +154,41 @@
152154 self.created_at = ''
153155 self.updated_at = ''
154156 self.url = ''
155-
157+
156158 service = SimilarityService()
157159 issue = MockIssue()
158-
160+
159161 score, reasons = service._calculate_discussion_score(issue)
160-
162+
161163 result = {
162164 'score': score,
163165 'reasons': reasons,
164166 'should_be_discussion': score >= 0.5,
165167 'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low'
166168 }
167-
169+
168170 print(json.dumps(result))
169171 PYTHON_SCRIPT
170-
172+
171173 # Run the analysis
172174 DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \
173175 ISSUE_BODY='${{ github.event.issue.body }}' \
174176 ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \
175177 ISSUE_NUMBER="${{ github.event.issue.number }}" \
176178 python check_discussion.py)
177-
179+
178180 echo "analysis<<EOF" >> $GITHUB_OUTPUT
179181 echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT
180182 echo "EOF" >> $GITHUB_OUTPUT
181-
183+
182184 # Extract whether it should be a discussion
183185 SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion')
184186 echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT
185-
187+
186188 # Extract confidence level
187189 CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence')
188190 echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
189-
191+
190192 - name: Comment with analysis
191193 uses: actions/github-script@v7
192194 with:
@@ -195,7 +197,7 @@
195197 const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true';
196198 const isPR = '${{ github.event_name }}' === 'pull_request';
197199 const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true';
198-
200+
199201 // Add similar issues section if found
200202 if (hasSimilar) {
201203 const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@@ -243,7 +245,7 @@
243245 comment += '\n';
244246 }
245247 }
246-
248+
247249 // Add discussion suggestion if applicable
248250 if (shouldBeDiscussion) {
249251 const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`);
@@ -280,7 +282,7 @@
280282
281283 comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n';
282284 }
283-
285+
284286 // Only comment if we have something to say
285287 if (comment) {
286288 comment += '\n---\n';
@@ -302,14 +304,14 @@
302304 });
303305 }
304306 }
305-
307+
306308 - name: Add labels
307309 if: github.event_name == 'issues'
308310 uses: actions/github-script@v7
309311 with:
310312 script: |
311313 const labels = [];
312-
314+
313315 // Check for duplicate
314316 if ('${{ steps.search.outputs.has_similar }}' === 'true') {
315317 const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@@ -319,7 +321,7 @@
319321 labels.push('potential-duplicate');
320322 }
321323 }
322-
324+
323325 // Check for discussion suggestion
324326 if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') {
325327 const confidence = '${{ steps.discussion_check.outputs.confidence }}';
@@ -330,7 +332,7 @@
330332 labels.push('discussion');
331333 }
332334 }
333-
335+
334336 // Add labels if any
335337 if (labels.length > 0) {
336338 await github.rest.issues.addLabels({
modified .github/workflows/submit-github-dependency-graph.yml +1 −1
@@ -12,7 +12,7 @@
1212 runs-on: ubuntu-latest
1313 steps:
1414 - name: Checkout sources
15- uses: actions/checkout@v4
15+ uses: actions/checkout@v5
1616 - name: Setup Java
1717 uses: actions/setup-java@v4
1818 with:
modified .github/workflows/vscode-version-bump.yml +1 −1
@@ -12,7 +12,7 @@
1212 runs-on: ubuntu-latest
1313 steps:
1414 - name: Checkout repository
15- uses: actions/checkout@v4
15+ uses: actions/checkout@v5
1616 with:
1717 fetch-depth: 0 # Fetch all history and tags
1818
modified README.md +14 −19
@@ -8,15 +8,6 @@
88
99 <div align="center">
1010
11-**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our
12-open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue)
13-and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
14-and [hub of models, rules, and MCP tools](https://hub.continue.dev)**
15-
16-</div>
17-
18-<div align="center">
19-
2011 <a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
2112 <img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
2213 </a>
@@ -32,38 +23,42 @@
3223
3324 <p></p>
3425
26+<div align="center">
27+
28+**Ship faster with Continuous AI**
29+
30+**Build and run custom agents across your IDE, terminal, and CI**
31+
32+</div>
33+
34+Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli)
35+
3536 ## Agent
3637
37-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
38+[Agent](/features/agent/quick-start) to work on development tasks together with AI
3839
3940 ![agent](docs/images/agent.gif)
4041
4142 ## Chat
4243
43-[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
44-the IDE
44+[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
4545
4646 ![chat](docs/images/chat.gif)
4747
4848 ## Edit
4949
50-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
51-file
50+[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
5251
5352 ![edit](docs/images/edit.gif)
5453
5554 ## Autocomplete
5655
57-[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
56+[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
5857
5958 ![autocomplete](docs/images/autocomplete.gif)
6059
6160 </div>
6261
63-## Getting Started
64-
65-Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install)
66-
6762 ## Contributing
6863
6964 Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
added actions/README.md +251 −0
@@ -0,0 +1,251 @@
1+# Continue PR Review Actions
2+
3+GitHub Actions that provide automated code reviews for pull requests using Continue CLI.
4+
5+## Available Actions
6+
7+This repository provides two GitHub Actions for different review styles:
8+
9+### 1. General Review Action
10+
11+Provides high-level PR assessment with overall feedback and recommendations.
12+
13+- **Path:** `continuedev/continue/actions/general-review@<commit-sha>`
14+- **Trigger:** `@continue-general-review`
15+- **Output:** Summary comment with strengths, issues, and recommendations
16+
17+### 2. Detailed Review Action
18+
19+Provides line-by-line inline comments on specific code changes.
20+
21+- **Path:** `continuedev/continue/actions/detailed-review@<commit-sha>`
22+- **Trigger:** `@continue-detailed-review`
23+- **Output:** Inline review comments on specific lines of code
24+
25+## Quick Start
26+
27+### Using Both Actions Together
28+
29+```yaml
30+name: PR Reviews
31+on:
32+ pull_request:
33+ types: [opened, ready_for_review]
34+ issue_comment:
35+ types: [created]
36+
37+permissions:
38+ contents: read
39+ pull-requests: write
40+ issues: write
41+
42+jobs:
43+ general-review:
44+ runs-on: ubuntu-latest
45+ timeout-minutes: 10
46+ steps:
47+ - uses: continuedev/continue/actions/general-review@<commit-sha>
48+ with:
49+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
50+ continue-org: "your-org-name"
51+ continue-config: "your-org-name/review-bot"
52+
53+ detailed-review:
54+ runs-on: ubuntu-latest
55+ timeout-minutes: 10
56+ steps:
57+ - uses: continuedev/continue/actions/detailed-review@<commit-sha>
58+ with:
59+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
60+ continue-org: "your-org-name"
61+ continue-config: "your-org-name/review-bot"
62+```
63+
64+### General Review Only
65+
66+```yaml
67+name: PR General Review
68+on:
69+ pull_request:
70+ types: [opened, ready_for_review]
71+ issue_comment:
72+ types: [created]
73+
74+permissions:
75+ contents: read
76+ pull-requests: write
77+ issues: write
78+
79+jobs:
80+ review:
81+ runs-on: ubuntu-latest
82+ timeout-minutes: 10
83+ steps:
84+ - uses: continuedev/continue/actions/general-review@<commit-sha>
85+ with:
86+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
87+ continue-org: "your-org-name"
88+ continue-config: "your-org-name/review-bot"
89+```
90+
91+### Detailed Review Only
92+
93+```yaml
94+name: PR Detailed Review
95+on:
96+ pull_request:
97+ types: [opened, ready_for_review]
98+ issue_comment:
99+ types: [created]
100+
101+permissions:
102+ contents: read
103+ pull-requests: write
104+ issues: write
105+
106+jobs:
107+ review:
108+ runs-on: ubuntu-latest
109+ timeout-minutes: 10
110+ steps:
111+ - uses: continuedev/continue/actions/detailed-review@<commit-sha>
112+ with:
113+ continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
114+ continue-org: "your-org-name"
115+ continue-config: "your-org-name/review-bot"
116+```
117+
118+## Inputs
119+
120+Both actions accept the same inputs:
121+
122+| Input | Description | Required |
123+| ------------------ | -------------------------------------- | -------- |
124+| `continue-api-key` | API key for Continue service | Yes |
125+| `continue-org` | Organization for Continue config | Yes |
126+| `continue-config` | Config path (e.g., "myorg/review-bot") | Yes |
127+
128+## Setup Requirements
129+
130+### 1. Continue API Key
131+
132+Add your Continue API key as a secret named `CONTINUE_API_KEY` in your repository:
133+
134+1. Go to your repository's Settings
135+2. Navigate to Secrets and variables → Actions
136+3. Click "New repository secret"
137+4. Name: `CONTINUE_API_KEY`
138+5. Value: Your Continue API key
139+
140+### 2. Continue Configuration
141+
142+Set up your review bot configuration in Continue:
143+
144+1. Create a configuration for your organization
145+2. Configure the review bot settings
146+3. Note your organization name and config path
147+
148+### 3. Workflow Permissions
149+
150+The workflow requires these permissions:
151+
152+- `contents: read` - To checkout and read repository code
153+- `pull-requests: write` - To post review comments on PRs
154+- `issues: write` - To respond to comment triggers
155+
156+## Triggering Reviews
157+
158+Both actions can be triggered in two ways:
159+
160+### Automatic Triggers
161+
162+- When a PR is opened by a team member (OWNER, MEMBER, or COLLABORATOR)
163+- When a PR is marked as "ready for review" by a team member
164+
165+### Manual Triggers
166+
167+Team members can trigger reviews by commenting on any pull request:
168+
169+- `@continue-general-review` - Triggers a general review
170+- `@continue-detailed-review` - Triggers a detailed inline review
171+
172+## Review Outputs
173+
174+### General Review Output
175+
176+The general review provides a structured comment that includes:
177+
178+- **Strengths**: What was done well in the PR
179+- **Issues Found**: Categorized by severity (Critical, High, Medium, Low)
180+- **Suggestions**: Improvement recommendations
181+- **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT)
182+
183+### Detailed Review Output
184+
185+The detailed review provides:
186+
187+- **Inline Comments**: Specific feedback on individual lines of code
188+- **Position Markers**: Comments appear directly on the changed lines
189+- **Review Summary**: Overall assessment of the changes
190+- **Actionable Feedback**: Specific suggestions for each issue found
191+
192+## How It Works
193+
194+### General Review Process
195+
196+1. Checks out repository code
197+2. Fetches PR diff using GitHub CLI
198+3. Generates a comprehensive review prompt
199+4. Runs Continue CLI with specified configuration
200+5. Posts review as a PR comment
201+
202+### Detailed Review Process
203+
204+1. Checks out repository code
205+2. Fetches PR diff with GitHub API positions
206+3. Annotates diff with position markers
207+4. Generates inline review prompt
208+5. Runs Continue CLI for detailed analysis
209+6. Posts inline comments using GitHub's review API
210+
211+## Versioning
212+
213+We recommend using a specific commit SHA for stability and predictability:
214+
215+- `@<commit-sha>` - Pins to a specific commit for maximum stability (recommended)
216+- `@main` - Uses the latest code from the main branch (for bleeding edge)
217+- `@v1` - Uses a version tag when available
218+
219+Example:
220+
221+```yaml
222+uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266
223+```
224+
225+## Troubleshooting
226+
227+### Review not triggering
228+
229+- Ensure the PR author or commenter has appropriate permissions (OWNER, MEMBER, or COLLABORATOR)
230+- Check that the workflow file is in the default branch
231+- Verify the Continue API key is correctly set as a repository secret
232+
233+### No review output generated
234+
235+- Check the action logs for any errors
236+- Verify your Continue configuration is correct
237+- Ensure your Continue API key is valid
238+
239+### Inline comments not appearing (Detailed Review)
240+
241+- Check that the PR has a valid diff
242+- Verify GitHub API permissions are correct
243+- Review action logs for position calculation errors
244+
245+## Support
246+
247+For issues or questions:
248+
249+- [Continue Documentation](https://docs.continue.dev)
250+- [GitHub Issues](https://github.com/continuedev/continue/issues)
251+- [Discord Community](https://discord.gg/vapESyrFmJ)
added actions/detailed-review/action.yml +350 −0
@@ -0,0 +1,350 @@
1+name: 'Continue Detailed PR Review'
2+description: 'Automated inline code review for pull requests using Continue CLI'
3+author: 'Continue Dev, Inc.'
4+
5+inputs:
6+ continue-api-key:
7+ description: 'API key for Continue service'
8+ required: true
9+ continue-org:
10+ description: 'Organization for Continue config'
11+ required: true
12+ continue-config:
13+ description: 'Config path to use (e.g., "myorg/review-bot")'
14+ required: true
15+
16+runs:
17+ using: 'composite'
18+ steps:
19+ - name: Checkout Repository
20+ uses: actions/checkout@v4
21+
22+ - name: Check Authorization
23+ shell: bash
24+ env:
25+ # Only move the dangerous check to env to prevent shell injection
26+ HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }}
27+ run: |
28+ # Check if this action should run based on event type and user permissions
29+ SHOULD_RUN="false"
30+
31+ if [ "${{ github.event_name }}" = "pull_request" ]; then
32+ # Check PR author association
33+ AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
34+ if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
35+ SHOULD_RUN="true"
36+ else
37+ echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
38+ fi
39+ elif [ "${{ github.event_name }}" = "issue_comment" ]; then
40+ # Check if it's a PR comment with the trigger phrase
41+ if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
42+ COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
43+ if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
44+ SHOULD_RUN="true"
45+ else
46+ echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
47+ fi
48+ else
49+ echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR"
50+ fi
51+ else
52+ echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported"
53+ fi
54+
55+ if [ "$SHOULD_RUN" != "true" ]; then
56+ echo "SKIP_REVIEW=true" >> $GITHUB_ENV
57+ exit 0
58+ fi
59+
60+ echo "SKIP_REVIEW=false" >> $GITHUB_ENV
61+
62+ - name: Setup Node.js
63+ if: env.SKIP_REVIEW != 'true'
64+ uses: actions/setup-node@v4
65+ with:
66+ node-version: 20
67+
68+ - name: Install Continue CLI
69+ if: env.SKIP_REVIEW != 'true'
70+ shell: bash
71+ run: npm install -g @continuedev/cli@1.4.25
72+
73+ - name: Build Inline Review Prompt
74+ if: env.SKIP_REVIEW != 'true'
75+ shell: bash
76+ env:
77+ GH_TOKEN: ${{ github.token }}
78+ run: |
79+ # Get PR number based on event type
80+ if [ "${{ github.event_name }}" = "pull_request" ]; then
81+ PR_NUMBER="${{ github.event.number }}"
82+ else
83+ # For issue_comment event on a PR
84+ PR_NUMBER="${{ github.event.issue.number }}"
85+ fi
86+
87+ # Get PR files with line numbers
88+ gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json
89+
90+ # Get PR diff with context
91+ gh pr diff $PR_NUMBER --color=never > pr_diff.txt
92+
93+ # Annotate diff with GitHub API positions
94+ node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt
95+
96+ # Debug: Show sample of annotated diff
97+ echo "=== SAMPLE OF ANNOTATED DIFF ==="
98+ head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt
99+ echo "=== END SAMPLE ==="
100+
101+ # Create review prompt for inline comments
102+ cat > inline_review_prompt.txt << 'EOF'
103+ You are conducting a detailed inline code review for a pull request.
104+
105+ Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code.
106+
107+ IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line.
108+
109+ Example of how to use the position markers:
110+ ```
111+ diff --git a/src/app.js b/src/app.js
112+ index abc123..def456 100644
113+ --- a/src/app.js
114+ +++ b/src/app.js
115+ @@ -10,4 +10,6 @@ function example() {
116+ [POS:1] console.log("context");
117+ [POS:2] - const old = "remove this";
118+ [POS:3] + const new = "add this";
119+ [POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4
120+ [POS:5] return result;
121+ [POS:6] + console.log("done");
122+ @@ -20,3 +22,4 @@ function another() {
123+ [POS:1] let x = 1;
124+ [POS:2] + let y = 2; <-- To comment here, use position: 2
125+ ```
126+
127+ To comment on a line, simply use the number from its [POS:N] marker as the position value.
128+ For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"}
129+
130+ Below is the annotated PR diff:
131+
132+ EOF
133+
134+ cat pr_diff_annotated.txt >> inline_review_prompt.txt
135+
136+ cat >> inline_review_prompt.txt << 'EOF'
137+
138+ Please analyze these changes and provide inline review comments in the following JSON format:
139+
140+ {
141+ "review_summary": "Overall assessment of the PR",
142+ "comments": [
143+ {
144+ "path": "path/to/file.js",
145+ "position": 4,
146+ "body": "Brief, specific comment about this line or section"
147+ }
148+ ]
149+ }
150+
151+ Focus on:
152+ 1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality
153+ 2. **High Priority**: Performance problems, incorrect logic, missing error handling
154+ 3. **Medium Priority**: Code style violations, potential edge cases, unclear code
155+ 4. **Low Priority**: Suggestions for improvement, refactoring opportunities
156+
157+ Guidelines for comments:
158+ - Be specific and actionable
159+ - Use the [POS:N] number shown in the diff as the position value
160+ - Keep comments concise but informative
161+ - Suggest concrete improvements when pointing out issues
162+ - Only comment on actual problems or important improvements
163+
164+ Important:
165+ - Output ONLY valid JSON, no markdown code blocks or backticks
166+ - Start your response with { and end with }
167+ - Use the exact number from [POS:N] markers as the position
168+ - Only comment on changed lines (lines with + or - prefix)
169+ - Comment on the most important issues first
170+ - Limit to maximum 20 most relevant comments
171+ EOF
172+
173+ - name: Run Continue CLI Inline Review
174+ if: env.SKIP_REVIEW != 'true'
175+ shell: bash
176+ env:
177+ CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
178+ run: |
179+ echo "Running Continue CLI for inline review..."
180+
181+ # Validate required inputs
182+ if [ -z "${{ inputs.continue-org }}" ]; then
183+ echo "Error: continue-org input is required"
184+ exit 1
185+ fi
186+
187+ if [ -z "${{ inputs.continue-config }}" ]; then
188+ echo "Error: continue-config input is required"
189+ exit 1
190+ fi
191+
192+ # Log the prompt for debugging
193+ echo "===== START REVIEW PROMPT ====="
194+ head -n 50 inline_review_prompt.txt
195+ echo "... [diff content] ..."
196+ tail -n 20 inline_review_prompt.txt
197+ echo "===== END REVIEW PROMPT ====="
198+
199+ # Run the CLI and capture JSON output
200+ cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
201+
202+ # Log the output for debugging
203+ echo "Initial Continue CLI output:"
204+ cat inline_review_raw.json
205+
206+ # Validate JSON output and use it directly
207+ if ! jq empty inline_review_raw.json 2>/dev/null; then
208+ echo "Error: Invalid JSON output from Continue CLI"
209+ exit 1
210+ fi
211+
212+ # Use the JSON output directly
213+ cp inline_review_raw.json inline_review.json
214+ echo "Review output:"
215+ cat inline_review.json
216+
217+ - name: Post Inline Review Comments
218+ if: env.SKIP_REVIEW != 'true'
219+ uses: actions/github-script@v7
220+ with:
221+ script: |
222+ const fs = require('fs');
223+
224+ try {
225+ // Read the review output
226+ let reviewData;
227+ try {
228+ const reviewContent = fs.readFileSync('inline_review.json', 'utf8');
229+ reviewData = JSON.parse(reviewContent);
230+ } catch (parseError) {
231+ console.log('Failed to parse review JSON:', parseError);
232+ reviewData = {
233+ review_summary: 'AI review completed but failed to parse output',
234+ comments: []
235+ };
236+ }
237+
238+ // Get PR number
239+ let prNumber;
240+ if (context.eventName === 'pull_request') {
241+ prNumber = context.payload.pull_request.number;
242+ } else {
243+ prNumber = context.payload.issue.number;
244+ }
245+
246+ // Get the latest commit SHA
247+ const { data: pr } = await github.rest.pulls.get({
248+ owner: context.repo.owner,
249+ repo: context.repo.repo,
250+ pull_number: prNumber
251+ });
252+
253+ const commitSha = pr.head.sha;
254+
255+ // Prepare review comments - filter out comments without required fields
256+ const allComments = reviewData.comments || [];
257+ const validComments = allComments.filter(comment =>
258+ comment.position &&
259+ comment.path &&
260+ comment.body &&
261+ typeof comment.position === 'number' &&
262+ comment.position > 0
263+ );
264+
265+ if (validComments.length < allComments.length) {
266+ console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`);
267+ const invalidComments = allComments.filter(c => !validComments.includes(c));
268+ console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
269+ }
270+
271+ const comments = validComments.map(comment => ({
272+ path: comment.path,
273+ position: comment.position,
274+ body: comment.body
275+ }));
276+
277+ // Debug: Log the positions we're trying to use
278+ console.log('Attempting to post comments with positions:');
279+ comments.forEach(c => {
280+ console.log(` ${c.path}: position ${c.position}`);
281+ });
282+
283+ // Create the review
284+ if (comments.length > 0) {
285+ try {
286+ await github.rest.pulls.createReview({
287+ owner: context.repo.owner,
288+ repo: context.repo.repo,
289+ pull_number: prNumber,
290+ commit_id: commitSha,
291+ body: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`,
292+ event: 'COMMENT',
293+ comments: comments
294+ });
295+ console.log(`Successfully created review with ${comments.length} inline comments`);
296+ } catch (reviewError) {
297+ console.log('Failed to create review:', reviewError.message);
298+
299+ // Fallback: post as a regular comment if review creation fails
300+ const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` +
301+ `*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` +
302+ `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
303+
304+ await github.rest.issues.createComment({
305+ issue_number: prNumber,
306+ owner: context.repo.owner,
307+ repo: context.repo.repo,
308+ body: fallbackBody
309+ });
310+ }
311+ } else {
312+ // No inline comments, just post the summary
313+ await github.rest.issues.createComment({
314+ issue_number: prNumber,
315+ owner: context.repo.owner,
316+ repo: context.repo.repo,
317+ body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
318+ `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`
319+ });
320+ }
321+
322+ // Add triggered by note if from comment
323+ if (context.eventName === 'issue_comment') {
324+ await github.rest.issues.createComment({
325+ issue_number: prNumber,
326+ owner: context.repo.owner,
327+ repo: context.repo.repo,
328+ body: `*Inline review triggered by @${context.payload.comment.user.login}*`
329+ });
330+ }
331+
332+ } catch (error) {
333+ console.log('Failed to post review:', error.message);
334+ console.log('Error details:', error);
335+ }
336+ env:
337+ GITHUB_TOKEN: ${{ github.token }}
338+
339+ - name: Upload Review Artifacts
340+ if: env.SKIP_REVIEW != 'true' && always()
341+ uses: actions/upload-artifact@v4
342+ with:
343+ name: inline-review-results
344+ path: |
345+ inline_review_raw.json
346+ inline_review.json
347+ inline_review_prompt.txt
348+ pr_diff.txt
349+ pr_diff_annotated.txt
350+ retention-days: 7
No newline at the end of the file
added actions/detailed-review/annotate-diff.js +96 −0
@@ -0,0 +1,96 @@
1+#!/usr/bin/env node
2+
3+/**
4+ * Annotates a git diff with GitHub API positions
5+ *
6+ * Takes a raw diff and adds [POS:N] markers with the correct
7+ * GitHub API positions (cumulative, with +1 between hunks)
8+ */
9+
10+const fs = require("fs");
11+
12+function annotateDiff(diffContent) {
13+ const lines = diffContent.split("\n");
14+ const output = [];
15+ let githubPos = 0;
16+ let inHunk = false;
17+
18+ for (const line of lines) {
19+ // Handle new file - reset position counter
20+ if (line.startsWith("diff --git")) {
21+ githubPos = 0;
22+ inHunk = false;
23+ output.push(line);
24+ continue;
25+ }
26+
27+ // Pass through other git headers unchanged
28+ if (
29+ line.startsWith("index ") ||
30+ line.startsWith("---") ||
31+ line.startsWith("+++") ||
32+ line.startsWith("rename ") ||
33+ line.startsWith("similarity ") ||
34+ line.startsWith("new file") ||
35+ line.startsWith("deleted file") ||
36+ line.startsWith("old mode") ||
37+ line.startsWith("new mode") ||
38+ line.startsWith("Binary files")
39+ ) {
40+ output.push(line);
41+ continue;
42+ }
43+
44+ // Handle hunk headers
45+ if (line.startsWith("@@")) {
46+ if (inHunk) {
47+ githubPos++; // GitHub's +1 between hunks
48+ }
49+ inHunk = true;
50+ output.push(line);
51+ continue;
52+ }
53+
54+ // Handle "no newline" marker - it counts as a position but isn't annotated
55+ if (line.startsWith("\\ No newline")) {
56+ if (inHunk) {
57+ githubPos++; // GitHub counts this as a position
58+ }
59+ output.push(line); // Don't annotate it
60+ continue;
61+ }
62+
63+ // Annotate actual diff lines with GitHub positions
64+ if (inHunk) {
65+ githubPos++;
66+ output.push(`[POS:${githubPos}] ${line}`);
67+ } else {
68+ output.push(line);
69+ }
70+ }
71+
72+ return output.join("\n");
73+}
74+
75+// Main
76+function main() {
77+ // Read diff from stdin or file
78+ let input = "";
79+
80+ if (process.argv.length > 2) {
81+ // Read from file
82+ input = fs.readFileSync(process.argv[2], "utf8");
83+ } else {
84+ // Read from stdin
85+ input = fs.readFileSync(0, "utf8");
86+ }
87+
88+ const annotated = annotateDiff(input);
89+ console.log(annotated);
90+}
91+
92+if (require.main === module) {
93+ main();
94+}
95+
96+module.exports = { annotateDiff };
added actions/detailed-review/annotate-diff.test.js +363 −0
@@ -0,0 +1,363 @@
1+const { annotateDiff } = require("./annotate-diff.js");
2+
3+describe("annotateDiff", () => {
4+ test("single file, single hunk", () => {
5+ const diff = `diff --git a/file.js b/file.js
6+index abc123..def456 100644
7+--- a/file.js
8++++ b/file.js
9+@@ -1,3 +1,4 @@
10+ line1
11+ line2
12++added line
13+ line3`;
14+
15+ const result = annotateDiff(diff);
16+ expect(result).toContain("[POS:1] line1");
17+ expect(result).toContain("[POS:2] line2");
18+ expect(result).toContain("[POS:3] +added line");
19+ expect(result).toContain("[POS:4] line3");
20+ });
21+
22+ test("single file, multiple hunks with +1 between", () => {
23+ const diff = `diff --git a/file.js b/file.js
24+index abc123..def456 100644
25+--- a/file.js
26++++ b/file.js
27+@@ -1,3 +1,3 @@
28+ line1
29+-old line
30++new line
31+ line3
32+@@ -10,3 +10,3 @@
33+ line10
34+-old line 11
35++new line 11
36+ line12`;
37+
38+ const result = annotateDiff(diff);
39+
40+ // First hunk
41+ expect(result).toContain("[POS:1] line1");
42+ expect(result).toContain("[POS:2] -old line");
43+ expect(result).toContain("[POS:3] +new line");
44+ expect(result).toContain("[POS:4] line3");
45+
46+ // Second hunk (should start at 6, because 4 lines + 1 for between hunks)
47+ expect(result).toContain("[POS:6] line10");
48+ expect(result).toContain("[POS:7] -old line 11");
49+ expect(result).toContain("[POS:8] +new line 11");
50+ expect(result).toContain("[POS:9] line12");
51+ });
52+
53+ test("multiple files reset position counter", () => {
54+ const diff = `diff --git a/file1.js b/file1.js
55+index abc123..def456 100644
56+--- a/file1.js
57++++ b/file1.js
58+@@ -1,2 +1,2 @@
59+ line1
60+-old
61++new
62+diff --git a/file2.js b/file2.js
63+index abc123..def456 100644
64+--- a/file2.js
65++++ b/file2.js
66+@@ -1,2 +1,2 @@
67+ first
68+-old2
69++new2`;
70+
71+ const result = annotateDiff(diff);
72+
73+ // File 1
74+ expect(result).toContain("[POS:1] line1");
75+ expect(result).toContain("[POS:2] -old");
76+ expect(result).toContain("[POS:3] +new");
77+
78+ // File 2 - positions should reset
79+ const file2Section = result.split("diff --git a/file2.js")[1];
80+ expect(file2Section).toContain("[POS:1] first");
81+ expect(file2Section).toContain("[POS:2] -old2");
82+ expect(file2Section).toContain("[POS:3] +new2");
83+ });
84+
85+ test("handles new file", () => {
86+ const diff = `diff --git a/newfile.js b/newfile.js
87+new file mode 100644
88+index 0000000..abc123
89+--- /dev/null
90++++ b/newfile.js
91+@@ -0,0 +1,3 @@
92++line1
93++line2
94++line3`;
95+
96+ const result = annotateDiff(diff);
97+ expect(result).toContain("new file mode 100644");
98+ expect(result).toContain("[POS:1] +line1");
99+ expect(result).toContain("[POS:2] +line2");
100+ expect(result).toContain("[POS:3] +line3");
101+ });
102+
103+ test("handles deleted file", () => {
104+ const diff = `diff --git a/deleted.js b/deleted.js
105+deleted file mode 100644
106+index abc123..0000000
107+--- a/deleted.js
108++++ /dev/null
109+@@ -1,3 +0,0 @@
110+-line1
111+-line2
112+-line3`;
113+
114+ const result = annotateDiff(diff);
115+ expect(result).toContain("deleted file mode 100644");
116+ expect(result).toContain("[POS:1] -line1");
117+ expect(result).toContain("[POS:2] -line2");
118+ expect(result).toContain("[POS:3] -line3");
119+ });
120+
121+ test("handles renamed file with changes", () => {
122+ const diff = `diff --git a/old-name.js b/new-name.js
123+similarity index 95%
124+rename from old-name.js
125+rename to new-name.js
126+index abc123..def456 100644
127+--- a/old-name.js
128++++ b/new-name.js
129+@@ -1,3 +1,3 @@
130+ line1
131+-old line
132++new line
133+ line3`;
134+
135+ const result = annotateDiff(diff);
136+ expect(result).toContain("rename from old-name.js");
137+ expect(result).toContain("rename to new-name.js");
138+ expect(result).toContain("[POS:1] line1");
139+ expect(result).toContain("[POS:2] -old line");
140+ expect(result).toContain("[POS:3] +new line");
141+ });
142+
143+ test("handles no newline at end of file", () => {
144+ const diff = `diff --git a/file.js b/file.js
145+index abc123..def456 100644
146+--- a/file.js
147++++ b/file.js
148+@@ -1,2 +1,2 @@
149+ line1
150+-old line
151+\\ No newline at end of file
152++new line
153+\\ No newline at end of file`;
154+
155+ const result = annotateDiff(diff);
156+ expect(result).toContain("[POS:1] line1");
157+ expect(result).toContain("[POS:2] -old line");
158+ // Position 3 is the first "No newline" marker (not annotated but counted)
159+ expect(result).toContain("\\ No newline at end of file");
160+ expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3
161+ // Position 5 is the second "No newline" marker (not annotated but counted)
162+ expect(result).toContain("\\ No newline at end of file");
163+ // No newline markers should not get [POS:N] annotations
164+ expect(result).not.toContain("[POS:3] \\");
165+ expect(result).not.toContain("[POS:5] \\");
166+ });
167+
168+ test("handles file mode changes", () => {
169+ const diff = `diff --git a/script.sh b/script.sh
170+old mode 100644
171+new mode 100755
172+index abc123..def456 100644
173+--- a/script.sh
174++++ b/script.sh
175+@@ -1,2 +1,2 @@
176+ #!/bin/bash
177+-echo "old"
178++echo "new"`;
179+
180+ const result = annotateDiff(diff);
181+ expect(result).toContain("old mode 100644");
182+ expect(result).toContain("new mode 100755");
183+ expect(result).toContain("[POS:1] #!/bin/bash");
184+ expect(result).toContain('[POS:2] -echo "old"');
185+ expect(result).toContain('[POS:3] +echo "new"');
186+ });
187+
188+ test("empty diff returns empty", () => {
189+ const diff = "";
190+ const result = annotateDiff(diff);
191+ expect(result).toBe("");
192+ });
193+
194+ test("handles binary files - modified", () => {
195+ const diff = `diff --git a/image.png b/image.png
196+index abc123..def456 100644
197+Binary files a/image.png and b/image.png differ`;
198+
199+ const result = annotateDiff(diff);
200+ expect(result).toContain("diff --git a/image.png b/image.png");
201+ expect(result).toContain("Binary files a/image.png and b/image.png differ");
202+ // Binary files line should not be annotated
203+ expect(result).not.toContain("[POS:");
204+ });
205+
206+ test("handles binary files - added", () => {
207+ const diff = `diff --git a/newimage.png b/newimage.png
208+new file mode 100644
209+index 0000000..abc123
210+Binary files /dev/null and b/newimage.png differ`;
211+
212+ const result = annotateDiff(diff);
213+ expect(result).toContain("diff --git a/newimage.png b/newimage.png");
214+ expect(result).toContain("new file mode 100644");
215+ expect(result).toContain(
216+ "Binary files /dev/null and b/newimage.png differ",
217+ );
218+ // Binary files line should not be annotated
219+ expect(result).not.toContain("[POS:");
220+ });
221+
222+ test("handles binary files - deleted", () => {
223+ const diff = `diff --git a/oldimage.png b/oldimage.png
224+deleted file mode 100644
225+index abc123..0000000
226+Binary files a/oldimage.png and /dev/null differ`;
227+
228+ const result = annotateDiff(diff);
229+ expect(result).toContain("diff --git a/oldimage.png b/oldimage.png");
230+ expect(result).toContain("deleted file mode 100644");
231+ expect(result).toContain(
232+ "Binary files a/oldimage.png and /dev/null differ",
233+ );
234+ // Binary files line should not be annotated
235+ expect(result).not.toContain("[POS:");
236+ });
237+
238+ test("handles mixed text and binary files", () => {
239+ const diff = `diff --git a/text.js b/text.js
240+index abc123..def456 100644
241+--- a/text.js
242++++ b/text.js
243+@@ -1,2 +1,2 @@
244+ line1
245+-old
246++new
247+diff --git a/image.png b/image.png
248+index 111111..222222 100644
249+Binary files a/image.png and b/image.png differ
250+diff --git a/another.js b/another.js
251+index 333333..444444 100644
252+--- a/another.js
253++++ b/another.js
254+@@ -1,1 +1,1 @@
255+-foo
256++bar`;
257+
258+ const result = annotateDiff(diff);
259+
260+ // First file (text)
261+ expect(result).toContain("[POS:1] line1");
262+ expect(result).toContain("[POS:2] -old");
263+ expect(result).toContain("[POS:3] +new");
264+
265+ // Second file (binary) - no positions
266+ expect(result).toContain("Binary files a/image.png and b/image.png differ");
267+
268+ // Third file (text) - positions reset
269+ const lastFileSection = result.split("diff --git a/another.js")[1];
270+ expect(lastFileSection).toContain("[POS:1] -foo");
271+ expect(lastFileSection).toContain("[POS:2] +bar");
272+ });
273+
274+ test("multiple no newline markers accumulate positions", () => {
275+ const diff = `diff --git a/file.js b/file.js
276+index abc123..def456 100644
277+--- a/file.js
278++++ b/file.js
279+@@ -1,3 +1,3 @@
280+ line1
281+-old1
282+\\ No newline at end of file
283++new1
284+\\ No newline at end of file
285+@@ -10,3 +10,3 @@
286+ line10
287+-old2
288+\\ No newline at end of file
289++new2
290+\\ No newline at end of file`;
291+
292+ const result = annotateDiff(diff);
293+
294+ // First hunk
295+ expect(result).toContain("[POS:1] line1");
296+ expect(result).toContain("[POS:2] -old1");
297+ // Position 3 is the first "No newline" marker
298+ expect(result).toContain("[POS:4] +new1");
299+ // Position 5 is the second "No newline" marker
300+
301+ // Second hunk (starts at position 7 = 5 + 1 for between hunks + 1)
302+ expect(result).toContain("[POS:7] line10");
303+ expect(result).toContain("[POS:8] -old2");
304+ // Position 9 is the third "No newline" marker
305+ expect(result).toContain("[POS:10] +new2");
306+ // Position 11 is the fourth "No newline" marker
307+
308+ // Verify "No newline" markers are not annotated
309+ expect(result).not.toContain("[POS:3] \\");
310+ expect(result).not.toContain("[POS:5] \\");
311+ expect(result).not.toContain("[POS:9] \\");
312+ expect(result).not.toContain("[POS:11] \\");
313+ });
314+
315+ test("complex multi-file, multi-hunk diff", () => {
316+ const diff = `diff --git a/src/app.js b/src/app.js
317+index abc123..def456 100644
318+--- a/src/app.js
319++++ b/src/app.js
320+@@ -10,4 +10,5 @@ function example() {
321+ console.log("start");
322+ const x = 1;
323+- const y = 2;
324++ const y = 3;
325++ const z = 4;
326+ return x + y;
327+@@ -20,3 +21,4 @@ function another() {
328+ let a = 1;
329+ let b = 2;
330++ let c = 3;
331+ return a + b;
332+diff --git a/src/util.js b/src/util.js
333+index 111111..222222 100644
334+--- a/src/util.js
335++++ b/src/util.js
336+@@ -1,2 +1,3 @@
337++import fs from 'fs';
338+ export function util() {
339+ return true;`;
340+
341+ const result = annotateDiff(diff);
342+
343+ // src/app.js - first hunk
344+ expect(result).toContain('[POS:1] console.log("start");');
345+ expect(result).toContain("[POS:2] const x = 1;");
346+ expect(result).toContain("[POS:3] - const y = 2;");
347+ expect(result).toContain("[POS:4] + const y = 3;");
348+ expect(result).toContain("[POS:5] + const z = 4;");
349+ expect(result).toContain("[POS:6] return x + y;");
350+
351+ // src/app.js - second hunk (7 = 6 + 1 for between hunks)
352+ expect(result).toContain("[POS:8] let a = 1;");
353+ expect(result).toContain("[POS:9] let b = 2;");
354+ expect(result).toContain("[POS:10] + let c = 3;");
355+ expect(result).toContain("[POS:11] return a + b;");
356+
357+ // src/util.js - new file, positions reset
358+ const utilSection = result.split("diff --git a/src/util.js")[1];
359+ expect(utilSection).toContain("[POS:1] +import fs from 'fs';");
360+ expect(utilSection).toContain("[POS:2] export function util() {");
361+ expect(utilSection).toContain("[POS:3] return true;");
362+ });
363+});
added actions/detailed-review/package.json +19 −0
@@ -0,0 +1,19 @@
1+{
2+ "name": "@continue/pr-review-scripts",
3+ "version": "1.0.0",
4+ "private": true,
5+ "description": "Scripts for Continue PR Review Action",
6+ "scripts": {
7+ "test": "jest",
8+ "test:watch": "jest --watch"
9+ },
10+ "devDependencies": {
11+ "jest": "^29.7.0"
12+ },
13+ "jest": {
14+ "testEnvironment": "node",
15+ "testMatch": [
16+ "**/*.test.js"
17+ ]
18+ }
19+}
added actions/general-review/action.yml +228 −0
@@ -0,0 +1,228 @@
1+name: 'Continue PR Review'
2+description: 'Automated code review for pull requests using Continue CLI'
3+author: 'Continue Dev, Inc.'
4+
5+inputs:
6+ continue-api-key:
7+ description: 'API key for Continue service'
8+ required: true
9+ continue-org:
10+ description: 'Organization for Continue config'
11+ required: true
12+ continue-config:
13+ description: 'Config path to use (e.g., "myorg/review-bot")'
14+ required: true
15+
16+runs:
17+ using: 'composite'
18+ steps:
19+ - name: Checkout Repository
20+ uses: actions/checkout@v4
21+
22+ - name: Check Authorization
23+ shell: bash
24+ env:
25+ # Only move the dangerous check to env to prevent shell injection
26+ HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }}
27+ run: |
28+ # Check if this action should run based on event type and user permissions
29+ SHOULD_RUN="false"
30+
31+ if [ "${{ github.event_name }}" = "pull_request" ]; then
32+ # Check PR author association
33+ AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
34+ if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
35+ SHOULD_RUN="true"
36+ else
37+ echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
38+ fi
39+ elif [ "${{ github.event_name }}" = "issue_comment" ]; then
40+ # Check if it's a PR comment with the trigger phrase
41+ if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
42+ COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
43+ if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
44+ SHOULD_RUN="true"
45+ else
46+ echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
47+ fi
48+ else
49+ echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR"
50+ fi
51+ else
52+ echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
53+ fi
54+
55+ echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
56+
57+ - name: Setup Node.js
58+ if: env.SHOULD_RUN == 'true'
59+ uses: actions/setup-node@v4
60+ with:
61+ node-version: 20
62+
63+ - name: Install Continue CLI
64+ if: env.SHOULD_RUN == 'true'
65+ shell: bash
66+ run: npm install -g @continuedev/cli@1.4.25
67+
68+ - name: Build PR Review Prompt
69+ if: env.SHOULD_RUN == 'true'
70+ shell: bash
71+ env:
72+ GH_TOKEN: ${{ github.token }}
73+ run: |
74+ # Get PR number based on event type
75+ if [ "${{ github.event_name }}" = "pull_request" ]; then
76+ PR_NUMBER="${{ github.event.number }}"
77+ else
78+ # For issue_comment event on a PR
79+ PR_NUMBER="${{ github.event.issue.number }}"
80+ fi
81+
82+ # Get PR diff
83+ gh pr diff $PR_NUMBER > pr_diff.txt
84+
85+ # Create review prompt
86+ cat > review_prompt.txt << 'EOF'
87+ You are conducting a code review for a pull request. Below is the git diff showing all the changes:
88+
89+ EOF
90+
91+ echo "--- PR DIFF START ---" >> review_prompt.txt
92+ cat pr_diff.txt >> review_prompt.txt
93+ echo "--- PR DIFF END ---" >> review_prompt.txt
94+
95+ cat >> review_prompt.txt << 'EOF'
96+
97+ Please analyze these changes and provide a comprehensive code review. Consider:
98+
99+ 1. **Code Quality**: Are there any bugs, performance issues, or code smells?
100+ 2. **Best Practices**: Does the code follow established patterns and conventions?
101+ 3. **Security**: Are there any potential security vulnerabilities?
102+ 4. **Testing**: Are appropriate tests included or updated?
103+ 5. **Documentation**: Is documentation adequate for the changes?
104+ 6. **Architecture**: Do the changes fit well with the existing codebase structure?
105+
106+ You can use the available tools to explore the codebase and understand context better.
107+
108+ Format your response as a markdown code review with the following structure:
109+
110+ ## Code Review Summary
111+
112+ ### ✅ Strengths
113+ - **[Aspect]**: [Description of what was done well]
114+
115+ ### ⚠️ Issues Found
116+
117+ Only include the severity subheaders below if you actually found issues at that level:
118+
119+ #### Critical
120+ - **[Issue Title]**: [Description of critical issues that must be fixed before merging]
121+
122+ #### High
123+ - **[Issue Title]**: [Description of high-priority issues that should be fixed]
124+
125+ #### Medium
126+ - **[Issue Title]**: [Description of issues that should be addressed]
127+
128+ #### Low
129+ - **[Issue Title]**: [Description of minor issues or nice-to-have improvements]
130+
131+
132+ ### 💡 Suggestions
133+ - **[Suggestion Title]**: [Description of improvement recommendations]
134+
135+ ### 🚀 Overall Assessment
136+ [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT]
137+
138+ Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
139+ EOF
140+
141+ - name: Run Continue CLI Review
142+ if: env.SHOULD_RUN == 'true'
143+ shell: bash
144+ env:
145+ CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
146+ CONTINUE_ORG: ${{ inputs.continue-org }}
147+ CONTINUE_CONFIG: ${{ inputs.continue-config }}
148+ run: |
149+ echo "Running Continue CLI with prompt:"
150+ echo "=================================="
151+ cat review_prompt.txt
152+ echo "=================================="
153+ echo ""
154+
155+ # Validate inputs to prevent command injection
156+ if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
157+ echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
158+ exit 1
159+ fi
160+
161+ if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
162+ echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
163+ exit 1
164+ fi
165+
166+ # Run the CLI with validated config
167+ cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
168+
169+ - name: Upload Review Results
170+ if: env.SHOULD_RUN == 'true' && always()
171+ uses: actions/upload-artifact@v4
172+ with:
173+ name: code-review-results
174+ path: |
175+ code_review.md
176+ review_prompt.txt
177+ pr_diff.txt
178+ retention-days: 30
179+
180+ - name: Comment PR with Review
181+ if: env.SHOULD_RUN == 'true' && always()
182+ uses: actions/github-script@v7
183+ with:
184+ script: |
185+ const fs = require('fs');
186+
187+ try {
188+ let reviewContent = '';
189+
190+ if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
191+ reviewContent = fs.readFileSync('code_review.md', 'utf8');
192+ } else {
193+ reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.';
194+ }
195+
196+ // Get PR number based on event type
197+ let prNumber;
198+ if (context.eventName === 'pull_request') {
199+ prNumber = context.payload.pull_request.number;
200+ } else {
201+ // For issue_comment event
202+ prNumber = context.payload.issue.number;
203+ }
204+
205+ // Add a header if triggered by comment
206+ if (context.eventName === 'issue_comment') {
207+ reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`;
208+ }
209+
210+ // Add instructions for re-review
211+ reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*';
212+
213+ // Create new comment
214+ await github.rest.issues.createComment({
215+ issue_number: prNumber,
216+ owner: context.repo.owner,
217+ repo: context.repo.repo,
218+ body: reviewContent
219+ });
220+ console.log(`Successfully created new comment on PR #${prNumber}`);
221+ } catch (error) {
222+ console.log('Failed to post comment:', error.message);
223+ console.log('Error details:', error);
224+ }
225+
226+branding:
227+ icon: 'code'
228+ color: 'blue'
No newline at the end of the file
modified core/.gitignore +3 −1
@@ -4,4 +4,6 @@
44 npm-debug.log*
55 .env
66 test/.continue-test
7-coverage
No newline at the end of the file
7+coverage
8+# Sentry Config File
9+.sentryclirc
modified core/codeRenderer/CodeRenderer.ts +52 −31
@@ -20,7 +20,7 @@
2020 Highlighter,
2121 } from "shiki";
2222 import { DiffLine } from "..";
23-import { escapeForSVG, kebabOfStr } from "../util/text";
23+import { escapeForSVG, kebabOfThemeStr } from "../util/text";
2424
2525 interface CodeRendererOptions {
2626 themesDir?: string;
@@ -70,28 +70,29 @@
7070
7171 public async setTheme(themeName: string): Promise<void> {
7272 if (
73- this.themeExists(kebabOfStr(themeName)) ||
73+ this.themeExists(kebabOfThemeStr(themeName)) ||
7474 themeName === "Default Dark Modern"
7575 ) {
7676 this.currentTheme =
7777 themeName === "Default Dark Modern"
7878 ? "dark-plus"
79- : kebabOfStr(themeName);
80-
81- this.highlighter = await getSingletonHighlighter({
82- langs: ["typescript"],
83- themes: [this.currentTheme],
84- });
85-
86- const th = this.highlighter.getTheme(this.currentTheme);
87-
88- this.editorBackground = th.bg;
89- this.editorForeground = th.fg;
90- this.editorLineHighlight =
91- th.colors!["editor.lineHighlightBackground"] ?? "#000000";
79+ : kebabOfThemeStr(themeName);
9280 } else {
81+ // Fallback to default theme for unsupported themes.
9382 this.currentTheme = "dark-plus";
9483 }
84+
85+ // Always initialize the highlighter with the current theme.
86+ this.highlighter = await getSingletonHighlighter({
87+ langs: ["typescript"],
88+ themes: [this.currentTheme],
89+ });
90+
91+ const th = this.highlighter.getTheme(this.currentTheme);
92+ this.editorBackground = th.bg;
93+ this.editorForeground = th.fg;
94+ this.editorLineHighlight =
95+ th.colors!["editor.lineHighlightBackground"] ?? "#000000";
9596 }
9697
9798 async init(): Promise<void> {}
@@ -243,7 +244,10 @@
243244 );
244245 const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
245246
246- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
247+ const lines = code.split("\n");
248+ const actualHeight = lines.length * options.lineHeight;
249+
250+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${actualHeight}" shape-rendering="crispEdges">
247251 <style>
248252 :root {
249253 --purple: rgb(112, 114, 209);
@@ -252,7 +256,7 @@
252256 }
253257 </style>
254258 <g>
255- <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
259+ <rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
256260 ${lineBackgrounds}
257261 ${guts}
258262 </g>
@@ -317,29 +321,46 @@
317321 const y = index * options.lineHeight;
318322 const isFirst = index === 0;
319323 const isLast = index === lines.length - 1;
324+ const isSingleLine = isFirst && isLast;
320325 const radius = 10;
326+
327+ // Handle single line case (both first and last)
328+ if (isSingleLine) {
329+ return `<path d="M ${radius} ${y}
330+ L ${options.dimensions.width - radius} ${y}
331+ Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
332+ L ${options.dimensions.width} ${y + options.lineHeight - radius}
333+ Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
334+ L ${radius} ${y + options.lineHeight}
335+ Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
336+ L ${0} ${y + radius}
337+ Q ${0} ${y} ${radius} ${y}
338+ Z"
339+ fill="${bgColor}" />`;
340+ }
341+
321342 // SVG notes:
322343 // By default SVGs have anti-aliasing on.
323344 // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
324345 // Turning it off with 'shape-rendering="crispEdges"' solves the issue.
325346 return isFirst
326347 ? `<path d="M ${0} ${y + options.lineHeight}
327- L ${0} ${y + radius}
328- Q ${0} ${y} ${radius} ${y}
329- L ${options.dimensions.width - radius} ${y}
330- Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
331- L ${options.dimensions.width} ${y + options.lineHeight}
332- Z"
333- fill="${bgColor}" />`
348+ L ${0} ${y + radius}
349+ Q ${0} ${y} ${radius} ${y}
350+ L ${options.dimensions.width - radius} ${y}
351+ Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
352+ L ${options.dimensions.width} ${y + options.lineHeight}
353+ Z"
354+ fill="${bgColor}" />`
334355 : isLast
335356 ? `<path d="M ${0} ${y}
336- L ${0} ${y + options.lineHeight - radius}
337- Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
338- L ${options.dimensions.width - radius} ${y + options.lineHeight}
339- Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
340- L ${options.dimensions.width} ${y}
341- Z"
342- fill="${bgColor}" />`
357+ L ${0} ${y + options.lineHeight - radius}
358+ Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
359+ L ${options.dimensions.width - radius} ${y + options.lineHeight}
360+ Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
361+ L ${options.dimensions.width} ${y}
362+ Z"
363+ fill="${bgColor}" />`
343364 : `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
344365 })
345366 .join("\n");
modified core/config/ConfigHandler.ts +44 −29
@@ -17,7 +17,8 @@
1717 ControlPlaneSessionInfo,
1818 } from "../control-plane/AuthTypes.js";
1919 import { getControlPlaneEnv } from "../control-plane/env.js";
20-import { logger } from "../util/logger.js";
20+import { PolicySingleton } from "../control-plane/PolicySingleton.js";
21+import { Logger } from "../util/Logger.js";
2122 import { Telemetry } from "../util/posthog.js";
2223 import {
2324 ASSISTANTS,
@@ -45,7 +46,7 @@
4546
4647 private organizations: OrgWithProfiles[] = [];
4748 currentProfile: ProfileLifecycleManager | null;
48- currentOrg: OrgWithProfiles;
49+ currentOrg: OrgWithProfiles | null;
4950 totalConfigReloads: number = 0;
5051
5152 public isInitialized: Promise<void>;
@@ -83,16 +84,9 @@
8384 this.ide,
8485 );
8586
86- // Just to be safe, always force a default personal org with local profile manager
87- this.currentProfile = this.globalLocalProfileManager;
88- const personalOrg: OrgWithProfiles = {
89- currentProfile: this.globalLocalProfileManager,
90- profiles: [this.globalLocalProfileManager],
91- ...this.PERSONAL_ORG_DESC,
92- };
93-
94- this.currentOrg = personalOrg;
95- this.organizations = [personalOrg];
87+ this.currentOrg = null;
88+ this.currentProfile = null;
89+ this.organizations = [];
9690
9791 this.initter = new EventEmitter();
9892 this.isInitialized = new Promise((resolve) => {
@@ -132,10 +126,10 @@
132126 const firstNonPersonal = orgs.find(
133127 (org) => org.id !== this.PERSONAL_ORG_DESC.id,
134128 );
135- const fallback = firstNonPersonal ?? orgs[0];
136- // note, ignoring case of zero orgs since should never happen
129+ const fallback: OrgWithProfiles | null =
130+ firstNonPersonal ?? orgs[0] ?? null;
137131
138- let selectedOrg: OrgWithProfiles;
132+ let selectedOrg: OrgWithProfiles | null;
139133 if (currentSelection) {
140134 const match = orgs.find((org) => org.id === currentSelection);
141135 if (match) {
@@ -153,12 +147,12 @@
153147
154148 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
155149 ...selectedOrgs,
156- [workspaceId]: selectedOrg.id,
150+ [workspaceId]: selectedOrg?.id,
157151 });
158152
159153 this.organizations = orgs;
160154 this.currentOrg = selectedOrg;
161- this.currentProfile = selectedOrg.currentProfile;
155+ this.currentProfile = selectedOrg?.currentProfile;
162156
163157 await this.reloadConfig(reason, errors);
164158 } catch (e) {
@@ -179,10 +173,27 @@
179173 const isSignedIn = await this.controlPlaneClient.isSignedIn();
180174 if (isSignedIn) {
181175 try {
182- const orgDescs = await this.controlPlaneClient.listOrganizations();
176+ // TODO use policy returned with org, not policy endpoint
177+ const policyResponse = await this.controlPlaneClient.getPolicy();
178+ PolicySingleton.getInstance().policy = policyResponse;
179+ const orgDescriptions =
180+ await this.controlPlaneClient.listOrganizations();
181+ const orgsWithPolicy = orgDescriptions.map((d) => ({
182+ ...d,
183+ policy: policyResponse?.policy,
184+ }));
185+
186+ if (policyResponse?.policy?.allowOtherOrgs === false) {
187+ if (orgsWithPolicy.length === 0) {
188+ return { orgs: [] };
189+ } else {
190+ const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
191+ return { orgs: [firstOrg] };
192+ }
193+ }
183194 const orgs = await Promise.all([
184195 this.getPersonalHubOrg(),
185- ...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
196+ ...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
186197 ]);
187198 // TODO make try/catch more granular here, to catch specific org errors
188199 return { orgs };
@@ -426,7 +437,7 @@
426437
427438 // Org id: check id validity, save selection, switch and reload
428439 async setSelectedOrgId(orgId: string, profileId?: string) {
429- if (orgId === this.currentOrg.id) {
440+ if (orgId === this.currentOrg?.id) {
430441 return;
431442 }
432443 const org = this.organizations.find((org) => org.id === orgId);
@@ -454,6 +465,9 @@
454465
455466 // Profile id: check id validity, save selection, switch and reload
456467 async setSelectedProfileId(profileId: string) {
468+ if (!this.currentOrg) {
469+ throw new Error(`No org selected`);
470+ }
457471 if (
458472 this.currentProfile &&
459473 profileId === this.currentProfile.profileDescription.id
@@ -490,10 +504,7 @@
490504 if (!this.currentProfile) {
491505 return {
492506 config: undefined,
493- errors: [
494- { message: "Current profile not found", fatal: true },
495- ...(injectErrors ?? []),
496- ],
507+ errors: injectErrors,
497508 configLoadInterrupted: true,
498509 };
499510 }
@@ -562,7 +573,7 @@
562573 if (!this.currentProfile) {
563574 return {
564575 config: undefined,
565- errors: [{ message: "Current profile not found", fatal: true }],
576+ errors: undefined,
566577 configLoadInterrupted: true,
567578 };
568579 }
@@ -575,7 +586,7 @@
575586 if (!this.currentProfile) {
576587 return {
577588 config: undefined,
578- errors: [{ message: "Current profile not found", fatal: true }],
589+ errors: undefined,
579590 configLoadInterrupted: true,
580591 };
581592 }
@@ -585,7 +596,7 @@
585596 );
586597
587598 if (config.errors?.length) {
588- logger.warn("Errors loading config: ", config.errors);
599+ Logger.error("Errors loading config: ", config.errors);
589600 }
590601 return config;
591602 }
@@ -598,11 +609,15 @@
598609 if (!openProfileId) {
599610 return;
600611 }
601- const profile = this.currentOrg.profiles.find(
612+ const profile = this.currentOrg?.profiles.find(
602613 (p) => p.profileDescription.id === openProfileId,
603614 );
615+ if (!profile) {
616+ console.error(`Profile ${profileId} not found`);
617+ return;
618+ }
604619
605- if (profile?.profileDescription.profileType === "local") {
620+ if (profile.profileDescription.profileType === "local") {
606621 const configFile = element?.sourceFile ?? profile.profileDescription.uri;
607622 await this.ide.openFile(configFile);
608623 } else {
modified core/config/ConfigHandler.vitest.ts +1 −1
@@ -10,7 +10,7 @@
1010
1111 describe.skip("Test the ConfigHandler and E2E config loading", () => {
1212 test("should show only local profile", () => {
13- const profiles = testConfigHandler.currentOrg.profiles;
13+ const profiles = testConfigHandler.currentOrg?.profiles;
1414 expect(profiles?.length).toBe(1);
1515 expect(profiles?.[0].profileDescription.id).toBe("local");
1616
modified core/config/ProfileLifecycleManager.ts +8 −0
@@ -2,6 +2,7 @@
22 ConfigResult,
33 ConfigValidationError,
44 FullSlug,
5+ Policy,
56 } from "@continuedev/config-yaml";
67
78 import {
@@ -11,6 +12,7 @@
1112 IDE,
1213 } from "../index.js";
1314
15+import { Logger } from "../util/Logger.js";
1416 import { finalToBrowserConfig } from "./load.js";
1517 import { IProfileLoader } from "./profile/IProfileLoader.js";
1618
@@ -30,6 +32,7 @@
3032 iconUrl: string;
3133 name: string;
3234 slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
35+ policy?: Policy;
3336 }
3437
3538 export type OrgWithProfiles = OrganizationDescription & {
@@ -96,6 +99,11 @@
9699 try {
97100 result = await this.profileLoader.doLoadConfig();
98101 } catch (e) {
102+ // Capture config loading system failures to Sentry
103+ Logger.error(e, {
104+ context: "profile_config_loading",
105+ });
106+
99107 const message =
100108 e instanceof Error
101109 ? `${e.message}\n${e.stack ? e.stack : ""}`
modified core/config/markdown/loadCodebaseRules.ts +17 −3
@@ -5,7 +5,7 @@
55 import { IDE, RuleWithSource } from "../..";
66 import { walkDirs } from "../../indexing/walkDir";
77 import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
8-import { getUriPathBasename } from "../../util/uri";
8+import { findUriInDirs, getUriPathBasename } from "../../util/uri";
99
1010 export class CodebaseRulesCache {
1111 private static instance: CodebaseRulesCache | null = null;
@@ -26,7 +26,14 @@
2626 }
2727 async update(ide: IDE, uri: string) {
2828 const content = await ide.readFile(uri);
29- const rule = markdownToRule(content, { uriType: "file", filePath: uri });
29+ const { relativePathOrBasename } = findUriInDirs(
30+ uri,
31+ await ide.getWorkspaceDirs(),
32+ );
33+ const rule = markdownToRule(content, {
34+ uriType: "file",
35+ fileUri: relativePathOrBasename,
36+ });
3037 const ruleWithSource: RuleWithSource = {
3138 ...rule,
3239 source: "colocated-markdown",
@@ -68,7 +75,14 @@
6875 for (const filePath of rulesMdFiles) {
6976 try {
7077 const content = await ide.readFile(filePath);
71- const rule = markdownToRule(content, { uriType: "file", filePath });
78+ const { relativePathOrBasename } = findUriInDirs(
79+ filePath,
80+ await ide.getWorkspaceDirs(),
81+ );
82+ const rule = markdownToRule(content, {
83+ uriType: "file",
84+ fileUri: relativePathOrBasename,
85+ });
7286
7387 rules.push({
7488 ...rule,
modified core/config/markdown/loadCodebaseRules.vitest.ts +23 −1
@@ -2,6 +2,7 @@
22 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33 import { IDE } from "../..";
44 import { walkDirs } from "../../indexing/walkDir";
5+import { findUriInDirs, getUriPathBasename } from "../../util/uri";
56 import { loadCodebaseRules } from "./loadCodebaseRules";
67
78 // Mock dependencies
@@ -13,12 +14,20 @@
1314 markdownToRule: vi.fn(),
1415 }));
1516
17+vi.mock("../../util/uri", () => ({
18+ findUriInDirs: vi.fn(),
19+ getUriPathBasename: vi.fn(),
20+}));
21+
1622 describe("loadCodebaseRules", () => {
1723 // Mock IDE with properly typed mock functions
1824 const mockIde = {
1925 readFile: vi.fn() as unknown as IDE["readFile"] & {
2026 mockImplementation: Function;
2127 },
28+ getWorkspaceDirs: vi.fn() as unknown as IDE["getWorkspaceDirs"] & {
29+ mockImplementation: Function;
30+ },
2231 } as unknown as IDE;
2332
2433 // Setup test files
@@ -77,6 +86,19 @@
7786 // Mock walkDirs to return our test files
7887 (walkDirs as any).mockResolvedValue(mockFiles);
7988
89+ // Mock getWorkspaceDirs to return a workspace directory
90+ (mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]);
91+
92+ // Mock getUriPathBasename to return just the filename
93+ (getUriPathBasename as any).mockImplementation((path: string) => {
94+ return path.split("/").pop() || "";
95+ });
96+
97+ // Mock findUriInDirs to return relative path
98+ (findUriInDirs as any).mockImplementation((uri: string) => {
99+ return { relativePathOrBasename: uri };
100+ });
101+
80102 // Mock readFile to return content based on path
81103 (mockIde.readFile as any).mockImplementation((path: string) => {
82104 return Promise.resolve(mockRuleContent[path] || "");
@@ -85,7 +107,7 @@
85107 // Mock markdownToRule to return converted rules
86108 (markdownToRule as any).mockImplementation(
87109 (content: string, options: any) => {
88- return mockConvertedRules[options.filePath];
110+ return mockConvertedRules[options.fileUri];
89111 },
90112 );
91113 });
modified core/config/markdown/loadMarkdownRules.ts +6 −1
@@ -3,6 +3,7 @@
33 markdownToRule,
44 } from "@continuedev/config-yaml";
55 import { IDE, RuleWithSource } from "../..";
6+import { findUriInDirs } from "../../util/uri";
67 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
78
89 /**
@@ -29,9 +30,13 @@
2930 // Process each markdown file
3031 for (const file of mdFiles) {
3132 try {
33+ const { relativePathOrBasename } = findUriInDirs(
34+ file.path,
35+ await ide.getWorkspaceDirs(),
36+ );
3237 const rule = markdownToRule(file.content, {
3338 uriType: "file",
34- filePath: file.path,
39+ fileUri: relativePathOrBasename,
3540 });
3641 rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
3742 } catch (e) {
modified core/config/profile/LocalProfileLoader.ts +1 −2
@@ -65,8 +65,7 @@
6565 orgScopeId: null,
6666 packageIdentifier: {
6767 uriType: "file",
68- filePath:
69- this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
68+ fileUri: this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
7069 },
7170 });
7271
modified core/config/profile/PlatformProfileLoader.ts +1 −1
@@ -109,7 +109,7 @@
109109 title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
110110 errors: configResult.errors,
111111 iconUrl: iconUrl,
112- uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
112+ uri: `${controlPlaneEnv.APP_URL}${ownerSlug}/${packageSlug}`,
113113 rawYaml,
114114 };
115115
modified core/config/profile/doLoadConfig.ts +37 −7
@@ -26,6 +26,7 @@
2626 import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
2727 import { ControlPlaneClient } from "../../control-plane/client.js";
2828 import { getControlPlaneEnv } from "../../control-plane/env.js";
29+import { PolicySingleton } from "../../control-plane/PolicySingleton";
2930 import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
3031 import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
3132 import { getConfigDependentToolDefinitions } from "../../tools";
@@ -35,6 +36,7 @@
3536 import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
3637 import { localPathOrUriToPath } from "../../util/pathToUri";
3738 import { Telemetry } from "../../util/posthog";
39+import { SentryLogger } from "../../util/sentry/SentryLogger";
3840 import { TTS } from "../../util/tts";
3941 import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
4042 import { loadContinueConfigFromJson } from "../load";
@@ -60,6 +62,11 @@
6062 rules.unshift(...markdownRules);
6163 errors.push(...markdownRulesErrors);
6264
65+ // Add colocated rules from CodebaseRulesCache
66+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
67+ rules.unshift(...codebaseRulesCache.rules);
68+ errors.push(...codebaseRulesCache.errors);
69+
6370 return { rules, errors };
6471 }
6572 export default async function doLoadConfig(options: {
@@ -180,11 +187,6 @@
180187 }
181188 });
182189
183- // Add rules from colocated rules.md files in the codebase
184- const codebaseRulesCache = CodebaseRulesCache.getInstance();
185- newConfig.rules.unshift(...codebaseRulesCache.rules);
186- errors.push(...codebaseRulesCache.errors);
187-
188190 // Rectify model selections for each role
189191 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
190192
@@ -325,8 +327,18 @@
325327 }
326328 });
327329
328- newConfig.allowAnonymousTelemetry =
329- newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
330+ if (newConfig.allowAnonymousTelemetry !== false) {
331+ if ((await ide.isTelemetryEnabled()) === false) {
332+ newConfig.allowAnonymousTelemetry = false;
333+ }
334+ }
335+
336+ if (
337+ PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
338+ false
339+ ) {
340+ newConfig.allowAnonymousTelemetry = false;
341+ }
330342
331343 // Setup telemetry only after (and if) we know it is enabled
332344 await Telemetry.setup(
@@ -335,6 +347,24 @@
335347 ideInfo,
336348 );
337349
350+ // Setup Sentry logger with same telemetry settings
351+ // TODO: Remove Continue team member check once Sentry is ready for all users
352+ let userEmail: string | undefined;
353+ try {
354+ // Access the session info to get user email for Continue team member check
355+ const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
356+ userEmail = sessionInfo?.account?.id;
357+ } catch (error) {
358+ // Ignore errors getting session info, will default to no Sentry
359+ }
360+
361+ await SentryLogger.setup(
362+ newConfig.allowAnonymousTelemetry ?? false,
363+ await ide.getUniqueId(),
364+ ideInfo,
365+ userEmail,
366+ );
367+
338368 // TODO: pass config to pre-load non-system TTS models
339369 await TTS.setup();
340370
modified core/config/types.ts +1 −0
@@ -387,6 +387,7 @@
387387
388388 export interface PromptLog {
389389 modelTitle: string;
390+ modelProvider: string;
390391 completionOptions: CompletionOptions;
391392 prompt: string;
392393 completion: string;
modified core/config/util.ts +0 −7
@@ -10,7 +10,6 @@
1010 JSONModelDescription,
1111 PromptTemplate,
1212 } from "../";
13-import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
1413 import { GlobalContext } from "../util/GlobalContext";
1514 import { editConfigFile } from "../util/paths";
1615
@@ -80,12 +79,6 @@
8079 maxStopWords: model.maxStopWords,
8180 defaultCompletionOptions: model.completionOptions,
8281 };
83- if (model.systemMessage) {
84- desc.chatOptions = {
85- baseSystemMessage:
86- DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
87- };
88- }
8982 config.models.push(desc);
9083 return config;
9184 },
modified core/config/yaml/loadLocalYamlBlocks.ts +1 −1
@@ -23,7 +23,7 @@
2323 const unrollResult = await unrollAssistantFromContent(
2424 {
2525 uriType: "file",
26- filePath: "",
26+ fileUri: "",
2727 },
2828 "name: FILLER\nschema: v1\nversion: 0.0.1",
2929 registryClient,
modified core/config/yaml/loadYaml.ts +3 −2
@@ -72,7 +72,7 @@
7272 );
7373 return localBlocks.map((b) => ({
7474 uriType: "file" as const,
75- filePath: b.path,
75+ fileUri: b.path,
7676 }));
7777 });
7878 const localPackageIdentifiers: PackageIdentifier[] = (
@@ -87,7 +87,7 @@
8787 const getRegistryClient = async () => {
8888 const rootPath =
8989 packageIdentifier.uriType === "file"
90- ? dirname(getCleanUriPath(packageIdentifier.filePath))
90+ ? dirname(getCleanUriPath(packageIdentifier.fileUri))
9191 : undefined;
9292 return new RegistryClient({
9393 accessToken: await controlPlaneClient.getAccessToken(),
@@ -428,6 +428,7 @@
428428 timeout: server.connectionTimeout,
429429 })),
430430 false,
431+ { ide },
431432 );
432433
433434 return { config: continueConfig, errors: localErrors };
modified core/context/mcp/MCPConnection.ts +48 −2
@@ -1,12 +1,16 @@
11 import { Client } from "@modelcontextprotocol/sdk/client/index.js";
22 import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
33
4-import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
4+import {
5+ SSEClientTransport,
6+ SseError,
7+} from "@modelcontextprotocol/sdk/client/sse.js";
58 import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
69 import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
710 import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
811
912 import {
13+ IDE,
1014 MCPConnectionStatus,
1115 MCPOptions,
1216 MCPPrompt,
@@ -16,6 +20,7 @@
1620 MCPTool,
1721 } from "../..";
1822 import { getEnvPathFromUserShell } from "../../util/shellPath";
23+import { getOauthToken } from "./MCPOauth";
1924
2025 const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
2126
@@ -30,10 +35,23 @@
3035 "bunx",
3136 ];
3237
38+function is401Error(error: unknown) {
39+ return (
40+ (error instanceof SseError && error.code === 401) ||
41+ (error instanceof Error && error.message.includes("401")) ||
42+ (error instanceof Error && error.message.includes("Unauthorized"))
43+ );
44+}
45+
46+export type MCPExtras = {
47+ ide: IDE;
48+};
49+
3350 class MCPConnection {
3451 public client: Client;
3552 public abortController: AbortController;
3653 public status: MCPConnectionStatus = "not-connected";
54+ public isProtectedResource = false;
3755 public errors: string[] = [];
3856 public prompts: MCPPrompt[] = [];
3957 public tools: MCPTool[] = [];
@@ -46,7 +64,10 @@
4664 stderr: "",
4765 };
4866
49- constructor(public options: MCPOptions) {
67+ constructor(
68+ public options: MCPOptions,
69+ public extras?: MCPExtras,
70+ ) {
5071 // Don't construct transport in constructor to avoid blocking
5172 this.transport = {} as Transport; // Will be set in connectClient
5273
@@ -78,6 +99,7 @@
7899 resourceTemplates: this.resourceTemplates,
79100 tools: this.tools,
80101 status: this.status,
102+ isProtectedResource: this.isProtectedResource,
81103 };
82104 }
83105
@@ -106,6 +128,26 @@
106128 this.abortController.abort();
107129 this.abortController = new AbortController();
108130
131+ // currently support oauth for sse transports only
132+ if (this.options.transport.type === "sse") {
133+ if (!this.options.transport.requestOptions) {
134+ this.options.transport.requestOptions = {
135+ headers: {},
136+ };
137+ }
138+ const accessToken = await getOauthToken(
139+ this.options.transport.url,
140+ this.extras?.ide!,
141+ );
142+ if (accessToken) {
143+ this.isProtectedResource = true;
144+ this.options.transport.requestOptions.headers = {
145+ ...this.options.transport.requestOptions.headers,
146+ Authorization: `Bearer ${accessToken}`,
147+ };
148+ }
149+ }
150+
109151 this.connectionPromise = Promise.race([
110152 // If aborted by a refresh or other, cancel and don't do anything
111153 new Promise((resolve) => {
@@ -244,6 +286,10 @@
244286 }
245287 }
246288
289+ if (is401Error(error)) {
290+ this.isProtectedResource = true;
291+ }
292+
247293 // Include stdio output if available for stdio transport
248294 if (
249295 this.options.transport.type === "stdio" &&
modified core/context/mcp/MCPConnection.vitest.ts +1 −1
@@ -1,7 +1,6 @@
11 import { Client } from "@modelcontextprotocol/sdk/client/index.js";
22 import { beforeEach, describe, expect, it, vi } from "vitest";
33 import MCPConnection from "./MCPConnection";
4-import { StdioOptions } from "../../index.d.js";
54
65 // Mock the shell path utility
76 vi.mock("../../util/shellPath", () => ({
@@ -143,6 +142,7 @@
143142 expect(status).toEqual({
144143 ...options,
145144 errors: [],
145+ isProtectedResource: false,
146146 prompts: [],
147147 resources: [],
148148 resourceTemplates: [],
modified core/context/mcp/MCPManagerSingleton.ts +17 −9
@@ -6,7 +6,7 @@
66 StdioOptions,
77 TransportOptions,
88 } from "../..";
9-import MCPConnection from "./MCPConnection";
9+import MCPConnection, { MCPExtras } from "./MCPConnection";
1010
1111 export class MCPManagerSingleton {
1212 private static instance: MCPManagerSingleton;
@@ -26,12 +26,12 @@
2626 }
2727
2828 createConnection(id: string, options: MCPOptions): MCPConnection {
29- if (!this.connections.has(id)) {
29+ if (this.connections.has(id)) {
30+ return this.connections.get(id)!;
31+ } else {
3032 const connection = new MCPConnection(options);
3133 this.connections.set(id, connection);
3234 return connection;
33- } else {
34- return this.connections.get(id)!;
3535 }
3636 }
3737
@@ -48,7 +48,11 @@
4848 this.connections.delete(id);
4949 }
5050
51- setConnections(servers: MCPOptions[], forceRefresh: boolean) {
51+ setConnections(
52+ servers: MCPOptions[],
53+ forceRefresh: boolean,
54+ extras?: MCPExtras,
55+ ) {
5256 let refresh = false;
5357
5458 // Remove any connections that are no longer in config
@@ -73,15 +77,15 @@
7377
7478 // Add any connections that are not yet in manager
7579 servers.forEach((server) => {
76- if (!this.connections.has(server.id)) {
77- refresh = true;
78- this.connections.set(server.id, new MCPConnection(server));
79- } else {
80+ if (this.connections.has(server.id)) {
8081 const conn = this.connections.get(server.id);
8182 if (conn) {
8283 // We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
8384 conn.options = server;
8485 }
86+ } else {
87+ refresh = true;
88+ this.connections.set(server.id, new MCPConnection(server, extras));
8589 }
8690 });
8791
@@ -162,6 +166,10 @@
162166 }));
163167 }
164168
169+ setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
170+ this.connections.get(server.id)!.status = status;
171+ }
172+
165173 async getPrompt(
166174 serverName: string,
167175 promptName: string,
added core/context/mcp/MCPOauth.ts +227 −0
@@ -0,0 +1,227 @@
1+import {
2+ OAuthClientProvider,
3+ auth,
4+} from "@modelcontextprotocol/sdk/client/auth.js";
5+import {
6+ OAuthClientInformationFull,
7+ OAuthClientInformationSchema,
8+ OAuthTokens,
9+ OAuthTokensSchema,
10+} from "@modelcontextprotocol/sdk/shared/auth.js";
11+import { IDE, MCPServerStatus, SSEOptions } from "../..";
12+
13+import http from "http";
14+import url from "url";
15+import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
16+
17+let authenticatingMCPContext = null as {
18+ authenticatingServer: MCPServerStatus;
19+ ide: IDE;
20+} | null;
21+
22+const PORT = 3000;
23+
24+const server = http.createServer((req, res) => {
25+ try {
26+ if (!req.url) {
27+ throw new Error("no url found");
28+ }
29+
30+ const parsedUrl = url.parse(req.url, true);
31+ if (!parsedUrl.query["code"]) {
32+ throw new Error("no query params found");
33+ }
34+
35+ void handleMCPOauthCode(parsedUrl.query["code"] as string);
36+
37+ const html = `
38+<!DOCTYPE html>
39+<html>
40+<head><title>Authentication Complete</title></head>
41+<body>Authentication Complete. You can close this page now.</body>
42+</html>`;
43+
44+ res.writeHead(200, {
45+ "Content-Type": "text/html",
46+ });
47+ res.end(html);
48+ } catch (error) {
49+ res.writeHead(400, { "Content-Type": "text/plain" });
50+ res.end(`Unexpected redirect error: ${(error as Error).message}`);
51+ }
52+});
53+
54+type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
55+type MCPOauthStorageKey = keyof MCPOauthStorage;
56+
57+class MCPConnectionOauthProvider implements OAuthClientProvider {
58+ private globalContext: GlobalContext;
59+
60+ constructor(
61+ public oauthServerUrl: string,
62+ private ide: IDE,
63+ ) {
64+ this.globalContext = new GlobalContext();
65+ }
66+
67+ get redirectUrl() {
68+ return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
69+ }
70+
71+ get clientMetadata() {
72+ return {
73+ redirect_uris: [this.redirectUrl],
74+ token_endpoint_auth_method: "none",
75+ grant_types: ["authorization_code", "refresh_token"],
76+ response_types: ["code"],
77+ client_name: "Continue Dev, Inc", // get this from package.json?
78+ client_uri: "https://continue.dev", // get this from package.json?
79+ };
80+ }
81+
82+ private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
83+ return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
84+ key
85+ ];
86+ }
87+
88+ private _updateOauthStorage<K extends MCPOauthStorageKey>(
89+ key: K,
90+ value: MCPOauthStorage[K],
91+ ) {
92+ const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
93+ const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
94+
95+ this.globalContext.update("mcpOauthStorage", {
96+ ...existingStorage,
97+ [this.oauthServerUrl]: {
98+ ...existingServerStorage,
99+ [key]: value,
100+ },
101+ });
102+ }
103+
104+ private _clearOauthStorage() {
105+ const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
106+ delete existingStorage[this.oauthServerUrl];
107+ this.globalContext.update("mcpOauthStorage", existingStorage);
108+ }
109+
110+ saveClientInformation(clientInformation: OAuthClientInformationFull) {
111+ this._updateOauthStorage("clientInformation", clientInformation);
112+ }
113+
114+ async clientInformation() {
115+ const existingClientInformation =
116+ this._getOauthStorage("clientInformation");
117+ if (!existingClientInformation) {
118+ return undefined;
119+ }
120+ return await OAuthClientInformationSchema.parseAsync(
121+ existingClientInformation,
122+ );
123+ }
124+
125+ async tokens() {
126+ const existingTokens = this._getOauthStorage("tokens");
127+ if (!existingTokens) {
128+ return undefined;
129+ }
130+ return await OAuthTokensSchema.parseAsync(existingTokens);
131+ }
132+
133+ saveTokens(tokens: OAuthTokens) {
134+ this._updateOauthStorage("tokens", tokens);
135+ }
136+
137+ codeVerifier(): string | Promise<string> {
138+ const existingCodeVerifier = this._getOauthStorage("codeVerifier");
139+ if (!existingCodeVerifier) {
140+ return "";
141+ }
142+ return existingCodeVerifier;
143+ }
144+
145+ saveCodeVerifier(codeVerifier: string) {
146+ this._updateOauthStorage("codeVerifier", codeVerifier);
147+ }
148+
149+ clear() {
150+ this._clearOauthStorage();
151+ }
152+
153+ async redirectToAuthorization(authorizationUrl: URL) {
154+ if (!server.listening) {
155+ server.listen(PORT, () => {
156+ console.debug(
157+ `Server started for MCP Oauth process at http://localhost:${PORT}/`,
158+ );
159+ });
160+ }
161+ void this.ide.openUrl(authorizationUrl.toString());
162+ }
163+}
164+
165+export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
166+ const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
167+ const tokens = await authProvider.tokens();
168+ return tokens?.access_token;
169+}
170+
171+/**
172+ * checks if the authentication is already done for the current server
173+ * if not, starts the authentication process by opening a webpage url
174+ */
175+export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
176+ const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
177+ const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
178+ authenticatingMCPContext = {
179+ authenticatingServer: mcpServer,
180+ ide,
181+ };
182+ return await auth(authProvider, {
183+ serverUrl: mcpServerUrl,
184+ });
185+}
186+
187+/**
188+ * handle the authentication code received from the oauth redirect
189+ */
190+async function handleMCPOauthCode(authorizationCode: string) {
191+ if (!authenticatingMCPContext) {
192+ return;
193+ }
194+ const { ide, authenticatingServer } = authenticatingMCPContext;
195+ const serverUrl = (authenticatingServer.transport as SSEOptions).url;
196+
197+ if (!serverUrl) {
198+ void ide.showToast("error", "No MCP server url found for authentication");
199+ return;
200+ }
201+ if (!authorizationCode) {
202+ void ide.showToast(
203+ "error",
204+ `No MCP authorization code found for ${serverUrl}`,
205+ );
206+ return;
207+ }
208+ server.close(() => console.debug("Server for MCP Oauth process was closed"));
209+ const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
210+ const authStatus = await auth(authProvider, {
211+ serverUrl,
212+ authorizationCode,
213+ });
214+ if (authStatus === "AUTHORIZED") {
215+ const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
216+ await MCPManagerSingleton.getInstance().refreshConnection(
217+ authenticatingServer.id,
218+ );
219+ }
220+ authenticatingMCPContext = null;
221+}
222+
223+export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
224+ const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
225+ const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
226+ authProvider.clear();
227+}
added core/context/mcp/MCPOauth.vitest.ts +181 −0
@@ -0,0 +1,181 @@
1+import fs from "node:fs";
2+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
3+import { GlobalContext } from "../../util/GlobalContext";
4+import { getGlobalContextFilePath } from "../../util/paths";
5+import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
6+
7+// Mock the MCP SDK auth module
8+vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
9+ auth: vi.fn(),
10+}));
11+
12+// Mock the MCPManagerSingleton to avoid circular imports
13+vi.mock("./MCPManagerSingleton", () => ({
14+ MCPManagerSingleton: {
15+ getInstance: vi.fn(() => ({
16+ refreshConnection: vi.fn(),
17+ })),
18+ },
19+}));
20+
21+describe("MCPOauth", () => {
22+ let globalContextFilePath: string;
23+ let mockIde: any;
24+ let mockMcpServer: any;
25+
26+ beforeEach(() => {
27+ // file is present in the core/test directory
28+ globalContextFilePath = getGlobalContextFilePath();
29+ if (fs.existsSync(globalContextFilePath)) {
30+ fs.unlinkSync(globalContextFilePath);
31+ }
32+
33+ mockIde = {
34+ openUrl: vi.fn(),
35+ showToast: vi.fn(),
36+ };
37+
38+ mockMcpServer = {
39+ id: "test-server",
40+ transport: {
41+ type: "sse",
42+ url: "https://test-server.com",
43+ },
44+ };
45+
46+ vi.clearAllMocks();
47+ });
48+
49+ afterEach(() => {
50+ if (fs.existsSync(globalContextFilePath)) {
51+ fs.unlinkSync(globalContextFilePath);
52+ }
53+ });
54+
55+ describe("getOauthToken", () => {
56+ test("should return undefined when no tokens are stored", async () => {
57+ const result = await getOauthToken("https://test-server.com", mockIde);
58+ expect(result).toBeUndefined();
59+ });
60+
61+ test("should return access token when tokens are stored", async () => {
62+ const globalContext = new GlobalContext();
63+ globalContext.update("mcpOauthStorage", {
64+ "https://test-server.com": {
65+ tokens: {
66+ access_token: "test-access-token",
67+ token_type: "Bearer",
68+ },
69+ },
70+ });
71+
72+ const result = await getOauthToken("https://test-server.com", mockIde);
73+ expect(result).toBe("test-access-token");
74+ });
75+
76+ test("should handle different server URLs independently", async () => {
77+ const globalContext = new GlobalContext();
78+ globalContext.update("mcpOauthStorage", {
79+ "https://server1.com": {
80+ tokens: {
81+ access_token: "token1",
82+ token_type: "Bearer",
83+ },
84+ },
85+ "https://server2.com": {
86+ tokens: {
87+ access_token: "token2",
88+ token_type: "Bearer",
89+ },
90+ },
91+ });
92+
93+ const result1 = await getOauthToken("https://server1.com", mockIde);
94+ const result2 = await getOauthToken("https://server2.com", mockIde);
95+ const result3 = await getOauthToken("https://server3.com", mockIde);
96+
97+ expect(result1).toBe("token1");
98+ expect(result2).toBe("token2");
99+ expect(result3).toBeUndefined();
100+ });
101+ });
102+
103+ describe("performAuth", () => {
104+ test("should call auth with correct parameters and return auth result", async () => {
105+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
106+ const mockAuth = vi.mocked(auth);
107+ mockAuth.mockResolvedValue("AUTHORIZED");
108+
109+ const result = await performAuth(mockMcpServer, mockIde);
110+
111+ expect(mockAuth).toHaveBeenCalledWith(
112+ expect.any(Object), // MCPConnectionOauthProvider instance
113+ {
114+ serverUrl: "https://test-server.com",
115+ },
116+ );
117+ expect(result).toBe("AUTHORIZED");
118+ });
119+ });
120+
121+ describe("removeMCPAuth", () => {
122+ test("should clear oauth storage for the server", () => {
123+ const globalContext = new GlobalContext();
124+ globalContext.update("mcpOauthStorage", {
125+ "https://test-server.com": {
126+ tokens: {
127+ access_token: "test-access-token",
128+ token_type: "Bearer",
129+ },
130+ clientInformation: {
131+ client_id: "test-client-id",
132+ redirect_uris: ["http://localhost:3000"],
133+ },
134+ codeVerifier: "test-code-verifier",
135+ },
136+ "https://other-server.com": {
137+ tokens: {
138+ access_token: "other-access-token",
139+ token_type: "Bearer",
140+ },
141+ },
142+ });
143+
144+ removeMCPAuth(mockMcpServer, mockIde);
145+
146+ const updatedStorage = globalContext.get("mcpOauthStorage");
147+ expect(updatedStorage).toEqual({
148+ "https://other-server.com": {
149+ tokens: {
150+ access_token: "other-access-token",
151+ token_type: "Bearer",
152+ },
153+ },
154+ });
155+ });
156+
157+ test("should handle non-existent server gracefully", () => {
158+ const globalContext = new GlobalContext();
159+ globalContext.update("mcpOauthStorage", {
160+ "https://other-server.com": {
161+ tokens: {
162+ access_token: "other-access-token",
163+ token_type: "Bearer",
164+ },
165+ },
166+ });
167+
168+ removeMCPAuth(mockMcpServer, mockIde);
169+
170+ const updatedStorage = globalContext.get("mcpOauthStorage");
171+ expect(updatedStorage).toEqual({
172+ "https://other-server.com": {
173+ tokens: {
174+ access_token: "other-access-token",
175+ token_type: "Bearer",
176+ },
177+ },
178+ });
179+ });
180+ });
181+});
modified core/context/providers/ClipboardContextProvider.ts +4 −0
@@ -18,6 +18,10 @@
1818 type: "submenu",
1919 };
2020
21+ get deprecationMessage() {
22+ return "The clipboard context provider is deprecated as it is not used. It will be removed in a future version.";
23+ }
24+
2125 async getContextItems(
2226 query: string,
2327 extras: ContextProviderExtras,
modified core/context/providers/DocsContextProvider.ts +7 −3
@@ -43,9 +43,13 @@
4343 try {
4444 const scores = await reranker.rerank(fullInput, chunksCopy);
4545
46- chunksCopy.sort(
47- (a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
48- );
46+ if (Array.isArray(scores)) {
47+ // reranker model has returned a valid array
48+ chunksCopy.sort(
49+ (a, b) =>
50+ scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
51+ );
52+ }
4953
5054 chunksCopy = chunksCopy.splice(
5155 0,
modified core/context/providers/MCPContextProvider.ts +2 −2
@@ -18,7 +18,7 @@
1818 static description: ContextProviderDescription = {
1919 title: "mcp",
2020 displayTitle: "MCP",
21- description: "Model Context Protocol",
21+ description: "MCP Resources",
2222 type: "submenu",
2323 renderInlineAs: "",
2424 };
@@ -29,7 +29,7 @@
2929 ? `${this.options["serverName"]} resources`
3030 : "MCP",
3131 renderInlineAs: "",
32- description: "Model Context Protocol",
32+ description: "MCP Resources",
3333 type: "submenu",
3434 };
3535 }
modified core/context/providers/_context-providers.vitest.ts +2 −1
@@ -36,6 +36,7 @@
3636 llmLogger,
3737 Promise.resolve(undefined),
3838 );
39+ await configHandler.isInitialized;
3940 const { config } = await configHandler.loadConfig();
4041 if (!config) {
4142 throw new Error("Config not found");
@@ -54,7 +55,7 @@
5455 };
5556 }
5657
57-describe.skip("Should successfully run all context providers", () => {
58+describe("Should successfully run all context providers", () => {
5859 afterAll(() => {
5960 tearDownTestDir();
6061 });
modified core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +2 −2
@@ -27,7 +27,7 @@
2727
2828 let embeddingsChunks: Chunk[] = [];
2929 try {
30- embeddingsChunks = !!config.selectedModelByRole.embed
30+ embeddingsChunks = Boolean(config.selectedModelByRole.embed)
3131 ? await this.retrieveEmbeddings(input, nRetrieve)
3232 : [];
3333 } catch (error) {
@@ -116,7 +116,7 @@
116116 const chunkIndexMap = new Map<Chunk, number>();
117117 chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
118118
119- results.sort(
119+ results?.sort(
120120 (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
121121 );
122122 results = results.slice(0, this.options.nFinal);
added core/control-plane/PolicySingleton.ts +15 −0
@@ -0,0 +1,15 @@
1+import { PolicyResponse } from "./client.js";
2+
3+export class PolicySingleton {
4+ private static instance: PolicySingleton;
5+ public policy: PolicyResponse | null = null;
6+
7+ private constructor() {}
8+
9+ public static getInstance(): PolicySingleton {
10+ if (!PolicySingleton.instance) {
11+ PolicySingleton.instance = new PolicySingleton();
12+ }
13+ return PolicySingleton.instance;
14+ }
15+}
modified core/control-plane/client.ts +41 −0
@@ -4,6 +4,7 @@
44 ConfigResult,
55 FQSN,
66 FullSlug,
7+ Policy,
78 SecretResult,
89 SecretType,
910 } from "@continuedev/config-yaml";
@@ -11,10 +12,16 @@
1112
1213 import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
1314 import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
15+import { Logger } from "../util/Logger.js";
1416
1517 import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
1618 import { getControlPlaneEnv } from "./env.js";
1719
20+export interface PolicyResponse {
21+ orgSlug?: string;
22+ policy?: Policy;
23+}
24+
1825 export interface ControlPlaneWorkspace {
1926 id: string;
2027 name: string;
@@ -140,6 +147,11 @@
140147 });
141148 return (await resp.json()) as any;
142149 } catch (e) {
150+ // Capture control plane API failures to Sentry
151+ Logger.error(e, {
152+ context: "control_plane_list_assistants",
153+ organizationId,
154+ });
143155 return [];
144156 }
145157 }
@@ -210,6 +222,26 @@
210222 });
211223 const { fullSlugs } = (await resp.json()) as any;
212224 return fullSlugs;
225+ } catch (e) {
226+ // Capture control plane API failures to Sentry
227+ Logger.error(e, {
228+ context: "control_plane_list_assistant_slugs",
229+ organizationId,
230+ });
231+ return null;
232+ }
233+ }
234+
235+ public async getPolicy(): Promise<PolicyResponse | null> {
236+ if (!(await this.isSignedIn())) {
237+ return null;
238+ }
239+
240+ try {
241+ const resp = await this.request(`ide/policy`, {
242+ method: "GET",
243+ });
244+ return (await resp.json()) as PolicyResponse;
213245 } catch (e) {
214246 return null;
215247 }
@@ -226,6 +258,10 @@
226258 });
227259 return (await resp.json()) as FreeTrialStatus;
228260 } catch (e) {
261+ // Capture control plane API failures to Sentry
262+ Logger.error(e, {
263+ context: "control_plane_free_trial_status",
264+ });
229265 return null;
230266 }
231267 }
@@ -260,6 +296,11 @@
260296 );
261297 return (await resp.json()) as { url: string };
262298 } catch (e) {
299+ // Capture control plane API failures to Sentry
300+ Logger.error(e, {
301+ context: "control_plane_models_checkout_url",
302+ vsCodeUriScheme,
303+ });
263304 return null;
264305 }
265306 }
modified core/core.ts +211 −114
@@ -23,7 +23,6 @@
2323 import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
2424 import { callTool } from "./tools/callTool";
2525 import { ChatDescriber } from "./util/chatDescriber";
26-import { clipboardCache } from "./util/clipboardCache";
2726 import { compactConversation } from "./util/conversationCompaction";
2827 import { GlobalContext } from "./util/GlobalContext";
2928 import historyManager from "./util/history";
@@ -61,6 +60,7 @@
6160 } from "./config/onboarding";
6261 import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
6362 import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
63+import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
6464 import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
6565 import { ApplyAbortManager } from "./edit/applyAbortManager";
6666 import { streamDiffLines } from "./edit/streamDiffLines";
@@ -71,10 +71,12 @@
7171 import { llmStreamChat } from "./llm/streamChat";
7272 import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
7373 import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
74+import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue";
7475 import { NextEditProvider } from "./nextEdit/NextEditProvider";
7576 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
7677 import { OnboardingModes } from "./protocol/core";
7778 import type { IMessenger, Message } from "./protocol/messenger";
79+import { Logger } from "./util/Logger.js";
7880 import { getUriPathBasename } from "./util/uri";
7981
8082 const hasRulesFiles = (uris: string[]): boolean => {
@@ -130,114 +132,143 @@
130132 private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
131133 private readonly ide: IDE,
132134 ) {
133- // Ensure .continue directory is created
134- migrateV1DevDataFiles();
135-
136- const ideInfoPromise = messenger.request("getIdeInfo", undefined);
137- const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
138- const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
139- silent: true,
140- useOnboarding: false,
141- });
142-
143- this.configHandler = new ConfigHandler(
144- this.ide,
145- ideSettingsPromise,
146- this.llmLogger,
147- sessionInfoPromise,
148- );
149-
150- this.docsService = DocsService.createSingleton(
151- this.configHandler,
152- this.ide,
153- this.messenger,
154- );
155-
156- MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
157- void this.configHandler.reloadConfig("MCP Connections refreshed");
135+ try {
136+ // Ensure .continue directory is created
137+ migrateV1DevDataFiles();
138+
139+ const ideInfoPromise = messenger.request("getIdeInfo", undefined);
140+ const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
141+ const sessionInfoPromise = messenger.request(
142+ "getControlPlaneSessionInfo",
143+ {
144+ silent: true,
145+ useOnboarding: false,
146+ },
147+ );
158148
159- // Refresh @mention dropdown submenu items for MCP providers
160- const mcpManager = MCPManagerSingleton.getInstance();
161- const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
162- (mcpId) => `mcp-${mcpId}`,
149+ this.configHandler = new ConfigHandler(
150+ this.ide,
151+ ideSettingsPromise,
152+ this.llmLogger,
153+ sessionInfoPromise,
163154 );
164155
165- if (mcpProviderNames.length > 0) {
166- this.messenger.send("refreshSubmenuItems", {
167- providers: mcpProviderNames,
168- });
169- }
170- };
156+ this.docsService = DocsService.createSingleton(
157+ this.configHandler,
158+ this.ide,
159+ this.messenger,
160+ );
171161
172- this.codeBaseIndexer = new CodebaseIndexer(
173- this.configHandler,
174- this.ide,
175- this.messenger,
176- this.globalContext.get("indexingPaused"),
177- );
162+ MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
163+ void this.configHandler.reloadConfig("MCP Connections refreshed");
178164
179- this.configHandler.onConfigUpdate((result) => {
180- void (async () => {
181- const serializedResult = await this.configHandler.getSerializedConfig();
182- this.messenger.send("configUpdate", {
183- result: serializedResult,
184- profileId:
185- this.configHandler.currentProfile?.profileDescription.id || null,
186- organizations: this.configHandler.getSerializedOrgs(),
187- selectedOrgId: this.configHandler.currentOrg.id,
188- });
165+ // Refresh @mention dropdown submenu items for MCP providers
166+ const mcpManager = MCPManagerSingleton.getInstance();
167+ const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
168+ (mcpId) => `mcp-${mcpId}`,
169+ );
189170
190- // update additional submenu context providers registered via VSCode API
191- const additionalProviders =
192- this.configHandler.getAdditionalSubmenuContextProviders();
193- if (additionalProviders.length > 0) {
171+ if (mcpProviderNames.length > 0) {
194172 this.messenger.send("refreshSubmenuItems", {
195- providers: additionalProviders,
173+ providers: mcpProviderNames,
196174 });
197175 }
198- })();
199- });
176+ };
200177
201- // Dev Data Logger
202- const dataLogger = DataLogger.getInstance();
203- dataLogger.core = this;
204- dataLogger.ideInfoPromise = ideInfoPromise;
205- dataLogger.ideSettingsPromise = ideSettingsPromise;
178+ this.configHandler.onConfigUpdate((result) => {
179+ void (async () => {
180+ const serializedResult =
181+ await this.configHandler.getSerializedConfig();
182+ this.messenger.send("configUpdate", {
183+ result: serializedResult,
184+ profileId:
185+ this.configHandler.currentProfile?.profileDescription.id || null,
186+ organizations: this.configHandler.getSerializedOrgs(),
187+ selectedOrgId: this.configHandler.currentOrg?.id ?? null,
188+ });
206189
207- const getLlm = async () => {
208- const { config } = await this.configHandler.loadConfig();
209- if (!config) {
210- return undefined;
211- }
212- return config.selectedModelByRole.autocomplete ?? undefined;
213- };
214- this.completionProvider = new CompletionProvider(
215- this.configHandler,
216- ide,
217- getLlm,
218- (e) => {},
219- (..._) => Promise.resolve([]),
220- );
190+ // update additional submenu context providers registered via VSCode API
191+ const additionalProviders =
192+ this.configHandler.getAdditionalSubmenuContextProviders();
193+ if (additionalProviders.length > 0) {
194+ this.messenger.send("refreshSubmenuItems", {
195+ providers: additionalProviders,
196+ });
197+ }
198+ })();
199+ });
221200
222- const codebaseRulesCache = CodebaseRulesCache.getInstance();
223- void codebaseRulesCache
224- .refresh(ide)
225- .catch((e) => console.error("Failed to initialize colocated rules cache"))
226- .then(() => {
227- void this.configHandler.reloadConfig(
228- "Initial codebase rules post-walkdir/load reload",
229- );
201+ this.codeBaseIndexer = new CodebaseIndexer(
202+ this.configHandler,
203+ this.ide,
204+ this.messenger,
205+ this.globalContext.get("indexingPaused"),
206+ );
207+
208+ // Dev Data Logger
209+ const dataLogger = DataLogger.getInstance();
210+ dataLogger.core = this;
211+ dataLogger.ideInfoPromise = ideInfoPromise;
212+ dataLogger.ideSettingsPromise = ideSettingsPromise;
213+
214+ void ideSettingsPromise.then((ideSettings) => {
215+ // Index on initialization
216+ void this.ide.getWorkspaceDirs().then(async (dirs) => {
217+ // Respect pauseCodebaseIndexOnStart user settings
218+ if (ideSettings.pauseCodebaseIndexOnStart) {
219+ this.codeBaseIndexer.paused = true;
220+ void this.messenger.request("indexProgress", {
221+ progress: 0,
222+ desc: "Initial Indexing Skipped",
223+ status: "paused",
224+ });
225+ return;
226+ }
227+
228+ void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
229+ });
230230 });
231- this.nextEditProvider = NextEditProvider.initialize(
232- this.configHandler,
233- ide,
234- getLlm,
235- (e) => {},
236- (..._) => Promise.resolve([]),
237- "fineTuned",
238- );
239231
240- this.registerMessageHandlers(ideSettingsPromise);
232+ const getLlm = async () => {
233+ const { config } = await this.configHandler.loadConfig();
234+ if (!config) {
235+ return undefined;
236+ }
237+ return config.selectedModelByRole.autocomplete ?? undefined;
238+ };
239+ this.completionProvider = new CompletionProvider(
240+ this.configHandler,
241+ ide,
242+ getLlm,
243+ (e) => {},
244+ (..._) => Promise.resolve([]),
245+ );
246+
247+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
248+ void codebaseRulesCache
249+ .refresh(ide)
250+ .catch((e) =>
251+ Logger.error("Failed to initialize colocated rules cache"),
252+ )
253+ .then(() => {
254+ void this.configHandler.reloadConfig(
255+ "Initial codebase rules post-walkdir/load reload",
256+ );
257+ });
258+ this.nextEditProvider = NextEditProvider.initialize(
259+ this.configHandler,
260+ ide,
261+ getLlm,
262+ (e) => {},
263+ (..._) => Promise.resolve([]),
264+ "fineTuned",
265+ );
266+
267+ this.registerMessageHandlers(ideSettingsPromise);
268+ } catch (error) {
269+ Logger.error(error);
270+ throw error; // Re-throw to prevent partially initialized core
271+ }
241272 }
242273
243274 /* eslint-disable max-lines-per-function */
@@ -417,6 +448,19 @@
417448 description: prompt.description,
418449 };
419450 });
451+ on("mcp/startAuthentication", async (msg) => {
452+ await new Promise((resolve) => setTimeout(resolve, 5000));
453+ MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
454+ const status = await performAuth(msg.data, this.ide);
455+ if (status === "AUTHORIZED") {
456+ await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
457+ }
458+ });
459+ on("mcp/removeAuthentication", async (msg) => {
460+ removeMCPAuth(msg.data, this.ide);
461+ await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
462+ });
463+
420464 // Context providers
421465 on("context/addDocs", async (msg) => {
422466 void this.docsService.indexAndAdd(msg.data);
@@ -447,7 +491,7 @@
447491 });
448492 return items || [];
449493 } catch (e) {
450- console.error(e);
494+ Logger.error(e);
451495 return [];
452496 }
453497 });
@@ -465,19 +509,10 @@
465509 profileId:
466510 this.configHandler.currentProfile?.profileDescription.id ?? null,
467511 organizations: this.configHandler.getSerializedOrgs(),
468- selectedOrgId: this.configHandler.currentOrg.id,
512+ selectedOrgId: this.configHandler.currentOrg?.id ?? null,
469513 };
470514 });
471515
472- on("clipboardCache/add", (msg) => {
473- const added = clipboardCache.add(uuidv4(), msg.data.content);
474- if (added) {
475- this.messenger.send("refreshSubmenuItems", {
476- providers: ["clipboard"],
477- });
478- }
479- });
480-
481516 on("llm/streamChat", (msg) => {
482517 const abortController = this.addMessageAbortController(msg.messageId);
483518 return llmStreamChat(
@@ -554,7 +589,7 @@
554589 });
555590 return undefined;
556591 } catch (error) {
557- console.error("Error compacting conversation:", error);
592+ Logger.error(`Error compacting conversation: ${error}`);
558593 return undefined;
559594 }
560595 });
@@ -578,18 +613,80 @@
578613 // Next Edit
579614 on("nextEdit/predict", async (msg) => {
580615 const outcome = await this.nextEditProvider.provideInlineCompletionItems(
581- msg.data,
616+ msg.data.input,
582617 undefined,
583- { withChain: false, usingFullFileDiff: true },
618+ {
619+ withChain: msg.data.options?.withChain ?? false,
620+ usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true,
621+ },
584622 );
585- return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
623+ return outcome;
624+ // ? [outcome.completion, outcome.originalEditableRange]
586625 });
587626 on("nextEdit/accept", async (msg) => {
627+ console.log("nextEdit/accept");
588628 this.nextEditProvider.accept(msg.data.completionId);
589629 });
590630 on("nextEdit/reject", async (msg) => {
631+ console.log("nextEdit/reject");
591632 this.nextEditProvider.reject(msg.data.completionId);
592633 });
634+ on("nextEdit/startChain", async (msg) => {
635+ console.log("nextEdit/startChain");
636+ NextEditProvider.getInstance().startChain();
637+ return;
638+ });
639+
640+ on("nextEdit/deleteChain", async (msg) => {
641+ console.log("nextEdit/deleteChain");
642+ await NextEditProvider.getInstance().deleteChain();
643+ return;
644+ });
645+
646+ on("nextEdit/isChainAlive", async (msg) => {
647+ console.log("nextEdit/isChainAlive");
648+ return NextEditProvider.getInstance().chainExists();
649+ });
650+
651+ on("nextEdit/queue/getProcessedCount", async (msg) => {
652+ console.log("nextEdit/queue/getProcessedCount");
653+ const queue = PrefetchQueue.getInstance();
654+ console.log(queue.processedCount);
655+ return queue.processedCount;
656+ });
657+
658+ on("nextEdit/queue/dequeueProcessed", async (msg) => {
659+ console.log("nextEdit/queue/dequeueProcessed");
660+ const queue = PrefetchQueue.getInstance();
661+ return queue.dequeueProcessed() || null;
662+ });
663+
664+ on("nextEdit/queue/processOne", async (msg) => {
665+ console.log("nextEdit/queue/processOne");
666+ const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
667+ const queue = PrefetchQueue.getInstance();
668+
669+ await queue.process({
670+ ...ctx,
671+ recentlyVisitedRanges,
672+ recentlyEditedRanges,
673+ });
674+ return;
675+ });
676+
677+ on("nextEdit/queue/clear", async (msg) => {
678+ console.log("nextEdit/queue/clear");
679+ const queue = PrefetchQueue.getInstance();
680+ queue.clear();
681+ return;
682+ });
683+
684+ on("nextEdit/queue/abort", async (msg) => {
685+ console.log("nextEdit/queue/abort");
686+ const queue = PrefetchQueue.getInstance();
687+ queue.abort();
688+ return;
689+ });
593690
594691 on("streamDiffLines", async (msg) => {
595692 const { config } = await this.configHandler.loadConfig();
@@ -762,7 +859,7 @@
762859 prevFilepaths.filepaths = filepaths;
763860 }
764861 } catch (e) {
765- console.error(
862+ Logger.error(
766863 `didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
767864 );
768865 }
@@ -787,7 +884,7 @@
787884 openedFilesLruCache.set(filepath, filepath);
788885 }
789886 } catch (e) {
790- console.error(
887+ Logger.error(
791888 `files/opened: failed to update openedFiles cache for ${filepath}`,
792889 );
793890 }
@@ -1067,7 +1164,7 @@
10671164 void this.configHandler.reloadConfig("Codebase rule update");
10681165 });
10691166 } catch (e) {
1070- console.error("Failed to update codebase rule", e);
1167+ Logger.error(`Failed to update codebase rule: ${e}`);
10711168 }
10721169 } else if (
10731170 uri.endsWith(".continueignore") ||
@@ -1144,7 +1241,7 @@
11441241 break;
11451242
11461243 default:
1147- console.error(`Invalid mode: ${mode}`);
1244+ Logger.error(`Invalid mode: ${mode}`);
11481245 editConfigYamlCallback = (config) => config;
11491246 }
11501247
modified core/data/log.vitest.ts +1 −0
@@ -34,6 +34,7 @@
3434 prompt: "Hello, world!",
3535 completion: "Hello, world!",
3636 modelProvider: "openai",
37+ modelName: "gpt-4",
3738 modelTitle: "gpt-4",
3839 sessionId: "1234",
3940 tools: ["test-tool1"],
modified core/edit/recursiveStream.ts +1 −0
@@ -7,6 +7,7 @@
77
88 const DUD_PROMPT_LOG: PromptLog = {
99 modelTitle: "",
10+ modelProvider: "",
1011 completionOptions: { model: "" },
1112 prompt: "",
1213 completion: "",
modified core/index.d.ts +3 −0
@@ -455,6 +455,7 @@
455455
456456 export interface PromptLog {
457457 modelTitle: string;
458+ modelProvider: string;
458459 completionOptions: CompletionOptions;
459460 prompt: string;
460461 completion: string;
@@ -1278,6 +1279,7 @@
12781279 | "connecting"
12791280 | "connected"
12801281 | "error"
1282+ | "authenticating"
12811283 | "not-connected";
12821284
12831285 export type MCPPromptArgs = {
@@ -1323,6 +1325,7 @@
13231325 export interface MCPServerStatus extends MCPOptions {
13241326 status: MCPConnectionStatus;
13251327 errors: string[];
1328+ isProtectedResource: boolean;
13261329
13271330 prompts: MCPPrompt[];
13281331 tools: MCPTool[];
modified core/indexing/CodebaseIndexer.ts +17 −8
@@ -10,6 +10,7 @@
1010 import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
1111 import type { IMessenger } from "../protocol/messenger";
1212 import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
13+import { Logger } from "../util/Logger.js";
1314 import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
1415 import { Telemetry } from "../util/posthog.js";
1516 import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
@@ -56,7 +57,7 @@
5657 // and only need to `await` it for tests.
5758 public initPromise: Promise<void>;
5859 private config!: ContinueConfig;
59- private indexingCancellationController: AbortController | undefined;
60+ private indexingCancellationController: AbortController;
6061 private codebaseIndexingState: IndexingProgressUpdate;
6162 private readonly pauseToken: PauseToken;
6263
@@ -97,6 +98,9 @@
9798 this.pauseToken = new PauseToken(initialPaused);
9899
99100 this.initPromise = this.init(configHandler);
101+
102+ this.indexingCancellationController = new AbortController();
103+ this.indexingCancellationController.abort(); // initialize and abort so that a new one can be created
100104 }
101105
102106 // Initialization - load config and attach config listener
@@ -123,12 +127,20 @@
123127 try {
124128 await fs.unlink(sqliteFilepath);
125129 } catch (error) {
130+ // Capture indexer system failures to Sentry
131+ Logger.error(error, {
132+ filepath: sqliteFilepath,
133+ });
126134 console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
127135 }
128136
129137 try {
130138 await fs.rm(lanceDbFolder, { recursive: true, force: true });
131139 } catch (error) {
140+ // Capture indexer system failures to Sentry
141+ Logger.error(error, {
142+ folderPath: lanceDbFolder,
143+ });
132144 console.error(`Error deleting ${lanceDbFolder}: ${error}`);
133145 }
134146 }
@@ -693,7 +705,7 @@
693705 }
694706
695707 public async refreshCodebaseIndex(paths: string[]) {
696- if (this.indexingCancellationController) {
708+ if (!this.indexingCancellationController.signal.aborted) {
697709 this.indexingCancellationController.abort();
698710 }
699711 const localController = new AbortController();
@@ -735,16 +747,13 @@
735747 });
736748 }
737749 if (this.indexingCancellationController === localController) {
738- this.indexingCancellationController = undefined;
750+ this.indexingCancellationController.abort();
739751 }
740752 }
741753
742754 public async refreshCodebaseIndexFiles(files: string[]) {
743755 // Can be cancelled by codebase index but not vice versa
744- if (
745- this.indexingCancellationController &&
746- !this.indexingCancellationController.signal.aborted
747- ) {
756+ if (!this.indexingCancellationController.signal.aborted) {
748757 return;
749758 }
750759 const localController = new AbortController();
@@ -770,7 +779,7 @@
770779 });
771780 }
772781 if (this.indexingCancellationController === localController) {
773- this.indexingCancellationController = undefined;
782+ this.indexingCancellationController.abort();
774783 }
775784 }
776785
deleted core/indexing/docs/DocsCache.test.ts +0 −25
@@ -1,25 +0,0 @@
1-import OpenAI from "../../llm/llms/OpenAI";
2-import { DocsCache } from "./DocsCache"; // adjust import path as needed
3-
4-describe("DocsCache", () => {
5- let openAIEmbeddings: OpenAI;
6-
7- beforeAll(() => {
8- openAIEmbeddings = new OpenAI({
9- apiKey: "",
10- model: "text-embedding-ada-002",
11- });
12- });
13-
14- test("normalizeEmbeddingId() produces a valid ID without constructor name", async () => {
15- // Get the embedding ID from OpenAI embeddings provider
16- const embeddingId = DocsCache.normalizeEmbeddingId(
17- openAIEmbeddings.embeddingId,
18- );
19-
20- // The ID should not contain the constructor name (OpenAI)
21- expect(embeddingId).toEqual(
22- `${openAIEmbeddings.model}::${openAIEmbeddings.maxEmbeddingChunkSize}`,
23- );
24- });
25-});
deleted core/indexing/docs/DocsCache.ts +0 −93
@@ -1,93 +0,0 @@
1-import request from "request";
2-import { Chunk } from "../..";
3-
4-export interface SiteIndexingResults {
5- chunks: (Chunk & { embedding: number[] })[];
6- url: string;
7- title: string;
8-}
9-
10-/**
11- * Strip off the trailing forward slash from the given URL
12- * @param url The URL of the document
13- * @returns A sanitized URL without trailing forward slash
14- */
15-const stripTrailingSlash = (url: string): string => {
16- return url.replace(/\/+$/, "");
17-};
18-
19-export class DocsCache {
20- static readonly AWS_REGION: string = "us-west-1";
21- static readonly BUCKET_NAME: string = "continue-preindexed-docs";
22-
23- /**
24- * Normalizes an embedding ID by stripping the constructor name part.
25- * This is done because we don't care about the provider, just the
26- * model and the max embedding chunk size.
27- */
28- static normalizeEmbeddingId(embeddingId: string): string {
29- // Split by "::" and remove the first part (constructor name)
30- const parts = embeddingId.split("::");
31- if (parts.length <= 1) return embeddingId; // Return original if no "::" found
32-
33- // Return everything except the first part, joining with "::"
34- return parts.slice(1).join("::");
35- }
36-
37- /**
38- * Gets the filepath for a given embedding ID and URL
39- */
40- static getFilepathForEmbeddingIdAndUrl(
41- embeddingId: string,
42- url: string,
43- ): string {
44- const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
45- const sanitizedUrl = stripTrailingSlash(url);
46- const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
47- return normalizedEmbeddingId + "/" + normalizedUrl;
48- }
49-
50- /**
51- * Gets the fully qualified S3 URL for a given filepath
52- */
53- private static getS3Url(filepath: string): string {
54- const pathname = filepath.split("/").map(encodeURIComponent).join("/");
55- return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`;
56- }
57-
58- /**
59- * Downloads cached site indexing results from S3 for a given embedding ID and URL
60- * @param embeddingId The embedding ID
61- * @param url The URL of the document
62- * @returns The downloaded data as a string
63- */
64- static async getDocsCacheForUrl(
65- embeddingId: string,
66- url: string,
67- ): Promise<string> {
68- const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl(
69- embeddingId,
70- url,
71- );
72-
73- return new Promise<string>((resolve, reject) => {
74- let data = "";
75- const url = this.getS3Url(filepath);
76- const download = request({
77- url,
78- });
79-
80- download.on("response", (response: any) => {
81- if (response.statusCode !== 200) {
82- reject(
83- new Error("There was an error retrieving the pre-indexed doc"),
84- );
85- }
86- });
87-
88- download.on("error", (err: any) => reject(err));
89- download.on("data", (chunk: any) => (data += chunk));
90- download.on("end", () => resolve(data));
91- });
92- }
93-}
modified core/indexing/docs/DocsService.ts +0 −137
@@ -37,7 +37,6 @@
3737
3838 import type * as LanceType from "vectordb";
3939 import { LLMError } from "../../llm";
40-import { DocsCache, SiteIndexingResults } from "./DocsCache";
4140
4241 // Purposefully lowercase because lancedb converts
4342 export interface LanceDbDocsRow {
@@ -433,60 +432,6 @@
433432 }
434433 }
435434
436- /**
437- * Attempt to load document embeddings from cache
438- * @returns true if cache was successfully loaded, false otherwise
439- */
440- private async tryLoadFromCache(
441- startUrl: string,
442- embeddingId: string,
443- siteIndexingConfig: SiteIndexingConfig,
444- ): Promise<boolean> {
445- try {
446- // Set a initial status when retrieving cache
447- this.handleStatusUpdate({
448- type: "docs",
449- id: startUrl,
450- embeddingsProviderId: embeddingId,
451- isReindexing: false,
452- title: siteIndexingConfig.title,
453- debugInfo: "Loaded from cache",
454- icon: siteIndexingConfig.faviconUrl,
455- url: startUrl,
456- progress: 0,
457- description: "Try to retrieve cache",
458- status: "indexing",
459- });
460-
461- const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
462-
463- if (cacheHit) {
464- console.log(`Successfully loaded cached embeddings for ${startUrl}`);
465- // Update status to complete
466- this.handleStatusUpdate({
467- type: "docs",
468- id: startUrl,
469- embeddingsProviderId: embeddingId,
470- isReindexing: false,
471- title: siteIndexingConfig.title,
472- debugInfo: "Loaded from cache",
473- icon: siteIndexingConfig.faviconUrl,
474- url: startUrl,
475- progress: 1,
476- description: "Complete",
477- status: "complete",
478- });
479-
480- return true;
481- }
482- } catch (e) {
483- console.log(`Error trying to fetch from cache: ${e}`);
484- // Continue with regular indexing
485- }
486-
487- return false;
488- }
489-
490435 // eslint-disable-next-line max-statements
491436 async indexAndAdd(
492437 siteIndexingConfig: SiteIndexingConfig,
@@ -508,19 +453,6 @@
508453 return;
509454 }
510455
511- // Try to fetch from cache first before crawling
512- if (!forceReindex) {
513- const cacheLoaded = await this.tryLoadFromCache(
514- startUrl,
515- provider.embeddingId,
516- siteIndexingConfig,
517- );
518-
519- if (cacheLoaded) {
520- return;
521- }
522- }
523-
524456 const startedWithEmbedder = provider.embeddingId;
525457
526458 // Check if doc has been successfully indexed with the given embedder
@@ -811,52 +743,6 @@
811743 }
812744 }
813745
814- /**
815- * Try to fetch embeddings from the S3 cache for any document URL
816- * @param startUrl The URL of the documentation site
817- * @param embeddingsProviderId The ID of the embeddings provider
818- * @returns True if cache hit and successfully loaded, false otherwise
819- */
820- private async tryFetchFromCache(
821- startUrl: string,
822- embeddingId: string,
823- ): Promise<boolean> {
824- try {
825- const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl);
826-
827- // Parse the cached data
828- const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
829-
830- // Try to get a favicon for the site
831- const favicon =
832- this.statuses.get(startUrl)?.icon ||
833- (await fetchFavicon(new URL(startUrl)));
834-
835- // Always try to make the title match what users set in the config
836- const title =
837- this.statuses.get(startUrl)?.title ||
838- siteEmbeddings.title ||
839- new URL(startUrl).hostname;
840-
841- // Add the cached embeddings to our database
842- await this.add({
843- favicon,
844- siteIndexingConfig: {
845- startUrl,
846- title,
847- },
848- chunks: siteEmbeddings.chunks,
849- embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
850- });
851-
852- return true;
853- } catch (e) {
854- // Cache miss or error - silently fail
855- console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`);
856- return false;
857- }
858- }
859-
860746 // Retrieve docs embeds based on user input
861747 async retrieveChunksFromQuery(
862748 query: string,
@@ -940,7 +826,6 @@
940826 }
941827 }
942828 // This function attempts to retrieve chunks by vector similarity
943- // It will also attempt to fetch from cache if no results are found
944829 async retrieveChunks(
945830 startUrl: string,
946831 vector: number[],
@@ -970,28 +855,6 @@
970855 console.warn("Error retrieving chunks from LanceDB", e);
971856 }
972857
973- // If no docs are found and this isn't a retry, try fetching from cache
974- if (docs.length === 0 && !isRetry) {
975- try {
976- // Try to fetch the document from the S3 cache
977- const cacheHit = await this.tryFetchFromCache(
978- startUrl,
979- provider.embeddingId,
980- );
981-
982- if (cacheHit) {
983- // If cache hit, refresh the submenu items for docs
984- this.messenger?.send("refreshSubmenuItems", {
985- providers: ["docs"],
986- });
987- // If cache hit, retry the search once
988- return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
989- }
990- } catch (e) {
991- console.warn("Error trying to fetch from cache:", e);
992- }
993- }
994-
995858 return docs.map(this.lanceDBRowToChunk);
996859 }
997860
modified core/llm/autodetect.ts +1 −1
@@ -178,7 +178,7 @@
178178 // update core/nextEdit/templating/NextEditPromptEngine.ts as well.
179179 const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
180180 NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
181- NEXT_EDIT_MODELS.MODEL_1,
181+ NEXT_EDIT_MODELS.INSTINCT,
182182 ];
183183
184184 function modelSupportsNextEdit(
modified core/llm/autodetect.vitest.ts +7 −5
@@ -245,8 +245,10 @@
245245 ).toBe(true);
246246 });
247247
248- it("should return true for model-1", () => {
249- expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true);
248+ it("should return true for instinct", () => {
249+ expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe(
250+ true,
251+ );
250252 });
251253
252254 it("should return true when model contains supported model name as substring", () => {
@@ -269,9 +271,9 @@
269271 ).toBe(true);
270272 });
271273
272- it("should return true when title contains model-1", () => {
274+ it("should return true when title contains instinct", () => {
273275 expect(
274- modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"),
276+ modelSupportsNextEdit(undefined, "some-model", "instinct deployment"),
275277 ).toBe(true);
276278 });
277279
@@ -317,7 +319,7 @@
317319
318320 it("should handle case sensitivity correctly", () => {
319321 expect(
320- modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"),
322+ modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
321323 ).toBe(true);
322324 });
323325
modified core/llm/constants.ts +1 −1
@@ -21,7 +21,7 @@
2121
2222 export enum NEXT_EDIT_MODELS {
2323 MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
24- MODEL_1 = "model-1",
24+ INSTINCT = "instinct",
2525 }
2626
2727 export {
modified core/llm/index.ts +47 −0
@@ -9,6 +9,7 @@
99 import Handlebars from "handlebars";
1010
1111 import { DevDataSqliteDb } from "../data/devdataSqlite.js";
12+import { Logger } from "../util/Logger.js";
1213 import { DataLogger } from "../data/log.js";
1314 import {
1415 CacheBehavior,
@@ -471,6 +472,15 @@
471472
472473 return resp;
473474 } catch (e: any) {
475+ // Capture all fetch errors to Sentry for monitoring
476+ Logger.error(e, {
477+ context: "llm_fetch",
478+ url: String(input),
479+ method: init?.method || "GET",
480+ model: this.model,
481+ provider: this.providerName,
482+ });
483+
474484 // Errors to ignore
475485 if (e.message.includes("/api/tags")) {
476486 throw new Error(`Error fetching tags: ${e.message}`);
@@ -635,6 +645,14 @@
635645 undefined,
636646 );
637647 } catch (e) {
648+ // Capture FIM (Fill-in-the-Middle) completion failures to Sentry
649+ Logger.error(e as Error, {
650+ context: "llm_stream_fim",
651+ model: completionOptions.model,
652+ provider: this.providerName,
653+ useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamFim"),
654+ });
655+
638656 status = this._logEnd(
639657 completionOptions.model,
640658 fimLog,
@@ -753,6 +771,15 @@
753771 undefined,
754772 );
755773 } catch (e) {
774+ // Capture streaming completion failures to Sentry
775+ Logger.error(e as Error, {
776+ context: "llm_stream_complete",
777+ model: completionOptions.model,
778+ provider: this.providerName,
779+ useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamComplete"),
780+ streamEnabled: completionOptions.stream !== false,
781+ });
782+
756783 status = this._logEnd(
757784 completionOptions.model,
758785 prompt,
@@ -779,6 +806,7 @@
779806
780807 return {
781808 modelTitle: this.title ?? completionOptions.model,
809+ modelProvider: this.underlyingProviderName,
782810 prompt,
783811 completion,
784812 completionOptions,
@@ -850,6 +878,14 @@
850878 undefined,
851879 );
852880 } catch (e) {
881+ // Capture completion failures to Sentry
882+ Logger.error(e as Error, {
883+ context: "llm_complete",
884+ model: completionOptions.model,
885+ provider: this.providerName,
886+ useOpenAIAdapter: this.shouldUseOpenAIAdapter("complete"),
887+ });
888+
853889 status = this._logEnd(
854890 completionOptions.model,
855891 prompt,
@@ -1059,6 +1095,16 @@
10591095 usage,
10601096 );
10611097 } catch (e) {
1098+ // Capture chat streaming failures to Sentry
1099+ Logger.error(e as Error, {
1100+ context: "llm_stream_chat",
1101+ model: completionOptions.model,
1102+ provider: this.providerName,
1103+ useOpenAIAdapter: this.shouldUseOpenAIAdapter("streamChat"),
1104+ streamEnabled: completionOptions.stream !== false,
1105+ templateMessages: !!this.templateMessages,
1106+ });
1107+
10621108 status = this._logEnd(
10631109 completionOptions.model,
10641110 prompt,
@@ -1094,6 +1140,7 @@
10941140
10951141 return {
10961142 modelTitle: this.title ?? completionOptions.model,
1143+ modelProvider: this.underlyingProviderName,
10971144 prompt,
10981145 completion,
10991146 completionOptions,
modified core/llm/llm-pre-fetch.vitest.ts +1 −0
@@ -23,6 +23,7 @@
2323 model: "",
2424 },
2525 modelTitle: "",
26+ modelProvider: "",
2627 prompt: "",
2728 });
2829 abortController.abort();
modified core/llm/llms/Voyage.ts +19 −2
@@ -1,7 +1,21 @@
1-import { Chunk, LLMOptions } from "../../index.js";
1+import { z } from "zod";
22
3+import { Chunk, LLMOptions } from "../../index.js";
34 import OpenAI from "./OpenAI.js";
45
6+/**used to check a valid response from voyage is received
7+ * reference: https://docs.voyageai.com/reference/reranker-api
8+ */
9+const VoyageRerankSuccessResponseSchema = z.object({
10+ data: z.array(
11+ z.object({
12+ index: z.number(),
13+ relevance_score: z.number(),
14+ document: z.string(),
15+ }),
16+ ),
17+});
18+
519 class Voyage extends OpenAI {
620 static providerName = "voyage";
721 static defaultOptions: Partial<LLMOptions> | undefined = {
@@ -36,7 +50,10 @@
3650 const data = (await resp.json()) as {
3751 data: Array<{ index: number; relevance_score: number }>;
3852 };
39- const results = data.data.sort((a, b) => a.index - b.index);
53+
54+ const parsedData = VoyageRerankSuccessResponseSchema.parse(data);
55+
56+ const results = parsedData.data.sort((a, b) => a.index - b.index);
4057 return results.map((result) => result.relevance_score);
4158 }
4259 }
modified core/llm/streamChat.ts +121 −98
@@ -40,6 +40,7 @@
4040 // Log to return in case of error
4141 const errorPromptLog = {
4242 modelTitle: model?.title ?? model?.model,
43+ modelProvider: model?.underlyingProviderName ?? "unknown",
4344 completion: "",
4445 prompt: "",
4546 completionOptions: {
@@ -48,114 +49,136 @@
4849 },
4950 };
5051
51- if (legacySlashCommandData) {
52- const { command, contextItems, historyIndex, input, selectedCode } =
53- legacySlashCommandData;
54- const slashCommand = config.slashCommands?.find(
55- (sc) => sc.name === command.name,
56- );
57- if (!slashCommand) {
58- throw new Error(`Unknown slash command ${command.name}`);
59- }
60- void Telemetry.capture(
61- "useSlashCommand",
62- {
63- name: command.name,
64- },
65- true,
66- );
67- if (!slashCommand.run) {
68- console.error(
69- `Slash command ${command.name} (${command.source}) has no run function`,
52+ try {
53+ if (legacySlashCommandData) {
54+ const { command, contextItems, historyIndex, input, selectedCode } =
55+ legacySlashCommandData;
56+ const slashCommand = config.slashCommands?.find(
57+ (sc) => sc.name === command.name,
7058 );
71- throw new Error(`Slash command not found`);
72- }
59+ if (!slashCommand) {
60+ throw new Error(`Unknown slash command ${command.name}`);
61+ }
62+ void Telemetry.capture(
63+ "useSlashCommand",
64+ {
65+ name: command.name,
66+ },
67+ true,
68+ );
69+ if (!slashCommand.run) {
70+ console.error(
71+ `Slash command ${command.name} (${command.source}) has no run function`,
72+ );
73+ throw new Error(`Slash command not found`);
74+ }
7375
74- const gen = slashCommand.run({
75- input,
76- history: messages,
77- llm: model,
78- contextItems,
79- params: command.params,
80- ide,
81- addContextItem: (item) => {
82- void messenger.request("addContextItem", {
83- item,
84- historyIndex,
85- });
86- },
87- selectedCode,
88- config,
89- fetch: (url, init) =>
90- fetchwithRequestOptions(
91- url,
92- {
93- ...init,
94- signal: abortController.signal,
95- },
96- config.requestOptions,
97- ),
98- completionOptions,
99- abortController,
100- });
101- let next = await gen.next();
102- while (!next.done) {
103- if (abortController.signal.aborted) {
104- next = await gen.return(errorPromptLog);
105- break;
76+ const gen = slashCommand.run({
77+ input,
78+ history: messages,
79+ llm: model,
80+ contextItems,
81+ params: command.params,
82+ ide,
83+ addContextItem: (item) => {
84+ void messenger.request("addContextItem", {
85+ item,
86+ historyIndex,
87+ });
88+ },
89+ selectedCode,
90+ config,
91+ fetch: (url, init) =>
92+ fetchwithRequestOptions(
93+ url,
94+ {
95+ ...init,
96+ signal: abortController.signal,
97+ },
98+ config.requestOptions,
99+ ),
100+ completionOptions,
101+ abortController,
102+ });
103+ let next = await gen.next();
104+ while (!next.done) {
105+ if (abortController.signal.aborted) {
106+ next = await gen.return(errorPromptLog);
107+ break;
108+ }
109+ if (next.value) {
110+ yield {
111+ role: "assistant",
112+ content: next.value,
113+ };
114+ }
115+ next = await gen.next();
106116 }
107- if (next.value) {
108- yield {
109- role: "assistant",
110- content: next.value,
111- };
117+ if (!next.done) {
118+ throw new Error("Will never happen");
112119 }
113- next = await gen.next();
114- }
115- if (!next.done) {
116- throw new Error("Will never happen");
117- }
118120
119- return next.value;
120- } else {
121- const gen = model.streamChat(
122- messages,
123- abortController.signal,
124- completionOptions,
125- messageOptions,
126- );
127- let next = await gen.next();
128- while (!next.done) {
129- if (abortController.signal.aborted) {
130- next = await gen.return(errorPromptLog);
131- break;
121+ return next.value;
122+ } else {
123+ const gen = model.streamChat(
124+ messages,
125+ abortController.signal,
126+ completionOptions,
127+ messageOptions,
128+ );
129+ let next = await gen.next();
130+ while (!next.done) {
131+ if (abortController.signal.aborted) {
132+ next = await gen.return(errorPromptLog);
133+ break;
134+ }
135+
136+ const chunk = next.value;
137+
138+ yield chunk;
139+ next = await gen.next();
140+ }
141+ if (config.experimental?.readResponseTTS && "completion" in next.value) {
142+ void TTS.read(next.value?.completion);
132143 }
133144
134- const chunk = next.value;
145+ void Telemetry.capture(
146+ "chat",
147+ {
148+ model: model.model,
149+ provider: model.providerName,
150+ },
151+ true,
152+ );
135153
136- yield chunk;
137- next = await gen.next();
138- }
139- if (config.experimental?.readResponseTTS && "completion" in next.value) {
140- void TTS.read(next.value?.completion);
141- }
154+ void checkForFreeTrialExceeded(configHandler, messenger);
142155
143- void Telemetry.capture(
144- "chat",
145- {
146- model: model.model,
147- provider: model.providerName,
148- },
149- true,
150- );
151-
152- void checkForFreeTrialExceeded(configHandler, messenger);
153-
154- if (!next.done) {
155- throw new Error("Will never happen");
156- }
156+ if (!next.done) {
157+ throw new Error("Will never happen");
158+ }
157159
158- return next.value;
160+ return next.value;
161+ }
162+ } catch (error) {
163+ if (
164+ error instanceof Error &&
165+ error.message.toLowerCase().includes("premature close")
166+ ) {
167+ void Telemetry.capture(
168+ "stream_premature_close_error",
169+ {
170+ model: model.model,
171+ provider: model.providerName,
172+ errorMessage: error.message,
173+ context: legacySlashCommandData ? "slash_command" : "regular_chat",
174+ ...(legacySlashCommandData && {
175+ command: legacySlashCommandData.command.name,
176+ }),
177+ },
178+ false,
179+ );
180+ }
181+ throw error;
159182 }
160183 }
161184
modified core/nextEdit/NextEditEditableRegionCalculator.ts +73 −30
@@ -1,11 +1,9 @@
11 import Parser from "web-tree-sitter";
22 import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from "..";
33 import { getAst } from "../autocomplete/util/ast";
4+import { NEXT_EDIT_MODELS } from "../llm/constants";
45 import { DocumentHistoryTracker } from "./DocumentHistoryTracker";
5-import {
6- NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
7- NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
8-} from "./constants";
6+import { MODEL_WINDOW_SIZES } from "./constants";
97
108 export enum EditableRegionStrategy {
119 Naive = "naive",
@@ -60,16 +58,16 @@
6058
6159 // Sliding splits the file using into sliding window.
6260 function slidingJump(ctx: any): RangeInFile[] | null {
63- const { fileLines, filepath } = ctx;
64- if (!fileLines || !filepath) {
65- console.warn("Missing required context for naive jump");
61+ const { fileLines, filepath, modelName, currentCursorPos } = ctx;
62+ if (!fileLines || !filepath || !modelName || !currentCursorPos) {
63+ console.warn("Missing required context for sliding jump");
6664 return null;
6765 }
6866
69- const windowSize =
70- NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN +
71- NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN +
72- 1; // 1 for current line;
67+ const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin;
68+ const bottomMargin =
69+ MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin;
70+ const windowSize = topMargin + bottomMargin + 1; // 1 for current line
7371
7472 if (fileLines.length <= windowSize) {
7573 return [
@@ -86,29 +84,74 @@
8684 ];
8785 }
8886
89- const slidingStep = Math.max(1, Math.floor(windowSize / 2));
9087 const ranges: RangeInFile[] = [];
88+ const cursorLine = currentCursorPos.line;
9189
92- for (
93- let startLine = 0;
94- startLine < fileLines.length;
95- startLine += slidingStep
96- ) {
97- const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1);
98-
99- ranges.push({
100- filepath,
101- range: {
102- start: { line: startLine, character: 0 },
103- end: {
104- line: endLine,
105- character: fileLines[endLine].length,
106- },
90+ // Create the first window centered around the cursor position
91+ const firstWindowStart = Math.max(0, cursorLine - topMargin);
92+ const firstWindowEnd = Math.min(
93+ fileLines.length - 1,
94+ cursorLine + bottomMargin,
95+ );
96+
97+ ranges.push({
98+ filepath,
99+ range: {
100+ start: { line: firstWindowStart, character: 0 },
101+ end: {
102+ line: firstWindowEnd,
103+ character: fileLines[firstWindowEnd].length,
107104 },
108- });
105+ },
106+ });
107+
108+ // Alternating pattern: down once, up once, repeat
109+ const slidingStep = Math.max(1, Math.floor(windowSize / 2));
110+ let currentStartDown = firstWindowEnd + 1;
111+ let currentStartUp = firstWindowStart - slidingStep;
112+ while (currentStartDown < fileLines.length || currentStartUp >= 0) {
113+ // Go down once
114+ if (currentStartDown < fileLines.length) {
115+ const windowStart = currentStartDown;
116+ const windowEnd = Math.min(
117+ windowStart + windowSize - 1,
118+ fileLines.length - 1,
119+ );
120+
121+ ranges.push({
122+ filepath,
123+ range: {
124+ start: { line: windowStart, character: 0 },
125+ end: {
126+ line: windowEnd,
127+ character: fileLines[windowEnd].length,
128+ },
129+ },
130+ });
131+
132+ currentStartDown += slidingStep;
133+ }
134+
135+ // Go up once
136+ if (currentStartUp >= 0) {
137+ const windowStart = Math.max(0, currentStartUp);
138+ const windowEnd = Math.min(
139+ windowStart + windowSize - 1,
140+ fileLines.length - 1,
141+ );
142+
143+ ranges.push({
144+ filepath,
145+ range: {
146+ start: { line: windowStart, character: 0 },
147+ end: {
148+ line: windowEnd,
149+ character: fileLines[windowEnd].length,
150+ },
151+ },
152+ });
109153
110- if (endLine >= fileLines.length - 1) {
111- break;
154+ currentStartUp -= slidingStep;
112155 }
113156 }
114157
modified core/nextEdit/NextEditPrefetchQueue.ts +25 −2
@@ -2,7 +2,7 @@
22 import { NextEditProvider } from "./NextEditProvider";
33 import { NextEditOutcome } from "./types";
44
5-interface ProcessedItem {
5+export interface ProcessedItem {
66 location: RangeInFile;
77 outcome: NextEditOutcome; // Result from the model
88 }
@@ -59,6 +59,11 @@
5959 !this.abortController.signal.aborted
6060 ) {
6161 const location = this.dequeueUnprocessed();
62+ console.log("processing:");
63+ console.log(
64+ location?.range.start.line + " to " + location?.range.end.line,
65+ );
66+
6267 if (!location) break;
6368
6469 try {
@@ -70,12 +75,20 @@
7075 this.usingFullFileDiff,
7176 );
7277
73- if (!outcome) continue;
78+ if (!outcome) {
79+ console.log("outcome is undefined");
80+ continue;
81+ }
7482
7583 this.enqueueProcessed({
7684 location,
7785 outcome,
7886 });
87+
88+ console.log(
89+ "the length of processed queue after processing is:",
90+ this.processedQueue.length,
91+ );
7992 } catch (error) {
8093 if (!this.abortController.signal.aborted) {
8194 // Handle error
@@ -115,6 +128,16 @@
115128 return this.processedQueue[0];
116129 }
117130
131+ peekThreeProcessed(): void {
132+ const count = Math.min(3, this.processedQueue.length);
133+ const firstThree = this.processedQueue.slice(0, count);
134+ firstThree.forEach((item, index) => {
135+ console.log(
136+ `Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`,
137+ );
138+ });
139+ }
140+
118141 setPreetchLimit(limit: number): void {
119142 this.prefetchLimit = limit;
120143 }
modified core/nextEdit/NextEditProvider.ts +90 −35
@@ -33,12 +33,11 @@
3333 import { modelSupportsNextEdit } from "../llm/autodetect.js";
3434 import { countTokens } from "../llm/countTokens.js";
3535 import { localPathOrUriToPath } from "../util/pathToUri.js";
36-import { replaceEscapedCharacters } from "../util/text.js";
3736 import {
37+ INSTINCT_SYSTEM_PROMPT,
3838 MERCURY_CODE_TO_EDIT_OPEN,
3939 MERCURY_SYSTEM_PROMPT,
40- NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
41- NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
40+ MODEL_WINDOW_SIZES,
4241 } from "./constants.js";
4342 import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
4443 import {
@@ -60,6 +59,7 @@
6059 PromptMetadata,
6160 RecentlyEditedRange,
6261 } from "./types.js";
62+import { isWhitespaceOnlyDeletion } from "./utils.js";
6363
6464 const autocompleteCache = AutocompleteLruCache.get();
6565
@@ -82,7 +82,8 @@
8282 private loggingService: NextEditLoggingService;
8383 private contextRetrievalService: ContextRetrievalService;
8484 private endpointType: "default" | "fineTuned";
85- private diffContext: string = "";
85+ private diffContext: string[] = [];
86+ private autocompleteContext: string = "";
8687 private promptMetadata: PromptMetadata | null = null;
8788 private currentEditChainId: string | null = null;
8889 private previousRequest: AutocompleteInput | null = null;
@@ -134,7 +135,14 @@
134135 }
135136
136137 public addDiffToContext(diff: string): void {
137- this.diffContext = diff;
138+ this.diffContext.push(diff);
139+ if (this.diffContext.length > 5) {
140+ this.diffContext.shift();
141+ }
142+ }
143+
144+ public addAutocompleteContext(ctx: string): void {
145+ this.autocompleteContext = ctx;
138146 }
139147
140148 private async _prepareLlm(): Promise<ILLM | undefined> {
@@ -384,16 +392,20 @@
384392 this.ide.getWorkspaceDirs(),
385393 ]);
386394
395+ const modelName = helper.modelName.includes("mercury-coder-nextedit")
396+ ? "mercury-coder-nextedit"
397+ : "instinct";
398+
387399 const { editableRegionStartLine, editableRegionEndLine } =
388400 opts?.usingFullFileDiff
389401 ? this._calculateOptimalEditableRegion(helper, "tokenizer")
390402 : {
391403 editableRegionStartLine: Math.max(
392- helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
404+ helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
393405 0,
394406 ),
395407 editableRegionEndLine: Math.min(
396- helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
408+ helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
397409 helper.fileLines.length - 1,
398410 ),
399411 };
@@ -552,11 +564,40 @@
552564 editDiffHistory: this.diffContext,
553565 currentFilePath: helper.filepath,
554566 };
555- } else if (modelName.includes("model-1")) {
567+ } else if (modelName.includes("instinct")) {
568+ // Calculate the window around the cursor position (25 lines above and below).
569+ const windowStart = Math.max(0, helper.pos.line - 25);
570+ const windowEnd = Math.min(
571+ helper.fileLines.length - 1,
572+ helper.pos.line + 25,
573+ );
574+
575+ // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
576+ // const actualEditableStart = Math.max(
577+ // 0,
578+ // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
579+ // );
580+ // const actualEditableEnd = Math.min(
581+ // helper.fileLines.length - 1,
582+ // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
583+ // );
584+
585+ // Ensure editable region boundaries are within the window.
586+ const adjustedEditableStart = Math.max(
587+ windowStart,
588+ editableRegionStartLine,
589+ );
590+ const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
556591 ctx = {
557- userEdits: historyDiff ?? this.diffContext,
592+ contextSnippets: this.autocompleteContext,
593+ currentFileContent: helper.fileContents,
594+ windowStart,
595+ windowEnd,
596+ editableRegionStartLine: adjustedEditableStart,
597+ editableRegionEndLine: adjustedEditableEnd,
598+ editDiffHistory: this.diffContext,
599+ currentFilePath: helper.filepath,
558600 languageShorthand: helper.lang.name,
559- userExcerpts: helper.fileContents,
560601 };
561602 } else {
562603 ctx = {};
@@ -567,7 +608,9 @@
567608
568609 const systemPrompt: Prompt = {
569610 role: "system",
570- content: MERCURY_SYSTEM_PROMPT,
611+ content: modelName.includes("mercury-coder-nextedit")
612+ ? MERCURY_SYSTEM_PROMPT
613+ : INSTINCT_SYSTEM_PROMPT,
571614 };
572615
573616 return [systemPrompt, promptMetadata.prompt];
@@ -635,27 +678,34 @@
635678 if (!llm) return undefined;
636679
637680 const msg: ChatMessage = await llm.chat(prompts, token);
681+ console.log("message");
682+ console.log(msg.content);
638683
639684 if (typeof msg.content !== "string") {
640685 return undefined;
641686 }
642687
643- const nextCompletion = msg.content.split(
644- `${MERCURY_CODE_TO_EDIT_OPEN}\n`,
645- )[1]
646- ? replaceEscapedCharacters(
647- msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
648- ).replace(/\n$/, "")
649- : "";
688+ // const nextCompletion = msg.content.split(
689+ // `${MERCURY_CODE_TO_EDIT_OPEN}\n`,
690+ // )[1]
691+ // ? replaceEscapedCharacters(
692+ // msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
693+ // ).replace(/\n$/, "")
694+ // : replaceEscapedCharacters(msg.content);
695+ const nextCompletion =
696+ msg.content
697+ .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
698+ .replace(/\n$/, "") ?? msg.content;
650699
651700 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
652701 return await this._handlePartialFileDiff(
702+ // we could use fillFileDiff
653703 helper,
704+ editableRegionStartLine,
705+ editableRegionEndLine,
654706 startTime,
655707 llm,
656708 nextCompletion,
657- editableRegionStartLine,
658- editableRegionEndLine,
659709 );
660710 } else {
661711 return await this._handleFullFileDiff(
@@ -671,11 +721,11 @@
671721
672722 private async _handlePartialFileDiff(
673723 helper: HelperVars,
724+ editableRegionStartLine: number,
725+ editableRegionEndLine: number,
674726 startTime: number,
675727 llm: ILLM,
676728 nextCompletion: string,
677- editableRegionStartLine: number,
678- editableRegionEndLine: number,
679729 ): Promise<NextEditOutcome | undefined> {
680730 const oldEditRangeSlice = helper.fileContents
681731 .split("\n")
@@ -727,13 +777,16 @@
727777 .slice(editableRegionStartLine, editableRegionEndLine + 1)
728778 .join("\n");
729779 const diffLines = myersDiff(fileSlice, nextCompletion);
730- const diffGroups = groupDiffLines(diffLines, editableRegionStartLine, 5);
780+ const diffGroups = groupDiffLines(
781+ diffLines,
782+ editableRegionStartLine,
783+ 5,
784+ ).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
731785 const currentLine = helper.pos.line;
732- let cursorLocalDiffGroup: DiffGroup | undefined;
733786 const prefetchQueue = PrefetchQueue.getInstance();
734787
735788 // Process diff groups and find the one containing the cursor
736- await this._processDiffGroups(
789+ const cursorLocalDiffGroup = await this._processDiffGroups(
737790 diffGroups,
738791 currentLine,
739792 helper,
@@ -752,16 +805,16 @@
752805 helper.input.completionId,
753806 true,
754807 );
755- } else if (diffGroups.length > 0) {
756- // Fallback to first diff group if cursor's group not found
757- return await this._createOutcomeFromDiffGroup(
758- diffGroups[0],
759- helper,
760- startTime,
761- llm,
762- helper.input.completionId,
763- false,
764- );
808+ // } else if (diffGroups.length > 0) {
809+ // // Fallback to first diff group if cursor's group not found
810+ // return await this._createOutcomeFromDiffGroup(
811+ // diffGroups[0],
812+ // helper,
813+ // startTime,
814+ // llm,
815+ // helper.input.completionId,
816+ // false,
817+ // );
765818 }
766819
767820 return undefined;
@@ -985,6 +1038,7 @@
9851038 try {
9861039 const previousOutcome = this.getPreviousCompletion();
9871040 if (!previousOutcome) {
1041+ console.log("previousOutcome is undefined");
9881042 return undefined;
9891043 }
9901044
@@ -995,6 +1049,7 @@
9951049 ctx,
9961050 );
9971051 if (!input) {
1052+ console.log("input is undefined");
9981053 return undefined;
9991054 }
10001055
modified core/nextEdit/constants.ts +43 −3
@@ -1,11 +1,51 @@
1+import { NEXT_EDIT_MODELS } from "../llm/constants";
2+
13 export const IS_NEXT_EDIT_ACTIVE = false;
24 export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
35 export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
46
7+export const MODEL_WINDOW_SIZES: Record<
8+ NEXT_EDIT_MODELS,
9+ { topMargin: number; bottomMargin: number }
10+> = {
11+ "mercury-coder-nextedit": {
12+ topMargin: 0,
13+ bottomMargin: 5,
14+ }, // mercury coder nextedit uses full file diff, so this should be unnecessary
15+ instinct: { topMargin: 1, bottomMargin: 5 },
16+};
17+
518 // Model 1-specific tokens.
6-export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
7-export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
8-export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
19+export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
20+export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
21+export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
22+export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>";
23+export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>";
24+export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags.
25+
26+You have access to the following information to help you make informed suggestions:
27+
28+- Context: In the section marked "### Context", there are context items from potentially relevant files in the developer's codebase. Each context item consists of a <|context_file|> marker, the filepath, a <|snippet|> marker, and then some content from that file, in that order. Keep in mind that not all of the context information may be relevant to the task, so use your judgement to determine which parts to consider.
29+- User Edits: In the section marked "### User Edits:", there is a record of the most recent changes made to the code, helping you understand the evolution of the code and the developer's intentions. These changes are listed from most recent to least recent. It's possible that some of the edit diff history is entirely irrelevant to the developer's change. The changes are provided in a unified line-diff format, i.e. with pluses and minuses for additions and deletions to the code.
30+- User Excerpt: In the section marked "### User Excerpt:", there is a filepath to the developer's current file, and then an excerpt from that file. The <|editable_region_start|> and <|editable_region_end|> markers are within this excerpt. Your job is to rewrite only this editable region, not the whole excerpt. The excerpt provides additional context on the surroundings of the developer's edit.
31+- Cursor Position: Within the user excerpt's editable region, the <|user_cursor_is_here|> flag indicates where the developer's cursor is currently located, which can be crucial for understanding what part of the code they are focusing on. Do not produce this marker in your output; simply take it into account.
32+
33+Your task is to predict and complete the changes the developer would have made next in the editable region. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they're following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn't get distracted by ensuring your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.
34+
35+# Steps
36+
37+1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.
38+2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.
39+3. **Suggest Edits**: If changes are required, ensure they align with the developer's patterns and improve code quality.
40+4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.
41+
42+# Output Format
43+
44+- Provide only the revised code within the tags. Do not include the tags in your output.
45+- Ensure that you do not output duplicate code that exists outside of these tags.
46+- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`;
47+export const INSTINCT_USER_PROMPT_PREFIX =
48+ "Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code.";
949
1050 // Mercury Coder Next Edit-specific tokens.
1151 export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN =
modified core/nextEdit/context/diffFormatting.ts +136 −0
@@ -95,3 +95,139 @@
9595 // TODO: Implement token line diff
9696 return "";
9797 };
98+
99+export interface DiffMetadata {
100+ oldFilename?: string; // Filename in the original version
101+ newFilename?: string; // Filename in the modified version
102+ oldTimestamp?: string; // Timestamp of the original file
103+ newTimestamp?: string; // Timestamp of the modified file
104+ hunks?: Array<{
105+ // Information about each change hunk
106+ oldStart: number; // Starting line in original file
107+ oldCount: number; // Number of lines in original file
108+ newStart: number; // Starting line in modified file
109+ newCount: number; // Number of lines in modified file
110+ header?: string; // Optional section header
111+ lines: Array<{
112+ type: "context" | "addition" | "deletion";
113+ content: string;
114+ oldLineNumber?: number;
115+ newLineNumber?: number;
116+ }>;
117+ }>;
118+ isBinary?: boolean; // Whether this is a binary file diff
119+ isNew?: boolean; // Whether this is a new file
120+ isDeleted?: boolean; // Whether this file was deleted
121+ isRename?: boolean; // Whether this file was renamed
122+}
123+
124+export function extractMetadataFromUnifiedDiff(
125+ unifiedDiff: string,
126+): DiffMetadata {
127+ const metadata: DiffMetadata = {};
128+ const lines = unifiedDiff.split("\n");
129+
130+ // Parse the header lines (first two lines)
131+ if (lines.length >= 2) {
132+ // Parse original file info (--- line)
133+ const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/);
134+ if (oldFileMatch) {
135+ metadata.oldFilename = oldFileMatch[2];
136+ metadata.oldTimestamp = oldFileMatch[3];
137+
138+ // Check if this is a new file
139+ if (metadata.oldFilename === "/dev/null") {
140+ metadata.isNew = true;
141+ }
142+ }
143+
144+ // Parse modified file info (+++ line)
145+ const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/);
146+ if (newFileMatch) {
147+ metadata.newFilename = newFileMatch[2];
148+ metadata.newTimestamp = newFileMatch[3];
149+
150+ // Check if this file was deleted
151+ if (metadata.newFilename === "/dev/null") {
152+ metadata.isDeleted = true;
153+ }
154+ }
155+
156+ // Check if this is a rename (different old and new names)
157+ if (
158+ metadata.oldFilename &&
159+ metadata.newFilename &&
160+ metadata.oldFilename !== "/dev/null" &&
161+ metadata.newFilename !== "/dev/null" &&
162+ metadata.oldFilename !== metadata.newFilename
163+ ) {
164+ metadata.isRename = true;
165+ }
166+ }
167+
168+ // Parse hunk headers and content
169+ metadata.hunks = [];
170+ const hunkHeaderRegex =
171+ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/;
172+
173+ let currentHunk: NonNullable<DiffMetadata["hunks"]>[0] | null = null;
174+ let oldLineNumber = 0;
175+ let newLineNumber = 0;
176+
177+ for (let i = 2; i < lines.length; i++) {
178+ const line = lines[i];
179+ const hunkMatch = line.match(hunkHeaderRegex);
180+
181+ if (hunkMatch) {
182+ currentHunk = {
183+ oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file
184+ oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified
185+ newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file
186+ newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified
187+ header: hunkMatch[5], // the line starting with @@
188+ lines: [], // the actual line changes
189+ };
190+
191+ oldLineNumber = currentHunk.oldStart;
192+ newLineNumber = currentHunk.newStart;
193+
194+ metadata.hunks.push(currentHunk);
195+ } else if (
196+ currentHunk &&
197+ (line.startsWith(" ") || line.startsWith("+") || line.startsWith("-"))
198+ ) {
199+ // Process hunk content lines.
200+ const lineType = line[0];
201+ const content = line.slice(1);
202+
203+ if (lineType === " ") {
204+ // Context line (unchanged).
205+ currentHunk.lines.push({
206+ type: "context",
207+ content,
208+ oldLineNumber: oldLineNumber++,
209+ newLineNumber: newLineNumber++,
210+ });
211+ } else if (lineType === "+") {
212+ currentHunk.lines.push({
213+ type: "addition",
214+ content,
215+ newLineNumber: newLineNumber++,
216+ });
217+ } else if (lineType === "-") {
218+ currentHunk.lines.push({
219+ type: "deletion",
220+ content,
221+ oldLineNumber: oldLineNumber++,
222+ });
223+ }
224+ }
225+
226+ // Check for binary file marker
227+ if (line.includes("Binary files") || line.includes("GIT binary patch")) {
228+ metadata.isBinary = true;
229+ }
230+ }
231+
232+ return metadata;
233+}
added core/nextEdit/context/diffFormatting.vitest.ts +462 −0
@@ -0,0 +1,462 @@
1+import { describe, expect, it } from "vitest";
2+import {
3+ BeforeAfterDiff,
4+ createBeforeAfterDiff,
5+ createDiff,
6+ CreateDiffArgs,
7+ DiffFormatType,
8+ DiffMetadata,
9+ extractMetadataFromUnifiedDiff,
10+} from "./diffFormatting";
11+
12+describe("diffFormatting", () => {
13+ const sampleFilePath = "test/sample.js";
14+ const beforeContent = "const a = 1;\nconst b = 2;";
15+ const afterContent = "const a = 1;\nconst b = 3;\nconst c = 4;";
16+
17+ describe("createDiff", () => {
18+ it("should create unified diff when specified", () => {
19+ const args: CreateDiffArgs = {
20+ beforeContent,
21+ afterContent,
22+ filePath: sampleFilePath,
23+ diffType: DiffFormatType.Unified,
24+ contextLines: 3,
25+ };
26+
27+ const result = createDiff(args);
28+
29+ expect(result).toContain("---");
30+ expect(result).toContain("+++");
31+ expect(result).toContain("@@");
32+ expect(result).toContain("-const b = 2;");
33+ expect(result).toContain("+const b = 3;");
34+ expect(result).toContain("+const c = 4;");
35+ });
36+
37+ it("should create token line diff when specified", () => {
38+ const args: CreateDiffArgs = {
39+ beforeContent,
40+ afterContent,
41+ filePath: sampleFilePath,
42+ diffType: DiffFormatType.TokenLineDiff,
43+ contextLines: 3,
44+ };
45+
46+ const result = createDiff(args);
47+
48+ // Currently returns empty string as TODO
49+ expect(result).toBe("");
50+ });
51+
52+ it("should return empty string for unsupported diff types", () => {
53+ const args: CreateDiffArgs = {
54+ beforeContent,
55+ afterContent,
56+ filePath: sampleFilePath,
57+ diffType: DiffFormatType.RawBeforeAfter,
58+ contextLines: 3,
59+ };
60+
61+ const result = createDiff(args);
62+
63+ expect(result).toBe("");
64+ });
65+
66+ it("should handle empty content", () => {
67+ const args: CreateDiffArgs = {
68+ beforeContent: "",
69+ afterContent: "new content",
70+ filePath: sampleFilePath,
71+ diffType: DiffFormatType.Unified,
72+ contextLines: 3,
73+ };
74+
75+ const result = createDiff(args);
76+
77+ expect(result).toContain("+++");
78+ expect(result).toContain("+new content");
79+ });
80+
81+ it("should handle deletion", () => {
82+ const args: CreateDiffArgs = {
83+ beforeContent: "old content",
84+ afterContent: "",
85+ filePath: sampleFilePath,
86+ diffType: DiffFormatType.Unified,
87+ contextLines: 3,
88+ };
89+
90+ const result = createDiff(args);
91+
92+ expect(result).toContain("---");
93+ expect(result).toContain("-old content");
94+ });
95+
96+ it("should handle content without newlines", () => {
97+ const args: CreateDiffArgs = {
98+ beforeContent: "line1",
99+ afterContent: "line2",
100+ filePath: sampleFilePath,
101+ diffType: DiffFormatType.Unified,
102+ contextLines: 3,
103+ };
104+
105+ const result = createDiff(args);
106+
107+ expect(result).toContain("-line1");
108+ expect(result).toContain("+line2");
109+ });
110+
111+ it("should respect contextLines parameter", () => {
112+ const multiLineContent = Array(10)
113+ .fill("line")
114+ .map((l, i) => `${l}${i}`)
115+ .join("\n");
116+ const modifiedContent = multiLineContent.replace("line5", "modified5");
117+
118+ const args: CreateDiffArgs = {
119+ beforeContent: multiLineContent,
120+ afterContent: modifiedContent,
121+ filePath: sampleFilePath,
122+ diffType: DiffFormatType.Unified,
123+ contextLines: 2,
124+ };
125+
126+ const result = createDiff(args);
127+
128+ expect(result).toContain("@@ -4,5 +4,5 @@");
129+ });
130+ });
131+
132+ describe("createBeforeAfterDiff", () => {
133+ it("should return BeforeAfterDiff with normalized content", () => {
134+ const result: BeforeAfterDiff = createBeforeAfterDiff(
135+ beforeContent,
136+ afterContent,
137+ sampleFilePath,
138+ );
139+
140+ expect(result).toEqual({
141+ filePath: sampleFilePath,
142+ beforeContent: beforeContent + "\n",
143+ afterContent: afterContent + "\n",
144+ });
145+ });
146+
147+ it("should not add extra newline if content already ends with one", () => {
148+ const contentWithNewline = "const a = 1;\n";
149+ const result: BeforeAfterDiff = createBeforeAfterDiff(
150+ contentWithNewline,
151+ contentWithNewline,
152+ sampleFilePath,
153+ );
154+
155+ expect(result.beforeContent).toBe(contentWithNewline);
156+ expect(result.afterContent).toBe(contentWithNewline);
157+ });
158+
159+ it("should handle empty content", () => {
160+ const result: BeforeAfterDiff = createBeforeAfterDiff(
161+ "",
162+ "",
163+ sampleFilePath,
164+ );
165+
166+ expect(result).toEqual({
167+ filePath: sampleFilePath,
168+ beforeContent: "\n",
169+ afterContent: "\n",
170+ });
171+ });
172+
173+ it("should handle mixed newline scenarios", () => {
174+ const beforeWithNewline = "line1\n";
175+ const afterWithoutNewline = "line2";
176+ const result: BeforeAfterDiff = createBeforeAfterDiff(
177+ beforeWithNewline,
178+ afterWithoutNewline,
179+ sampleFilePath,
180+ );
181+
182+ expect(result.beforeContent).toBe("line1\n");
183+ expect(result.afterContent).toBe("line2\n");
184+ });
185+ });
186+
187+ describe("extractMetadataFromUnifiedDiff", () => {
188+ it("should extract basic file information", () => {
189+ const unifiedDiff = `--- a/old.js\ttimestamp1
190++++ b/new.js\ttimestamp2
191+@@ -1,3 +1,3 @@
192+ line1
193+-line2
194++modified2
195+ line3`;
196+
197+ const metadata: DiffMetadata =
198+ extractMetadataFromUnifiedDiff(unifiedDiff);
199+
200+ expect(metadata.oldFilename).toBe("old.js");
201+ expect(metadata.newFilename).toBe("new.js");
202+ expect(metadata.oldTimestamp).toBe("timestamp1");
203+ expect(metadata.newTimestamp).toBe("timestamp2");
204+ expect(metadata.isNew).toBeFalsy();
205+ expect(metadata.isDeleted).toBeFalsy();
206+ expect(metadata.isRename).toBeTruthy();
207+ });
208+
209+ it("should detect new files", () => {
210+ const unifiedDiff = `--- /dev/null
211++++ b/new.js
212+@@ -0,0 +1,2 @@
213++line1
214++line2`;
215+
216+ const metadata: DiffMetadata =
217+ extractMetadataFromUnifiedDiff(unifiedDiff);
218+
219+ expect(metadata.oldFilename).toBe("/dev/null");
220+ expect(metadata.newFilename).toBe("new.js");
221+ expect(metadata.isNew).toBeTruthy();
222+ expect(metadata.isDeleted).toBeFalsy();
223+ expect(metadata.isRename).toBeFalsy();
224+ });
225+
226+ it("should detect deleted files", () => {
227+ const unifiedDiff = `--- a/old.js
228++++ /dev/null
229+@@ -1,2 +0,0 @@
230+-line1
231+-line2`;
232+
233+ const metadata: DiffMetadata =
234+ extractMetadataFromUnifiedDiff(unifiedDiff);
235+
236+ expect(metadata.oldFilename).toBe("old.js");
237+ expect(metadata.newFilename).toBe("/dev/null");
238+ expect(metadata.isNew).toBeFalsy();
239+ expect(metadata.isDeleted).toBeTruthy();
240+ expect(metadata.isRename).toBeFalsy();
241+ });
242+
243+ it("should parse hunk information", () => {
244+ const unifiedDiff = `--- a/file.js
245++++ b/file.js
246+@@ -1,5 +1,6 @@ function header
247+ line1
248+-line2
249++modified2
250++newline
251+ line3
252+@@ -10,3 +11,3 @@
253+ line10
254+-line11
255++modified11
256+ line12`;
257+
258+ const metadata: DiffMetadata =
259+ extractMetadataFromUnifiedDiff(unifiedDiff);
260+
261+ expect(metadata.hunks).toHaveLength(2);
262+ expect(metadata.hunks![0]).toEqual({
263+ oldStart: 1,
264+ oldCount: 5,
265+ newStart: 1,
266+ newCount: 6,
267+ header: "function header",
268+ lines: [
269+ {
270+ content: "line1",
271+ newLineNumber: 1,
272+ oldLineNumber: 1,
273+ type: "context",
274+ },
275+ {
276+ content: "line2",
277+ oldLineNumber: 2,
278+ type: "deletion",
279+ },
280+ {
281+ content: "modified2",
282+ newLineNumber: 2,
283+ type: "addition",
284+ },
285+ {
286+ content: "newline",
287+ newLineNumber: 3,
288+ type: "addition",
289+ },
290+ {
291+ content: "line3",
292+ newLineNumber: 4,
293+ oldLineNumber: 3,
294+ type: "context",
295+ },
296+ ],
297+ });
298+ expect(metadata.hunks![1]).toEqual({
299+ oldStart: 10,
300+ oldCount: 3,
301+ newStart: 11,
302+ newCount: 3,
303+ header: undefined,
304+ lines: [
305+ {
306+ content: "line10",
307+ newLineNumber: 11,
308+ oldLineNumber: 10,
309+ type: "context",
310+ },
311+ {
312+ content: "line11",
313+ oldLineNumber: 11,
314+ type: "deletion",
315+ },
316+ {
317+ content: "modified11",
318+ newLineNumber: 12,
319+ type: "addition",
320+ },
321+ {
322+ content: "line12",
323+ newLineNumber: 13,
324+ oldLineNumber: 12,
325+ type: "context",
326+ },
327+ ],
328+ });
329+ });
330+
331+ it("should handle single line hunks", () => {
332+ const unifiedDiff = `--- a/file.js
333++++ b/file.js
334+@@ -1 +1 @@
335+-old
336++new`;
337+
338+ const metadata: DiffMetadata =
339+ extractMetadataFromUnifiedDiff(unifiedDiff);
340+
341+ expect(metadata.hunks).toHaveLength(1);
342+ expect(metadata.hunks![0]).toEqual({
343+ oldStart: 1,
344+ oldCount: 1,
345+ newStart: 1,
346+ newCount: 1,
347+ header: undefined,
348+ lines: [
349+ {
350+ content: "old",
351+ oldLineNumber: 1,
352+ type: "deletion",
353+ },
354+ {
355+ content: "new",
356+ newLineNumber: 1,
357+ type: "addition",
358+ },
359+ ],
360+ });
361+ });
362+
363+ it("should detect binary files", () => {
364+ const unifiedDiff = `--- a/image.png
365++++ b/image.png
366+Binary files a/image.png and b/image.png differ`;
367+
368+ const metadata: DiffMetadata =
369+ extractMetadataFromUnifiedDiff(unifiedDiff);
370+
371+ expect(metadata.isBinary).toBeTruthy();
372+ });
373+
374+ it("should detect git binary patches", () => {
375+ const unifiedDiff = `--- a/file.bin
376++++ b/file.bin
377+GIT binary patch
378+delta 123
379+...`;
380+
381+ const metadata: DiffMetadata =
382+ extractMetadataFromUnifiedDiff(unifiedDiff);
383+
384+ expect(metadata.isBinary).toBeTruthy();
385+ });
386+
387+ it("should handle files without a/ b/ prefixes", () => {
388+ const unifiedDiff = `--- old.js
389++++ new.js
390+@@ -1,2 +1,2 @@
391+-line1
392++modified1
393+ line2`;
394+
395+ const metadata: DiffMetadata =
396+ extractMetadataFromUnifiedDiff(unifiedDiff);
397+
398+ expect(metadata.oldFilename).toBe("old.js");
399+ expect(metadata.newFilename).toBe("new.js");
400+ });
401+
402+ it("should handle empty diff", () => {
403+ const metadata: DiffMetadata = extractMetadataFromUnifiedDiff("");
404+
405+ expect(metadata.oldFilename).toBeUndefined();
406+ expect(metadata.newFilename).toBeUndefined();
407+ expect(metadata.hunks).toEqual([]);
408+ expect(metadata.isBinary).toBeFalsy();
409+ });
410+
411+ it("should handle malformed diff gracefully", () => {
412+ const malformedDiff = `not a diff
413+random text`;
414+
415+ const metadata: DiffMetadata =
416+ extractMetadataFromUnifiedDiff(malformedDiff);
417+
418+ expect(metadata.oldFilename).toBeUndefined();
419+ expect(metadata.newFilename).toBeUndefined();
420+ expect(metadata.hunks).toEqual([]);
421+ });
422+
423+ it("should not consider same filenames as rename", () => {
424+ const unifiedDiff = `--- a/file.js
425++++ b/file.js
426+@@ -1,2 +1,2 @@
427+-line1
428++modified1
429+ line2`;
430+
431+ const metadata: DiffMetadata =
432+ extractMetadataFromUnifiedDiff(unifiedDiff);
433+
434+ expect(metadata.isRename).toBeFalsy();
435+ });
436+
437+ it("should handle files with spaces in names", () => {
438+ const unifiedDiff = `--- a/my file.js\t2023-01-01 00:00:00
439++++ b/my new file.js\t2023-01-01 00:01:00
440+@@ -1,1 +1,1 @@
441+-content
442++new content`;
443+
444+ const metadata: DiffMetadata =
445+ extractMetadataFromUnifiedDiff(unifiedDiff);
446+
447+ expect(metadata.oldFilename).toBe("my file.js");
448+ expect(metadata.newFilename).toBe("my new file.js");
449+ expect(metadata.oldTimestamp).toBe("2023-01-01 00:00:00");
450+ expect(metadata.newTimestamp).toBe("2023-01-01 00:01:00");
451+ expect(metadata.isRename).toBeTruthy();
452+ });
453+ });
454+
455+ describe("DiffFormatType enum", () => {
456+ it("should have correct enum values", () => {
457+ expect(DiffFormatType.Unified).toBe("unified");
458+ expect(DiffFormatType.RawBeforeAfter).toBe("beforeAfter");
459+ expect(DiffFormatType.TokenLineDiff).toBe("linediff");
460+ });
461+ });
462+});
modified core/nextEdit/context/processNextEditData.ts +7 −0
@@ -3,6 +3,7 @@
33 import { GetLspDefinitionsFunction } from "../../autocomplete/types";
44 import { ConfigHandler } from "../../config/ConfigHandler";
55 import { DataLogger } from "../../data/log";
6+import { NextEditProvider } from "../NextEditProvider";
67 import { RecentlyEditedRange } from "../types";
78 import { getAutocompleteContext } from "./autocompleteContextFetching";
89 import { createDiff, DiffFormatType } from "./diffFormatting";
@@ -60,6 +61,7 @@
6061 // undefined;
6162
6263 const modelName = "Codestral";
64+ const modelProvider = "mistral";
6365 const maxPromptTokens = randomNumberBetween(500, 12000);
6466
6567 const autocompleteContext = await getAutocompleteContext(
@@ -75,6 +77,8 @@
7577 modelName,
7678 );
7779
80+ NextEditProvider.getInstance().addAutocompleteContext(autocompleteContext);
81+
7882 // console.log(
7983 // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
8084 // );
@@ -121,6 +125,9 @@
121125 beforeCursorPos: cursorPosBeforeEdit,
122126 afterCursorPos: cursorPosAfterPrevEdit,
123127 context: autocompleteContext,
128+ modelProvider,
129+ modelName,
130+ modelTitle: modelName,
124131 },
125132 });
126133 }
modified core/nextEdit/context/processSmallEdit.ts +1 −1
@@ -20,7 +20,7 @@
2020 afterContent: beforeAfterdiff.afterContent,
2121 filePath: beforeAfterdiff.filePath,
2222 diffType: DiffFormatType.Unified,
23- contextLines: 3, // NOTE: This can change depending on experiments!
23+ contextLines: 5, // NOTE: This can change depending on experiments!
2424 }),
2525 );
2626
modified core/nextEdit/templating/NextEditPromptEngine.ts +40 −24
@@ -2,25 +2,30 @@
22 import { Position } from "../..";
33 import { SnippetPayload } from "../../autocomplete/snippets";
44 import { HelperVars } from "../../autocomplete/util/HelperVars";
5+import { NEXT_EDIT_MODELS } from "../../llm/constants";
56 import {
7+ INSTINCT_USER_PROMPT_PREFIX,
68 MERCURY_CURRENT_FILE_CONTENT_CLOSE,
79 MERCURY_CURRENT_FILE_CONTENT_OPEN,
8- MERCURY_CURSOR,
910 MERCURY_EDIT_DIFF_HISTORY_CLOSE,
1011 MERCURY_EDIT_DIFF_HISTORY_OPEN,
1112 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1213 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
13- MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
1414 } from "../constants";
1515 import {
16+ InstinctTemplateVars,
1617 MercuryTemplateVars,
17- Model1TemplateVars,
1818 NextEditTemplate,
1919 PromptMetadata,
2020 SystemPrompt,
2121 TemplateVars,
2222 UserPrompt,
2323 } from "../types";
24+import {
25+ contextSnippetsBlock,
26+ currentFileContentBlock as instinctCurrentFileContentBlock,
27+ editHistoryBlock as instinctEditHistoryBlock,
28+} from "./instinct";
2429 import {
2530 currentFileContentBlock,
2631 editHistoryBlock,
@@ -30,7 +35,6 @@
3035 insertCursorToken,
3136 insertEditableRegionTokensWithStaticRange,
3237 } from "./utils";
33-import { NEXT_EDIT_MODELS } from "../../llm/constants";
3438
3539 type TemplateRenderer = (vars: TemplateVars) => string;
3640
@@ -38,9 +42,8 @@
3842 "mercury-coder-nextedit": {
3943 template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
4044 },
41- "model-1": {
42- template:
43- "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
45+ instinct: {
46+ template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
4447 },
4548 };
4649
@@ -90,11 +93,11 @@
9093 case "mercury-coder-nextedit": {
9194 userEdits = ctx.editDiffHistory;
9295
93- editedCodeWithTokens = insertTokens(
94- helper.fileContents.split("\n"),
95- helper.pos,
96- MERCURY_CURSOR,
97- );
96+ // editedCodeWithTokens = insertTokens(
97+ // helper.fileContents.split("\n"),
98+ // helper.pos,
99+ // MERCURY_CURSOR,
100+ // );
98101
99102 const mercuryCtx: MercuryTemplateVars = {
100103 recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
@@ -112,24 +115,37 @@
112115
113116 tv = mercuryCtx;
114117
118+ editedCodeWithTokens = mercuryCtx.currentFileContent;
119+
115120 break;
116121 }
117- case "model-1": {
118- userEdits = ctx.userEdits;
119-
120- editedCodeWithTokens = insertTokens(
121- helper.fileContents.split("\n"),
122- helper.pos,
123- MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
124- );
122+ case "instinct": {
123+ userEdits = ctx.editDiffHistory;
125124
126- const model1Ctx: Model1TemplateVars = {
127- userEdits: ctx.userEdits,
125+ // editedCodeWithTokens = insertTokens(
126+ // helper.fileContents.split("\n"),
127+ // helper.pos,
128+ // INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
129+ // );
130+
131+ const instinctCtx: InstinctTemplateVars = {
132+ contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
133+ currentFileContent: instinctCurrentFileContentBlock(
134+ ctx.currentFileContent,
135+ ctx.windowStart,
136+ ctx.windowEnd,
137+ ctx.editableRegionStartLine,
138+ ctx.editableRegionEndLine,
139+ helper.pos,
140+ ),
141+ editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
142+ currentFilePath: ctx.currentFilePath,
128143 languageShorthand: ctx.languageShorthand,
129- userExcerpts: ctx.userExcerpts,
130144 };
131145
132- tv = model1Ctx;
146+ tv = instinctCtx;
147+
148+ editedCodeWithTokens = instinctCtx.currentFileContent;
133149
134150 break;
135151 }
modified core/nextEdit/templating/NextEditPromptEngine.vitest.ts +31 −12
@@ -3,7 +3,10 @@
33 import { SnippetPayload } from "../../autocomplete/snippets";
44 import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
55 import { HelperVars } from "../../autocomplete/util/HelperVars";
6+import { NEXT_EDIT_MODELS } from "../../llm/constants";
67 import {
8+ INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
9+ INSTINCT_USER_PROMPT_PREFIX,
710 MERCURY_CURRENT_FILE_CONTENT_CLOSE,
811 MERCURY_CURRENT_FILE_CONTENT_OPEN,
912 MERCURY_CURSOR,
@@ -11,19 +14,17 @@
1114 MERCURY_EDIT_DIFF_HISTORY_OPEN,
1215 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1316 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
14- MODEL_1_USER_CURSOR_IS_HERE_TOKEN,
1517 } from "../constants";
1618 import {
1719 renderDefaultSystemPrompt,
1820 renderDefaultUserPrompt,
1921 renderPrompt,
2022 } from "./NextEditPromptEngine";
21-import { NEXT_EDIT_MODELS } from "../../llm/constants";
2223
2324 describe("NextEditPromptEngine", () => {
2425 describe("renderPrompt", () => {
2526 let mercuryHelper: HelperVars;
26- let model1Helper: HelperVars;
27+ let instinctHelper: HelperVars;
2728 let testHelper: HelperVars;
2829 let unsupportedHelper: HelperVars;
2930 let ctx: any;
@@ -35,8 +36,8 @@
3536 pos: { line: 1, character: 12 } as Position,
3637 lang: { name: "typescript" },
3738 } as HelperVars;
38- model1Helper = {
39- modelName: "continuedev/model-1" as NEXT_EDIT_MODELS,
39+ instinctHelper = {
40+ modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
4041 fileContents: "function test() {\n const a = 1;\n return a;\n}",
4142 pos: { line: 1, character: 12 } as Position,
4243 lang: { name: "typescript" },
@@ -53,7 +54,7 @@
5354 { filepath: "/path/to/file1.ts", content: "const b = 2;" },
5455 ],
5556 currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
56- editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
57+ editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
5758 editableRegionStartLine: 0,
5859 editableRegionEndLine: 3,
5960 userEdits: "Added constant a",
@@ -80,17 +81,35 @@
8081 expect(result.userExcerpts).toContain(MERCURY_CURSOR);
8182 });
8283
83- it("should render model-1 prompt correctly", async () => {
84- const result = await renderPrompt(model1Helper, ctx);
84+ it("should render instinct prompt correctly", async () => {
85+ // Create proper instinct context structure matching NextEditProvider.ts
86+ const instinctCtx = {
87+ contextSnippets:
88+ "+++++ /path/to/context.ts\nconst contextVar = 'test';",
89+ currentFileContent: instinctHelper.fileContents,
90+ windowStart: 0, // Math.max(0, helper.pos.line - 25)
91+ windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
92+ editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
93+ editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
94+ editDiffHistory: [
95+ "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
96+ ], // unified diff
97+ currentFilePath: "/path/to/file.ts",
98+ languageShorthand: "ts",
99+ };
100+
101+ const result = await renderPrompt(instinctHelper, instinctCtx);
102+ console.log(result);
85103
86104 expect(result).toHaveProperty("prompt");
87105 expect(result.prompt.role).toBe("user");
106+ expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
107+ expect(result.prompt.content).toContain("### Context:");
88108 expect(result.prompt.content).toContain("### User Edits:");
89109 expect(result.prompt.content).toContain("### User Excerpts:");
90- expect(result.prompt.content).toContain("```ts");
91110
92- expect(result.userEdits).toBe(ctx.userEdits);
93- expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN);
111+ expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
112+ expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
94113 });
95114
96115 it("should throw error for unsupported model name", async () => {
@@ -204,7 +223,7 @@
204223 { filepath: "/path/to/file1.ts", content: "const b = 2;" },
205224 ],
206225 currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
207- editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@",
226+ editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
208227 editableRegionStartLine: 0,
209228 editableRegionEndLine: 3,
210229 userEdits: "Added constant a",
added core/nextEdit/templating/instinct.ts +129 −0
@@ -0,0 +1,129 @@
1+import { Position } from "../..";
2+import {
3+ INSTINCT_CONTEXT_FILE_TOKEN,
4+ INSTINCT_EDITABLE_REGION_END_TOKEN,
5+ INSTINCT_EDITABLE_REGION_START_TOKEN,
6+ INSTINCT_SNIPPET_TOKEN,
7+ INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
8+} from "../constants";
9+import { insertCursorToken } from "./utils";
10+
11+/**
12+ * @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string.
13+ */
14+export function contextSnippetsBlock(contextSnippets: string) {
15+ const headerRegex = /^(\+\+\+\+\+ )(.*)/;
16+ const lines = contextSnippets.split("\n");
17+
18+ return lines
19+ .reduce<string[]>((acc, line) => {
20+ const matches = line.match(headerRegex);
21+ if (matches) {
22+ const filename = matches[2];
23+ acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`);
24+ } else {
25+ if (
26+ acc.length > 0 &&
27+ acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before
28+ ) {
29+ acc.push(`${INSTINCT_SNIPPET_TOKEN}`);
30+ }
31+ acc.push(line);
32+ }
33+
34+ return acc;
35+ }, [])
36+ .join("\n");
37+}
38+
39+export function currentFileContentBlock(
40+ currentFileContent: string,
41+ windowStart: number,
42+ windowEnd: number,
43+ editableRegionStartLine: number,
44+ editableRegionEndLine: number,
45+ cursorPosition: Position,
46+) {
47+ const currentFileContentLines = currentFileContent.split("\n");
48+
49+ const insertedCursorLines = insertCursorToken(
50+ currentFileContentLines,
51+ cursorPosition,
52+ INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
53+ );
54+
55+ const instrumentedLines = [
56+ ...insertedCursorLines.slice(windowStart, editableRegionStartLine),
57+ INSTINCT_EDITABLE_REGION_START_TOKEN,
58+ ...insertedCursorLines.slice(
59+ editableRegionStartLine,
60+ editableRegionEndLine + 1,
61+ ),
62+ INSTINCT_EDITABLE_REGION_END_TOKEN,
63+ ...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1),
64+ ];
65+
66+ return instrumentedLines.join("\n");
67+}
68+
69+export function editHistoryBlock(
70+ editDiffHistories: string[], // array of unified diffs with Index headers
71+) {
72+ if (!editDiffHistories.length) {
73+ return "";
74+ }
75+
76+ const blocks: string[] = [];
77+
78+ for (const editDiffHistory of editDiffHistories) {
79+ if (!editDiffHistory.trim()) {
80+ continue;
81+ }
82+
83+ // Split on Index: lines to get the unified diff.
84+ const diffSections = editDiffHistory
85+ .split(/^Index: /m)
86+ .filter((section) => section.trim());
87+
88+ for (const section of diffSections) {
89+ const lines = section.split("\n");
90+
91+ // Extract filename from the first line (after "Index: " was split off).
92+ const filename = lines[0];
93+
94+ // Find the start of the actual diff content (skip ---, +++, and === lines).
95+ const diffLines = lines
96+ .filter(
97+ (line) =>
98+ !line.startsWith("---") &&
99+ !line.startsWith("+++") &&
100+ !line.startsWith("===") &&
101+ line.trim() !== "", // remove empty lines from header section
102+ )
103+ .slice(1); // remove the filename line
104+
105+ // Only include lines that are actual diff content (@@, +, -, or context lines).
106+ const actualDiffContent = diffLines.filter(
107+ (line) =>
108+ line.startsWith("@@") ||
109+ line.startsWith("+") ||
110+ line.startsWith("-") ||
111+ line.startsWith(" "), // context lines
112+ );
113+
114+ if (actualDiffContent.length === 0) continue;
115+
116+ const diffBlock = [
117+ `User edited file "${filename}"`,
118+ "",
119+ "```diff",
120+ actualDiffContent.join("\n"),
121+ "```",
122+ ].join("\n");
123+
124+ blocks.push(diffBlock);
125+ }
126+ }
127+
128+ return blocks.join("\n");
129+}
added core/nextEdit/templating/instinct.vitest.ts +483 −0
@@ -0,0 +1,483 @@
1+import { describe, expect, test } from "vitest";
2+import { Position } from "../..";
3+import {
4+ contextSnippetsBlock,
5+ currentFileContentBlock,
6+ editHistoryBlock,
7+} from "./instinct";
8+
9+describe("contextSnippetsBlock", () => {
10+ test("should format empty context snippets", () => {
11+ const result = contextSnippetsBlock("");
12+ expect(result).toBe("");
13+ });
14+
15+ test("should format single context snippet with codestral style header", () => {
16+ const input = `+++++ src/utils.ts
17+function helper() {
18+ return "test";
19+}`;
20+
21+ const expected = `<|context_file|>: src/utils.ts
22+<|snippet|>
23+function helper() {
24+ return "test";
25+}`;
26+
27+ const result = contextSnippetsBlock(input);
28+ expect(result).toBe(expected);
29+ });
30+
31+ test("should format multiple context snippets", () => {
32+ const input = `+++++ src/file1.ts
33+const var1 = "value1";
34+
35++++++ src/file2.ts
36+const var2 = "value2";
37+function test() {}`;
38+
39+ const expected = `<|context_file|>: src/file1.ts
40+<|snippet|>
41+const var1 = "value1";
42+
43+<|context_file|>: src/file2.ts
44+<|snippet|>
45+const var2 = "value2";
46+function test() {}`;
47+
48+ const result = contextSnippetsBlock(input);
49+ expect(result).toBe(expected);
50+ });
51+
52+ test("should handle context snippet without content", () => {
53+ const input = "+++++ src/empty.ts";
54+
55+ const expected = `<|context_file|>: src/empty.ts`;
56+
57+ const result = contextSnippetsBlock(input);
58+ expect(result).toBe(expected);
59+ });
60+
61+ test("should handle malformed headers gracefully", () => {
62+ const input = `not a header
63++++++ src/valid.ts
64+valid content`;
65+
66+ const expected = `not a header
67+<|context_file|>: src/valid.ts
68+<|snippet|>
69+valid content`;
70+
71+ const result = contextSnippetsBlock(input);
72+ expect(result).toBe(expected);
73+ });
74+
75+ test("should handle multiple consecutive headers", () => {
76+ const input = `+++++ src/file1.ts
77++++++ src/file2.ts
78+content after headers`;
79+
80+ const expected = `<|context_file|>: src/file1.ts
81+<|context_file|>: src/file2.ts
82+<|snippet|>
83+content after headers`;
84+
85+ const result = contextSnippetsBlock(input);
86+ expect(result).toBe(expected);
87+ });
88+});
89+
90+describe("currentFileContentBlock", () => {
91+ test("should insert cursor and editable region tokens correctly", () => {
92+ const content = `line 0
93+line 1
94+line 2
95+line 3
96+line 4`;
97+ const windowStart = 0;
98+ const windowEnd = 4;
99+ const cursorPosition: Position = { line: 2, character: 4 };
100+ const editableRegionStartLine = 1;
101+ const editableRegionEndLine = 3;
102+
103+ const result = currentFileContentBlock(
104+ content,
105+ windowStart,
106+ windowEnd,
107+ editableRegionStartLine,
108+ editableRegionEndLine,
109+ cursorPosition,
110+ );
111+
112+ const expected = `line 0
113+<|editable_region_start|>
114+line 1
115+line<|user_cursor_is_here|> 2
116+line 3
117+<|editable_region_end|>
118+line 4`;
119+
120+ expect(result).toBe(expected);
121+ });
122+
123+ test("should handle cursor at beginning of line", () => {
124+ const content = `line 0
125+line 1
126+line 2`;
127+ const windowStart = 0;
128+ const windowEnd = 2;
129+ const cursorPosition: Position = { line: 1, character: 0 };
130+ const editableRegionStartLine = 0;
131+ const editableRegionEndLine = 2;
132+
133+ const result = currentFileContentBlock(
134+ content,
135+ windowStart,
136+ windowEnd,
137+ editableRegionStartLine,
138+ editableRegionEndLine,
139+ cursorPosition,
140+ );
141+
142+ const expected = `<|editable_region_start|>
143+line 0
144+<|user_cursor_is_here|>line 1
145+line 2
146+<|editable_region_end|>`;
147+
148+ expect(result).toBe(expected);
149+ });
150+
151+ test("should handle cursor at end of line", () => {
152+ const content = `line 0
153+line 1
154+line 2`;
155+ const windowStart = 0;
156+ const windowEnd = 2;
157+ const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1"
158+ const editableRegionStartLine = 0;
159+ const editableRegionEndLine = 2;
160+
161+ const result = currentFileContentBlock(
162+ content,
163+ windowStart,
164+ windowEnd,
165+ editableRegionStartLine,
166+ editableRegionEndLine,
167+ cursorPosition,
168+ );
169+
170+ const expected = `<|editable_region_start|>
171+line 0
172+line 1<|user_cursor_is_here|>
173+line 2
174+<|editable_region_end|>`;
175+
176+ expect(result).toBe(expected);
177+ });
178+
179+ test("should handle single line editable region", () => {
180+ const content = `line 0
181+line 1
182+line 2`;
183+ const windowStart = 0;
184+ const windowEnd = 2;
185+ const cursorPosition: Position = { line: 1, character: 2 };
186+ const editableRegionStartLine = 1;
187+ const editableRegionEndLine = 1;
188+
189+ const result = currentFileContentBlock(
190+ content,
191+ windowStart,
192+ windowEnd,
193+ editableRegionStartLine,
194+ editableRegionEndLine,
195+ cursorPosition,
196+ );
197+
198+ const expected = `line 0
199+<|editable_region_start|>
200+li<|user_cursor_is_here|>ne 1
201+<|editable_region_end|>
202+line 2`;
203+
204+ expect(result).toBe(expected);
205+ });
206+
207+ test("should handle cursor outside bounds gracefully (this shouldn't happen)", () => {
208+ const content = `line 0
209+line 1`;
210+ const windowStart = 0;
211+ const windowEnd = 1;
212+ const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds
213+ const editableRegionStartLine = 0;
214+ const editableRegionEndLine = 1;
215+
216+ const result = currentFileContentBlock(
217+ content,
218+ windowStart,
219+ windowEnd,
220+ editableRegionStartLine,
221+ editableRegionEndLine,
222+ cursorPosition,
223+ );
224+
225+ const expected = `<|editable_region_start|>
226+line 0
227+line 1
228+<|editable_region_end|>`;
229+
230+ expect(result).toBe(expected);
231+ });
232+
233+ test("should handle editable region covering entire file", () => {
234+ const content = `line 0
235+line 1
236+line 2`;
237+ const windowStart = 0;
238+ const windowEnd = 2;
239+ const cursorPosition: Position = { line: 1, character: 0 };
240+ const editableRegionStartLine = 0;
241+ const editableRegionEndLine = 2;
242+
243+ const result = currentFileContentBlock(
244+ content,
245+ windowStart,
246+ windowEnd,
247+ editableRegionStartLine,
248+ editableRegionEndLine,
249+ cursorPosition,
250+ );
251+
252+ const expected = `<|editable_region_start|>
253+line 0
254+<|user_cursor_is_here|>line 1
255+line 2
256+<|editable_region_end|>`;
257+
258+ expect(result).toBe(expected);
259+ });
260+
261+ test("should handle windowing - content outside window not included", () => {
262+ const content = `line 0
263+line 1
264+line 2
265+line 3
266+line 4`;
267+ const windowStart = 1;
268+ const windowEnd = 3;
269+ const cursorPosition: Position = { line: 2, character: 2 };
270+ const editableRegionStartLine = 2;
271+ const editableRegionEndLine = 2;
272+
273+ const result = currentFileContentBlock(
274+ content,
275+ windowStart,
276+ windowEnd,
277+ editableRegionStartLine,
278+ editableRegionEndLine,
279+ cursorPosition,
280+ );
281+
282+ const expected = `line 1
283+<|editable_region_start|>
284+li<|user_cursor_is_here|>ne 2
285+<|editable_region_end|>
286+line 3`;
287+
288+ expect(result).toBe(expected);
289+ });
290+});
291+
292+describe("editHistoryBlock", () => {
293+ test("should format empty edit history", () => {
294+ const result = editHistoryBlock([]);
295+ expect(result).toBe("");
296+ });
297+
298+ test("should format single diff history entry", () => {
299+ const diff = `Index: test.js
300+===================================================================
301+--- a/test.js 2023-01-01 10:00:00.000000000 +0000
302++++ b/test.js 2023-01-01 10:01:00.000000000 +0000
303+@@ -1,3 +1,3 @@
304+ function test() {
305+- console.log("old");
306++ console.log("new");
307+ }`;
308+
309+ const result = editHistoryBlock([diff]);
310+ const expected = `User edited file "test.js"
311+
312+\`\`\`diff
313+@@ -1,3 +1,3 @@
314+ function test() {
315+- console.log("old");
316++ console.log("new");
317+ }
318+\`\`\``;
319+
320+ expect(result).toBe(expected);
321+ });
322+
323+ test("should format multiple diff history entries in unified format", () => {
324+ // Multiple diffs should be concatenated into a single string
325+ const unifiedDiff = `Index: file1.js
326+===================================================================
327+--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
328++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
329+@@ -1 +1 @@
330+-const old = 1;
331++const new = 1;
332+Index: file2.js
333+===================================================================
334+--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
335++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
336+@@ -1 +1 @@
337+-let x = "old";
338++let x = "new";`;
339+
340+ const result = editHistoryBlock([unifiedDiff]);
341+ const expected = `User edited file "file1.js"
342+
343+\`\`\`diff
344+@@ -1 +1 @@
345+-const old = 1;
346++const new = 1;
347+\`\`\`
348+User edited file "file2.js"
349+
350+\`\`\`diff
351+@@ -1 +1 @@
352+-let x = "old";
353++let x = "new";
354+\`\`\``;
355+
356+ expect(result).toBe(expected);
357+ });
358+
359+ test("should format multiple diff history entries", () => {
360+ // Multiple diffs should be concatenated into a single string
361+ const unifiedDiffs = [
362+ `Index: file1.js
363+===================================================================
364+--- a/file1.js 2023-01-01 10:00:00.000000000 +0000
365++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000
366+@@ -1 +1 @@
367+-const old = 1;
368++const new = 1;`,
369+ `Index: file2.js
370+===================================================================
371+--- a/file2.js 2023-01-01 10:02:00.000000000 +0000
372++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000
373+@@ -1 +1 @@
374+-let x = "old";
375++let x = "new";`,
376+ ];
377+
378+ const result = editHistoryBlock(unifiedDiffs);
379+ const expected = `User edited file "file1.js"
380+
381+\`\`\`diff
382+@@ -1 +1 @@
383+-const old = 1;
384++const new = 1;
385+\`\`\`
386+User edited file "file2.js"
387+
388+\`\`\`diff
389+@@ -1 +1 @@
390+-let x = "old";
391++let x = "new";
392+\`\`\``;
393+
394+ expect(result).toBe(expected);
395+ });
396+
397+ // Fix remaining tests to pass strings instead of arrays
398+ test("should handle diff with complex filename paths", () => {
399+ const diff = `Index: src/components/Button/Button.tsx
400+===================================================================
401+--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000
402++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000
403+@@ -1,2 +1,2 @@
404+-export const Button = () => <button>Old</button>;
405++export const Button = () => <button>New</button>;`;
406+
407+ const result = editHistoryBlock([diff]);
408+ const expected = `User edited file "src/components/Button/Button.tsx"
409+
410+\`\`\`diff
411+@@ -1,2 +1,2 @@
412+-export const Button = () => <button>Old</button>;
413++export const Button = () => <button>New</button>;
414+\`\`\``;
415+
416+ expect(result).toBe(expected);
417+ });
418+
419+ test("should handle diff with new file creation", () => {
420+ const diff = `Index: newfile.js
421+===================================================================
422+--- /dev/null 2023-01-01 10:00:00.000000000 +0000
423++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000
424+@@ -0,0 +1,3 @@
425++function newFunction() {
426++ return "hello world";
427++}`;
428+
429+ const result = editHistoryBlock([diff]);
430+ const expected = `User edited file "newfile.js"
431+
432+\`\`\`diff
433+@@ -0,0 +1,3 @@
434++function newFunction() {
435++ return "hello world";
436++}
437+\`\`\``;
438+
439+ expect(result).toBe(expected);
440+ });
441+
442+ test("should handle diff with file deletion", () => {
443+ const diff = `Index: deletedfile.js
444+===================================================================
445+--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000
446++++ /dev/null 2023-01-01 10:01:00.000000000 +0000
447+@@ -1,3 +0,0 @@
448+-function deletedFunction() {
449+- return "goodbye";
450+-}`;
451+
452+ const result = editHistoryBlock([diff]);
453+ const expected = `User edited file "deletedfile.js"
454+
455+\`\`\`diff
456+@@ -1,3 +0,0 @@
457+-function deletedFunction() {
458+- return "goodbye";
459+-}
460+\`\`\``;
461+
462+ expect(result).toBe(expected);
463+ });
464+
465+ test("should handle minimal diff format", () => {
466+ const diff = `Index: simple.txt
467+===================================================================
468+@@ -1 +1 @@
469+-old text
470++new text`;
471+
472+ const result = editHistoryBlock([diff]);
473+ const expected = `User edited file "simple.txt"
474+
475+\`\`\`diff
476+@@ -1 +1 @@
477+-old text
478++new text
479+\`\`\``;
480+
481+ expect(result).toBe(expected);
482+ });
483+});
modified core/nextEdit/templating/mercuryCoderNextEdit.ts +5 −2
@@ -50,12 +50,15 @@
5050 }
5151
5252 export function editHistoryBlock(
53- editDiffHistory: string, // could be a singe large unified diff
53+ editDiffHistory: string[], // could be a singe large unified diff
5454 ) {
5555 // diffHistory is made from createDiff.
5656 // This uses createPatch from npm diff library, which includes an index line and a separator.
5757 // We get rid of these first two lines.
58- return editDiffHistory.split("\n").slice(2).join("\n");
58+ return editDiffHistory
59+ .map((diff) => diff.split("\n").slice(2).join("\n"))
60+ .join("\n");
61+ // return editDiffHistory.split("\n").slice(2).join("\n");
5962 }
6063
6164 function mercuryNextEditTemplateBuilder(
modified core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +2 −2
@@ -108,12 +108,12 @@
108108 it("should return the edit diff history unchanged", () => {
109109 const diffHistory =
110110 "diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@";
111- const result = editHistoryBlock(diffHistory);
111+ const result = editHistoryBlock([diffHistory]);
112112 expect(result).toBe("@@ -1,3 +1,4 @@");
113113 });
114114
115115 it("should handle empty diff history", () => {
116- const result = editHistoryBlock("");
116+ const result = editHistoryBlock([]);
117117 expect(result).toBe("");
118118 });
119119 });
modified core/nextEdit/templating/utils.ts +4 −4
@@ -1,7 +1,7 @@
11 import { Position } from "../..";
22 import {
3- MODEL_1_EDITABLE_REGION_END_TOKEN,
4- MODEL_1_EDITABLE_REGION_START_TOKEN,
3+ INSTINCT_EDITABLE_REGION_END_TOKEN,
4+ INSTINCT_EDITABLE_REGION_START_TOKEN,
55 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
66 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
77 } from "../constants";
@@ -53,9 +53,9 @@
5353
5454 const instrumentedLines = [
5555 ...lines.slice(0, editableRegionStart),
56- MODEL_1_EDITABLE_REGION_START_TOKEN,
56+ INSTINCT_EDITABLE_REGION_START_TOKEN,
5757 ...lines.slice(editableRegionStart, editableRegionEnd + 1),
58- MODEL_1_EDITABLE_REGION_END_TOKEN,
58+ INSTINCT_EDITABLE_REGION_END_TOKEN,
5959 ...lines.slice(editableRegionEnd + 1),
6060 ];
6161
modified core/nextEdit/templating/utils.vitest.ts +6 −6
@@ -1,8 +1,8 @@
11 import { describe, expect, it } from "vitest";
22 import { Position } from "../..";
33 import {
4- MODEL_1_EDITABLE_REGION_END_TOKEN,
5- MODEL_1_EDITABLE_REGION_START_TOKEN,
4+ INSTINCT_EDITABLE_REGION_END_TOKEN,
5+ INSTINCT_EDITABLE_REGION_START_TOKEN,
66 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
77 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
88 } from "../constants";
@@ -88,9 +88,9 @@
8888
8989 const expected = [
9090 ...lines.slice(0, expectedStart),
91- MODEL_1_EDITABLE_REGION_START_TOKEN,
91+ INSTINCT_EDITABLE_REGION_START_TOKEN,
9292 ...lines.slice(expectedStart, expectedEnd + 1),
93- MODEL_1_EDITABLE_REGION_END_TOKEN,
93+ INSTINCT_EDITABLE_REGION_END_TOKEN,
9494 ...lines.slice(expectedEnd + 1),
9595 ];
9696
@@ -112,11 +112,11 @@
112112
113113 const expected = [
114114 "line 0",
115- MODEL_1_EDITABLE_REGION_START_TOKEN,
115+ INSTINCT_EDITABLE_REGION_START_TOKEN,
116116 "line 1",
117117 "line 2",
118118 "line 3",
119- MODEL_1_EDITABLE_REGION_END_TOKEN,
119+ INSTINCT_EDITABLE_REGION_END_TOKEN,
120120 "line 4",
121121 ];
122122
modified core/nextEdit/types.ts +5 −3
@@ -90,10 +90,12 @@
9090
9191 export interface TemplateVars {}
9292
93-export interface Model1TemplateVars extends TemplateVars {
94- userEdits: string;
93+export interface InstinctTemplateVars extends TemplateVars {
94+ contextSnippets: string;
95+ currentFileContent: string;
96+ editDiffHistory: string; // could be a singe large unified diff
97+ currentFilePath: string;
9598 languageShorthand: string;
96- userExcerpts: string;
9799 }
98100
99101 export interface MercuryTemplateVars extends TemplateVars {
modified core/nextEdit/utils.ts +10 −0
@@ -1,3 +1,5 @@
1+import { DiffLine } from "..";
2+
13 export function isNextEditTest(): boolean {
24 const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
35
@@ -11,3 +13,11 @@
1113
1214 return false;
1315 }
16+
17+export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean {
18+ return diffLines.every(
19+ (diff) =>
20+ diff.type === "old" &&
21+ (diff.line.trim() === "" || /^\s+$/.test(diff.line)),
22+ );
23+}
added core/nextEdit/utils.vitest.ts +59 −0
@@ -0,0 +1,59 @@
1+import { describe, expect, test, vi } from "vitest";
2+import { DiffLine } from "..";
3+import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
4+
5+describe("isNextEditTest", () => {
6+ test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
7+ vi.stubEnv("NEXT_EDIT_TEST_ENABLED", "true");
8+ expect(isNextEditTest()).toBe(true);
9+ });
10+
11+ test("returns false when NEXT_EDIT_TEST_ENABLED is 'false'", () => {
12+ vi.stubEnv("NEXT_EDIT_TEST_ENABLED", "false");
13+ expect(isNextEditTest()).toBe(false);
14+ });
15+
16+ test("returns false when NEXT_EDIT_TEST_ENABLED is undefined", () => {
17+ vi.stubEnv("NEXT_EDIT_TEST_ENABLED", undefined);
18+ expect(isNextEditTest()).toBe(false);
19+ });
20+});
21+
22+describe("isWhitespaceOnlyDeletion", () => {
23+ test("returns true for whitespace-only deletions", () => {
24+ const diffLines: DiffLine[] = [
25+ { type: "old", line: " " },
26+ { type: "old", line: "\t" },
27+ ];
28+ expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
29+ });
30+
31+ test("returns false for non-whitespace deletions", () => {
32+ const diffLines: DiffLine[] = [
33+ { type: "old", line: "code" },
34+ { type: "old", line: " " },
35+ ];
36+ expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
37+ });
38+
39+ test("returns false for mixed content", () => {
40+ const diffLines: DiffLine[] = [
41+ { type: "old", line: " " },
42+ { type: "old", line: "code" },
43+ ];
44+ expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
45+ });
46+
47+ test("returns false for mixed type", () => {
48+ const diffLines: DiffLine[] = [
49+ { type: "old", line: " " },
50+ { type: "new", line: "" },
51+ ];
52+ expect(isWhitespaceOnlyDeletion(diffLines)).toBe(false);
53+ });
54+
55+ test("returns true for empty array", () => {
56+ const diffLines: DiffLine[] = [];
57+ expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
58+ });
59+});
modified core/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified core/package.json +8 −2
@@ -7,9 +7,10 @@
77 "vitest": "vitest run",
88 "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
99 "tsc:check": "tsc -p ./ --noEmit",
10- "build:npm": "tsc -p ./tsconfig.npm.json",
10+ "build:npm": "tsc -p ./tsconfig.npm.json && npm run sentry:sourcemaps",
1111 "lint": "eslint . --ext ts",
12- "lint:fix": "eslint . --ext ts --fix"
12+ "lint:fix": "eslint . --ext ts --fix",
13+ "sentry:sourcemaps": "sentry-cli sourcemaps inject --org continue-xd --project continue ./dist && sentry-cli sourcemaps upload --org continue-xd --project continue ./dist"
1314 },
1415 "type": "module",
1516 "author": "Continue Dev, Inc",
@@ -60,6 +61,11 @@
6061 "@modelcontextprotocol/sdk": "^1.12.0",
6162 "@mozilla/readability": "^0.5.0",
6263 "@octokit/rest": "^20.1.1",
64+ "@sentry/cli": "^2.50.2",
65+ "@sentry/core": "^9.43.0",
66+ "@sentry/esbuild-plugin": "^4.0.2",
67+ "@sentry/node": "^9.43.0",
68+ "@sentry/vite-plugin": "^4.0.2",
6369 "@typescript-eslint/eslint-plugin": "^7.8.0",
6470 "@xenova/transformers": "2.14.0",
6571 "adf-to-md": "^1.1.0",
modified core/protocol/core.ts +44 −2
@@ -26,6 +26,7 @@
2626 FileSymbolMap,
2727 IdeSettings,
2828 LLMFullCompletionOptions,
29+ MCPServerStatus,
2930 MessageOption,
3031 ModelDescription,
3132 PromptLog,
@@ -48,6 +49,8 @@
4849 ControlPlaneSessionInfo,
4950 } from "../control-plane/AuthTypes";
5051 import { FreeTrialStatus } from "../control-plane/client";
52+import { NextEditOutcome } from "../nextEdit/types";
53+import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
5154
5255 export enum OnboardingModes {
5356 API_KEY = "API Key",
@@ -90,7 +93,7 @@
9093 result: ConfigResult<BrowserSerializedContinueConfig>;
9194 profileId: string | null;
9295 organizations: SerializedOrgWithProfiles[];
93- selectedOrgId: string;
96+ selectedOrgId: string | null;
9497 },
9598 ];
9699 "config/deleteModel": [{ title: string }, void];
@@ -128,6 +131,7 @@
128131 },
129132 ContextItemWithId[],
130133 ];
134+
131135 "mcp/reloadServer": [
132136 {
133137 id: string;
@@ -145,6 +149,9 @@
145149 description: string | undefined;
146150 },
147151 ];
152+ "mcp/startAuthentication": [MCPServerStatus, void];
153+ "mcp/removeAuthentication": [MCPServerStatus, void];
154+
148155 "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
149156 "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
150157 "autocomplete/complete": [AutocompleteInput, string[]];
@@ -153,9 +160,44 @@
153160 "context/indexDocs": [{ reIndex: boolean }, void];
154161 "autocomplete/cancel": [undefined, void];
155162 "autocomplete/accept": [{ completionId: string }, void];
156- "nextEdit/predict": [AutocompleteInput, string[]];
163+ "nextEdit/predict": [
164+ {
165+ input: AutocompleteInput;
166+ options?: {
167+ withChain?: boolean;
168+ usingFullFileDiff?: boolean;
169+ };
170+ },
171+ NextEditOutcome | undefined,
172+ ];
157173 "nextEdit/reject": [{ completionId: string }, void];
158174 "nextEdit/accept": [{ completionId: string }, void];
175+ "nextEdit/startChain": [undefined, void];
176+ "nextEdit/deleteChain": [undefined, void];
177+ "nextEdit/isChainAlive": [undefined, boolean];
178+ "nextEdit/queue/getProcessedCount": [undefined, number];
179+ "nextEdit/queue/dequeueProcessed": [undefined, ProcessedItem | null];
180+ "nextEdit/queue/processOne": [
181+ {
182+ ctx: {
183+ completionId: string;
184+ manuallyPassFileContents?: string;
185+ manuallyPassPrefix?: string;
186+ selectedCompletionInfo?: {
187+ text: string;
188+ range: Range;
189+ };
190+ isUntitledFile: boolean;
191+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
192+ recentlyEditedRanges: RecentlyEditedRange[];
193+ };
194+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
195+ recentlyEditedRanges: RecentlyEditedRange[];
196+ },
197+ void,
198+ ];
199+ "nextEdit/queue/clear": [undefined, void];
200+ "nextEdit/queue/abort": [undefined, void];
159201 "llm/complete": [
160202 {
161203 prompt: string;
modified core/protocol/messenger/index.ts +50 −13
@@ -1,5 +1,6 @@
11 import { v4 as uuidv4 } from "uuid";
22
3+import { Logger } from "../../util/Logger.js";
34 import type { IProtocol } from "../index";
45
56 export interface Message<T = any> {
@@ -85,7 +86,19 @@
8586 data,
8687 messageId: messageId ?? uuidv4(),
8788 };
88- return listener(msg);
89+
90+ try {
91+ return listener(msg);
92+ } catch (error) {
93+ // Capture message handling errors to Sentry
94+ Logger.error(error, {
95+ messageType: String(messageType),
96+ messageId: msg.messageId,
97+ });
98+
99+ // Re-throw the original error
100+ throw error;
101+ }
89102 }
90103
91104 send<T extends keyof FromProtocol>(
@@ -119,12 +132,24 @@
119132 if (!listener) {
120133 throw new Error(`No handler for message type "${String(messageType)}"`);
121134 }
122- const response = await listener({
123- messageType: messageType as string,
124- data,
125- messageId,
126- });
127- return response;
135+
136+ try {
137+ const response = await listener({
138+ messageType: messageType as string,
139+ data,
140+ messageId,
141+ });
142+ return response;
143+ } catch (error) {
144+ // Capture message handling errors to Sentry
145+ Logger.error(error, {
146+ messageType: String(messageType),
147+ messageId,
148+ });
149+
150+ // Re-throw the original error
151+ throw error;
152+ }
128153 }
129154
130155 externalOn<T extends keyof FromProtocol>(
@@ -144,11 +169,23 @@
144169 if (!listener) {
145170 throw new Error(`No handler for message type "${String(messageType)}"`);
146171 }
147- const response = listener({
148- messageType: messageType as string,
149- data,
150- messageId,
151- });
152- return Promise.resolve(response);
172+
173+ try {
174+ const response = listener({
175+ messageType: messageType as string,
176+ data,
177+ messageId,
178+ });
179+ return Promise.resolve(response);
180+ } catch (error) {
181+ // Capture message handling errors to Sentry
182+ Logger.error(error, {
183+ messageType: String(messageType),
184+ messageId,
185+ });
186+
187+ // Re-throw the original error
188+ throw error;
189+ }
153190 }
154191 }
modified core/protocol/passThrough.ts +10 −0
@@ -28,6 +28,8 @@
2828 "config/updateSelectedModel",
2929 "mcp/reloadServer",
3030 "mcp/getPrompt",
31+ "mcp/startAuthentication",
32+ "mcp/removeAuthentication",
3133 "context/getContextItems",
3234 "context/getSymbolsForFiles",
3335 "context/loadSubmenuItems",
@@ -40,6 +42,14 @@
4042 "nextEdit/predict",
4143 "nextEdit/reject",
4244 "nextEdit/accept",
45+ "nextEdit/startChain",
46+ "nextEdit/deleteChain",
47+ "nextEdit/isChainAlive",
48+ "nextEdit/queue/getProcessedCount",
49+ "nextEdit/queue/dequeueProcessed",
50+ "nextEdit/queue/processOne",
51+ "nextEdit/queue/clear",
52+ "nextEdit/queue/abort",
4353 "tts/kill",
4454 "llm/complete",
4555 "llm/streamChat",
modified core/tools/mcpToolName.vitest.ts +1 −0
@@ -15,6 +15,7 @@
1515 type: "sse",
1616 url: "",
1717 },
18+ isProtectedResource: false,
1819 });
1920
2021 const createMCPTool = (name: string): MCPTool => ({
modified core/tsconfig.json +8 −1
@@ -18,7 +18,14 @@
1818 "noEmitOnError": false,
1919 "experimentalDecorators": true,
2020 "emitDecoratorMetadata": true,
21- "types": ["jest", "node"]
21+ "types": ["jest", "node"],
22+ "sourceMap": true,
23+ "inlineSources": true,
24+
25+ // Set `sourceRoot` to "/" to strip the build path prefix
26+ // from generated source code references.
27+ // This improves issue grouping in Sentry.
28+ "sourceRoot": "/"
2229 },
2330 "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],
2431 "exclude": ["dist"]
modified core/util/GlobalContext.test.ts +151 −1
@@ -115,7 +115,7 @@
115115
116116 expect(consoleWarnMock).toHaveBeenCalledWith(
117117 expect.stringContaining(
118- "Error updating global context, deleting corrupted file",
118+ "Error updating global context, attempting to salvage security-sensitive values",
119119 ),
120120 );
121121
@@ -174,4 +174,154 @@
174174 it("should not crash or throw when getting a key that hasn't been set", () => {
175175 expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBeUndefined();
176176 });
177+
178+ describe("salvage functionality", () => {
179+ it("should salvage allowAnonymousTelemetry from corrupted sharedConfig", () => {
180+ // Create a file with partially corrupted JSON that contains salvageable sharedConfig
181+ const corruptedContent = `{
182+ "indexingPaused": true,
183+ "sharedConfig": {"allowAnonymousTelemetry": false},
184+ "corrupted": { invalid json
185+}`;
186+ fs.writeFileSync(globalContextFilePath, corruptedContent);
187+
188+ const consoleWarnMock = jest
189+ .spyOn(console, "warn")
190+ .mockImplementation(() => {});
191+
192+ // Try to update - this should salvage the allowAnonymousTelemetry value
193+ globalContext.update("indexingPaused", false);
194+
195+ expect(consoleWarnMock).toHaveBeenCalledWith(
196+ expect.stringContaining(
197+ "Error updating global context, attempting to salvage security-sensitive values",
198+ ),
199+ );
200+
201+ // Should have the new value
202+ expect(globalContext.get("indexingPaused")).toBe(false);
203+
204+ // Should have salvaged the sharedConfig with allowAnonymousTelemetry
205+ const salvaged = globalContext.get("sharedConfig");
206+ expect(salvaged).toEqual({ allowAnonymousTelemetry: false });
207+
208+ consoleWarnMock.mockRestore();
209+ });
210+
211+ it("should handle salvage when no sharedConfig is present", () => {
212+ const corruptedContent = `{
213+ "indexingPaused": true,
214+ "corrupted": { invalid json
215+}`;
216+ fs.writeFileSync(globalContextFilePath, corruptedContent);
217+
218+ const consoleWarnMock = jest
219+ .spyOn(console, "warn")
220+ .mockImplementation(() => {});
221+
222+ globalContext.update("hasAlreadyCreatedAPromptFile", true);
223+
224+ expect(consoleWarnMock).toHaveBeenCalledWith(
225+ expect.stringContaining(
226+ "Error updating global context, attempting to salvage security-sensitive values",
227+ ),
228+ );
229+
230+ // Should have the new value
231+ expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true);
232+
233+ // Should not have any sharedConfig since none was salvageable
234+ expect(globalContext.get("sharedConfig")).toBeUndefined();
235+
236+ consoleWarnMock.mockRestore();
237+ });
238+
239+ it("should handle salvage when sharedConfig has invalid allowAnonymousTelemetry", () => {
240+ const corruptedContent = `{
241+ "indexingPaused": true,
242+ "sharedConfig": {"allowAnonymousTelemetry": "not-a-boolean"},
243+ "corrupted": { invalid json
244+}`;
245+ fs.writeFileSync(globalContextFilePath, corruptedContent);
246+
247+ const consoleWarnMock = jest
248+ .spyOn(console, "warn")
249+ .mockImplementation(() => {});
250+
251+ globalContext.update("indexingPaused", false);
252+
253+ // Should not have salvaged an invalid boolean value
254+ const salvaged = globalContext.get("sharedConfig");
255+ expect(salvaged).toBeUndefined();
256+
257+ consoleWarnMock.mockRestore();
258+ });
259+
260+ it("should handle salvage with valid allowAnonymousTelemetry set to true", () => {
261+ const corruptedContent = `{
262+ "indexingPaused": true,
263+ "sharedConfig": {"allowAnonymousTelemetry": true, "otherField": "value"},
264+ "corrupted": { invalid json
265+}`;
266+ fs.writeFileSync(globalContextFilePath, corruptedContent);
267+
268+ const consoleWarnMock = jest
269+ .spyOn(console, "warn")
270+ .mockImplementation(() => {});
271+
272+ globalContext.update("hasAlreadyCreatedAPromptFile", true);
273+
274+ // Should have salvaged only the allowAnonymousTelemetry value
275+ const salvaged = globalContext.get("sharedConfig");
276+ expect(salvaged).toEqual({ allowAnonymousTelemetry: true });
277+
278+ consoleWarnMock.mockRestore();
279+ });
280+
281+ it("should handle completely unparseable content gracefully", () => {
282+ fs.writeFileSync(
283+ globalContextFilePath,
284+ "complete garbage not json at all",
285+ );
286+
287+ const consoleWarnMock = jest
288+ .spyOn(console, "warn")
289+ .mockImplementation(() => {});
290+
291+ globalContext.update("indexingPaused", true);
292+
293+ // Should still work and create a new file
294+ expect(globalContext.get("indexingPaused")).toBe(true);
295+ expect(globalContext.get("sharedConfig")).toBeUndefined();
296+
297+ consoleWarnMock.mockRestore();
298+ });
299+
300+ it("should preserve multiple salvageable values when updating different key", () => {
301+ const corruptedContent = `{
302+ "indexingPaused": true,
303+ "sharedConfig": {"allowAnonymousTelemetry": false},
304+ "hasAlreadyCreatedAPromptFile": true,
305+ "corrupted": { invalid json
306+}`;
307+ fs.writeFileSync(globalContextFilePath, corruptedContent);
308+
309+ const consoleWarnMock = jest
310+ .spyOn(console, "warn")
311+ .mockImplementation(() => {});
312+
313+ // Update a different key - should salvage and preserve existing data
314+ globalContext.update("showConfigUpdateToast", false);
315+
316+ // Should have the new value
317+ expect(globalContext.get("showConfigUpdateToast")).toBe(false);
318+
319+ // Should have salvaged the security-sensitive value
320+ expect(globalContext.get("sharedConfig")).toEqual({
321+ allowAnonymousTelemetry: false,
322+ });
323+
324+ consoleWarnMock.mockRestore();
325+ });
326+ });
177327 });
modified core/util/GlobalContext.ts +37 −12
@@ -1,6 +1,10 @@
11 import fs from "node:fs";
22
33 import { ModelRole } from "@continuedev/config-yaml";
4+import {
5+ OAuthClientInformationFull,
6+ OAuthTokens,
7+} from "@modelcontextprotocol/sdk/shared/auth.js";
48
59 import { SiteIndexingConfig } from "..";
610 import {
@@ -42,6 +46,13 @@
4246 shownDeprecatedProviderWarnings: {
4347 [providerTitle: string]: boolean;
4448 };
49+ mcpOauthStorage: {
50+ [serverUrl: string]: {
51+ clientInformation?: OAuthClientInformationFull;
52+ tokens?: OAuthTokens;
53+ codeVerifier?: string;
54+ };
55+ };
4556 };
4657
4758 /**
@@ -72,8 +83,25 @@
7283 parsed = JSON.parse(data);
7384 } catch (e: any) {
7485 console.warn(
75- `Error updating global context, deleting corrupted file: ${e}`,
86+ `Error updating global context, attempting to salvage security-sensitive values: ${e}`,
7687 );
88+
89+ // Attempt to salvage security-sensitive values before deleting
90+ let salvaged: Partial<GlobalContextType> = {};
91+ try {
92+ // Try to partially parse the corrupted data to extract sharedConfig
93+ const match = data.match(/"sharedConfig"\s*:\s*({[^}]*})/);
94+ if (match) {
95+ const sharedConfigObj = JSON.parse(match[1]);
96+ const salvagedSharedConfig = salvageSharedConfig(sharedConfigObj);
97+ if (Object.keys(salvagedSharedConfig).length > 0) {
98+ salvaged.sharedConfig = salvagedSharedConfig;
99+ }
100+ }
101+ } catch {
102+ // If salvage fails, continue with empty salvaged object
103+ }
104+
77105 // Delete the corrupted file and recreate it fresh
78106 try {
79107 fs.unlinkSync(filepath);
@@ -82,17 +110,14 @@
82110 `Error deleting corrupted global context file: ${deleteError}`,
83111 );
84112 }
85- // Recreate the file with just the new value
86- fs.writeFileSync(
87- filepath,
88- JSON.stringify(
89- {
90- [key]: value,
91- },
92- null,
93- 2,
94- ),
95- );
113+
114+ // Recreate the file with salvaged values plus the new value
115+ const newData = {
116+ ...salvaged,
117+ [key]: value,
118+ };
119+
120+ fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
96121 return;
97122 }
98123
added core/util/Logger.ts +86 −0
@@ -0,0 +1,86 @@
1+import winston from "winston";
2+import { captureException } from "./sentry/SentryLogger";
3+
4+class LoggerClass {
5+ private static instance: LoggerClass;
6+ private winston: winston.Logger;
7+
8+ private constructor() {
9+ this.winston = winston.createLogger({
10+ level: "info",
11+ format: winston.format.combine(
12+ winston.format.colorize(),
13+ winston.format.timestamp(),
14+ winston.format.printf(({ level, message, timestamp, ...meta }) => {
15+ const metaStr = Object.keys(meta).length
16+ ? ` ${JSON.stringify(meta)}`
17+ : "";
18+ return `[@continuedev] ${level}: ${message}${metaStr}`;
19+ }),
20+ ),
21+ transports: [
22+ // Write all logs with importance level of `info` or higher to `info.log`
23+ ...(process.env.NODE_ENV === "test"
24+ ? [
25+ new winston.transports.File({
26+ filename: "e2e.log",
27+ level: "info",
28+ }),
29+ ]
30+ : []),
31+ // Normal console.log behavior
32+ new winston.transports.Console(),
33+ ],
34+ });
35+ }
36+
37+ public static getInstance(): LoggerClass {
38+ if (!LoggerClass.instance) {
39+ LoggerClass.instance = new LoggerClass();
40+ }
41+ return LoggerClass.instance;
42+ }
43+
44+ private shouldSendToSentry(): boolean {
45+ return process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "e2e";
46+ }
47+
48+ public log(message: string, meta?: any): void {
49+ this.winston.info(message, meta);
50+ }
51+
52+ public debug(message: string, meta?: any): void {
53+ this.winston.debug(message, meta);
54+ }
55+
56+ public info(message: string, meta?: any): void {
57+ this.winston.info(message, meta);
58+ }
59+
60+ public warn(message: string, meta?: any): void {
61+ this.winston.warn(message, meta);
62+ }
63+
64+ public error(
65+ error: Error | string | unknown,
66+ context?: Record<string, any>,
67+ ): void {
68+ let errorMessage: string;
69+
70+ if (error instanceof Error) {
71+ errorMessage = error.message;
72+ } else if (typeof error === "string") {
73+ errorMessage = error;
74+ } else {
75+ errorMessage = "An unknown error occurred";
76+ }
77+
78+ this.winston.error(errorMessage, context);
79+
80+ if (this.shouldSendToSentry() && error instanceof Error) {
81+ captureException(error, context);
82+ }
83+ }
84+}
85+
86+export const Logger = LoggerClass.getInstance();
added core/util/isContinueTeamMember.ts +7 −0
@@ -0,0 +1,7 @@
1+/**
2+ * Utility to check if a user is a Continue team member
3+ */
4+export function isContinueTeamMember(email?: string): boolean {
5+ if (!email) return false;
6+ return email.endsWith("@continue.dev");
7+}
deleted core/util/logger.ts +0 −16
@@ -1,16 +0,0 @@
1-import winston from "winston";
2-
3-console.log("NODE_ENV", process.env.NODE_ENV);
4-
5-export const logger = winston.createLogger({
6- level: "info",
7- format: winston.format.json(),
8- transports: [
9- // Write all logs with importance level of `info` or higher to `info.log`
10- ...(process.env.NODE_ENV === "test"
11- ? [new winston.transports.File({ filename: "e2e.log", level: "info" })]
12- : []),
13- // Normal console.log behavior
14- new winston.transports.Console(),
15- ],
16-});
added core/util/sentry/SentryLogger.test.ts +886 −0
@@ -0,0 +1,886 @@
1+import { IdeInfo } from "../../index.js";
2+import {
3+ SentryLogger,
4+ captureException,
5+ captureLog,
6+ createSpan,
7+ initializeSentry,
8+} from "./SentryLogger";
9+import { anonymizeSentryEvent } from "./anonymization";
10+
11+describe("SentryLogger Integration Tests", () => {
12+ const mockIdeInfo: IdeInfo = {
13+ extensionVersion: "1.0.0",
14+ name: "vscode",
15+ ideType: "vscode",
16+ version: "1.0.0",
17+ remoteName: "local",
18+ isPrerelease: false,
19+ };
20+
21+ beforeEach(() => {
22+ // Reset SentryLogger state before each test
23+ SentryLogger.client = undefined;
24+ SentryLogger.scope = undefined;
25+ SentryLogger.allowTelemetry = false;
26+ SentryLogger.uniqueId = "NOT_UNIQUE";
27+ SentryLogger.ideInfo = undefined;
28+ });
29+
30+ afterEach(() => {
31+ // Clean up after each test
32+ SentryLogger.shutdownSentryClient();
33+ });
34+
35+ describe("Telemetry Toggle Behavior", () => {
36+ it("should not initialize when telemetry is disabled", async () => {
37+ await SentryLogger.setup(
38+ false,
39+ "test-id",
40+ mockIdeInfo,
41+ "test@continue.dev",
42+ );
43+
44+ expect(SentryLogger.allowTelemetry).toBe(false);
45+ expect(SentryLogger.client).toBeUndefined();
46+ expect(SentryLogger.scope).toBeUndefined();
47+ expect(SentryLogger.uniqueId).toBe("test-id");
48+ expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
49+ });
50+
51+ it("should not initialize in test environment even when telemetry is enabled", async () => {
52+ const originalNodeEnv = process.env.NODE_ENV;
53+ process.env.NODE_ENV = "test";
54+
55+ await SentryLogger.setup(
56+ true,
57+ "test-id",
58+ mockIdeInfo,
59+ "test@continue.dev",
60+ );
61+
62+ // In the updated implementation, the Continue team member check is used instead of NODE_ENV check
63+ // so we're not setting allowTelemetry to false just because we're in test environment anymore
64+ expect(SentryLogger.allowTelemetry).toBe(true);
65+ // But client and scope should still be initialized
66+ expect(SentryLogger.client).toBeDefined();
67+ expect(SentryLogger.scope).toBeDefined();
68+
69+ process.env.NODE_ENV = originalNodeEnv;
70+ });
71+
72+ it("should initialize when telemetry is enabled in non-test environment", async () => {
73+ const originalNodeEnv = process.env.NODE_ENV;
74+ process.env.NODE_ENV = "development";
75+
76+ await SentryLogger.setup(
77+ true,
78+ "test-id",
79+ mockIdeInfo,
80+ "test@continue.dev",
81+ );
82+
83+ expect(SentryLogger.allowTelemetry).toBe(true);
84+ expect(SentryLogger.uniqueId).toBe("test-id");
85+ expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
86+ expect(SentryLogger.client).toBeDefined();
87+ expect(SentryLogger.scope).toBeDefined();
88+
89+ process.env.NODE_ENV = originalNodeEnv;
90+ });
91+
92+ it("should handle telemetry being disabled after being enabled", async () => {
93+ const originalNodeEnv = process.env.NODE_ENV;
94+ process.env.NODE_ENV = "development";
95+
96+ // Enable telemetry first
97+ await SentryLogger.setup(
98+ true,
99+ "test-id",
100+ mockIdeInfo,
101+ "test@continue.dev",
102+ );
103+ expect(SentryLogger.allowTelemetry).toBe(true);
104+ expect(SentryLogger.client).toBeDefined();
105+
106+ // Then disable it
107+ await SentryLogger.setup(false, "test-id-2", mockIdeInfo);
108+ expect(SentryLogger.allowTelemetry).toBe(false);
109+ expect(SentryLogger.client).toBeUndefined();
110+ expect(SentryLogger.scope).toBeUndefined();
111+
112+ process.env.NODE_ENV = originalNodeEnv;
113+ });
114+
115+ it("should not reinitialize if client already exists", async () => {
116+ const originalNodeEnv = process.env.NODE_ENV;
117+ process.env.NODE_ENV = "development";
118+
119+ // First setup
120+ await SentryLogger.setup(
121+ true,
122+ "test-id",
123+ mockIdeInfo,
124+ "test@continue.dev",
125+ );
126+ const firstClient = SentryLogger.client;
127+ const firstScope = SentryLogger.scope;
128+
129+ // Second setup should not change the client
130+ await SentryLogger.setup(
131+ true,
132+ "test-id-2",
133+ mockIdeInfo,
134+ "test@continue.dev",
135+ );
136+ expect(SentryLogger.client).toBe(firstClient);
137+ expect(SentryLogger.scope).toBe(firstScope);
138+ expect(SentryLogger.uniqueId).toBe("test-id-2"); // ID should update
139+ expect(SentryLogger.ideInfo).toBe(mockIdeInfo); // Info should update
140+
141+ process.env.NODE_ENV = originalNodeEnv;
142+ });
143+ });
144+
145+ describe("Lazy Initialization", () => {
146+ it("should initialize when accessing lazyClient if conditions are met", () => {
147+ const originalNodeEnv = process.env.NODE_ENV;
148+ process.env.NODE_ENV = "development";
149+
150+ // Set up conditions for lazy initialization
151+ SentryLogger.allowTelemetry = true;
152+ SentryLogger.ideInfo = mockIdeInfo;
153+
154+ // Access lazy client should trigger initialization
155+ const client = SentryLogger.lazyClient;
156+
157+ expect(client).toBeDefined();
158+ expect(SentryLogger.client).toBe(client);
159+ expect(SentryLogger.scope).toBeDefined();
160+
161+ process.env.NODE_ENV = originalNodeEnv;
162+ });
163+
164+ it("should not initialize if telemetry is disabled", () => {
165+ SentryLogger.allowTelemetry = false;
166+ SentryLogger.ideInfo = mockIdeInfo;
167+
168+ const client = SentryLogger.lazyClient;
169+
170+ expect(client).toBeUndefined();
171+ expect(SentryLogger.client).toBeUndefined();
172+ expect(SentryLogger.scope).toBeUndefined();
173+ });
174+
175+ it("should not initialize if ideInfo is missing", () => {
176+ const originalNodeEnv = process.env.NODE_ENV;
177+ process.env.NODE_ENV = "development";
178+
179+ SentryLogger.allowTelemetry = true;
180+ SentryLogger.ideInfo = undefined;
181+
182+ const client = SentryLogger.lazyClient;
183+
184+ expect(client).toBeUndefined();
185+ expect(SentryLogger.client).toBeUndefined();
186+
187+ process.env.NODE_ENV = originalNodeEnv;
188+ });
189+ });
190+
191+ describe("Shutdown Behavior", () => {
192+ it("should properly shutdown when client exists", async () => {
193+ const originalNodeEnv = process.env.NODE_ENV;
194+ process.env.NODE_ENV = "development";
195+
196+ // Setup Sentry first
197+ await SentryLogger.setup(
198+ true,
199+ "test-id",
200+ mockIdeInfo,
201+ "test@continue.dev",
202+ );
203+ expect(SentryLogger.client).toBeDefined();
204+
205+ // Shutdown should clean up
206+ SentryLogger.shutdownSentryClient();
207+ expect(SentryLogger.client).toBeUndefined();
208+ expect(SentryLogger.scope).toBeUndefined();
209+
210+ process.env.NODE_ENV = originalNodeEnv;
211+ });
212+
213+ it("should handle shutdown gracefully when client is undefined", () => {
214+ expect(() => SentryLogger.shutdownSentryClient()).not.toThrow();
215+ expect(SentryLogger.client).toBeUndefined();
216+ expect(SentryLogger.scope).toBeUndefined();
217+ });
218+ });
219+});
220+
221+describe("Sentry Utility Functions", () => {
222+ const mockIdeInfo: IdeInfo = {
223+ extensionVersion: "1.0.0",
224+ name: "vscode",
225+ ideType: "vscode",
226+ version: "1.0.0",
227+ remoteName: "local",
228+ isPrerelease: false,
229+ };
230+
231+ beforeEach(() => {
232+ // Reset SentryLogger state
233+ SentryLogger.client = undefined;
234+ SentryLogger.scope = undefined;
235+ SentryLogger.allowTelemetry = false;
236+ });
237+
238+ afterEach(() => {
239+ SentryLogger.shutdownSentryClient();
240+ });
241+
242+ describe("initializeSentry", () => {
243+ it("should return undefined when telemetry is disabled", () => {
244+ const result = initializeSentry();
245+
246+ expect(result.client).toBeUndefined();
247+ expect(result.scope).toBeUndefined();
248+ });
249+
250+ it("should return client and scope when telemetry is enabled", async () => {
251+ const originalNodeEnv = process.env.NODE_ENV;
252+ process.env.NODE_ENV = "development";
253+
254+ await SentryLogger.setup(
255+ true,
256+ "test-id",
257+ mockIdeInfo,
258+ "test@continue.dev",
259+ );
260+ const result = initializeSentry();
261+
262+ expect(result.client).toBeDefined();
263+ expect(result.scope).toBeDefined();
264+ expect(result.client).toBe(SentryLogger.client);
265+ expect(result.scope).toBe(SentryLogger.scope);
266+
267+ process.env.NODE_ENV = originalNodeEnv;
268+ });
269+ });
270+
271+ describe("createSpan", () => {
272+ it("should execute callback normally when telemetry is disabled", () => {
273+ const callback = jest.fn().mockReturnValue("test-result");
274+
275+ const result = createSpan("test.operation", "test span", callback);
276+
277+ expect(result).toBe("test-result");
278+ expect(callback).toHaveBeenCalledTimes(1);
279+ });
280+
281+ it("should execute callback with span when telemetry is enabled", async () => {
282+ const originalNodeEnv = process.env.NODE_ENV;
283+ process.env.NODE_ENV = "development";
284+
285+ await SentryLogger.setup(
286+ true,
287+ "test-id",
288+ mockIdeInfo,
289+ "test@continue.dev",
290+ );
291+
292+ const callback = jest.fn().mockReturnValue("test-result");
293+ const result = createSpan("test.operation", "test span", callback);
294+
295+ expect(result).toBe("test-result");
296+ expect(callback).toHaveBeenCalledTimes(1);
297+
298+ process.env.NODE_ENV = originalNodeEnv;
299+ });
300+
301+ it("should handle async callbacks", async () => {
302+ const originalNodeEnv = process.env.NODE_ENV;
303+ process.env.NODE_ENV = "development";
304+
305+ await SentryLogger.setup(
306+ true,
307+ "test-id",
308+ mockIdeInfo,
309+ "test@continue.dev",
310+ );
311+
312+ const asyncCallback = jest.fn().mockResolvedValue("async-result");
313+ const result = await createSpan(
314+ "test.operation",
315+ "test span",
316+ asyncCallback,
317+ );
318+
319+ expect(result).toBe("async-result");
320+ expect(asyncCallback).toHaveBeenCalledTimes(1);
321+
322+ process.env.NODE_ENV = originalNodeEnv;
323+ });
324+ });
325+
326+ describe("captureException", () => {
327+ it("should not throw when telemetry is disabled", () => {
328+ const error = new Error("test error");
329+
330+ expect(() => captureException(error)).not.toThrow();
331+ expect(() => captureException(error, { context: "test" })).not.toThrow();
332+ });
333+
334+ it("should not throw when telemetry is enabled", async () => {
335+ const originalNodeEnv = process.env.NODE_ENV;
336+ process.env.NODE_ENV = "development";
337+
338+ await SentryLogger.setup(
339+ true,
340+ "test-id",
341+ mockIdeInfo,
342+ "test@continue.dev",
343+ );
344+
345+ const error = new Error("test error");
346+
347+ expect(() => captureException(error)).not.toThrow();
348+ expect(() => captureException(error, { context: "test" })).not.toThrow();
349+
350+ process.env.NODE_ENV = originalNodeEnv;
351+ });
352+
353+ it("should handle malformed context gracefully", async () => {
354+ const originalNodeEnv = process.env.NODE_ENV;
355+ process.env.NODE_ENV = "development";
356+
357+ await SentryLogger.setup(
358+ true,
359+ "test-id",
360+ mockIdeInfo,
361+ "test@continue.dev",
362+ );
363+
364+ const error = new Error("test error");
365+
366+ expect(() => captureException(error, null as any)).not.toThrow();
367+ expect(() => captureException(error, undefined)).not.toThrow();
368+ expect(() => captureException(error, { circular: {} })).not.toThrow();
369+
370+ process.env.NODE_ENV = originalNodeEnv;
371+ });
372+ });
373+
374+ describe("captureLog", () => {
375+ it("should not throw when telemetry is disabled", () => {
376+ expect(() => captureLog("test message")).not.toThrow();
377+ expect(() =>
378+ captureLog("test message", "info", { context: "test" }),
379+ ).not.toThrow();
380+ });
381+
382+ it("should not throw when telemetry is enabled", async () => {
383+ const originalNodeEnv = process.env.NODE_ENV;
384+ process.env.NODE_ENV = "development";
385+
386+ await SentryLogger.setup(
387+ true,
388+ "test-id",
389+ mockIdeInfo,
390+ "test@continue.dev",
391+ );
392+
393+ expect(() => captureLog("test message")).not.toThrow();
394+ expect(() =>
395+ captureLog("test message", "error", { context: "test" }),
396+ ).not.toThrow();
397+
398+ process.env.NODE_ENV = originalNodeEnv;
399+ });
400+
401+ it("should handle malformed context gracefully", async () => {
402+ const originalNodeEnv = process.env.NODE_ENV;
403+ process.env.NODE_ENV = "development";
404+
405+ await SentryLogger.setup(
406+ true,
407+ "test-id",
408+ mockIdeInfo,
409+ "test@continue.dev",
410+ );
411+
412+ expect(() =>
413+ captureLog("test message", "info", null as any),
414+ ).not.toThrow();
415+ expect(() =>
416+ captureLog("test message", "warning", undefined),
417+ ).not.toThrow();
418+ expect(() =>
419+ captureLog("test message", "error", { circular: {} }),
420+ ).not.toThrow();
421+
422+ process.env.NODE_ENV = originalNodeEnv;
423+ });
424+ });
425+
426+ describe("Integration Tests", () => {
427+ it("should maintain consistent state across utility functions", async () => {
428+ const originalNodeEnv = process.env.NODE_ENV;
429+ process.env.NODE_ENV = "development";
430+
431+ // Start with telemetry disabled
432+ expect(initializeSentry().client).toBeUndefined();
433+
434+ const callback = jest.fn().mockReturnValue("result");
435+ createSpan("test", "test", callback);
436+ expect(callback).toHaveBeenCalled();
437+
438+ // Enable telemetry
439+ await SentryLogger.setup(
440+ true,
441+ "test-id",
442+ mockIdeInfo,
443+ "test@continue.dev",
444+ );
445+
446+ // Now utility functions should work with Sentry
447+ const sentryResult = initializeSentry();
448+ expect(sentryResult.client).toBeDefined();
449+ expect(sentryResult.scope).toBeDefined();
450+
451+ // Functions should work without throwing
452+ const callback2 = jest.fn().mockReturnValue("result2");
453+ const spanResult = createSpan("test2", "test2", callback2);
454+ expect(spanResult).toBe("result2");
455+ expect(callback2).toHaveBeenCalled();
456+
457+ const error = new Error("test error");
458+ expect(() => captureException(error, { test: "context" })).not.toThrow();
459+ expect(() =>
460+ captureLog("test log message", "info", { test: "context" }),
461+ ).not.toThrow();
462+
463+ // Disable telemetry again
464+ await SentryLogger.setup(
465+ false,
466+ "test-id",
467+ mockIdeInfo,
468+ "test@continue.dev",
469+ );
470+ expect(initializeSentry().client).toBeUndefined();
471+
472+ process.env.NODE_ENV = originalNodeEnv;
473+ });
474+ });
475+});
476+
477+describe("Sentry Data Anonymization Tests", () => {
478+ describe("anonymizeSentryEvent", () => {
479+ it("should anonymize user file paths in stack traces", () => {
480+ const event: any = {
481+ exception: {
482+ values: [
483+ {
484+ stacktrace: {
485+ frames: [
486+ {
487+ filename: "/Users/john/workspace/my-project/src/app.js",
488+ abs_path: "/Users/john/workspace/my-project/src/app.js",
489+ function: "myFunction",
490+ lineno: 42,
491+ vars: { secret: "password123" },
492+ pre_context: ["const secret = 'password123'"],
493+ post_context: ["console.log(secret)"],
494+ context_line: "throw new Error('test')",
495+ },
496+ ],
497+ },
498+ },
499+ ],
500+ },
501+ };
502+
503+ const result = anonymizeSentryEvent(event);
504+ expect(result).not.toBeNull();
505+ expect(
506+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
507+ ).toBe("<file>");
508+ expect(
509+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
510+ ).toBe("");
511+ expect(
512+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
513+ ).toBeUndefined();
514+ expect(
515+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
516+ ).toBeUndefined();
517+ expect(
518+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
519+ ).toBeUndefined();
520+ expect(
521+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
522+ ).toBe("<code>");
523+ });
524+
525+ it("should anonymize all absolute file paths equally", () => {
526+ const event: any = {
527+ exception: {
528+ values: [
529+ {
530+ stacktrace: {
531+ frames: [
532+ {
533+ filename: "/Users/dev/continue/core/util/sentry.js",
534+ abs_path: "/Users/dev/continue/core/util/sentry.js",
535+ function: "captureException",
536+ lineno: 42,
537+ vars: { secret: "password123" },
538+ pre_context: ["const secret = 'password123'"],
539+ post_context: ["console.log(secret)"],
540+ context_line: "throw new Error('test')",
541+ },
542+ ],
543+ },
544+ },
545+ ],
546+ },
547+ };
548+
549+ const result = anonymizeSentryEvent(event);
550+ expect(result).not.toBeNull();
551+ expect(
552+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
553+ ).toBe("<file>");
554+ expect(
555+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
556+ ).toBe("");
557+ expect(
558+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
559+ ).toBeUndefined();
560+ expect(
561+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
562+ ).toBeUndefined();
563+ expect(
564+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
565+ ).toBeUndefined();
566+ expect(
567+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
568+ ).toBe("<code>");
569+ });
570+
571+ it("should preserve node_modules package names for debugging", () => {
572+ const event: any = {
573+ exception: {
574+ values: [
575+ {
576+ stacktrace: {
577+ frames: [
578+ {
579+ filename:
580+ "/Users/dev/project/node_modules/@sentry/node/index.js",
581+ abs_path:
582+ "/Users/dev/project/node_modules/@sentry/node/index.js",
583+ function: "init",
584+ lineno: 123,
585+ },
586+ ],
587+ },
588+ },
589+ ],
590+ },
591+ };
592+
593+ const result = anonymizeSentryEvent(event);
594+ expect(result).not.toBeNull();
595+ expect(
596+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
597+ ).toBe("node_modules/@sentry/<file>");
598+ expect(
599+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
600+ ).toBe("");
601+ });
602+
603+ it("should hash user IDs", () => {
604+ const event: any = {
605+ user: {
606+ id: "real-machine-id-12345",
607+ username: "john.doe",
608+ email: "john@example.com",
609+ ip_address: "192.168.1.100",
610+ },
611+ };
612+
613+ const result = anonymizeSentryEvent(event);
614+ expect(result).not.toBeNull();
615+ expect(result?.user?.id).not.toBe("real-machine-id-12345");
616+ expect(result?.user?.id).toMatch(/^[a-f0-9]{8}$/); // Should be 8-char hash
617+ expect(result?.user?.username).toBeUndefined();
618+ expect(result?.user?.email).toBeUndefined();
619+ expect(result?.user?.ip_address).toBeUndefined();
620+ });
621+
622+ it("should preserve breadcrumbs unchanged", () => {
623+ const event: any = {
624+ breadcrumbs: [
625+ {
626+ message:
627+ "File opened: /Users/john/Documents/secret-project/config.js",
628+ category: "file",
629+ data: {
630+ filename: "/Users/john/Documents/secret-project/config.js",
631+ action: "open",
632+ },
633+ },
634+ {
635+ message: "Error in module initialization",
636+ category: "error",
637+ data: {
638+ module: "auth",
639+ error: "Connection failed",
640+ },
641+ },
642+ ],
643+ };
644+
645+ const result = anonymizeSentryEvent(event);
646+ expect(result).not.toBeNull();
647+ // Breadcrumbs are preserved as-is in our minimalist approach
648+ expect(result?.breadcrumbs?.[0]?.message).toBe(
649+ "File opened: /Users/john/Documents/secret-project/config.js",
650+ );
651+ expect(result?.breadcrumbs?.[0]?.data?.filename).toBe(
652+ "/Users/john/Documents/secret-project/config.js",
653+ );
654+ expect(result?.breadcrumbs?.[0]?.data?.action).toBe("open");
655+ expect(result?.breadcrumbs?.[1]?.message).toBe(
656+ "Error in module initialization",
657+ );
658+ expect(result?.breadcrumbs?.[1]?.data?.module).toBe("auth");
659+ expect(result?.breadcrumbs?.[1]?.data?.error).toBe("Connection failed");
660+ });
661+
662+ it("should preserve tags unchanged", () => {
663+ const event: any = {
664+ tags: {
665+ username: "john.doe",
666+ user_id: "12345",
667+ workspace: "/Users/john/workspace",
668+ project_path: "/path/to/project",
669+ environment: "production",
670+ version: "1.2.3",
671+ },
672+ };
673+
674+ const result = anonymizeSentryEvent(event);
675+ expect(result).not.toBeNull();
676+ // Tags are preserved as-is in our minimalist approach
677+ expect(result?.tags?.username).toBe("john.doe");
678+ expect(result?.tags?.user_id).toBe("12345");
679+ expect(result?.tags?.workspace).toBe("/Users/john/workspace");
680+ expect(result?.tags?.project_path).toBe("/path/to/project");
681+ expect(result?.tags?.environment).toBe("production");
682+ expect(result?.tags?.version).toBe("1.2.3");
683+ });
684+
685+ it("should preserve extra data unchanged", () => {
686+ const event: any = {
687+ extra: {
688+ path: "/Users/john/secret-project",
689+ filename: "config.js",
690+ directory: "/home/user/workspace",
691+ workspace: "/Users/john/workspace",
692+ user: "john.doe",
693+ home: "/Users/john",
694+ config_file: "/some/long/path/to/config.json",
695+ error_code: 500,
696+ timestamp: "2023-01-01T00:00:00Z",
697+ },
698+ };
699+
700+ const result = anonymizeSentryEvent(event);
701+ expect(result).not.toBeNull();
702+ // Extra data is preserved as-is in our minimalist approach
703+ expect(result?.extra?.path).toBe("/Users/john/secret-project");
704+ expect(result?.extra?.filename).toBe("config.js");
705+ expect(result?.extra?.directory).toBe("/home/user/workspace");
706+ expect(result?.extra?.workspace).toBe("/Users/john/workspace");
707+ expect(result?.extra?.user).toBe("john.doe");
708+ expect(result?.extra?.home).toBe("/Users/john");
709+ expect(result?.extra?.config_file).toBe("/some/long/path/to/config.json");
710+ expect(result?.extra?.error_code).toBe(500);
711+ expect(result?.extra?.timestamp).toBe("2023-01-01T00:00:00Z");
712+ });
713+
714+ it("should anonymize thread stack traces", () => {
715+ const event: any = {
716+ threads: {
717+ values: [
718+ {
719+ id: "main",
720+ name: "MainThread",
721+ stacktrace: {
722+ frames: [
723+ {
724+ filename: "/Users/john/workspace/app.js",
725+ abs_path: "/Users/john/workspace/app.js",
726+ function: "main",
727+ lineno: 1,
728+ vars: { apiKey: "secret-key-123" },
729+ context_line: "const apiKey = 'secret-key-123'",
730+ },
731+ ],
732+ },
733+ },
734+ ],
735+ },
736+ };
737+
738+ const result = anonymizeSentryEvent(event);
739+ expect(result).not.toBeNull();
740+ expect(
741+ result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
742+ ).toBe("<file>");
743+ expect(
744+ result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
745+ ).toBe("");
746+ expect(
747+ result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
748+ ).toBeUndefined();
749+ expect(
750+ result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
751+ ).toBe("<code>");
752+ });
753+
754+ it("should remove OS environment variables", () => {
755+ const event: any = {
756+ contexts: {
757+ os: {
758+ name: "macOS",
759+ version: "12.6",
760+ environment: {
761+ HOME: "/Users/john",
762+ USER: "john",
763+ PATH: "/usr/local/bin:/usr/bin",
764+ },
765+ },
766+ },
767+ };
768+
769+ const result = anonymizeSentryEvent(event);
770+ expect(result).not.toBeNull();
771+ expect(result?.contexts?.os?.name).toBe("macOS");
772+ expect(result?.contexts?.os?.version).toBe("12.6");
773+ expect(result?.contexts?.os?.environment).toBeUndefined();
774+ });
775+
776+ it("should handle events with no sensitive data", () => {
777+ const event: any = {
778+ message: "Simple error message",
779+ level: "error",
780+ timestamp: 1234567890,
781+ tags: {
782+ component: "auth",
783+ level: "error",
784+ },
785+ extra: {
786+ error_code: 404,
787+ retry_count: 3,
788+ },
789+ };
790+
791+ const result = anonymizeSentryEvent(event);
792+ expect(result).not.toBeNull();
793+ expect(result?.message).toBe("Simple error message");
794+ expect(result?.level).toBe("error");
795+ expect(result?.timestamp).toBe(1234567890);
796+ expect(result?.tags?.component).toBe("auth");
797+ expect(result?.extra?.error_code).toBe(404);
798+ });
799+
800+ it("should handle malformed events gracefully", () => {
801+ const malformedEvent: any = {
802+ exception: {
803+ values: null,
804+ },
805+ user: null,
806+ breadcrumbs: "not-an-array",
807+ tags: null,
808+ extra: null,
809+ };
810+
811+ const result = anonymizeSentryEvent(malformedEvent);
812+ expect(result).not.toBeNull();
813+ });
814+
815+ it("should handle anonymization errors by returning null", () => {
816+ // Create a circular reference that would cause JSON serialization issues
817+ const circularEvent: any = {
818+ message: "Test event",
819+ };
820+ circularEvent.circular = circularEvent;
821+
822+ // Mock the anonymization to throw an error
823+ const originalConsoleError = console.error;
824+ console.error = jest.fn();
825+
826+ const result = anonymizeSentryEvent(circularEvent);
827+
828+ // Should not throw, but should return null for safety
829+ expect(result).not.toBeNull(); // Actually, our function might handle this case
830+
831+ console.error = originalConsoleError;
832+ });
833+
834+ it("should anonymize all absolute paths regardless of format", () => {
835+ const event: any = {
836+ exception: {
837+ values: [
838+ {
839+ stacktrace: {
840+ frames: [
841+ {
842+ filename:
843+ "C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
844+ abs_path:
845+ "C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
846+ },
847+ {
848+ filename: "/home/dev/continue/core/util/sentry.js",
849+ abs_path: "/home/dev/continue/core/util/sentry.js",
850+ },
851+ {
852+ filename: "relative/path/file.js",
853+ abs_path: "/absolute/path/file.js",
854+ },
855+ ],
856+ },
857+ },
858+ ],
859+ },
860+ };
861+
862+ const result = anonymizeSentryEvent(event);
863+ expect(result).not.toBeNull();
864+ // All absolute paths get anonymized equally
865+ expect(
866+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
867+ ).toBe("<file>");
868+ expect(
869+ result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.filename,
870+ ).toBe("<file>");
871+ expect(
872+ result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.filename,
873+ ).toBe("relative/path/file.js"); // Relative path preserved
874+ // All abs_path fields cleared
875+ expect(
876+ result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
877+ ).toBe("");
878+ expect(
879+ result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.abs_path,
880+ ).toBe("");
881+ expect(
882+ result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.abs_path,
883+ ).toBe("");
884+ });
885+ });
886+});
added core/util/sentry/SentryLogger.ts +263 −0
@@ -0,0 +1,263 @@
1+import { Extras } from "@sentry/core";
2+import * as Sentry from "@sentry/node";
3+import os from "node:os";
4+import { IdeInfo } from "../../index.js";
5+import { isContinueTeamMember } from "../isContinueTeamMember.js";
6+import { anonymizeSentryEvent } from "./anonymization.js";
7+import { SENTRY_DSN } from "./constants.js";
8+
9+export class SentryLogger {
10+ static client: Sentry.NodeClient | undefined = undefined;
11+ static scope: Sentry.Scope | undefined = undefined;
12+ static uniqueId = "NOT_UNIQUE";
13+ static os: string | undefined = undefined;
14+ static ideInfo: IdeInfo | undefined = undefined;
15+ static allowTelemetry: boolean = false;
16+
17+ private static initializeSentryClient(release: string): {
18+ client: Sentry.NodeClient | undefined;
19+ scope: Sentry.Scope | undefined;
20+ } {
21+ try {
22+ // For shared environments like VSCode extensions, we need to avoid global state pollution
23+ // Filter out integrations that use global state
24+ // See https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/
25+
26+ // Filter integrations that use the global variable
27+ const integrations = Sentry.getDefaultIntegrations({}).filter(
28+ (defaultIntegration) => {
29+ // Remove integrations that might interfere with shared environments
30+ return ![
31+ "OnUncaughtException",
32+ "OnUnhandledRejection",
33+ "ContextLines",
34+ "LocalVariables",
35+ ].includes(defaultIntegration.name);
36+ },
37+ );
38+
39+ // Create client manually without polluting global state
40+ const client = new Sentry.NodeClient({
41+ dsn: SENTRY_DSN,
42+ release,
43+ environment: process.env.NODE_ENV,
44+ transport: Sentry.makeNodeTransport,
45+ stackParser: Sentry.defaultStackParser,
46+
47+ // For basic error tracking, a lower sample rate should be fine
48+ sampleRate: 0.1,
49+ tracesSampleRate: 0.1,
50+
51+ // Privacy-conscious default
52+ sendDefaultPii: false,
53+
54+ // Strip sensitive data and add basic properties before sending events
55+ beforeSend(event) {
56+ // First apply anonymization
57+ const anonymizedEvent = anonymizeSentryEvent(event);
58+ if (!anonymizedEvent) return null;
59+
60+ // Add basic properties similar to PostHog telemetry
61+ if (!anonymizedEvent.tags) anonymizedEvent.tags = {};
62+ if (!anonymizedEvent.extra) anonymizedEvent.extra = {};
63+
64+ // Add OS information
65+ if (SentryLogger.os) {
66+ anonymizedEvent.tags.os = SentryLogger.os;
67+ }
68+
69+ // Add ideInfo properties spread out as top-level properties
70+ if (SentryLogger.ideInfo) {
71+ anonymizedEvent.tags.extensionVersion =
72+ SentryLogger.ideInfo.extensionVersion;
73+ anonymizedEvent.tags.ideName = SentryLogger.ideInfo.name;
74+ anonymizedEvent.tags.ideType = SentryLogger.ideInfo.ideType;
75+ anonymizedEvent.tags.ideVersion = SentryLogger.ideInfo.version;
76+ anonymizedEvent.tags.remoteName = SentryLogger.ideInfo.remoteName;
77+ anonymizedEvent.tags.isPrerelease =
78+ SentryLogger.ideInfo.isPrerelease;
79+ }
80+
81+ return anonymizedEvent;
82+ },
83+
84+ // Use filtered integrations for Node.js/VSCode shared environment
85+ integrations,
86+
87+ // Enable structured logging
88+ _experiments: {
89+ enableLogs: true,
90+ },
91+ });
92+
93+ // Create a new scope and set the client
94+ const scope = new Sentry.Scope();
95+ scope.setClient(client);
96+
97+ // Initialize the client after setting it on the scope
98+ client.init();
99+
100+ return { client, scope };
101+ } catch (error) {
102+ console.error("Failed to initialize Sentry client:", error);
103+ return { client: undefined, scope: undefined };
104+ }
105+ }
106+
107+ static async setup(
108+ allowAnonymousTelemetry: boolean,
109+ uniqueId: string,
110+ ideInfo: IdeInfo,
111+ userEmail?: string,
112+ ) {
113+ // TODO: Remove Continue team member check once Sentry is ready for all users
114+ SentryLogger.allowTelemetry =
115+ allowAnonymousTelemetry && isContinueTeamMember(userEmail);
116+ SentryLogger.uniqueId = uniqueId;
117+ SentryLogger.ideInfo = ideInfo;
118+ SentryLogger.os = os.platform();
119+
120+ if (!SentryLogger.allowTelemetry) {
121+ SentryLogger.client = undefined;
122+ SentryLogger.scope = undefined;
123+ } else if (!SentryLogger.client) {
124+ const { client, scope } = SentryLogger.initializeSentryClient(
125+ ideInfo.extensionVersion,
126+ );
127+ SentryLogger.client = client;
128+ SentryLogger.scope = scope;
129+ }
130+ }
131+
132+ private static ensureInitialized(): void {
133+ if (!SentryLogger.allowTelemetry || SentryLogger.client) {
134+ return;
135+ }
136+
137+ if (SentryLogger.ideInfo) {
138+ const { client, scope } = SentryLogger.initializeSentryClient(
139+ SentryLogger.ideInfo.extensionVersion,
140+ );
141+ SentryLogger.client = client;
142+ SentryLogger.scope = scope;
143+ }
144+ }
145+
146+ static get lazyClient(): Sentry.NodeClient | undefined {
147+ SentryLogger.ensureInitialized();
148+ return SentryLogger.client;
149+ }
150+
151+ static get lazyScope(): Sentry.Scope | undefined {
152+ SentryLogger.ensureInitialized();
153+ return SentryLogger.scope;
154+ }
155+
156+ static shutdownSentryClient() {
157+ if (SentryLogger.client) {
158+ void SentryLogger.client.close();
159+ SentryLogger.client = undefined;
160+ SentryLogger.scope = undefined;
161+ }
162+ }
163+}
164+
165+/**
166+ * Initialize Sentry for error tracking, performance monitoring, and structured logging.
167+ * Returns the Sentry client and scope, or undefined objects if telemetry is disabled.
168+ */
169+export function initializeSentry(): {
170+ client: Sentry.NodeClient | undefined;
171+ scope: Sentry.Scope | undefined;
172+} {
173+ return {
174+ client: SentryLogger.lazyClient,
175+ scope: SentryLogger.lazyScope,
176+ };
177+}
178+
179+// Export utility functions for using Sentry throughout the application
180+
181+/**
182+ * Create a custom span for performance monitoring
183+ *
184+ * @param operation The operation category (e.g., "http.client", "ui.click", "db.query")
185+ * @param name A descriptive name for the span
186+ * @param callback The function to execute within the span
187+ * @returns The result of the callback function
188+ */
189+export function createSpan<T>(
190+ operation: string,
191+ name: string,
192+ callback: () => T | Promise<T>,
193+): T | Promise<T> {
194+ const client = SentryLogger.lazyClient;
195+ if (!client) {
196+ return callback();
197+ }
198+
199+ // Use withScope from Sentry to isolate the span context
200+ return Sentry.withScope((isolatedScope) => {
201+ isolatedScope.setClient(client);
202+ return Sentry.startSpan(
203+ {
204+ op: operation,
205+ name,
206+ },
207+ () => callback(),
208+ );
209+ });
210+}
211+
212+/**
213+ * Capture an exception and send it to Sentry
214+ *
215+ * @param error The error to capture
216+ * @param context Additional context information
217+ */
218+export function captureException(error: Error, context?: Record<string, any>) {
219+ const scope = SentryLogger.lazyScope;
220+ if (!scope) {
221+ return;
222+ }
223+
224+ try {
225+ // Add context to scope if provided
226+ if (context) {
227+ scope.setExtras(context);
228+ }
229+ // Use scope's captureException to avoid global state
230+ scope.captureException(error);
231+ } catch (e) {
232+ console.error(`Failed to capture exception to Sentry: ${e}`);
233+ }
234+}
235+
236+/**
237+ * Capture a structured log message and send it to Sentry
238+ *
239+ * @param message The log message
240+ * @param level The severity level (default: 'info')
241+ * @param context Additional context information
242+ */
243+export function captureLog(
244+ message: string,
245+ level: Sentry.SeverityLevel = "info",
246+ context?: Extras,
247+) {
248+ const scope = SentryLogger.lazyScope;
249+ if (!scope) {
250+ return;
251+ }
252+
253+ try {
254+ // Add context to scope if provided
255+ if (context) {
256+ scope.setExtras(context);
257+ }
258+ // Use scope's captureMessage to avoid global state
259+ scope.captureMessage(message, level);
260+ } catch (e) {
261+ console.error(`Failed to capture log to Sentry: ${e}`);
262+ }
263+}
added core/util/sentry/anonymization.test.ts +174 −0
@@ -0,0 +1,174 @@
1+import {
2+ anonymizeFilePath,
3+ anonymizeSentryEvent,
4+ anonymizeStackTrace,
5+ anonymizeUserInfo,
6+} from "./anonymization";
7+
8+describe("Sentry Anonymization Utilities", () => {
9+ describe("anonymizeFilePath", () => {
10+ it("should anonymize absolute paths but preserve node_modules package names", () => {
11+ expect(anonymizeFilePath("/Users/john/workspace/app.js")).toBe("<file>");
12+ expect(anonymizeFilePath("/home/user/project/file.py")).toBe("<file>");
13+ expect(anonymizeFilePath("C:\\Users\\john\\Documents\\code.go")).toBe(
14+ "<file>",
15+ );
16+ expect(anonymizeFilePath("/project/node_modules/react/index.js")).toBe(
17+ "node_modules/react/<file>",
18+ );
19+ });
20+
21+ it("should keep relative paths unchanged", () => {
22+ expect(anonymizeFilePath("src/app.js")).toBe("src/app.js");
23+ expect(anonymizeFilePath("./utils/helper.py")).toBe("./utils/helper.py");
24+ expect(anonymizeFilePath("package/main.go")).toBe("package/main.go");
25+ });
26+
27+ it("should handle empty or undefined paths", () => {
28+ expect(anonymizeFilePath("")).toBe("");
29+ expect(anonymizeFilePath(undefined as any)).toBe(undefined);
30+ expect(anonymizeFilePath(null as any)).toBe(null);
31+ });
32+ });
33+
34+ describe("anonymizeStackTrace", () => {
35+ it("should anonymize stack frame filenames", () => {
36+ const frames = [
37+ {
38+ filename: "/Users/john/project/app.js",
39+ abs_path: "/Users/john/project/app.js",
40+ function: "myFunction",
41+ lineno: 42,
42+ vars: { secret: "password123" },
43+ pre_context: ['const secret = "password123"'],
44+ post_context: ["console.log(secret)"],
45+ context_line: 'throw new Error("test")',
46+ },
47+ ];
48+
49+ const result = anonymizeStackTrace(frames);
50+
51+ expect(result[0].filename).toBe("<file>");
52+ expect(result[0].abs_path).toBe(""); // Always cleared like Rasa
53+ expect(result[0].vars).toBeUndefined();
54+ expect(result[0].pre_context).toBeUndefined();
55+ expect(result[0].post_context).toBeUndefined();
56+ expect(result[0].context_line).toBe("<code>");
57+ expect(result[0].function).toBe("myFunction"); // Preserve function name
58+ expect(result[0].lineno).toBe(42); // Preserve line number
59+ });
60+
61+ it("should handle non-array input", () => {
62+ expect(anonymizeStackTrace(null as any)).toBe(null);
63+ expect(anonymizeStackTrace(undefined as any)).toBe(undefined);
64+ expect(anonymizeStackTrace("not-array" as any)).toBe("not-array");
65+ });
66+ });
67+
68+ describe("anonymizeUserInfo", () => {
69+ it("should hash user ID and remove other info", () => {
70+ const user = {
71+ id: "real-machine-id-12345",
72+ username: "john.doe",
73+ email: "john@example.com",
74+ ip_address: "192.168.1.100",
75+ };
76+
77+ const result = anonymizeUserInfo(user);
78+
79+ expect(result.id).not.toBe("real-machine-id-12345");
80+ expect(result.id).toMatch(/^[a-f0-9]{8}$/); // 8-char hash
81+ expect(result.username).toBeUndefined();
82+ expect(result.email).toBeUndefined();
83+ expect(result.ip_address).toBeUndefined();
84+ });
85+
86+ it("should handle null/undefined user", () => {
87+ expect(anonymizeUserInfo(null)).toBe(null);
88+ expect(anonymizeUserInfo(undefined)).toBe(undefined);
89+ });
90+ });
91+
92+ describe("anonymizeSentryEvent (integration)", () => {
93+ it("should anonymize events with user file paths", () => {
94+ const event: any = {
95+ exception: {
96+ values: [
97+ {
98+ stacktrace: {
99+ frames: [
100+ {
101+ filename: "/Users/john/workspace/app.js",
102+ abs_path: "/Users/john/workspace/app.js",
103+ vars: { secret: "password" },
104+ context_line: 'throw new Error("test")',
105+ },
106+ ],
107+ },
108+ },
109+ ],
110+ },
111+ user: {
112+ id: "machine-id-12345",
113+ username: "john",
114+ },
115+ contexts: {
116+ os: {
117+ environment: { HOME: "/Users/john" },
118+ },
119+ },
120+ };
121+
122+ const result = anonymizeSentryEvent(event);
123+
124+ expect(result).not.toBeNull();
125+ expect(result.exception.values[0].stacktrace.frames[0].filename).toBe(
126+ "<file>",
127+ );
128+ expect(result.exception.values[0].stacktrace.frames[0].abs_path).toBe("");
129+ expect(
130+ result.exception.values[0].stacktrace.frames[0].vars,
131+ ).toBeUndefined();
132+ expect(result.exception.values[0].stacktrace.frames[0].context_line).toBe(
133+ "<code>",
134+ );
135+ expect(result.user.id).toMatch(/^[a-f0-9]{8}$/);
136+ expect(result.user.username).toBeUndefined();
137+ expect(result.contexts.os.environment).toBeUndefined();
138+ });
139+
140+ it("should handle malformed events gracefully", () => {
141+ const malformedEvent: any = {
142+ exception: {
143+ values: null,
144+ },
145+ user: null,
146+ breadcrumbs: "not-an-array",
147+ tags: null,
148+ extra: null,
149+ };
150+
151+ const result = anonymizeSentryEvent(malformedEvent);
152+ expect(result).not.toBeNull(); // Should not crash
153+ });
154+
155+ it("should return null on anonymization errors", () => {
156+ // Create a circular reference that would cause issues
157+ const circularEvent: any = {
158+ message: "Test event",
159+ };
160+ circularEvent.circular = circularEvent;
161+
162+ // Mock console.error to avoid noise in tests
163+ const originalConsoleError = console.error;
164+ console.error = jest.fn();
165+
166+ const result = anonymizeSentryEvent(circularEvent);
167+
168+ // Should handle gracefully without crashing
169+ expect(result).not.toBeNull(); // Our implementation might handle this
170+
171+ console.error = originalConsoleError;
172+ });
173+ });
174+});
added core/util/sentry/anonymization.ts +132 −0
@@ -0,0 +1,132 @@
1+import { ErrorEvent } from "@sentry/core";
2+/**
3+ * Minimalist Sentry anonymization utilities
4+ */
5+
6+// Browser-compatible hash function (avoids Node.js crypto dependency)
7+function simpleHash(input: string): string {
8+ let hash = 0;
9+ for (let i = 0; i < input.length; i++) {
10+ const char = input.charCodeAt(i);
11+ hash = (hash << 5) - hash + char;
12+ hash = hash & hash; // Convert to 32-bit integer
13+ }
14+ return Math.abs(hash).toString(16).substring(0, 8);
15+}
16+
17+/**
18+ * Anonymize file paths - keep package names, remove user paths
19+ */
20+export function anonymizeFilePath(filePath: string): string {
21+ if (!filePath) return filePath;
22+
23+ const normalized = filePath.replace(/\\/g, "/");
24+
25+ // Keep node_modules package names for debugging
26+ if (normalized.includes("node_modules")) {
27+ const match = normalized.match(/node_modules\/([^\/]+)/);
28+ if (match) {
29+ return `node_modules/${match[1]}/<file>`;
30+ }
31+ }
32+
33+ // Replace absolute paths with generic identifier
34+ if (normalized.startsWith("/") || normalized.match(/^[A-Za-z]:/)) {
35+ return "<file>";
36+ }
37+
38+ return normalized;
39+}
40+
41+/**
42+ * Clean stack trace frames - remove sensitive data but keep the event
43+ */
44+export function anonymizeStackTrace(frames: any[]): any[] {
45+ if (!Array.isArray(frames)) return frames;
46+
47+ return frames.map((frame) => ({
48+ ...frame,
49+ filename: frame.filename
50+ ? anonymizeFilePath(frame.filename)
51+ : frame.filename,
52+ abs_path: "",
53+ // Remove local variables and source code context
54+ vars: undefined,
55+ pre_context: undefined,
56+ post_context: undefined,
57+ context_line: frame.context_line ? "<code>" : frame.context_line,
58+ }));
59+}
60+
61+/**
62+ * Anonymize user information - hash ID, remove PII
63+ */
64+export function anonymizeUserInfo(user: any): any {
65+ if (!user) return user;
66+
67+ return {
68+ id: user.id ? simpleHash(String(user.id)) : user.id,
69+ username: undefined,
70+ email: undefined,
71+ ip_address: undefined,
72+ };
73+}
74+
75+/**
76+ * Main anonymization function - minimalist approach like Rasa
77+ */
78+export function anonymizeSentryEvent(event: ErrorEvent): any | null {
79+ try {
80+ // Deep copy to avoid mutating the original event
81+ const anonymized = structuredClone(event);
82+
83+ // Clean exception stack traces
84+ if (anonymized.exception?.values) {
85+ anonymized.exception.values = anonymized.exception.values.map(
86+ (exception: any) => ({
87+ ...exception,
88+ stacktrace: exception.stacktrace
89+ ? {
90+ ...exception.stacktrace,
91+ frames: exception.stacktrace.frames
92+ ? anonymizeStackTrace(exception.stacktrace.frames)
93+ : exception.stacktrace.frames,
94+ }
95+ : exception.stacktrace,
96+ }),
97+ );
98+ }
99+
100+ // Clean thread stack traces
101+ if (anonymized.threads?.values) {
102+ anonymized.threads.values = anonymized.threads.values.map(
103+ (thread: any) => ({
104+ ...thread,
105+ stacktrace: thread.stacktrace
106+ ? {
107+ ...thread.stacktrace,
108+ frames: thread.stacktrace.frames
109+ ? anonymizeStackTrace(thread.stacktrace.frames)
110+ : thread.stacktrace.frames,
111+ }
112+ : thread.stacktrace,
113+ }),
114+ );
115+ }
116+
117+ // Anonymize user info
118+ if (anonymized.user) {
119+ anonymized.user = anonymizeUserInfo(anonymized.user);
120+ }
121+
122+ // Remove OS environment variables
123+ if (anonymized.contexts?.os?.environment) {
124+ anonymized.contexts.os.environment = undefined;
125+ }
126+
127+ return anonymized;
128+ } catch (error) {
129+ console.error("Error anonymizing Sentry event:", error);
130+ return null; // Drop event if anonymization fails
131+ }
132+}
added core/util/sentry/constants.ts +5 −0
@@ -0,0 +1,5 @@
1+/**
2+ * Sentry configuration constants
3+ */
4+export const SENTRY_DSN =
5+ "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016";
modified core/util/text.ts +7 −0
@@ -44,3 +44,10 @@
4444 .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens
4545 .toLowerCase();
4646 }
47+
48+export function kebabOfThemeStr(str: string): string {
49+ return str
50+ .toLowerCase()
51+ .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens
52+ .replace(/\(|\)/g, ""); // remove parentheses
53+}
modified core/util/text.vitest.ts +58 −0
@@ -3,6 +3,7 @@
33 capitalizeFirstLetter,
44 escapeForSVG,
55 kebabOfStr,
6+ kebabOfThemeStr,
67 replaceEscapedCharacters,
78 } from "./text";
89
@@ -184,3 +185,60 @@
184185 expect(kebabOfStr("MiXeD cAsE")).toBe("mi-xe-d-c-as-e");
185186 });
186187 });
188+
189+describe("kebabOfThemeStr", () => {
190+ it("should convert spaces to hyphens", () => {
191+ expect(kebabOfThemeStr("hello world")).toBe("hello-world");
192+ expect(kebabOfThemeStr("multiple spaces")).toBe("multiple-spaces");
193+ });
194+
195+ it("should convert underscores to hyphens", () => {
196+ expect(kebabOfThemeStr("snake_case")).toBe("snake-case");
197+ expect(kebabOfThemeStr("multiple___underscores")).toBe(
198+ "multiple-underscores",
199+ );
200+ });
201+
202+ it("should convert mixed spaces and underscores", () => {
203+ expect(kebabOfThemeStr("mixed_ case")).toBe("mixed-case");
204+ expect(kebabOfThemeStr("theme name_variant")).toBe("theme-name-variant");
205+ });
206+
207+ it("should convert to lowercase", () => {
208+ expect(kebabOfThemeStr("UPPERCASE")).toBe("uppercase");
209+ expect(kebabOfThemeStr("MiXeD CaSe")).toBe("mixed-case");
210+ });
211+
212+ it("should handle already kebab-case strings", () => {
213+ expect(kebabOfThemeStr("already-kebab")).toBe("already-kebab");
214+ });
215+
216+ it("should handle empty strings", () => {
217+ expect(kebabOfThemeStr("")).toBe("");
218+ });
219+
220+ it("should handle single characters", () => {
221+ expect(kebabOfThemeStr("A")).toBe("a");
222+ expect(kebabOfThemeStr("a")).toBe("a");
223+ });
224+
225+ it("should preserve other special characters", () => {
226+ expect(kebabOfThemeStr("hello@world")).toBe("hello@world");
227+ expect(kebabOfThemeStr("test.file.name")).toBe("test.file.name");
228+ });
229+
230+ it("should not convert camelCase (unlike kebabOfStr)", () => {
231+ expect(kebabOfThemeStr("camelCase")).toBe("camelcase");
232+ expect(kebabOfThemeStr("PascalCase")).toBe("pascalcase");
233+ });
234+
235+ it("should handle strings with numbers", () => {
236+ expect(kebabOfThemeStr("theme_v2 beta")).toBe("theme-v2-beta");
237+ expect(kebabOfThemeStr("version_123_FINAL")).toBe("version-123-final");
238+ });
239+
240+ it("should handle strings with parentheses", () => {
241+ expect(kebabOfThemeStr("theme_v2 (beta)")).toBe("theme-v2-beta");
242+ expect(kebabOfThemeStr("Gruvbox Dark (Hard)")).toBe("gruvbox-dark-hard");
243+ });
244+});
modified docs/README.md +1 −1
@@ -1,4 +1,4 @@
1-# Mintlify Starter Kit
1+## Mintlify Starter Kit
22
33 Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including
44
modified docs/autocomplete/how-to-use-it.mdx +3 −2
@@ -1,14 +1,15 @@
11 ---
22 title: "Autocomplete"
3-sidebarTitle: "How To Use It"
3+sidebarTitle: "How To Use AI Autocomplete"
44 icon: "circle-question"
5+description: "Learn how to use Continue's AI-powered code autocomplete feature with keyboard shortcuts for accepting, rejecting, or partially accepting inline suggestions as you type"
56 ---
67
78 <Frame>
89 <img src="/images/autocomplete-9d4e3f7658d3e65b8e8b20f2de939675.gif" />
910 </Frame>
1011
11-## How to use it
12+## How to Use AI Code Autocomplete in Continue
1213
1314 Autocomplete provides inline code suggestions as you type. To enable it, simply click the "Continue" button in the status bar at the bottom right of your IDE or ensure the "Enable Tab Autocomplete" option is checked in your IDE settings.
1415
modified docs/chat/how-to-use-it.mdx +11 −10
@@ -1,39 +1,40 @@
11 ---
22 title: "Chat"
3-sidebarTitle: "How To Use It"
3+sidebarTitle: "How To Use AI Chat"
44 icon: "circle-question"
5+description: "Learn how to use Continue's AI chat assistant to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
56 ---
67
78 <Frame>
89 <img src="/images/chat-489b68d156be2aafe09ee7cedf233fba.gif" />
910 </Frame>
1011
11-## How to use it
12+## How to Use AI Chat in Continue for Coding Help
1213
1314 Chat makes it easy to ask for help from an LLM without needing to leave the IDE. You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you what you want, then you can send follow up messages to clarify and adjust its approach until the task is completed.
1415
1516 Chat is best used to understand and iterate on code or as a replacement for search engine queries.
1617
17-## Type a request and press enter
18+## Send a Coding Question or Task to AI Chat
1819
19-You send it a question, and it replies with an answer. You tell it to solve a problem, and it provides you a solution. You ask for some code, and it generates it.
20+To send a question, add it to the input box in the extention and press enter. You send it a question, and it replies with an answer. You tell it to solve a problem, and it provides you a solution. You ask for some code, and it generates it.
2021
21-## Highlight a code section to include as context
22+## Add Code Context to AI Chat by Highlighting Code
2223
2324 You select a code section with your mouse, press `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way.
2425
25-## Reference context with the @ symbol
26+## Use @ to Include Project Context in AI Chat Responses
2627
27-If there is information from the codebase, documentation, IDE, or other tools that you want to include as context, you can type @ to select and include it as context. You can learn more about how to use this in [Chat context selection](/features/chat/quick-start#3-use--for-additional-context).
28+If there is information from the codebase, documentation, IDE, or other tools that you want to include as context, you can type @ to select and include it as context. You can learn more about how to use this in [Chat context selection](/features/chat/quick-start#how-to-use-%40-for-additional-context).
2829
29-## Apply generated code to your file
30+## Insert AI-Generated Code Changes Directly into Your File
3031
3132 When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes.
3233
33-## Start a fresh session for a new task
34+## How to Begin a New AI Chat Session for a Different Coding Task
3435
3536 Once you complete a task and want to start a new one, press `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM.
3637
37-## Switch between different models
38+## Change AI Models in Continue Chat for Different Coding Needs
3839
3940 If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl` + `’`
modified docs/customization/mcp-tools.mdx +6 −2
@@ -1,8 +1,12 @@
11 ---
22 title: "MCP Blocks"
3-description: "Model Context Protocol servers provide specialized functionality:"
3+description: "Learn how to use Model Context Protocol (MCP) blocks in Continue to integrate external tools, connect databases, and extend your development environment."
44 ---
55
6+Model Context Protocol (MCP) blocks let Continue connect to external tools, systems, and databases by running MCP servers.
7+
8+These blocks make it possible to:
9+
610 - **Enable integration** with external tools and systems
711 - **Create extensible interfaces** for custom capabilities
812 - **Support complex interactions** with your development environment
@@ -11,6 +15,6 @@
1115
1216 ![MCP Blocks Overview](/images/customization/images/mcp-blocks-overview-c9a104f9b586779c156f9cf34da197c2.png)
1317
14-## Learn More
18+## Learn More About MCP Blocks
1519
1620 Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
modified docs/customization/models.mdx +2 −2
@@ -12,8 +12,8 @@
1212
1313 ![Model Blocks Overview](/images/customization/images/model-blocks-overview-36c30e7e01928d7a9b5b26ff1639c34b.png)
1414
15-## Learn More
15+## Learn More About Model Blocks
1616
17-Continue supports [many model providers](/customization/models#openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
17+Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
1818
1919 Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference.
modified docs/customization/overview.mdx +26 −8
@@ -1,21 +1,39 @@
11 ---
2-title: "Overview"
3-description: "Continue can be deeply customized. For example you might:"
2+title: "Customization Overview"
3+description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding assistant"
44 ---
55
6-- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers/top-level/openai).
7-- **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](/customize/model-roles).
8-- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/custom-providers).
9-- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands).
10-- **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools)
6+Continue can be deeply customized to fit your specific development workflow and preferences. This guide covers the main ways you can customize Continue to enhance your coding experience.
7+
8+## Change Your Model Provider
9+
10+Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers/top-level/openai).
11+
12+## Select Different Models for Specific Tasks
13+
14+Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](/customize/model-roles).
15+
16+## Add a Context Provider
17+
18+Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/custom-providers).
19+
20+## Create a Slash Command
21+
22+Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands).
23+
24+## Call External Tools and Functions
25+
26+Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools)
1127
1228 Whatever you choose, you'll probably start by editing your Assistant.
1329
14-## Editing your assistant
30+## Edit Your Assistant
1531
1632 You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
1733
1834 ![configure an assistant](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png)
1935
36+## Manage Your Assistant
37+
2038 - See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant
2139 - See the [Config Deep Dive](/reference) for more details on configuring local assistants.
modified docs/customization/rules.mdx +1 −1
@@ -11,7 +11,7 @@
1111
1212 By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints.
1313
14-### How Rules Work
14+## How Rules Work
1515
1616 Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
1717
modified docs/customize/context/codebase.mdx +19 −12
@@ -1,7 +1,8 @@
11 ---
2-title: "@Codebase"
3-description: Talk to your codebase
2+title: "How to Set Up @Codebase Context Provider in Continue"
3+description: Retrieve relevant context and answers from your codebase using embeddings and keyword search.
44 keywords: [talk, embeddings, reranker, codebase, experimental]
5+sidebarTitle: "@Codebase"
56 ---
67
78 Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`.
@@ -9,35 +10,41 @@
910 <Info>
1011 **Note:** `transformers.js` cannot be used in JetBrains IDEs. However, you can
1112 select a different embeddings model from [the list
12- here](../model-roles/embeddings.mdx).
13+ here](../model-roles/embeddings).
1314 </Info>
1415
16+## How to Use @Codebase and @Folder Context Providers
17+
1518 Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
1619
20+### When @Codebase Context Provider Is Useful
21+
1722 Here are some common use cases where it can be useful:
1823
19-- Asking high-level questions about your codebase
24+- **Asking high-level questions about your codebase**
2025 - "How do I add a new endpoint to the server?"
2126 - "Do we use VS Code's CodeLens feature anywhere?"
2227 - "Is there any code written already to convert HTML to markdown?"
23-- Generate code using existing samples as reference
28+- **Generate code using existing samples as reference**
2429 - "Generate a new React component with a date picker, using the same patterns as existing components"
2530 - "Write a draft of a CLI application for this project using Python's argparse"
2631 - "Implement the `foo` method in the `bar` class, following the patterns seen in other subclasses of `baz`.
27-- Use `@Folder` to ask questions about a specific folder, increasing the likelihood of relevant results
32+- **Use `@Folder` to ask questions about a specific folder, increasing the likelihood of relevant results**
2833 - "What is the main purpose of this folder?"
2934 - "How do we use VS Code's CodeLens API?"
3035 - Or any of the above examples, but with `@Folder` instead of `@Codebase`
3136
37+### When @Codebase Context Provider Is Not Useful
38+
3239 Here are use cases where it is not useful:
3340
34-- When you need the LLM to see _literally every_ file in your codebase
41+- **When you need the LLM to see _literally every_ file in your codebase**
3542 - "Find everywhere where the `foo` function is called"
3643 - "Review our codebase and find any spelling mistakes"
37-- Refactoring
44+- **Refactoring tasks**
3845 - "Add a new parameter to the `bar` function and update usages"
3946
40-## Configuration
47+## How to Configure @Codebase Context Provider Settings
4148
4249 There are a few options that let you configure the behavior of the `@codebase` context provider, which are the same for the `@folder` context provider:
4350
@@ -82,7 +89,7 @@
8289
8390 Whether to use re-ranking, which will allow initial selection of `nRetrieve` results, then will use an LLM to select the top `nFinal` results (default: true)
8491
85-## Ignore files during indexing
92+## How to Ignore Files During Indexing
8693
8794 Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`.
8895
@@ -92,6 +99,6 @@
9299
93100 If you need to force a refresh of the index, reload the VS Code window with <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>p</kbd> + "Reload Window".
94101
95-## Repository map
102+## How Repository Map Enhances Codebase Understanding
96103
97-Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
104+Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](/customize/context/codebase#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
modified docs/customize/context/documentation.mdx +25 −21
@@ -1,5 +1,5 @@
11 ---
2-title: "@Docs"
2+title: "How to Set Up @Docs Context Provider in Continue"
33 description: Learn how to access and search your project's documentation directly within Continue
44 keywords:
55 [
@@ -13,11 +13,12 @@
1313 documentation,
1414 ]
1515 toc_max_heading_level: 5
16+sidebarTitle: "@Docs"
1617 ---
1718
18-The [`@Docs` context provider](../custom-providers#docs) allows you to efficiently reference documentation directly within Continue.
19+The `@Docs` context provider allows you to efficiently reference documentation directly within Continue.
1920
20-## Enabling the `@Docs` context provider
21+## How to Enable the @Docs Context Provider
2122
2223 To enable the `@Docs` context provider, add it to the list of context providers in your `config.json` file.
2324
@@ -41,7 +42,7 @@
4142 </Tab>
4243 </Tabs>
4344
44-## How It Works
45+## How the @Docs Context Provider Works
4546
4647 The `@Docs` context provider works by
4748
@@ -50,13 +51,13 @@
5051 3. Storing the embeddings locally on your machine
5152 4. Embedding chat input to include similar documentation chunks as context
5253
53-## Indexing Your Own Documentation
54+## How to Index Your Own Documentation
5455
55-### Hub `docs` Blocks
56+### Using Hub `docs` Blocks
5657
5758 @Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
5859
59-### Through the `@Docs` Context Provider
60+### How to Add Documentation Through the @Docs Context Provider
6061
6162 To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed
6263
@@ -79,7 +80,7 @@
7980
8081 ![Add documentation form](/images/docs-form.png)
8182
82-### In a configuration file
83+### How to Add Documentation in Configuration Files
8384
8485 For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows:
8586
@@ -111,13 +112,13 @@
111112
112113 Indexing will re-sync upon saving the configuration file.
113114
114-## Configuration
115+## How to Configure @Docs Advanced Settings
115116
116-### Using Your Embeddings Provider
117+### How to Use Your Custom Embeddings Provider
117118
118119 If you have set up an [embeddings provider](../model-roles/embeddings.mdx), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration.
119120
120-### Reranking
121+### How to Configure Reranking for Better Results
121122
122123 As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`.
123124
@@ -150,7 +151,7 @@
150151 </Tab>
151152 </Tabs>
152153
153-### GitHub
154+### How to Set Up GitHub Token for GitHub Documentation
154155
155156 The GitHub API rate limits public requests to 60 per hour. If you want to reliably index GitHub repos, you can add a github token to your config file:
156157
@@ -179,7 +180,7 @@
179180 </Tab>
180181 </Tabs>
181182
182-### Local Crawling
183+### How to Enable Local Crawling for Private Documentation
183184
184185 By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites.
185186
@@ -212,9 +213,12 @@
212213 </Tabs>
213214
214215 <Info>
215- The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler.
216-
217- **Note:** Chromium crawling support is being deprecated and may be removed in future versions.
216+ The default local crawler is a lightweight tool that cannot render sites that
217+ are dynamically generated using JavaScript. If your sites need to be rendered,
218+ you can enable the experimental `Use Chromium for Docs Crawling` feature from
219+ your [User Settings Page](../settings) This will download and install Chromium
220+ to `~/.continue/.utils`, and use it as the local crawler. **Note:** Chromium
221+ crawling support is being deprecated and may be removed in future versions.
218222 </Info>
219223
220224 Further notes:
@@ -222,7 +226,7 @@
222226 - If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential.
223227 - For GitHub Repos this has no effect because only the GitHub Crawler will be used, and if the repo is private it can only be accessed with a priveleged GitHub token anyways.
224228
225-## Managing your docs indexes
229+## How to Manage Your Documentation Indexes
226230
227231 You can view indexing statuses and manage your documentation sites from the `@docs indexes` section of the `More` page (three dots)
228232
@@ -239,9 +243,9 @@
239243
240244 You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`.
241245
242-## Examples
246+## Configuration Examples for Different Setups
243247
244-### VS Code minimal setup
248+### How to Set Up @Docs in VS Code (Minimal Configuration)
245249
246250 The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking.
247251
@@ -275,7 +279,7 @@
275279 </Tab>
276280 </Tabs>
277281
278-### Jetbrains minimal setup
282+### How to Set Up @Docs in JetBrains IDEs (Minimal Configuration)
279283
280284 Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx).
281285
@@ -318,7 +322,7 @@
318322 </Tab>
319323 </Tabs>
320324
321-### Full-power setup (VS Code or Jetbrains)
325+### How to Set Up @Docs with Advanced Features (VS Code or JetBrains)
322326
323327 The following configuration example includes:
324328
modified docs/customize/custom-providers.mdx +36 −36
@@ -7,7 +7,7 @@
77
88 ![Context Items](/images/customize/images/context-provider-example-0c96ff77286fa970b23dddfdc1fa986a.png)
99
10-## Context blocks
10+## How Do Context Blocks Work?
1111
1212 You can add context providers to assistants using [`context` blocks](/hub/blocks/block-types#context). Explore available context blocks in [the hub](https://hub.continue.dev/explore/context).
1313
@@ -15,7 +15,7 @@
1515
1616 You can add any built-in context-providers in your config file as shown below:
1717
18-### `@File`
18+### @File Context Provider – Reference Files in Your Workspace
1919
2020 Reference any file in your current workspace.
2121
@@ -34,7 +34,7 @@
3434 { "contextProviders": [{ "name": "file" }] }
3535 ```
3636
37-### `@Code`
37+### @Code Context Provider – Reference Functions and Classes
3838
3939 Reference specific functions or classes from throughout your project.
4040
@@ -53,7 +53,7 @@
5353 { "contextProviders": [{ "name": "code" }] }
5454 ```
5555
56-### `@Git Diff`
56+### @Git Diff Context Provider – Reference Branch Changes
5757
5858 Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
5959
@@ -72,7 +72,7 @@
7272 { "contextProviders": [{ "name": "diff" }] }
7373 ```
7474
75-### `@Current File`
75+### @Current File Context Provider – Reference the Active File
7676
7777 Reference the currently open file.
7878
@@ -91,7 +91,7 @@
9191 { "contextProviders": [{ "name": "currentFile" }] }
9292 ```
9393
94-### `@Terminal`
94+### @Terminal Context Provider – Reference Last Terminal Command and Output
9595
9696 Reference the last command you ran in your IDE's terminal and its output.
9797
@@ -110,7 +110,7 @@
110110 { "contextProviders": [{ "name": "terminal" }] }
111111 ```
112112
113-### `@Docs`
113+### @Docs Context Provider – Reference Documentation Site Content
114114
115115 Reference the contents from any documentation site.
116116
@@ -131,9 +131,9 @@
131131
132132 Note that this will only enable the `@Docs` context provider.
133133
134-To use it, you need to add a documentation site to your config file. See the [docs](/customization/overview#documentation-context) page for more information.
134+To use it, you need to add a documentation site to your config file. See the [docs](/customize/overview#documentation-context) page for more information.
135135
136-### `@Open`
136+### @Open Context Provider – Reference All Open Files or Pinned Files
137137
138138 Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
139139
@@ -155,7 +155,7 @@
155155 { "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] }
156156 ```
157157
158-### `@Web`
158+### @Web Context Provider – Reference Relevant Web Pages
159159
160160 Reference relevant pages from across the web, automatically determined from your input.
161161
@@ -179,7 +179,7 @@
179179 { "contextProviders": [{ "name": "web", "params": { "n": 5 } }] }
180180 ```
181181
182-### `@Codebase`
182+### @Codebase Context Provider – Reference Relevant Codebase Snippets
183183
184184 Reference the most relevant snippets from your codebase.
185185
@@ -199,9 +199,9 @@
199199 { "contextProviders": [{ "name": "codebase" }] }
200200 ```
201201
202-Read more about indexing and retrieval [here](/customization/overview#codebase-context).
202+Read more about indexing and retrieval [here](/customize/overview#codebase-context).
203203
204-### `@Folder`
204+### @Folder Context Provider – Reference Code from a Specific Folder
205205
206206 Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
207207
@@ -220,7 +220,7 @@
220220 { "contextProviders": [{ "name": "folder" }] }
221221 ```
222222
223-### `@Search`
223+### @Search Context Provider – Reference Code Search Results
224224
225225 Reference the results of codebase search, just like the results you would get from VS Code search.
226226
@@ -244,7 +244,7 @@
244244
245245 This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
246246
247-### `@Url`
247+### @Url Context Provider – Reference Content from a URL
248248
249249 Reference the markdown converted contents of a given URL.
250250
@@ -264,7 +264,7 @@
264264 { "contextProviders": [{ "name": "url" }] }
265265 ```
266266
267-### `@Clipboard`
267+### @Clipboard Context Provider – Reference Clipboard Items
268268
269269 Reference recent clipboard items
270270
@@ -284,7 +284,7 @@
284284 { "contextProviders": [{ "name": "clipboard" }] }
285285 ```
286286
287-### `@Tree`
287+### @Tree Context Provider – Reference Workspace File Structure
288288
289289 Reference the structure of your current workspace.
290290
@@ -304,7 +304,7 @@
304304 { "contextProviders": [{ "name": "tree" }] }
305305 ```
306306
307-### `@Problems`
307+### @Problems Context Provider – Reference Problems in the Current File
308308
309309 Get Problems from the current file.
310310
@@ -324,7 +324,7 @@
324324 { "contextProviders": [{ "name": "problems" }] }
325325 ```
326326
327-### `@Debugger`
327+### @Debugger Context Provider – Reference Debugger Local Variables
328328
329329 Reference the contents of the local variables in the debugger. Currently only available in VS Code.
330330
@@ -348,7 +348,7 @@
348348
349349 Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
350350
351-### `@Repository Map`
351+### @Repository Map Context Provider – Reference Codebase Outline and Signatures
352352
353353 Reference the outline of your codebase. By default, signatures are included along with file in the repo map.
354354
@@ -374,11 +374,11 @@
374374
375375 Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
376376
377-In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
377+In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repository map from.
378378
379-This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
379+This context provider is inspired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
380380
381-### `@Operating System`
381+### @Operating System Context Provider – Reference System Architecture and Platform
382382
383383 Reference the architecture and platform of your current operating system.
384384
@@ -398,7 +398,7 @@
398398 { "contextProviders": [{ "name": "os" }] }
399399 ```
400400
401-### Model Context Protocol
401+### Using the Model Context Protocol (MCP) in Continue
402402
403403 The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
404404
@@ -437,7 +437,7 @@
437437
438438 You'll then be able to type "@" and see "MCP" in the context providers dropdown.
439439
440-### `@Issue`
440+### @Issue Context Provider – Reference GitHub Issue Conversations
441441
442442 Reference the conversation in a GitHub issue.
443443
@@ -474,7 +474,7 @@
474474
475475 Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
476476
477-### `@Database`
477+### @Database Context Provider – Reference Database Table Schemas
478478
479479 Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
480480
@@ -559,7 +559,7 @@
559559 - `mysql`
560560 - `sqlite`
561561
562-### `@Google`
562+### @Google Context Provider – Reference Google Search Results
563563
564564 Reference the results of a Google search.
565565
@@ -592,7 +592,7 @@
592592
593593 Note: You can get an API key for free at [serper.dev](https://serper.dev).
594594
595-### `@Gitlab Merge Request`
595+### @Gitlab Merge Request Context Provider – Reference GitLab Merge Requests
596596
597597 Reference an open MR for this branch on GitLab.
598598
@@ -616,7 +616,7 @@
616616
617617 You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope.
618618
619-#### Using Self-Hosted GitLab
619+#### How to Use Self-Hosted GitLab
620620
621621 You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`.
622622
@@ -646,11 +646,11 @@
646646 }
647647 ```
648648
649-#### Filtering Comments
649+#### How to Provide Context by Filtering Comments
650650
651651 If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`.
652652
653-### `@Jira`
653+### @Jira Context Provider – Reference Jira Issues
654654
655655 Reference the conversation in a Jira issue.
656656
@@ -718,7 +718,7 @@
718718
719719 You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
720720
721-### `@Discord`
721+### @Discord Context Provider – Reference Messages in Discord Channels
722722
723723 Reference the messages in a Discord channel.
724724
@@ -762,7 +762,7 @@
762762
763763 Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
764764
765-### `@HTTP`
765+### @HTTP Context Provider – Reference Data from an HTTP Request
766766
767767 The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
768768
@@ -804,7 +804,7 @@
804804 [ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""}
805805 ```
806806
807-### `@Commits`
807+### @Commits Context Provider – Reference Git Commit Metadata and Diffs
808808
809809 Reference specific git commit metadata and diff or all of the recent commits.
810810
@@ -833,7 +833,7 @@
833833
834834 The depth is how many commits will be loaded into the submenu, defaults to 50. The LastXCommitsDepth is how many recent commits will be included, defaults to 10.
835835
836-### `@Greptile`
836+### @Greptile Context Provider – Query Greptile Index of Repo/Branch
837837
838838 Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
839839
@@ -863,6 +863,6 @@
863863 }
864864 ```
865865
866-### Requesting Context Providers
866+### How to Request a New Context Provider in Continue
867867
868868 Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.
modified docs/customize/deep-dives/autocomplete.mdx +34 −28
@@ -1,10 +1,11 @@
11 ---
2-title: "Autocomplete"
3-description: "Deep dive into Continue's autocomplete functionality and configuration"
2+title: "Continue Autocomplete Setup and Configuration Guide"
3+description: "Step-by-step guide to setting up and configuring autocomplete in Continue, including Codestral, Ollama, and IDE settings."
44 keywords: [autocomplete]
5+sidebarTitle: Autocomplete
56 ---
67
7-### Setting up with Codestral (recommended)
8+## How to Set Up Autocomplete in Continue with Codestral (Recommended)
89
910 If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your config:
1011
@@ -45,7 +46,7 @@
4546 "https://api.mistral.ai/v1"` in your `tabAutocompleteModel`.
4647 </Tip>
4748
48-### Setting up with Ollama (default)
49+## How to Set Up Autocomplete in Continue with Ollama (Local Model)
4950
5051 If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
5152
@@ -84,37 +85,42 @@
8485
8586 Once the model has been downloaded, you should begin to see completions in VS Code.
8687
87-NOTE: Typically, thinking-type models are not recommended as they generate more slowly and are not suitable for scenarios that require speed.
88+<Note>
89+ Typically, thinking-type models are not recommended as they generate more
90+ slowly and are not suitable for scenarios that require speed.
91+</Note>
8892
8993 However, if you use any thinking-switchable models, you can configure these models for autocomplete functions by turning off the thinking mode.
9094
9195 For example:
9296
9397 <Tabs>
94- <Tab title="YAML">
98+<Tab title="YAML">
99+
95100 ```yaml title="config.yaml"
96- models:
97- - name: Qwen3 without Thinking for Autocomplete
98- provider: ollama
99- model: qwen3:4b # qwen3 is a thinking-switchable model
100- roles:
101- - autocomplete
102- requestOptions:
103- extraBodyProperties:
104- think: false # turning off the thinking
105- ```
106- </Tab>
101+models:
102+ - name: Qwen3 without Thinking for Autocomplete
103+ provider: ollama
104+ model: qwen3:4b # qwen3 is a thinking-switchable model
105+ roles:
106+ - autocomplete
107+ requestOptions:
108+ extraBodyProperties:
109+ think: false # turning off the thinking
110+```
111+
112+</Tab>
107113 </Tabs>
108114
109115 Then, in the continue panel, select this model as the default model for autocomplete.
110116
111-## Configuration Options
117+## Autocomplete Configuration Options in Continue
112118
113-### Hub Autocomplete models
119+### Autocomplete Models Available on the Continue Hub
114120
115121 Explore autocomplete model configurations on [the hub](https://hub.continue.dev/explore/models?roles=autocomplete)
116122
117-### Autocomplete User Settings
123+### Customize Autocomplete User Settings in the Continue Extension
118124
119125 {/* - `Use autocomplete cache`: If on, caches completions */}
120126 The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md):
@@ -122,7 +128,7 @@
122128 - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
123129 - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"
124130
125-### Autocomplete Configuration
131+### How to Configure Autocomplete with `config.json` (Deprecated Format)
126132
127133 #### YAML Configuration
128134
@@ -149,13 +155,13 @@
149155
150156 The `config.json` configuration format offers configuration options through `tabAutocompleteOptions`. See the [JSON Reference](/reference/json-reference#tabautocomplete-options) for more details.
151157
152-## FAQs
158+## Autocomplete FAQs and Troubleshooting in Continue
153159
154160 ### I want better completions, should I use GPT-4?
155161
156162 Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templating/AutocompleteTemplate.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
157163
158-### I'm not seeing any completions
164+### Autocomplete Not Working – How to Fix It
159165
160166 Follow these steps to ensure that everything is set up correctly:
161167
@@ -167,13 +173,13 @@
167173 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> then search for this and check the box)
168174 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
169175
170-### Completions are only ever single-line
176+### Why Are My Completions Only Single-Line?
171177
172178 To ensure that you receive multi-line completions, you can set `"multilineCompletions": "always"` in `tabAutocompleteOptions`. By default, it is `"auto"`. If you still find that you are only seeing single-line completions, this may be because some models tend to produce shorter completions when starting in the middle of a file. You can try temporarily moving text below your cursor out of your active file, or switching to a larger model.
173179
174-### Can I configure a "trigger key" for autocomplete?
180+### How to Set a Trigger Key for Autocomplete Suggestions
175181
176-Yes, in VS Code, if you don't want to be shown suggestions automatically you can:
182+In VS Code, if you don't want to be shown suggestions automatically you can:
177183
178184 1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions
179185 2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger`
@@ -181,7 +187,7 @@
181187 4. Press the key combination you want to use to trigger suggestions (e.g. <kbd>cmd/ctrl</kbd> + <kbd>space</kbd>)
182188 5. Now whenever you want to see a suggestion, you can press your key binding (e.g. <kbd>cmd/ctrl</kbd> + <kbd>space</kbd>) to trigger suggestions manually
183189
184-### Is there a shortcut to accept one line at a time?
190+### Shortcut for Accepting One Line at a Time in Autocomplete
185191
186192 This is a built-in feature of VS Code, but it's just a bit hidden. Follow these settings to reassign the keyboard shortcuts in VS Code:
187193
@@ -192,7 +198,7 @@
192198 This will make multi-line completion (including continue and from VS Code built-in or other plugin snippets) still work, and you will see multi-line completion. However, Tab will only fill in one line at a time. Any unnecessary code can be canceled with <kbd>Esc</kbd>.
193199 If you need to apply all the code, just press <kbd>Tab</kbd> multiple times.
194200
195-### How to turn off autocomplete
201+### How to Turn Off Autocomplete in Continue (VS Code and JetBrains)
196202
197203 #### VS Code
198204
modified docs/customize/deep-dives/configuration.mdx +10 −9
@@ -1,18 +1,19 @@
11 ---
2-title: "Configuration"
2+title: "How to Configure Continue Assistants"
33 description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files
44 keywords: [config, settings, customize]
5+sidebarTitle: "Assistant Configuration"
56 ---
67
78 You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
89
910 ![configure an assistant](/images/configure-continue.png)
1011
11-## Hub Assistants
12+## How to Manage Hub Assistants
1213
1314 Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md)
1415
15-## YAML Config
16+## How to Configure Local Assistants with YAML
1617
1718 Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
1819
@@ -27,19 +28,19 @@
2728
2829 See the full reference for `config.yaml` [here](/reference).
2930
30-## Deprecated configuration methods
31+## Legacy Configuration Methods (Deprecated)
3132
3233 <Info>
33- View the `config.json` migration guide [here](../yaml-migration.mdx)
34+ View the `config.json` migration guide [here](../yaml-migration)
3435 </Info>
3536
3637 - [`config.json`](/reference) - The original configuration format which is stored in a file at the same location as `config.yaml`
37-- [`.continuerc.json`](#continuercjson) - Workspace-level configuration
38-- [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema:
38+- [`.continuerc.json`](#how-to-use-continuercjson-for-workspace-configuration) - Workspace-level configuration
39+- [`config.ts`](#how-to-use-configts-for-advanced-configuration) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema:
3940 - `~/.continue/config.ts` (MacOS / Linux)
4041 - `%USERPROFILE%\.continue\config.ts` (Windows)
4142
42-### `.continuerc.json`
43+### How to Use `.continuerc.json` for Workspace Configuration
4344
4445 The format of `.continuerc.json` is the same as `config.json`, plus one _additional_ property `mergeBehavior`, which can be set to either "merge" or "overwrite". If set to "merge" (the default), `.continuerc.json` will be applied on top of `config.json` (arrays and objects are merged). If set to "overwrite", then every top-level property of `.continuerc.json` will overwrite that property from `config.json`.
4546
@@ -54,7 +55,7 @@
5455 }
5556 ```
5657
57-### `config.ts`
58+### How to Use `config.ts` for Advanced Configuration
5859
5960 `config.yaml` or `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically extend Continue configuration, you can use a `config.ts` file, placed at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows).
6061
modified docs/customize/deep-dives/development-data.mdx +3 −2
@@ -1,14 +1,15 @@
11 ---
2-title: Development Data
2+title: "How to Collect and Manage Development Data in Continue"
33 description: Collecting data on how you build software
44 keywords: [development data, dev data, LLM-aided development]
5+sidebarTitle: "Development Data"
56 ---
67
78 When you use Continue, you automatically collect data on how you build software. By default, this development data is saved to `.continue/dev_data` on your local machine.
89
910 You can read more about how development data is generated as a byproduct of LLM-aided development and why we believe that you should start collecting it now: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software)
1011
11-## Custom Data Destinations
12+## How to Configure Custom Data Destinations
1213
1314 You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories.
1415
modified docs/customize/deep-dives/mcp.mdx +12 −11
@@ -1,7 +1,8 @@
11 ---
2-title: MCP
2+title: "How to Set Up Model Context Protocol (MCP) in Continue"
33 description: MCP use and customization
44 keywords: [tool, use, function calling, claude, automatic]
5+sidebarTitle: "Model Context Protocol (MCP)"
56 ---
67
78 As AI systems get better, they're still held back by their training data and
@@ -13,7 +14,7 @@
1314 prompts, context, and tool use, is key for building truly useful AI experiences
1415 that can be set up with custom tools.
1516
16-## How it works
17+## How MCP Works in Continue
1718
1819 Currently custom tools can be configured using the Model Context
1920 Protocol standard to unify prompts, context, and tool use.
@@ -24,7 +25,7 @@
2425
2526 <Info>MCP can only be used in the **agent** mode.</Info>
2627
27-## Quick Start
28+## Quick Start: How to Set Up Your First MCP Server
2829
2930 Below is a quick example of setting up a new MCP server for use in your assistant:
3031
@@ -53,13 +54,13 @@
5354
5455 ![playwright mcp](/images/mcp-playwright.png)
5556
56-## Continue Documentation Search
57+## How to Set Up Continue Documentation Search with MCP
5758
5859 You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features.
5960
6061 For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp).
6162
62-## Using MCP Servers
63+## How to Configure MCP Servers
6364
6465 To set up your own MCP server, read the [MCP
6566 quickstart](https://modelcontextprotocol.io/quickstart) and then [create an
@@ -100,7 +101,7 @@
100101 </Tab>
101102 </Tabs>
102103
103-### Syntax
104+### How to Configure MCP Server Properties
104105
105106 MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers.
106107
@@ -110,11 +111,11 @@
110111 - `args`: Arguments to pass to the command.
111112 - `env`: Secrets to be injected into the command as environment variables.
112113
113-### Transport Types
114+### How to Choose MCP Transport Types
114115
115116 MCP now supports remote server connections through HTTP-based transports, expanding beyond the traditional local stdio transport method. This enables integration with cloud-hosted MCP servers and distributed architectures.
116117
117-#### Server-Sent Events Transport (`sse`)
118+#### How to Use Server-Sent Events Transport (`sse`)
118119
119120 For real-time streaming communication, use the SSE transport:
120121
@@ -125,7 +126,7 @@
125126 url: https://....
126127 ```
127128
128-#### Standard Input/Output (`stdio`)
129+#### How to Use Standard Input/Output (`stdio`)
129130
130131 For local MCP servers that communicate via standard input and output:
131132
@@ -139,7 +140,7 @@
139140 - "/path/to/your/database.db"
140141 ```
141142
142-#### Streamable HTTP Transport (`streamable-http`)
143+#### How to Use Streamable HTTP Transport
143144
144145 For standard HTTP-based communication with streaming capabilities:
145146
@@ -154,7 +155,7 @@
154155
155156 For detailed information about transport mechanisms and their use cases, refer to the official MCP documentation on [transports](https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse).
156157
157-### Working with Secrets
158+### How to Work with Secrets in MCP Servers
158159
159160 With some MCP servers you will need to use API keys or other secrets. You can leverage locally stored environments secrets
160161 as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`.
modified docs/customize/deep-dives/model-capabilities.mdx +22 −19
@@ -1,12 +1,13 @@
11 ---
2-title: Model Capabilities
2+title: "How to Configure Model Capabilities in Continue"
33 description: Understanding and configuring model capabilities for tools and image support
44 keywords: [capabilities, tools, function calling, image input, config]
5+sidebarTitle: "Model Capabilities"
56 ---
67
78 Continue needs to know what features your models support to provide the best experience. This guide explains how model capabilities work and how to configure them.
89
9-## What are Model Capabilities?
10+## What Are Model Capabilities?
1011
1112 Model capabilities tell Continue what features a model supports:
1213
@@ -19,11 +20,11 @@
1920 - Tools not working at all
2021 - Image uploads being disabled
2122
22-## How Continue Detects Capabilities
23+## How Continue Detects Model Capabilities
2324
2425 Continue uses a two-tier system for determining model capabilities:
2526
26-### 1. Automatic Detection (Default)
27+### How Automatic Detection Works (Default)
2728
2829 Continue automatically detects capabilities based on your provider and model name. For example:
2930
@@ -39,12 +40,14 @@
3940 - [toolSupport.ts](https://github.com/continuedev/continue/blob/main/core/llm/toolSupport.ts) - Tool capability detection logic
4041 - [@continuedev/llm-info](https://www.npmjs.com/package/@continuedev/llm-info) - Image support detection
4142
42-### 2. Manual Configuration
43+### How to Configure Capabilities Manually
4344
4445 You can add capabilities to models that Continue doesn't automatically detect in your `config.yaml`.
4546
4647 <Note>
47-You cannot override autodetection - you can only add capabilities. Continue will always use its built-in knowledge about your model in addition to any capabilities you specify.
48+ You cannot override autodetection - you can only add capabilities. Continue
49+ will always use its built-in knowledge about your model in addition to any
50+ capabilities you specify.
4851 </Note>
4952
5053 ```yaml
@@ -58,7 +61,7 @@
5861 - image_input
5962 ```
6063
61-## When to Add Capabilities
64+## When to Add Capabilities Manually
6265
6366 Add capabilities when:
6467
@@ -67,9 +70,9 @@
6770 3. **Experiencing issues** - Autodetection isn't working correctly for your setup
6871 4. **Using proxy services** - Some proxy services modify model capabilities
6972
70-## Configuration Examples
73+## How to Configure Model Capabilities (Examples)
7174
72-### Basic Configuration
75+### How to Add Basic Tool Support
7376
7477 Add tool support for a model that Continue doesn't recognize:
7578
@@ -88,13 +91,13 @@
8891 </Info>
8992
9093 <Warning>
91- **Experimental**: System message tools are available as an experimental feature
92- for models without native tool support. These are not automatically used as a
93- fallback and must be explicitly configured. Most models are trained for native
94- tools, so system message tools may not work as well.
94+ **Experimental**: System message tools are available as an experimental
95+ feature for models without native tool support. These are not automatically
96+ used as a fallback and must be explicitly configured. Most models are trained
97+ for native tools, so system message tools may not work as well.
9598 </Warning>
9699
97-### Disable Capabilities
100+### How to Handle Models with Limited Capabilities
98101
99102 Explicitly set no capabilities (autodetection will still apply):
100103
@@ -113,7 +116,7 @@
113116 features.
114117 </Warning>
115118
116-### Multiple Capabilities
119+### How to Enable Multiple Capabilities
117120
118121 Enable both tools and image support:
119122
@@ -127,7 +130,7 @@
127130 - image_input
128131 ```
129132
130-## Common Scenarios
133+## Common Configuration Scenarios
131134
132135 Some providers and custom deployments may require explicit capability configuration:
133136
@@ -148,11 +151,11 @@
148151 - image_input # If supports vision
149152 ```
150153
151-## Troubleshooting
154+## How to Troubleshoot Capability Issues
152155
153-For troubleshooting capability-related issues like Agent mode being unavailable or tools not working, see the [Troubleshooting guide](/troubleshooting#agent-mode-is-unavailable-or-tools-arent-working).
156+For troubleshooting capability-related issues like Agent mode being unavailable or tools not working, see the [Troubleshooting guide](/troubleshooting#agent-mode-is-unavailable-or-tools-aren’t-working).
154157
155-## Best Practices
158+## Best Practices for Model Capabilities
156159
157160 1. **Start with autodetection** - Only override if you experience issues
158161 2. **Test after changes** - Verify tools and images work as expected
modified docs/customize/deep-dives/prompts.mdx +7 −6
@@ -1,5 +1,6 @@
11 ---
2-title: Prompts
2+title: "Creating Custom Prompts in Continue"
3+description: "Learn how to create reusable prompt files in Continue to streamline repetitive tasks, including examples for code reviews, security checks, and entity generation"
34 ---
45
56 Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
@@ -7,11 +8,11 @@
78 <Info>
89 Prompts were previously defined in a `.prompt` file format, but for
910 consistency we now recommend using the same Markdown format as
10- [rules](./rules.mdx) and adding `alwaysApply: false` to the frontmatter so
11+ [rules](./rules) and adding `alwaysApply: false` to the frontmatter so
1112 that they are manually triggered.
1213 </Info>
1314
14-### Quick Start
15+## Quick Start: How to Create Your First Prompt File
1516
1617 Below is a quick example of setting up a prompt file:
1718
@@ -30,11 +31,11 @@
3031
3132 Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add.
3233
33-## Further Examples
34+## Example Prompt Templates for Common Use Cases
3435
3536 Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts).
3637
37-### Security review
38+### How to Create a Security Review Prompt
3839
3940 ```md title="security-review.md"
4041 ---
@@ -49,7 +50,7 @@
4950 - Is sensitive data handled appropriately throughout the lifecycle?
5051 ```
5152
52-### Pull in commonly used files for tasks
53+### How to Create a Prompt That References Existing Files
5354
5455 ```md title="typeorm-entity-generator.md"
5556 ---
modified docs/customize/deep-dives/rules.mdx +13 −12
@@ -1,25 +1,26 @@
11 ---
2-title: "Rules"
2+title: "How to Create and Manage Rules in Continue"
33 description: "Rules are used to provide instructions to the model for Agent, Chat, and Edit requests."
44 keywords: [rules, .continuerules, system, prompt, message]
5+sidebarTitle: "Rules"
56 ---
67
78 Rules provide instructions to the model for [Agent](../../features/agent/quick-start), [Chat](../../features/chat/quick-start), and [Edit](../../features/edit/quick-start) requests.
89
910 <Info>
10- Rules are not included in [autocomplete](./autocomplete.mdx) or
11- [apply](../model-roles/apply.mdx).
11+ Rules are not included in [autocomplete](./autocomplete) or
12+ [apply](../model-roles/apply).
1213 </Info>
1314
14-## How it works
15+## How Rules Work in Continue
1516
1617 You can view the current rules by clicking the pen icon above the main toolbar:
1718
1819 ![rules input toolbar section](/images/notch-rules.png)
1920
20-To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)).
21+To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#how-to-customize-chat-system-message)).
2122
22-## Quick Start
23+## Quick Start: How to Create Your First Rule File
2324
2425 Below is a quick example of setting up a new rule file:
2526
@@ -39,7 +40,7 @@
3940
4041 ![pirate rule test](/images/pirate-rule-test.png)
4142
42-## Creating rules blocks
43+## How to Create Rules Blocks
4344
4445 Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules.
4546
@@ -56,7 +57,7 @@
5657
5758 Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
5859
59-### Syntax
60+### How to Configure Rule Properties and Syntax
6061
6162 <Info>
6263 Rules were originally defined in YAML format (demonstrated below), but we
@@ -125,13 +126,13 @@
125126 </Tab>
126127 </Tabs>
127128
128-### `.continue/rules` folder
129+### How to Set Up Project-Specific Rules
129130
130131 You can create project-specific rules by adding a `.continue/rules` folder to the root of your project and adding new rule files.
131132
132133 Rules files are loaded in lexicographical order, so you can prefix them with numbers to control the order in which they are applied. For example: `01-general.md`, `02-frontend.md`, `03-backend.md`.
133134
134-### Example: TypeScript Rules
135+### Example: How to Create TypeScript-Specific Rules
135136
136137 ```md title=".continue/rules/typescript.md"
137138 ---
@@ -149,7 +150,7 @@
149150 - modularize components into smaller, reusable pieces
150151 ```
151152
152-### Chat System Message
153+### How to Customize Chat System Message
153154
154155 Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output.
155156
@@ -157,7 +158,7 @@
157158
158159 Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](/reference#models).
159160
160-### `.continuerules`
161+### Legacy: .continuerules File (Deprecated)
161162
162163 <Warning>
163164 `.continuerules` will be deprecated in a future release. Please use the
modified docs/customize/deep-dives/slash-commands.mdx +9 −8
@@ -1,7 +1,8 @@
11 ---
2-title: Slash commands
3-description: Shortcuts that can be activated by prefacing your input with '/'
2+title: "Using Slash Commands in Continue"
3+description: "Learn how to use and create Slash Commands in Continue to run custom prompts, access context providers, and speed up coding tasks."
44 keywords: [slash command, custom commands, step]
5+sidebarTitle: "Slash Commands"
56 ---
67
78 ![actions](/images/actions.gif)
@@ -18,18 +19,18 @@
1819 commands.
1920 </Note>
2021
21-## Prompts
22+## Ways to Create Slash Commands in Continue
2223
23-### Assistant prompt blocks
24+### Assistant Prompt Blocks
2425
25-The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
26+The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works).
2627
27-### Prompt files
28+### Prompt Files
2829
2930 It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
3031
3132 Learn more about prompt files [here](./prompts).
3233
33-### MCP Server prompts
34+### MCP Server Prompts
3435
35-Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp.mdx) for more details.
36+Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp) for more details.
modified docs/customize/deep-dives/vscode-actions.mdx +8 −10
@@ -1,15 +1,15 @@
11 ---
2-title: VS Code Actions
2+title: "How to Use Continue's VS Code Actions and Quick Features"
33 keywords: [vscode, quick actions, quick, actions]
4+description: "Learn about Continue's VS Code-specific actions including quick actions buttons, right-click context menu options, debug shortcuts, and quick fixes for errors in your code"
5+sidebarTitle: "VS Code Actions"
46 ---
57
6-### Other triggers for Actions (VS Code)
7-
88 <Info>Currently all of these are only available in VS Code</Info>
99
1010 To make common use cases even more accessible, we provide a handful of other ways to invoke actions in VS Code.
1111
12-## Quick actions
12+## How to Use Quick Actions
1313
1414 Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions.
1515
@@ -17,17 +17,17 @@
1717
1818 By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings.
1919
20-## Right click actions
20+## How to Use Right Click Actions
2121
2222 Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu.
2323
2424 The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit.
2525
26-Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../features/edit/how-it-works.mdx).
26+Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../features/edit/how-it-works).
2727
2828 ![context-menu](/images/context-menu.png)
2929
30-## Debug action
30+## How to Use the Debug Action Shortcut
3131
3232 The debug action is a special built-in keyboard shortcut in the VS Code extension. Use <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>R</kbd> to instantly copy the contents of the most recent terminal output into the chat sidebar and get debugging advice. There is no additional, non-visible information sent to the language model.
3333
@@ -37,10 +37,8 @@
3737 [ERROR_MESSAGE]
3838 ```
3939
40-## Quick fixes
40+## How to Use Quick Fixes for Code Errors
4141
4242 Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> again and Continue will attempt to help solve the problem.
4343
4444 Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”.
45-
46-![ask-continue](/images/ask-continue.png)
modified docs/customize/model-providers/_category_.json +5 −1
@@ -1,4 +1,8 @@
11 {
22 "label": "Model Providers",
3- "position": 4
3+ "position": 1,
4+ "link": {
5+ "type": "doc",
6+ "id": "customize/model-providers/overview"
7+ }
48 }
modified docs/customize/model-providers/more/SambaNova.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "SambaNova"
3+description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
34 ---
45
56 The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup.
modified docs/customize/model-providers/more/asksage.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "AskSage"
3+description: "Configure AskSage with Continue to access a wide range of models including government-compliant versions of GPT and Claude models, supporting chat and edit functionalities"
34 ---
45
56 <Info>
modified docs/customize/model-providers/more/cerebras.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Cerebras"
3+description: "Configure Cerebras Inference with Continue for fast model inference using specialized silicon, including setup instructions for Llama 3.1 70B model"
34 ---
45
56 Cerebras Inference uses specialized silicon to provides fast inference.
modified docs/customize/model-providers/more/cloudflare.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Cloudflare"
3+description: "Configure Cloudflare Workers AI with Continue to access various models for chat and autocomplete, including Llama 3 8B and DeepSeek Coder through Cloudflare's serverless AI platform"
34 ---
45
56 Cloudflare Workers AI can be used for both chat and tab autocompletion in Continue. Here is an example of Cloudflare Workers AI configuration:
modified docs/customize/model-providers/more/cohere.mdx +2 −1
@@ -1,5 +1,6 @@
11 ---
22 title: "Cohere"
3+description: "Configure Cohere's AI models with Continue, including setup for Command A for chat, embed-v4.0 for embeddings, and rerank-v3.5 for reranking capabilities"
34 ---
45
56 Before using Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.
@@ -38,7 +39,7 @@
3839
3940 Cohere currently does not offer any autocomplete models.
4041
41-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
42+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
4243
4344 ## Embeddings model
4445
modified docs/customize/model-providers/more/deepinfra.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "DeepInfra"
3+description: "Configure DeepInfra with Continue to access low-cost inference for open-source models like Mixtral-8x7B-Instruct, including API setup instructions"
34 ---
45
56 [DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here:
modified docs/customize/model-providers/more/flowise.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Flowise"
3+description: "Configure Flowise with Continue to integrate with this low-code/no-code drag & drop tool for building and visualizing LLM applications"
34 ---
45
56 [Flowise](https://flowiseai.com/) is a low-code/no-code drag & drop tool with the aim to make it easy for people to visualize and build LLM apps. Continue can then be configured to use the `Flowise` LLM class, like the example here:
modified docs/customize/model-providers/more/function-network.mdx +1 −7
@@ -1,12 +1,6 @@
11 ---
22 title: "Function Network"
3----
4-
5----
6-
7-title: Function Network
8-slug: ../function-network
9-
3+description: "Configure Function Network with Continue to access private and affordable AI models, including Llama 3.1, Qwen2.5-Coder, and various embedding models for a user-owned AI experience"
104 ---
115
126 > Private, Affordable User-Owned AI
modified docs/customize/model-providers/more/groq.mdx +3 −1
@@ -1,5 +1,7 @@
11 ---
2-title: "Groq"
2+title: "How to Configure Groq with Continue"
3+description: "Configure Groq with Continue to access their ultra-fast inference platform for open-source language models, including the entire Llama 3.1 and 3.3 family with industry-leading speeds"
4+sidebarTitle: "Groq"
35 ---
46
57 <Info>
modified docs/customize/model-providers/more/huggingfaceinferenceapi.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "HuggingFace Inference Endpoints"
3+description: "Configure HuggingFace Inference Endpoints with Continue to deploy and access open-source language models on any cloud, including setup instructions for models like WizardCoder"
34 ---
45
56 Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this:
modified docs/customize/model-providers/more/ipex_llm.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Intel Extension for PyTorch"
3+description: "Configure Intel Extension for PyTorch (IPEX-LLM) with Continue to run language models with very low latency on Intel CPUs and GPUs, leveraging accelerated Ollama backend"
34 ---
45
56 <Info>
modified docs/customize/model-providers/more/kindo.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Kindo"
3+description: "Configure Kindo with Continue to centralize control over your organization's AI operations with support for commercial and open-source models while ensuring data protection and policy compliance"
34 ---
45
56 Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create an API key in [Settings > API > API Keys](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the "Available Models" tab or copy and paste the config in [Plugins > Your Configuration](https://app.kindo.ai/plugins).
modified docs/customize/model-providers/more/llamacpp.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Llama.cpp"
3+description: "Configure Llama.cpp with Continue to run local language models using high-performance C++ inference, including setup instructions for the server and client configuration"
34 ---
45
56 Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0:
modified docs/customize/model-providers/more/llamafile.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Llamafile"
3+description: "Configure Llamafile with Continue to use self-contained binary files that can run open-source language models like Mistral without additional setup"
34 ---
45
56 A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contained binary that can run an open-source LLM. You can configure this provider in your config.json as follows:
modified docs/customize/model-providers/more/lmstudio.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "LM Studio"
3+description: "Configure LM Studio with Continue to run open-source models locally, including setup for Llama3.1 8B for chat, embedding models, and instructions for connecting to remote instances"
34 ---
45
56 [LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class:
modified docs/customize/model-providers/more/moonshot.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Moonshot AI"
3+description: "Configure Moonshot AI's language models with Continue, including setup instructions for their 8K, 32K, and 128K context window models with competitive pricing"
34 ---
45
56 [Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance.
modified docs/customize/model-providers/more/morph.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Morph"
3+description: "Configure Morph with Continue to access their optimized models for code application, embeddings, and reranking, designed for fast and accurate integration of AI-generated code changes"
34 ---
45
56 Morph provides a fast apply model that helps you quickly and accurately apply code changes from chat suggestions to your files. It's optimized for speed and precision when integrating generated code into your existing codebase. You can sign up for Morph's generous free tier [here](https://morphllm.com/dashboard). Then, update your configuration file as follows:
modified docs/customize/model-providers/more/msty.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Msty"
3+description: "Configure Msty with Continue to easily run both online and local open-source models like Llama-2 and DeepSeek Coder through their user-friendly application for Windows, Mac, and Linux"
34 ---
45
56 [Msty](https://msty.app/) is an application for Windows, Mac, and Linux that makes it really easy to run online as well as local open-source models, including Llama-2, DeepSeek Coder, etc. No need to fidget with your terminal, run a command, or anything. Just download the app from the website, click a button, and you are up and running. Continue can then be configured to use the `Msty` LLM class:
modified docs/customize/model-providers/more/ncompass.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "NCompass"
3+description: "Configure NCompass Technologies with Continue to access their fast inference engine for open-source models like Google's Gemma 3 Coder"
34 ---
45
56 The nCompass Technologies API exposes an extremely fast inference engine for open-source language models. You can sign up [here](https://app.ncompass.tech/api-settings), copy your API key on the initial welcome screen, and then hit the play button on any model from the [nCompass Models list](https://ncompass.tech/models). Change `~/.continue/config.json` to look like this:
modified docs/customize/model-providers/more/nebius.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Nebius"
3+description: "Configure Nebius AI Studio with Continue to access their language model offerings, including DeepSeek R1 for chat and BAAI embeddings models"
34 ---
45
56 You can get an API key from the [Nebius AI Studio API keys page](https://studio.nebius.ai/settings/api-keys)
modified docs/customize/model-providers/more/novita.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Novita"
3+description: "Configure Novita AI with Continue to access their affordable and reliable inference platform for language models like Llama 3.1, offering scalable LLM API services"
34 ---
45
56 [Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!. You can sign up [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), copy your API key on the [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), and then hit the play button on any model from the [Novita AI Models list](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link). Change `~/.continue/config.json` to look like this:
modified docs/customize/model-providers/more/nvidia.mdx +2 −5
@@ -1,11 +1,8 @@
11 ---
22 title: "NVIDIA"
3+description: "Configure NVIDIA AI models with Continue, including setup for Nemotron-4-340B-Instruct for chat and NVIDIA Retrieval QA Mistral 7B for embeddings"
34 ---
45
5----
6-
7-## title: NVIDIA
8-
96 <Info>
107 [View the
118 docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)
@@ -46,7 +43,7 @@
4643
4744 NVIDIA currently does not offer any autocomplete models.
4845
49-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
46+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
5047
5148 ## Embeddings model
5249
modified docs/customize/model-providers/more/openrouter.mdx +8 −3
@@ -1,5 +1,7 @@
11 ---
2-title: "OpenRouter"
2+title: "How to Configure OpenRouter with Continue"
3+sidebarTitle: "OpenRouter"
4+description: "Configure OpenRouter with Continue to access various commercial and open-source models through a unified interface, including model capability configuration and advanced request options"
35 ---
46
57 OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models).
@@ -74,10 +76,13 @@
7476
7577 ## Model Capabilities
7678
77-OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support.
79+OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support.
7880
7981 <Info>
80- Continue automatically uses system message tools for models that don't support native function calling, so Agent mode should work even without explicit capability configuration. However, you can still override capabilities if needed.
82+ Continue automatically uses system message tools for models that don't support
83+ native function calling, so Agent mode should work even without explicit
84+ capability configuration. However, you can still override capabilities if
85+ needed.
8186 </Info>
8287
8388 If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field:
modified docs/customize/model-providers/more/openvino_model_server.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "OpenVINO Model Server"
3+description: "Configure OpenVINO Model Server with Continue to use Intel-optimized models for CPU, iGPU, GPU and NPU via the OpenAI-compatible API, supporting code completion with models like CodeLlama and Qwen"
34 ---
45
56 <Info>
modified docs/customize/model-providers/more/ovhcloud.mdx +1 −4
@@ -1,11 +1,8 @@
11 ---
22 title: "OVHcloud"
3+description: "Configure OVHcloud AI Endpoints with Continue to access their GDPR-compliant serverless inference API for models like Qwen, Llama, Mistral, and Deepseek, with strong security and data privacy features"
34 ---
45
5----
6-
7-## title: OVHcloud AI Endpoints
8-
96 OVHcloud AI Endpoints is a serverless inference API that provides access to a curated selection of models (e.g., Llama, Mistral, Qwen, Deepseek). It is designed with security and data privacy in mind and is compliant with GDPR.
107
118 <Info>
modified docs/customize/model-providers/more/relace.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Relace"
3+description: "Configure Relace with Continue to access their Fast Apply model, which helps you quickly and reliably apply chat suggestions to your codebase"
34 ---
45
56 Relace provides a fast apply model through their API that helps you reliably and almost instantly apply chat suggestions to your codebase. You can sign up and obtain an API key [here](https://app.relace.ai/settings/api-keys). Then, change your configuration file to look like this:
modified docs/customize/model-providers/more/replicatellm.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Replicate"
3+description: "Configure Replicate with Continue to access newly released language models or deploy your own through their platform, with support for various models including CodeLLama"
34 ---
45
56 Replicate is a great option for newly released language models or models that you've deployed through their platform. Sign up for an account [here](https://replicate.ai/), copy your API key, and then select any model from the [Replicate Streaming List](https://replicate.com/collections/streaming-language-models). Change `~/.continue/config.json` to look like this:
modified docs/customize/model-providers/more/sagemaker.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Amazon SageMaker"
3+description: "Configure Amazon SageMaker with Continue to use deployed LLM endpoints for both chat and embedding models, supporting LMI and HuggingFace TEI deployments with AWS credentials"
34 ---
45
56 SageMaker can be used for both chat and embedding models. Chat models are supported for endpoints deployed with [LMI](https://docs.djl.ai/docs/serving/serving/docs/lmi/index.html), and embedding models are supported for endpoints deployed with [HuggingFace TEI](https://huggingface.co/blog/sagemaker-huggingface-embedding)
modified docs/customize/model-providers/more/scaleway.mdx +2 −5
@@ -1,11 +1,8 @@
11 ---
22 title: "Scaleway"
3+description: "Configure Scaleway Generative APIs with Continue to access AI models hosted in European data centers, offering low latency, data privacy, and EU AI Act compliance with models like Qwen2.5-Coder and BGE-Multilingual-Gemma2"
34 ---
45
5----
6-
7-## title: Scaleway
8-
96 <Info>
107 Scaleway Generative APIs give you instant access to leading AI models hosted
118 in European data centers, ideal for developers requiring low latency, full
@@ -50,7 +47,7 @@
5047
5148 Scaleway currently does not offer any autocomplete models.
5249
53-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
50+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
5451
5552 ## Embeddings model
5653
modified docs/customize/model-providers/more/siliconflow.mdx +1 −4
@@ -1,11 +1,8 @@
11 ---
22 title: "SiliconFlow"
3+description: "Configure SiliconFlow with Continue to access their AI model platform, featuring Qwen's Coder models for chat and autocomplete, along with various embedding and reranking models"
34 ---
45
5----
6-
7-## title: SiliconFlow
8-
96 <Info>
107 You can get an API key from the [Silicon
118 Cloud](https://cloud.siliconflow.cn/account/ak).
modified docs/customize/model-providers/more/textgenwebui.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Text Generation WebUI"
3+description: "Configure Text Generation WebUI with Continue to use its comprehensive open-source language model UI and local server through its OpenAI-compatible API"
34 ---
45
56 TextGenWebUI is a comprehensive, open-source language model UI and local server. You can set it up with an OpenAI-compatible server plugin, and then configure it like this:
modified docs/customize/model-providers/more/together.mdx +3 −1
@@ -1,5 +1,7 @@
11 ---
2-title: "Together AI"
2+title: "How to Configure Together AI with Continue"
3+description: "Configure the Together AI cloud platform for running large language models with Continue, including setup instructions and sample configuration for Qwen2.5 Coder"
4+sidebarTitle: "Together AI"
35 ---
46
57 The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this:
modified docs/customize/model-providers/more/venice.mdx +1 −4
@@ -1,11 +1,8 @@
11 ---
22 title: "Venice AI"
3+description: "Configure Venice AI with Continue to access this privacy-focused generative AI platform that supports open-source LLMs without storing private user data"
34 ---
45
5----
6-
7-## title: "Venice AI"
8-
96 Venice.AI is a privacy focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data. To get started with Venice's API, either purchase a pro account, stake $VVV to obtain daily inference allotments or fund your account with USD and head over to https://venice.ai/settings/api. Venice hosts state of the art open-source AI models and supports the OpenAI API standard, allowing users to easily interact with the platform. Learn more about the Venice API at https://venice.ai/api.
107
118 Change `~/.continue/config.json` to look like the following.
modified docs/customize/model-providers/more/vllm.mdx +3 −2
@@ -1,5 +1,6 @@
11 ---
22 title: "vLLM"
3+description: "Configure vLLM's high-performance inference library with Continue for chat, autocomplete, and embeddings, including setup instructions for Llama3.1, Qwen2.5-Coder, and Nomic Embed models"
34 ---
45
56 vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same time. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html).
@@ -101,6 +102,6 @@
101102
102103 Continue automatically handles vLLM's response format (which uses `results` instead of `data`).
103104
104-[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
105+[Click here](../../model-roles/reranking) to see a list of reranking model providers.
105106
106-The continue implementation uses [OpenAI](../top-level/openai.mdx) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)
107+The continue implementation uses [OpenAI](../top-level/openai) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)
modified docs/customize/model-providers/more/watsonx.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "IBM WatsonX"
3+description: "How to configure IBM's watsonx models in Continue, including authentication methods, deployment options, and support for chat, autocomplete, embeddings, and reranking models"
34 ---
45
56 watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.
added docs/customize/model-providers/overview.mdx +85 −0
@@ -0,0 +1,85 @@
1+---
2+title: "Model Providers Overview"
3+description: "Continue supports a wide range of AI model providers to power different features like chat, code editing, autocompletion, and embeddings. This overview helps you navigate through the available options and find the right provider for your needs."
4+---
5+
6+## Popular Model Providers
7+
8+These are the most commonly used model providers that offer a wide range of capabilities:
9+
10+| Provider | Description | Capabilities |
11+| :------------------------------------------------------------- | :------------------------------------------------------------------------------ | :------------------------------------------ |
12+| [Anthropic](/customize/model-providers/top-level/anthropic) | Providers of Claude models, known for long context windows and strong reasoning | Chat, Edit, Apply, Embeddings |
13+| [OpenAI](/customize/model-providers/top-level/openai) | Creators of GPT models with strong coding capabilities | Chat, Edit, Apply, Embeddings |
14+| [Azure](/customize/model-providers/top-level/azure) | Microsoft's cloud platform offering OpenAI models | Chat, Edit, Apply, Embeddings |
15+| [Amazon Bedrock](/customize/model-providers/top-level/bedrock) | AWS service offering access to various foundation models | Chat, Edit, Apply, Embeddings |
16+| [Ollama](/customize/model-providers/top-level/ollama) | Run open-source models locally with a simple interface | Chat, Edit, Apply, Embeddings, Autocomplete |
17+| [Google Gemini](/customize/model-providers/top-level/gemini) | Google's multimodal AI models | Chat, Edit, Apply, Embeddings |
18+| [DeepSeek](/customize/model-providers/top-level/deepseek) | Specialized code models with strong performance | Chat, Edit, Apply |
19+| [Mistral](/customize/model-providers/top-level/mistral) | High-performance open models with commercial offerings | Chat, Edit, Apply, Embeddings |
20+| [xAI](/customize/model-providers/top-level/xAI) | Grok models from xAI | Chat, Edit, Apply |
21+| [Vertex AI](/customize/model-providers/top-level/vertexai) | Google Cloud's machine learning platform | Chat, Edit, Apply, Embeddings |
22+| [Inception](/customize/model-providers/top-level/inception) | On-premises open-source model runners | Chat, Edit, Apply |
23+
24+## Additional Model Providers
25+
26+Beyond the top-level providers, Continue supports many other options:
27+
28+### Hosted Services
29+
30+| Provider | Description |
31+| :--------------------------------------------------------------------- | :--------------------------------------------------------- |
32+| [Groq](/customize/model-providers/more/groq) | Ultra-fast inference for various open models |
33+| [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models |
34+| [DeepInfra](/customize/model-providers/more/deepinfra) | Hosting for various open source models |
35+| [OpenRouter](/customize/model-providers/more/openrouter) | Gateway to multiple model providers |
36+| [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation |
37+| [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting |
38+| [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services |
39+| [HuggingFace](/customize/model-providers/more/huggingfaceinferenceapi) | Platform for open source models |
40+
41+### Local Model Options
42+
43+| Provider | Description |
44+| :------------------------------------------------------- | :-------------------------------------------- |
45+| [LM Studio](/customize/model-providers/more/lmstudio) | Desktop app for running models locally |
46+| [llama.cpp](/customize/model-providers/more/llamacpp) | Optimized C++ implementation for running LLMs |
47+| [LlamaStack](/customize/model-providers/more/llamastack) | Stack for running Llama models locally |
48+| [llamafile](/customize/model-providers/more/llamafile) | Self-contained executable model files |
49+
50+### Enterprise Solutions
51+
52+| Provider | Description |
53+| :----------------------------------------------------- | :------------------------------------ |
54+| [SambaNova](/customize/model-providers/more/SambaNova) | Enterprise AI platform |
55+| [Watson x](/customize/model-providers/more/watsonx) | IBM's enterprise AI platform |
56+| [Sagemaker](/customize/model-providers/more/sagemaker) | AWS machine learning platform |
57+| [Nebius](/customize/model-providers/more/nebius) | Cloud-based machine learning platform |
58+
59+## How to Choose a Model Provider
60+
61+When selecting a model provider, consider:
62+
63+1. **Hosting preference**: Do you need local models for offline use or privacy, or are you comfortable with cloud services?
64+2. **Performance requirements**: Different providers offer varying levels of speed, quality, and context length.
65+3. **Specific capabilities**: Some models excel at code generation, others at embeddings or reasoning tasks.
66+4. **Pricing**: Costs vary significantly between providers, from free local options to premium cloud services.
67+5. **API key requirements**: Most cloud providers require API keys that you'll need to configure.
68+
69+## Configuration Format
70+
71+You can add models to your `config.yaml` file like this:
72+
73+```yaml
74+models:
75+ - name: My Model
76+ provider: openai # Choose provider from the lists above
77+ model: gpt-4o # Specific model name
78+ apiKey: ${{ secrets.OPENAI_API_KEY }}
79+ roles:
80+ - chat
81+ - edit
82+ - apply
83+```
84+
85+For more detailed configuration, visit the specific provider pages linked above.
modified docs/customize/model-providers/top-level/anthropic.mdx +9 −7
@@ -1,6 +1,8 @@
11 ---
2-title: Anthropic
2+title: "How to Configure Anthropic Claude Models with Continue"
33 slug: ../anthropic
4+description: "Configure Anthropic's Claude models with Continue, including Claude 4 Sonnet with prompt caching capabilities to improve performance and reduce costs for chat applications"
5+sidebarTitle: "Anthropic"
46 ---
57
68 <Info>
@@ -8,7 +10,7 @@
810 console](https://console.anthropic.com/account/keys).
911 </Info>
1012
11-## Chat model
13+## How to Set Up Anthropic Chat Models
1214
1315 We recommend configuring **Claude 4 Sonnet** as your chat model.
1416
@@ -38,25 +40,25 @@
3840 </Tab>
3941 </Tabs>
4042
41-## Autocomplete model
43+## Anthropic Autocomplete Model Availability
4244
4345 Anthropic currently does not offer any autocomplete models.
4446
45-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
47+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
4648
47-## Embeddings model
49+## Anthropic Embeddings Model Availability
4850
4951 Anthropic currently does not offer any embeddings models.
5052
5153 [Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
5254
53-## Reranking model
55+## Anthropic Reranking Model Availability
5456
5557 Anthropic currently does not offer any reranking models.
5658
5759 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
5860
59-## Prompt caching
61+## How to Enable Prompt Caching with Claude
6062
6163 Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching), which allows Claude models to cache system messages and conversation history between requests to improve performance and reduce costs.
6264
modified docs/customize/model-providers/top-level/azure.mdx +14 −7
@@ -1,17 +1,19 @@
11 ---
2-title: Azure AI Foundry
2+title: "How to Configure Azure AI Foundry with Continue"
33 slug: ../azure
4+description: "Configure Azure AI Foundry with Continue to access models from OpenAI and Mistral with Microsoft's enterprise security features, including setup for GPT-4o, Codestral, and embedding models"
5+sidebarTitle: "Azure AI Foundry"
46 ---
57
68 Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com).
79
810 <Info>
911
10-For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azure-openai-service-configuration).
12+For details on OpenAI model setup, see [Azure OpenAI Service configuration](#how-to-configure-azure-openai-service).
1113
1214 </Info>
1315
14-## Chat model
16+## How to Set Up Azure AI Foundry Chat Models
1517
1618 We recommend configuring **GPT-4o** as your chat model.
1719
@@ -27,6 +29,7 @@
2729 env:
2830 deployment: <YOUR_DEPLOYMENT_NAME>
2931 apiType: azure-foundry # Or "azure-openai" if using OpenAI models
32+ apiVersion: 2023-07-01-preview # Azure API version
3033 ```
3134 </Tab>
3235 <Tab title="JSON">
@@ -46,12 +49,15 @@
4649 </Tab>
4750 </Tabs>
4851
49-## Autocomplete model
52+## How to Set Up Azure AI Foundry Autocomplete Models
5053
51-We recommend configuring **Codestral** as your autocomplete model.
54+We recommend configuring **Codestral** as your autocomplete model.
5255
5356 <Info>
54-**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint.
57+ **Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint
58+ required for autocomplete functionality. To use Codestral for autocomplete,
59+ deploy it through **Azure Machine Learning Studio** instead, which provides
60+ the necessary `/v1/fim/completions` endpoint.
5561 </Info>
5662
5763 If you use Azure Machine Learning Studio to deploy Codestral:
@@ -84,7 +90,7 @@
8490 </Tab>
8591 </Tabs>
8692
87-## Embeddings model
93+## How to Configure Azure AI Foundry Embeddings Models
8894
8995 We recommend configuring **text-embedding-3-large** as your embeddings model.
9096
@@ -100,6 +106,7 @@
100106 env:
101107 deployment: <YOUR_DEPLOYMENT_NAME>
102108 apiType: azure
109+ apiVersion: 2023-07-01-preview
103110 ```
104111 </Tab>
105112 <Tab title="JSON">
modified docs/customize/model-providers/top-level/bedrock.mdx +11 −9
@@ -1,11 +1,13 @@
11 ---
2-title: Amazon Bedrock
2+title: "How to Configure Amazon Bedrock with Continue"
33 slug: ../bedrock
4+description: "Configure Amazon Bedrock with Continue to access foundation models like Claude 3.7 Sonnet for chat, Titan for embeddings, and Cohere for reranking, with AWS credential authentication"
5+sidebarTitle: "Amazon Bedrock"
46 ---
57
68 Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API.
79
8-## Chat model
10+## How to Set Up Amazon Bedrock Chat Models
911
1012 We recommend configuring **Claude 3.7 Sonnet** as your chat model.
1113
@@ -75,13 +77,13 @@
7577 </Tab>
7678 </Tabs>
7779
78-## Autocomplete model
80+## How to Set Up Amazon Bedrock Autocomplete Models
7981
8082 Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future.
8183
82-In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete.md).
84+In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete).
8385
84-## Embeddings model
86+## How to Configure Amazon Bedrock Embeddings Models
8587
8688 We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) as your embeddings model.
8789
@@ -112,7 +114,7 @@
112114 </Tab>
113115 </Tabs>
114116
115-## Reranking model
117+## How to Configure Amazon Bedrock Reranking Models
116118
117119 We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`.
118120
@@ -144,7 +146,7 @@
144146 </Tab>
145147 </Tabs>
146148
147-## Prompt caching
149+## How to Enable Prompt Caching with Amazon Bedrock
148150
149151 Bedrock allows Claude models to cache tool payloads, system messages, and chat
150152 messages between requests. Enable this behavior by adding
@@ -174,7 +176,7 @@
174176
175177 Prompt caching is not supported in JSON configuration files, so use the YAML syntax above to enable it.
176178
177-## Authentication
179+## How to Set Up Authentication for Amazon Bedrock
178180
179181 Authentication will be through temporary or long-term credentials in
180182 `~/.aws/credentials` under a configured profile (e.g. "bedrock").
@@ -221,7 +223,7 @@
221223 </Tab>
222224 </Tabs>
223225
224-## Custom Imported Models
226+## How to Configure Custom Imported Models with Amazon Bedrock
225227
226228 To setup Bedrock using custom imported models, add the following to your config file:
227229
modified docs/customize/model-providers/top-level/deepseek.mdx +7 −5
@@ -1,13 +1,15 @@
11 ---
2-title: DeepSeek
2+title: "How to Configure DeepSeek with Continue"
33 slug: ../deepseek
4+description: "Configure DeepSeek models with Continue, including DeepSeek Chat for general conversations and DeepSeek Coder specifically optimized for code autocomplete and programming tasks"
5+sidebarTitle: "DeepSeek"
46 ---
57
68 <Info>
79 You can get an API key from the [DeepSeek console](https://www.deepseek.com/).
810 </Info>
911
10-## Chat model
12+## How to Set Up DeepSeek Chat Models
1113
1214 We recommend configuring **DeepSeek Chat** as your chat model.
1315
@@ -37,7 +39,7 @@
3739 </Tab>
3840 </Tabs>
3941
40-## Autocomplete model
42+## How to Set Up DeepSeek Autocomplete Models
4143
4244 We recommend configuring **DeepSeek Coder** as your autocomplete model.
4345
@@ -67,13 +69,13 @@
6769 </Tab>
6870 </Tabs>
6971
70-## Embeddings model
72+## How to Configure DeepSeek Embeddings Models
7173
7274 DeepSeek currently does not offer any embeddings models.
7375
7476 [Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
7577
76-## Reranking model
78+## How to Configure DeepSeek Reranking Models
7779
7880 DeepSeek currently does not offer any reranking models.
7981
modified docs/customize/model-providers/top-level/gemini.mdx +8 −6
@@ -1,6 +1,8 @@
11 ---
2-title: Gemini
2+title: "How to Configure Gemini with Continue"
33 slug: ../gemini
4+description: "Configure Google's Gemini models with Continue to access Gemini 2.0 Flash for chat and text-embedding-004 for embeddings with simple API key authentication"
5+sidebarTitle: "Gemini"
46 ---
57
68 <Info>
@@ -8,7 +10,7 @@
810 Studio](https://aistudio.google.com/).
911 </Info>
1012
11-## Chat model
13+## How to Set Up Gemini Chat Models
1214
1315 We recommend configuring **Gemini 2.0 Flash** as your chat model.
1416
@@ -38,13 +40,13 @@
3840 </Tab>
3941 </Tabs>
4042
41-## Autocomplete model
43+## How to Set Up Gemini Autocomplete Models
4244
4345 Gemini currently does not offer any autocomplete models.
4446
45-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
47+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
4648
47-## Embeddings model
49+## How to Configure Gemini Embeddings Models
4850
4951 We recommend configuring **text-embedding-004** as your embeddings model.
5052
@@ -73,7 +75,7 @@
7375 </Tab>
7476 </Tabs>
7577
76-## Reranking model
78+## How to Configure Gemini Reranking Models
7779
7880 Gemini currently does not offer any reranking models.
7981
modified docs/customize/model-providers/top-level/inception.mdx +7 −5
@@ -1,6 +1,8 @@
11 ---
2-title: Inception
2+title: "How to Configure Inception with Continue"
33 slug: ../inception
4+description: "Configure Inception Labs models with Continue, featuring Mercury Coder Small for both chat and autocomplete functions, optimized for programming and code generation tasks"
5+sidebarTitle: "Inception"
46 ---
57
68 <Info>
@@ -8,7 +10,7 @@
810 Dashboard](https://platform.inceptionlabs.ai/dashboard/api-keys).
911 </Info>
1012
11-## Chat model
13+## How to Set Up Inception Chat Models
1214
1315 We recommend configuring **Mercury Coder Small** as your chat model.
1416
@@ -37,7 +39,7 @@
3739 </Tab>
3840 </Tabs>
3941
40-## Autocomplete model
42+## How to Set Up Inception Autocomplete Models
4143
4244 We also recommend configuring **Mercury Coder Small** as your autocomplete model.
4345
@@ -66,13 +68,13 @@
6668 </Tab>
6769 </Tabs>
6870
69-## Embeddings model
71+## How to Configure Inception Embeddings Models
7072
7173 Inception currently does not offer any embeddings models.
7274
7375 [Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
7476
75-## Reranking model
77+## How to Configure Inception Reranking Models
7678
7779 Inception currently does not offer any reranking models.
7880
modified docs/customize/model-providers/top-level/mistral.mdx +7 −5
@@ -1,6 +1,8 @@
11 ---
2-title: Mistral
2+title: "How to Configure Mistral with Continue"
33 slug: ../mistral
4+description: "Configure Mistral AI models with Continue, including Mistral Large for chat, Codestral for code autocomplete, and Mistral Embed for embeddings with separate API key options"
5+sidebarTitle: "Mistral"
46 ---
57
68 <Info>
@@ -12,7 +14,7 @@
1214 using `https://api.mistral.ai/v1`.
1315 </Info>
1416
15-## Chat model
17+## How to Set Up Mistral Chat Models
1618
1719 We recommend configuring **Mistral Large** as your chat model.
1820
@@ -44,7 +46,7 @@
4446 </Tab>
4547 </Tabs>
4648
47-## Autocomplete model
49+## How to Set Up Mistral Autocomplete Models
4850
4951 We recommend configuring **Codestral** as your autocomplete model.
5052
@@ -74,7 +76,7 @@
7476 </Tab>
7577 </Tabs>
7678
77-## Embeddings model
79+## How to Configure Mistral Embeddings Models
7880
7981 We recommend configuring **Mistral Embed** as your embeddings model.
8082
@@ -105,7 +107,7 @@
105107 </Tab>
106108 </Tabs>
107109
108-## Reranking model
110+## How to Configure Mistral Reranking Models
109111
110112 Mistral currently does not offer any reranking models.
111113
modified docs/customize/model-providers/top-level/ollama.mdx +12 −9
@@ -1,11 +1,13 @@
11 ---
2-title: Ollama
2+title: "How to Configure Ollama with Continue"
33 slug: ../ollama
4+description: "Configure Ollama with Continue to run powerful open source models locally including Llama3.1 for chat, Qwen2.5-Coder for autocomplete, and Nomic Embed Text for embeddings"
5+sidebarTitle: "Ollama"
46 ---
57
68 Ollama is an open-source tool that allows to run large language models (LLMs) locally on their own computers. To use Ollama, you can install it [here](https://ollama.ai/download) and download the model you want to run with the `ollama run` command.
79
8-## Chat model
10+## How to Set Up Ollama Chat Models
911
1012 We recommend configuring **Llama3.1 8B** as your chat model.
1113
@@ -33,7 +35,7 @@
3335 </Tab>
3436 </Tabs>
3537
36-## Autocomplete model
38+## How to Configure Ollama Autocomplete Models
3739
3840 We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
3941
@@ -61,7 +63,7 @@
6163 </Tab>
6264 </Tabs>
6365
64-## Embeddings model
66+## How to Set Up Ollama Embeddings Models
6567
6668 We recommend configuring **Nomic Embed Text** as your embeddings model.
6769
@@ -88,13 +90,13 @@
8890 </Tab>
8991 </Tabs>
9092
91-## Reranking model
93+## Ollama Reranking Model Availability
9294
9395 Ollama currently does not offer any reranking models.
9496
95-[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
97+[Click here](../../model-roles/reranking) to see a list of reranking model providers.
9698
97-## Using a remote instance
99+## How to Configure Remote Ollama Instance
98100
99101 To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json:
100102
@@ -124,7 +126,7 @@
124126 </Tab>
125127 </Tabs>
126128
127-## Model Capabilities
129+## How to Configure Model Capabilities in Ollama
128130
129131 Ollama models usually have their capabilities auto-detected correctly. However, if you're using custom model names or experiencing issues with tools/images not working, you can explicitly set capabilities:
130132
@@ -160,5 +162,6 @@
160162 </Tabs>
161163
162164 <Note>
163-Most standard Ollama models (like llama3.1, mistral, etc.) support tool use by default. Vision models (like llava) also support image input.
165+ Most standard Ollama models (like llama3.1, mistral, etc.) support tool use by
166+ default. Vision models (like llava) also support image input.
164167 </Note>
modified docs/customize/model-providers/top-level/openai.mdx +13 −7
@@ -1,6 +1,8 @@
11 ---
2-title: OpenAI
2+title: "How to Configure OpenAI Models with Continue"
33 slug: ../openai
4+description: "Configure OpenAI models with Continue, including GPT-4o for chat and text-embedding-3-large for embeddings, with support for OpenAI-compatible servers and APIs"
5+sidebarTitle: "OpenAI"
46 ---
57
68 <Info>
@@ -8,7 +10,7 @@
810 console](https://platform.openai.com/account/api-keys)
911 </Info>
1012
11-## Chat model
13+## How to Set Up OpenAI Chat Models
1214
1315 We recommend configuring **GPT-4o** as your chat model.
1416
@@ -38,13 +40,13 @@
3840 </Tab>
3941 </Tabs>
4042
41-## Autocomplete model
43+## OpenAI Autocomplete Model Availability
4244
4345 OpenAI currently does not offer any autocomplete models.
4446
45-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
47+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
4648
47-## Embeddings model
49+## How to Configure OpenAI Embeddings Models
4850
4951 We recommend configuring **text-embedding-3-large** as your embeddings model.
5052
@@ -73,13 +75,13 @@
7375 </Tab>
7476 </Tabs>
7577
76-## Reranking model
78+## OpenAI Reranking Model Availability
7779
7880 OpenAI currently does not offer any reranking models.
7981
8082 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
8183
82-## OpenAI compatible servers / APIs
84+## How to Use OpenAI-Compatible Servers and APIs
8385
8486 OpenAI compatible servers
8587
@@ -97,6 +99,8 @@
9799 - [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others)
98100 - [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints)
99101
102+### How to Configure Custom API Base for OpenAI-Compatible Services
103+
100104 If you are using an OpenAI compatible server / API, you can change the `apiBase` like this:
101105
102106 <Tabs>
@@ -127,6 +131,8 @@
127131 </Tab>
128132 </Tabs>
129133
134+### How to Force Legacy Completions Endpoint Usage
135+
130136 To force usage of `chat/completions` instead of `completions` endpoint you can set:
131137
132138 <Tabs>
modified docs/customize/model-providers/top-level/vertexai.mdx +8 −6
@@ -1,6 +1,8 @@
11 ---
2-title: Vertex AI
2+title: "How to Configure Vertex AI with Continue"
33 slug: ../vertexai
4+description: "Configure Google Cloud's Vertex AI with Continue to access powerful models like Claude 3.5 Sonnet, Codestral, and text-embedding-004 for chat, autocomplete, and embeddings"
5+sidebarTitle: "Vertex AI"
46 ---
57
68 <Info>
@@ -10,7 +12,7 @@
1012 Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).
1113 </Info>
1214
13-## Chat model
15+## How to Set Up Vertex AI Chat Models
1416
1517 We recommend configuring **Claude 3.5 Sonnet** as your chat model.
1618
@@ -43,7 +45,7 @@
4345 </Tab>
4446 </Tabs>
4547
46-## Autocomplete model
48+## How to Set Up Vertex AI Autocomplete Models
4749
4850 We recommend configuring **Codestral** or **code-gecko** as your autocomplete model.
4951
@@ -77,7 +79,7 @@
7779 </Tab>
7880 </Tabs>
7981
80-## Embeddings model
82+## How to Configure Vertex AI Embeddings Models
8183
8284 We recommend configuring **text-embedding-004** as your embeddings model.
8385
@@ -109,13 +111,13 @@
109111 </Tab>
110112 </Tabs>
111113
112-## Reranking model
114+## How to Configure Vertex AI Reranking Models
113115
114116 Vertex AI currently does not offer any reranking models.
115117
116118 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
117119
118-## Express mode
120+## How to Enable Vertex AI Express Mode
119121
120122 You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now.
121123
modified docs/customize/model-providers/top-level/xAI.mdx +8 −6
@@ -1,13 +1,15 @@
11 ---
2-title: xAI
2+title: "How to Configure xAI with Continue"
33 slug: ../xai
4+description: "Configure xAI's Grok 4 model with Continue for advanced chat capabilities, with easy API key setup from the xAI console"
5+sidebarTitle: "xAI"
46 ---
57
68 <Info>
79 You can get an API key from the [xAI console](https://console.x.ai/)
810 </Info>
911
10-## Chat model
12+## How to Set Up xAI Chat Models
1113
1214 We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
1315
@@ -40,19 +42,19 @@
4042 </Tab>
4143 </Tabs>
4244
43-## Autocomplete model
45+## How to Set Up xAI Autocomplete Models
4446
4547 xAI currently does not offer any autocomplete models.
4648
47-[Click here](../../model-roles/autocomplete.md) to see a list of autocomplete model providers.
49+[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
4850
49-## Embeddings model
51+## How to Configure xAI Embeddings Models
5052
5153 xAI currently does not offer any embeddings models.
5254
5355 [Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
5456
55-## Reranking model
57+## How to Configure xAI Reranking Models
5658
5759 xAI currently does not offer any reranking models.
5860
modified docs/customize/model-roles.mdx +1 −0
@@ -2,6 +2,7 @@
22 title: "Model roles"
33 sidebarTitle: Overview
44 icon: "circle-info"
5+description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding assistant's capabilities"
56 ---
67
78 <CardGroup>
modified docs/customize/model-roles/00-intro.mdx +1 −1
@@ -9,7 +9,7 @@
99 Models in Continue can be configured to be used for various roles in the extension.
1010
1111 - [`chat`](./chat.mdx): Used for chat conversations in the extension sidebar
12-- [`autocomplete`](./autocomplete.md): Used for autocomplete code suggestions in the editor
12+- [`autocomplete`](./autocomplete): Used for autocomplete code suggestions in the editor
1313 - [`edit`](./edit.mdx): Used to generate code based on edit prompts
1414 - [`apply`](./apply.mdx): Used to decide how to apply edits to a file
1515 - [`embed`](./embeddings.mdx): Used to generate embeddings used for vector search (@Codebase and @Docs context providers)
modified docs/customize/model-roles/autocomplete.mdx +4 −3
@@ -1,6 +1,7 @@
11 ---
2-title: Autocomplete Role
3-description: Autocomplete model role
2+title: "Autocomplete Role in Continue Models"
3+sidebarTitle: "Autocomplete Role"
4+description: "Learn how the autocomplete role works in Continue, which models to use, and how to customize prompt templates for inline code suggestions."
45 keywords: [autocomplete, model, role]
56 sidebar_position: 2
67 ---
@@ -11,7 +12,7 @@
1112
1213 ## Recommended Autocomplete models
1314
14-Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details.
15+Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete) for recommended models and more details.
1516
1617 ## Prompt templating
1718
modified docs/customize/model-roles/chat.mdx +7 −7
@@ -7,7 +7,7 @@
77
88 A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters.
99
10-In Continue, these models are used for normal [Chat](../../features/chat/quick-start) and [VS Code actions](../deep-dives/vscode-actions.md). The selected chat model will also be used for [Edit](../../features/edit/quick-start) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively.
10+In Continue, these models are used for normal [Chat](../../features/chat/quick-start) and [VS Code actions](../deep-dives/vscode-actions). The selected chat model will also be used for [Edit](../../features/edit/quick-start) and [Apply](./apply) if no `edit` or `apply` models are specified, respectively.
1111
1212 ## Recommended Chat models
1313
@@ -17,7 +17,7 @@
1717
1818 ### Claude Sonnet 3.7 from Anthropic
1919
20-Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic.mdx).
20+Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic).
2121
2222 <Tabs>
2323 <Tab title="Hub">
@@ -50,7 +50,7 @@
5050
5151 ### Gemma from Google DeepMind
5252
53-If you prefer to use an open-weight model, then the Gemma family of Models from Google DeepMind is a good choice. You will need to decide if you use it through a SaaS model provider, e.g. [Together](../model-providers/more/together.mdx), or self-host it, e.g. [Ollama](../model-providers/top-level/ollama.mdx).
53+If you prefer to use an open-weight model, then the Gemma family of Models from Google DeepMind is a good choice. You will need to decide if you use it through a SaaS model provider, e.g. [Together](../model-providers/more/together), or self-host it, e.g. [Ollama](../model-providers/top-level/ollama).
5454
5555 <Tabs>
5656 <Tab title="Hub">
@@ -119,7 +119,7 @@
119119
120120 ### GPT-4o from OpenAI
121121
122-If you prefer to use a model from [OpenAI](../model-providers/top-level/openai.mdx), then we recommend GPT-4o.
122+If you prefer to use a model from [OpenAI](../model-providers/top-level/openai), then we recommend GPT-4o.
123123
124124 <Tabs>
125125 <Tab title="Hub">
@@ -152,7 +152,7 @@
152152
153153 ### Grok-2 from xAI
154154
155-If you prefer to use a model from [xAI](../model-providers/top-level/xAI.mdx), then we recommend Grok-2.
155+If you prefer to use a model from [xAI](../model-providers/top-level/xAI), then we recommend Grok-2.
156156
157157 <Tabs>
158158 <Tab title="Hub">
@@ -185,7 +185,7 @@
185185
186186 ### Gemini 2.0 Flash from Google
187187
188-If you prefer to use a model from [Google](../model-providers/top-level/gemini.mdx), then we recommend Gemini 2.0 Flash.
188+If you prefer to use a model from [Google](../model-providers/top-level/gemini), then we recommend Gemini 2.0 Flash.
189189
190190 <Tabs>
191191 <Tab title="Hub">
@@ -222,7 +222,7 @@
222222
223223 ### Llama 3.1 8B
224224
225-If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../model-providers/top-level/ollama.mdx) or [LM Studio](../model-providers/more/lmstudio.mdx)).
225+If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../model-providers/top-level/ollama) or [LM Studio](../model-providers/more/lmstudio)).
226226
227227 <Tabs>
228228 <Tab title="Hub">
modified docs/customize/model-roles/embeddings.mdx +6 −6
@@ -7,7 +7,7 @@
77
88 An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
99
10-In Continue, embeddings are generated during indexing and then used by [@Codebase](../context/codebase.mdx) to perform similarity search over your codebase.
10+In Continue, embeddings are generated during indexing and then used by [@Codebase](../context/codebase) to perform similarity search over your codebase.
1111
1212 You can add `embed` to a model's `roles` to specify that it can be used to embed.
1313
@@ -118,7 +118,7 @@
118118
119119 ### OpenAI
120120
121-See [here](../model-providers/top-level/openai#embeddings-model) for instructions on how to use OpenAI for embeddings.
121+See [here](../model-providers/top-level/openai#how-to-configure-openai-embeddings-models) for instructions on how to use OpenAI for embeddings.
122122
123123 ### Cohere
124124
@@ -126,15 +126,15 @@
126126
127127 ### Gemini
128128
129-See [here](../model-providers/top-level/gemini#embeddings-model) for instructions on how to use Gemini for embeddings.
129+See [here](../model-providers/top-level/gemini#how-to-configure-gemini-embeddings-models) for instructions on how to use Gemini for embeddings.
130130
131131 ### Vertex
132132
133-See [here](../model-providers/top-level/vertexai#embeddings-model) for instructions on how to use Vertex for embeddings.
133+See [here](../model-providers/top-level/vertexai#how-to-configure-vertex-ai-embeddings-models) for instructions on how to use Vertex for embeddings.
134134
135135 ### Mistral
136136
137-See [here](../model-providers/top-level/mistral#embeddings-model) for instructions on how to use Mistral for embeddings.
137+See [here](../model-providers/top-level/mistral#how-to-configure-mistral-embeddings-models) for instructions on how to use Mistral for embeddings.
138138
139139 ### NVIDIA
140140
@@ -142,7 +142,7 @@
142142
143143 ### Bedrock
144144
145-See [here](../model-providers/top-level/bedrock#embeddings-model) for instructions on how to use Bedrock for embeddings.
145+See [here](../model-providers/top-level/bedrock#how-to-configure-amazon-bedrock-embeddings-models) for instructions on how to use Bedrock for embeddings.
146146
147147 ### WatsonX
148148
modified docs/customize/model-roles/reranking.mdx +2 −1
@@ -7,7 +7,7 @@
77
88 A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
99
10-In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../context/codebase.mdx) in order to select the most relevant code snippets after vector search.
10+In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../context/codebase) in order to select the most relevant code snippets after vector search.
1111
1212 ## Recommended reranking models
1313
@@ -131,6 +131,7 @@
131131 models:
132132 - name: Huggingface-tei Reranker
133133 provider: huggingface-tei
134+ model: tei
134135 apiBase: http://localhost:8080
135136 apiKey: <YOUR_TEI_API_KEY>
136137 roles:
modified docs/customize/overview.mdx +3 −3
@@ -13,19 +13,19 @@
1313
1414 Specialized context features for codebase understanding and documentation integration.
1515
16-[Browse Context Features →](/customization/overview#codebase-context)
16+[Browse Context Features →](customize/context/codebase)
1717
1818 ## Deep Dives
1919
2020 Detailed technical explanations of Continue's internal workings and advanced configuration options.
2121
22-[Read Deep Dives →](/customization/overview#configuration)
22+[Read Deep Dives →](/customize/deep-dives/configuration)
2323
2424 ## Model Providers
2525
2626 Configure and optimize different AI model providers for your specific needs and infrastructure.
2727
28-[Configure Providers →](/customization/models#openai)
28+[Configure Providers →](/customize/model-providers/overview)
2929
3030 ## Model Roles
3131
modified docs/customize/telemetry.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Telemetry"
3+description: "Learn about Continue's anonymous telemetry collection practices, what usage data is collected, and how to opt out if you prefer not to share your usage information"
34 ---
45
56 ## Overview
modified docs/docs.json +7 −1
@@ -19,7 +19,8 @@
1919 "pages": [
2020 "index",
2121 "getting-started/overview",
22- "getting-started/install"
22+ "getting-started/install",
23+ "getting-started/quick-start"
2324 ]
2425 },
2526 {
@@ -102,6 +103,7 @@
102103 "group": "Model Providers",
103104 "icon": "server",
104105 "pages": [
106+ "customize/model-providers/overview",
105107 {
106108 "group": "Popular Providers",
107109 "pages": [
@@ -1008,6 +1010,10 @@
10081010 {
10091011 "source": "/customization/overview#documentation-context",
10101012 "destination": "/customize/context/documentation"
1013+ },
1014+ {
1015+ "source": "/customize/model-providers",
1016+ "destination": "/customize/model-providers/overview"
10111017 }
10121018 ]
10131019 }
modified docs/features/agent/context-selection.mdx +5 −0
@@ -1,3 +1,8 @@
1+---
2+title: "Context Selection"
3+description: "Learn how Continue's agent mode selects relevant code context using file content, language server definitions, imports, and recent file history."
4+---
5+
16 You can use the same methods to manually add context as [Chat](/features/chat/context-selection).
27
38 Tool call responses are automatically included as context items. This enables Agent mode to see the result of the previous action and decide what to do next.
modified docs/features/agent/how-it-works.mdx +8 −9
@@ -1,9 +1,9 @@
11 ---
2-title: "How Agent Works"
2+title: "How Agent Mode Works"
33 description: "Agent offers the same functionality as Chat, while also including tools in the request to the model and an interface for handling tool calls and responses."
44 ---
55
6-## The tool handshake
6+## How the Tool Handshake Works
77
88 Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file.
99
@@ -17,19 +17,18 @@
1717 6. The model responds, potentially with another tool call and step 2 begins again
1818
1919 <Info>
20- Tool availability varies by mode:
21- - **Chat mode**: No tools included
22- - **Plan mode**: Only read-only tools included
23- - **Agent mode**: All tools included
20+ Tool availability varies by mode: - **Chat mode**: No tools included - **Plan
21+ mode**: Only read-only tools included - **Agent mode**: All tools included
2422 </Info>
2523
26-## Built-in tools
24+## What Built-in Tools Are Available
2725
2826 Continue includes several built-in tools which provide the model access to IDE functionality.
2927
30-### Plan mode tools (read-only)
28+### What Tools Are Available in Plan Mode (Read-Only)
3129
3230 In Plan mode, only these read-only tools are available:
31+
3332 - **Read file** (`read_file`)
3433 - **Read currently open file** (`read_currently_open_file`)
3534 - **List directory** (`ls`)
@@ -42,7 +41,7 @@
4241 - **View subdirectory** (`view_subdirectory`)
4342 - **Codebase tool** (`codebase_tool`)
4443
45-### Agent mode tools (all tools)
44+### What Tools Are Available in Agent Mode (All Tools)
4645
4746 In Agent mode, all tools are available including the read-only tools above plus:
4847
modified docs/features/agent/how-to-customize.mdx +10 −4
@@ -1,8 +1,14 @@
1-## Add Rules Blocks
1+---
2+title: "How to Customize Agent Mode"
3+description: "Learn how to customize Agent Mode in Continue to better fit your workflow and coding style."
4+sidebarTitle: "Customize Agent"
5+---
6+
7+## How to Add Rules Blocks
28
39 Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
410
5-## Customize System Messages
11+## How to Customize System Messages
612
713 You can customize the system messages for Chat, Agent, and Plan modes using model-level configuration:
814
@@ -17,11 +23,11 @@
1723 basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps."
1824 ```
1925
20-## Add MCP Tools
26+## How to Add MCP Tools
2127
2228 You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
2329
24-## Tool Policies
30+## How to Configure Tool Policies
2531
2632 You can adjust the Agent's tool usage behavior to three options:
2733
modified docs/features/agent/model-setup.mdx +12 −4
@@ -1,6 +1,12 @@
1+---
2+title: "Model Setup for Agent Mode"
3+description: "Learn how to set up models for Agent Mode in Continue, including recommended models and configuration options for optimal performance"
4+sidebarTitle: "Model Setup"
5+---
6+
17 The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup).
28
3-## System Message Tools
9+## How System Message Tools Work
410
511 <Info>
612 System message tools are experimental and may change in future releases.
@@ -8,7 +14,7 @@
814
915 Continue implements an innovative approach called **system message tools** that ensures consistent tool functionality across all models, regardless of their native capabilities. This allows Agent mode to work seamlessly with a wider range of models and providers.
1016
11-### How It Works
17+### How System Message Tools Function
1218
1319 Instead of relying solely on native tool calling APIs (which vary between providers), Continue converts tools into XML format and includes them in the system message. The model generates tool calls as structured XML within its response, which Continue then parses and executes. This approach provides:
1420
@@ -17,21 +23,23 @@
1723 - **Better reliability** - Models that struggle with native tools often perform better with system message tools
1824 - **Seamless switching** - Change between providers without modifying your workflow
1925
20-### Recommended Models
26+### What Models Are Recommended for Agent Mode
2127
2228 For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
2329
2430 **Premium Models:**
31+
2532 - **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
2633 - **GPT-4** models (OpenAI) - Excellent native tool support
2734 - **DeepSeek** models - Strong performance with competitive pricing
2835
2936 **Local Models:**
3037 While more limited in capabilities, these models can work with system message tools:
38+
3139 - Qwen2.5-Coder 32B - Best local option for Agent mode
3240 - Devstral 27B - Good for code-specific tasks
3341 - Smaller models (7B-13B) - May struggle with complex tool interactions
3442
35-### Configuration
43+### How to Configure Agent Mode
3644
3745 Agent mode automatically determines whether to use native or system message tools based on the model's capabilities. No additional configuration is required - simply select your model and Continue handles the rest.
modified docs/features/agent/plan-mode.mdx +13 −8
@@ -1,6 +1,7 @@
11 ---
2-title: "Plan Mode"
3-description: "Explore and understand code safely with read-only tools"
2+title: "Plan Mode in Continue – Safe, Read-Only Code Exploration"
3+sidebarTitle: "Plan Mode"
4+description: "Learn how to use Plan Mode in Continue to explore and understand codebases safely with read-only tools, search, and analysis before making changes"
45 ---
56
67 ## What is Plan mode?
@@ -9,16 +10,17 @@
910
1011 ![Plan mode in action](/images/plan-mode.gif)
1112
12-### Key features
13+### What Are the Key Features of Plan Mode?
1314
1415 - **Read-only tools**: Access files, search, and analyze without risk
1516 - **Safe exploration**: Perfect for understanding unfamiliar codebases
1617 - **Planning focus**: Develop implementation strategies before execution
1718 - **MCP support**: Works with all MCP tools alongside built-in read-only tools
1819
19-### How it works
20+### How Plan Mode Works
2021
2122 Plan mode filters the available tools to only include read-only operations. This means you can:
23+
2224 - Read any file in your project
2325 - Search through code with grep and glob patterns
2426 - View repository structure and diffs
@@ -26,11 +28,12 @@
2628 - Use all MCP tools
2729
2830 But you cannot:
31+
2932 - Create, edit, or delete files
3033 - Run terminal commands
3134 - Make any system changes
3235
33-### Getting started
36+### How to Get Started with Plan Mode
3437
3538 Select "Plan" from the mode selector below the chat input, or use `Cmd/Ctrl + .` to cycle through modes.
3639
@@ -38,12 +41,14 @@
3841
3942 For detailed information about tools and usage, see the [Agent documentation](/features/agent/how-it-works), which covers both Agent and Plan modes.
4043
41-### Common workflow
44+### What Is the Common Workflow for Plan Mode?
4245
4346 1. **Start in Plan mode** to explore and understand
4447 2. **Develop your approach** with the model's help
4548 3. **Switch to Agent mode** when ready to implement
4649
4750 <Tip>
48- Plan mode shares the same interface and context features as Chat and Agent modes. You can use `@` context providers and highlight code just like in other modes.
49-</Tip>
No newline at the end of the file
51+ Plan mode shares the same interface and context features as Chat and Agent
52+ modes. You can use `@` context providers and highlight code just like in other
53+ modes.
54+</Tip>
modified docs/features/agent/quick-start.mdx +43 −25
@@ -1,28 +1,46 @@
11 ---
22 title: "Quick Start"
3+description: "Get started with Continue's Agent mode to automatically implement code changes, fix bugs, and run commands using AI-powered tools that can modify your codebase based on natural language instructions"
34 ---
45
5-## How to use it
6-
76 Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
87
9-### When to use each mode
10-
11-- **Plan mode**: Use when you want to explore code, understand systems, or plan changes without making modifications. Perfect for:
12- - Understanding unfamiliar codebases
13- - Planning complex refactors
14- - Debugging and investigation
15- - Creating implementation strategies
16-
17-- **Agent mode**: Use when you're ready to make changes. Ideal for:
18- - Implementing features
19- - Fixing bugs
20- - Running tests and commands
21- - Executing plans developed in Plan mode
22-
23-### Use Agent
8+<Accordion title="Learn how to choose the right mode" icon="lightbulb">
9+ <Columns cols={3}>
10+ <Card title="Chat Mode" icon="comments">
11+ *Learn and discuss without changing code.*
12+
13+ **Mental Model:** Talking to a knowledgeable colleague
14+
15+ **Best For:** Explaining concepts, comparing approaches, code review discussions.
16+
17+ </Card>
18+
19+ <Card title="Plan Mode" icon="binoculars">
20+ *Safely explore and plan with read-only tools.*
21+
22+ **Mental Model:** Architect surveying before renovation
23+
24+ **Best For:** Understanding a codebase, bug investigation, planning implementations.
25+
26+ </Card>
27+
28+ <Card title="Agent Mode" icon="hammer">
29+ *Make actual changes with full tool access.*
30+
31+ **Mental Model:** Contractor executing approved blueprints
32+
33+ **Best For:** Implementing features, fixing bugs, running tests and commands.
34+
35+ </Card>
36+
37+ </Columns>
38+</Accordion>
39+
40+### How to Use Agent Mode
2441
2542 You can switch to `Agent` in the mode selector below the chat input box. The mode selector offers three options:
43+
2644 - **Chat**: No tools available, pure conversation
2745 - **Plan**: Read-only tools for safe exploration and planning
2846 - **Agent**: All tools available for making changes
@@ -30,20 +48,20 @@
3048 ![How to select agent mode](/images/mode-select-agent.png)
3149
3250 <Info>
33- If Agent or Plan is disabled with a `Not Supported` message, the selected model or
34- provider doesn't support tools, or Continue doesn't yet support tools with it.
35- See [Model Blocks](/customization/models) for more information.
51+ If Agent or Plan is disabled with a `Not Supported` message, the selected
52+ model or provider doesn't support tools, or Continue doesn't yet support tools
53+ with it. See [Model Blocks](/customization/models) for more information.
3654 </Info>
3755
3856 <Tip>
3957 Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between modes.
4058 </Tip>
4159
42-### Chat with Agent
60+### How to Chat with Agent
4361
44-Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
62+Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#how-to-include-code-context).
4563
46-#### Use natural language
64+#### How to Use Natural Language with Agent
4765
4866 With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say
4967
@@ -51,7 +69,7 @@
5169
5270 Agent will then decide which tools to use to get the job done.
5371
54-## Give Agent permission
72+## How to Give Agent Permission
5573
5674 By default, Agent will ask permission when it wants to use a tool. Click `Continue` to allow Agent mode to proceed with the tool call or `Cancel` to reject it.
5775
@@ -59,7 +77,7 @@
5977
6078 You can use tool policies to exclude or make usage automatic for specific tools. See [MCP Tools](/customization/mcp-tools) for more background.
6179
62-## View Tool Responses
80+## How to View Tool Responses
6381
6482 Any data returned from a tool call is automatically fed back into the model as a context item. Most errors are also caught and returned, so that Agent mode can decide how to proceed.
6583
modified docs/features/autocomplete/context-selection.mdx +9 −4
@@ -1,17 +1,22 @@
1+---
2+title: "Context Selection"
3+description: "Learn how Continue's autocomplete selects relevant code context using file content, language server definitions, imports, and recent file history."
4+---
5+
16 Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt:
27
3-## File prefix/suffix
8+## File Prefix and Suffix Context
49
510 We will always include the code from your file prior to and after the cursor position.
611
7-## Definitions from the Language Server Protocol
12+## Language Server Protocol (LSP) Definitions
813
914 Similar to how you can use cmd/ctrl + click in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type.
1015
11-## Imported files
16+## Imported File Context
1217
1318 Because there are often many imports, we can't include all of them. Instead, we look for symbols around your cursor that have matching imports and use that as context.
1419
15-## Recent files
20+## Recent File Context
1621
1722 We automatically consider recently opened or edited files and include snippets that are relevant to the current completion.
modified docs/features/autocomplete/how-it-works.mdx +10 −10
@@ -1,27 +1,27 @@
11 ---
2-title: "How Autocomplete Works"
3-description: "Autocomplete is a that uses a combination of retrieval methods and response processing techniques. The system can be understood in roughly three parts."
2+title: "How Autocomplete Works in Continue"
3+sidebarTitle: "How Autocomplete Works"
4+description: "Understand how Continue's autocomplete works, including timing optimization, context retrieval from your codebase, and filtering to improve AI code suggestions."
45 ---
56
6-## Timing
7+## Timing Optimization for Autocomplete
78
89 In order to display suggestions quickly, without sending too many requests, we do the following:
910
1011 - Debouncing: If you are typing quickly, we won't make a request on each keystroke. Instead, we wait until you have finished.
1112 - Caching: If your cursor is in a position that we've already generated a completion for, this completion is reused. For example, if you backspace, we'll be able to immediately show the suggestion you saw before.
1213
13-## Context
14+## Context Retrieval from Your Codebase
1415
1516 Continue uses a number of retrieval methods to find relevant snippets from your codebase to include in the prompt.
1617
17-## Filtering
18+## Filtering and Post-Processing AI Suggestions
1819
1920 Language models aren't perfect, but can be made much closer by adjusting their output. We do extensive post-processing on responses before displaying a suggestion, including:
2021
21-- filtering out special tokens
22-- stopping early when re-generating code
23-- fixing indentation
24-
25-We will also occasionally entirely filter out responses if they are bad. This is often due to extreme repetition.
22+- Removing special tokens
23+- Stopping early when regenerating code to avoid long, irrelevant output
24+- Fixing indentation for proper formatting
25+- Occasionally discarding low-quality responses, such as those with excessive repetition
2626
2727 You can learn more about how it works in the [Autocomplete deep dive](/customization/models#autocomplete).
modified docs/features/autocomplete/how-to-customize.mdx +6 −1
@@ -1,3 +1,8 @@
1-Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/deep-dives/settings/) to manage these settings.
1+---
2+title: “Customize Autocomplete Settings in Continue”
3+description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.”
4+---
5+
6+Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
27
38 For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
modified docs/features/autocomplete/model-setup.mdx +8 −2
@@ -1,6 +1,12 @@
1+---
2+title: "Recommended Models for Autocomplete in Continue"
3+description: "Choose the best autocomplete model for Continue, including hosted high-performance options, fast speed/quality tradeoffs, and local privacy-first models."
4+sidebarTitle: "Recommended Autocomplete Models"
5+---
6+
17 Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
28
3-## Recommended Models
9+## Recommended Models for Autocomplete in Continue
410
511 ### Hosted (Best Performance)
612
@@ -46,4 +52,4 @@
4652
4753 ## Model Compatibility
4854
49-To see a complete list of models and their capabilities, visit our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).
55+To see a complete list of models and their capabilities, visit our [Model Capabilities guide](/customize/deep-dives/model-capabilities).
modified docs/features/autocomplete/quick-start.mdx +10 −6
@@ -1,23 +1,27 @@
11 ---
2-title: "Quick Start"
2+title: "Quick Start with Continue Autocomplete"
3+description: "Learn how to quickly start using Continue's AI autocomplete in your IDE, including enabling inline code suggestions and keyboard shortcuts for accepting, rejecting, or partially accepting completions."
4+sidebarTitle: "Autocomplete Quick Start"
35 ---
46
5-## How to use it
7+## How to Enable and Use Continue Autocomplete
68
79 Autocomplete provides inline code suggestions as you type. To enable it, simply click the "Continue" button in the status bar at the bottom right of your IDE or ensure the "Enable Tab Autocomplete" option is checked in your IDE settings.
810
9-### Accepting a full suggestion
11+## Keyboard Shortcuts for Autocomplete
12+
13+### Accept a Full Suggestion
1014
1115 Accept a full suggestion by pressing `Tab`
1216
13-### Rejecting a full suggestion
17+### Reject a Full Suggestion
1418
1519 Reject a full suggestion with `Esc`
1620
17-### Partially accepting a suggestion
21+### Partially Accept a Suggestion
1822
1923 For more granular control, use `cmd/ctrl` + `→` to accept parts of the suggestion word-by-word.
2024
21-### Forcing a suggestion (VS Code)
25+### Force a Suggestion (VS Code)
2226
2327 If you want to trigger a suggestion immediately without waiting, or if you've dismissed a suggestion and want a new one, you can force it by using the keyboard shortcut **`cmd/ctrl` + `alt` + `space`**.
modified docs/features/chat/context-selection.mdx +16 −10
@@ -1,39 +1,45 @@
1-## Input
1+---
2+title: "Chat Mode Context Selection"
3+sidebarTitle: "Context Selection"
4+description: "Learn how Continue selects relevant context for your chat requests, including text input, highlighted code, active files."
5+---
6+
7+## How to Use Text Input
28
39 Typing a question or instructions into the input box is the only required context.
410
5-## Highlighted Code
11+## How to Include Highlighted Code
612
713 The highlighted code you've selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt.
814
9-## Active File
15+## How to Include the Active File
1016
1117 You can include the currently open file as context by pressing opt/alt + enter when you send your request.
1218
13-## Specific File
19+## How to Include a Specific File
1420
1521 You can include a specific file in your current workspace by typing '@Files' and selecting the file.
1622
17-## Specific Folder
23+## How to Include a Specific Folder
1824
1925 You can include a folder in your current workspace by typing '@Folder' and selecting the directory.
2026
21-## Codebase Search
27+## How to Use Codebase Search
2228
2329 You can automatically include relevant files from your codebase by typing '@Codebase'.
2430
25-## Documentation Site
31+## How to Include Documentation Sites
2632
2733 You can include a documentation site as context by typing '@Docs' and selecting the site.
2834
29-## Terminal Contents
35+## How to Include Terminal Contents
3036
3137 You can include the contents of the terminal in your IDE by typing '@Terminal'.
3238
33-## Git Diff
39+## How to Include Git Diff
3440
3541 You can include all of the changes you've made to your current branch by typing '@Git Diff'.
3642
37-## Other Context
43+## How to Use Other Context Providers
3844
3945 You can see a full list of built-in context providers [here](/customize/custom-providers) and learn about how to create your own context provider [here](/guides/build-your-own-context-provider).
modified docs/features/chat/how-it-works.mdx +9 −9
@@ -3,7 +3,7 @@
33 description: "Continue's Chat feature provides a conversational interface with AI models directly in your IDE sidebar."
44 ---
55
6-## Core Functionality
6+## How Chat Core Functionality Works
77
88 When you start a chat conversation, Continue:
99
@@ -12,22 +12,22 @@
1212 3. **Sends to Model**: Prompts the configured AI model for a response
1313 4. **Streams Response**: Returns the AI response in real-time to the sidebar
1414
15-## Context Management
15+## How Context Management Works
1616
17-### Automatic Context
17+### What Context Is Automatically Included
1818
1919 - Selected code in your editor
2020 - Current file context when relevant
2121 - Previous conversation history in the session
2222
23-### Manual Context
23+### How to Add Manual Context
2424
2525 - `@Codebase` - Search and include relevant code from your project
2626 - `@Docs` - Include documentation context
2727 - `@Files` - Reference specific files
2828 - Custom context providers
2929
30-## Response Handling
30+## How Response Handling Works
3131
3232 Each code section in the AI response includes action buttons:
3333
@@ -35,19 +35,19 @@
3535 - **Insert at cursor** - Add code at cursor position
3636 - **Copy** - Copy code to clipboard
3737
38-## Session Management
38+## How Session Management Works
3939
4040 - Use `Cmd/Ctrl + L` (VS Code) or `Cmd/Ctrl + J` (JetBrains) to start a new session
4141 - Clears all previous context for a fresh start
4242 - Helpful for switching between different tasks
4343
44-## Advanced Features
44+## What Advanced Features Are Available
4545
46-### Prompt Inspection
46+### How to Use Prompt Inspection
4747
4848 View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting) for debugging and optimization.
4949
50-### Context Providers
50+### How to Learn More About Context Providers
5151
5252 Learn more about how context providers work:
5353
modified docs/features/chat/how-to-customize.mdx +7 −0
@@ -1,3 +1,10 @@
1+---
2+title: "How to Customize Chat"
3+description: "Learn how to customize the Chat feature in Continue to better suit your workflow."
4+---
5+
6+## How to Customize Chat
7+
18 There are a number of different ways to customize Chat:
29
310 - Add a `rules` block to give the model persistent instructions through the system prompt
modified docs/features/chat/model-setup.mdx +5 −5
@@ -3,7 +3,7 @@
33 - used with Edit mode by default but can be switched
44 - always used with Agent mode if the model supports tool calling
55
6-## Recommended Models
6+## What Models Are Recommended for Chat?
77
88 Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
99
@@ -14,7 +14,7 @@
1414 3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
1515 4. Click `Reload config` in the assistant selector in the Continue IDE extension
1616
17-#### Other hosted models
17+### What Other Hosted Models Are Available?
1818
1919 These models have varying tool calling and reasoning capabilities.
2020
@@ -67,7 +67,7 @@
6767 3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
6868 4. Click `Reload config` in the assistant selector in the Continue IDE extension
6969
70-#### Local models
70+### What Local Models Are Available?
7171
7272 These models can be run on your computer if you have enough VRAM.
7373
@@ -99,6 +99,6 @@
9999
100100 For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
101101
102-## Model Compatibility
102+## How to Check Model Compatibility
103103
104-To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).
104+To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities).
modified docs/features/chat/quick-start.mdx +10 −8
@@ -1,12 +1,14 @@
11 ---
2-title: "Quick Start"
2+title: "Chat Mode Quick Start"
3+sidebarTitle: "Quick Start"
4+description: "Get started with Continue's AI chat assistant to solve coding problems directly in your IDE, with features for code context sharing, codebase search, and applying generated solutions to your files"
35 ---
46
57 Chat makes it easy to ask for help from an AI without leaving your IDE. Get explanations, generate code, and iterate on solutions conversationally.
68
7-## Basic Usage
9+## How to Use Chat - Basic Usage
810
9-### 1. Start a Conversation
11+### How to Start a Conversation
1012
1113 Type your question or request in the chat input and press Enter.
1214
@@ -16,7 +18,7 @@
1618 - "How do I handle errors in this code?"
1719 - "Generate a test for this component"
1820
19-### 2. Include Code Context
21+### How to Include Code Context
2022
2123 Select code in your editor, then use the keyboard shortcut to include it in your chat:
2224
@@ -27,7 +29,7 @@
2729
2830 Press `Cmd/Ctrl + J` to send selected code to chat
2931
30-### 3. Use @ for Additional Context
32+### How to Use @ for Additional Context
3133
3234 Type `@` to include specific context:
3335
@@ -36,7 +38,7 @@
3638 - `@Files` - Reference specific files
3739 - `@Terminal` - Include terminal output
3840
39-## Working with Responses
41+## How to Work with Responses
4042
4143 When the AI provides code in its response, you'll see action buttons:
4244
@@ -44,7 +46,7 @@
4446 - **Insert at cursor** - Add code at your cursor position
4547 - **Copy** - Copy code to clipboard
4648
47-## Pro Tips
49+## What Are the Pro Tips for Chat
4850
4951 ### Start Fresh
5052
@@ -66,7 +68,7 @@
6668 - Request modifications
6769 - Provide additional context
6870
69-## Common Use Cases
71+## What Are Common Use Cases for Chat
7072
7173 ### Code Explanation
7274
modified docs/features/edit/context-selection.mdx +9 −3
@@ -1,7 +1,13 @@
1-## Input
1+---
2+title: "Context Selection in Edit Mode"
3+sidebarTitle: "Context Selection"
4+description: "Learn how Continue's Edit mode selects relevant code context using file content, language server"
5+---
26
3-The input you provide is included in the prompt.
7+## How to Use Text Input
48
5-## Code to Edit
9+Typing a question or instructions into the input box is the only required context.
10+
11+## What Context is Included in Edit Mode
612
713 The **entire contents** of the current file are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
modified docs/features/edit/how-it-works.mdx +7 −1
@@ -3,7 +3,13 @@
33 description: "Using the highlighted code, the contents of the current file containing your highlight, and your input instructions, we prompt the model to edit the code according to your instructions. No other additional context is provided to the model."
44 ---
55
6-The model response is then streamed directly back to the highlighted range in your code, where we apply a diff formatting to show the proposed changes.
6+## How Edit Functionality Works
7+
8+When you start an edit session, Continue:
9+
10+1. **Gathers Context**: Uses the highlighted code and the current file contents
11+2. **Prompts the Model**: Sends the gathered context and your input instructions to the model
12+3. **Applies Changes**: The model response is then streamed directly back to the highlighted range in your code, where we apply a diff formatting to show the proposed changes.
713
814 If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes.
915
modified docs/features/edit/how-to-customize.mdx +7 −1
@@ -1,4 +1,10 @@
1-## Setting active Edit/Apply model
1+---
2+title: "How to Customize Edit Functionality"
3+description: "Learn how to customize the Edit functionality in Continue to better suit your workflow."
4+sidebarTitle: "Customize Edit"
5+---
6+
7+## How to Set Active Edit/Apply Model
28
39 You can configure particular models from your Assistant to be used for Edit and Apply requests.
410
modified docs/features/edit/model-setup.mdx +9 −3
@@ -1,8 +1,14 @@
1+---
2+title: "How to Set Up Edit Models"
3+sidebarTitle: "Set Up Edit Models"
4+description: "Learn how to set up and customize models for Edit functionality in Continue."
5+---
6+
17 The model you set up for Chat mode will be used for Edit mode by default.
28
39 The recommended models and how to set them up can be found [here](/features/chat/model-setup).
410
5-## Apply Model
11+## How to Set Up an Apply Model
612
713 We also recommend setting up an Apply model for the best Edit experience.
814
@@ -11,6 +17,6 @@
1117 - [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
1218 - [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
1319
14-## Model Compatibility
20+## How to Determine Model Compatibility
1521
16-For a complete overview of which models support various features, see our [Model Capabilities guide](/customize/deep-dives/model-capabilities#model-compatibility-matrix).
22+For a complete overview of which models support various features, see our [Model Capabilities guide](/customize/deep-dives/model-capabilities).
modified docs/features/edit/quick-start.mdx +10 −7
@@ -1,8 +1,10 @@
11 ---
2-title: "Quick Start"
2+title: "Quick Start with Continue Edit"
3+sideBarTitle: "Quick Start"
4+description: "Get started with Continue's Edit feature for making quick, targeted code changes directly in your file using AI suggestions, with keyboard shortcuts for accepting or rejecting modifications"
35 ---
46
5-## How to use it
7+## How to Continue Edit
68
79 Edit is a convenient way to make quick changes to specific code and files. Select code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject.
810
@@ -12,15 +14,17 @@
1214 - Generating unit tests
1315 - Refactoring functions or methods
1416
15-## Highlight code and activate
17+## How to Activate Edit
1618
1719 Highlight the block of code you would like to modify and press `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to activate Edit mode. You can also press `Cmd/Ctrl+I` with no code highlighted, which will default to inserting code at the current cursor location.
1820
19-## Describe code changes
21+Once you've activated Edit, you're ready to provide instructions.
22+
23+### How to Provide Instructions
2024
2125 Describe the changes you would like the model to make to your highlighted code. For edits, a good prompt should be relatively short and concise. For longer, more complex tasks, we recommend using [Chat](/features/chat/quick-start).
2226
23-## Accept or reject changes
27+### How to Accept or Reject Changes
2428
2529 Proposed changes appear as inline diffs within your highlighted text.
2630
@@ -30,7 +34,6 @@
3034
3135 If you want to request a new suggestion for the same highlighted code section, you can use `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to re-prompt the model.
3236
33-
34-## Jetbrains
37+## How to Use Edit in Jetbrains
3538
3639 In Jetbrains, Edit is implemented as an inline popup. See the header GIF example.
modified docs/features/plan/how-it-works.mdx +4 −1
@@ -46,7 +46,10 @@
4646 In addition to built-in read-only tools, Plan mode also supports all MCP (Model Context Protocol) tools. This allows integration with external services that provide additional context or analysis capabilities without modifying your local environment.
4747
4848 <Info>
49- While Plan mode restricts built-in tools to read-only operations, MCP tools are not filtered by Continue. Some MCP tools may have write capabilities that could modify your system or external services. Always verify what actions your MCP tools can perform before using them in Plan mode.
49+ While Plan mode restricts built-in tools to read-only operations, MCP tools
50+ are not filtered by Continue. Some MCP tools may have write capabilities that
51+ could modify your system or external services. Always verify what actions your
52+ MCP tools can perform before using them in Plan mode.
5053 </Info>
5154
5255 ## The planning workflow
modified docs/features/plan/quick-start.mdx +8 −4
@@ -1,5 +1,6 @@
11 ---
22 title: "Quick Start"
3+description: "Get started with Continue's Plan mode to safely explore codebases, plan refactors, debug issues, and develop implementation strategies without modifying code before switching to execution"
34 ---
45
56 ## How to use it
@@ -14,17 +15,18 @@
1415
1516 <Info>
1617 If Plan is disabled with a `Not Supported` message, the selected model or
17- provider doesn't support tools. See [Model Setup](/features/plan/model-setup)
18+ provider doesn't support tools. See [Model Setup](/features/agent/model-setup)
1819 for more information.
1920 </Info>
2021
2122 ### Chat with Plan
2223
23-Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
24+Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#how-to-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#how-to-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#how-to-include-code-context).
2425
2526 #### What makes Plan different
2627
2728 Unlike Agent mode, Plan mode:
29+
2830 - Only uses read-only tools (file reading, searching, analysis)
2931 - Cannot modify, create, or delete files
3032 - Focuses on understanding and planning rather than execution
@@ -33,6 +35,7 @@
3335 ### Common use cases
3436
3537 Plan mode is ideal for:
38+
3639 - **Code exploration**: Understanding how a codebase works
3740 - **Planning refactors**: Analyzing impact before making changes
3841 - **Debugging**: Investigating issues without modifying code
@@ -56,5 +59,6 @@
5659 When you're ready to implement your plan, simply switch to Agent mode using the mode selector or keyboard shortcut (`Cmd/Ctrl + .`). The conversation context carries over, so Agent mode can immediately start implementing the plan you developed.
5760
5861 <Tip>
59- Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between Agent, Chat, and Plan modes.
60-</Tip>
No newline at the end of the file
62+ Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between Agent, Chat,
63+ and Plan modes.
64+</Tip>
modified docs/getting-started/extensions.mdx +1 −1
@@ -3,4 +3,4 @@
33 description: "Continue offers two ways to configure your AI assistants"
44 ---
55
6-This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)
No newline at the end of the file
6+This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)
modified docs/getting-started/overview.mdx +0 −1
@@ -57,7 +57,6 @@
5757 </Tab>
5858 </Tabs>
5959
60-
6160 ## AI Coding Assistants
6261
6362 Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).
added docs/getting-started/quick-start.mdx +265 −0
@@ -0,0 +1,265 @@
1+---
2+title: "Quick Start Tutorial"
3+description: "Learn Continue's core features through hands-on exercises. Get started with Autocomplete, Edit, Chat, and Agent in minutes."
4+sidebarTitle: "Quick Start"
5+---
6+
7+Welcome to Continue! This interactive tutorial will guide you through all four core features using practical examples. Follow along step-by-step to learn more about Continue's capabilities.
8+
9+<Info>
10+ **Prerequisites**: Make sure you have [installed
11+ Continue](/getting-started/install) and [signed
12+ in](https://auth.continue.dev/) to get started.
13+</Info>
14+
15+---
16+
17+## 🔄 Autocomplete
18+
19+**What it does**: Provides intelligent inline code suggestions as you type, powered by AI.
20+
21+<Steps>
22+<Step title="Create a Test File">
23+Create a new file called `tutorial.js` (or use any language you prefer) in your IDE
24+</Step>
25+
26+<Step title="Try Autocomplete">
27+Copy this starter code and place your cursor at the end of the comment:
28+
29+```javascript
30+// TODO: Implement a sorting algorithm function
31+function sortingAlgorithm(arr) {
32+ // Place cursor here and press Enter
33+}
34+```
35+
36+Press **Enter** and watch Continue suggest code completions. Press **Tab** to accept suggestions.
37+
38+</Step>
39+
40+<Step title="See the Magic">
41+Continue will intelligently suggest function implementations based on the context and comment.
42+</Step>
43+</Steps>
44+
45+<Tip>
46+ Autocomplete works best when you provide clear function names, comments, or
47+ type annotations that give context about your intent.
48+</Tip>
49+
50+---
51+
52+## ✏️ Edit
53+
54+**What it does**: Make quick, targeted changes to specific code sections using natural language instructions.
55+
56+<Steps>
57+<Step title="Add Sample Code">
58+Paste this bubble sort implementation in your file:
59+
60+```javascript
61+function sortingAlgorithm(x) {
62+ for (let i = 0; i < x.length; i++) {
63+ for (let j = 0; j < x.length - 1; j++) {
64+ if (x[j] > x[j + 1]) {
65+ let temp = x[j];
66+ x[j] = x[j + 1];
67+ x[j + 1] = temp;
68+ }
69+ }
70+ }
71+ return x;
72+}
73+```
74+
75+</Step><Step title="Highlight the Function">
76+**Highlight** the entire function in your editor
77+</Step>
78+
79+<Step title="Open Edit Mode">Press **Cmd/Ctrl + I** to open Edit mode</Step>
80+
81+<Step title="Give Instructions">
82+ Type: `"make this more readable and add TypeScript types"`
83+</Step>
84+
85+<Step title="Watch the Magic">
86+ Watch Continue refactor your code automatically!
87+</Step>
88+
89+<Step title="Review Changes">
90+Continue will show you a diff of the proposed changes. Accept or reject individual changes as needed.
91+</Step>
92+</Steps>
93+
94+<Note>
95+ Edit is perfect for refactoring, adding documentation, fixing bugs, or
96+ converting between languages/frameworks.
97+</Note>
98+
99+---
100+
101+## 💬 Chat
102+
103+**What it does**: Interactive AI assistant that can analyze code, answer questions, and provide guidance without leaving your IDE.
104+
105+<Steps>
106+<Step title="Add Another Function">
107+Add this second sorting function to your file:
108+
109+```javascript
110+function sortingAlgorithm2(x) {
111+ for (let i = 0; i < x.length; i++) {
112+ for (let j = 0; j < x.length - 1; j++) {
113+ if (x[j] > x[j + 1]) {
114+ let temp = x[j];
115+ x[j] = x[j + 1];
116+ x[j + 1] = temp;
117+ }
118+ }
119+ }
120+ return x;
121+}
122+```
123+
124+</Step>
125+<Step title="Start a Conversation">
126+1. **Highlight** the function
127+2. Use the keyboard shortcuts below to add it to Chat.
128+3. Ask: `"What sorting algorithm is this and how can I optimize it?"`
129+</Step>
130+
131+<Step title="Explore Further">
132+Try these follow-up questions:
133+- `"Show me how to implement quicksort instead"`
134+- `"What's the time complexity of this algorithm?"`
135+- `"Can you write unit tests for this function?"`
136+</Step>
137+</Steps>
138+
139+### Chat Keyboard Shortcuts
140+
141+<Tabs>
142+<Tab title="VS Code">
143+
144+**Cmd/Ctrl + L**
145+New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus
146+
147+**Cmd/Ctrl + Shift + L**
148+Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus
149+
150+</Tab>
151+<Tab title="JetBrains IDEs">
152+
153+**Cmd/Ctrl + J**
154+New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus
155+
156+**Cmd/Ctrl + Shift + J**
157+Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus
158+
159+</Tab>
160+</Tabs>
161+
162+<Tip>
163+ Use Chat for code reviews, debugging help, learning new concepts, or
164+ brainstorming solutions to complex problems.
165+</Tip>
166+
167+---
168+
169+## 🤖 Agent
170+
171+**What it does**: An autonomous coding assistant that can read files, make changes, run commands, and handle complex multi-step tasks.
172+
173+<Steps>
174+<Step title="Switch to Agent Mode">
175+1. Open the Continue panel
176+2. Click the **dropdown** in the bottom left of the input box
177+3. Select **"Agent"** mode
178+</Step>
179+
180+<Step title="Give Agent a Complex Task">
181+ Try this prompt: ``` "Write comprehensive unit tests for the sorting functions
182+ in this file. Create the tests in a new file using Jest, and make sure to test
183+ edge cases like empty arrays and single elements." ```
184+</Step>
185+
186+<Step title="Watch Agent Work">
187+Agent will:
188+- ✅ Analyze your existing code
189+- ✅ Create a new test file
190+- ✅ Write comprehensive tests
191+- ✅ Handle setup and imports
192+- ✅ Explain what it's doing at each step
193+</Step>
194+</Steps>
195+
196+<Warning>
197+ Agent has powerful capabilities including file creation and modification.
198+ Always review Agent's changes before accepting them.
199+</Warning>
200+
201+---
202+
203+## 🚀 Next Steps
204+
205+Congratulations! You've experienced all four core Continue features. Here's what to explore next:
206+
207+<CardGroup cols={2}>
208+ <Card title="Customize Your Setup" icon="gear" href="/customize/overview">
209+ Configure models, add context providers, and personalize your workflow
210+ </Card>
211+ <Card
212+ title="Advanced Features"
213+ icon="rocket"
214+ href="/features/agent/quick-start"
215+ >
216+ Dive deeper into Agent capabilities and advanced use cases
217+ </Card>
218+ <Card
219+ title="Model Providers"
220+ icon="brain"
221+ href="/customize/model-providers/overview"
222+ >
223+ Connect your preferred AI models and providers
224+ </Card>
225+ <Card
226+ title="Join Community"
227+ icon="users"
228+ href="https://discord.gg/NWtdYexhMs"
229+ >
230+ Get help and share experiences with other Continue users
231+ </Card>
232+</CardGroup>
233+
234+---
235+
236+## 📚 Feature Deep Dives
237+
238+Ready to master specific features? Check out these detailed guides:
239+
240+<AccordionGroup>
241+ <Accordion title="Autocomplete Deep Dive">
242+ Learn about [configuring autocomplete
243+ models](/customize/model-roles/autocomplete), [fine-tuning
244+ suggestions](/customize/deep-dives/autocomplete), and [troubleshooting
245+ common issues](/troubleshooting).
246+ </Accordion>
247+
248+<Accordion title="Chat & Agent Best Practices">
249+ Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub
250+ v. local assistants](/guides/understanding-assistants), and [custom slash
251+ commands](/customize/deep-dives/slash-commands).
252+</Accordion>
253+
254+ <Accordion title="Enterprise & Teams">
255+ Explore [Hub Assistants](/hub/assistants/intro), [organization
256+ management](/hub/governance/creating-an-org), and [sharing
257+ configurations](/hub/sharing).
258+ </Accordion>
259+</AccordionGroup>
260+
261+<Info>
262+ **Need help?** Check our [troubleshooting guide](/troubleshooting) or ask a
263+ question in our [community
264+ discussions](https://github.com/continuedev/continue/discussions).
265+</Info>
modified docs/guides/build-your-own-context-provider.mdx +9 −8
@@ -1,9 +1,9 @@
11 ---
2-title: "Build Your Own Context Provider"
3-description: "Continue offers several way to provide your custom context to the extension."
2+title: "How to Build Your Own Context Provider"
3+description: "Learn how to create custom context providers for Continue using HTTP servers, CustomContextProvider API, or VSCode extensions to provide tailored context to your AI assistant"
44 ---
55
6-## HTTP Context Provider
6+## How to Create an HTTP Context Provider
77
88 Continue can retrieve context from a custom HTTP server that you create and serve. Add the `@HTTP` context provider to your configuration like this:
99
@@ -42,11 +42,11 @@
4242 <Info>
4343 The following methods for creating custom context providers are deprecated. We
4444 recommend using HTTP context providers, [MCP
45- Servers](/customization/mcp-tools), and [Prompts](/customization/prompts)
45+ Servers](/customize/deep-dives/mcp), and [Prompts](/customize/deep-dives/prompts)
4646 where possible.
4747 </Info>
4848
49-## Using CustomContextProvider
49+## How to Use CustomContextProvider
5050
5151 Custom context providers can be implemented in a `config.ts` placed in your Continue global directory (`~/.continue` for MacOS, `%USERPROFILE%/.continue` for Windows). You can implement the `CustomContextProvider` interface in your `config.ts`
5252
@@ -76,7 +76,7 @@
7676
7777 This is automatically appended to your configuration.
7878
79-### Custom Context Providers with Submenu or Query
79+### How to Create Custom Context Providers with Submenu or Query
8080
8181 There are 3 types of context providers: "normal", "query", and "submenu". The "normal" type is the default, and is what we've seen so far.
8282
@@ -97,7 +97,7 @@
9797 3. The `id` of the chosen `ContextSubmenuItem` is passed to `getContextItems` as the `query` argument. In this case it is the filepath of the README.
9898 4. The `getContextItems` function can then use the `query` to retrieve the full contents of the README and format the content before returning the context item which will be included in the prompt.
9999
100-### Importing outside modules
100+### How to Import Outside Modules
101101
102102 To include outside Node modules in your config.ts, run `npm install <module_name>` from the `~/.continue` directory, and then import them in config.ts.
103103
@@ -116,6 +116,7 @@
116116 - `renderInlineAs` (optional): The string that will be rendered inline at the top of the prompt. If no value is provided, the `displayTitle` will be used. An empty string can be provided to prevent rendering the default `displayTitle`.
117117
118118 - `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments:
119+
119120 - `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents
120121 - `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding
121122 - `extras.llm`: The current default LLM, which you can use to make completion requests
@@ -124,7 +125,7 @@
124125
125126 - `loadSubmenuItems` (optional): A function that returns a list of `ContextSubmenuItem`s to display in a submenu. It is given access to an `IDE`, the same that is passed to `getContextItems`. .
126127
127-## Extension API for VSCode
128+## How to Use Extension API for VSCode
128129
129130 Continue exposes an API for registering context providers from a 3rd party VSCode extension. This is useful if you have a VSCode extension that provides some additional context that you would like to use in Continue. To use this API, add the following to your `package.json`:
130131
modified docs/guides/cli.mdx +14 −13
@@ -1,6 +1,7 @@
11 ---
2-title: "Continue CLI (cn)"
3-description: "Context engineering on the command line"
2+title: "How to Use Continue CLI (cn)"
3+sidebarTitle: "Continue CLI (cn)"
4+description: "Learn how to use Continue's command-line interface for context engineering, automated coding tasks, and headless development workflows with customizable models, rules, and tools"
45 ---
56
67 <Warning>Continue CLI (cn) is currently in Alpha</Warning>
@@ -29,7 +30,7 @@
2930 cn -p "Generate a conventional commit name for the current git changes"
3031 ```
3132
32-## Basic usage
33+## How to Use Continue CLI - Basic Usage
3334
3435 Out of the box, `cn` comes with tools that let it understand your codebase, edit files, run terminal commands, and more (if you approve). You can ask `cn` to:
3536
@@ -43,7 +44,7 @@
4344
4445 If you want to resume a previous conversation, run `cn --resume`.
4546
46-## Headless mode (`-p` flag)
47+## How to Use Headless Mode (`-p` flag)
4748
4849 In headless mode, `cn` will only output its final response, making it perfect for Unix Philosophy-style scripting and automation. For example, you could pipe your git diff into `cn` to generate a commit message, and write this to a file:
4950
@@ -51,25 +52,25 @@
5152 echo "$(git diff) Generate a conventional commit name for the current git changes" | cn -p > commit-message.txt
5253 ```
5354
54-## Configuration
55+## How to Configure Continue CLI
5556
56-`cn` uses [`config.yaml`](./reference.mdx), the exact same configuration file as Continue. This means that you can log in to [Continue Hub](./hub/introduction.mdx) or use your existing local configuration.
57+`cn` uses [`config.yaml`](/reference), the exact same configuration file as Continue. This means that you can log in to [Continue Hub](/hub/introduction) or use your existing local configuration.
5758
5859 To switch between configurations, you can use the `/config` slash command in `cn`, or you can start it with the `--config` flag (e.g. `cn --config continuedev/default-agent` or `cn --config ~/.continue/config.yaml`).
5960
60-### Models
61+### How to Add Custom Models
6162
62-Learn how to add custom models [here](./customization/models.mdx). Then, you can use the `/model` slash command to switch between them in `cn`.
63+Learn how to add custom models [here](/customize/overview). Then, you can use the `/model` slash command to switch between them in `cn`.
6364
64-### Rules
65+### How to Configure Rules
6566
66-`cn` supports [rules](./customize/deep-dives/rules.mdx) in the same way as the Continue IDE extensions. You can also use the `--rule` flag to manually include a rule from the hub. For example, `cn --rule nate/spanish` will tell `cn` to use [this rule](https://hub.continue.dev/nate/spanish) to always speak in Spanish.
67+`cn` supports [rules](/customize/deep-dives/rules) in the same way as the Continue IDE extensions. You can also use the `--rule` flag to manually include a rule from the hub. For example, `cn --rule nate/spanish` will tell `cn` to use [this rule](https://hub.continue.dev/nate/spanish) to always speak in Spanish.
6768
68-### Tools
69+### How to Configure Tools
6970
70-`cn` supports MCP tools, which can be configured in the [same way](./customize/deep-dives/mcp.mdx) as with the Continue IDE extensions.
71+`cn` supports MCP tools, which can be configured in the [same way](/customize/deep-dives/mcp) as with the Continue IDE extensions.
7172
72-#### Tool Permissions
73+#### How to Set Tool Permissions
7374
7475 `cn` includes a tool permission system to make sure you approve of the agent's actions. It will begin with minimal permissions but as you approve tool calls, it will add policies to `~/.continue/permissions.yaml` to remember your preferences.
7576
modified docs/guides/custom-code-rag.mdx +9 −9
@@ -1,19 +1,19 @@
11 ---
2-title: "Custom code RAG"
3-description: "While Continue comes with out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this."
2+title: "How to Build Custom Code RAG"
3+description: "Learn how to build a custom retrieval-augmented generation (RAG) system for code using vector databases like LanceDB, embeddings models like voyage-code-3, and chunking strategies for better code search and context"
44 ---
55
6-## Step 1: Choose an embeddings model
6+## Step 1: How to Choose an Embeddings Model
77
88 If possible, we recommend using [`voyage-code-3`](https://docs.voyageai.com/docs/embeddings), which will give the most accurate answers of any existing embeddings model for code. You can obtain an API key [here](https://dash.voyageai.com/api-keys). Because their API is [OpenAI-compatible](https://docs.voyageai.com/reference/embeddings-api), you can use any OpenAI client by swapping out the URL.
99
10-## Step 2: Choose a vector database
10+## Step 2: How to Choose a Vector Database
1111
1212 There are a number of available vector databases, but because most vector databases will be able to performantly handle large codebases, we would recommend choosing one for ease of setup and experimentation.
1313
1414 [LanceDB](https://lancedb.github.io/lancedb/basic/) is a good choice for this because it can run in-memory with libraries for both Python and Node.js. This means that in the beginning you can focus on writing code rather than setting up infrastructure. If you have already chosen a vector database, then using this instead of LanceDB is also a fine choice.
1515
16-## Step 3: Choose a "chunking" strategy
16+## Step 3: How to Choose a "Chunking" Strategy
1717
1818 Most embeddings models can only handle a limited amount of text at once. To get around this, we "chunk" our code into smaller pieces.
1919
@@ -25,7 +25,7 @@
2525
2626 As usual in this guide, we recommend starting with the strategy that gives 80% of the benefit with 20% of the effort.
2727
28-## Step 4: Put together an indexing script
28+## Step 4: How to Put Together an Indexing Script
2929
3030 Indexing, in which we will insert your code into the vector database in a retrievable format, happens in three steps:
3131
@@ -48,7 +48,7 @@
4848
4949 Regardless of which database or model you have chosen, your script should iterate over all of the files that you wish to index, chunk them, generate embeddings for each chunk, and then insert all of the chunks into your vector database.
5050
51-## Step 5: Run your indexing script
51+## Step 5: How to Run Your Indexing Script
5252
5353 <Check>
5454 In a perfect production version, you would want to build "automatic, incremental indexing", so that you whenever a file changes, that file and nothing else is automatically re-indexed. This has the benefits of perfectly up-to-date embeddings and lower cost.
@@ -61,7 +61,7 @@
6161
6262 In the beginning, you should probably run it by hand. Once you are confident that your custom RAG is providing value and is ready for the long-term, then you can set up a cron job to run it periodically. Because codebases are largely unchanged in short time frames, you won't want to re-index more than once a day. Once per week or month is probably even sufficient.
6363
64-## Step 6: Set up your server
64+## Step 6: How to Set Up Your Server
6565
6666 In order for the Continue extension to access your custom RAG system, you'll need to set up a server. This server is responsible for recieving a query from the extension, querying the vector database, and returning the results in the format expected by Continue.
6767
@@ -106,7 +106,7 @@
106106 }
107107 ```
108108
109-## Step 7 (Bonus): Set up reranking
109+## Step 7 (Bonus): How to Set Up Reranking
110110
111111 If you'd like to improve the quality of your results, a great first step is to add reranking. This involves retrieving a larger initial pool of results from the vector database, and then using a reranking model to order them from most to least relevant. This works because the reranking model can perform a slightly more expensive calculation on the small set of top results, and so can give a more accurate ordering than similarity search, which has to search over all entries in the database.
112112
modified docs/guides/how-to-self-host-a-model.mdx +3 −3
@@ -1,6 +1,6 @@
11 ---
22 title: "How to Self-Host a Model"
3-description: "You can deploy a model in your , , , , or using:"
3+description: "Learn how to deploy and self-host open-source language models using HuggingFace TGI, vLLM, SkyPilot, Anyscale Private Endpoints, or Lambda for use with Continue"
44 ---
55
66 - [HuggingFace TGI](https://github.com/continuedev/deploy-os-code-llm#tgi)
@@ -9,13 +9,13 @@
99 - [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API)
1010 - [Lambda](https://github.com/continuedev/deploy-os-code-llm#lambda)
1111
12-## Self-hosting an open-source model
12+## How to Self-Host an Open-Source Model
1313
1414 For many cases, either Continue will have a built-in provider or the API you use will be OpenAI-compatible, in which case you can use the "openai" provider and change the "baseUrl" to point to the server.
1515
1616 However, if neither of these are the case, you will need to wire up a new LLM object.
1717
18-## Authentication
18+## How to Set Up Authentication
1919
2020 Basic authentication can be done with any provider using the `apiKey` field:
2121
modified docs/guides/llama3.1.mdx +9 −9
@@ -1,13 +1,13 @@
11 ---
2-title: "Using Llama 3.1 with Continue"
3-description: "Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. Llama 3.2 models are also supported but not recommended for chat, because they are specifically designed to be small or multi-modal."
2+title: "How to Use Llama 3.1 with Continue"
3+description: "Learn how to set up and use Llama 3.1 models with Continue using Ollama, Groq, Together AI, Replicate, SambaNova, or Cerebras Inference for local and cloud-based development"
44 ---
55
6-If you haven't already installed Continue, you can do that [here for VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [here for JetBrains](https://plugins.jetbrains.com/plugin/22707-continue). For more general information on customizing Continue, read [our customization docs](/customization/overview).
6+If you haven't already installed Continue, you can do that [here for VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [here for JetBrains](https://plugins.jetbrains.com/plugin/22707-continue). For more general information on customizing Continue, read [our customization docs](/customize/overview).
77
88 Below we share some of the easiest ways to get up and running, depending on your use-case.
99
10-## Ollama
10+## How to Use Llama 3.1 with Ollama
1111
1212 Ollama is the fastest way to get up and running with local language models. We recommend trying Llama 3.1 8b, which is impressive for its size and will perform well on most hardware.
1313
@@ -37,7 +37,7 @@
3737 }
3838 ```
3939
40-## Groq
40+## How to Use Llama 3.1 with Groq
4141
4242 <Info>
4343 Check if your chosen model is still supported by referring to the [model
@@ -78,7 +78,7 @@
7878 }
7979 ```
8080
81-## Together AI
81+## How to Use Llama 3.1 with Together AI
8282
8383 Together AI provides fast and reliable inference of open-source models. You'll be able to run the 405b model with good speed.
8484
@@ -114,7 +114,7 @@
114114 }
115115 ```
116116
117-## Replicate
117+## How to Use Llama 3.1 with Replicate
118118
119119 Replicate makes it easy to host and run open-source AI with an API.
120120
@@ -149,7 +149,7 @@
149149 }
150150 ```
151151
152-## SambaNova
152+## How to Use Llama 3.1 with SambaNova
153153
154154 SambaNova Cloud provides world record Llama3.1 70B/405B serving.
155155
@@ -185,7 +185,7 @@
185185 }
186186 ```
187187
188-## Cerebras Inference
188+## How to Use Llama 3.1 with Cerebras Inference
189189
190190 Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B/70B.
191191
modified docs/guides/ollama-guide.mdx +20 −20
@@ -1,9 +1,9 @@
11 ---
22 title: "Using Ollama with Continue: A Developer's Guide"
3-description: "This comprehensive guide will walk you through setting up Ollama with Continue for powerful local AI development. Ollama allows you to run large language models locally on your machine, providing privacy, control, and offline capabilities for AI-assisted coding."
3+description: "Complete guide to setting up Ollama with Continue for local AI development. Learn installation, configuration, model selection, performance optimization, and troubleshooting for privacy-focused offline coding assistance"
44 ---
55
6-## Prerequisites
6+## What Are the Prerequisites for Using Ollama
77
88 Before getting started, ensure your system meets these requirements:
99
@@ -12,9 +12,9 @@
1212 - Storage: At least 10GB free space
1313 - Continue extension installed
1414
15-## Installation Steps
15+## How to Install Ollama - Step-by-Step
1616
17-### Step 1: Install Ollama
17+### Step 1: How to Install Ollama
1818
1919 Choose the installation method for your operating system:
2020
@@ -29,7 +29,7 @@
2929 # Download from ollama.ai
3030 ```
3131
32-### Step 2: Download Models
32+### Step 2: How to Download Models
3333
3434 After installing Ollama, download the models you want to use. Here are some popular options:
3535
@@ -40,11 +40,11 @@
4040 ollama pull nomic-embed-text:latest
4141 ```
4242
43-## Configuration
43+## How to Configure Ollama with Continue
4444
4545 Configure Continue to work with your local Ollama instance:
4646
47-### Continue Configuration
47+### How to Set Up Continue Configuration
4848
4949 ```yaml
5050 models:
@@ -70,9 +70,9 @@
7070 - embed
7171 ```
7272
73-You can update `apiBase` with the IP address of a remote machine serving Ollama.
73+You can update `apiBase` with the IP address of a remote machine serving Ollama.
7474
75-### Advanced Settings
75+### How to Configure Advanced Settings
7676
7777 For optimal performance, consider these advanced configuration options:
7878
@@ -81,9 +81,9 @@
8181 - Custom model parameters
8282 - Performance tuning
8383
84-## Best Practices
84+## What Are the Best Practices for Ollama
8585
86-### Model Selection
86+### How to Choose the Right Model
8787
8888 Choose models based on your specific needs:
8989
@@ -91,7 +91,7 @@
9191 2. **Chat**: Llama2 or Mistral
9292 3. **Specialized Tasks**: Domain-specific models
9393
94-### Performance Optimization
94+### How to Optimize Performance
9595
9696 To get the best performance from Ollama:
9797
@@ -100,25 +100,25 @@
100100 - Use appropriate model sizes
101101 - Enable GPU acceleration when available
102102
103-## Troubleshooting
103+## How to Troubleshoot Ollama Issues
104104
105-### Common Issues
105+### What Are Common Issues
106106
107107 Here are solutions to common problems you might encounter:
108108
109-#### Connection Problems
109+#### How to Fix Connection Problems
110110
111111 - Check Ollama service status
112112 - Verify port availability
113113 - Review firewall settings
114114
115-#### Performance Issues
115+#### How to Resolve Performance Issues
116116
117117 - Insufficient RAM
118118 - Model too large for system
119119 - GPU compatibility
120120
121-### Solutions
121+### How to Apply Solutions
122122
123123 Try these solutions in order:
124124
@@ -127,15 +127,15 @@
127127 3. Update to latest version
128128 4. Check system requirements
129129
130-## Example Workflows
130+## What Are Example Workflows with Ollama
131131
132-### Code Generation
132+### How to Use Ollama for Code Generation
133133
134134 ```
135135 # Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass
136136 ```
137137
138-### Code Review
138+### How to Use Ollama for Code Review
139139
140140 Use Continue with Ollama to:
141141
modified docs/guides/overview.mdx +5 −4
@@ -1,8 +1,9 @@
11 ---
2-title: "Overview"
2+title: "How to Use Continue Guides"
3+description: "Comprehensive collection of practical guides for Continue including model setup, local development with Ollama, offline usage, self-hosting, custom context providers, and advanced customization tutorials"
34 ---
45
5-## Model & Setup Guides
6+## What Model & Setup Guides Are Available
67
78 - [Using Ollama with Continue](/guides/ollama-guide) - Local AI development with Ollama
89 - [Setting up Codestral](/guides/set-up-codestral) - Configure Mistral's Codestral model
@@ -10,11 +11,11 @@
1011 - [Running Continue Without Internet](/guides/running-continue-without-internet) - Offline development setup
1112 - [Llama 3.1 Setup](/guides/llama3.1) - Getting started with Llama 3.1
1213
13-## Advanced Tutorials
14+## What Advanced Tutorials Are Available
1415
1516 - [Build Your Own Context Provider](/guides/build-your-own-context-provider) - Create custom context providers
1617 - [Custom Code RAG](/guides/custom-code-rag) - Implement custom retrieval-augmented generation
1718
18-## Contributing
19+## How to Contribute to Guides
1920
2021 Have a guide idea or found an issue? We welcome contributions! Check our [GitHub repository](https://github.com/continuedev/continue) to get involved.
modified docs/guides/plan-mode-guide.mdx +7 −7
@@ -33,7 +33,7 @@
3333 </Columns>
3434 </Accordion>
3535
36-## Use Cases
36+## What Are the Use Cases for Plan Mode
3737
3838 Plan Mode excels in four key scenarios where understanding before acting prevents expensive mistakes:
3939
@@ -65,14 +65,14 @@
6565 </Card>
6666 </Columns>
6767
68-## Best Practices
68+## What Are the Best Practices for Plan Mode?
6969
70-### For Faster Planning
70+### How to Plan Faster
7171
7272 1. **Scope your requests**: `Focus analysis on the user authentication module only, ignore the admin features`
7373 2. **Use targeted context**: `Analyze @Files and its direct imports for security issues`
7474
75-### For Higher Quality Plans
75+### How to Create Higher Quality Plans
7676
7777 1. **Provide business context**: `This feature needs to handle Black Friday traffic (10x normal load). Plan accordingly.`
7878 2. **Share technical constraints**: `We're on AWS with strict security requirements. Plan a file upload system that meets SOC2 compliance.`
@@ -85,7 +85,7 @@
8585
8686 ![How to select plan mode](../images/plan-mode-selector.png)
8787
88-## Available Tools in Plan Mode
88+## What Tools Are Available in Plan Mode?
8989
9090 | Tool | Available | Description |
9191 | :-------------------------------- | :-------- | :--------------------------------------------------- |
@@ -104,7 +104,7 @@
104104 | **Git commits/pushes** | ❌ | Making changes to version control |
105105 | **Database modifications** | ❌ | Altering database data or structure |
106106
107-## Context Integration in Plan Mode
107+## How Context Integration Works in Plan Mode
108108
109109 Context is the foundation of effective planning. Without proper context, AI models fall back on generic patterns, leading to plans that don't fit your specific system. Continue's [context system](/features/chat/context-selection) transforms broad suggestions into actionable strategies:
110110
@@ -256,7 +256,7 @@
256256 </Accordion>
257257 </AccordionGroup>
258258
259-## From Plan to Execution
259+## How to Transition From Plan to Execution
260260
261261 ### When to Transition to Agent Mode
262262
modified docs/guides/running-continue-without-internet.mdx +3 −3
@@ -1,9 +1,9 @@
11 ---
2-title: "Running Continue without Internet"
3-description: "Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work."
2+title: "How to Run Continue Without Internet"
3+description: "Learn how to set up Continue for air-gapped or offline environments using local models, including steps to disable telemetry and configure local model providers"
44 ---
55
66 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
77 2. Open the [User Settings Page](/customize/settings) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry).
8-3. Also in `config.json`, set the default model to a local model. You can available options [here](/customization/models#openai).
8+3. Also in `config.json`, set the default model to a local model. You can find available options [here](/customize/model-providers/overview).
99 4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect.
modified docs/guides/set-up-codestral.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "How to Set Up Codestral"
3+description: "Step-by-step guide for configuring Mistral's Codestral model with Continue for both chat and autocomplete functionality using your Mistral AI API key"
34 ---
45
56 **Here is a step-by-step guide on how to set up Codestral with Continue using the Mistral AI API:**
modified docs/guides/understanding-assistants.mdx +30 −14
@@ -1,15 +1,17 @@
11 ---
2-title: "Understanding Assistants: Hub vs Local Configuration"
3-description: "Master the two approaches to configuring AI assistants in Continue - choosing the right path for your development workflow"
2+title: "How to Understand Assistants: Hub vs Local Configuration"
3+description: "Learn how to choose between cloud-managed Hub assistants and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
44 ---
55
66 Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
77
8-## The Two Paths to AI Assistance
8+## What Are the Two Paths to AI Assistance?
9+
10+Continue provides two distinct ways to configure your AI assistant:
911
1012 Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly.
1113
12-### Accessing Your Assistant Configuration
14+### How to Access Your Assistant Configuration
1315
1416 Before we dive into the specifics, let's understand how to access your configuration:
1517
@@ -21,13 +23,14 @@
2123
2224 ![configure an assistant](/images/configure-continue.png)
2325
24-## Hub Assistants: The Managed Experience
26+## What Are Hub Assistants: The Managed Experience
2527
2628 Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments.
2729
28-### Why Choose Hub Assistants?
30+### Why Should You Choose Hub Assistants?
2931
3032 **The Power of Simplicity**
33+
3134 - **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click
3235 - **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required
3336 - **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
@@ -35,7 +38,7 @@
3538
3639 ![nextjs assistant](/images/nextjs-assistant.png)
3740
38-### Getting Started with Hub Assistants
41+### How to Get Started with Hub Assistants
3942
4043 The journey from zero to AI-powered coding takes just four steps:
4144
@@ -46,31 +49,34 @@
4649
4750 Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link.
4851
49-### Managing Hub Assistants
52+### How to Manage Hub Assistants
5053
5154 All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant).
5255
53-## Local Assistants: The Power User's Choice
56+## What Are Local Assistants: The Power User's Choice
5457
5558 Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine.
5659
57-### Why Choose Local Assistants?
60+### Why Should You Choose Local Assistants?
5861
5962 **Complete Control and Privacy**
63+
6064 - **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies
6165 - **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments
6266 - **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
6367 - **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
6468
65-### Setting Up Local Assistants
69+### How to Set Up Local Assistants
6670
6771 Local configuration lives in a single YAML file in your home directory:
6872
6973 **File Locations:**
74+
7075 - macOS/Linux: `~/.continue/config.yaml`
7176 - Windows: `%USERPROFILE%\.continue\config.yaml`
7277
7378 **Quick Access Method:**
79+
7480 1. Open the assistants dropdown in your IDE
7581 2. Click the gear icon next to "Local Assistant"
7682 3. The `config.yaml` file opens in your editor
@@ -85,24 +91,27 @@
8591
8692 For the complete configuration reference, see our [config.yaml documentation](/reference).
8793
88-## Making the Right Choice
94+## How to Make the Right Choice
8995
9096 The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide:
9197
9298 ### Choose Hub Assistants When You:
9399
94100 **Value Convenience Over Control**
101+
95102 - Want to start coding with AI assistance in under 60 seconds
96103 - Prefer visual interfaces over editing configuration files
97104 - Need to switch between multiple machines frequently
98105 - Work in a team that needs standardized AI assistance
99106
100107 **Need Advanced Collaboration**
108+
101109 - Want to share custom assistants with teammates
102110 - Need centralized API key management
103111 - Require quick updates across your entire organization
104112
105113 **Are Getting Started**
114+
106115 - New to AI-powered development
107116 - Want to experiment with different models and configurations
108117 - Prefer guided setup experiences
@@ -110,21 +119,24 @@
110119 ### Choose Local Assistants When You:
111120
112121 **Require Maximum Control**
122+
113123 - Need to version control your exact configuration
114124 - Want to customize every aspect of the AI behavior
115125 - Require reproducible development environments
116126
117127 **Have Privacy Requirements**
128+
118129 - Work with sensitive code that requires air-gapped environments
119130 - Need to ensure all configuration data stays local
120131 - Have strict compliance requirements about data storage
121132
122133 **Are a Power User**
134+
123135 - Comfortable editing YAML/JSON files
124136 - Want access to experimental features
125137 - Need to integrate with local tools and scripts
126138
127-## The Hybrid Approach
139+## How to Use the Hybrid Approach
128140
129141 Here's a secret: you don't have to choose just one. Many developers use both approaches:
130142
@@ -154,22 +166,26 @@
154166 ### Hub Assistant Issues
155167
156168 **Changes Not Reflecting?**
169+
157170 - Click "Reload config" in your IDE
158171 - Check your internet connection
159172 - Ensure you're signed in to the correct account
160173
161174 **Assistant Not Available?**
175+
162176 - Verify it's added to your account on the hub
163177 - Check if it requires specific API keys
164178
165179 ### Local Assistant Issues
166180
167181 **Config Not Loading?**
182+
168183 - Verify file location matches your OS
169184 - Check YAML syntax (Continue will show errors)
170185 - Ensure file permissions allow reading
171186
172187 **Autocomplete Not Working?**
188+
173189 - Update to the latest Continue version
174190 - Check that you're editing the correct file
175191
@@ -183,4 +199,4 @@
183199
184200 Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow.
185201
186-Happy coding with Continue! 🚀
No newline at the end of the file
202+Happy coding with Continue! 🚀
modified docs/home.mdx +16 −4
@@ -1,10 +1,22 @@
11 ---
22 title: "Introduction"
3+description: "Learn how Continue enables developers to embrace continuous AI, enabling them to build custom AI code assistants with open source VS Code and JetBrains extensions featuring chat, autocomplete, edit, and agent capabilities"
34 ---
45
5-**Continue enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
6+## What is Continue?
67
7-- [Chat](/features/chat/quick-start) to understand and iterate on code in the sidebar
8+**Continue enables developers to create, share, and use custom AI code assistants with our open source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
9+
10+## Key Features
11+
12+**You can use Continue to build and run custom agents across your IDE, terminal, and CI.**
13+
14+1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions:
15+- [Agent](/features/agent/quick-start) to work on development tasks together with AI
16+- [Chat](/features/chat/quick-start) to ask general questions and clarify code sections
17+- [Edit](/features/edit/quick-start) to modify code section without leaving your current file
818 - [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
9-- [Edit](/features/edit/quick-start) to modify code without leaving your current file
10-- [Agent](/features/agent/quick-start) to make more substantial changes to your codebase
19+
20+2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback
21+
22+3. Discover the models, rules, and MCP tools you need to create a custom AI coding agent on [Continue Hub](https://hub.continue.dev/)
modified docs/hub/assistants/create-an-assistant.mdx +18 −16
@@ -1,32 +1,34 @@
11 ---
2-title: "Create an assistant"
2+title: "How to Create an AI Assistant"
3+description: "Learn how to create custom AI coding assistants in Continue Hub by remixing existing assistants or building new ones from scratch with reusable blocks and YAML configuration."
4+sidebarTitle: "Create an AI Assistant"
35 ---
46
5-## Remix an assistant
7+## How to Create an AI Assistant from Scratch
68
7-You should remix an assistant if you want to use it after some modifications.
9+To create an assistant from scratch, select “New assistant” in the top bar.
810
9-By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
11+![New assistant button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png)
1012
11-![Remix Assistant Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png)
13+Choose a name, slug, description, and icon for your assistant.
1214
13-Once here, you’ll be able to
15+The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar.
1416
15-1. add or remove blocks in YAML configuration
16-2. change the name, description, icon, etc.
17+Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
1718
18-Clicking “Create assistant” will make this assistant available for use.
19+![New assistant YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png)
1920
20-## Create an assistant from scratch
21+## How to Remix an Assistant
2122
22-To create an assistant from scratch, select “New assistant” in the top bar.
23+You can also create an assistant by remixing an existing one. This is useful if you want to start with a pre-configured assistant and make modifications.
2324
24-![New assistant button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png)
25+By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
2526
26-Choose a name, slug, description, and icon for your assistant.
27+![Remix Assistant Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png)
2728
28-The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar.
29+Once here, you’ll be able to
2930
30-Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
31+1. add or remove blocks in YAML configuration
32+2. change the name, description, icon, etc.
3133
32-![New assistant YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png)
34+Clicking “Create assistant” will make this assistant available for use.
modified docs/hub/assistants/edit-an-assistant.mdx +1 −1
@@ -1,5 +1,5 @@
11 ---
2-title: "Edit an Assistant"
2+title: "How to Edit an Assistant"
33 description: "New versions of an assistant can be created and published using the sidebar."
44 ---
55
modified docs/hub/assistants/use-an-assistant.mdx +9 −4
@@ -1,14 +1,19 @@
11 ---
2-title: "Use an assistant"
3-description: "To use an existing assistant, you can explore other assistants ."
2+title: "How to Use an Assistant"
3+description: "Learn how to add, configure, and use an AI assistant in Continue, including setting required inputs and selecting it in your IDE extension."
44 ---
55
6-Once you've found the assistant you want to use
6+## Steps to Use an AI Assistant in Continue
7+
8+Once you've found the assistant you want to use on Continue Hub:
79
810 1. Click “Add Assistant” on its page
911 2. Add any required inputs (e.g. secrets like API keys)
1012 3. Select “Save changes” in assistant sidebar on the right hand side
1113
12-After this, you can then go to your IDE extension and begin using the assistant by selecting it from the assistant dropdown.
14+After saving, open your IDE extension and:
15+
16+- Select the assistant from the **assistant dropdown** in the Continue extension.
17+- Begin using it for chat, code generation, or other configured capabilities.
1318
1419 [Extension Assistant Selector](/images/assistant-extension-select-319492a06d6249e5389747687341dfdb.png)
modified docs/hub/blocks/block-types.mdx +6 −3
@@ -1,12 +1,14 @@
11 ---
2-title: "Block Types"
2+title: "Block Types in Continue Hub: Models, Context Providers, Prompts, and More"
3+sideBarTitle: "Block Types"
4+description: "Explore the different types of reusable blocks in Continue Hub including models, context providers, documentation, MCP servers, rules, prompts, and data components"
35 ---
46
57 ## Models
68
79 Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models).
810
9-Continue supports [many model providers](/customization/models#openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles). View [`models`](/reference#models) in the YAML Reference for more details.
11+Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles). View [`models`](/reference#models) in the YAML Reference for more details.
1012
1113 ## Context
1214
@@ -36,7 +38,8 @@
3638
3739 Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
3840
39-Prompt blocks have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
41+Prompt blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
42+Prompt blocks have the same syntax as [prompt files](/customize/deep-dives/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
4043
4144 ## Data
4245
modified docs/hub/blocks/bundles.mdx +4 −4
@@ -3,9 +3,9 @@
33 description: "Bundles are collections of blocks that are commonly used together. You can use them to add multiple building blocks to your custom AI code assistants at once. They are only a concept on , so they are not represented in ."
44 ---
55
6-## Use a bundle
6+## How to Use a Bundle
77
8-Once you know which bundle you want to use, you’ll need to
8+Once you know which bundle you want to use, you’ll need to:
99
1010 1. Make sure the correct assistant is in the sidebar
1111 2. Click “Add all blocks". This adds the individual blocks to your assistant.
@@ -14,7 +14,7 @@
1414
1515 After this, you can then go to your IDE extension using the "Open VS Code" or "Open Jetbrains" buttons and begin using the new blocks.
1616
17-## Create a bundle
17+## How to Create a Bundle
1818
1919 To create a bundle, click “New bundle” in the header.
2020
@@ -28,6 +28,6 @@
2828
2929 Once you have added all the blocks you want in your bundle, click "Create Bundle" to save it and make it available for use.
3030
31-## Remix a bundle
31+## How to Remix a Bundle
3232
3333 It is not currently possible to remix a bundle.
modified docs/hub/blocks/create-a-block.mdx +6 −4
@@ -1,8 +1,10 @@
11 ---
2-title: "Create a block"
2+title: "How to Create a Block"
3+sidebarTitle: "Create a Block"
4+description: "Learn how to create and remix reusable blocks in Continue Hub for sharing configuration components like models, prompts, and tools with customizable inputs and template variables"
35 ---
46
5-## Remix a block
7+## How to Remix a Block
68
79 You should remix a block if you want to use it after some modifications.
810
@@ -12,7 +14,7 @@
1214
1315 Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an assistant.
1416
15-## Create a block from scratch
17+## How to Create a Block from Scratch
1618
1719 To create a block from scratch, you will need to click “New block” in the top bar.
1820
@@ -22,6 +24,6 @@
2224
2325 ![New block page](/images/hub/blocks/images/block-new-page-2d7faf71739d0f062d555b5d7257fb56.png)
2426
25-### Block inputs
27+### Block Inputs
2628
2729 Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant.
modified docs/hub/blocks/intro.mdx +2 −2
@@ -1,6 +1,6 @@
11 ---
2-title: "Introduction"
3-description: "Blocks are the components you use to build a custom AI code assistant. These include , , , , , , and ."
2+title: "Introduction to Continue Blocks"
3+description: "Blocks are the components you use to build a custom AI code assistant. These include models, prompts, tools, context, and more."
44 ---
55
66 Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant.
modified docs/hub/blocks/use-a-block.mdx +4 −2
@@ -1,8 +1,10 @@
11 ---
2-title: "Use a block"
3-description: "Blocks can be used by adding them to assistants:"
2+title: "How to Use a Block"
3+description: "Learn how to use blocks in Continue Hub to enhance your AI code assistant."
44 ---
55
6+Blocks are used to build custom AI code assistants in Continue Hub. Learn more:
7+
68 - [Create an assistant](/hub/assistants/create-an-assistant)
79 - [Edit an assistant](/hub/assistants/edit-an-assistant)
810
modified docs/hub/governance/pricing.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Pricing"
3+description: "Continue Hub pricing plans for individuals, teams, and enterprises, including the Models Add-On that provides access to frontier AI models for a flat monthly fee"
34 ---
45
56 ## Solo
modified docs/hub/introduction.mdx +1 −0
@@ -1,5 +1,6 @@
11 ---
22 title: "Introduction"
3+description: "Continue Hub provides a central registry for creating, managing, and sharing AI coding assistants and their reusable building blocks with organization-level governance and configuration"
34 ---
45
56 [Continue Hub](https://hub.continue.dev) makes it simple to create custom AI code [assistants](/hub/assistants/intro), providing a registry for defining, managing, and sharing assistant [building blocks](/hub/blocks/intro).
modified docs/index.mdx +24 −14
@@ -1,30 +1,39 @@
11 ---
22 title: "Introduction"
33 icon: book-open
4+description: "Continue is an open source platform for building AI-powered coding assistants with customizable components for chat, autocomplete, edit, and agent workflows in VS Code and JetBrains IDEs"
45 ---
56
67 <Frame>
78 <img src="/images/intro-0c302b9c15b890c251b1ad04586c880f.png" />
89 </Frame>
910
10-**Continue enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
11+**Continue enables developers to ship faster with Continuous AI.**
12+
13+**You can use Continue to build and run custom agents across your IDE, terminal, and CI.**
14+
15+1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
16+
17+2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback
18+
19+3. Discover models, rules, and MCP tools on [Continue Hub](https://hub.continue.dev/)
1120
1221 <CardGroup cols={2}>
1322 <Card
14- title="Chat"
15- icon="messages"
16- href="/features/chat/quick-start"
23+ title="Agent"
24+ icon="robot"
25+ href="/features/agent/quick-start"
1726 horizontal
1827 >
19- to understand and iterate on code in the sidebar
28+ to work on development tasks together with AI
2029 </Card>
2130 <Card
22- title="Autocomplete"
23- icon="sparkles"
24- href="/features/autocomplete/quick-start"
31+ title="Chat"
32+ icon="messages"
33+ href="/features/chat/quick-start"
2534 horizontal
2635 >
27- to receive inline code suggestions as you type
36+ to ask general questions and clarify code sections
2837 </Card>
2938 <Card
3039 title="Edit"
@@ -32,14 +41,15 @@
3241 href="/features/edit/quick-start"
3342 horizontal
3443 >
35- to modify code without leaving your current file
44+ to modify a code section without leaving your current file
3645 </Card>
3746 <Card
38- title="Agent"
39- icon="robot"
40- href="/features/agent/quick-start"
47+ title="Autocomplete"
48+ icon="sparkles"
49+ href="/features/autocomplete/quick-start"
4150 horizontal
4251 >
43- to make more substantial changes to your codebase
52+ to receive inline code suggestions as you type
4453 </Card>
54+
4555 </CardGroup>
deleted docs/migrate-i18n.md +0 −72
@@ -1,72 +0,0 @@
1-# Internationalization (i18n) Migration Plan
2-
3-## Current State
4-
5-- Docusaurus has complete Chinese (zh-CN) translations but they're **commented out** in config
6-- 79 translated markdown files exist in `/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/`
7-- Theme translations exist in `/docs/i18n/zh-CN/code.json`
8-
9-## Mintlify Pro i18n Approach
10-
11-- Uses `versions` array in `mint.json` with `locale` values
12-- Supports Chinese as `cn` locale
13-- Auto-translates fixed UI text ("Was this page helpful?", etc.)
14-- Built-in internationalization feature in Mintlify Pro
15-- Requires manual content translation (which we already have)
16-
17-## Migration Steps
18-
19-### 1. Add Chinese Version to mint.json
20-
21-```json
22-"versions": [
23- {
24- "name": "English",
25- "locale": "en"
26- },
27- {
28- "name": "中文",
29- "locale": "cn"
30- }
31-]
32-```
33-
34-### 2. Create Chinese Content Structure
35-
36-- Create `/docs2/cn/` directory
37-- Copy translated content from `/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/`
38-- Update paths and frontmatter for Mintlify format
39-
40-### 3. Update Navigation for Chinese
41-
42-- Add version specification to navigation groups
43-- Ensure proper routing for Chinese pages
44-
45-### 4. Content Format Migration
46-
47-- Convert Docusaurus-specific syntax to Mintlify format
48-- Update image paths from `/img/` to `/images/`
49-- Convert components (Info, Warning, Tabs, etc.)
50-
51-## Implementation Decision
52-
53-For Phase 4, we have two options:
54-
55-1. **Enable Chinese translations** - Full migration of existing Chinese content
56-2. **Document for future** - Create migration plan but defer implementation
57-
58-Given that Chinese translations are currently disabled in production, **Option 2** is recommended for Phase 4 to avoid scope creep. The Chinese content is ready and can be migrated when needed.
59-
60-## Files to Migrate (if enabled)
61-
62-- `/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/` → `/docs2/cn/`
63-- 79 translated markdown files
64-- Navigation structure adaptation
65-- Theme translations (handled automatically by Mintlify)
66-
67-## Next Steps
68-
69-1. Document the migration approach
70-2. Create helper scripts for content conversion
71-3. Test with a small subset of Chinese pages
72-4. Full migration when Chinese localization is prioritized
modified docs/reference.mdx +7 −6
@@ -1,5 +1,6 @@
11 ---
22 title: "config.yaml Reference"
3+description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding assistants. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration."
34 ---
45
56 ## Introduction
@@ -14,7 +15,7 @@
1415
1516 <Info>
1617 Config YAML replaces `config.json`, which is deprecated. View the **[Migration
17- Guide](/customize/yaml-migration)**.
18+ Guide](/reference/yaml-migration)**.
1819 </Info>
1920
2021 An assistant is made up of:
@@ -175,16 +176,16 @@
175176
176177 - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
177178
178-
179179 - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include:
180+
180181 - `tool_use`: Enables function/tool calling support (required for Agent mode)
181182 - `image_input`: Enables image upload and processing support
182-
183+
183184 Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly.
184185
185186 - `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
186187
187-- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chat`, [`edit`](/customize/model-roles#edit-prompt-templating), [`apply`](/customize/model-roles#apply-prompt-templating) and [`autocomplete`](/customize/model-roles#autocomplete-prompt-templating). The `chat` property must be a valid template name, such as `llama3` or `anthropic`.
188+- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`chat`](), [`edit`](/customize/model-roles/edit#edit-prompt-templating), [`apply`](/customize/model-roles/apply#apply-prompt-templating) and [`autocomplete`](/customize/model-roles/autocomplete#autocomplete-prompt-templating). The `chat` property must be a valid template name, such as `llama3` or `anthropic`.
188189
189190 - `chatOptions`: If the model includes role `chat`, these settings apply for Agent and Chat mode:
190191
@@ -316,7 +317,7 @@
316317
317318 ### `rules`
318319
319-List of rules that the LLM should follow. These are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests. See the [rules deep dive](/customization/rules) for details.
320+List of rules that the LLM should follow. These are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests. See the [rules deep dive](/customize/deep-dives/rules) for details.
320321
321322 Explicit rules can either be simple text or an object with the following properties:
322323
@@ -411,7 +412,7 @@
411412
412413 ### `data`
413414
414-Destinations to which [development data](/customize/overview#development-data) will be sent.
415+Destinations to which [development data](/customize/deep-dives/development-data) will be sent.
415416
416417 **Properties:**
417418
modified docs/reference/json-reference.mdx +19 −19
@@ -18,9 +18,9 @@
1818
1919 **All properties at all levels are optional unless explicitly marked required**
2020
21-### `models`
21+## `models`
2222
23-Your **chat** models are defined here, which are used for [Chat](/features/chat/how-it-works), [Edit](/features/edit/how-it-works) and [VS Code actions](/customization/overview#vscode-actions).
23+Your **chat** models are defined here, which are used for [Chat](/features/chat/how-it-works), [Edit](/features/edit/how-it-works) and [VS Code actions](/customize/overview#vscode-actions).
2424
2525 Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json.
2626
@@ -85,7 +85,7 @@
8585 }
8686 ```
8787
88-### `tabAutocompleteModel`
88+## `tabAutocompleteModel`
8989
9090 Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model.
9191
@@ -137,7 +137,7 @@
137137 }
138138 ```
139139
140-### `embeddingsProvider`
140+## `embeddingsProvider`
141141
142142 Embeddings model settings - the model used for @Codebase and @docs.
143143
@@ -172,7 +172,7 @@
172172 }
173173 ```
174174
175-### `completionOptions`
175+## `completionOptions`
176176
177177 Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_.
178178
@@ -202,7 +202,7 @@
202202 { "completionOptions": { "stream": false, "temperature": 0.5 } }
203203 ```
204204
205-### `requestOptions`
205+## `requestOptions`
206206
207207 Default HTTP request options that apply to all models and context providers, unless overridden at the model level.
208208
@@ -261,7 +261,7 @@
261261 }
262262 ```
263263
264-### `docs`
264+## `docs`
265265
266266 List of documentation sites to index.
267267
@@ -282,7 +282,7 @@
282282 "docs": [ { "title": "Continue", "startUrl": "https://docs.continue.dev/intro", "faviconUrl": "https://docs.continue.dev/favicon.ico", }]
283283 ```
284284
285-### `slashCommands`
285+## `slashCommands`
286286
287287 Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined.
288288
@@ -295,7 +295,7 @@
295295
296296 The following commands are built-in and can be added to `config.json` to make them visible:
297297
298-#### `/share`
298+### `/share`
299299
300300 Generate a shareable markdown transcript of your current chat history.
301301
@@ -315,7 +315,7 @@
315315
316316 Use the `outputDir` parameter to specify where you want to the markdown file to be saved.
317317
318-#### `/cmd`
318+### `/cmd`
319319
320320 Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal.
321321
@@ -329,7 +329,7 @@
329329 }
330330 ```
331331
332-#### `/commit`
332+### `/commit`
333333
334334 Shows the LLM your current git diff and asks it to generate a commit message.
335335
@@ -346,7 +346,7 @@
346346 }
347347 ```
348348
349-#### `/http`
349+### `/http`
350350
351351 Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference.
352352
@@ -364,7 +364,7 @@
364364 }
365365 ```
366366
367-#### `/issue`
367+### `/issue`
368368
369369 Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for.
370370
@@ -382,7 +382,7 @@
382382 }
383383 ```
384384
385-#### `/onboard`
385+### `/onboard`
386386
387387 The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture.
388388
@@ -463,15 +463,15 @@
463463 }
464464 ```
465465
466-### `userToken`
466+## `userToken`
467467
468468 An optional token that identifies the user, primarily for authenticated services.
469469
470-### `systemMessage`
470+## `systemMessage`
471471
472472 Defines a system message that appears before every response from the language model, providing guidance or context.
473473
474-### `experimental`
474+## `experimental`
475475
476476 Several experimental config parameters are available, as described below:
477477
@@ -498,7 +498,7 @@
498498 - `fix`: Prompt for fixing code.
499499 - `optimize`: Prompt for optimizing code.
500500
501-- `modelContextProtocolServers`: See [Model Context Protocol](/customization/mcp-tools)
501+- `modelContextProtocolServers`: See [Model Context Protocol](/customize/deep-dives/mcp)
502502
503503 Example
504504
@@ -531,7 +531,7 @@
531531 }
532532 ```
533533
534-### Fully deprecated settings
534+## Fully deprecated settings
535535
536536 Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](/customize/settings). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`.
537537
modified docs/reference/yaml-migration.mdx +1 −0
@@ -321,6 +321,7 @@
321321 - top-level `completionOptions`
322322
323323 - `tabAutocompleteOptions`
324+
324325 - `disable`
325326 - `maxPromptTokens`
326327 - `debounceDelay`
deleted docs/replace-custom-plugins.md +0 −147
@@ -1,147 +0,0 @@
1-# Custom Plugin Replacement Plan
2-
3-## Overview
4-
5-This document outlines how to replace custom Docusaurus plugins and functionality with Mintlify Pro equivalents.
6-
7-## Custom Plugins Analysis
8-
9-### 1. Custom LLMs.txt Plugin ✅ BUILT-IN (Mintlify Pro)
10-
11-**Current functionality:**
12-
13-- Scans HTML files post-build
14-- Extracts titles, descriptions, URLs from all pages
15-- Organizes content by sections (Getting Started, Features, Guides, etc.)
16-- Generates structured `/llms.txt` file for AI model consumption
17-
18-**Mintlify Pro replacement:**
19-
20-- **Automatic `/llms.txt`** - Lists all available pages automatically
21-- **Automatic `/llms-full.txt`** - Combines entire documentation into single file
22-- **AI-optimized** - Specifically designed for LLM consumption
23-- **No custom code required** - Built-in feature
24-
25-**Status:** ✅ Complete - No migration needed
26-
27-### 2. Analytics Configuration ✅ BUILT-IN
28-
29-**Current:**
30-
31-- Google Analytics: `G-M3JWW8N2XQ`
32-- Custom Reo.dev script
33-
34-**Mintlify replacement:**
35-
36-- Native Google Analytics support in mint.json
37-- Custom scripts can be added via mint.json
38-
39-### 3. Search Configuration ✅ BUILT-IN
40-
41-**Current:**
42-
43-- Algolia search (App ID: `0OMUMCQZVV`, Index: `continue`)
44-
45-**Mintlify replacement:**
46-
47-- Native search functionality built-in
48-- Can configure Algolia if needed
49-
50-### 4. URL Redirects ✅ COMPLETE
51-
52-**Status:** Already migrated (145 redirects) in mint.json
53-
54-## Implementation Plan
55-
56-### Phase 4A: Replace LLMs.txt Plugin
57-
58-1. Create `generate-llms-txt.js` script
59-2. Adapt to work with Mintlify's build structure
60-3. Test with current docs2 content
61-4. Add to build process
62-
63-### Phase 4B: Add Analytics
64-
65-1. Add Google Analytics to mint.json
66-2. Migrate custom Reo.dev script if needed
67-
68-### Phase 4C: Configure Search
69-
70-1. Verify Mintlify search works
71-2. Configure Algolia if required
72-
73-## Custom LLMs.txt Script for Mintlify
74-
75-```javascript
76-// generate-llms-txt.js - Adapted for Mintlify
77-const fs = require("fs");
78-const path = require("path");
79-
80-function generateLLMsTxt(buildDir) {
81- const sections = {
82- "Getting Started": [],
83- Features: [],
84- Guides: [],
85- Customization: [],
86- Customize: [],
87- Hub: [],
88- Reference: [],
89- };
90-
91- // Read mint.json to get page structure
92- const mintJson = JSON.parse(fs.readFileSync("mint.json", "utf8"));
93-
94- // Extract page info from navigation
95- function extractPages(navItems, sectionName = "") {
96- navItems.forEach((item) => {
97- if (typeof item === "string") {
98- // Direct page reference
99- const pageInfo = getPageInfo(item);
100- if (pageInfo) {
101- categorizeContent(pageInfo, sections);
102- }
103- } else if (item.group && item.pages) {
104- // Group with pages
105- extractPages(item.pages, item.group);
106- }
107- });
108- }
109-
110- extractPages(mintJson.navigation);
111-
112- // Generate llms.txt content
113- generateContent(sections);
114-}
115-```
116-
117-## Files to Create
118-
119-1. **`/docs2/scripts/generate-llms-txt.js`** - LLMs.txt generator
120-2. **`/docs2/scripts/build-hooks.js`** - Post-build automation
121-3. **Update mint.json** - Add analytics and search config
122-
123-## Success Criteria
124-
125-- [ ] LLMs.txt generated correctly from Mintlify build
126-- [ ] Analytics tracking matches current setup
127-- [ ] Search functionality works as expected
128-- [ ] All redirects function properly
129-- [ ] No loss of functionality compared to Docusaurus
130-
131-## Risk Assessment
132-
133-**Low Risk:**
134-
135-- Analytics migration (built-in support)
136-- Search configuration (native functionality)
137-
138-**Medium Risk:**
139-
140-- LLMs.txt generation (requires custom script)
141-- Custom JavaScript integration
142-
143-**Mitigation:**
144-
145-- Test scripts thoroughly before deployment
146-- Keep Docusaurus version running during transition
147-- Monitor analytics and search metrics post-migration
modified docs/telemetry.mdx +1 −0
@@ -1,6 +1,7 @@
11 ---
22 title: "Telemetry"
33 icon: "chart-line"
4+description: "Learn about Continue's anonymous telemetry collection practices, what usage data is tracked, and how to opt out of data collection to maintain your privacy preferences"
45 ---
56
67 ## Overview
modified docs/troubleshooting.mdx +3 −1
@@ -1,5 +1,6 @@
11 ---
22 title: "Troubleshooting"
3+description: "Comprehensive guide to resolving common issues with Continue, including logging, keyboard shortcuts, networking problems, model capabilities, and extension configuration troubleshooting"
34 ---
45
56 1. [Check the logs](#check-the-logs)
@@ -140,7 +141,8 @@
140141 If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues.
141142
142143 <Info>
143- Continue uses system message tools as a fallback for models without native tool support, so most models should work with Agent mode automatically.
144+ Continue uses system message tools as a fallback for models without native
145+ tool support, so most models should work with Agent mode automatically.
144146 </Info>
145147
146148 #### Check if your model has tool support
modified extensions/intellij/README.md +19 −17
@@ -4,35 +4,37 @@
44
55 <div align="center">
66
7-[**Continue**](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [JetBrains extension](https://plugins.jetbrains.com/plugin/22707-continue-extension) and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev).
7+<a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
8+ <img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
9+</a>
10+<a target="_blank" href="https://docs.continue.dev" style="background:none">
11+ <img src="https://img.shields.io/badge/Continue-docs-%23BE1B55.svg?logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNiAyNCIgZmlsbD0id2hpdGUiPgogIDxwYXRoIGQ9Ik0yMC41Mjg2IDMuMjY4MTFMMTkuMTUxMiA1LjY1Njk0TDIyLjYzMjggMTEuNjg0OUMyMi42NTgyIDExLjczMDYgMjIuNjczNSAxMS43ODY2IDIyLjY3MzUgMTEuODM3NEMyMi42NzM1IDExLjg4ODIgMjIuNjU4MiAxMS45NDQxIDIyLjYzMjggMTEuOTg5OUwxOS4xNTEyIDE4LjAyMjlMMjAuNTI4NiAyMC40MTE3TDI1LjQ3OTEgMTEuODM3NEwyMC41Mjg2IDMuMjYzMDNWMy4yNjgxMVpNMTguNjE3NiA1LjM0NjlMMTkuOTk1IDIuOTU4MDdIMTcuMjQwMkwxNS44NjI4IDUuMzQ2OUgxOC42MjI3SDE4LjYxNzZaTTE1Ljg1NzcgNS45NjY5N0wxOS4wNzUgMTEuNTMyNEgyMS44Mjk4TDE4LjYxNzYgNS45NjY5N0gxNS44NTc3Wk0xOC42MTc2IDE3LjcxNzlMMjEuODI5OCAxMi4xNDc0SDE5LjA3NUwxNS44NTc3IDE3LjcxNzlIMTguNjE3NlpNMTUuODU3NyAxOC4zMzhMMTcuMjM1MSAyMC43MTY3SDE5Ljk4OTlMMTguNjEyNSAxOC4zMzhIMTUuODUyNkgxNS44NTc3Wk02LjUyMDk4IDIxLjMwNjNDNi40NjUwNyAyMS4zMDYzIDYuNDE0MjQgMjEuMjkxIDYuMzY4NSAyMS4yNjU2QzYuMzIyNzYgMjEuMjQwMiA2LjI4MjA5IDIxLjE5OTUgNi4yNTY2OCAyMS4xNTM4TDIuNzcwMDIgMTUuMTIwN0gwLjAxNTI0ODJMNC45NjU3IDIzLjY5SDE0Ljg2MTVMMTMuNDg0MSAyMS4zMDYzSDYuNTI2MDZINi41MjA5OFpNMTQuMDE3OCAyMC45OTYyTDE1LjM5NTIgMjMuMzhMMTYuNzcyNiAyMC45OTExTDE1LjM5NTIgMTguNjAyM0wxNC4wMTc4IDIwLjk5MTFWMjAuOTk2MlpNMTQuODYxNSAxOC4yOTc0SDguNDM3MTJMNy4wNTk3MyAyMC42ODYySDEzLjQ4NDFMMTQuODYxNSAxOC4yOTc0Wk03Ljg5ODM2IDE3Ljk5MjRMNC42ODEwOCAxMi40MjE5TDMuMzAzNjkgMTQuODEwN0w2LjUyMDk4IDIwLjM4MTJMNy44OTgzNiAxNy45OTI0Wk0wLjAxMDE2NTQgMTQuNTAwN0gyLjc2NDk0TDQuMTQyMzIgMTIuMTExOEgxLjM5MjYzTDAuMDEwMTY1NCAxNC41MDA3Wk02LjI0MTQzIDIuNTQxM0M2LjI2Njg1IDIuNDk1NTYgNi4zMDc1MSAyLjQ1NDkgNi4zNTMyNSAyLjQyOTQ4QzYuMzk5IDIuNDA0MDcgNi40NTQ5IDIuMzg4ODIgNi41MDU3MyAyLjM4ODgySDEzLjQ3NEwxNC44NTE0IDBINC45NTA0NUwwIDguNTc0MzVIMi43NTQ3N0w2LjIzMTI3IDIuNTQ2MzhMNi4yNDE0MyAyLjU0MTNaTTQuMTQyMzIgMTEuNTc4MkwyLjc2NDk0IDkuMTg5MzRIMC4wMTAxNjU0TDEuMzg3NTUgMTEuNTc4Mkg0LjE0MjMyWk02LjUxMDgxIDMuMzEzODZMMy4yOTg2MSA4Ljg3OTNMNC42NzU5OSAxMS4yNjgxTDcuODg4MiA1LjcwMjY4TDYuNTEwODEgMy4zMTM4NlpNMTMuNDc5MSAzLjAwMzgySDcuMDQ0NDhMOC40MjE4NyA1LjM5MjY0SDE0Ljg1NjRMMTMuNDc5MSAzLjAwMzgyWk0xNS4zOTUyIDUuMDgyNkwxNi43Njc1IDIuNjk4ODZMMTUuMzk1MiAwLjMxMDAzOEwxNC4wMTc4IDIuNjkzNzhMMTUuMzk1MiA1LjA4MjZaIi8+Cjwvc3ZnPg==" style="height: 22px;" />
12+</a>
13+<a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
14+ <img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
15+</a>
816
9-</div>
17+<p></p>
1018
11-<div align="center">
19+**Ship faster with Continuous AI**
1220
13-## Chat
14-
15-[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.
21+**Build and run custom agents across your IDE, terminal, and CI**
1622
17-You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you what you want, then you can send follow up messages to clarify and adjust its approach until the task is completed.
23+## Agent
1824
19-## Autocomplete
25+[Agent](/features/agent/quick-start) to work on development tasks together with AI
2026
21-[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type.
27+## Chat
2228
23-To enable it, simply click the "Continue" button in the status bar at the bottom right of your IDE or ensure the "Enable Tab Autocomplete" option is checked in your IDE settings.
29+[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
2430
2531 ## Edit
2632
27-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file.
28-
29-Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject.
33+[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
3034
31-## Agent
32-
33-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
35+## Autocomplete
3436
35-Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
37+[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
3638
3739 </div>
3840
modified extensions/intellij/gradle.properties +1 −1
@@ -1,6 +1,6 @@
11 pluginGroup=com.github.continuedev.continueintellijextension
22 pluginRepositoryUrl=https://github.com/continuedev/continue
3-pluginVersion=1.0.35
3+pluginVersion=1.0.38
44 pluginSinceBuild=223
55 platformType=IC
66 platformVersion=2022.3.3
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +8 −0
@@ -105,6 +105,14 @@
105105 "nextEdit/predict",
106106 "nextEdit/reject",
107107 "nextEdit/accept",
108+ "nextEdit/startChain",
109+ "nextEdit/deleteChain",
110+ "nextEdit/isChainAlive",
111+ "nextEdit/queue/getProcessedCount",
112+ "nextEdit/queue/dequeueProcessed",
113+ "nextEdit/queue/processOne",
114+ "nextEdit/queue/clear",
115+ "nextEdit/queue/abort",
108116 "tts/kill",
109117 "llm/complete",
110118 "llm/streamChat",
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +11 −32
@@ -47,7 +47,7 @@
4747 ) : IDE {
4848
4949 private val gitService = GitService(project, continuePluginService)
50- private val fileUtils = FileUtils()
50+ private val fileUtils = FileUtils(project)
5151 private val ripgrep: String = getRipgrepPath()
5252
5353 init {
@@ -183,7 +183,9 @@
183183 fileUtils.fileExists(filepath)
184184
185185 override suspend fun writeFile(path: String, contents: String) =
186- fileUtils.writeFile(path, contents)
186+ withContext(Dispatchers.EDT) {
187+ fileUtils.writeFile(path, contents)
188+ }
187189
188190 override suspend fun showVirtualFile(title: String, contents: String) {
189191 val virtualFile = LightVirtualFile(title, contents)
@@ -196,20 +198,8 @@
196198 return getContinueGlobalPath()
197199 }
198200
199- override suspend fun openFile(path: String) {
200- // Convert URI path to absolute file path
201- val filePath = UriUtils.uriToFile(path).absolutePath
202- // Find the file using the absolute path
203- val file = withContext(Dispatchers.IO) {
204- LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
205- }
206-
207- file?.let {
208- ApplicationManager.getApplication().invokeLater {
209- FileEditorManager.getInstance(project).openFile(it, true)
210- }
211- }
212- }
201+ override suspend fun openFile(path: String) =
202+ fileUtils.openFile(path)
213203
214204 override suspend fun openUrl(url: String) {
215205 withContext(Dispatchers.IO) {
@@ -278,18 +268,10 @@
278268 }
279269 }
280270
281- override suspend fun saveFile(filepath: String) {
282- ApplicationManager.getApplication().invokeLater {
283- val file =
284- LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path) ?: return@invokeLater
285- val fileDocumentManager = FileDocumentManager.getInstance()
286- val document = fileDocumentManager.getDocument(file)
287-
288- document?.let {
289- fileDocumentManager.saveDocument(it)
290- }
271+ override suspend fun saveFile(filepath: String) =
272+ withContext(Dispatchers.EDT) {
273+ fileUtils.saveFile(filepath)
291274 }
292- }
293275
294276 override suspend fun readFile(filepath: String): String =
295277 fileUtils.readFile(filepath)
@@ -604,11 +586,8 @@
604586 override suspend fun listDir(dir: String): List<List<Any>> =
605587 fileUtils.listDir(dir)
606588
607- override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
608- return files.associateWith { file ->
609- FileStats(UriUtils.uriToFile(file).lastModified(), UriUtils.uriToFile(file).length())
610- }
611- }
589+ override suspend fun getFileStats(files: List<String>): Map<String, FileStats> =
590+ fileUtils.getFileStats(files)
612591
613592 override suspend fun gotoDefinition(location: Location): List<RangeInFile> {
614593 throw NotImplementedError("gotoDefinition not implemented yet")
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt +100 −59
@@ -1,69 +1,110 @@
11 package com.github.continuedev.continueintellijextension.`continue`.file
22
3+import com.github.continuedev.continueintellijextension.FileStats
34 import com.github.continuedev.continueintellijextension.FileType
4-import com.github.continuedev.continueintellijextension.`continue`.UriUtils
5-import com.intellij.openapi.application.ApplicationManager
5+import com.intellij.openapi.application.runReadAction
6+import com.intellij.openapi.application.runWriteAction
67 import com.intellij.openapi.fileEditor.FileDocumentManager
7-import com.intellij.openapi.vfs.LocalFileSystem
8-import kotlinx.coroutines.Dispatchers
9-import kotlinx.coroutines.withContext
10-import java.io.FileInputStream
11-import java.nio.charset.Charset
12-
13-class FileUtils {
14- // todo: use VFS (it's moved from IntellijIde)
15-
16- fun fileExists(uri: String): Boolean {
17- val file = UriUtils.uriToFile(uri)
18- return file.exists()
19- }
20-
21- fun writeFile(uri: String, contents: String) {
22- val file = UriUtils.uriToFile(uri)
23- file.parentFile?.mkdirs()
24- file.writeText(contents)
25- }
26-
27- fun listDir(dir: String): List<List<Any>> {
28- val files = UriUtils.uriToFile(dir).listFiles()?.map {
29- listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
30- } ?: emptyList()
31-
32- return files
33- }
34-
35- fun readFile(uri: String): String {
36- return try {
37- val content = ApplicationManager.getApplication().runReadAction<String?> {
38- val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(uri).path)
39- if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
40- return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
41- }
42- return@runReadAction null
43- }
44-
45- if (content != null) {
46- content
47- } else {
48- val file = UriUtils.uriToFile(uri)
49- if (!file.exists() || file.isDirectory) return ""
50- FileInputStream(file).use { fis ->
51- val sizeToRead = minOf(100000, file.length()).toInt()
52- val buffer = ByteArray(sizeToRead)
53- val bytesRead = fis.read(buffer, 0, sizeToRead)
54- if (bytesRead <= 0) return@use ""
55- val content = String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
56- // Remove `\r` characters but preserve trailing newlines to prevent line count discrepancies
57- val contentWithoutCR = content.replace("\r\n", "\n").replace("\r", "\n")
58- contentWithoutCR
59- }
60- }
61- } catch (e: Exception) {
62- e.printStackTrace()
63- ""
8+import com.intellij.openapi.fileEditor.FileEditorManager
9+import com.intellij.openapi.project.Project
10+import com.intellij.openapi.util.TextRange
11+import com.intellij.openapi.vfs.VfsUtil
12+import com.intellij.openapi.vfs.VfsUtilCore
13+import com.intellij.openapi.vfs.VirtualFile
14+import com.intellij.openapi.vfs.VirtualFileManager
15+import kotlin.math.min
16+
17+
18+class FileUtils(
19+ private val project: Project,
20+) {
21+ fun fileExists(fileUri: String): Boolean =
22+ findFile(fileUri) != null
23+
24+ fun writeFile(fileUri: String, content: String) {
25+ val path = VfsUtilCore.urlToPath(fileUri)
26+ val pathDirectory = VfsUtil.getParentDir(path)
27+ ?: return
28+ val vfsDirectory = VfsUtil.createDirectories(pathDirectory)
29+ val pathFilename = VfsUtil.extractFileName(path)
30+ ?: return
31+ runWriteAction {
32+ val newFile = vfsDirectory.createChildData(this, pathFilename)
33+ VfsUtil.saveText(newFile, content)
6434 }
35+ }
36+
37+ fun listDir(fileUri: String): List<List<Any>> {
38+ val found = findFile(fileUri)
39+ ?: return emptyList()
40+ if (!found.isDirectory)
41+ return emptyList()
42+ return found.children.map { file ->
43+ val fileType = if (file.isDirectory)
44+ FileType.DIRECTORY.value
45+ else
46+ FileType.FILE.value
47+ listOf(file.name, fileType)
48+ }
49+ }
50+
51+ fun readFile(fileUri: String, maxLength: Int = 100_000): String {
52+ val found = findFile(fileUri)
53+ ?: return ""
54+ val text = runReadAction {
55+ // note: document (if exists) is more up-to-date than VFS
56+ readDocument(found, maxLength) ?: VfsUtil.loadText(found, maxLength)
57+ }
58+ return normalizeLineEndings(text)
59+ }
6560
61+ fun openFile(fileUri: String) {
62+ val found = findFile(fileUri)
63+ ?: return
64+ FileEditorManager.getInstance(project).openFile(found, true)
6665 }
6766
67+ fun saveFile(fileUri: String) {
68+ val found = findFile(fileUri)
69+ ?: return
70+ val manager = FileDocumentManager.getInstance()
71+ val document = manager.getDocument(found)
72+ ?: return
73+ manager.saveDocument(document)
74+ }
75+
76+ fun getFileStats(fileUris: List<String>): Map<String, FileStats> =
77+ fileUris.mapNotNull { fileUri ->
78+ val file = findFile(fileUri)
79+ ?: return@mapNotNull null
80+ fileUri to FileStats(file.timeStamp, file.length)
81+ }.toMap()
82+
83+ private fun findFile(fileUri: String): VirtualFile? {
84+ val noParams = fileUri.substringBefore("?")
85+ val normalizedAuthority = normalizeWindowsAuthority(noParams)
86+ return VirtualFileManager.getInstance()
87+ .refreshAndFindFileByUrl(normalizedAuthority)
88+ }
6889
90+ private fun readDocument(file: VirtualFile, maxLength: Int): String? {
91+ val document = FileDocumentManager.getInstance().getDocument(file)
92+ ?: return ""
93+ val length = min(document.textLength, maxLength)
94+ return document.getText(TextRange(0, length))
95+ }
96+
97+ private fun normalizeLineEndings(text: String) =
98+ text.replace("\r\n", "\n")
99+ .replace("\r", "\n")
100+
101+ private fun normalizeWindowsAuthority(fileUri: String): String {
102+ val authorityPrefix = "file://"
103+ val noAuthorityPrefix = "file:///"
104+ if (fileUri.startsWith(authorityPrefix) && !fileUri.startsWith(noAuthorityPrefix)) {
105+ val path = fileUri.substringAfter(authorityPrefix)
106+ return "$noAuthorityPrefix$path"
107+ }
108+ return fileUri
109+ }
69110 }
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt +68 −0
@@ -0,0 +1,68 @@
1+package com.github.continuedev.continueintellijextension.license
2+
3+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
5+import com.intellij.notification.NotificationAction
6+import com.intellij.notification.NotificationGroupManager
7+import com.intellij.notification.NotificationType
8+import com.intellij.openapi.actionSystem.ActionManager
9+import com.intellij.openapi.actionSystem.ActionPlaces
10+import com.intellij.openapi.actionSystem.AnAction
11+import com.intellij.openapi.actionSystem.AnActionEvent
12+import com.intellij.openapi.application.ApplicationManager
13+import com.intellij.openapi.components.service
14+import com.intellij.openapi.ui.DialogWrapper
15+
16+class AddLicenseKey : AnAction() {
17+
18+ override fun actionPerformed(e: AnActionEvent) {
19+ val dialog = AddLicenseKeyDialog(e.project)
20+ dialog.show()
21+ if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE)
22+ return
23+ val messenger = e.project?.service<ContinuePluginService>()?.coreMessenger
24+ ?: return
25+ messenger.request("mdm/setLicenseKey", mapOf("licenseKey" to dialog.licenseKey), null) { response ->
26+ val isValid = response.castNestedOrNull<Boolean>("content") ?: false
27+ val notification = if (isValid)
28+ createSuccessAction()
29+ else
30+ createErrorAction()
31+ notification.notify(e.project)
32+ }
33+ }
34+
35+ private fun createSuccessAction() =
36+ getContinueNotifications().createNotification(
37+ "License key is valid. A restart is required for it to take effect.",
38+ NotificationType.INFORMATION
39+ ).addAction(
40+ NotificationAction.create("Restart IDE") { event, notification ->
41+ ApplicationManager.getApplication().restart()
42+ }
43+ )
44+
45+ private fun createErrorAction() =
46+ getContinueNotifications().createNotification(
47+ "License key is invalid.",
48+ NotificationType.ERROR
49+ ).addAction(
50+ NotificationAction.create("Try again") { event, notification ->
51+ notification.expire()
52+ val action = this@AddLicenseKey
53+ action.actionPerformed(
54+ AnActionEvent(
55+ null,
56+ event.dataContext,
57+ ActionPlaces.UNKNOWN,
58+ action.templatePresentation.clone(),
59+ ActionManager.getInstance(),
60+ 0
61+ )
62+ )
63+ }
64+ )
65+
66+ private fun getContinueNotifications() =
67+ NotificationGroupManager.getInstance().getNotificationGroup("Continue")
68+}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt +35 −0
@@ -0,0 +1,35 @@
1+package com.github.continuedev.continueintellijextension.license
2+
3+import com.intellij.openapi.project.Project
4+import com.intellij.openapi.ui.DialogWrapper
5+import com.intellij.openapi.ui.ValidationInfo
6+import com.intellij.ui.dsl.builder.bindText
7+import com.intellij.ui.dsl.builder.panel
8+import com.intellij.ui.dsl.gridLayout.HorizontalAlign
9+import javax.swing.JComponent
10+
11+class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) {
12+
13+ var licenseKey: String = ""
14+ private set
15+
16+ init {
17+ title = "Enterprise License Key"
18+ init()
19+ }
20+
21+ override fun createCenterPanel(): JComponent? =
22+ panel {
23+ row {
24+ textField().bindText(::licenseKey)
25+ .horizontalAlign(HorizontalAlign.FILL)
26+ .focused()
27+ .validationOnApply {
28+ if (it.text.isBlank())
29+ ValidationInfo("License key cannot be empty")
30+ else
31+ null
32+ }
33+ }
34+ }
35+}
No newline at the end of the file
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +7 −0
@@ -106,6 +106,13 @@
106106 <override-text place="GoToAction" text="Continue: Reject Vertical Diff Block"/>
107107 </action>
108108
109+ <action id="continue.addLicenseKey"
110+ class="com.github.continuedev.continueintellijextension.license.AddLicenseKey"
111+ text="Enter Enterprise License Key"
112+ description="Enter Enterprise License Key">
113+ <override-text place="GoToAction" text="Continue: Enter Enterprise License Key"/>
114+ </action>
115+
109116 <action id="continue.focusContinueInputWithoutClear"
110117 class="com.github.continuedev.continueintellijextension.actions.FocusContinueInputWithoutClearAction"
111118 text="Add selected code to context"
modified extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/FileUtilsTest.kt +124 −29
@@ -2,54 +2,95 @@
22
33 import com.github.continuedev.continueintellijextension.FileType
44 import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
5+import com.intellij.openapi.application.runWriteAction
6+import com.intellij.openapi.fileEditor.FileDocumentManager
7+import com.intellij.openapi.fileEditor.FileEditorManager
8+import com.intellij.openapi.vfs.VfsUtil
59 import com.intellij.testFramework.UsefulTestCase
610 import com.intellij.testFramework.fixtures.CodeInsightTestFixture
711 import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
812
913 class FileUtilsTest : UsefulTestCase() {
10- val fileUtils = FileUtils()
11- val myFixture = setupRealFilesFixture()
12- val tmpFixture get() = myFixture.tempDirFixture
13- val tmpDir get() = myFixture.tempDirPath
14-
15- override fun setUp() =
14+ private val myFixture = setupRealFilesFixture()
15+ private lateinit var fileUtils: FileUtils
16+ private val tmp get() = myFixture.tempDirPath
17+
18+ override fun setUp() {
1619 myFixture.setUp()
20+ fileUtils = FileUtils(myFixture.project)
21+ }
1722
1823 override fun tearDown() =
1924 myFixture.tearDown()
2025
2126 fun `test fileExists`() {
22- val file = tmpFixture.createFile("test.txt", "")
23- val uri = "file://${file.path}"
24- assertTrue(fileUtils.fileExists(uri))
27+ myFixture.createTempFile("file.txt")
28+ assertTrue(fileUtils.fileExists("file://$tmp/file.txt"))
29+ }
30+
31+ fun `test fileExists with dir`() {
32+ myFixture.createTempFile("dir/dir/file.txt")
33+ assertTrue(fileUtils.fileExists("file://$tmp/dir/dir/file.txt"))
34+ }
35+
36+ fun `test fileExists fails when file is missing`() {
37+ assertFalse(fileUtils.fileExists("file://missing.txt"))
38+ }
39+
40+ fun `test fileExists fails when file and dir are missing`() {
41+ assertFalse(fileUtils.fileExists("file://dir/missing.txt"))
42+ }
43+
44+ fun `test writeFile creates missing file`() {
45+ fileUtils.writeFile("file://$tmp/file.txt", "text")
46+ assertEquals("text", myFixture.readTempFile("file.txt"))
2547 }
2648
27- fun `test fileExists inside directory`() {
28- val file = tmpFixture.createFile("dir/dir2/file.txt", "")
29- val uri = "file://${file.path}"
30- assertTrue(fileUtils.fileExists(uri))
49+ fun `test writeFile creates missing file and missing dirs`() {
50+ fileUtils.writeFile("file://$tmp/missing/dir/to/file.txt", "text")
51+ assertEquals("text", myFixture.readTempFile("missing/dir/to/file.txt"))
3152 }
3253
33- fun `test fileExists fails when file doesn't exists`() {
34- val uri = "file:///tmp/aaaa.txt"
35- assertFalse(fileUtils.fileExists(uri))
54+ fun `test writeFile overwrites existing file`() {
55+ myFixture.createTempFile("file.txt", "old_text")
56+ fileUtils.writeFile("file://$tmp/overwrite.txt", "new_text")
57+ assertEquals("new_text", myFixture.readTempFile("overwrite.txt"))
3658 }
3759
3860 fun `test readFile`() {
39- val uri = "file://$tmpDir/bbbb.txt"
40- tmpFixture.createFile("bbbb.txt", "contents")
41- val text = fileUtils.readFile(uri)
42- assertEquals("contents", text)
61+ myFixture.createTempFile("file.txt", "text")
62+ assertEquals("text", fileUtils.readFile("file://$tmp/file.txt"))
63+ }
64+
65+ fun `test readFile limits the output to specified length`() {
66+ myFixture.createTempFile("limited.txt", "text")
67+ val text = fileUtils.readFile("file://$tmp/limited.txt", maxLength = 3)
68+ assertEquals("tex", text)
69+ }
70+
71+ fun `test readFile inside dir`() {
72+ myFixture.createTempFile("dir/dir/file.txt", "text")
73+ assertEquals("text", fileUtils.readFile("file://$tmp/dir/dir/file.txt"))
74+ }
75+
76+ fun `test readFile fails when file is missing`() {
77+ assertEmpty(fileUtils.readFile("file://missing.txt"))
78+ }
79+
80+ fun `test readFile normalizes line endings`() {
81+ myFixture.createTempFile("file.txt", "line\r\nline\rline\nline")
82+ val normalized = fileUtils.readFile("file://$tmp/file.txt")
83+ assertEquals("line\nline\nline\nline", normalized)
4384 }
4485
4586 fun `test listDir`() {
46- tmpFixture.createFile("a.txt", "a")
47- tmpFixture.createFile("b.txt", "b")
48- tmpFixture.createFile("c.txt", "c")
49- tmpFixture.createFile("dir/invisibleA.txt", "d")
50- tmpFixture.createFile("dir/invisibleB.txt", "e")
87+ myFixture.createTempFile("a.txt", "a")
88+ myFixture.createTempFile("b.txt", "b")
89+ myFixture.createTempFile("c.txt", "c")
90+ myFixture.createTempFile("dir/invisibleA.txt", "d")
91+ myFixture.createTempFile("dir/invisibleB.txt", "e")
5192
52- val result = fileUtils.listDir("file://$tmpDir")
93+ val result = fileUtils.listDir("file://$tmp")
5394
5495 assertTrue(result.any { it[0] == "a.txt" && it[1] == FileType.FILE.value })
5596 assertTrue(result.any { it[0] == "b.txt" && it[1] == FileType.FILE.value })
@@ -61,10 +102,57 @@
61102 assertEquals(4, result.size)
62103 }
63104
64- private companion object {
105+ fun `test listDir works with empty dir`() {
106+ val result = fileUtils.listDir("file://$tmp")
107+ assertEmpty(result)
108+ }
109+
110+ fun `test listDir invalid usage with file instead of dir results in empty list`() {
111+ myFixture.createTempFile("file.txt")
112+ val invalid = fileUtils.listDir("file://$tmp/file.txt")
113+ assertEmpty(invalid)
114+ }
115+
116+ fun `test openFile opens editor`() {
117+ myFixture.createTempFile("file.txt", "text")
118+ fileUtils.openFile("file://$tmp/file.txt")
119+ val virtualFile = myFixture.tempDirFixture.getFile("file.txt")!!
120+ assertTrue(FileEditorManager.getInstance(myFixture.project).isFileOpen(virtualFile))
121+ }
122+
123+ fun `test openFile ignores non-existing file`() {
124+ fileUtils.openFile("file://$tmp/invalid.txt")
125+ }
126+
127+ fun `test saveFile`() {
128+ val manager = FileDocumentManager.getInstance()
129+ val modified = myFixture.createTempFile("modified.txt")
130+ val document = manager.getDocument(modified)!!
131+ runWriteAction {
132+ document.setText("modified content")
133+ }
134+ assertTrue(manager.isDocumentUnsaved(document))
135+ fileUtils.saveFile("file://$tmp/modified.txt")
136+ assertFalse(manager.isDocumentUnsaved(document))
137+ }
65138
139+ fun `test getFileStats`() {
140+ myFixture.createTempFile("a.txt", "aa")
141+ myFixture.createTempFile("b.txt", "bbbbb")
142+
143+ val stats = fileUtils.getFileStats(listOf("file://$tmp/a.txt", "file://$tmp/b.txt"))
144+
145+ assertTrue(stats.any { (fileUri, stats) -> fileUri == "file://$tmp/a.txt" && stats.size == 2L })
146+ assertTrue(stats.any { (fileUri, stats) -> fileUri == "file://$tmp/b.txt" && stats.size == 5L })
147+ }
148+
149+ fun `test getFileStats ignores non-existing file`() {
150+ assertTrue(fileUtils.getFileStats(listOf("file://invalid.txt")).isEmpty())
151+ }
152+
153+ private companion object {
66154 // note: with this, files will actually exist inside /tmp/unitTest/ dir, otherwise it's virtual
67- fun setupRealFilesFixture(): CodeInsightTestFixture {
155+ private fun setupRealFilesFixture(): CodeInsightTestFixture {
68156 val factory = IdeaTestFixtureFactory.getFixtureFactory()
69157 return factory.createCodeInsightFixture(
70158 factory.createLightFixtureBuilder("my_continue_project").fixture,
@@ -72,6 +160,13 @@
72160 )
73161 }
74162
75- }
163+ private fun CodeInsightTestFixture.createTempFile(path: String, content: String = "") =
164+ tempDirFixture.createFile(path, content)
76165
166+ private fun CodeInsightTestFixture.readTempFile(path: String): String {
167+ val file = tempDirFixture.getFile(path)!!
168+ VfsUtil.markDirtyAndRefresh(false, false, false, file)
169+ return VfsUtil.loadText(file)
170+ }
171+ }
77172 }
No newline at the end of the file
modified extensions/vscode/README.md +16 −16
@@ -2,16 +2,6 @@
22
33 ![Continue logo](media/readme.png)
44
5-</div>
6-
7-<h1 align="center">Continue</h1>
8-
9-<div align="center">
10-
11-**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code extension](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
12-
13-</div>
14-
155 <div align="center">
166
177 <a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
@@ -26,29 +16,39 @@
2616
2717 <p></p>
2818
19+</div>
20+
21+<h1 align="center">Continue</h1>
22+
23+<div align="center">
24+
25+**Ship faster with Continuous AI**
26+
27+**Build and run custom agents across your IDE, terminal, and CI**
28+
29+</div>
30+
2931 ## Agent
3032
31-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
33+[Agent](/features/agent/quick-start) to work on development tasks together with AI
3234
3335 ![agent](docs/images/agent.gif)
3436
3537 ## Chat
3638
37-[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
38-the IDE
39+[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
3940
4041 ![chat](docs/images/chat.gif)
4142
4243 ## Edit
4344
44-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
45-file
45+[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
4646
4747 ![edit](docs/images/edit.gif)
4848
4949 ## Autocomplete
5050
51-[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
51+[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
5252
5353 ![autocomplete](docs/images/autocomplete.gif)
5454
modified extensions/vscode/package.json +2 −2
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.75",
5+ "version": "1.1.78",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -695,7 +695,7 @@
695695 "e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh",
696696 "e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
697697 "e2e:install-extensions": "extest install-from-marketplace ms-vscode-remote.remote-ssh --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage && extest install-from-marketplace ms-vscode-remote.remote-containers --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage && extest install-from-marketplace ms-vscode-remote.remote-wsl --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
698- "e2e:test": "extest run-tests ${TEST_FILE:-'./e2e/_output/tests/*.test.js'} --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
698+ "e2e:test": "NODE_ENV=e2e extest run-tests ${TEST_FILE:-'./e2e/_output/tests/*.test.js'} --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
699699 "e2e:clean": "rm -rf ./e2e/_output ./e2e/storage",
700700 "e2e:all": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
701701 "e2e:all-non-mac": "npm run e2e:build && npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && npm run e2e:install-extensions && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
modified extensions/vscode/src/VsCodeIde.ts +4 −4
@@ -262,10 +262,10 @@
262262 }
263263
264264 async getClipboardContent() {
265- return this.context.workspaceState.get("continue.copyBuffer", {
266- text: "",
267- copiedAt: new Date("1900-01-01").toISOString(),
268- });
265+ return {
266+ text: await vscode.env.clipboard.readText(),
267+ copiedAt: new Date().toISOString(),
268+ };
269269 }
270270
271271 async getTerminalContents(): Promise<string> {
modified extensions/vscode/src/activation/JumpManager.ts +143 −21
@@ -1,11 +1,65 @@
11 import { NextEditProvider } from "core/nextEdit/NextEditProvider";
22 import { NextEditOutcome } from "core/nextEdit/types";
3+// @ts-ignore
4+import svgBuilder from "svg-builder";
35 import * as vscode from "vscode";
6+import { getTheme } from "../util/getTheme";
47 import {
58 HandlerPriority,
69 SelectionChangeManager,
710 } from "./SelectionChangeManager";
811
12+// Instead of getters that execute immediately, use methods or lazy properties
13+const SVG_CONFIG = {
14+ stroke: "#999998",
15+ strokeWidth: 1,
16+ shortcutColor: "#999998",
17+ filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
18+ radius: 3,
19+ leftMargin: 40,
20+ debounceDelay: 500,
21+ label: "📍 Press Tab to jump, Esc to cancel",
22+
23+ // Convert getters to methods that are called when needed
24+ getFontSize(): number {
25+ return Math.ceil(
26+ (vscode.workspace.getConfiguration("editor").get<number>("fontSize") ??
27+ 14) * 0.8,
28+ );
29+ },
30+
31+ getFontFamily(): string {
32+ return (
33+ vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
34+ "helvetica"
35+ );
36+ },
37+
38+ getPaddingX(): number {
39+ return Math.ceil(this.getEstimatedTextWidth(" "));
40+ },
41+
42+ getGap(): number {
43+ return this.getFontSize() * 0.5;
44+ },
45+
46+ getTipWidth(): number {
47+ return this.getEstimatedTextWidth(this.label) + this.getPaddingX();
48+ },
49+
50+ getTipHeight(): number {
51+ return this.getFontSize();
52+ },
53+
54+ getTextY(): number {
55+ return (this.getTipHeight() + this.getFontSize()) / 2;
56+ },
57+
58+ getEstimatedTextWidth(text: string): number {
59+ return text.length * this.getFontSize() * 0.6;
60+ },
61+} as const;
62+
963 export interface CompletionDataForAfterJump {
1064 completionId: string;
1165 outcome: NextEditOutcome;
@@ -16,16 +70,29 @@
1670 private static _instance: JumpManager | undefined;
1771
1872 // Decoration state.
73+ private _jumpIcon: vscode.Uri | undefined;
1974 private _jumpDecoration: vscode.TextEditorDecorationType | undefined;
2075 private _jumpDecorationVisible = false;
2176 private _disposables: vscode.Disposable[] = [];
77+ private _theme = getTheme();
2278
2379 private _jumpInProgress: boolean = false;
2480 private _jumpAccepted: boolean = false;
2581 private _completionAfterJump: CompletionDataForAfterJump | null = null;
2682 private _oldCursorPosition: vscode.Position | undefined;
2783
28- private constructor() {}
84+ private constructor() {
85+ // Build the first SVG icon
86+ this._createSvgJumpIcon();
87+
88+ // Re‑build when the colour theme changes
89+ vscode.workspace.onDidChangeConfiguration((e) => {
90+ if (e.affectsConfiguration("workbench.colorTheme")) {
91+ this._theme = getTheme();
92+ this._createSvgJumpIcon();
93+ }
94+ });
95+ }
2996
3097 initialize() {}
3198
@@ -51,6 +118,62 @@
51118 this._disposables = [];
52119 }
53120
121+ private _createSvgJumpIcon() {
122+ // if (!this._theme) {
123+ // return;
124+ // }
125+
126+ const baseTextConfig = {
127+ y: SVG_CONFIG.getTextY(),
128+ "font-family": SVG_CONFIG.getFontFamily(),
129+ "font-size": SVG_CONFIG.getFontSize(),
130+ };
131+
132+ try {
133+ const svgContent = svgBuilder
134+ .width(SVG_CONFIG.getTipWidth())
135+ .height(SVG_CONFIG.getTipHeight())
136+ .text(
137+ {
138+ ...baseTextConfig,
139+ x: 4,
140+ fill: this._theme?.colors["editor.foreground"] ?? SVG_CONFIG.stroke,
141+ },
142+ SVG_CONFIG.label,
143+ )
144+ .render();
145+
146+ const dataUri = `data:image/svg+xml;base64,${Buffer.from(
147+ svgContent,
148+ ).toString("base64")}`;
149+ this._jumpIcon = vscode.Uri.parse(dataUri);
150+
151+ // Dispose the old decoration (if any) and create a fresh one.
152+ if (this._jumpDecoration) {
153+ this._jumpDecoration.dispose();
154+ }
155+ this._jumpDecoration = this._createSvgJumpDecoration();
156+ } catch (err) {
157+ console.error("Error creating SVG jump tooltip:", err);
158+ }
159+ }
160+
161+ private _createSvgJumpDecoration(): vscode.TextEditorDecorationType {
162+ const backgroundColour =
163+ this._theme?.colors["editor.background"] ?? "#333333";
164+
165+ return vscode.window.createTextEditorDecorationType({
166+ after: {
167+ contentIconPath: this._jumpIcon,
168+ border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${SVG_CONFIG.getTipHeight()}px ${backgroundColour};
169+ border-radius: ${SVG_CONFIG.radius}px;
170+ filter: ${SVG_CONFIG.filter}`,
171+ margin: `0 0 0 ${SVG_CONFIG.leftMargin}px`,
172+ width: `${SVG_CONFIG.getTipWidth()}px`,
173+ },
174+ });
175+ }
176+
54177 public async suggestJump(
55178 currentPosition: vscode.Position,
56179 nextJumpLocation: vscode.Position,
@@ -157,17 +280,6 @@
157280 );
158281 }
159282
160- // Scroll to show the jump location.
161- editor.revealRange(
162- new vscode.Range(decorationLine, 0, decorationLine, 0),
163- vscode.TextEditorRevealType.InCenter,
164- );
165-
166- // Clean up after timeout if no jump has been made.
167- // setTimeout(() => {
168- // this._jumpInProgress = false;
169- // }, 10000);
170-
171283 return true;
172284 }
173285
@@ -180,18 +292,22 @@
180292 await this.clearJumpDecoration();
181293
182294 // Create a decoration for jump.
183- this._jumpDecoration = vscode.window.createTextEditorDecorationType({
184- before: {
185- contentText: "📍 Press Tab to jump, Esc to cancel",
186- color: new vscode.ThemeColor("editor.foreground"),
187- backgroundColor: new vscode.ThemeColor("editorInfo.background"),
188- margin: `0 0 0 4px`,
189- },
190- });
295+ // this._jumpDecoration = vscode.window.createTextEditorDecorationType({
296+ // before: {
297+ // contentText: "📍 Press Tab to jump, Esc to cancel",
298+ // color: new vscode.ThemeColor("editor.foreground"),
299+ // backgroundColor: new vscode.ThemeColor("editorHover.background"),
300+ // margin: `0 0 0 4px`,
301+ // },
302+ // });
303+
304+ if (!this._jumpDecoration) {
305+ this._createSvgJumpIcon(); // makes both the icon & decoration
306+ }
191307
192308 // Apply the decoration.
193309 const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length;
194- editor.setDecorations(this._jumpDecoration, [
310+ editor.setDecorations(this._jumpDecoration!, [
195311 new vscode.Range(
196312 lineToRenderOn,
197313 lastIndexOfLine,
@@ -240,6 +356,12 @@
240356 if (this._jumpDecorationVisible) {
241357 this._jumpAccepted = true;
242358
359+ // Scroll to show the jump location.
360+ editor.revealRange(
361+ new vscode.Range(jumpPosition.line, 0, jumpPosition.line, 0),
362+ vscode.TextEditorRevealType.InCenter,
363+ );
364+
243365 // Move cursor to the jump position.
244366 editor.selection = new vscode.Selection(jumpPosition, jumpPosition);
245367 await this.clearJumpDecoration();
modified extensions/vscode/src/activation/JumpManager.vitest.ts +90 −13
@@ -36,6 +36,21 @@
3636 dispose: vi.fn(),
3737 }),
3838 },
39+ workspace: {
40+ getConfiguration: vi.fn().mockImplementation((section?: string) => {
41+ // Return a configuration object with a get method
42+ return {
43+ get: vi.fn().mockImplementation((key: string) => {
44+ if (key === "fontSize") return 14;
45+ if (key === "fontFamily") return "monaco";
46+ return undefined;
47+ }),
48+ };
49+ }),
50+ onDidChangeConfiguration: vi.fn().mockReturnValue({
51+ dispose: vi.fn(),
52+ }),
53+ },
3954 Position: class {
4055 constructor(
4156 public line: number,
@@ -69,6 +84,32 @@
6984 dispose: vi.fn(),
7085 }),
7186 },
87+ Uri: {
88+ parse: vi.fn().mockReturnValue({ toString: () => "mock-uri" }),
89+ },
90+ };
91+});
92+
93+// Mock getTheme utility
94+vi.mock("../util/getTheme", () => ({
95+ getTheme: vi.fn().mockReturnValue({
96+ colors: {
97+ "editor.foreground": "#ffffff",
98+ "editor.background": "#1e1e1e",
99+ },
100+ }),
101+}));
102+
103+// Mock svg-builder
104+vi.mock("svg-builder", () => {
105+ const mockSvgBuilder = {
106+ width: vi.fn().mockReturnThis(),
107+ height: vi.fn().mockReturnThis(),
108+ text: vi.fn().mockReturnThis(),
109+ render: vi.fn().mockReturnValue("<svg>mock svg</svg>"),
110+ };
111+ return {
112+ default: mockSvgBuilder,
72113 };
73114 });
74115
@@ -152,20 +193,32 @@
152193 let jumpManager: JumpManager;
153194
154195 beforeEach(() => {
155- // Reset mocks
156- vi.resetAllMocks();
157-
158- // Re-setup the lineAt mock after reset
159- const mockLineAt = vi.fn().mockReturnValue({
160- text: "Sample line text",
161- lineNumber: 0,
196+ // Clear mock history but keep implementations
197+ vi.clearAllMocks();
198+
199+ // Create a proper TextLine mock
200+ const createMockTextLine = (text: string, lineNumber: number) => ({
201+ text,
202+ lineNumber,
203+ range: new vscode.Range(lineNumber, 0, lineNumber, text.length),
204+ rangeIncludingLineBreak: new vscode.Range(
205+ lineNumber,
206+ 0,
207+ lineNumber + 1,
208+ 0,
209+ ),
210+ firstNonWhitespaceCharacterIndex: text.search(/\S/),
211+ isEmptyOrWhitespace: text.trim().length === 0,
162212 });
163213
164- // Ensure our mock is properly set up after reset
165- if (vscode.window.activeTextEditor?.document) {
214+ // Reset lineAt mock with proper TextLine objects
215+ if (vscode.window.activeTextEditor?.document.lineAt) {
166216 vi.mocked(
167217 vscode.window.activeTextEditor.document.lineAt,
168- ).mockImplementation(mockLineAt);
218+ // @ts-ignore
219+ ).mockImplementation((line: number) =>
220+ createMockTextLine("Sample line text", line),
221+ );
169222 }
170223
171224 // Clear any existing instance
@@ -240,7 +293,7 @@
240293 // Decorations should not be created
241294 expect(
242295 vscode.window.createTextEditorDecorationType,
243- ).not.toHaveBeenCalled();
296+ ).toHaveBeenCalledOnce(); // only during setup
244297 });
245298
246299 it("should render decoration for jump location outside visible range (below)", async () => {
@@ -293,8 +346,32 @@
293346
294347 // Should create decoration
295348 expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled();
296- // Should reveal range
297- expect(vscode.window.activeTextEditor!.revealRange).toHaveBeenCalled();
349+ // Should not reveal range
350+ expect(
351+ vscode.window.activeTextEditor!.revealRange,
352+ ).not.toHaveBeenCalled();
353+ });
354+
355+ it("should call revealRange when jump is accepted", async () => {
356+ const currentPosition = new vscode.Position(1, 0);
357+ const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range
358+
359+ await jumpManager.suggestJump(currentPosition, nextJumpLocation);
360+
361+ // Find the acceptJump command handler.
362+ const commandArgs = vi
363+ .mocked(vscode.commands.registerCommand)
364+ .mock.calls.find((call: any) => call[0] === "continue.acceptJump");
365+ expect(commandArgs).toBeDefined();
366+ const acceptJumpHandler = commandArgs![1];
367+
368+ await acceptJumpHandler();
369+
370+ // Should reveal the jump location range after jumping.
371+ expect(vscode.window.activeTextEditor!.revealRange).toHaveBeenCalledWith(
372+ new vscode.Range(nextJumpLocation.line, 0, nextJumpLocation.line, 0),
373+ vscode.TextEditorRevealType.InCenter,
374+ );
298375 });
299376 });
300377
modified extensions/vscode/src/activation/NextEditWindowManager.ts +12 −16
@@ -669,17 +669,9 @@
669669 const offsetFromTop =
670670 (position.line - editableRegionStartLine) * SVG_CONFIG.lineHeight;
671671
672- // Set the margin-left so that it's never covering code inside the editable region.
673- const marginLeft =
674- SVG_CONFIG.getTipWidth(originalCode) -
675- SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]);
676-
677- // console.log(marginLeft);
678- // console.log(SVG_CONFIG.getTipWidth(originalCode));
679- // console.log(
680- // SVG_CONFIG.getTipWidth(originalCode.split("\n")[currLineOffsetFromTop]),
681- // );
682- // console.log(originalCode.split("\n")[currLineOffsetFromTop]);
672+ // Position the decoration with minimal left margin since it's already at line end
673+ const marginLeft = SVG_CONFIG.paddingX; // Use consistent padding instead of complex calculation
674+
683675 return vscode.window.createTextEditorDecorationType({
684676 before: {
685677 contentIconPath: uri,
@@ -770,12 +762,16 @@
770762 ): vscode.Position {
771763 // Create a position that's offset spaces to the right of the cursor.
772764
765+ // const line = editor.document.lineAt(position.line);
766+ // const offsetChar = Math.min(
767+ // position.character + SVG_CONFIG.cursorOffset,
768+ // line.text.length,
769+ // );
770+ // return new vscode.Position(position.line, offsetChar);
771+
772+ // Place decoration at the end of the current line
773773 const line = editor.document.lineAt(position.line);
774- const offsetChar = Math.min(
775- position.character + SVG_CONFIG.cursorOffset,
776- line.text.length,
777- );
778- return new vscode.Position(position.line, offsetChar);
774+ return new vscode.Position(position.line, line.text.length);
779775 }
780776
781777 /**
modified extensions/vscode/src/apply/ApplyManager.ts +28 −20
@@ -50,37 +50,45 @@
5050 toolCallId,
5151 });
5252
53- const hasExistingDocument = !!activeTextEditor.document.getText().trim();
53+ try {
54+ const hasExistingDocument = !!activeTextEditor.document.getText().trim();
5455
55- if (hasExistingDocument) {
56- // Currently `isSearchAndReplace` will always provide a full file rewrite
57- // as the contents of `text`, so we can just instantly apply
58- if (isSearchAndReplace) {
59- const diffLinesGenerator = generateLines(
60- myersDiff(activeTextEditor.document.getText(), text),
61- );
56+ if (hasExistingDocument) {
57+ // Currently `isSearchAndReplace` will always provide a full file rewrite
58+ // as the contents of `text`, so we can just instantly apply
59+ if (isSearchAndReplace) {
60+ const diffLinesGenerator = generateLines(
61+ myersDiff(activeTextEditor.document.getText(), text),
62+ );
6263
63- await this.verticalDiffManager.streamDiffLines(
64- diffLinesGenerator,
65- true,
66- streamId,
67- toolCallId,
68- );
64+ await this.verticalDiffManager.streamDiffLines(
65+ diffLinesGenerator,
66+ true,
67+ streamId,
68+ toolCallId,
69+ );
70+ } else {
71+ await this.handleExistingDocument(
72+ activeTextEditor,
73+ text,
74+ streamId,
75+ toolCallId,
76+ );
77+ }
6978 } else {
70- await this.handleExistingDocument(
79+ await this.handleEmptyDocument(
7180 activeTextEditor,
7281 text,
7382 streamId,
7483 toolCallId,
7584 );
7685 }
77- } else {
78- await this.handleEmptyDocument(
79- activeTextEditor,
80- text,
86+ } finally {
87+ await this.webviewProtocol.request("updateApplyState", {
8188 streamId,
89+ status: "closed",
8290 toolCallId,
83- );
91+ });
8492 }
8593 }
8694
modified extensions/vscode/src/autocomplete/completionProvider.ts +5 −9
@@ -261,18 +261,15 @@
261261
262262 let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
263263
264- // console.log(
265- // "chain exists?",
266- // this.nextEditProvider.chainExists(),
267- // ", length:",
268- // this.nextEditProvider.getChainLength(),
269- // ", next regions queue:",
270- // this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(),
271- // );
264+ // TODO: We can probably decide here if we want to do the jumping logic.
265+ // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
266+ // It would simplify the logic quite substantially.
272267
273268 // Determine why this method was triggered.
274269 const isJumping = this.jumpManager.isJumpInProgress();
275270 const chainExists = this.nextEditProvider.chainExists();
271+ console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
272+ this.prefetchQueue.peekThreeProcessed();
276273
277274 if (isJumping && chainExists) {
278275 // Case 2: Jumping (chain exists, jump was taken)
@@ -340,7 +337,6 @@
340337
341338 if (isJumpSuggested) {
342339 // Store completion to be rendered after a jump.
343- // TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location.
344340 this.jumpManager.setCompletionAfterJump({
345341 completionId: completionId,
346342 outcome,
modified extensions/vscode/src/commands.ts +0 −55
@@ -8,7 +8,6 @@
88 import { Core } from "core/core";
99 import { walkDirAsync } from "core/indexing/walkDir";
1010 import { isModelInstaller } from "core/llm";
11-import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
1211 import { startLocalOllama } from "core/util/ollamaHelper";
1312 import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths";
1413 import { Telemetry } from "core/util/posthog";
@@ -808,44 +807,6 @@
808807 };
809808 };
810809
811-const registerCopyBufferService = (
812- context: vscode.ExtensionContext,
813- core: Core,
814-) => {
815- const typeDisposable = vscode.commands.registerCommand(
816- "editor.action.clipboardCopyAction",
817- async (arg) => doCopy(typeDisposable),
818- );
819-
820- async function doCopy(typeDisposable: any) {
821- typeDisposable.dispose(); // must dispose to avoid endless loops
822-
823- await vscode.commands.executeCommand("editor.action.clipboardCopyAction");
824-
825- const clipboardText = await vscode.env.clipboard.readText();
826-
827- if (clipboardText) {
828- core.invoke("clipboardCache/add", {
829- content: clipboardText,
830- });
831- }
832-
833- await context.workspaceState.update("continue.copyBuffer", {
834- text: clipboardText,
835- copiedAt: new Date().toISOString(),
836- });
837-
838- // re-register to continue intercepting copy commands
839- typeDisposable = vscode.commands.registerCommand(
840- "editor.action.clipboardCopyAction",
841- async () => doCopy(typeDisposable),
842- );
843- context.subscriptions.push(typeDisposable);
844- }
845-
846- context.subscriptions.push(typeDisposable);
847-};
848-
849810 async function installModelWithProgress(
850811 modelName: string,
851812 modelInstaller: ModelInstaller,
@@ -916,20 +877,4 @@
916877 vscode.commands.registerCommand(command, callback),
917878 );
918879 }
919-
920- try {
921- registerCopyBufferService(context, core);
922- } catch (e: any) {
923- //Non-critical error, it needs to be intercepted and not prevent the extension from starting
924- console.log("Error registering CopyBufferService: ", e);
925- Telemetry.capture(
926- "vscode_extension_copy_buffer_failure",
927- {
928- stack: extractMinimalStackTraceInfo(e.stack),
929- message: e.message,
930- },
931- false,
932- true,
933- );
934- }
935880 }
modified extensions/vscode/src/diff/vertical/manager.ts +1 −0
@@ -536,6 +536,7 @@
536536 streamId: EDIT_MODE_STREAM_ID,
537537 timestamp: new Date().toISOString(),
538538 modelProvider: model.underlyingProviderName,
539+ modelName: model.title ?? "",
539540 modelTitle: model.title ?? "",
540541 prompt: stripImages(prompt),
541542 completion: newCode,
modified extensions/vscode/src/extension.ts +3 −1
@@ -7,6 +7,7 @@
77 import { Telemetry } from "core/util/posthog";
88 import * as vscode from "vscode";
99
10+import { SentryLogger } from "core/util/sentry/SentryLogger";
1011 import { getExtensionVersion } from "./util/util";
1112 export { default as buildTimestamp } from "./.buildTimestamp";
1213
@@ -46,7 +47,7 @@
4647 }
4748
4849 export function deactivate() {
49- Telemetry.capture(
50+ void Telemetry.capture(
5051 "deactivate",
5152 {
5253 extensionVersion: getExtensionVersion(),
@@ -55,4 +56,5 @@
5556 );
5657
5758 Telemetry.shutdownPosthogClient();
59+ SentryLogger.shutdownSentryClient();
5860 }
modified extensions/vscode/src/extension/EditOutcomeTracker.ts +3 −1
@@ -6,6 +6,7 @@
66 streamId: string;
77 timestamp: string;
88 modelProvider: string;
9+ modelName: string;
910 modelTitle: string;
1011 prompt: string;
1112 completion: string;
@@ -56,7 +57,8 @@
5657 name: "editOutcome",
5758 data: {
5859 modelProvider: pendingEdit.modelProvider,
59- modelTitle: pendingEdit.modelTitle,
60+ modelName: pendingEdit.modelName,
61+ modelTitle: pendingEdit.modelName,
6062 prompt: pendingEdit.prompt,
6163 completion: pendingEdit.completion,
6264 previousCode: pendingEdit.previousCode,
modified extensions/vscode/src/extension/VsCodeExtension.ts +3 −1
@@ -86,6 +86,7 @@
8686 constructor(context: vscode.ExtensionContext) {
8787 // Register auth provider
8888 this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
89+
8990 void this.workOsAuthProvider.refreshSessions();
9091 context.subscriptions.push(this.workOsAuthProvider);
9192
@@ -113,7 +114,8 @@
113114 Date.now() - state.lastDocumentChangeTime;
114115 if (
115116 state.isTypingSession &&
116- timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY
117+ timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
118+ !NextEditWindowManager.getInstance().hasAccepted()
117119 ) {
118120 console.log("VsCodeExtension: typing in progress, preserving chain");
119121 return true;
modified extensions/vscode/src/extension/VsCodeMessenger.ts +2 −0
@@ -30,6 +30,7 @@
3030 import { getExtensionUri } from "../util/vscode";
3131 import { VsCodeIde } from "../VsCodeIde";
3232 import { VsCodeWebviewProtocol } from "../webviewProtocol";
33+
3334 import { VsCodeExtension } from "./VsCodeExtension";
3435
3536 type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
@@ -240,6 +241,7 @@
240241 prompt: stripImages(prompt),
241242 completion: fileAfterEdit ?? "",
242243 modelProvider: model.underlyingProviderName,
244+ modelName: model.title ?? "",
243245 modelTitle: model.title ?? "",
244246 filepath: msg.data.range.filepath,
245247 },
modified extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +5 −5
@@ -238,15 +238,15 @@
238238 prompt: string,
239239 path: string | undefined,
240240 ) => {
241- const model = await this.getCurModel();
242- if (!model) {
241+ const modelTitle = await this.getCurModel();
242+ if (!modelTitle) {
243243 throw new Error("No model selected");
244244 }
245245
246246 const { config } = await this.configHandler.loadConfig();
247247 const rules = config?.rules ?? []; // no need to error - getCurModel above will handle
248248
249- await this._streamEditWithInputAndContext(prompt, model, rules);
249+ await this._streamEditWithInputAndContext(prompt, modelTitle, rules);
250250 this.openAcceptRejectMenu(prompt, path);
251251 };
252252
@@ -352,9 +352,9 @@
352352 label: QuickEditInitialItemLabels | undefined;
353353 value: string | undefined;
354354 }> {
355- const modelTitle = await this.getCurModel();
355+ const model = await this.getCurModel();
356356
357- if (!modelTitle) {
357+ if (!model) {
358358 this.ide.showToast("error", "Please configure a model to use Quick Edit");
359359 return { label: undefined, value: undefined };
360360 }
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +44 −1
@@ -1,4 +1,5 @@
11 import crypto from "crypto";
2+import { EventEmitter as NodeEventEmitter } from "node:events";
23
34 import {
45 AuthType,
@@ -7,8 +8,8 @@
78 isHubEnv,
89 } from "core/control-plane/AuthTypes";
910 import { getControlPlaneEnvSync } from "core/control-plane/env";
11+import { Logger } from "core/util/Logger";
1012 import fetch from "node-fetch";
11-import { EventEmitter as NodeEventEmitter } from "node:events";
1213 import { v4 as uuidv4 } from "uuid";
1314 import {
1415 authentication,
@@ -121,6 +122,13 @@
121122 );
122123 return decodedToken;
123124 } catch (e: any) {
125+ // Capture JWT decoding failures to Sentry (could indicate token corruption)
126+ Logger.error(e, {
127+ context: "workOS_auth_jwt_decode",
128+ jwtLength: jwt.length,
129+ jwtPrefix: jwt.substring(0, 20) + "...", // Safe prefix for debugging
130+ });
131+
124132 console.warn(`Error decoding JWT: ${e}`);
125133 return null;
126134 }
@@ -162,6 +170,12 @@
162170 const value = JSON.parse(data) as ContinueAuthenticationSession[];
163171 return value;
164172 } catch (e: any) {
173+ // Capture session file parsing errors to Sentry
174+ Logger.error(e, {
175+ context: "workOS_sessions_json_parse",
176+ dataLength: data.length,
177+ });
178+
165179 console.warn(`Error parsing sessions.json: ${e}`);
166180 return [];
167181 }
@@ -200,6 +214,12 @@
200214 this._isRefreshing = true;
201215 await this._refreshSessions();
202216 } catch (e) {
217+ // Capture session refresh failures to Sentry
218+ Logger.error(e, {
219+ context: "workOS_auth_session_refresh",
220+ authType: controlPlaneEnv.AUTH_TYPE,
221+ });
222+
203223 console.error(`Error refreshing sessions: ${e}`);
204224 } finally {
205225 this._isRefreshing = false;
@@ -228,6 +248,12 @@
228248 expiresInMs: newSession.expiresInMs,
229249 });
230250 } catch (e: any) {
251+ // Capture individual session refresh failures to Sentry
252+ Logger.error(e, {
253+ context: "workOS_individual_session_refresh",
254+ sessionId: session.id,
255+ });
256+
231257 // If refresh fails (after retries for valid tokens), drop the session
232258 console.debug(`Error refreshing session token: ${e.message}`);
233259 this._sessionChangeEmitter.fire({
@@ -258,6 +284,16 @@
258284 try {
259285 return await this._refreshSession(refreshToken);
260286 } catch (error: any) {
287+ // Capture token refresh retry errors to Sentry
288+ Logger.error(error, {
289+ attempt,
290+ errorMessage: error.message,
291+ isAuthError:
292+ error.message?.includes("401") ||
293+ error.message?.includes("Invalid refresh token") ||
294+ error.message?.includes("Unauthorized"),
295+ });
296+
261297 this.attemptEmitter.emit("attempted");
262298 // Don't retry for auth errors
263299 if (
@@ -374,6 +410,13 @@
374410
375411 return session;
376412 } catch (e) {
413+ // Capture authentication failures to Sentry
414+ Logger.error(e, {
415+ context: "workOS_auth_session_creation",
416+ scopes: scopes.join(","),
417+ authType: controlPlaneEnv.AUTH_TYPE,
418+ });
419+
377420 void window.showErrorMessage(`Sign in failed: ${e}`);
378421 throw e;
379422 }
modified gui/.gitignore +3 −1
@@ -24,4 +24,6 @@
2424 *.sw?
2525
2626 # test result files
27-coverage
No newline at the end of the file
27+coverage
28+# Sentry Config File
29+.env.sentry-build-plugin
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/package.json +4 −2
@@ -21,6 +21,8 @@
2121 "@heroicons/react": "^2.0.18",
2222 "@panzoom/panzoom": "^4.6.0",
2323 "@reduxjs/toolkit": "^2.3.0",
24+ "@sentry/react": "^9.43.0",
25+ "@sentry/vite-plugin": "^4.0.2",
2426 "@tiptap/core": "^2.3.2",
2527 "@tiptap/extension-document": "^2.3.2",
2628 "@tiptap/extension-dropcursor": "^2.1.16",
@@ -82,8 +84,8 @@
8284 "@swc/cli": "^0.3.14",
8385 "@swc/core": "^1.7.26",
8486 "@testing-library/dom": "^10.4.0",
85- "@testing-library/jest-dom": "^6.5.0",
86- "@testing-library/react": "^16.0.1",
87+ "@testing-library/jest-dom": "^6.6.4",
88+ "@testing-library/react": "^16.3.0",
8789 "@testing-library/user-event": "^14.5.2",
8890 "@types/dompurify": "^3.2.0",
8991 "@types/lodash": "^4.17.6",
modified gui/src/components/FeedbackButtons.tsx +5 −1
@@ -21,10 +21,14 @@
2121 setFeedback(feedback);
2222 if (item.promptLogs?.length) {
2323 for (const promptLog of item.promptLogs) {
24+ const { modelTitle, modelProvider, ...logData } = promptLog;
2425 ideMessenger.post("devdata/log", {
2526 name: "chatFeedback",
2627 data: {
27- ...promptLog,
28+ ...logData,
29+ modelProvider: modelProvider || "unknown",
30+ modelName: modelTitle,
31+ modelTitle: modelTitle,
2832 feedback,
2933 sessionId,
3034 },
modified gui/src/components/Layout.tsx +42 −37
@@ -6,6 +6,7 @@
66 import { AuthProvider } from "../context/Auth";
77 import { IdeMessengerContext } from "../context/IdeMessenger";
88 import { LocalStorageProvider } from "../context/LocalStorage";
9+import TelemetryProviders from "../hooks/TelemetryProviders";
910 import { useWebviewListener } from "../hooks/useWebviewListener";
1011 import { useAppDispatch, useAppSelector } from "../redux/hooks";
1112 import { setCodeToEdit } from "../redux/slices/editState";
@@ -26,6 +27,7 @@
2627 } from "./OnboardingCard";
2728 import OSRContextMenu from "./OSRContextMenu";
2829 import PostHogPageView from "./PosthogPageView";
30+import { FatalErrorIndicator } from "./config/FatalErrorNotice";
2931
3032 const LayoutTopDiv = styled(CustomScrollbarDiv)`
3133 height: 100%;
@@ -245,45 +247,48 @@
245247 return (
246248 <LocalStorageProvider>
247249 <AuthProvider>
248- <LayoutTopDiv>
249- {showStagingIndicator && (
250- <span
251- title="Staging environment"
252- className="absolute right-0 mx-1.5 h-1.5 w-1.5 rounded-full"
253- style={{
254- backgroundColor: "var(--vscode-list-warningForeground)",
255- }}
256- />
257- )}
258- <LumpProvider>
259- <OSRContextMenu />
260- <div
261- style={{
262- scrollbarGutter: "stable both-edges",
263- minHeight: "100%",
264- display: "grid",
265- gridTemplateRows: "1fr auto",
266- }}
267- >
268- <TextDialog
269- showDialog={showDialog}
270- onEnter={() => {
271- dispatch(setShowDialog(false));
250+ <TelemetryProviders>
251+ <LayoutTopDiv>
252+ {showStagingIndicator && (
253+ <span
254+ title="Staging environment"
255+ className="absolute right-0 mx-1.5 h-1.5 w-1.5 rounded-full"
256+ style={{
257+ backgroundColor: "var(--vscode-list-warningForeground)",
272258 }}
273- onClose={() => {
274- dispatch(setShowDialog(false));
275- }}
276- message={dialogMessage}
277259 />
278-
279- <GridDiv>
280- <PostHogPageView />
281- <Outlet />
282- </GridDiv>
283- </div>
284- <div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
285- </LumpProvider>
286- </LayoutTopDiv>
260+ )}
261+ <LumpProvider>
262+ <OSRContextMenu />
263+ <div
264+ style={{
265+ scrollbarGutter: "stable both-edges",
266+ minHeight: "100%",
267+ display: "grid",
268+ gridTemplateRows: "1fr auto",
269+ }}
270+ >
271+ <TextDialog
272+ showDialog={showDialog}
273+ onEnter={() => {
274+ dispatch(setShowDialog(false));
275+ }}
276+ onClose={() => {
277+ dispatch(setShowDialog(false));
278+ }}
279+ message={dialogMessage}
280+ />
281+
282+ <GridDiv>
283+ <PostHogPageView />
284+ <Outlet />
285+ <FatalErrorIndicator />
286+ </GridDiv>
287+ </div>
288+ <div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
289+ </LumpProvider>
290+ </LayoutTopDiv>
291+ </TelemetryProviders>
287292 </AuthProvider>
288293 </LocalStorageProvider>
289294 );
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +30 −0
@@ -1,10 +1,13 @@
11 import { ChevronDownIcon } from "@heroicons/react/24/outline";
22 import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
3+import { renderContextItems } from "core/util/messageContent";
34 import { useContext, useEffect, useMemo, useState } from "react";
45 import { IdeMessengerContext } from "../../../context/IdeMessenger";
56 import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest";
67 import { useWebviewListener } from "../../../hooks/useWebviewListener";
8+import { getStatusIcon } from "../../../pages/gui/ToolCallDiv/utils";
79 import { useAppSelector } from "../../../redux/hooks";
10+import { selectToolCallById } from "../../../redux/selectors/selectToolCalls";
811 import {
912 selectApplyStateByStreamId,
1013 selectApplyStateByToolCallId,
@@ -21,6 +24,7 @@
2124 import { RunInTerminalButton } from "./RunInTerminalButton";
2225
2326 export interface StepContainerPreToolbarProps {
27+ showToolCallStatusIcon?: boolean;
2428 codeBlockContent: string;
2529 language: string | null;
2630 relativeFilepath?: string;
@@ -37,6 +41,7 @@
3741 }
3842
3943 export function StepContainerPreToolbar({
44+ showToolCallStatusIcon,
4045 codeBlockContent,
4146 language,
4247 relativeFilepath,
@@ -81,6 +86,30 @@
8186 selectApplyStateByToolCallId(state, forceToolCallId),
8287 );
8388
89+ const toolCallState = useAppSelector((state) =>
90+ forceToolCallId ? selectToolCallById(state, forceToolCallId) : undefined,
91+ );
92+
93+ const toolCallStatusIcon =
94+ showToolCallStatusIcon &&
95+ (toolCallState?.status === "canceled" ||
96+ toolCallState?.status === "errored" ||
97+ toolCallState?.status === "done") ? (
98+ <div
99+ className={`mr-1 h-4 w-4 ${toolCallState.output ? "cursor-pointer" : ""}`}
100+ onClick={() => {
101+ if (toolCallState.output) {
102+ ideMessenger.post("showVirtualFile", {
103+ name: "Edit output",
104+ content: renderContextItems(toolCallState.output),
105+ });
106+ }
107+ }}
108+ >
109+ {getStatusIcon(toolCallState.status)}
110+ </div>
111+ ) : null;
112+
84113 /**
85114 * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`.
86115 * However, if no `relativeFilepath` is defined, then this will
@@ -269,6 +298,7 @@
269298 style={{ fontSize: `${getFontSize() - 2}px` }}
270299 >
271300 <div className="flex max-w-[50%] flex-row items-center">
301+ {toolCallStatusIcon}
272302 <ChevronDownIcon
273303 data-testid="toggle-codeblock"
274304 onClick={() => setIsExpanded(!isExpanded)}
modified gui/src/components/StyledMarkdownPreview/index.tsx +3 −0
@@ -123,6 +123,7 @@
123123 `;
124124
125125 interface StyledMarkdownPreviewProps {
126+ showToolCallStatusIcon?: boolean;
126127 source?: string;
127128 className?: string;
128129 isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
@@ -300,6 +301,7 @@
300301
301302 return (
302303 <StepContainerPreToolbar
304+ showToolCallStatusIcon={props.showToolCallStatusIcon}
303305 codeBlockContent={codeBlockContent}
304306 itemIndex={itemIndexRef.current}
305307 codeBlockIndex={codeBlockIndex}
@@ -357,6 +359,7 @@
357359
358360 const uiConfig = useAppSelector(selectUIConfig);
359361 const codeWrapState = uiConfig?.codeWrap ? "pre-wrap" : "pre";
362+
360363 return (
361364 <StyledMarkdown
362365 fontSize={getFontSize()}
modified gui/src/components/config/FatalErrorNotice.tsx +4 −4
@@ -32,10 +32,10 @@
3232 return null;
3333 }
3434
35- const displayName =
36- selectedProfile?.title ??
37- `${selectedProfile?.fullSlug?.ownerSlug}/${selectedProfile?.fullSlug?.packageSlug}` ??
38- "assistant";
35+ const displayName = selectedProfile
36+ ? (selectedProfile.title ??
37+ `${selectedProfile.fullSlug?.ownerSlug}/${selectedProfile.fullSlug?.packageSlug}`)
38+ : "agent";
3939
4040 return (
4141 <Alert type="error" className="mx-2 my-1 px-2">
modified gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +48 −5
@@ -3,7 +3,10 @@
33 ArrowPathIcon,
44 CircleStackIcon,
55 CommandLineIcon,
6+ GlobeAltIcon,
67 InformationCircleIcon,
8+ ShieldCheckIcon,
9+ ShieldExclamationIcon,
710 WrenchScrewdriverIcon,
811 } from "@heroicons/react/24/outline";
912 import { MCPServerStatus } from "core";
@@ -30,8 +33,9 @@
3033 const promptsTooltipId = `${server.id}-prompts`;
3134 const resourcesTooltipId = `${server.id}-resources`;
3235 const errorsTooltipId = `${server.id}-errors`;
36+ const mcpAuthTooltipId = `${server.id}-auth`;
3337
34- async function onRefresh() {
38+ const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
3539 // optimistic config update
3640 dispatch(
3741 updateConfig({
@@ -40,23 +44,37 @@
4044 s.id === server.id
4145 ? {
4246 ...s,
43- status: "connecting",
47+ status,
4448 }
4549 : s,
4650 ),
4751 }),
4852 );
53+ };
54+
55+ const onAuthenticate = async () => {
56+ updateMCPServerStatus("authenticating");
57+ await ideMessenger.request("mcp/startAuthentication", server);
58+ };
59+
60+ const onRemoveAuth = async () => {
61+ updateMCPServerStatus("authenticating");
62+ await ideMessenger.request("mcp/removeAuthentication", server);
63+ };
64+
65+ const onRefresh = async () => {
66+ updateMCPServerStatus("connecting");
4967 ideMessenger.post("mcp/reloadServer", {
5068 id: server.id,
5169 });
52- }
70+ };
5371
5472 return (
5573 <div
5674 style={{
5775 fontSize: fontSize(-2),
5876 }}
59- className="flex flex-row items-center justify-between gap-3"
77+ className={`flex flex-row items-center justify-between gap-3 ${server.status === "authenticating" ? "my-0.5" : ""}`}
6078 >
6179 <div className="flex flex-row items-center gap-3">
6280 {/* Name and Status */}
@@ -159,8 +177,33 @@
159177 </div>
160178 </div>
161179
162- {/* Refresh button */}
163180 <div className="flex items-center gap-2">
181+ {server.isProtectedResource && (
182+ <>
183+ <div
184+ className="text-lightgray flex cursor-pointer items-center hover:text-white hover:opacity-80"
185+ data-tooltip-id={
186+ server.status !== "authenticating" ? mcpAuthTooltipId : ""
187+ }
188+ >
189+ {server.status === "error" ? (
190+ <ShieldExclamationIcon
191+ className="h-3 w-3"
192+ onClick={onAuthenticate}
193+ />
194+ ) : server.status === "authenticating" ? (
195+ <GlobeAltIcon className="animate-spin-slow h-3 w-3" />
196+ ) : (
197+ <ShieldCheckIcon className="h-3 w-3" onClick={onRemoveAuth} />
198+ )}
199+ </div>
200+ {server.status !== "authenticating" && (
201+ <ToolTip place="left" id={mcpAuthTooltipId}>
202+ {server.status === "error" ? "Authenticate" : "Logout"}
203+ </ToolTip>
204+ )}
205+ </>
206+ )}
164207 <EditBlockButton
165208 blockType={"mcpServers"}
166209 block={serverFromYaml}
modified gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +1 −1
@@ -118,7 +118,7 @@
118118 </div>
119119
120120 <div
121- className={`flex w-8 flex-row items-center justify-end gap-2 px-2 py-0.5 sm:w-16 ${disabled ? "cursor-not-allowed" : "hover:text-list-active-foreground cursor-pointer hover:brightness-125"}`}
121+ className={`flex w-8 select-none flex-row items-center justify-end gap-2 px-2 py-0.5 sm:w-16 ${disabled ? "cursor-not-allowed" : "hover:text-list-active-foreground cursor-pointer hover:brightness-125"}`}
122122 data-testid={`tool-policy-item-${props.tool.function.name}`}
123123 data-tooltip-id={disabled ? disabledTooltipId : undefined}
124124 onClick={
deleted gui/src/hooks/CustomPostHogProvider.tsx +0 −31
@@ -1,31 +0,0 @@
1-import posthog from "posthog-js";
2-import { PostHogProvider } from "posthog-js/react";
3-import { PropsWithChildren, useEffect } from "react";
4-import { useAppSelector } from "../redux/hooks";
5-
6-const CustomPostHogProvider = ({ children }: PropsWithChildren) => {
7- const allowAnonymousTelemetry = useAppSelector(
8- (store) => store?.config?.config?.allowAnonymousTelemetry,
9- );
10-
11- useEffect(() => {
12- if (allowAnonymousTelemetry) {
13- posthog.init("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
14- api_host: "https://app.posthog.com",
15- disable_session_recording: true,
16- autocapture: false,
17- // // We need to manually track pageviews since we're a SPA
18- capture_pageleave: false,
19- capture_pageview: false,
20- });
21- posthog.identify(window.vscMachineId);
22- posthog.opt_in_capturing();
23- } else {
24- posthog.opt_out_capturing();
25- }
26- }, [allowAnonymousTelemetry]);
27-
28- return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
29-};
30-
31-export default CustomPostHogProvider;
added gui/src/hooks/TelemetryProviders.test.tsx +306 −0
@@ -0,0 +1,306 @@
1+import { createStore } from "@reduxjs/toolkit";
2+import * as Sentry from "@sentry/react";
3+import { render, screen } from "@testing-library/react";
4+import posthog from "posthog-js";
5+import React from "react";
6+import { Provider } from "react-redux";
7+import { PersistGate } from "redux-persist/integration/react";
8+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9+import { AuthProvider } from "../context/Auth";
10+import TelemetryProviders from "./TelemetryProviders";
11+
12+// Mock Sentry
13+vi.mock("@sentry/react", () => ({
14+ init: vi.fn(),
15+ setUser: vi.fn(),
16+ getClient: vi.fn(),
17+ getCurrentScope: vi.fn(() => ({
18+ clear: vi.fn(),
19+ })),
20+ browserTracingIntegration: vi.fn(() => ({ name: "BrowserTracing" })),
21+ replayIntegration: vi.fn(() => ({ name: "Replay" })),
22+ feedbackIntegration: vi.fn(() => ({ name: "Feedback" })),
23+ contextLinesIntegration: vi.fn(() => ({ name: "ContextLines" })),
24+ ErrorBoundary: ({ children }: { children: React.ReactNode }) => (
25+ <div data-testid="sentry-error-boundary">{children}</div>
26+ ),
27+}));
28+
29+// Mock PostHog
30+vi.mock("posthog-js", () => ({
31+ default: {
32+ init: vi.fn(),
33+ identify: vi.fn(),
34+ opt_in_capturing: vi.fn(),
35+ opt_out_capturing: vi.fn(),
36+ },
37+}));
38+
39+// Mock PostHog React provider
40+vi.mock("posthog-js/react", () => ({
41+ PostHogProvider: ({ children }: { children: React.ReactNode }) => (
42+ <div data-testid="posthog-provider">{children}</div>
43+ ),
44+}));
45+
46+// Mock the Auth context
47+vi.mock("../context/Auth", () => ({
48+ AuthProvider: ({ children }: { children: React.ReactNode }) => (
49+ <div data-testid="auth-provider">{children}</div>
50+ ),
51+ useAuth: () => ({
52+ session: {
53+ account: {
54+ id: "test@continue.dev", // Mock Continue team member email
55+ },
56+ },
57+ }),
58+}));
59+
60+// Mock isContinueTeamMember utility
61+vi.mock("../util/isContinueTeamMember", () => ({
62+ isContinueTeamMember: vi.fn(() => true), // Mock as Continue team member
63+}));
64+
65+// Mock window.vscMachineId
66+Object.defineProperty(window, "vscMachineId", {
67+ value: "test-machine-id",
68+ writable: true,
69+});
70+
71+// Create a minimal Redux store for testing
72+const createTestStore = (allowAnonymousTelemetry: boolean) => {
73+ return createStore(
74+ (
75+ state = {
76+ config: {
77+ config: {
78+ allowAnonymousTelemetry,
79+ },
80+ },
81+ },
82+ ) => state,
83+ );
84+};
85+
86+// Mock persistor
87+const mockPersistor = {
88+ persist: vi.fn(),
89+ purge: vi.fn(),
90+ flush: vi.fn(),
91+ pause: vi.fn(),
92+ getState: vi.fn(() => ({
93+ bootstrapped: true,
94+ registry: [],
95+ })),
96+ dispatch: vi.fn(),
97+ subscribe: vi.fn(),
98+};
99+
100+const TestWrapper: React.FC<{
101+ children: React.ReactNode;
102+ allowAnonymousTelemetry: boolean;
103+}> = ({ children, allowAnonymousTelemetry }) => {
104+ const store = createTestStore(allowAnonymousTelemetry);
105+
106+ return (
107+ <Provider store={store}>
108+ <PersistGate loading={null} persistor={mockPersistor}>
109+ <AuthProvider>{children}</AuthProvider>
110+ </PersistGate>
111+ </Provider>
112+ );
113+};
114+
115+describe("TelemetryProviders", () => {
116+ const mockSentry = Sentry as any;
117+ const mockPosthog = posthog as any;
118+
119+ beforeEach(() => {
120+ vi.clearAllMocks();
121+ // Reset NODE_ENV to test
122+ process.env.NODE_ENV = "test";
123+ });
124+
125+ afterEach(() => {
126+ vi.clearAllMocks();
127+ });
128+
129+ describe("when telemetry is enabled", () => {
130+ it("should initialize both PostHog and Sentry", () => {
131+ const originalNodeEnv = process.env.NODE_ENV;
132+ process.env.NODE_ENV = "development";
133+
134+ render(
135+ <TestWrapper allowAnonymousTelemetry={true}>
136+ <TelemetryProviders>
137+ <div data-testid="test-child">Test Child</div>
138+ </TelemetryProviders>
139+ </TestWrapper>,
140+ );
141+
142+ // Verify PostHog initialization
143+ expect(mockPosthog.init).toHaveBeenCalledWith(
144+ "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
145+ expect.objectContaining({
146+ api_host: "https://app.posthog.com",
147+ disable_session_recording: true,
148+ autocapture: false,
149+ capture_pageleave: false,
150+ capture_pageview: false,
151+ }),
152+ );
153+ expect(mockPosthog.identify).toHaveBeenCalledWith("test-machine-id");
154+ expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
155+
156+ // Verify Sentry initialization
157+ expect(mockSentry.init).toHaveBeenCalledWith(
158+ expect.objectContaining({
159+ dsn: "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016",
160+ environment: "development",
161+ tracesSampleRate: 0.25,
162+ }),
163+ );
164+ expect(mockSentry.setUser).toHaveBeenCalledWith({
165+ id: expect.stringMatching(/^[a-f0-9]{8}$/), // Should be 8-char hash
166+ email: undefined,
167+ username: undefined,
168+ ip_address: undefined,
169+ });
170+
171+ // Verify children are rendered
172+ expect(screen.getByTestId("test-child")).toBeInTheDocument();
173+ expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
174+
175+ process.env.NODE_ENV = originalNodeEnv;
176+ });
177+ });
178+
179+ describe("when telemetry is disabled", () => {
180+ it("should disable PostHog and clear Sentry scope", () => {
181+ const mockClear = vi.fn();
182+ const mockClose = vi.fn();
183+ const mockClient = { close: mockClose };
184+
185+ mockSentry.getCurrentScope.mockReturnValue({ clear: mockClear });
186+ mockSentry.getClient.mockReturnValue(mockClient);
187+
188+ render(
189+ <TestWrapper allowAnonymousTelemetry={false}>
190+ <TelemetryProviders>
191+ <div data-testid="test-child">Test Child</div>
192+ </TelemetryProviders>
193+ </TestWrapper>,
194+ );
195+
196+ // Verify PostHog is disabled
197+ expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
198+ expect(mockPosthog.init).not.toHaveBeenCalled();
199+ expect(mockPosthog.identify).not.toHaveBeenCalled();
200+ expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();
201+
202+ // Verify Sentry is properly disabled
203+ expect(mockSentry.getClient).toHaveBeenCalled();
204+ expect(mockClose).toHaveBeenCalled();
205+ expect(mockSentry.getCurrentScope).toHaveBeenCalled();
206+ expect(mockClear).toHaveBeenCalled();
207+ expect(mockSentry.init).not.toHaveBeenCalled();
208+ expect(mockSentry.setUser).not.toHaveBeenCalled();
209+
210+ // Verify children are still rendered
211+ expect(screen.getByTestId("test-child")).toBeInTheDocument();
212+ expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
213+ });
214+ });
215+
216+ describe("provider structure", () => {
217+ it("should wrap children with PostHogProvider", () => {
218+ render(
219+ <TestWrapper allowAnonymousTelemetry={false}>
220+ <TelemetryProviders>
221+ <div data-testid="nested-child">
222+ <span data-testid="deeply-nested">Deep content</span>
223+ </div>
224+ </TelemetryProviders>
225+ </TestWrapper>,
226+ );
227+
228+ // Verify the provider structure is maintained
229+ expect(screen.getByTestId("posthog-provider")).toBeInTheDocument();
230+ expect(screen.getByTestId("nested-child")).toBeInTheDocument();
231+ expect(screen.getByTestId("deeply-nested")).toBeInTheDocument();
232+ });
233+
234+ it("should handle missing vscMachineId gracefully", () => {
235+ // Temporarily modify vscMachineId
236+ const originalMachineId = window.vscMachineId;
237+ (window as any).vscMachineId = undefined;
238+
239+ const originalNodeEnv = process.env.NODE_ENV;
240+ process.env.NODE_ENV = "development";
241+
242+ render(
243+ <TestWrapper allowAnonymousTelemetry={true}>
244+ <TelemetryProviders>
245+ <div data-testid="test-child">Test Child</div>
246+ </TelemetryProviders>
247+ </TestWrapper>,
248+ );
249+
250+ // Should still initialize but with anonymized ID (hashed "anonymous")
251+ expect(mockSentry.setUser).toHaveBeenCalledWith({
252+ id: expect.stringMatching(/^[a-f0-9]{8}$/), // Should be 8-char hash
253+ email: undefined,
254+ username: undefined,
255+ ip_address: undefined,
256+ });
257+
258+ // Restore
259+ (window as any).vscMachineId = originalMachineId;
260+ process.env.NODE_ENV = originalNodeEnv;
261+ });
262+ });
263+
264+ describe("telemetry toggle behavior", () => {
265+ it("should maintain proper state when telemetry setting changes", () => {
266+ const originalNodeEnv = process.env.NODE_ENV;
267+ process.env.NODE_ENV = "development";
268+
269+ // First render with telemetry enabled
270+ const { rerender } = render(
271+ <TestWrapper allowAnonymousTelemetry={true}>
272+ <TelemetryProviders>
273+ <div data-testid="test-child">Test Child</div>
274+ </TelemetryProviders>
275+ </TestWrapper>,
276+ );
277+
278+ expect(mockSentry.init).toHaveBeenCalled();
279+ expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
280+
281+ // Clear mocks and rerender with telemetry disabled
282+ vi.clearAllMocks();
283+ const mockClear = vi.fn();
284+ const mockClose = vi.fn();
285+ const mockClient = { close: mockClose };
286+
287+ mockSentry.getCurrentScope.mockReturnValue({ clear: mockClear });
288+ mockSentry.getClient.mockReturnValue(mockClient);
289+
290+ rerender(
291+ <TestWrapper allowAnonymousTelemetry={false}>
292+ <TelemetryProviders>
293+ <div data-testid="test-child">Test Child</div>
294+ </TelemetryProviders>
295+ </TestWrapper>,
296+ );
297+
298+ expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
299+ expect(mockClose).toHaveBeenCalled();
300+ expect(mockClear).toHaveBeenCalled();
301+ expect(mockSentry.init).not.toHaveBeenCalled();
302+
303+ process.env.NODE_ENV = originalNodeEnv;
304+ });
305+ });
306+});
added gui/src/hooks/TelemetryProviders.tsx +126 −0
@@ -0,0 +1,126 @@
1+import * as Sentry from "@sentry/react";
2+import { HubSessionInfo } from "core/control-plane/AuthTypes";
3+import {
4+ anonymizeSentryEvent,
5+ anonymizeUserInfo,
6+} from "core/util/sentry/anonymization";
7+import { SENTRY_DSN } from "core/util/sentry/constants";
8+import posthog from "posthog-js";
9+import { PostHogProvider } from "posthog-js/react";
10+import { PropsWithChildren, useEffect } from "react";
11+import { useAuth } from "../context/Auth";
12+import { useAppSelector } from "../redux/hooks";
13+import { isPrerelease } from "../util/index";
14+import { isContinueTeamMember } from "../util/isContinueTeamMember";
15+import { getLocalStorage } from "../util/localStorage";
16+
17+const SAMPLE_REATE = 0.1;
18+const TRACES_SAMPLE_RATE = 0.25;
19+
20+const TelemetryProviders = ({ children }: PropsWithChildren) => {
21+ const allowAnonymousTelemetry = useAppSelector(
22+ (store) => store?.config?.config?.allowAnonymousTelemetry,
23+ );
24+ const { session } = useAuth();
25+
26+ // TODO: Remove Continue team member check once Sentry is ready for all users
27+ const hasContinueEmail = isContinueTeamMember(
28+ (session as HubSessionInfo)?.account?.id,
29+ );
30+
31+ useEffect(() => {
32+ if (allowAnonymousTelemetry && hasContinueEmail) {
33+ // Initialize PostHog (existing logic)
34+ posthog.init("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
35+ api_host: "https://app.posthog.com",
36+ disable_session_recording: true,
37+ autocapture: false,
38+ // We need to manually track pageviews since we're a SPA
39+ capture_pageleave: false,
40+ capture_pageview: false,
41+ });
42+ posthog.identify(window.vscMachineId);
43+ posthog.opt_in_capturing();
44+
45+ // Initialize Sentry (new for GUI - enhanced React setup)
46+ Sentry.init({
47+ dsn: SENTRY_DSN,
48+ environment: process.env.NODE_ENV,
49+ integrations: [
50+ // Performance monitoring
51+ Sentry.browserTracingIntegration(),
52+ ],
53+
54+ // For basic error tracking, a lower sample rate should be fine
55+ sampleRate: SAMPLE_REATE,
56+ tracesSampleRate: TRACES_SAMPLE_RATE,
57+
58+ // Privacy-conscious default
59+ sendDefaultPii: false,
60+
61+ // Strip sensitive data and add basic properties
62+ beforeSend(event) {
63+ // Apply comprehensive anonymization using shared logic
64+ const anonymizedEvent = anonymizeSentryEvent(event);
65+ if (!anonymizedEvent) return null;
66+
67+ // Add basic properties available in GUI environment
68+ if (!anonymizedEvent.tags) anonymizedEvent.tags = {};
69+
70+ // Add environment information
71+ anonymizedEvent.tags.environment = process.env.NODE_ENV;
72+
73+ // Add ideInfo properties spread out as top-level properties (like PostHog)
74+ const extensionVersion = getLocalStorage("extensionVersion");
75+ const ideType = getLocalStorage("ide");
76+
77+ if (extensionVersion) {
78+ anonymizedEvent.tags.extensionVersion = extensionVersion;
79+ }
80+
81+ if (ideType) {
82+ anonymizedEvent.tags.ideType = ideType;
83+ }
84+
85+ // Add isPrerelease information
86+ anonymizedEvent.tags.isPrerelease = isPrerelease();
87+
88+ return anonymizedEvent;
89+ },
90+ });
91+
92+ // Set anonymized user context for Sentry
93+ const anonymizedUser = anonymizeUserInfo({
94+ id: window.vscMachineId || "anonymous",
95+ });
96+ Sentry.setUser(anonymizedUser);
97+ } else {
98+ // Disable PostHog
99+ posthog.opt_out_capturing();
100+
101+ // Disable Sentry properly - close the client to stop all network requests
102+ try {
103+ const client = Sentry.getClient();
104+ if (client) {
105+ client.close();
106+ }
107+ Sentry.getCurrentScope().clear();
108+ } catch (error) {
109+ console.error("Error disabling Sentry:", error);
110+ }
111+ }
112+ }, [allowAnonymousTelemetry, hasContinueEmail]);
113+
114+ // Conditionally wrap with ErrorBoundary when telemetry is enabled and user is Continue team member
115+ const content =
116+ allowAnonymousTelemetry && hasContinueEmail ? (
117+ <Sentry.ErrorBoundary showDialog={false}>{children}</Sentry.ErrorBoundary>
118+ ) : (
119+ children
120+ );
121+
122+ // Only PostHog needs a provider wrapper - Sentry works globally once initialized
123+ return <PostHogProvider client={posthog}>{content}</PostHogProvider>;
124+};
125+
126+export default TelemetryProviders;
modified gui/src/main.tsx +7 −5
@@ -3,18 +3,20 @@
33 import { Provider } from "react-redux";
44 import { PersistGate } from "redux-persist/integration/react";
55 import App from "./App";
6-import CustomPostHogProvider from "./hooks/CustomPostHogProvider";
76 import "./index.css";
87 import { persistor, store } from "./redux/store";
98
109 (async () => {
11- ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
10+ const container = document.getElementById("root") as HTMLElement;
11+
12+ // Create React root
13+ const root = ReactDOM.createRoot(container);
14+
15+ root.render(
1216 <React.StrictMode>
1317 <Provider store={store}>
1418 <PersistGate loading={null} persistor={persistor}>
15- <CustomPostHogProvider>
16- <App />
17- </CustomPostHogProvider>
19+ <App />
1820 </PersistGate>
1921 </Provider>
2022 </React.StrictMode>,
modified gui/src/pages/AddNewModel/configs/models.ts +0 −21
@@ -679,7 +679,6 @@
679679 model: "granite-code",
680680 contextLength: 20_000,
681681 title: "Granite Code",
682- systemMessage: `You are Granite Chat, an AI language model developed by IBM. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior. You always respond to greetings (for example, hi, hello, g'day, morning, afternoon, evening, night, what's up, nice to meet you, sup, etc) with "Hello! I am Granite Chat, created by IBM. How can I help you today?". Please do not say anything else and do not start a conversation.`,
683682 },
684683 providerOptions: ["ollama", "lmstudio", "llama.cpp", "replicate"],
685684 icon: "ibm.png",
@@ -1154,8 +1153,6 @@
11541153 model: "gpt-4o",
11551154 contextLength: 128_000,
11561155 title: "GPT-4o",
1157- systemMessage:
1158- "You are an expert software developer. You give helpful and concise responses.",
11591156 },
11601157 providerOptions: ["openai", "askSage"],
11611158 icon: "openai.png",
@@ -1169,8 +1166,6 @@
11691166 model: "gpt-4o-mini",
11701167 contextLength: 128_000,
11711168 title: "GPT-4o mini",
1172- systemMessage:
1173- "You are an expert software developer. You give helpful and concise responses.",
11741169 },
11751170 providerOptions: ["openai", "askSage"],
11761171 icon: "openai.png",
@@ -1424,8 +1419,6 @@
14241419 model: "gpt4-gov",
14251420 contextLength: 128_000,
14261421 title: "GPT-4 gov",
1427- systemMessage:
1428- "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed
14291422 },
14301423 providerOptions: ["askSage"],
14311424 icon: "openai.png",
@@ -1439,8 +1432,6 @@
14391432 model: "gpt-4o-gov",
14401433 contextLength: 128_000,
14411434 title: "GPT-4o-gov",
1442- systemMessage:
1443- "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed
14441435 },
14451436 providerOptions: ["askSage"],
14461437 icon: "openai.png",
@@ -1453,8 +1444,6 @@
14531444 model: "gpt-gov",
14541445 contextLength: 8096,
14551446 title: "GPT-3.5-Turbo gov",
1456- systemMessage:
1457- "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed
14581447 },
14591448 providerOptions: ["askSage"],
14601449 icon: "openai.png",
@@ -1468,8 +1457,6 @@
14681457 model: "gpt-4o-mini-gov",
14691458 contextLength: 128_000,
14701459 title: "GPT-4o-mini gov",
1471- systemMessage:
1472- "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed
14731460 },
14741461 providerOptions: ["askSage"],
14751462 icon: "openai.png",
@@ -1509,8 +1496,6 @@
15091496 model: "gpt-o1",
15101497 contextLength: 128_000,
15111498 title: "GPT-o1",
1512- systemMessage:
1513- "You are an expert software developer. You give helpful and concise responses.",
15141499 },
15151500 providerOptions: ["askSage"],
15161501 icon: "openai.png",
@@ -1524,8 +1509,6 @@
15241509 model: "gpt-o1-mini",
15251510 contextLength: 128_000,
15261511 title: "GPT-o1-mini",
1527- systemMessage:
1528- "You are an expert software developer. You give helpful and concise responses.",
15291512 },
15301513 providerOptions: ["askSage"],
15311514 icon: "openai.png",
@@ -1539,8 +1522,6 @@
15391522 model: "gpt-o3-mini",
15401523 contextLength: 200_000,
15411524 title: "GPT-o3-mini",
1542- systemMessage:
1543- "You are an expert software developer. You give helpful and concise responses.",
15441525 },
15451526 providerOptions: ["askSage"],
15461527 icon: "openai.png",
@@ -1554,8 +1535,6 @@
15541535 model: "aws-bedrock-claude-35-sonnet-gov",
15551536 contextLength: 200_000,
15561537 title: "Claude 3.5 Sonnet gov",
1557- systemMessage:
1558- "You are an expert software developer. You give helpful and concise responses.",
15591538 },
15601539 providerOptions: ["askSage"],
15611540 icon: "anthropic.png",
modified gui/src/pages/config/UserSettingsForm.tsx +10 −2
@@ -20,6 +20,8 @@
2020 import { IdeMessengerContext } from "../../context/IdeMessenger";
2121 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
2222 import { updateConfig } from "../../redux/slices/configSlice";
23+import { selectCurrentOrg } from "../../redux/slices/profilesSlice";
24+import { isContinueTeamMember } from "../../util/isContinueTeamMember";
2325 import { setLocalStorage } from "../../util/localStorage";
2426 import { ContinueFeaturesMenu } from "./ContinueFeaturesMenu";
2527
@@ -28,6 +30,8 @@
2830 const dispatch = useAppDispatch();
2931 const ideMessenger = useContext(IdeMessengerContext);
3032 const config = useAppSelector((state) => state.config.config);
33+ const currentOrg = useAppSelector(selectCurrentOrg);
34+
3135 const [showExperimental, setShowExperimental] = useState(false);
3236 const { session } = useAuth();
3337
@@ -129,10 +133,13 @@
129133 });
130134 }, [ideMessenger]);
131135
132- const hasContinueEmail = (session as HubSessionInfo)?.account?.id.includes(
133- "@continue.dev",
136+ const hasContinueEmail = isContinueTeamMember(
137+ (session as HubSessionInfo)?.account?.id,
134138 );
135139
140+ const disableTelemetryToggle =
141+ currentOrg?.policy?.allowAnonymousTelemetry === false;
142+
136143 return (
137144 <div className="flex flex-col">
138145 {/* {selectedProfile && isLocalProfile(selectedProfile) ? (
@@ -225,6 +232,7 @@
225232
226233 <ToggleSwitch
227234 isToggled={allowAnonymousTelemetry}
235+ disabled={disableTelemetryToggle}
228236 onToggle={() =>
229237 handleUpdate({
230238 allowAnonymousTelemetry: !allowAnonymousTelemetry,
modified gui/src/pages/gui/ToolCallDiv/EditFile.tsx +5 −0
@@ -1,11 +1,15 @@
1+import { ContextItem, ToolCallState } from "core";
12 import { getMarkdownLanguageTagForFile } from "core/util";
23 import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
34
45 type EditToolCallProps = {
6+ showToolCallStatusIcon?: boolean;
57 relativeFilePath: string;
68 changes: string;
79 historyIndex: number;
810 toolCallId?: string;
11+ output?: undefined | ContextItem[];
12+ status?: ToolCallState["status"];
913 };
1014
1115 export function EditFile(props: EditToolCallProps) {
@@ -17,6 +21,7 @@
1721
1822 return (
1923 <StyledMarkdownPreview
24+ showToolCallStatusIcon={props.showToolCallStatusIcon}
2025 expandCodeblocks={false}
2126 isRenderingInStepContainer
2227 disableManualApply
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +3 −0
@@ -38,8 +38,11 @@
3838 ? args.diffs.join("\n\n---\n\n")
3939 : args.diffs
4040 : "";
41+
4142 return (
4243 <EditFile
44+ showToolCallStatusIcon={true}
45+ status={toolCallState.status}
4346 relativeFilePath={args?.filepath ?? ""}
4447 changes={changes}
4548 toolCallId={toolCall.id}
modified gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +6 −10
@@ -117,17 +117,13 @@
117117 <TerminalCollapsibleContainer
118118 collapsible={processedTerminalContent.isLimited}
119119 hiddenLinesCount={processedTerminalContent.hiddenLinesCount}
120- className="mt-2"
121- collapsedContent={
122- <div className="mt-2">
123- <Ansi>{processedTerminalContent.limitedContent}</Ansi>
124- </div>
120+ className={
121+ processedTerminalContent.hiddenLinesCount === 0 ? "-mt-3" : "-mt-5"
125122 }
126- expandedContent={
127- <div className="mt-2">
128- <Ansi>{processedTerminalContent.fullContent}</Ansi>
129- </div>
123+ collapsedContent={
124+ <Ansi>{processedTerminalContent.limitedContent}</Ansi>
130125 }
126+ expandedContent={<Ansi>{processedTerminalContent.fullContent}</Ansi>}
131127 />
132128 )}
133129
@@ -142,7 +138,7 @@
142138 onClick={(e) => {
143139 e.preventDefault();
144140 // Dispatch the action to move the command to the background
145- dispatch(
141+ void dispatch(
146142 moveTerminalProcessToBackground({
147143 toolCallId: props.toolCallId as string,
148144 }),
modified gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +1 −1
@@ -63,7 +63,7 @@
6363 }
6464
6565 return (
66- <div className="flex flex-col">
66+ <div className="mt-1 flex flex-col px-4">
6767 <div className="flex min-w-0 flex-row items-center justify-between gap-2">
6868 <div
6969 className={`text-description flex min-w-0 flex-row items-center justify-between gap-1.5 text-xs transition-colors duration-200 ease-in-out ${
modified gui/src/pages/gui/ToolCallDiv/ToolCallDisplay.tsx +26 −31
@@ -26,40 +26,35 @@
2626 }, [toolCallState.parsedArgs]);
2727
2828 return (
29- <>
30- <div className="flex flex-col justify-center">
31- <div className="mb-2 flex flex-col">
32- <div className="flex flex-row items-center justify-between gap-1.5">
33- <div className="flex min-w-0 flex-row items-center gap-2">
34- <div className="mt-[1px] h-4 w-4 flex-shrink-0 font-semibold">
35- {icon}
36- </div>
37- {tool?.faviconUrl && (
38- <img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
39- )}
40- <ToolCallStatusMessage
41- tool={tool}
42- toolCallState={toolCallState}
43- />
44- </div>
45- <div className="flex flex-row items-center gap-1.5">
46- {!!toolCallState.output && (
47- <ToolTruncateHistoryIcon historyIndex={historyIndex} />
48- )}
49- {!!args.length ? (
50- <ArgsToggleIcon
51- isShowing={argsExpanded}
52- setIsShowing={setArgsExpanded}
53- />
54- ) : null}
29+ <div className="flex flex-col justify-center px-4">
30+ <div className="mb-2 flex flex-col">
31+ <div className="flex flex-row items-center justify-between gap-1.5">
32+ <div className="flex min-w-0 flex-row items-center gap-2">
33+ <div className="mt-[1px] h-4 w-4 flex-shrink-0 font-semibold">
34+ {icon}
5535 </div>
36+ {tool?.faviconUrl && (
37+ <img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
38+ )}
39+ <ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
40+ </div>
41+ <div className="flex flex-row items-center gap-1.5">
42+ {!!toolCallState.output && (
43+ <ToolTruncateHistoryIcon historyIndex={historyIndex} />
44+ )}
45+ {!!args.length ? (
46+ <ArgsToggleIcon
47+ isShowing={argsExpanded}
48+ setIsShowing={setArgsExpanded}
49+ />
50+ ) : null}
5651 </div>
57- {argsExpanded && !!args.length && (
58- <ArgsItems args={args} isShowing={argsExpanded} />
59- )}
6052 </div>
61- <div>{children}</div>
53+ {argsExpanded && !!args.length && (
54+ <ArgsItems args={args} isShowing={argsExpanded} />
55+ )}
6256 </div>
63- </>
57+ <div>{children}</div>
58+ </div>
6459 );
6560 }
modified gui/src/pages/gui/ToolCallDiv/index.tsx +8 −6
@@ -56,10 +56,12 @@
5656 // But we'd need a nicer place to put the truncate button and the X icon when tool call fails
5757 if (functionName === BuiltInToolNames.SearchAndReplaceInFile) {
5858 return (
59- <FunctionSpecificToolCallDiv
60- toolCallState={toolCallState}
61- historyIndex={historyIndex}
62- />
59+ <div className="flex flex-col px-1">
60+ <FunctionSpecificToolCallDiv
61+ toolCallState={toolCallState}
62+ historyIndex={historyIndex}
63+ />
64+ </div>
6365 );
6466 }
6567
@@ -80,7 +82,7 @@
8082
8183 if (shouldShowGroupedUI) {
8284 return (
83- <div className="border-border rounded-lg border p-3 pb-0">
85+ <div className="border-border rounded-lg border px-4 py-3 pb-0">
8486 <GroupedToolCallHeader
8587 toolCallStates={toolCallStates}
8688 activeCalls={activeCalls}
@@ -103,7 +105,7 @@
103105 }
104106
105107 return toolCallStates.map((toolCallState) => (
106- <div className="px-4 py-1" key={toolCallState.toolCallId}>
108+ <div className="py-1" key={toolCallState.toolCallId}>
107109 {renderToolCall(toolCallState)}
108110 </div>
109111 ));
modified gui/src/redux/thunks/streamNormalInput.ts +4 −4
@@ -3,7 +3,6 @@
33 import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
44 import { ToCoreProtocol } from "core/protocol";
55 import { BuiltInToolNames } from "core/tools/builtIn";
6-import posthog from "posthog-js";
76 import { selectActiveTools } from "../selectors/selectActiveTools";
87 import { selectUseSystemMessageTools } from "../selectors/selectUseSystemMessageTools";
98 import { selectSelectedChatModel } from "../slices/configSlice";
@@ -27,9 +26,9 @@
2726 import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
2827 import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
2928 import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
29+import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
3030 import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
3131 import { callToolById } from "./callToolById";
32-import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
3332 /**
3433 * Handles the execution of tool calls that may be automatically accepted.
3534 * Sets all tools as generated first, then executes auto-approved tool calls.
@@ -126,8 +125,8 @@
126125 * Determines whether to use search and replace tool instead of edit file
127126 * Right now we only know that this is reliable with Claude models
128127 */
129-function shouldUseFindReplaceEdits(model: ModelDescription): boolean {
130- return model.model.includes("claude");
128+function shouldUseFindReplaceEdits({ model }: ModelDescription): boolean {
129+ return model.includes("claude") || model.includes("gpt-5");
131130 }
132131
133132 export const streamNormalInput = createAsyncThunk<
@@ -274,6 +273,7 @@
274273 prompt: next.value.prompt,
275274 completion: next.value.completion,
276275 modelProvider: selectedChatModel.underlyingProviderName,
276+ modelName: selectedChatModel.title,
277277 modelTitle: selectedChatModel.title,
278278 sessionId: state.session.id,
279279 ...(!!activeTools.length && {
modified gui/src/redux/thunks/streamResponse.test.ts +1 −0
@@ -461,6 +461,7 @@
461461 prompt: "Hello",
462462 completion: "Hi there!",
463463 modelProvider: "anthropic",
464+ modelName: "Claude 3.5 Sonnet",
464465 modelTitle: "Claude 3.5 Sonnet",
465466 sessionId: "session-123",
466467 },
modified gui/src/util/editOutcomeLogger.ts +5 −1
@@ -7,6 +7,7 @@
77 */
88 function extractModelInfo(toolCallState: ToolCallState): {
99 modelProvider: string;
10+ modelName: string;
1011 modelTitle: string;
1112 } {
1213 // Get the conversation history to find the model info
@@ -28,6 +29,7 @@
2829 const modelParts = String(assistantMessage.message.model).split("::");
2930 return {
3031 modelProvider: modelParts[0] || "unknown",
32+ modelName: modelParts[1] || String(assistantMessage.message.model),
3133 modelTitle: modelParts[1] || String(assistantMessage.message.model),
3234 };
3335 }
@@ -38,6 +40,7 @@
3840
3941 return {
4042 modelProvider: chatModel?.provider || "unknown",
43+ modelName: chatModel?.model || "unknown",
4144 modelTitle: chatModel?.model || "unknown",
4245 };
4346 }
@@ -153,7 +156,8 @@
153156 streamId: applyState.streamId,
154157 timestamp: new Date().toISOString(),
155158 modelProvider: modelInfo.modelProvider,
156- modelTitle: modelInfo.modelTitle,
159+ modelName: modelInfo.modelName,
160+ modelTitle: modelInfo.modelName,
157161 prompt: promptAndCompletion.prompt,
158162 completion: promptAndCompletion.completion,
159163 previousCode: codeChanges.previousCode,

Next files