Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into nate/metrics-action
Changesetef601eb11092ff5ba1ae8f56c9e46214e0bef3e51bf670eea49b4271218a1963
AuthorNate <sestinj@gmail.com> · 2025-05-25 18:09 -07:00
CommitterNate <sestinj@gmail.com> · 2025-05-25 18:09 -07:00
Parents9d8db5fc402e, f8a28b58727d

Browse the files at this changeset

More than 300 files changed

deleted .changes/extensions/intellij/0.0.34.md +0 −8
@@ -1,8 +0,0 @@
1-## 0.0.34 - 2024-03-03
2-### Added
3-* diff context provider
4-### Changed
5-* Allow LLM servers to handle templating
6-### Fixed
7-* Fix a few context providers / slash commands
8-* Fixed issues preventing proper extension startup
deleted .changes/extensions/intellij/0.0.38.md +0 −4
@@ -1,4 +0,0 @@
1-## 0.0.38 - 2024-03-15
2-### Added
3-* Remote config server support
4-* Autocomplete support in JetBrains
deleted .changes/extensions/intellij/0.0.42.md +0 −7
@@ -1,7 +0,0 @@
1-## 0.0.42 - 2024-04-12
2-### Added
3-* Inline cmd/ctrl+I in JetBrains
4-### Fixed
5-* Fixed character encoding error causing display issues
6-* Fixed error causing input to constantly demand focus
7-* Fixed automatic reloading of config.json
deleted .changes/extensions/intellij/0.0.53.md +0 −8
@@ -1,8 +0,0 @@
1-## 0.0.53 - 2024-07-10
2-### Added
3-* Support for .prompt files
4-* New onboarding experience
5-### Fixed
6-* Indexing fixes from VS Code versions merged into IntelliJ
7-* Improved codebase indexing reliability and testing
8-* Fixes for autocomplete text positioning and timing
deleted .changes/extensions/intellij/0.0.54.md +0 −6
@@ -1,6 +0,0 @@
1-## 0.0.54 - 2024-07-13
2-### Added
3-* Partial autocomplete acceptance
4-* Autocomplete status bar spinner
5-### Fixed
6-* Fixed duplicate completion bug and others
deleted .changes/extensions/intellij/0.0.69.md +0 −7
@@ -1,7 +0,0 @@
1-## 0.0.69 - 2024-09-22
2-### Added
3-* Support for the "search" context provider
4-### Fixed
5-* Fixed bug where only first module would be recognized
6-* Improved concurrency handling to avoid freezes
7-* Made compatible with latest JetBrains versions
deleted .changes/extensions/intellij/0.0.72.md +0 −7
@@ -1,7 +0,0 @@
1-## 0.0.72 - 2024-10-04
2-### Added
3-* Listen for changes to Intellij settings without requiring window reload
4-### Changed
5-* Updated tutorial file
6-### Fixed
7-* Fix ability to load config.ts in JetBrains IDEs
deleted .changes/extensions/intellij/0.0.92.md +0 −5
@@ -1,5 +0,0 @@
1-## 0.0.92 - 2025-02-26
2-### Fixed
3-* Off-screen rendering to solve white flash on load and lack of changing cursor type
4-* OSR-related fixes for non-Mac users
5-* Fixes for inline edit in JetBrains
deleted .changes/extensions/intellij/1.0.0.md +0 −7
@@ -1,7 +0,0 @@
1-## 1.0.0 - 2025-02-26
2-### Added
3-* Introduces hub.continue.dev
4-* Improved theme matching
5-### Fixed
6-* Fixes interference between SonarQube and Continue autocomplete
7-* Numerous reliability improvements
deleted .changes/extensions/intellij/v0.0.1.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.0.1 - 2023-09-01
2-
3-### Added
4-
5-- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
deleted .changes/extensions/intellij/v0.0.19.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.0.19 - 2023-11-19
2-
3-### Changed
4-
5-- migrated to .json config file format
deleted .changes/extensions/intellij/v0.0.21.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.0.21 - 2023-12-05
2-
3-### Added
4-
5-- updated to match latest VS Code updates
deleted .changes/extensions/intellij/v0.0.25.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.0.25 - 2023-12-25
2-
3-### Changed
4-
5-- Intellij extension no longer relies on the Continue Python server
deleted .changes/extensions/intellij/v0.0.26.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.0.26 - 2023-12-28
2-### Added
3-* auto-reloading of config on save
4-### Fixed
5-* Fixed /edit bug for versions without Python server
deleted .changes/extensions/vscode/0.8.14.md +0 −10
@@ -1,10 +0,0 @@
1-## 0.8.14 - 2024-03-03
2-### Added
3-* Image support
4-* Full-text search index for retrieval
5-* Docs context provider
6-* CodeLlama-70b support
7-### Changed
8-* config.ts only runs in NodeJS, not browser
9-### Fixed
10-* Fixed proxy setting in config.json
deleted .changes/extensions/vscode/0.8.15.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.15 - 2024-03-05
2-### Added
3-* Tab-autocomplete in beta
deleted .changes/extensions/vscode/0.8.24.md +0 −5
@@ -1,5 +0,0 @@
1-## 0.8.24 - 2024-04-12
2-### Added
3-* Support for improved retrieval models (Voyage embeddings/reranking)
4-* New @code context provider
5-* Personal usage analytics
deleted .changes/extensions/vscode/0.8.42.md +0 −16
@@ -1,16 +0,0 @@
1-## 0.8.42 - 2024-07-02
2-
3-### Added
4-
5-- Support for Gemini 1.5 Pro
6-- Link to code in the sidebar when using codebase retrieval
7-- Smoother onboarding experience
8-- .prompt files, a way of saving and sharing slash commands
9-- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
10-- Support for comments in config.json
11-- Specify multiple autocomplete models and switch between them
12-- Improved bracket matching strategy reduces noisy completions
13-
14-### Fixed
15-
16-- Numerous reliability upgrades to codebase indexing
deleted .changes/extensions/vscode/0.8.43.md +0 −4
@@ -1,4 +0,0 @@
1-## 0.8.43 - 2024-07-08
2-### Added
3-* Improved indexing reliability and testing
4-* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
deleted .changes/extensions/vscode/0.8.45.md +0 −12
@@ -1,12 +0,0 @@
1-## 0.8.45 - 2024-08-05
2-### Added
3-* Support for Llama 3.1 and gpt-4o-mini
4-* Support for WatsonX+Granite models
5-### Changed
6-* Significant improvements to indexing performance
7-* Improved @codebase quality by more accurately searching over file names and paths
8-* Improved @codebase accuracy
9-* Further improvements to indexing performance
10-### Fixed
11-* Improved docs indexing and management
12-* Fixed Gemini embeddings provider
deleted .changes/extensions/vscode/0.8.46.md +0 −6
@@ -1,6 +0,0 @@
1-## 0.8.46 - 2024-08-11
2-### Added
3-* new /onboard slash command
4-### Fixed
5-* Fixed problem loading config.ts
6-* Fixed bug causing duplicate indexing work
deleted .changes/extensions/vscode/0.8.47.md +0 −8
@@ -1,8 +0,0 @@
1-## 0.8.47 - 2024-08-27
2-### Added
3-* Use headless browser for crawling to get better results
4-* TTS support in the chat window
5-### Changed
6-* Improved support for WatsonX models
7-### Fixed
8-* Fixed several small indexing bugs
deleted .changes/extensions/vscode/0.8.48.md +0 −8
@@ -1,8 +0,0 @@
1-## 0.8.48 - 2024-09-01
2-### Added
3-* Improved indexing progress UI
4-* Improved @codebase using repomap
5-* Repo map context provider
6-### Fixed
7-* Many small UI improvements
8-* Fixes db.search not a function
deleted .changes/extensions/vscode/0.8.49.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.49 - 2024-09-01
2-### Fixed
3-* Hotfix: submenu context providers
deleted .changes/extensions/vscode/0.8.50.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.50 - 2024-09-02
2-### Fixed
3-* Hotfix for ability to use more than one inline context provider
deleted .changes/extensions/vscode/0.8.51.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.51 - 2024-09-05
2-### Fixed
3-* Fixed CRLF bug causing diff streams to treat every line as changed on Windows
deleted .changes/extensions/vscode/0.8.52.md +0 −4
@@ -1,4 +0,0 @@
1-## 0.8.52 - 2024-09-16
2-### Changed
3-* Use Chromium only as a fallback after asking user
4-* Redesigned onboarding flow
deleted .changes/extensions/vscode/0.8.53.md +0 −12
@@ -1,12 +0,0 @@
1-## 0.8.53 - 2024-10-11
2-### Added
3-* Improved loading/accept/reject UI for apply
4-* Polished chat sidebar, especially context dropdown
5-* Further prompt caching with Anthropic
6-### Changed
7-* Updated tutorial file
8-* Improved styling on "More" page
9-### Fixed
10-* Continue for teams auth bug fix
11-* Fixed a number of apply bugs
12-* Fixed autoscrolling behavior
deleted .changes/extensions/vscode/0.8.54.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.54 - 2024-10-15
2-### Fixed
3-* Hotfix: throttle transformers.js embeddings provider
deleted .changes/extensions/vscode/0.8.55.md +0 −9
@@ -1,9 +0,0 @@
1-## 0.8.55 - 2024-10-25
2-### Added
3-* Web context provider
4-* Cerebras inference provider
5-* Automatic descriptions for previous chats
6-* Discord context provider
7-* Improved full screen UI
8-### Changed
9-* Easier way to accept/reject/re-prompt after cmd/ctrl+I
deleted .changes/extensions/vscode/0.8.56.md +0 −4
@@ -1,4 +0,0 @@
1-## 0.8.56 - 2024-11-08
2-### Added
3-* New Edit mode in sidebar (cmd/ctrl+I)
4-* Significantly faster and more accurate docs crawler by default
deleted .changes/extensions/vscode/0.8.58.md +0 −25
@@ -1,25 +0,0 @@
1-## 0.8.58 - 2024-11-22
2-### Added
3-* OpenAI predicted outputs support
4-* Improve codebase retrieval with BM25
5-* Support for Grok from xAI
6-* Chat enhancements including sticking input to bottom
7-* New UI for cmd+I in sidebar
8-* Support for Nebius LLM provider
9-* Support for Ask Sage LLM provider
10-* Improved reference for config.json
11-* New @web context provider
12-* Updates for llama3.2
13-* .continuerules file to set system prompt
14-* .prompt files v2
15-* Dedicated UI for docs indexing
16-* Clickable code symbols in chat
17-* Use clipboard content as autocomplete context
18-### Changed
19-* Improved @docs crawler
20-* Many improvements to make autocomplete more eager
21-* Near complete type definition retrieval for TypeScript autocomplete
22-* Remove footer from chat sidebar
23-### Fixed
24-* Brought back the Apply button for all code blocks
25-* Automatically update codebase index on removed files
deleted .changes/extensions/vscode/0.8.59.md +0 −3
@@ -1,3 +0,0 @@
1-## 0.8.59 - 2024-11-25
2-### Fixed
3-* Hotfix for Ollama onboarding
deleted .changes/extensions/vscode/0.8.62.md +0 −6
@@ -1,6 +0,0 @@
1-## 0.8.62 - 2024-12-10
2-### Added
3-* Tool use
4-* Support for Model Context Protocol
5-### Fixed
6-* hotfix: context providers no longer hidden when not in edit mode
deleted .changes/extensions/vscode/0.8.66.md +0 −9
@@ -1,9 +0,0 @@
1-## 0.8.66 - 2024-12-20
2-### Changed
3-* Improved autocomplete in untitled files
4-### Fixed
5-* Display more mid-line completions
6-* Restored syntax highlighting
7-* Fix tool use bug for models that don't support tools
8-* Autodetect mistral API key type
9-* Fixes Azure OpenAI regressions
deleted .changes/extensions/vscode/1.0.0.md +0 −6
@@ -1,6 +0,0 @@
1-## 1.0.0 - 2025-02-26
2-### Added
3-* Introduces hub.continue.dev
4-* Improved apply quality
5-### Fixed
6-* Numerous reliability improvements
deleted .changes/extensions/vscode/v0.5.0.md +0 −9
@@ -1,9 +0,0 @@
1-## v0.5.0 - 2023-11-09
2-
3-### Added
4-
5-- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
6-
7-### Changed
8-
9-- Switch from Websockets to Socket.io
deleted .changes/extensions/vscode/v0.6.0.md +0 −11
@@ -1,11 +0,0 @@
1-## v0.6.0 - 2023-11-10
2-
3-### Added
4-
5-- Full screen mode
6-- StackOverflow slash command to augment with web search
7-- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
8-
9-### Fixed
10-
11-- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor
deleted .changes/extensions/vscode/v0.6.16.md +0 −6
@@ -1,6 +0,0 @@
1-## v0.6.16 - 2023-12-25
2-
3-### Changed
4-
5-- Context items are now kept around as a part of past messages, instead of staying at the main input
6-- No more Python server - Continue runs entirely in Typescript
deleted .changes/extensions/vscode/v0.6.19.md +0 −11
@@ -1,11 +0,0 @@
1-## v0.6.19 - 2024-01-05
2-
3-### Added
4-
5-- support for .continuerc.json in root of workspace to override config.json
6-- Inline context providers
7-- cmd+shift+L with new diff streaming UI for edits
8-
9-### Changed
10-
11-- Allow certain LLM servers to handle templating
deleted .changes/extensions/vscode/v0.6.4.md +0 −5
@@ -1,5 +0,0 @@
1-## v0.6.4 - 2023-11-19
2-
3-### Changed
4-
5-- migrated to .json config file format
deleted .changes/extensions/vscode/v0.8.1.md +0 −9
@@ -1,9 +0,0 @@
1-## v0.8.1 - 2024-01-08
2-
3-### Added
4-
5-- disableSessionTitles option in config.json
6-
7-### Changed
8-
9-- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
deleted .changes/extensions/vscode/v0.8.2.md +0 −8
@@ -1,8 +0,0 @@
1-## v0.8.2 - 2024-01-23
2-### Added
3-* Add codellama and gemini to free trial, using new server
4-* Local codebase syncing and embeddings using LanceDB
5-* Improved VS Code theme matching
6-### Changed
7-* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
8-* Context providers now run from the extension side (in Node.js instead of browser javascript)
deleted .changes/header.tpl.md +0 −5
@@ -1,5 +0,0 @@
1-All notable changes to this project will be documented in this file.
2-
3-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
4-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
5-and is generated by [Changie](https://github.com/miniscruff/changie).
deleted .changes/unreleased/.gitkeep +0 −0
deleted .changie.yaml +0 −35
@@ -1,35 +0,0 @@
1-changesDir: .changes
2-unreleasedDir: unreleased
3-headerPath: header.tpl.md
4-changelogPath: CHANGELOG.md
5-versionExt: md
6-versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
7-kindFormat: "### {{.Kind}}"
8-changeFormat: "* {{.Body}}"
9-kinds:
10- - label: Added
11- auto: minor
12- - label: Changed
13- auto: major
14- - label: Deprecated
15- auto: minor
16- - label: Removed
17- auto: major
18- - label: Fixed
19- auto: patch
20- - label: Security
21- auto: patch
22-newlines:
23- afterChangelogHeader: 1
24- beforeChangelogVersion: 1
25- endOfVersion: 1
26-envPrefix: CHANGIE_
27-
28-projects:
29- - label: extensions/intellij
30- key: extensions/intellij
31- changelog: extensions/intellij/CHANGELOG.md
32-
33- - label: extensions/vscode
34- key: extensions/vscode
35- changelog: extensions/vscode/CHANGELOG.md
added .continue/rules/intellij-plugin-test-execution.yaml +15 −0
@@ -0,0 +1,15 @@
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
added .continue/rules/intellij-test-standards.yaml +10 −0
@@ -0,0 +1,10 @@
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"
added .continue/rules/unit-testing-rules.yaml +30 −0
@@ -0,0 +1,30 @@
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+
10+ 1. The project uses Jest as the testing framework
11+
12+ 2. Run tests using `npm test` from within the specific package/module
13+ directory
14+
15+ 3. Command structure: `cd [directory] && npm test -- [test file path]`
16+
17+ 4. The test script uses experimental VM modules via NODE_OPTIONS flag
18+
19+ 5. Test files follow the pattern `*.test.ts`
20+
21+ 6. Tests must import Jest with `import { jest } from "@jest/globals";`
22+
23+ 7. Run tests from within the specific package directory (e.g., `cd core`
24+ for core module tests)
25+
26+ 8. Write tests as top-level `test()` functions - DO NOT use `describe()`
27+ blocks
28+
29+ 9. Include the function name being tested in the test description for
30+ clarity
modified .github/pull_request_template.md +2 −2
@@ -12,6 +12,6 @@
1212
1313 [ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
1414
15-## Testing instructions
15+## Tests
1616
17-[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change, including any relevant tests to run. ]
17+[ What tests were added or updated to ensure the changes work as expected? ]
added .github/workflows/cla.yaml +30 −0
@@ -0,0 +1,30 @@
1+name: "CLA Assistant"
2+on:
3+ issue_comment:
4+ types: [created]
5+ pull_request_target:
6+ types: [opened, closed, synchronize]
7+
8+permissions:
9+ actions: write
10+ contents: write
11+ pull-requests: write
12+ statuses: write
13+
14+jobs:
15+ CLAAssistant:
16+ runs-on: ubuntu-latest
17+ # Only run this workflow on the main repository (continuedev/continue)
18+ if: github.repository == 'continuedev/continue'
19+ steps:
20+ - name: "CLA Assistant"
21+ if: (contains(github.event.comment.body, 'recheck') || contains(github.event.comment.body, 'I have read the CLA Document and I hereby sign the CLA')) || github.event_name == 'pull_request_target'
22+ uses: contributor-assistant/github-action@v2.6.1
23+ env:
24+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
25+ with:
26+ path-to-signatures: "signatures/version1/cla.json"
27+ path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
28+ branch: cla-signatures
29+ allowlist: dependabot[bot]
30+ signed-commit-message: "CLA signed in $pullRequestNo"
modified .github/workflows/jetbrains-release.yaml +1 −1
@@ -63,7 +63,7 @@
6363
6464 - name: Bump version in gradle.properties
6565 run: |
66- cd extensions/intelllij
66+ cd extensions/intellij
6767 awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
6868 rm -rf tmp
6969 NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
modified .github/workflows/main.yaml +1 −1
@@ -235,7 +235,7 @@
235235 - name: Publish to VS Code Marketplace
236236 run: |
237237 cd extensions/vscode
238- npx vsce publish --packagePath ../../vsix-artifacts/*.vsix
238+ npx @vscode/vsce publish --packagePath ../../vsix-artifacts/*.vsix
239239 env:
240240 VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
241241
modified .github/workflows/pr_checks.yaml +2 −1
@@ -235,10 +235,11 @@
235235 cd packages/config-yaml
236236 npm run build
237237
238- - name: Type check
238+ - name: Type check and lint
239239 run: |
240240 cd gui
241241 npx tsc --noEmit
242+ npm run lint
242243
243244 binary-checks:
244245 needs: [install-root, install-core, install-config-yaml]
modified .github/workflows/preview.yaml +1 −1
@@ -232,7 +232,7 @@
232232 - name: Publish to VS Code Marketplace
233233 run: |
234234 cd extensions/vscode
235- npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
235+ npx @vscode/vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
236236 env:
237237 VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
238238
modified .gitignore +5 −1
@@ -162,5 +162,9 @@
162162
163163 *.vsix
164164
165+# intellij module library files
166+*.iml
167+
165168 .continuerules
166-**/.continue/assistants/
No newline at the end of the file
169+**/.continue/assistants/
170+keys
No newline at the end of the file
added .idea/jsLinters/eslint.xml +6 −0
@@ -0,0 +1,6 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<project version="4">
3+ <component name="EslintConfiguration">
4+ <option name="fix-on-save" value="true" />
5+ </component>
6+</project>
No newline at the end of the file
modified .idea/prettier.xml +1 −0
@@ -2,5 +2,6 @@
22 <project version="4">
33 <component name="PrettierConfiguration">
44 <option name="myConfigurationMode" value="AUTOMATIC" />
5+ <option name="myRunOnSave" value="true" />
56 </component>
67 </project>
No newline at the end of the file
added .idea/runConfigurations/config_yaml_tests.xml +22 −0
@@ -0,0 +1,22 @@
1+<component name="ProjectRunConfigurationManager">
2+ <configuration default="false" name="config-yaml tests" type="JavaScriptTestRunnerJest">
3+ <config-file value="$PROJECT_DIR$/packages/config-yaml/jest.config.mjs" />
4+ <node-interpreter value="project" />
5+ <node-options value="--experimental-vm-modules" />
6+ <jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
7+ <working-dir value="$PROJECT_DIR$/packages/config-yaml" />
8+ <envs />
9+ <scope-kind value="ALL" />
10+ <method v="2">
11+ <option name="NpmBeforeRunTask" enabled="true">
12+ <package-json value="$PROJECT_DIR$/packages/config-yaml/package.json" />
13+ <command value="run" />
14+ <scripts>
15+ <script value="build" />
16+ </scripts>
17+ <node-interpreter value="project" />
18+ <envs />
19+ </option>
20+ </method>
21+ </configuration>
22+</component>
No newline at the end of the file
added .idea/runConfigurations/core_tests.xml +12 −0
@@ -0,0 +1,12 @@
1+<component name="ProjectRunConfigurationManager">
2+ <configuration default="false" name="core tests" type="JavaScriptTestRunnerJest">
3+ <config-file value="$PROJECT_DIR$/core/jest.config.js" />
4+ <node-interpreter value="project" />
5+ <node-options value="--experimental-vm-modules" />
6+ <jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
7+ <working-dir value="$PROJECT_DIR$/core" />
8+ <envs />
9+ <scope-kind value="ALL" />
10+ <method v="2" />
11+ </configuration>
12+</component>
No newline at the end of the file
added .idea/runConfigurations/openai_adapters_configuration.xml +25 −0
@@ -0,0 +1,25 @@
1+<component name="ProjectRunConfigurationManager">
2+ <configuration default="false" name="openai-adapters configuration" type="JavaScriptTestRunnerJest">
3+ <node-interpreter value="project" />
4+ <node-options value="--experimental-vm-modules" />
5+ <jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
6+ <working-dir value="$PROJECT_DIR$/packages/openai-adapters" />
7+ <envs />
8+ <scope-kind value="SUITE" />
9+ <test-file value="$PROJECT_DIR$/packages/openai-adapters/src/test/main.test.ts" />
10+ <test-names>
11+ <test-name value="openai configuration" />
12+ </test-names>
13+ <method v="2">
14+ <option name="NpmBeforeRunTask" enabled="true">
15+ <package-json value="$PROJECT_DIR$/packages/openai-adapters/package.json" />
16+ <command value="run" />
17+ <scripts>
18+ <script value="build" />
19+ </scripts>
20+ <node-interpreter value="project" />
21+ <envs />
22+ </option>
23+ </method>
24+ </configuration>
25+</component>
No newline at the end of the file
modified .idea/vcs.xml +6 −0
@@ -1,5 +1,11 @@
11 <?xml version="1.0" encoding="UTF-8"?>
22 <project version="4">
3+ <component name="CommitMessageInspectionProfile">
4+ <profile version="1.0">
5+ <inspection_tool class="CommitFormat" enabled="true" level="WARNING" enabled_by_default="true" />
6+ <inspection_tool class="CommitNamingConvention" enabled="true" level="WARNING" enabled_by_default="true" />
7+ </profile>
8+ </component>
39 <component name="VcsDirectoryMappings">
410 <mapping directory="" vcs="Git" />
511 </component>
modified .vscode/extensions.json +2 −1
@@ -5,6 +5,7 @@
55 "dbaeumer.vscode-eslint",
66 "esbenp.prettier-vscode",
77 "bradlc.vscode-tailwindcss",
8- "YoavBls.pretty-ts-errors"
8+ "YoavBls.pretty-ts-errors",
9+ "github.vscode-github-actions"
910 ]
1011 }
deleted CHANGELOG.md +0 −6
@@ -1,6 +0,0 @@
1-# Changelog
2-
3-Separate changelogs are kept for each extension:
4-
5-- [VS Code Extension](./extensions/vscode/CHANGELOG.md)
6-- [JetBrains Extension](./extensions/intellij/CHANGELOG.md)
modified CONTRIBUTING.md +135 −90
@@ -3,44 +3,49 @@
33 ## Table of Contents
44
55 - [Contributing to Continue](#contributing-to-continue)
6- - [Table of Contents](#table-of-contents)
6+ - [Table of Contents](#table-of-contents)
77 - [❤️ Ways to Contribute](#️-ways-to-contribute)
8- - [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
9- - [🐛 Report Bugs](#-report-bugs)
10- - [✨ Suggest Enhancements](#-suggest-enhancements)
11- - [📖 Updating / Improving Documentation](#-updating--improving-documentation)
12- - [Running the Documentation Server Locally](#running-the-documentation-server-locally)
13- - [Method 1: NPM Script](#method-1-npm-script)
14- - [Method 2: VS Code Task](#method-2-vs-code-task)
15- - [🧑‍💻 Contributing Code](#-contributing-code)
16- - [Environment Setup](#environment-setup)
17- - [Pre-requisites](#pre-requisites)
18- - [Fork the Continue Repository](#fork-the-continue-repository)
19- - [VS Code](#vs-code)
20- - [Debugging](#debugging)
21- - [JetBrains](#jetbrains)
22- - [Our Git Workflow](#our-git-workflow)
23- - [Development workflow](#development-workflow)
24- - [Formatting](#formatting)
25- - [Testing](#testing)
26- - [Review Process](#review-process)
27- - [Getting help](#getting-help)
28- - [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
29- - [Adding an LLM Provider](#adding-an-llm-provider)
30- - [Adding Models](#adding-models)
31- - [📐 Continue Architecture](#-continue-architecture)
32- - [Continue VS Code Extension](#continue-vs-code-extension)
33- - [Continue JetBrains Extension](#continue-jetbrains-extension)
8+ - [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
9+ - [🐛 Report Bugs](#-report-bugs)
10+ - [✨ Suggest Enhancements](#-suggest-enhancements)
11+ - [📖 Updating / Improving Documentation](#-updating--improving-documentation)
12+ - [Running the Documentation Server Locally](#running-the-documentation-server-locally)
13+ - [Method 1: NPM Script](#method-1-npm-script)
14+ - [Method 2: VS Code Task](#method-2-vs-code-task)
15+ - [🧑‍💻 Contributing Code](#-contributing-code)
16+ - [Environment Setup](#environment-setup)
17+ - [Pre-requisites](#pre-requisites)
18+ - [Fork the Continue Repository](#fork-the-continue-repository)
19+ - [VS Code](#vs-code)
20+ - [Debugging](#debugging)
21+ - [JetBrains](#jetbrains)
22+ - [Our Git Workflow](#our-git-workflow)
23+ - [Development workflow](#development-workflow)
24+ - [Formatting](#formatting)
25+ - [Testing](#testing)
26+ - [Review Process](#review-process)
27+ - [Getting help](#getting-help)
28+ - [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
29+ - [Adding an LLM Provider](#adding-an-llm-provider)
30+ - [Adding Models](#adding-models)
31+ - [📐 Continue Architecture](#-continue-architecture)
32+ - [Continue VS Code Extension](#continue-vs-code-extension)
33+ - [Continue JetBrains Extension](#continue-jetbrains-extension)
34+ - [Contibutor License Agreement](#contributor-license-agreement-cla)
3435
3536 # ❤️ Ways to Contribute
3637
3738 ## 👋 Continue Contribution Ideas
3839
39-[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project.
40+[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can
41+contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project. You
42+can also browse the list
43+of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
4044
4145 ## 🐛 Report Bugs
4246
43-If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug report includes:
47+If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug
48+report includes:
4449
4550 - A description of the bug
4651 - Steps to reproduce
@@ -50,19 +55,22 @@
5055
5156 ## ✨ Suggest Enhancements
5257
53-Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
58+Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest
59+an enhancement are:
5460
5561 - Create an issue
5662
57- - First, check whether a similar proposal has already been made
58- - If not, [create an issue](https://github.com/continuedev/continue/issues)
59- - Please describe the enhancement in as much detail as you can, and why it would be useful
63+ - First, check whether a similar proposal has already been made
64+ - If not, [create an issue](https://github.com/continuedev/continue/issues)
65+ - Please describe the enhancement in as much detail as you can, and why it would be useful
6066
6167 - Join the [Continue Discord](https://discord.gg/NWtdYexhMs) and tell us about your idea in the `#feedback` channel
6268
6369 ## 📖 Updating / Improving Documentation
6470
65-Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev).
71+Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see
72+something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page
73+on [docs.continue.dev](https://docs.continue.dev).
6674
6775 ### Running the Documentation Server Locally
6876
@@ -70,7 +78,8 @@
7078
7179 #### Method 1: NPM Script
7280
73-1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
81+1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see
82+ there is a sign you're in the right place.
7483
7584 2. Run the following command to install the necessary dependencies for the documentation server:
7685
@@ -92,17 +101,22 @@
92101
93102 3. Look for the `docs:start` task and select it.
94103
95-This will start a local server and you can see the documentation rendered in your default browser, typically accessible at `http://localhost:3000`.
104+This will start a local server and you can see the documentation rendered in your default browser, typically accessible
105+at `http://localhost:3000`.
96106
97107 ## 🧑‍💻 Contributing Code
98108
99-We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
109+We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source
110+maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the
111+process as welcoming and straightforward as possible.
100112
101113 ### Environment Setup
102114
103115 #### Pre-requisites
104116
105-You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
117+You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it
118+on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct
119+version of Node.js for this project by running the following command in the root of the project:
106120
107121 ```bash
108122 nvm use
@@ -114,32 +128,39 @@
114128
115129 2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
116130
117-3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
131+3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there,
132+ like so: `git checkout -b 123-my-feature-branch`
118133
119134 4. Send your pull request to the main branch.
120135
121136 #### VS Code
122137
123-1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
138+1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select
139+ `install-all-dependencies`
124140
125141 2. Start debugging:
126142
127- 1. Switch to Run and Debug view
128- 2. Select `Launch extension` from drop down
129- 3. Hit play button
130- 4. This will start the extension in debug mode and open a new VS Code window with it installed
131- 1. The new VS Code window with the extension is referred to as the _Host VS Code_
132- 2. The window you started debugging from is referred to as the _Main VS Code_
143+ 1. Switch to Run and Debug view
144+ 2. Select `Launch extension` from drop down
145+ 3. Hit play button
146+ 4. This will start the extension in debug mode and open a new VS Code window with it installed
147+ 1. The new VS Code window with the extension is referred to as the _Host VS Code_
148+ 2. The window you started debugging from is referred to as the _Main VS Code_
133149
134-3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
150+3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and
151+ then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which
152+ you can install by right-clicking and selecting "Install Extension VSIX".
135153
136154 ##### Debugging
137155
138-**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code.
156+**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently
157+supported inside of `gui` code.
139158
140-**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
159+**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected
160+without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
141161
142-Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS Code_ window with cmd/ctrl+shift+p "Reload Window".
162+Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS
163+Code_ window with cmd/ctrl+shift+p "Reload Window".
143164
144165 #### JetBrains
145166
@@ -147,11 +168,20 @@
147168
148169 ### Our Git Workflow
149170
150-We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <http://releaseflow.org>.
171+We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
172+`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
173+in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
174+a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
175+workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
176+extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
177+is well explained by <http://releaseflow.org>.
151178
152-### Development workflow
179+### What makes a good PR?
153180
154-- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction.
181+To keep the Continue codebase clean and maintainable, we expect the following from our own team and all contributors:
182+
183+- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned
184+ with the project direction
155185 - Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
156186 - Write or update tests for new functionality
157187 - Update relevant documentation in the `docs` folder
@@ -159,18 +189,22 @@
159189
160190 ### Formatting
161191
162-Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
192+Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format
193+JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
163194
164195 ### Testing
165196
166-We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
197+We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on
198+each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we
199+merge.
167200
168201 When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
169202
170203 ### Review Process
171204
172205 - **Initial Review** - A maintainer will be assigned as primary reviewer
173-- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
206+- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is
207+ maintainable and follows our patterns.
174208 - **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
175209
176210 ### Getting help
@@ -181,42 +215,53 @@
181215
182216 ### Adding an LLM Provider
183217
184-Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
185-
186-1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
187-
188-- `providerName` - the identifier for your provider.
189-- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
190-
218+Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI,
219+Ollama, Together, LM Studio, Msty, and more. You can find all of the existing
220+providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can
221+add it with the following steps:
222+
223+1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it
224+ should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We
225+ recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a
226+ good simple example.
191227 2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
192-3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
193-4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`.
194-5. Add a documentation page for your provider in [`docs/docs/customize/model-providers`](./docs/docs/customize/model-providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
228+3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
229+ in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
230+4. Add a documentation page for your provider in [
231+ `docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
232+ of configuring your provider in `config.yaml` and explain what options are available.
195233
196234 ### Adding Models
197235
198-While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
199-
200-- [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it.
201-- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
202- 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
203- 2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
204-- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
205-- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
206-- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
207-
208-## 📐 Continue Architecture
209-
210-Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible:
211-
212-1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
213-
214-2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
215-
216-### Continue VS Code Extension
217-
218-The starting point for the VS Code extension is [activate.ts](./extensions/vscode/src/activation/activate.ts). The `activateExtension` function here will register all commands and load the Continue GUI in the sidebar of the IDE as a webview.
219-
220-### Continue JetBrains Extension
236+While any model that works with a supported provider can be used with Continue, we keep a list of recommended models
237+that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a
238+model:
239+
240+- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the
241+ side bar model selection UI. To add a new model:
242+ 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts),
243+ following the lead of the many examples near the top of the file
244+ 2. Add the model within its provider's array
245+ to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
246+- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the
247+ translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these
248+ providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts),
249+ and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists
250+ here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
251+- [Prompt Templates](./core/llm/autodetect.ts) - In this file you'll find the `autodetectTemplateType` function. Make
252+ sure that for the model name you just added, this function returns the correct template type. This is assuming that
253+ the chat template for that model is already built in Continue. If not, you will have to add the template type and
254+ corresponding edit and chat templates.
255+
256+## Contributor License Agreement (CLA)
257+
258+We require all contributors to accept the CLA and have made it as easy as commenting on your PR:
259+
260+1. Open your pull request.
261+2. Paste the following comment (or reply `recheck` if you’ve signed before):
262+
263+ ```text
264+ I have read the CLA Document and I hereby sign the CLA
265+ ```
221266
222-The JetBrains extension is currently in alpha testing. Please reach out on [Discord](https://discord.gg/vapESyrFmJ) if you are interested in contributing to its development.
267+3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.
No newline at the end of the file
modified README.md +19 −9
@@ -8,7 +8,10 @@
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 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](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, prompts, docs, and other building blocks](https://hub.continue.dev)**
1215
1316 </div>
1417
@@ -20,15 +23,25 @@
2023 <a target="_blank" href="https://docs.continue.dev" style="background:none">
2124 <img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" />
2225 </a>
26+<a target="_blank" href="https://changelog.continue.dev" style="background:none">
27+ <img src="https://img.shields.io/badge/changelog-%96EFF3" style="height: 22px;" />
28+</a>
2329 <a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
2430 <img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
2531 </a>
2632
2733 <p></p>
2834
35+## Agent
36+
37+[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
38+
39+![agent](docs/static/img/agent.gif)
40+
2941 ## Chat
3042
31-[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
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
3245
3346 ![chat](docs/static/img/chat.gif)
3447
@@ -40,15 +53,11 @@
4053
4154 ## Edit
4255
43-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
56+[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
57+file
4458
4559 ![edit](docs/static/img/edit.gif)
4660
47-## Agent
48-
49-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
50-
51-![agent](docs/static/img/agent.gif)
5261
5362 </div>
5463
@@ -58,7 +67,8 @@
5867
5968 ## Contributing
6069
61-Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
70+Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
71+join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
6272
6373 ## License
6474
modified binary/build.js +1 −1
@@ -64,7 +64,7 @@
6464 format: "cjs",
6565 platform: "node",
6666 sourcemap: true,
67- minify: true,
67+ minify: !esbuildOnly,
6868 treeShaking: true,
6969 loader: {
7070 // eslint-disable-next-line @typescript-eslint/naming-convention
modified binary/package-lock.json +25 −3
@@ -33,6 +33,7 @@
3333 "@types/jest": "^29.5.12",
3434 "@types/uuid": "^9.0.8",
3535 "@vercel/ncc": "^0.38.1",
36+ "cross-env": "^7.0.3",
3637 "esbuild": "0.19.11",
3738 "jest": "^29.7.0",
3839 "pkg": "^5.8.1",
@@ -92,6 +93,7 @@
9293 "p-limit": "^6.1.0",
9394 "partial-json": "^0.1.7",
9495 "pg": "^8.11.3",
96+ "plist": "^3.1.0",
9597 "posthog-node": "^3.6.3",
9698 "puppeteer": "^22.4.0",
9799 "puppeteer-chromium-resolver": "^23.0.0",
@@ -128,6 +130,7 @@
128130 "@types/mustache": "^4.2.5",
129131 "@types/node-fetch": "^2.6.11",
130132 "@types/pg": "^8.11.6",
133+ "@types/plist": "^3.0.5",
131134 "@types/request": "^2.48.12",
132135 "@types/tar": "^6.1.13",
133136 "@types/uuid": "^9.0.7",
@@ -2586,9 +2589,9 @@
25862589 }
25872590 },
25882591 "node_modules/axios": {
2589- "version": "1.7.9",
2590- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
2591- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
2592+ "version": "1.9.0",
2593+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
2594+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
25922595 "license": "MIT",
25932596 "dependencies": {
25942597 "follow-redirects": "^1.15.6",
@@ -3196,6 +3199,25 @@
31963199 "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
31973200 }
31983201 },
3202+ "node_modules/cross-env": {
3203+ "version": "7.0.3",
3204+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
3205+ "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
3206+ "dev": true,
3207+ "license": "MIT",
3208+ "dependencies": {
3209+ "cross-spawn": "^7.0.1"
3210+ },
3211+ "bin": {
3212+ "cross-env": "src/bin/cross-env.js",
3213+ "cross-env-shell": "src/bin/cross-env-shell.js"
3214+ },
3215+ "engines": {
3216+ "node": ">=10.14",
3217+ "npm": ">=6",
3218+ "yarn": ">=1"
3219+ }
3220+ },
31993221 "node_modules/cross-spawn": {
32003222 "version": "7.0.6",
32013223 "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
modified binary/package.json +1 −0
@@ -33,6 +33,7 @@
3333 "@types/jest": "^29.5.12",
3434 "@types/uuid": "^9.0.8",
3535 "@vercel/ncc": "^0.38.1",
36+ "cross-env": "^7.0.3",
3637 "esbuild": "0.19.11",
3738 "jest": "^29.7.0",
3839 "pkg": "^5.8.1",
modified core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +2 −1
@@ -72,7 +72,8 @@
7272 fullStop,
7373 );
7474
75- const timeoutValue = helper.options.showWhateverWeHaveAtXMs;
75+ const timeoutValue = helper.options.modelTimeout;
76+
7677
7778 lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
7879
modified core/autocomplete/filtering/streamTransforms/lineStream.test.ts +81 −1
@@ -2,6 +2,7 @@
22
33 import * as lineStream from "./lineStream";
44
5+// eslint-disable-next-line max-lines-per-function
56 describe("lineStream", () => {
67 let mockFullStop: jest.Mock;
78
@@ -204,6 +205,33 @@
204205 });
205206
206207 describe("filterCodeBlockLines", () => {
208+ it("should handle unfenced code", async () => {
209+ const linesGenerator = await getLineGenerator(["const x = 5;"]);
210+
211+ const result = lineStream.filterCodeBlockLines(linesGenerator);
212+ const filteredLines = await getFilteredLines(result);
213+
214+ expect(filteredLines).toEqual(["const x = 5;"]);
215+ });
216+
217+ it("should handle unfenced code with a code block", async () => {
218+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
219+
220+ const result = lineStream.filterCodeBlockLines(linesGenerator);
221+ const filteredLines = await getFilteredLines(result);
222+
223+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
224+ });
225+
226+ it("should handle unfenced code with two code blocks", async () => {
227+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
228+
229+ const result = lineStream.filterCodeBlockLines(linesGenerator);
230+ const filteredLines = await getFilteredLines(result);
231+
232+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
233+ });
234+
207235 it("should remove lines before the first valid line", async () => {
208236 const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
209237
@@ -213,7 +241,59 @@
213241 expect(filteredLines).toEqual(["const x = 5;"]);
214242 });
215243
216- it.todo("Need some sample inputs to properly test this");
244+ it("should remove outer blocks", async () => {
245+ const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
246+
247+ const result = lineStream.filterCodeBlockLines(linesGenerator);
248+ const filteredLines = await getFilteredLines(result);
249+
250+ expect(filteredLines).toEqual(["const x = 5;"]);
251+ });
252+
253+ it("should leave inner blocks intact", async () => {
254+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
255+
256+ const result = lineStream.filterCodeBlockLines(linesGenerator);
257+ const filteredLines = await getFilteredLines(result);
258+
259+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
260+ });
261+
262+ it("should handle included inner ticks", async () => {
263+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
264+
265+ const result = lineStream.filterCodeBlockLines(linesGenerator);
266+ const filteredLines = await getFilteredLines(result);
267+
268+ expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
269+ });
270+
271+ it("should leave single inner blocks intact but not return trailing text", async () => {
272+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
273+
274+ const result = lineStream.filterCodeBlockLines(linesGenerator);
275+ const filteredLines = await getFilteredLines(result);
276+
277+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
278+ });
279+
280+ it("should leave double inner blocks intact but not return trailing text", async () => {
281+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
282+
283+ const result = lineStream.filterCodeBlockLines(linesGenerator);
284+ const filteredLines = await getFilteredLines(result);
285+
286+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
287+ });
288+
289+ it("should leave inner blocks intact but not return trailing or leading text", async () => {
290+ const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
291+
292+ const result = lineStream.filterCodeBlockLines(linesGenerator);
293+ const filteredLines = await getFilteredLines(result);
294+
295+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
296+ });
217297 });
218298
219299 describe("filterEnglishLinesAtStart", () => {
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +40 −26
@@ -55,8 +55,8 @@
5555 return line;
5656 }
5757
58- if (line.includes(CODE_START_BLOCK)) {
59- return line.split(CODE_START_BLOCK)[0].trimEnd();
58+ if (line.includes(CODE_STOP_BLOCK)) {
59+ return line.split(CODE_STOP_BLOCK)[0].trimEnd();
6060 }
6161
6262 return undefined;
@@ -71,9 +71,9 @@
7171 return hasUselessLine || trimmed.startsWith("// end");
7272 }
7373
74-export const USELESS_LINES = ["", "```"];
74+export const USELESS_LINES = [""];
7575 export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
76-export const CODE_START_BLOCK = "[/CODE]";
76+export const CODE_STOP_BLOCK = "[/CODE]";
7777 export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
7878 export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
7979 export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
@@ -343,34 +343,48 @@
343343 * 4. Yields processed lines that are part of the actual code block content.
344344 */
345345 export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
346- let seenValidLine = false;
347- let waitingToSeeIfLineIsLast = undefined;
346+ let seenFirstFence = false;
347+ // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
348+ // when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
349+ // when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
350+ let nestCount = 0;
348351
349352 for await (const line of rawLines) {
350- // Filter out starting ```
351- if (!seenValidLine) {
353+
354+
355+ if (!seenFirstFence) {
352356 if (shouldRemoveLineBeforeStart(line)) {
353- continue;
357+ // Filter out starting ``` or START block
358+ continue
354359 }
355- seenValidLine = true;
356- }
357-
358- // Filter out ending ```
359- if (typeof waitingToSeeIfLineIsLast !== "undefined") {
360- yield waitingToSeeIfLineIsLast;
361- waitingToSeeIfLineIsLast = undefined;
360+ // Regardless of a fence or START block start tracking the nesting level
361+ seenFirstFence = true;
362+ nestCount = 1;
362363 }
363364
364- const changedEndLine = shouldChangeLineAndStop(line);
365- if (typeof changedEndLine === "string") {
366- yield changedEndLine;
367- return;
368- }
369-
370- if (line.startsWith("```")) {
371- waitingToSeeIfLineIsLast = line;
372- } else {
373- yield line;
365+ if (nestCount > 0) {
366+ // Inside a block including the outer block
367+ const changedEndLine = shouldChangeLineAndStop(line);
368+ if (typeof changedEndLine === "string") {
369+ // Ending a block with just backticks (```) or STOP
370+ nestCount--;
371+ if (nestCount === 0) {
372+ // if we are closing the outer block then exit early
373+ // only exit early if the outer block was started with a block
374+ // it it was text, we will never exit early
375+ return;
376+ } else {
377+ // otherwise just yield the line
378+ yield line;
379+ }
380+ } else if (line.startsWith("```")) {
381+ // Going into a nested codeblock
382+ nestCount++;
383+ yield line;
384+ } else {
385+ // otherwise just yield the line
386+ yield line;
387+ }
374388 }
375389 }
376390 }
modified core/autocomplete/generation/CompletionStreamer.ts +22 −7
@@ -3,6 +3,7 @@
33 import { HelperVars } from "../util/HelperVars";
44
55 import { GeneratorReuseManager } from "./GeneratorReuseManager";
6+import { stopAfterMaxProcessingTime } from "./utils";
67
78 export class CompletionStreamer {
89 private streamTransformPipeline = new StreamTransformPipeline();
@@ -22,23 +23,37 @@
2223 completionOptions: Partial<CompletionOptions> | undefined,
2324 helper: HelperVars,
2425 ) {
26+ // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
27+ const fullStop = () =>
28+ this.generatorReuseManager.currentGenerator?.cancel();
29+
2530 // Try to reuse pending requests if what the user typed matches start of completion
2631 const generator = this.generatorReuseManager.getGenerator(
2732 prefix,
28- (abortSignal: AbortSignal) =>
29- llm.supportsFim()
33+ (abortSignal: AbortSignal) => {
34+ const generator = llm.supportsFim()
3035 ? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
3136 : llm.streamComplete(prompt, abortSignal, {
3237 ...completionOptions,
3338 raw: true,
34- }),
39+ });
40+
41+ /**
42+ * This transformer applies even on reused generator. We are deliberately
43+ * not using streamTransformPipeline because we want to capture and stop
44+ * the request even if the generator is being reused.
45+ */
46+ return helper.options.transform
47+ ? stopAfterMaxProcessingTime(
48+ generator,
49+ helper.options.modelTimeout * 2.5,
50+ fullStop,
51+ )
52+ : generator;
53+ },
3554 multiline,
3655 );
3756
38- // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
39- const fullStop = () =>
40- this.generatorReuseManager.currentGenerator?.cancel();
41-
4257 // LLM
4358 const generatorWithCancellation = async function* () {
4459 for await (const update of generator) {
added core/autocomplete/generation/utils.test.ts +138 −0
@@ -0,0 +1,138 @@
1+import { jest } from "@jest/globals";
2+import { stopAfterMaxProcessingTime } from "./utils";
3+
4+describe("stopAfterMaxProcessingTime", () => {
5+ beforeEach(() => {
6+ jest.useFakeTimers();
7+ });
8+
9+ afterEach(() => {
10+ jest.useRealTimers();
11+ });
12+
13+ async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
14+ for (const chunk of chunks) {
15+ yield chunk;
16+ }
17+ }
18+
19+ async function streamToString(
20+ stream: AsyncGenerator<string>,
21+ ): Promise<string> {
22+ let result = "";
23+ for await (const chunk of stream) {
24+ result += chunk;
25+ }
26+ return result;
27+ }
28+
29+ it("should yield all chunks when maxTimeMs is not reached", async () => {
30+ const mockStream = createMockStream(["Hello", " world", "!"]);
31+ const fullStop = jest.fn();
32+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
33+
34+ const output = await streamToString(result);
35+
36+ expect(output).toBe("Hello world!");
37+ expect(fullStop).not.toHaveBeenCalled();
38+ });
39+
40+ it.only("should stop processing after max time is reached", async () => {
41+ // Mock implementation of Date.now
42+ let currentTime = 0;
43+ const originalDateNow = Date.now;
44+ Date.now = jest.fn(() => currentTime);
45+
46+ // Create a generator that we can control
47+ async function* controlledGenerator(): AsyncGenerator<string> {
48+ for (let i = 0; i < 100; i++) {
49+ // After yielding 10 chunks, simulate time passing beyond our limit
50+ if (i === 10) {
51+ currentTime = 1000; // This exceeds our 500ms limit
52+ }
53+ yield `chunk-${i}`;
54+ }
55+ }
56+
57+ const fullStop = jest.fn();
58+ const maxTimeMs = 500;
59+
60+ const transformedGenerator = stopAfterMaxProcessingTime(
61+ controlledGenerator(),
62+ maxTimeMs,
63+ fullStop,
64+ );
65+
66+ // Consume the generator and collect outputs
67+ const outputs: string[] = [];
68+ for await (const chunk of transformedGenerator) {
69+ outputs.push(chunk);
70+ }
71+
72+ // We expect:
73+ // 1. Not all chunks were processed (less than 100)
74+ // 2. fullStop was called
75+ // 3. We processed at least the chunks before time was exceeded
76+ expect(outputs.length).toBeLessThan(100);
77+ expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
78+ expect(fullStop).toHaveBeenCalled();
79+
80+ // Restore Date.now
81+ Date.now = originalDateNow;
82+ });
83+
84+ it("should check time only periodically based on checkInterval", async () => {
85+ const chunks = Array(100).fill("x");
86+ const mockStream = createMockStream(chunks);
87+ const fullStop = jest.fn();
88+
89+ // Spy on Date.now to count how many times it's called
90+ const dateSpy = jest.spyOn(Date, "now");
91+
92+ // Stream should complete normally (not hitting the timeout)
93+ await streamToString(
94+ stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
95+ );
96+
97+ // The first call is to set startTime, then once every checkInterval (10) chunks
98+ // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
99+ // We use a range because implementation details might vary slightly
100+ expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
101+ expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
102+
103+ dateSpy.mockRestore();
104+ });
105+
106+ it("should handle empty stream gracefully", async () => {
107+ const mockStream = createMockStream([]);
108+ const fullStop = jest.fn();
109+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
110+
111+ const output = await streamToString(result);
112+
113+ expect(output).toBe("");
114+ expect(fullStop).not.toHaveBeenCalled();
115+ });
116+
117+ it("should pass through all chunks if there's no timeout", async () => {
118+ const chunks = Array(100).fill("test chunk");
119+ const mockStream = createMockStream(chunks);
120+ const fullStop = jest.fn();
121+
122+ // Use undefined as timeout to simulate no timeout
123+ const result = stopAfterMaxProcessingTime(
124+ mockStream,
125+ undefined as any,
126+ fullStop,
127+ );
128+
129+ // Process the stream
130+ const processedChunks = [];
131+ for await (const chunk of result) {
132+ processedChunks.push(chunk);
133+ }
134+
135+ expect(processedChunks.length).toBe(chunks.length);
136+ expect(fullStop).not.toHaveBeenCalled();
137+ });
138+});
added core/autocomplete/generation/utils.ts +27 −0
@@ -0,0 +1,27 @@
1+export async function* stopAfterMaxProcessingTime(
2+ stream: AsyncGenerator<string>,
3+ maxTimeMs: number,
4+ fullStop: () => void,
5+): AsyncGenerator<string> {
6+ const startTime = Date.now();
7+ /**
8+ * Check every 10 chunks to avoid performance overhead.
9+ */
10+ const checkInterval = 10;
11+ let chunkCount = 0;
12+ let totalCharCount = 0;
13+
14+ for await (const chunk of stream) {
15+ yield chunk;
16+
17+ chunkCount++;
18+ totalCharCount += chunk.length;
19+
20+ if (chunkCount % checkInterval === 0) {
21+ if (Date.now() - startTime > maxTimeMs) {
22+ fullStop();
23+ return;
24+ }
25+ }
26+ }
27+}
modified core/autocomplete/templating/AutocompleteTemplate.ts +19 −0
@@ -71,6 +71,21 @@
7171 },
7272 };
7373
74+const seedCoderFimTemplate: AutocompleteTemplate = {
75+ template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
76+ completionOptions: {
77+ stop: [
78+ "<[end▁of▁sentence]>",
79+ "<[fim-prefix]>",
80+ "<[fim-middle]>",
81+ "<[fim-suffix]>",
82+ "<[PAD▁TOKEN]>",
83+ "<[SEP▁TOKEN]>",
84+ "<[begin▁of▁sentence]>",
85+ ],
86+ },
87+};
88+
7489 const codestralFimTemplate: AutocompleteTemplate = {
7590 template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
7691 completionOptions: {
@@ -426,6 +441,10 @@
426441 return qwenCoderFimTemplate;
427442 }
428443
444+ if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
445+ return seedCoderFimTemplate;
446+ }
447+
429448 if (
430449 lowerCaseModel.includes("starcoder") ||
431450 lowerCaseModel.includes("star-coder") ||
modified core/autocomplete/util/AutocompleteDebouncer.ts +24 −24
@@ -1,32 +1,32 @@
11 import { v4 as uuidv4 } from "uuid";
2+
23 export class AutocompleteDebouncer {
34 private debounceTimeout: NodeJS.Timeout | undefined = undefined;
4- private debouncing = false;
5- private lastUUID: string | undefined = undefined;
5+ private currentRequestId: string | undefined = undefined;
66
77 async delayAndShouldDebounce(debounceDelay: number): Promise<boolean> {
8- // Debounce
9- const uuid = uuidv4();
10- this.lastUUID = uuid;
11-
12- // Debounce
13- if (this.debouncing) {
14- this.debounceTimeout?.refresh();
15- const lastUUID = await new Promise((resolve) =>
16- setTimeout(() => {
17- resolve(this.lastUUID);
18- }, debounceDelay),
19- );
20- if (uuid !== lastUUID) {
21- return true;
22- }
23- } else {
24- this.debouncing = true;
25- this.debounceTimeout = setTimeout(async () => {
26- this.debouncing = false;
27- }, debounceDelay);
8+ // Generate a unique ID for this request
9+ const requestId = uuidv4();
10+ this.currentRequestId = requestId;
11+
12+ // Clear any existing timeout
13+ if (this.debounceTimeout) {
14+ clearTimeout(this.debounceTimeout);
2815 }
29-
30- return false;
16+
17+ // Create a new promise that resolves after the debounce delay
18+ return new Promise<boolean>((resolve) => {
19+ this.debounceTimeout = setTimeout(() => {
20+ // When the timeout completes, check if this is still the most recent request
21+ const shouldDebounce = this.currentRequestId !== requestId;
22+
23+ // If this is the most recent request, it shouldn't be debounced
24+ if (!shouldDebounce) {
25+ this.currentRequestId = undefined;
26+ }
27+
28+ resolve(shouldDebounce);
29+ }, debounceDelay);
30+ });
3131 }
3232 }
modified core/commands/slash/http.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { SlashCommand } from "../../index.js";
23 import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { streamResponse } from "../../llm/stream.js";
44
55 const HttpSlashCommand: SlashCommand = {
66 name: "http",
modified core/config/ConfigHandler.ts +17 −10
@@ -1,10 +1,6 @@
11 import { ConfigResult } from "@continuedev/config-yaml";
22
3-import {
4- ControlPlaneClient,
5- ControlPlaneSessionInfo,
6-} from "../control-plane/client.js";
7-import { getControlPlaneEnv } from "../control-plane/env.js";
3+import { ControlPlaneClient } from "../control-plane/client.js";
84 import {
95 BrowserSerializedContinueConfig,
106 ContinueConfig,
@@ -15,10 +11,15 @@
1511 } from "../index.js";
1612 import { GlobalContext } from "../util/GlobalContext.js";
1713
14+import {
15+ AuthType,
16+ ControlPlaneSessionInfo,
17+} from "../control-plane/AuthTypes.js";
18+import { getControlPlaneEnv } from "../control-plane/env.js";
1819 import { logger } from "../util/logger.js";
1920 import {
2021 ASSISTANTS,
21- getAllDotContinueYamlFiles,
22+ getAllDotContinueDefinitionFiles,
2223 LoadAssistantFilesOptions,
2324 } from "./loadLocalAssistants.js";
2425 import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@@ -136,8 +137,7 @@
136137 }
137138
138139 private async getOrgs(): Promise<OrgWithProfiles[]> {
139- const userId = await this.controlPlaneClient.userId;
140- if (userId) {
140+ if (await this.controlPlaneClient.isSignedIn()) {
141141 const orgDescs = await this.controlPlaneClient.listOrganizations();
142142 const personalHubOrg = await this.getPersonalHubOrg();
143143 const hubOrgs = await Promise.all(
@@ -255,7 +255,7 @@
255255 if (currentProfile) {
256256 this.globalContext.update("lastSelectedProfileForWorkspace", {
257257 ...selectedProfiles,
258- [profileKey]: selectedProfiles.id ?? null,
258+ [profileKey]: currentProfile.profileDescription.id,
259259 });
260260 }
261261
@@ -270,6 +270,13 @@
270270 /**
271271 * Users can define as many local assistants as they want in a `.continue/assistants` folder
272272 */
273+
274+ // Local customization disabled for on-premise deployments
275+ const env = await getControlPlaneEnv(this.ide.getIdeSettings());
276+ if (env.AUTH_TYPE === AuthType.OnPrem) {
277+ return [];
278+ }
279+
273280 const localProfiles: ProfileLifecycleManager[] = [];
274281
275282 if (options.includeGlobal) {
@@ -277,7 +284,7 @@
277284 }
278285
279286 if (options.includeWorkspace) {
280- const assistantFiles = await getAllDotContinueYamlFiles(
287+ const assistantFiles = await getAllDotContinueDefinitionFiles(
281288 this.ide,
282289 options,
283290 ASSISTANTS,
modified core/config/load.ts +9 −3
@@ -101,7 +101,14 @@
101101
102102 const configMergeKeys = {
103103 models: (a: any, b: any) => a.title === b.title,
104- contextProviders: (a: any, b: any) => a.name === b.name,
104+ contextProviders: (a: any, b: any) => {
105+ // If not HTTP providers, use the name only
106+ if (a.name !== "http" || b.name !== "http") {
107+ return a.name === b.name;
108+ }
109+ // For HTTP providers, consider them different if they have different URLs
110+ return a.name === b.name && a.params?.url === b.params?.url;
111+ },
105112 slashCommands: (a: any, b: any) => a.name === b.name,
106113 customCommands: (a: any, b: any) => a.name === b.name,
107114 };
@@ -970,6 +977,5 @@
970977 finalToBrowserConfig,
971978 intermediateToFinalConfig,
972979 loadContinueConfigFromJson,
973- type BrowserSerializedContinueConfig
980+ type BrowserSerializedContinueConfig,
974981 };
975-
modified core/config/loadLocalAssistants.ts +5 −5
@@ -13,7 +13,7 @@
1313 export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
1414
1515 export function isLocalAssistantFile(uri: string): boolean {
16- if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
16+ if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
1717 return false;
1818 }
1919
@@ -21,7 +21,7 @@
2121 return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
2222 }
2323
24-export async function listYamlFilesInDir(
24+async function getDefinitionFilesInDir(
2525 ide: IDE,
2626 dir: string,
2727 ): Promise<{ path: string; content: string }[]> {
@@ -41,7 +41,7 @@
4141 source: "get assistant files",
4242 });
4343 const assistantFilePaths = uris.filter(
44- (p) => p.endsWith(".yaml") || p.endsWith(".yml"),
44+ (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
4545 );
4646 const results = assistantFilePaths.map(async (uri) => {
4747 const content = await ide.readFile(uri); // make a try catch
@@ -86,7 +86,7 @@
8686 * This method searches in both ~/.continue and workspace .continue
8787 * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
8888 */
89-export async function getAllDotContinueYamlFiles(
89+export async function getAllDotContinueDefinitionFiles(
9090 ide: IDE,
9191 options: LoadAssistantFilesOptions,
9292 subDirName: string,
@@ -103,7 +103,7 @@
103103
104104 // Get all assistant files from the directories
105105 const assistantFiles = (
106- await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
106+ await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
107107 ).flat();
108108
109109 return await Promise.all(
added core/config/markdown/loadMarkdownRules.ts +47 −0
@@ -0,0 +1,47 @@
1+import { ConfigValidationError } from "@continuedev/config-yaml";
2+import { IDE, RuleWithSource } from "../..";
3+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4+import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
5+
6+/**
7+ * Loads rules from markdown files in the .continue/rules directory
8+ */
9+export async function loadMarkdownRules(ide: IDE): Promise<{
10+ rules: RuleWithSource[];
11+ errors: ConfigValidationError[];
12+}> {
13+ const errors: ConfigValidationError[] = [];
14+ const rules: RuleWithSource[] = [];
15+
16+ try {
17+ // Get all .md files from .continue/rules
18+ const markdownFiles = await getAllDotContinueDefinitionFiles(
19+ ide,
20+ { includeGlobal: true, includeWorkspace: true },
21+ "rules",
22+ );
23+
24+ // Filter to just .md files
25+ const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
26+
27+ // Process each markdown file
28+ for (const file of mdFiles) {
29+ try {
30+ const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
31+ rules.push(rule);
32+ } catch (e) {
33+ errors.push({
34+ fatal: false,
35+ message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
36+ });
37+ }
38+ }
39+ } catch (e) {
40+ errors.push({
41+ fatal: false,
42+ message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
43+ });
44+ }
45+
46+ return { rules, errors };
47+}
added core/config/markdown/parseMarkdownRule.test.ts +174 −0
@@ -0,0 +1,174 @@
1+import {
2+ convertMarkdownRuleToContinueRule,
3+ parseMarkdownRule,
4+} from "./parseMarkdownRule";
5+
6+describe("parseMarkdownRule", () => {
7+ it("should correctly parse markdown with YAML frontmatter", () => {
8+ const content = `---
9+globs: "**/test/**/*.kt"
10+---
11+
12+# Test Rule
13+
14+This is a test rule.`;
15+
16+ const result = parseMarkdownRule(content);
17+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
18+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
19+ });
20+
21+ it("should handle missing frontmatter", () => {
22+ const content = `# Test Rule
23+
24+This is a test rule without frontmatter.`;
25+
26+ const result = parseMarkdownRule(content);
27+ expect(result.frontmatter).toEqual({});
28+ expect(result.markdown).toBe(content);
29+ });
30+
31+ it("should handle empty frontmatter", () => {
32+ const content = `---
33+---
34+
35+# Test Rule
36+
37+This is a test rule with empty frontmatter.`;
38+
39+ const result = parseMarkdownRule(content);
40+
41+ // Log exact strings for debugging
42+ console.log("Actual:", JSON.stringify(result.markdown));
43+ console.log(
44+ "Expected:",
45+ JSON.stringify(
46+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
47+ ),
48+ );
49+
50+ expect(result.frontmatter).toEqual({});
51+ expect(result.markdown).toBe(
52+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
53+ );
54+ });
55+
56+ it("should handle frontmatter with whitespace", () => {
57+ const content = `---
58+globs: "**/test/**/*.kt"
59+---
60+
61+# Test Rule
62+
63+This is a test rule.`;
64+
65+ const result = parseMarkdownRule(content);
66+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
67+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
68+ });
69+
70+ it("should handle Windows line endings (CRLF)", () => {
71+ // Using \r\n for CRLF line endings
72+ const content = `---\r
73+globs: "**/test/**/*.kt"\r
74+---\r
75+\r
76+# Test Rule\r
77+\r
78+This is a test rule.`;
79+
80+ const result = parseMarkdownRule(content);
81+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
82+ // The result should be normalized to \n
83+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
84+ });
85+
86+ it("should handle malformed frontmatter", () => {
87+ const content = `---
88+globs: - "**/test/**/*.kt"
89+invalid: yaml: content
90+---
91+
92+# Test Rule
93+
94+This is a test rule.`;
95+
96+ // Should treat as only markdown when frontmatter is malformed
97+ const result = parseMarkdownRule(content);
98+ expect(result.frontmatter).toEqual({});
99+ expect(result.markdown).toBe(content);
100+ });
101+});
102+
103+describe("convertMarkdownRuleToContinueRule", () => {
104+ it("should convert markdown with frontmatter to a rule", () => {
105+ const content = `---
106+globs: "**/test/**/*.kt"
107+name: Custom Name
108+---
109+
110+# Test Rule
111+
112+This is a test rule.`;
113+
114+ const result = convertMarkdownRuleToContinueRule(
115+ "/path/to/rule.md",
116+ content,
117+ );
118+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
119+ expect(result.globs).toBe("**/test/**/*.kt");
120+ expect(result.name).toBe("Custom Name");
121+ expect(result.source).toBe("rules-block");
122+ expect(result.ruleFile).toBe("/path/to/rule.md");
123+ });
124+
125+ it("should use the first heading as name if not in frontmatter", () => {
126+ const content = `---
127+globs: "**/test/**/*.kt"
128+---
129+
130+# Test Rule Title
131+
132+This is a test rule.`;
133+
134+ const result = convertMarkdownRuleToContinueRule(
135+ "/path/to/rule.md",
136+ content,
137+ );
138+ expect(result.name).toBe("Test Rule Title");
139+ });
140+
141+ it("should use filename as name if no heading or frontmatter name", () => {
142+ const content = `---
143+globs: "**/test/**/*.kt"
144+---
145+
146+This is a test rule without a heading.`;
147+
148+ const result = convertMarkdownRuleToContinueRule(
149+ "/path/to/custom-rule.md",
150+ content,
151+ );
152+ expect(result.name).toBe("custom-rule");
153+ });
154+
155+ it("should include description from frontmatter", () => {
156+ const content = `---
157+globs: "**/test/**/*.kt"
158+name: Test Rule
159+description: This is a rule description from frontmatter
160+---
161+
162+# Test Rule
163+
164+This is the content of the rule.`;
165+
166+ const result = convertMarkdownRuleToContinueRule(
167+ "/path/to/rule.md",
168+ content,
169+ );
170+ expect(result.description).toBe(
171+ "This is a rule description from frontmatter",
172+ );
173+ });
174+});
added core/config/markdown/parseMarkdownRule.ts +69 −0
@@ -0,0 +1,69 @@
1+import { basename } from "path";
2+import * as YAML from "yaml";
3+import { RuleWithSource } from "../..";
4+
5+/**
6+ * Parses markdown content with YAML frontmatter
7+ */
8+export function parseMarkdownRule(content: string): {
9+ frontmatter: Record<string, any>;
10+ markdown: string;
11+} {
12+ // Normalize line endings to \n
13+ const normalizedContent = content.replace(/\r\n/g, "\n");
14+
15+ // More reliable frontmatter detection
16+ const parts = normalizedContent.split(/^---\s*$/m);
17+
18+ // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
19+ if (parts.length >= 3) {
20+ const frontmatterStr = parts[1];
21+ // Join the remaining parts back together (in case there are more --- in the markdown)
22+ const markdownContent = parts.slice(2).join("---");
23+
24+ try {
25+ // Parse YAML frontmatter
26+ const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
27+ return { frontmatter, markdown: markdownContent.trim() };
28+ } catch (e) {
29+ // Error parsing frontmatter, treat as markdown only
30+ console.warn("Error parsing markdown frontmatter:", e);
31+ return { frontmatter: {}, markdown: normalizedContent };
32+ }
33+ }
34+
35+ // No frontmatter found
36+ return { frontmatter: {}, markdown: normalizedContent };
37+}
38+
39+/**
40+ * Converts a markdown file with YAML frontmatter to a RuleWithSource object
41+ */
42+export function convertMarkdownRuleToContinueRule(
43+ path: string,
44+ content: string,
45+): RuleWithSource {
46+ const { frontmatter, markdown } = parseMarkdownRule(content);
47+
48+ // Try to extract title from first heading if no name in frontmatter
49+ let name = frontmatter.name;
50+ if (!name) {
51+ // Look for a heading in the markdown
52+ const headingMatch = markdown.match(/^#\s+(.+)$/m);
53+ if (headingMatch) {
54+ name = headingMatch[1].trim();
55+ } else {
56+ // Fall back to filename
57+ name = basename(path).replace(/\.md$/, "");
58+ }
59+ }
60+
61+ return {
62+ name,
63+ rule: markdown,
64+ globs: frontmatter.globs,
65+ description: frontmatter.description,
66+ source: "rules-block",
67+ ruleFile: path,
68+ };
69+}
modified core/config/migrateSharedConfig.ts +7 −0
@@ -173,6 +173,13 @@
173173 effected = true;
174174 }
175175
176+ const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI;
177+ if (autoAcceptEditToolDiffs !== undefined) {
178+ shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs;
179+ migratedUI = withoutAutoApply;
180+ effected = true;
181+ }
182+
176183 const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
177184 if (showChatScrollbar !== undefined) {
178185 shareConfigUpdates.showChatScrollbar = showChatScrollbar;
modified core/config/profile/doLoadConfig.ts +7 −0
@@ -32,6 +32,7 @@
3232 import { TTS } from "../../util/tts";
3333 import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
3434 import { loadContinueConfigFromJson } from "../load";
35+import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
3536 import { migrateJsonSharedConfig } from "../migrateSharedConfig";
3637 import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
3738 import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@@ -128,6 +129,12 @@
128129 newConfig.rules.unshift(...rules);
129130 errors.push(...continueRulesErrors);
130131
132+ // Add rules from markdown files in .continue/rules
133+ const { rules: markdownRules, errors: markdownRulesErrors } =
134+ await loadMarkdownRules(ide);
135+ newConfig.rules.unshift(...markdownRules);
136+ errors.push(...markdownRulesErrors);
137+
131138 // Rectify model selections for each role
132139 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
133140
modified core/config/sharedConfig.ts +14 −0
@@ -26,11 +26,14 @@
2626 codeWrap: z.boolean(),
2727 displayRawMarkdown: z.boolean(),
2828 showChatScrollbar: z.boolean(),
29+ autoAcceptEditToolDiffs: z.boolean(),
2930
3031 // `tabAutocompleteOptions` in `ContinueConfig`
3132 useAutocompleteCache: z.boolean(),
3233 useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]),
3334 disableAutocompleteInFiles: z.array(z.string()),
35+ modelTimeout: z.number(),
36+ debounceDelay: z.number(),
3437 })
3538 .partial();
3639
@@ -103,6 +106,13 @@
103106 configCopy.tabAutocompleteOptions.disableInFiles =
104107 sharedConfig.disableAutocompleteInFiles;
105108 }
109+ if (sharedConfig.modelTimeout !== undefined) {
110+ configCopy.tabAutocompleteOptions.modelTimeout = sharedConfig.modelTimeout;
111+ }
112+ if (sharedConfig.debounceDelay !== undefined) {
113+ configCopy.tabAutocompleteOptions.debounceDelay =
114+ sharedConfig.debounceDelay;
115+ }
106116
107117 configCopy.ui = {
108118 ...configCopy.ui,
@@ -124,6 +134,10 @@
124134 if (sharedConfig.showChatScrollbar !== undefined) {
125135 configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
126136 }
137+ if (sharedConfig.autoAcceptEditToolDiffs !== undefined) {
138+ configCopy.ui.autoAcceptEditToolDiffs =
139+ sharedConfig.autoAcceptEditToolDiffs;
140+ }
127141
128142 if (sharedConfig.allowAnonymousTelemetry !== undefined) {
129143 configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
modified core/config/util.ts +1 −0
@@ -77,6 +77,7 @@
7777 model: model.model,
7878 apiKey: model.apiKey,
7979 apiBase: model.apiBase,
80+ maxStopWords: model.maxStopWords,
8081 defaultCompletionOptions: model.completionOptions,
8182 };
8283 if (model.systemMessage) {
modified core/config/yaml/loadYaml.ts +25 −10
@@ -9,6 +9,7 @@
99 PackageIdentifier,
1010 RegistryClient,
1111 Rule,
12+ TEMPLATE_VAR_REGEX,
1213 unrollAssistant,
1314 validateConfigYaml,
1415 } from "@continuedev/config-yaml";
@@ -40,9 +41,8 @@
4041 import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
4142
4243 import { getControlPlaneEnvSync } from "../../control-plane/env";
43-import { logger } from "../../util/logger";
4444 import { getCleanUriPath } from "../../util/uri";
45-import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
45+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4646 import { LocalPlatformClient } from "./LocalPlatformClient";
4747 import { llmsFromModelConfig } from "./models";
4848
@@ -71,8 +71,8 @@
7171 command: server.command,
7272 args: server.args ?? [],
7373 env: server.env,
74- },
75- timeout: server.connectionTimeout
74+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
75+ timeout: server.connectionTimeout,
7676 };
7777 }
7878
@@ -96,7 +96,7 @@
9696 // Add local .continue blocks
9797 const allLocalBlocks: PackageIdentifier[] = [];
9898 for (const blockType of BLOCK_TYPES) {
99- const localBlocks = await getAllDotContinueYamlFiles(
99+ const localBlocks = await getAllDotContinueDefinitionFiles(
100100 ide,
101101 { includeGlobal: true, includeWorkspace: true },
102102 blockType,
@@ -114,9 +114,9 @@
114114 ? dirname(getCleanUriPath(packageIdentifier.filePath))
115115 : undefined;
116116
117- logger.info(
118- `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
119- );
117+ // logger.info(
118+ // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
119+ // );
120120
121121 let config =
122122 overrideConfigYaml ??
@@ -241,6 +241,21 @@
241241 rootUrl: doc.rootUrl,
242242 faviconUrl: doc.faviconUrl,
243243 }));
244+
245+ config.mcpServers?.forEach((mcpServer) => {
246+ const mcpArgVariables =
247+ mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
248+
249+ if (mcpArgVariables.length === 0) {
250+ return;
251+ }
252+
253+ localErrors.push({
254+ fatal: false,
255+ message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
256+ });
257+ });
258+
244259 continueConfig.experimental = {
245260 modelContextProtocolServers: config.mcpServers?.map(
246261 convertYamlMcpToContinueMcp,
@@ -443,9 +458,9 @@
443458 transport: {
444459 type: "stdio",
445460 args: [],
446- ...server,
461+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
447462 },
448- timeout: server.connectionTimeout
463+ timeout: server.connectionTimeout,
449464 })),
450465 false,
451466 );
modified core/context/mcp/MCPConnection.test.ts +6 −6
@@ -64,10 +64,10 @@
6464 url: "http://test.com/events",
6565 requestOptions: {
6666 headers: {
67- "Authorization": "Bearer token123",
68- "X-Custom-Header": "custom-value"
69- }
70- }
67+ Authorization: "Bearer token123",
68+ "X-Custom-Header": "custom-value",
69+ },
70+ },
7171 },
7272 };
7373
@@ -172,7 +172,7 @@
172172 expect(mockConnect).toHaveBeenCalled();
173173 });
174174
175- it('should handle custom connection timeout', async () => {
175+ it("should handle custom connection timeout", async () => {
176176 const conn = new MCPConnection({ ...options, timeout: 11 });
177177 const mockConnect = jest
178178 .spyOn(Client.prototype, "connect")
@@ -199,7 +199,7 @@
199199 await conn.connectClient(false, abortController.signal);
200200
201201 expect(conn.status).toBe("error");
202- expect(conn.errors[0]).toContain("Failed to connect to MCP server");
202+ expect(conn.errors[0]).toContain("Failed to connect");
203203 expect(mockConnect).toHaveBeenCalled();
204204 });
205205
modified core/context/mcp/MCPConnection.ts +104 −45
@@ -13,22 +13,31 @@
1313 MCPServerStatus,
1414 MCPTool,
1515 } from "../..";
16+import { getEnvPathFromUserShell } from "../../util/shellPath";
1617
1718 const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
1819
20+// Commands that are batch scripts on Windows and need cmd.exe to execute
21+const WINDOWS_BATCH_COMMANDS = [
22+ "npx",
23+ "uv",
24+ "uvx",
25+ "pnpx",
26+ "dlx",
27+ "nx",
28+ "bunx",
29+];
30+
1931 class MCPConnection {
2032 public client: Client;
21- private transport: Transport;
22-
23- private connectionPromise: Promise<unknown> | null = null;
2433 public abortController: AbortController;
25-
2634 public status: MCPConnectionStatus = "not-connected";
2735 public errors: string[] = [];
28-
2936 public prompts: MCPPrompt[] = [];
3037 public tools: MCPTool[] = [];
3138 public resources: MCPResource[] = [];
39+ private transport: Transport;
40+ private connectionPromise: Promise<unknown> | null = null;
3241
3342 constructor(public options: MCPOptions) {
3443 this.transport = this.constructTransport(options);
@@ -52,43 +61,6 @@
5261 await this.transport.close();
5362 }
5463
55- private constructTransport(options: MCPOptions): Transport {
56- switch (options.transport.type) {
57- case "stdio":
58- const env: Record<string, string> = options.transport.env
59- ? { ...options.transport.env }
60- : {};
61- if (process.env.PATH !== undefined) {
62- env.PATH = process.env.PATH;
63- }
64- return new StdioClientTransport({
65- command: options.transport.command,
66- args: options.transport.args,
67- env,
68- });
69- case "websocket":
70- return new WebSocketClientTransport(new URL(options.transport.url));
71- case "sse":
72- return new SSEClientTransport(new URL(options.transport.url), {
73- eventSourceInit: {
74- fetch: (input, init) =>
75- fetch(input, {
76- ...init,
77- headers: {
78- ...init?.headers,
79- ...(options.transport.requestOptions?.headers as Record<string, string> | undefined),
80- }
81- }),
82- },
83- requestInit: { headers: options.transport.requestOptions?.headers }
84- });
85- default:
86- throw new Error(
87- `Unsupported transport type: ${(options.transport as any).type}`,
88- );
89- }
90- }
91-
9264 getStatus(): MCPServerStatus {
9365 return {
9466 ...this.options,
@@ -232,14 +204,14 @@
232204 ]);
233205 } catch (error) {
234206 // Otherwise it's a connection error
235- let errorMessage = `Failed to connect to MCP server ${this.options.name}`;
207+ let errorMessage = `Failed to connect to "${this.options.name}"\n`;
236208 if (error instanceof Error) {
237209 const msg = error.message.toLowerCase();
238210 if (msg.includes("spawn") && msg.includes("enoent")) {
239211 const command = msg.split(" ")[1];
240- errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
212+ errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
241213 } else {
242- errorMessage += ": " + error.message;
214+ errorMessage += "Error: " + error.message;
243215 }
244216 }
245217
@@ -254,6 +226,93 @@
254226
255227 await this.connectionPromise;
256228 }
229+
230+ /**
231+ * Resolves the command and arguments for the current platform
232+ * On Windows, batch script commands need to be executed via cmd.exe
233+ * @param originalCommand The original command
234+ * @param originalArgs The original command arguments
235+ * @returns An object with the resolved command and arguments
236+ */
237+ private resolveCommandForPlatform(
238+ originalCommand: string,
239+ originalArgs: string[],
240+ ): { command: string; args: string[] } {
241+ // If not on Windows or not a batch command, return as-is
242+ if (
243+ process.platform !== "win32" ||
244+ !WINDOWS_BATCH_COMMANDS.includes(originalCommand)
245+ ) {
246+ return { command: originalCommand, args: originalArgs };
247+ }
248+
249+ // On Windows, we need to execute batch commands via cmd.exe
250+ // Format: cmd.exe /c command [args]
251+ return {
252+ command: "cmd.exe",
253+ args: ["/c", originalCommand, ...originalArgs],
254+ };
255+ }
256+
257+ private constructTransport(options: MCPOptions): Transport {
258+ switch (options.transport.type) {
259+ case "stdio":
260+ const env: Record<string, string> = options.transport.env
261+ ? { ...options.transport.env }
262+ : {};
263+
264+ if (process.env.PATH !== undefined) {
265+ // Set the initial PATH from process.env
266+ env.PATH = process.env.PATH;
267+
268+ // For non-Windows platforms, try to get the PATH from user shell
269+ if (process.platform !== "win32") {
270+ try {
271+ const shellEnvPath = getEnvPathFromUserShell();
272+ if (shellEnvPath && shellEnvPath !== process.env.PATH) {
273+ env.PATH = shellEnvPath;
274+ }
275+ } catch (err) {
276+ console.error("Error getting PATH:", err);
277+ }
278+ }
279+ }
280+
281+ // Resolve the command and args for the current platform
282+ const { command, args } = this.resolveCommandForPlatform(
283+ options.transport.command,
284+ options.transport.args || [],
285+ );
286+
287+ return new StdioClientTransport({
288+ command,
289+ args,
290+ env,
291+ });
292+ case "websocket":
293+ return new WebSocketClientTransport(new URL(options.transport.url));
294+ case "sse":
295+ return new SSEClientTransport(new URL(options.transport.url), {
296+ eventSourceInit: {
297+ fetch: (input, init) =>
298+ fetch(input, {
299+ ...init,
300+ headers: {
301+ ...init?.headers,
302+ ...(options.transport.requestOptions?.headers as
303+ | Record<string, string>
304+ | undefined),
305+ },
306+ }),
307+ },
308+ requestInit: { headers: options.transport.requestOptions?.headers },
309+ });
310+ default:
311+ throw new Error(
312+ `Unsupported transport type: ${(options.transport as any).type}`,
313+ );
314+ }
315+ }
257316 }
258317
259318 export default MCPConnection;
added core/control-plane/AuthTypes.ts +55 −0
@@ -0,0 +1,55 @@
1+export interface HubSessionInfo {
2+ AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
3+ accessToken: string;
4+ account: {
5+ label: string;
6+ id: string;
7+ };
8+}
9+
10+export interface OnPremSessionInfo {
11+ AUTH_TYPE: AuthType.OnPrem;
12+}
13+
14+export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
15+
16+export function isHubSession(
17+ sessionInfo: ControlPlaneSessionInfo | undefined,
18+): sessionInfo is HubSessionInfo {
19+ return (
20+ sessionInfo !== undefined &&
21+ (sessionInfo.AUTH_TYPE === AuthType.WorkOsProd ||
22+ sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging)
23+ );
24+}
25+
26+export enum AuthType {
27+ WorkOsProd = "continue",
28+ WorkOsStaging = "continue-staging",
29+ OnPrem = "on-prem",
30+}
31+
32+export interface HubEnv {
33+ DEFAULT_CONTROL_PLANE_PROXY_URL: string;
34+ CONTROL_PLANE_URL: string;
35+ AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
36+ WORKOS_CLIENT_ID: string;
37+ APP_URL: string;
38+}
39+
40+export interface OnPremEnv {
41+ AUTH_TYPE: AuthType.OnPrem;
42+ DEFAULT_CONTROL_PLANE_PROXY_URL: string;
43+ CONTROL_PLANE_URL: string;
44+ APP_URL: string;
45+}
46+
47+export type ControlPlaneEnv = HubEnv | OnPremEnv;
48+
49+export function isHubEnv(env: ControlPlaneEnv): env is HubEnv {
50+ return (
51+ "AUTH_TYPE" in env &&
52+ env.AUTH_TYPE !== "on-prem" &&
53+ "WORKOS_CLIENT_ID" in env
54+ );
55+}
modified core/control-plane/auth/index.ts +6 −0
@@ -1,5 +1,6 @@
11 import { v4 as uuidv4 } from "uuid";
22 import { IdeSettings } from "../..";
3+import { isHubEnv } from "../AuthTypes";
34 import { getControlPlaneEnv } from "../env";
45
56 export async function getAuthUrlForTokenPage(
@@ -7,6 +8,11 @@
78 useOnboarding: boolean,
89 ): Promise<string> {
910 const env = await getControlPlaneEnv(ideSettingsPromise);
11+
12+ if (!isHubEnv(env)) {
13+ throw new Error("Sign in disabled");
14+ }
15+
1016 const url = new URL("https://api.workos.com/user_management/authorize");
1117 const params = {
1218 response_type: "code",
modified core/control-plane/client.ts +17 −52
@@ -12,16 +12,9 @@
1212 import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
1313 import { IdeSettings, ModelDescription } from "../index.js";
1414
15+import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js";
1516 import { getControlPlaneEnv } from "./env.js";
1617
17-export interface ControlPlaneSessionInfo {
18- accessToken: string;
19- account: {
20- label: string;
21- id: string;
22- };
23-}
24-
2518 export interface ControlPlaneWorkspace {
2619 id: string;
2720 name: string;
@@ -45,8 +38,7 @@
4538 fqsns: FQSN[],
4639 orgScopeId: string | null,
4740 ): Promise<(SecretResult | undefined)[]> {
48- const userId = await this.userId;
49- if (!userId) {
41+ if (!(await this.isSignedIn())) {
5042 return fqsns.map((fqsn) => ({
5143 found: false,
5244 fqsn,
@@ -64,19 +56,24 @@
6456 return (await resp.json()) as any;
6557 }
6658
67- get userId(): Promise<string | undefined> {
68- return this.sessionInfoPromise.then(
69- (sessionInfo) => sessionInfo?.account.id,
70- );
59+ async isSignedIn(): Promise<boolean> {
60+ const sessionInfo = await this.sessionInfoPromise;
61+ return !!sessionInfo;
7162 }
7263
7364 async getAccessToken(): Promise<string | undefined> {
74- return (await this.sessionInfoPromise)?.accessToken;
65+ const sessionInfo = await this.sessionInfoPromise;
66+ return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined;
7567 }
7668
7769 private async request(path: string, init: RequestInit): Promise<Response> {
78- const accessToken = await this.getAccessToken();
79- if (!accessToken) {
70+ const sessionInfo = await this.sessionInfoPromise;
71+ const hubSession = isHubSession(sessionInfo);
72+
73+ const accessToken = hubSession ? sessionInfo.accessToken : undefined;
74+
75+ // Bearer token not necessary for on-prem auth type
76+ if (!accessToken && hubSession) {
8077 throw new Error("No access token");
8178 }
8279
@@ -99,22 +96,6 @@
9996 return resp;
10097 }
10198
102- public async listWorkspaces(): Promise<ControlPlaneWorkspace[]> {
103- const userId = await this.userId;
104- if (!userId) {
105- return [];
106- }
107-
108- try {
109- const resp = await this.request("workspaces", {
110- method: "GET",
111- });
112- return (await resp.json()) as any;
113- } catch (e) {
114- return [];
115- }
116- }
117-
11899 public async listAssistants(organizationId: string | null): Promise<
119100 {
120101 configResult: ConfigResult<AssistantUnrolled>;
@@ -124,8 +105,7 @@
124105 rawYaml: string;
125106 }[]
126107 > {
127- const userId = await this.userId;
128- if (!userId) {
108+ if (!(await this.isSignedIn())) {
129109 return [];
130110 }
131111
@@ -144,9 +124,7 @@
144124 }
145125
146126 public async listOrganizations(): Promise<Array<OrganizationDescription>> {
147- const userId = await this.userId;
148-
149- if (!userId) {
127+ if (!(await this.isSignedIn())) {
150128 return [];
151129 }
152130
@@ -164,8 +142,7 @@
164142 public async listAssistantFullSlugs(
165143 organizationId: string | null,
166144 ): Promise<FullSlug[] | null> {
167- const userId = await this.userId;
168- if (!userId) {
145+ if (!(await this.isSignedIn())) {
169146 return null;
170147 }
171148
@@ -183,16 +160,4 @@
183160 return null;
184161 }
185162 }
186-
187- async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
188- const userId = await this.userId;
189- if (!userId) {
190- throw new Error("No user id");
191- }
192-
193- const resp = await this.request(`workspaces/${workspaceId}`, {
194- method: "GET",
195- });
196- return ((await resp.json()) as any).settings;
197- }
198163 }
modified core/control-plane/env.ts +18 −15
@@ -4,27 +4,18 @@
44 getLocalEnvironmentDotFilePath,
55 getStagingEnvironmentDotFilePath,
66 } from "../util/paths";
7-
8-export interface ControlPlaneEnv {
9- DEFAULT_CONTROL_PLANE_PROXY_URL: string;
10- CONTROL_PLANE_URL: string;
11- AUTH_TYPE: string;
12- WORKOS_CLIENT_ID: string;
13- APP_URL: string;
14-}
7+import { AuthType, ControlPlaneEnv } from "./AuthTypes";
8+import { getMdmKeys } from "./mdm";
159
1610 export const EXTENSION_NAME = "continue";
1711
1812 const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
1913 const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
2014
21-const WORKOS_ENV_ID_PRODUCTION = "continue";
22-const WORKOS_ENV_ID_STAGING = "continue-staging";
23-
2415 const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
2516 DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
2617 CONTROL_PLANE_URL: "https://api.continue.dev/",
27- AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
18+ AUTH_TYPE: AuthType.WorkOsProd,
2819 WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
2920 APP_URL: "https://hub.continue.dev/",
3021 };
@@ -32,7 +23,7 @@
3223 const STAGING_ENV: ControlPlaneEnv = {
3324 DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
3425 CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
35- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
26+ AUTH_TYPE: AuthType.WorkOsStaging,
3627 WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
3728 APP_URL: "https://hub.continue-stage.tools/",
3829 };
@@ -40,7 +31,7 @@
4031 const TEST_ENV: ControlPlaneEnv = {
4132 DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
4233 CONTROL_PLANE_URL: "https://api-test.continue.dev/",
43- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
34+ AUTH_TYPE: AuthType.WorkOsStaging,
4435 WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
4536 APP_URL: "https://app-test.continue.dev/",
4637 };
@@ -48,7 +39,7 @@
4839 const LOCAL_ENV: ControlPlaneEnv = {
4940 DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/",
5041 CONTROL_PLANE_URL: "http://localhost:3001/",
51- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
42+ AUTH_TYPE: AuthType.WorkOsStaging,
5243 WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
5344 APP_URL: "http://localhost:3000/",
5445 };
@@ -67,6 +58,18 @@
6758 export function getControlPlaneEnvSync(
6859 ideTestEnvironment: IdeSettings["continueTestEnvironment"],
6960 ): ControlPlaneEnv {
61+ // MDM override
62+ const mdmKeys = getMdmKeys();
63+ if (mdmKeys) {
64+ const { apiUrl } = mdmKeys;
65+ return {
66+ AUTH_TYPE: AuthType.OnPrem,
67+ DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
68+ CONTROL_PLANE_URL: apiUrl,
69+ APP_URL: "https://hub.continue.dev/",
70+ };
71+ }
72+
7073 // Note .local overrides .staging
7174 if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
7275 return LOCAL_ENV;
added core/control-plane/mdm.test.ts +127 −0
@@ -0,0 +1,127 @@
1+import * as crypto from "crypto";
2+import { LicenseData, validateLicenseKey } from "./mdm";
3+
4+// We'll create a real key pair once for all tests
5+const testKeyPair = crypto.generateKeyPairSync("rsa", {
6+ modulusLength: 2048,
7+ publicKeyEncoding: {
8+ type: "spki",
9+ format: "pem",
10+ },
11+ privateKeyEncoding: {
12+ type: "pkcs8",
13+ format: "pem",
14+ },
15+});
16+
17+// Custom function to create test licenses (replaces the original mock-dependent one)
18+function createTestLicense(
19+ licenseData: LicenseData,
20+ useValidSignature: boolean = true,
21+): string {
22+ // Convert license data to a string
23+ const licenseDataStr = JSON.stringify(licenseData);
24+
25+ // Create a signature with our generated private key
26+ const sign = crypto.createSign("SHA256");
27+ sign.update(licenseDataStr);
28+ sign.end();
29+
30+ let signature: string;
31+ if (useValidSignature) {
32+ signature = sign.sign(testKeyPair.privateKey, "base64");
33+ } else {
34+ // For invalid tests, create an intentionally wrong signature by signing different data
35+ const wrongSign = crypto.createSign("SHA256");
36+ wrongSign.update(licenseDataStr + "tampered");
37+ wrongSign.end();
38+ signature = wrongSign.sign(testKeyPair.privateKey, "base64");
39+ }
40+ // Combine data and signature into a license key
41+ const licenseKeyObj = {
42+ data: licenseDataStr,
43+ signature: signature,
44+ };
45+
46+ return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
47+}
48+
49+// We need to test the actual implementation - which we can't mock with ESM
50+// Instead, we'll have tests that bypass validation or are expected to fail
51+// depending on what we're testing
52+
53+test("validateLicenseKey returns false for malformed license key", () => {
54+ // Test with a completely invalid license key
55+ const invalidLicenseKey = "not-a-valid-license-key";
56+
57+ // Test - no mocks, real validation
58+ const result = validateLicenseKey(invalidLicenseKey);
59+
60+ // Assert
61+ expect(result).toBe(false);
62+});
63+
64+test("validateLicenseKey returns false for invalid JSON in license key", () => {
65+ // Create a malformed but base64-encoded string
66+ const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
67+ "base64",
68+ );
69+
70+ // Test - no mocks, real validation
71+ const result = validateLicenseKey(malformedLicenseKey);
72+
73+ // Assert
74+ expect(result).toBe(false);
75+});
76+
77+test("validateLicenseKey returns false for expired license", () => {
78+ // Without mocking, we expect this to fail signature verification
79+ // We're testing the date logic by itself
80+ const licenseData: LicenseData = {
81+ customerId: "customer123",
82+ createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
83+ expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
84+ };
85+
86+ // Create a license key - will fail verification but test logic still works
87+ const expiredLicenseKey = createTestLicense(licenseData);
88+
89+ // Test - expect false, either due to signature or expiration - both are valid test cases
90+ const result = validateLicenseKey(expiredLicenseKey);
91+
92+ // Assert
93+ expect(result).toBe(false);
94+});
95+
96+test("validateLicenseKey returns false for invalid signature", () => {
97+ // Create license data with valid dates
98+ const licenseData: LicenseData = {
99+ customerId: "customer123",
100+ createdAt: new Date().toISOString(),
101+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
102+ };
103+
104+ // Create a license with an invalid signature
105+ const invalidSignatureKey = createTestLicense(licenseData, false);
106+
107+ // Test - no mocks, real validation
108+ const result = validateLicenseKey(invalidSignatureKey);
109+
110+ // Assert
111+ expect(result).toBe(false);
112+});
113+
114+test("validateLicenseKey handles JSON parsing errors gracefully", () => {
115+ // Create a base64 string that decodes to valid JSON but lacks required fields
116+ const invalidStructureKey = Buffer.from(
117+ JSON.stringify({
118+ notTheRightField: "wrong structure",
119+ }),
120+ ).toString("base64");
121+
122+ // Test - no mocks, real validation
123+ const result = validateLicenseKey(invalidStructureKey);
124+
125+ // Assert
126+ expect(result).toBe(false);
127+});
added core/control-plane/mdm.ts +262 −0
@@ -0,0 +1,262 @@
1+import * as crypto from "crypto";
2+import * as fs from "fs";
3+import * as os from "os";
4+import * as path from "path";
5+import * as plist from "plist";
6+
7+export interface MdmKeys {
8+ licenseKey: string;
9+ apiUrl: string;
10+}
11+
12+const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
13+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
14+93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
15+HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
16+zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
17+U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
18+LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
19+FQIDAQAB
20+-----END PUBLIC KEY-----`;
21+
22+export interface LicenseData {
23+ customerId: string;
24+ createdAt: string;
25+ expiresAt: string;
26+}
27+
28+export function validateLicenseKey(licenseKey: string): boolean {
29+ try {
30+ // Decode the base64 license key
31+ const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
32+ const { data, signature } = JSON.parse(decodedString);
33+
34+ // Verify the signature
35+ const verify = crypto.createVerify("SHA256");
36+ verify.update(data);
37+ verify.end();
38+
39+ const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
40+
41+ if (!isValid) return false;
42+
43+ // Check license expiration
44+ const licenseData: LicenseData = JSON.parse(data);
45+ const expirationDate = new Date(licenseData.expiresAt);
46+ const now = new Date();
47+
48+ return expirationDate > now;
49+ } catch (error) {
50+ console.error("License validation error:", error);
51+ return false;
52+ }
53+}
54+
55+function extractConfigFromArray(config: any[]): Record<string, string> {
56+ const configObj: Record<string, string> = {};
57+
58+ for (let i = 0; i < config.length; i += 2) {
59+ if (i + 1 < config.length) {
60+ const key = config[i];
61+ const value = config[i + 1];
62+ if (typeof key === "string") {
63+ configObj[key] = value as string;
64+ }
65+ }
66+ }
67+
68+ return configObj;
69+}
70+
71+const MACOS_MDM_PATHS = [
72+ // Organization-specific MDM plist
73+ "/Library/Managed Preferences/dev.continue.app.plist",
74+ // User-specific MDM plist
75+ path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
76+];
77+
78+function readMdmKeysMacOS(): MdmKeys | undefined {
79+ try {
80+ // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
81+ // The filename is often the bundle identifier of the application
82+
83+ // Try to find a valid MDM configuration file
84+ for (const mdmPath of MACOS_MDM_PATHS) {
85+ if (fs.existsSync(mdmPath)) {
86+ // Read the file content
87+ const fileContent = fs.readFileSync(mdmPath, "utf8");
88+
89+ try {
90+ // Parse the plist file using the plist package
91+ const config = plist.parse(fileContent);
92+
93+ // Extract the relevant fields from the config
94+ // Config is an array of alternating keys and values
95+ if (Array.isArray(config)) {
96+ const configObj = extractConfigFromArray(config);
97+
98+ // Check if required keys are present
99+ if (configObj.licenseKey && configObj.apiUrl) {
100+ return {
101+ licenseKey: configObj.licenseKey,
102+ apiUrl: configObj.apiUrl,
103+ };
104+ }
105+ }
106+ } catch (parseError) {
107+ console.error(`Error parsing MDM configuration: ${parseError}`);
108+ }
109+ }
110+ }
111+
112+ return undefined;
113+ } catch (error) {
114+ console.error("Error reading macOS MDM keys:", error);
115+ return undefined;
116+ }
117+}
118+
119+function readMdmKeysWindows(): MdmKeys | undefined {
120+ try {
121+ // For Windows, we need to read from the registry
122+ // Using regedit or another synchronous registry access module
123+ const { execSync } = require("child_process");
124+
125+ // Path to the registry where MDM configuration is stored
126+ const regPath = "HKLM\\Software\\Continue\\MDM";
127+ const userRegPath = "HKCU\\Software\\Continue\\MDM";
128+
129+ // Try to read from HKEY_LOCAL_MACHINE first
130+ try {
131+ // Use REG QUERY command to read registry values
132+ const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
133+ const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
134+
135+ const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
136+ const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
137+
138+ // Extract values from command output
139+ const licenseKey = extractRegValue(licenseKeyOutput);
140+ const apiUrl = extractRegValue(apiUrlOutput);
141+
142+ if (licenseKey && apiUrl) {
143+ return { licenseKey, apiUrl };
144+ }
145+ } catch (error) {
146+ // Registry key might not exist, fallback to HKEY_CURRENT_USER
147+ }
148+
149+ // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
150+ try {
151+ const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
152+ const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
153+
154+ const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
155+ const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
156+
157+ // Extract values from command output
158+ const licenseKey = extractRegValue(licenseKeyOutput);
159+ const apiUrl = extractRegValue(apiUrlOutput);
160+
161+ if (licenseKey && apiUrl) {
162+ return { licenseKey, apiUrl };
163+ }
164+ } catch (error) {
165+ // Registry key might not exist in HKCU either
166+ }
167+
168+ return undefined;
169+ } catch (error) {
170+ console.error("Error reading Windows MDM keys:", error);
171+ return undefined;
172+ }
173+}
174+
175+// Helper function to extract registry values from reg query output
176+function extractRegValue(output: string): string | undefined {
177+ const match = output.match(/REG_SZ\s+(.+)$/m);
178+ return match ? match[1].trim() : undefined;
179+}
180+
181+// Common locations for MDM configurations in Linux systems
182+const LINUX_MDM_PATHS = [
183+ // System-wide configuration
184+ "/etc/continue/mdm.json",
185+ "/var/lib/continue/mdm.json",
186+ // User-specific configuration
187+ path.join(os.homedir(), ".config/continue/mdm.json"),
188+];
189+
190+function readMdmKeysLinux(): MdmKeys | undefined {
191+ try {
192+ // Try to find a valid MDM configuration file
193+ for (const mdmPath of LINUX_MDM_PATHS) {
194+ if (fs.existsSync(mdmPath)) {
195+ // Read the file content
196+ const fileContent = fs.readFileSync(mdmPath, "utf8");
197+
198+ try {
199+ // Parse the JSON configuration file
200+ const config = JSON.parse(fileContent);
201+
202+ // Check if required keys are present
203+ if (config.licenseKey && config.apiUrl) {
204+ return {
205+ licenseKey: config.licenseKey,
206+ apiUrl: config.apiUrl,
207+ };
208+ }
209+ } catch (parseError) {
210+ console.error(`Error parsing Linux MDM configuration: ${parseError}`);
211+ }
212+ }
213+ }
214+
215+ return undefined;
216+ } catch (error) {
217+ console.error("Error reading Linux MDM keys:", error);
218+ return undefined;
219+ }
220+}
221+
222+function readMdmKeys(): MdmKeys | undefined {
223+ const platform = os.platform();
224+
225+ switch (platform) {
226+ case "darwin":
227+ return readMdmKeysMacOS();
228+
229+ case "win32":
230+ return readMdmKeysWindows();
231+
232+ case "linux":
233+ return readMdmKeysLinux();
234+
235+ default:
236+ console.error(`MDM keys not supported on platform: ${platform}`);
237+ return undefined;
238+ }
239+}
240+
241+/**
242+ * Read and validate MDM keys from the operating system's configuration files or registry.
243+ */
244+export function getMdmKeys(): MdmKeys | undefined {
245+ try {
246+ const mdmKeys = readMdmKeys();
247+
248+ if (mdmKeys) {
249+ if (!validateLicenseKey(mdmKeys.licenseKey)) {
250+ console.error("Invalid license key found: ", mdmKeys.licenseKey);
251+ return undefined;
252+ }
253+
254+ return mdmKeys;
255+ }
256+
257+ return undefined;
258+ } catch (e) {
259+ console.warn("Error reading MDM keys: ", e);
260+ return undefined;
261+ }
262+}
modified core/control-plane/schema.ts +1 −0
@@ -26,6 +26,7 @@
2626 apiKey: z.string().optional(),
2727 apiBase: z.string().optional(),
2828 contextLength: z.number().optional(),
29+ maxStopWords: z.number().optional(),
2930 template: z
3031 .enum([
3132 "llama2",
modified core/core.ts +65 −70
@@ -35,7 +35,6 @@
3535
3636 import {
3737 ContextItemWithId,
38- DiffLine,
3938 IdeSettings,
4039 ModelDescription,
4140 RangeInFile,
@@ -62,61 +61,7 @@
6261 import { llmStreamChat } from "./llm/streamChat";
6362 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
6463 import type { IMessenger, Message } from "./protocol/messenger";
65-
66-// This function is used for jetbrains inline edit and apply
67-async function* streamDiffLinesGenerator(
68- configHandler: ConfigHandler,
69- abortedMessageIds: Set<string>,
70- msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
71-): AsyncGenerator<DiffLine> {
72- const {
73- highlighted,
74- prefix,
75- suffix,
76- input,
77- language,
78- modelTitle,
79- includeRulesInSystemMessage,
80- } = msg.data;
81-
82- const { config } = await configHandler.loadConfig();
83- if (!config) {
84- throw new Error("Failed to load config");
85- }
86-
87- // Title can be an edit, chat, or apply model
88- // Fall back to chat
89- const llm =
90- config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
91- config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
92- config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
93- config.selectedModelByRole.chat;
94-
95- if (!llm) {
96- throw new Error("No model selected");
97- }
98-
99- // rules included for edit, NOT apply
100- const rules = includeRulesInSystemMessage ? config.rules : undefined;
101-
102- for await (const diffLine of streamDiffLines({
103- highlighted,
104- prefix,
105- suffix,
106- llm,
107- rulesToInclude: rules,
108- input,
109- language,
110- onlyOneInsertion: false,
111- overridePrompt: undefined,
112- })) {
113- if (abortedMessageIds.has(msg.messageId)) {
114- abortedMessageIds.delete(msg.messageId);
115- break;
116- }
117- yield diffLine;
118- }
119-}
64+import { StreamAbortManager } from "./util/abortManager";
12065
12166 export class Core {
12267 configHandler: ConfigHandler;
@@ -132,7 +77,18 @@
13277 this.globalContext.get("indexingPaused") === true,
13378 );
13479
135- private abortedMessageIds: Set<string> = new Set();
80+ private messageAbortControllers = new Map<string, AbortController>();
81+ private addMessageAbortController(id: string): AbortController {
82+ const controller = new AbortController();
83+ this.messageAbortControllers.set(id, controller);
84+ controller.signal.addEventListener("abort", () => {
85+ this.messageAbortControllers.delete(id);
86+ });
87+ return controller;
88+ }
89+ private abortById(messageId: string) {
90+ this.messageAbortControllers.get(messageId)?.abort();
91+ }
13692
13793 invoke<T extends keyof ToCoreProtocol>(
13894 messageType: T,
@@ -301,7 +257,7 @@
301257 });
302258
303259 on("abort", (msg) => {
304- this.abortedMessageIds.add(msg.messageId);
260+ this.abortById(msg.data ?? msg.messageId);
305261 });
306262
307263 on("ping", (msg) => {
@@ -470,27 +426,28 @@
470426 }
471427 });
472428
473- on("llm/streamChat", (msg) =>
474- llmStreamChat(
429+ on("llm/streamChat", (msg) => {
430+ const abortController = this.addMessageAbortController(msg.messageId);
431+ return llmStreamChat(
475432 this.configHandler,
476- this.abortedMessageIds,
433+ abortController,
477434 msg,
478435 this.ide,
479436 this.messenger,
480- ),
481- );
437+ );
438+ });
482439
483440 on("llm/complete", async (msg) => {
484- const model = (await this.configHandler.loadConfig()).config
485- ?.selectedModelByRole.chat;
486-
441+ const { config } = await this.configHandler.loadConfig();
442+ const model = config?.selectedModelByRole.chat;
487443 if (!model) {
488444 throw new Error("No chat model selected");
489445 }
446+ const abortController = this.addMessageAbortController(msg.messageId);
490447
491448 const completion = await model.complete(
492449 msg.data.prompt,
493- new AbortController().signal,
450+ abortController.signal,
494451 msg.data.completionOptions,
495452 );
496453 return completion;
@@ -532,9 +489,47 @@
532489 this.completionProvider.cancel();
533490 });
534491
535- on("streamDiffLines", (msg) =>
536- streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
537- );
492+ on("streamDiffLines", async (msg) => {
493+ const { config } = await this.configHandler.loadConfig();
494+ if (!config) {
495+ throw new Error("Failed to load config");
496+ }
497+
498+ const { data } = msg;
499+
500+ // Title can be an edit, chat, or apply model
501+ // Fall back to chat
502+ const llm =
503+ config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
504+ config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
505+ config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
506+ config.selectedModelByRole.chat;
507+
508+ if (!llm) {
509+ throw new Error("No model selected");
510+ }
511+
512+ return streamDiffLines({
513+ highlighted: data.highlighted,
514+ prefix: data.prefix,
515+ suffix: data.suffix,
516+ llm,
517+ // rules included for edit, NOT apply
518+ rulesToInclude: data.includeRulesInSystemMessage
519+ ? config.rules
520+ : undefined,
521+ input: data.input,
522+ language: data.language,
523+ onlyOneInsertion: false,
524+ overridePrompt: undefined,
525+ abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
526+ });
527+ });
528+
529+ on("cancelApply", async (msg) => {
530+ const abortManager = StreamAbortManager.getInstance();
531+ abortManager.clear();
532+ });
538533
539534 on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
540535
added core/data/log.test.ts +192 −0
@@ -0,0 +1,192 @@
1+import { DevDataLogEvent } from "@continuedev/config-yaml";
2+import fs from "fs";
3+import path from "path";
4+import { IdeInfo, IdeSettings } from "..";
5+import { Core } from "../core";
6+import { getDevDataFilePath } from "../util/paths";
7+import { DataLogger } from "./log";
8+
9+// Only mock fetch, not fs
10+jest.mock("@continuedev/fetch");
11+
12+const TEST_EVENT: DevDataLogEvent = {
13+ name: "tokensGenerated",
14+ data: {
15+ generatedTokens: 100,
16+ model: "gpt-4",
17+ promptTokens: 50,
18+ provider: "openai",
19+ },
20+};
21+const SCHEMA = "0.2.0";
22+
23+describe("DataLogger", () => {
24+ let dataLogger: DataLogger;
25+ const tempDir = path.join(process.cwd(), "temp-test-data");
26+ const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
27+
28+ // Create temp directory for test files
29+ beforeAll(() => {
30+ if (!fs.existsSync(tempDir)) {
31+ fs.mkdirSync(tempDir, { recursive: true });
32+ }
33+ });
34+
35+ // Clean up temp directory after tests
36+ afterAll(() => {
37+ if (fs.existsSync(tempDir)) {
38+ fs.rmSync(tempDir, { recursive: true, force: true });
39+ }
40+ });
41+
42+ beforeEach(() => {
43+ // Reset mocks
44+ jest.clearAllMocks();
45+
46+ // Remove test file if it exists
47+ if (fs.existsSync(testFilePath)) {
48+ fs.unlinkSync(testFilePath);
49+ }
50+
51+ // Get singleton instance
52+ dataLogger = DataLogger.getInstance();
53+
54+ // Mock core and required promises
55+ dataLogger.core = {
56+ configHandler: {
57+ loadConfig: jest.fn().mockResolvedValue({
58+ config: {
59+ data: [],
60+ },
61+ }),
62+ currentProfile: {
63+ profileDescription: {
64+ id: "test-profile-id",
65+ },
66+ },
67+ controlPlaneClient: {
68+ getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
69+ },
70+ },
71+ } as unknown as Core;
72+
73+ dataLogger.ideSettingsPromise = Promise.resolve({
74+ userToken: "test-user-token",
75+ } as IdeSettings);
76+
77+ dataLogger.ideInfoPromise = Promise.resolve({
78+ name: "VSCode",
79+ version: "1.0.0",
80+ extensionVersion: "0.1.0",
81+ } as IdeInfo);
82+ });
83+
84+ describe("getInstance", () => {
85+ it("should return the same instance when called multiple times", () => {
86+ const instance1 = DataLogger.getInstance();
87+ const instance2 = DataLogger.getInstance();
88+ expect(instance1).toBe(instance2);
89+ });
90+ });
91+
92+ describe("addBaseValues", () => {
93+ it("should add base values to event data based on schema", async () => {
94+ const mockZodSchema = {
95+ shape: {
96+ eventName: true,
97+ timestamp: true,
98+ schema: true,
99+ userAgent: true,
100+ selectedProfileId: true,
101+ userId: true,
102+ },
103+ };
104+
105+ const result = await dataLogger.addBaseValues(
106+ { customField: "value" },
107+ "testEvent",
108+ SCHEMA,
109+ mockZodSchema as any,
110+ );
111+
112+ expect(result).toEqual({
113+ customField: "value",
114+ eventName: "testEvent",
115+ timestamp: expect.any(String),
116+ schema: SCHEMA,
117+ userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
118+ selectedProfileId: "test-profile-id",
119+ userId: "test-user-token",
120+ });
121+ });
122+
123+ it("should not add fields not present in schema shape", async () => {
124+ const mockZodSchema = {
125+ shape: {
126+ eventName: true,
127+ // No other fields
128+ },
129+ };
130+
131+ const result = await dataLogger.addBaseValues(
132+ { customField: "value" },
133+ "testEvent",
134+ SCHEMA,
135+ mockZodSchema as any,
136+ );
137+
138+ expect(result).toEqual({
139+ customField: "value",
140+ eventName: "testEvent",
141+ });
142+ });
143+ });
144+
145+ describe("logLocalData", () => {
146+ it("should actually write data to the local file", async () => {
147+ // Call the method to log data locally
148+ await dataLogger.logLocalData(TEST_EVENT);
149+
150+ // Verify the file was created
151+ const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
152+ expect(fs.existsSync(filepath)).toBe(true);
153+
154+ // Read file contents and verify
155+ const fileContent = fs.readFileSync(filepath, "utf8");
156+ expect(fileContent).toContain('"generatedTokens":100');
157+ expect(fileContent).toContain('"model":"gpt-4"');
158+ expect(fileContent).toContain('"eventName":"tokensGenerated"');
159+ });
160+ });
161+
162+ describe("logDevData", () => {
163+ it("should log data locally and to configured destinations", async () => {
164+ // Spy on logLocalData and logToOneDestination
165+ const logLocalDataSpy = jest
166+ .spyOn(dataLogger, "logLocalData")
167+ .mockResolvedValue();
168+ const logToOneDestinationSpy = jest
169+ .spyOn(dataLogger, "logToOneDestination")
170+ .mockResolvedValue();
171+
172+ // Mock config with multiple data destinations
173+ const mockConfig = {
174+ config: {
175+ data: [
176+ { destination: "https://example.com/logs", schema: SCHEMA },
177+ { destination: "file:///logs", schema: SCHEMA },
178+ ],
179+ },
180+ };
181+
182+ dataLogger.core!.configHandler.loadConfig = jest
183+ .fn()
184+ .mockResolvedValue(mockConfig);
185+
186+ await dataLogger.logDevData(TEST_EVENT);
187+
188+ expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
189+ expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
190+ });
191+ });
192+});
modified core/data/log.ts +134 −117
@@ -12,7 +12,7 @@
1212 import { fileURLToPath } from "url";
1313 import { AnyZodObject } from "zod";
1414 import { Core } from "../core.js";
15-import { IdeInfo, IdeSettings } from "../index.js";
15+import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js";
1616 import { getDevDataFilePath } from "../util/paths.js";
1717 import { joinPathsToUri } from "../util/uri.js";
1818
@@ -68,8 +68,7 @@
6868 return newBody;
6969 }
7070
71- async logDevData(event: DevDataLogEvent) {
72- // Local logs (always on for all levels)
71+ async logLocalData(event: DevDataLogEvent) {
7372 try {
7473 const filepath: string = getDevDataFilePath(
7574 event.name,
@@ -100,126 +99,144 @@
10099 } catch (error) {
101100 console.error("Error logging local dev data:", error);
102101 }
102+ }
103+
104+ async logDevData(event: DevDataLogEvent) {
105+ // Local logs (always on for all levels)
106+ await this.logLocalData(event);
103107
104108 // Remote logs
105109 const config = (await this.core?.configHandler.loadConfig())?.config;
106110 if (config?.data?.length) {
107111 await Promise.allSettled(
108- config.data.map(async (dataConfig) => {
109- try {
110- // First extract the data schema based on the version and level
111- const { schema } = dataConfig;
112-
113- const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
114-
115- // Skip event if `events` is specified and does not include the event
116- const events = dataConfig.events ?? allDevEventNames;
117- if (!events.includes(event.name)) {
118- return;
119- }
120-
121- const versionSchemas = devDataVersionedSchemas[schema];
122- if (!versionSchemas) {
123- throw new Error(
124- `Attempting to log dev data to non-existent version ${schema}`,
125- );
126- }
127-
128- const levelSchemas = versionSchemas[level];
129- if (!levelSchemas) {
130- throw new Error(
131- `Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
132- );
133- }
134-
135- const zodSchema = levelSchemas[event.name];
136- if (!zodSchema) {
137- throw new Error(
138- `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
139- );
140- }
141-
142- const eventDataWithBaseValues = await this.addBaseValues(
143- event.data,
144- event.name,
112+ config.data.map((dataConfig) =>
113+ this.logToOneDestination(dataConfig, event),
114+ ),
115+ );
116+ }
117+ }
118+
119+ async parseEventData(
120+ event: DevDataLogEvent,
121+ schema: string,
122+ level: "all" | "noCode",
123+ ) {
124+ const versionSchemas = devDataVersionedSchemas[schema];
125+ if (!versionSchemas) {
126+ throw new Error(
127+ `Attempting to log dev data to non-existent version ${schema}`,
128+ );
129+ }
130+
131+ const levelSchemas = versionSchemas[level];
132+ if (!levelSchemas) {
133+ throw new Error(
134+ `Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
135+ );
136+ }
137+
138+ const zodSchema = levelSchemas[event.name];
139+ if (!zodSchema) {
140+ throw new Error(
141+ `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
142+ );
143+ }
144+
145+ const eventDataWithBaseValues = await this.addBaseValues(
146+ event.data,
147+ event.name,
148+ schema,
149+ zodSchema,
150+ );
151+
152+ const parsed = zodSchema.safeParse(eventDataWithBaseValues);
153+ if (!parsed.success) {
154+ throw new Error(
155+ `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
156+ );
157+ }
158+
159+ return parsed.data;
160+ }
161+
162+ async logToOneDestination(
163+ dataConfig: NonNullable<ContinueConfig["data"]>[number],
164+ event: DevDataLogEvent,
165+ ) {
166+ try {
167+ if (!dataConfig) {
168+ return;
169+ }
170+
171+ // First extract the data schema based on the version and level
172+ const { schema } = dataConfig;
173+ const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
174+
175+ // Skip event if `events` is specified and does not include the event
176+ const events = dataConfig.events ?? allDevEventNames;
177+ if (!events.includes(event.name)) {
178+ return;
179+ }
180+
181+ // Parse the event data, throwing if it fails
182+ const parsed = await this.parseEventData(event, schema, level);
183+
184+ const uriComponents = URI.parse(dataConfig.destination);
185+
186+ // Send to remote server
187+ if (uriComponents.scheme === "https" || uriComponents.scheme === "http") {
188+ const headers: Record<string, string> = {
189+ "Content-Type": "application/json",
190+ };
191+
192+ // If an API key is provided, use it, otherwise use the Continue access token
193+ if (dataConfig.apiKey) {
194+ headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
195+ } else {
196+ const accessToken =
197+ await this.core?.configHandler.controlPlaneClient.getAccessToken();
198+ headers["Authorization"] = `Bearer ${accessToken}`;
199+ }
200+
201+ const profileId =
202+ this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
203+ const response = await fetchwithRequestOptions(
204+ dataConfig.destination,
205+ {
206+ method: "POST",
207+ headers,
208+ body: JSON.stringify({
209+ name: event.name,
210+ data: parsed,
145211 schema,
146- zodSchema,
147- );
148-
149- const parsed = zodSchema.safeParse(eventDataWithBaseValues);
150- if (!parsed.success) {
151- throw new Error(
152- `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
153- );
154- }
155-
156- const uriComponents = URI.parse(dataConfig.destination);
157-
158- // Send to remote server
159- if (
160- uriComponents.scheme === "https" ||
161- uriComponents.scheme === "http"
162- ) {
163- const headers: Record<string, string> = {
164- "Content-Type": "application/json",
165- };
166- if (dataConfig.apiKey) {
167- headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
168- }
169-
170- // For events going to Continue, overwrite the access token
171- if (
172- uriComponents.host?.endsWith(".continue.dev") ||
173- uriComponents.host === "continue.dev"
174- ) {
175- //
176- const accessToken =
177- await this.core?.configHandler.controlPlaneClient.getAccessToken();
178- headers["Authorization"] = `Bearer ${accessToken}`;
179- }
180- const profileId =
181- this.core?.configHandler.currentProfile?.profileDescription
182- .id ?? "";
183- const response = await fetchwithRequestOptions(
184- dataConfig.destination,
185- {
186- method: "POST",
187- headers,
188- body: JSON.stringify({
189- name: event.name,
190- data: parsed.data,
191- schema,
192- level,
193- profileId,
194- }),
195- },
196- dataConfig.requestOptions,
197- );
198- if (!response.ok) {
199- throw new Error(
200- `Post request failed. ${response.status}: ${response.statusText}`,
201- );
202- }
203- } else if (uriComponents.scheme === "file") {
204- // Write to jsonc file for local file URIs
205- const dirUri = joinPathsToUri(dataConfig.destination, schema);
206- const dirPath = fileURLToPath(dirUri);
207-
208- if (!fs.existsSync(dirPath)) {
209- fs.mkdirSync(dirPath, { recursive: true });
210- }
211- const filepath = path.join(dirPath, `${event.name}.jsonl`);
212- const jsonLine = JSON.stringify(event.data);
213- fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
214- } else {
215- throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
216- }
217- } catch (error) {
218- console.error(
219- `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
220- );
221- }
222- }),
212+ level,
213+ profileId,
214+ }),
215+ },
216+ dataConfig.requestOptions,
217+ );
218+ if (!response.ok) {
219+ throw new Error(
220+ `Post request failed. ${response.status}: ${response.statusText}`,
221+ );
222+ }
223+ } else if (uriComponents.scheme === "file") {
224+ // Write to jsonc file for local file URIs
225+ const dirUri = joinPathsToUri(dataConfig.destination, schema);
226+ const dirPath = fileURLToPath(dirUri);
227+
228+ if (!fs.existsSync(dirPath)) {
229+ fs.mkdirSync(dirPath, { recursive: true });
230+ }
231+ const filepath = path.join(dirPath, `${event.name}.jsonl`);
232+ const jsonLine = JSON.stringify(event.data);
233+ fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
234+ } else {
235+ throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
236+ }
237+ } catch (error) {
238+ console.error(
239+ `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
223240 );
224241 }
225242 }
modified core/edit/recursiveStream.ts +5 −2
@@ -16,6 +16,7 @@
1616
1717 export async function* recursiveStream(
1818 llm: ILLM,
19+ abortController: AbortController,
1920 prompt: ChatMessage[] | string,
2021 prediction: Prediction | undefined,
2122 currentBuffer = "",
@@ -28,7 +29,7 @@
2829 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
2930
3031 if (typeof prompt === "string") {
31- const generator = llm.streamComplete(prompt, new AbortController().signal, {
32+ const generator = llm.streamComplete(prompt, abortController.signal, {
3233 raw: true,
3334 prediction: undefined,
3435 reasoning: false,
@@ -50,6 +51,7 @@
5051 // // TODO - Prediction capabilities lost because of partial input
5152 // yield* recursiveStream(
5253 // llm,
54+ // abortController,
5355 // continuationPrompt,
5456 // undefined,
5557 // buffer,
@@ -60,7 +62,7 @@
6062 }
6163 }
6264 } else {
63- const generator = llm.streamChat(prompt, new AbortController().signal, {
65+ const generator = llm.streamChat(prompt, abortController.signal, {
6466 prediction,
6567 reasoning: false,
6668 });
@@ -90,6 +92,7 @@
9092 // await generator.return(DUD_PROMPT_LOG);
9193 // yield* recursiveStream(
9294 // llm,
95+ // abortController,
9396 // continuationPrompt,
9497 // undefined,
9598 // buffer,
modified core/edit/streamDiffLines.ts +7 −1
@@ -20,6 +20,7 @@
2020 import { streamLines } from "../diff/util";
2121 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2222 import { gptEditPrompt } from "../llm/templates/edit";
23+import { StreamAbortManager } from "../util/abortManager";
2324 import { findLast } from "../util/findLast";
2425 import { Telemetry } from "../util/posthog";
2526 import { recursiveStream } from "./recursiveStream";
@@ -63,6 +64,7 @@
6364 highlighted,
6465 suffix,
6566 llm,
67+ abortControllerId,
6668 input,
6769 language,
6870 onlyOneInsertion,
@@ -73,12 +75,15 @@
7375 highlighted: string;
7476 suffix: string;
7577 llm: ILLM;
78+ abortControllerId: string;
7679 input: string;
7780 language: string | undefined;
7881 onlyOneInsertion: boolean;
7982 overridePrompt: ChatMessage[] | undefined;
8083 rulesToInclude: RuleWithSource[] | undefined;
8184 }): AsyncGenerator<DiffLine> {
85+ const abortManager = StreamAbortManager.getInstance();
86+ const abortController = abortManager.get(abortControllerId);
8287 void Telemetry.capture(
8388 "inlineEdit",
8489 {
@@ -122,6 +127,7 @@
122127 (msg) => msg.role === "user" || msg.role === "tool",
123128 ) as UserChatMessage | ToolResultChatMessage | undefined),
124129 baseSystemMessage: undefined,
130+ contextItems: [],
125131 })
126132 : undefined;
127133
@@ -157,7 +163,7 @@
157163 content: highlighted,
158164 };
159165
160- const completion = recursiveStream(llm, prompt, prediction);
166+ const completion = recursiveStream(llm, abortController, prompt, prediction);
161167
162168 let lines = streamLines(completion);
163169
modified core/index.d.ts +46 −13
@@ -197,15 +197,14 @@
197197 description?: string;
198198 renderInlineAs?: string;
199199 type?: ContextProviderType;
200+ loadSubmenuItems?: (
201+ args: LoadSubmenuItemsArgs,
202+ ) => Promise<ContextSubmenuItem[]>;
200203
201204 getContextItems(
202205 query: string,
203206 extras: ContextProviderExtras,
204207 ): Promise<ContextItem[]>;
205-
206- loadSubmenuItems?: (
207- args: LoadSubmenuItemsArgs,
208- ) => Promise<ContextSubmenuItem[]>;
209208 }
210209
211210 export interface ContextSubmenuItem {
@@ -459,6 +458,7 @@
459458 toolCallState?: ToolCallState;
460459 isGatheringContext?: boolean;
461460 reasoning?: Reasoning;
461+ appliedRules?: RuleWithSource[];
462462 }
463463
464464 export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@@ -842,6 +842,7 @@
842842 description: string;
843843 prompt?: string;
844844 params?: { [key: string]: any };
845+ promptFile?: string;
845846 run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
846847 }
847848
@@ -1023,6 +1024,7 @@
10231024 toolChoice?: ToolChoice;
10241025 reasoning?: boolean;
10251026 reasoningBudgetTokens?: number;
1027+ promptCaching?: boolean;
10261028 }
10271029
10281030 export interface ModelCapability {
@@ -1090,6 +1092,7 @@
10901092 disable: boolean;
10911093 maxPromptTokens: number;
10921094 debounceDelay: number;
1095+ modelTimeout: number;
10931096 maxSuffixPercentage: number;
10941097 prefixPercentage: number;
10951098 transform?: boolean;
@@ -1165,6 +1168,7 @@
11651168 description?: string;
11661169 mimeType?: string;
11671170 }
1171+
11681172 export interface MCPTool {
11691173 name: string;
11701174 description?: string;
@@ -1190,6 +1194,7 @@
11901194 showChatScrollbar?: boolean;
11911195 codeWrap?: boolean;
11921196 showSessionTabs?: boolean;
1197+ autoAcceptEditToolDiffs?: boolean;
11931198 }
11941199
11951200 export interface ContextMenuConfig {
@@ -1227,6 +1232,32 @@
12271232 toolCallId?: string;
12281233 }
12291234
1235+export interface StreamDiffLinesPayload {
1236+ prefix: string;
1237+ highlighted: string;
1238+ suffix: string;
1239+ input: string;
1240+ language: string | undefined;
1241+ modelTitle: string | undefined;
1242+ includeRulesInSystemMessage: boolean;
1243+ fileUri?: string;
1244+}
1245+
1246+export interface HighlightedCodePayload {
1247+ rangeInFileWithContents: RangeInFileWithContents;
1248+ prompt?: string;
1249+ shouldRun?: boolean;
1250+}
1251+
1252+export interface AcceptOrRejectDiffPayload {
1253+ filepath: string;
1254+ streamId?: string;
1255+}
1256+
1257+export interface ShowFilePayload {
1258+ filepath: string;
1259+}
1260+
12301261 export interface RangeInFileWithContents {
12311262 filepath: string;
12321263 range: {
@@ -1236,7 +1267,7 @@
12361267 contents: string;
12371268 }
12381269
1239-export type CodeToEdit = RangeInFileWithContents | FileWithContents;
1270+export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
12401271
12411272 /**
12421273 * Represents the configuration for a quick action in the Code Lens.
@@ -1495,17 +1526,19 @@
14951526 waitForCompletion?: boolean;
14961527 }
14971528
1529+export type RuleSource =
1530+ | "default-chat"
1531+ | "default-agent"
1532+ | "model-chat-options"
1533+ | "model-agent-options"
1534+ | "rules-block"
1535+ | "json-systemMessage"
1536+ | ".continuerules";
1537+
14981538 export interface RuleWithSource {
14991539 name?: string;
15001540 slug?: string;
1501- source:
1502- | "default-chat"
1503- | "default-agent"
1504- | "model-chat-options"
1505- | "model-agent-options"
1506- | "rules-block"
1507- | "json-systemMessage"
1508- | ".continuerules";
1541+ source: RuleSource;
15091542 globs?: string | string[];
15101543 rule: string;
15111544 description?: string;
modified core/indexing/CodeSnippetsIndex.ts +2 −1
@@ -7,7 +7,7 @@
77 getQueryForFile,
88 } from "../util/treeSitter";
99
10-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
10+import { DatabaseConnection, SqliteDb } from "./refreshIndex";
1111 import {
1212 IndexResultType,
1313 MarkCompleteCallback,
@@ -29,6 +29,7 @@
2929 getLastNUriRelativePathParts,
3030 getUriPathBasename,
3131 } from "../util/uri";
32+import { tagToString } from "./utils";
3233
3334 type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
3435
modified core/indexing/FullTextSearchCodebaseIndex.ts +7 −3
@@ -3,13 +3,14 @@
33 import { getUriPathBasename } from "../util/uri";
44
55 import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
6-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
6+import { DatabaseConnection, SqliteDb } from "./refreshIndex";
77 import {
88 IndexResultType,
99 MarkCompleteCallback,
1010 RefreshIndexResults,
1111 type CodebaseIndex,
1212 } from "./types";
13+import { tagToString } from "./utils";
1314
1415 export interface RetrieveConfig {
1516 tags: BranchAndDir[];
@@ -97,11 +98,14 @@
9798
9899 // Delete
99100 for (const item of results.del) {
100- await db.run(`
101+ await db.run(
102+ `
101103 DELETE FROM fts WHERE rowid IN (
102104 SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
103105 )
104- `,[item.path, item.cacheKey]);
106+ `,
107+ [item.path, item.cacheKey],
108+ );
105109 await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
106110 item.path,
107111 item.cacheKey,
modified core/indexing/LanceDbIndex.ts +2 −1
@@ -14,7 +14,7 @@
1414
1515 import { basicChunker } from "./chunk/basic.js";
1616 import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
17-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
17+import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
1818 import {
1919 CodebaseIndex,
2020 IndexResultType,
@@ -24,6 +24,7 @@
2424 } from "./types";
2525
2626 import type * as LanceType from "vectordb";
27+import { tagToString } from "./utils";
2728
2829 interface LanceDbRow {
2930 uuid: string;
modified core/indexing/chunk/ChunkCodebaseIndex.ts +3 −2
@@ -4,7 +4,7 @@
44
55 import { IContinueServerClient } from "../../continueServer/interface.js";
66 import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
7-import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
7+import { DatabaseConnection, SqliteDb } from "../refreshIndex.js";
88 import {
99 IndexResultType,
1010 MarkCompleteCallback,
@@ -13,8 +13,9 @@
1313 type CodebaseIndex,
1414 } from "../types.js";
1515
16-import { chunkDocument, shouldChunk } from "./chunk.js";
1716 import { getUriPathBasename } from "../../util/uri.js";
17+import { tagToString } from "../utils.js";
18+import { chunkDocument, shouldChunk } from "./chunk.js";
1819
1920 export class ChunkCodebaseIndex implements CodebaseIndex {
2021 relativeExpectedTime: number = 1;
modified core/indexing/refreshIndex.ts +0 −4
@@ -18,10 +18,6 @@
1818
1919 export type DatabaseConnection = Database<sqlite3.Database>;
2020
21-export function tagToString(tag: IndexTag): string {
22- return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
23-}
24-
2521 export class SqliteDb {
2622 static db: DatabaseConnection | null = null;
2723
modified core/indexing/test/indexing.ts +1 −1
@@ -3,11 +3,11 @@
33 import { IndexTag } from "../..";
44 import { IContinueServerClient } from "../../continueServer/interface";
55 import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex";
6-import { tagToString } from "../refreshIndex";
76 import { CodebaseIndex, RefreshIndexResults } from "../types";
87
98 import { testIde } from "../../test/fixtures";
109 import { addToTestDir, TEST_DIR } from "../../test/testDir";
10+import { tagToString } from "../utils";
1111
1212 export const mockFilename = "test.py";
1313 export const mockPathAndCacheKey = {
added core/indexing/utils.test.ts +58 −0
@@ -0,0 +1,58 @@
1+import { IndexTag } from "..";
2+import { tagToString } from "./utils";
3+
4+test("tagToString returns full tag string when under length limit", () => {
5+ const tag: IndexTag = {
6+ directory: "/normal/path/to/repo",
7+ branch: "main",
8+ artifactId: "12345",
9+ };
10+
11+ expect(tagToString(tag)).toBe("/normal/path/to/repo::main::12345");
12+});
13+
14+test("tagToString truncates beginning of directory when path is too long", () => {
15+ // Create a very long directory path that exceeds MAX_DIR_LENGTH (200)
16+ const longPrefix = "/very/long/path/that/will/be/truncated/";
17+ const importantSuffix = "/user/important-project/src/feature";
18+ const longPath = longPrefix + "x".repeat(200) + importantSuffix;
19+
20+ const tag: IndexTag = {
21+ directory: longPath,
22+ branch: "feature-branch",
23+ artifactId: "67890",
24+ };
25+
26+ const result = tagToString(tag);
27+
28+ // The result should keep the important suffix part
29+ expect(result).toContain(importantSuffix);
30+ // The result should NOT contain the beginning of the path
31+ expect(result).not.toContain(longPrefix);
32+ // The result should include the branch and artifactId
33+ expect(result).toContain("::feature-branch::67890");
34+ // The result should be within the MAX_TABLE_NAME_LENGTH limit (240)
35+ expect(result.length).toBeLessThanOrEqual(240);
36+});
37+
38+test("tagToString preserves branch and artifactId exactly, even when truncating", () => {
39+ const longPath = "/a".repeat(300); // Much longer than MAX_DIR_LENGTH
40+ const tag: IndexTag = {
41+ directory: longPath,
42+ branch: "release-v2.0",
43+ artifactId: "build-123",
44+ };
45+
46+ const result = tagToString(tag);
47+
48+ // Should contain the exact branch and artifactId
49+ expect(result).toContain("::release-v2.0::build-123");
50+ // Should contain the end of the path
51+ expect(result).toContain("/a/a/a");
52+ // Should not contain the full original path (it should be truncated)
53+ expect(result.length).toBeLessThan(
54+ longPath.length + "::release-v2.0::build-123".length,
55+ );
56+ // The result should be within the MAX_TABLE_NAME_LENGTH limit
57+ expect(result.length).toBeLessThanOrEqual(240);
58+});
added core/indexing/utils.ts +45 −0
@@ -0,0 +1,45 @@
1+import { IndexTag } from "..";
2+
3+// Maximum length for table names to stay under OS filename limits
4+const MAX_TABLE_NAME_LENGTH = 240;
5+
6+// Leave room for branch and artifactId
7+const MAX_DIR_LENGTH = 200;
8+
9+/**
10+ * Converts an IndexTag to a string representation, safely handling long paths.
11+ *
12+ * The string is used as a table name and identifier in various places, so it needs
13+ * to stay under OS filename length limits (typically 255 chars). This is especially
14+ * important for dev containers where the directory path can be very long due to
15+ * containing container configuration.
16+ *
17+ * The format is: "{directory}::{branch}::{artifactId}"
18+ *
19+ * To handle long paths:
20+ * 1. First tries the full string - most backwards compatible
21+ * 2. If too long, truncates directory from the beginning to maintain uniqueness
22+ * (since final parts of paths are more unique than prefixes)
23+ * 3. Finally ensures entire string stays under MAX_TABLE_NAME_LENGTH for OS compatibility
24+ *
25+ * @param tag The tag containing directory, branch, and artifactId
26+ * @returns A string representation safe for use as a table name
27+ */
28+export function tagToString(tag: IndexTag): string {
29+ const result = `${tag.directory}::${tag.branch}::${tag.artifactId}`;
30+
31+ if (result.length <= MAX_TABLE_NAME_LENGTH) {
32+ return result;
33+ }
34+
35+ // Truncate from the beginning of directory path to preserve the more unique end parts
36+ const dir =
37+ tag.directory.length > MAX_DIR_LENGTH
38+ ? tag.directory.slice(tag.directory.length - MAX_DIR_LENGTH)
39+ : tag.directory;
40+
41+ return `${dir}::${tag.branch}::${tag.artifactId}`.slice(
42+ 0,
43+ MAX_TABLE_NAME_LENGTH,
44+ );
45+}
modified core/llm/constructMessages.ts +35 −2
@@ -1,6 +1,7 @@
11 import {
22 ChatHistoryItem,
33 ChatMessage,
4+ ContextItemWithId,
45 RuleWithSource,
56 TextMessagePart,
67 ToolResultChatMessage,
@@ -58,7 +59,7 @@
5859 at the beginning, middle, or end of files using these "lazy" comments. Only
5960 provide the complete file when explicitly requested. Include a concise explanation
6061 of changes unless the user specifically asks for code only.
61-`
62+`;
6263
6364 export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
6465 <important_rules>
@@ -77,6 +78,31 @@
7778 ${EDIT_MESSAGE}
7879 </important_rules>`;
7980
81+/**
82+ * Helper function to get the context items for a user message
83+ */
84+function getUserContextItems(
85+ userMsg: UserChatMessage | ToolResultChatMessage | undefined,
86+ history: ChatHistoryItem[],
87+): ContextItemWithId[] {
88+ if (!userMsg) return [];
89+
90+ // Find the history item that contains the userMsg
91+ const historyItem = history.find((item) => {
92+ // Check if the message ID matches
93+ if ("id" in userMsg && "id" in item.message) {
94+ return (item.message as any).id === (userMsg as any).id;
95+ }
96+ // Fallback to content comparison
97+ return (
98+ item.message.content === userMsg.content &&
99+ item.message.role === userMsg.role
100+ );
101+ });
102+
103+ return historyItem?.contextItems || [];
104+}
105+
80106 export function constructMessages(
81107 messageMode: string,
82108 history: ChatHistoryItem[],
@@ -92,7 +118,8 @@
92118 const historyItem = filteredHistory[i];
93119
94120 if (messageMode === "chat") {
95- const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage;
121+ const toolMessage: ToolResultChatMessage =
122+ historyItem.message as ToolResultChatMessage;
96123 if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
97124 // remove all tool calls from the history
98125 continue;
@@ -127,10 +154,16 @@
127154 | ToolResultChatMessage
128155 | undefined;
129156
157+ // Get context items for the last user message
158+ const lastUserContextItems = getUserContextItems(
159+ lastUserMsg,
160+ filteredHistory,
161+ );
130162 const systemMessage = getSystemMessageWithRules({
131163 baseSystemMessage: baseChatOrAgentSystemMessage,
132164 rules,
133165 userMessage: lastUserMsg,
166+ contextItems: lastUserContextItems,
134167 });
135168
136169 if (systemMessage.trim()) {
modified core/llm/index.ts +3 −0
@@ -382,6 +382,9 @@
382382
383383 // Error mapping to be more helpful
384384 if (!resp.ok) {
385+ if (resp.status === 499) {
386+ return resp; // client side cancellation
387+ }
385388 let text = await resp.text();
386389 if (resp.status === 404 && !resp.url.includes("/v1")) {
387390 const error = JSON.parse(text)?.error?.replace(/"/g, "'");
modified core/llm/llm.test.ts +25 −10
@@ -22,6 +22,20 @@
2222 // maxTokens: 5,
2323 };
2424
25+/**
26+ * Retries a test function if it fails on the first attempt
27+ * @param testFn The test function to run
28+ * @returns A function that will retry once if the test fails
29+ */
30+const retryOnce = (testFn: () => Promise<any>) => async () => {
31+ try {
32+ return await testFn();
33+ } catch (error) {
34+ console.log("Test failed on first attempt, retrying once...");
35+ return await testFn();
36+ }
37+};
38+
2539 function testLLM(
2640 llm: BaseLLM,
2741 {
@@ -47,7 +61,7 @@
4761 describe(llm.providerName + "/" + llm.model, () => {
4862 test(
4963 "Stream Chat works",
50- async () => {
64+ retryOnce(async () => {
5165 let total = "";
5266 for await (const chunk of llm.streamChat(
5367 [{ role: "user", content: "Hi" }],
@@ -58,13 +72,13 @@
5872
5973 expect(total.length).toBeGreaterThan(0);
6074 return;
61- },
75+ }),
6276 timeout,
6377 );
6478
6579 test(
6680 "Stream Complete works",
67- async () => {
81+ retryOnce(async () => {
6882 let total = "";
6983 for await (const chunk of llm.streamComplete(
7084 "Hi",
@@ -75,13 +89,13 @@
7589
7690 expect(total.length).toBeGreaterThan(0);
7791 return;
78- },
92+ }),
7993 timeout,
8094 );
8195
8296 test(
8397 "Complete works",
84- async () => {
98+ retryOnce(async () => {
8599 const completion = await llm.complete(
86100 "Hi",
87101 new AbortController().signal,
@@ -89,14 +103,14 @@
89103
90104 expect(completion.length).toBeGreaterThan(0);
91105 return;
92- },
106+ }),
93107 timeout,
94108 );
95109
96110 if (testFim) {
97111 test(
98112 "FIM works",
99- async () => {
113+ retryOnce(async () => {
100114 let total = "";
101115 for await (const chunk of llm.streamFim(
102116 "Hi",
@@ -108,7 +122,7 @@
108122
109123 expect(total.length).toBeGreaterThan(0);
110124 return;
111- },
125+ }),
112126 timeout,
113127 );
114128 }
@@ -116,7 +130,7 @@
116130 if (testToolCall) {
117131 test(
118132 "Tool Call works",
119- async () => {
133+ retryOnce(async () => {
120134 let args = "";
121135 let isFirstChunk = true;
122136 for await (const chunk of llm.streamChat(
@@ -175,7 +189,7 @@
175189
176190 const parsedArgs = JSON.parse(args);
177191 expect(parsedArgs.name).toBe("Nate");
178- },
192+ }),
179193 timeout,
180194 );
181195 }
@@ -230,6 +244,7 @@
230244 testFim: true,
231245 skip: false,
232246 testToolCall: true,
247+ timeout: 60000,
233248 },
234249 );
235250 testLLM(
modified core/llm/llms/Anthropic.ts +5 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
23 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 class Anthropic extends BaseLLM {
77 static providerName = "anthropic";
@@ -213,6 +213,10 @@
213213 signal,
214214 });
215215
216+ if (response.status === 499) {
217+ return; // Aborted by user
218+ }
219+
216220 if (!response.ok) {
217221 const json = await response.json();
218222 if (json.type === "error") {
modified core/llm/llms/Asksage.ts +4 −8
@@ -134,10 +134,8 @@
134134 body: JSON.stringify(args),
135135 });
136136
137- if (!response.ok) {
138- throw new Error(
139- `API request failed with status ${response.status}: ${response.statusText}`,
140- );
137+ if (response.status === 499) {
138+ return ""; // Aborted by user
141139 }
142140
143141 const data = await response.json();
@@ -167,10 +165,8 @@
167165 signal,
168166 });
169167
170- if (!response.ok) {
171- throw new Error(
172- `API request failed with status ${response.status}: ${response.statusText}`,
173- );
168+ if (response.status === 499) {
169+ return; // Aborted by user
174170 }
175171
176172 const data = await response.json();
modified core/llm/llms/Bedrock.ts +26 −18
@@ -5,6 +5,7 @@
55 ConverseStreamCommandOutput,
66 InvokeModelCommand,
77 Message,
8+ ToolConfiguration,
89 } from "@aws-sdk/client-bedrock-runtime";
910 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
1011
@@ -291,9 +292,10 @@
291292 const convertedMessages = this._convertMessages(messages);
292293
293294 const shouldCacheSystemMessage =
294- !!systemMessage && this.cacheBehavior?.cacheSystemMessage;
295+ !!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
295296 const enablePromptCaching =
296- shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
297+ shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
298+ const shouldCacheToolsConfig = this.completionOptions.promptCaching;
297299
298300 // Add header for prompt caching
299301 if (enablePromptCaching) {
@@ -304,29 +306,35 @@
304306 }
305307
306308 const supportsTools =
307- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
309+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
310+
311+ let toolConfig = supportsTools && options.tools
312+ ? {
313+ tools: options.tools.map((tool) => ({
314+ toolSpec: {
315+ name: tool.function.name,
316+ description: tool.function.description,
317+ inputSchema: {
318+ json: tool.function.parameters,
319+ },
320+ },
321+ })),
322+ } as ToolConfiguration
323+ : undefined;
324+
325+ if (toolConfig?.tools && shouldCacheToolsConfig) {
326+ toolConfig.tools.push({ cachePoint: { type: "default" } });
327+ }
328+
308329 return {
309330 modelId: options.model,
310- messages: convertedMessages,
311331 system: systemMessage
312332 ? shouldCacheSystemMessage
313333 ? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
314334 : [{ text: systemMessage }]
315335 : undefined,
316- toolConfig:
317- supportsTools && options.tools
318- ? {
319- tools: options.tools.map((tool) => ({
320- toolSpec: {
321- name: tool.function.name,
322- description: tool.function.description,
323- inputSchema: {
324- json: tool.function.parameters,
325- },
326- },
327- })),
328- }
329- : undefined,
336+ toolConfig: toolConfig,
337+ messages: convertedMessages,
330338 inferenceConfig: {
331339 maxTokens: options.maxTokens,
332340 temperature: options.temperature,
modified core/llm/llms/Cloudflare.ts +1 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions } from "../../index.js";
23 import { renderChatMessage } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 export default class Cloudflare extends BaseLLM {
77 static providerName = "cloudflare";
modified core/llm/llms/Cohere.ts +5 −1
@@ -1,3 +1,4 @@
1+import { streamJSON } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
@@ -6,7 +7,6 @@
67 } from "../../index.js";
78 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
89 import { BaseLLM } from "../index.js";
9-import { streamJSON } from "../stream.js";
1010
1111 class Cohere extends BaseLLM {
1212 static providerName = "cohere";
@@ -84,6 +84,10 @@
8484 signal,
8585 });
8686
87+ if (resp.status === 499) {
88+ return; // Aborted by user
89+ }
90+
8791 if (options.stream === false) {
8892 const data = await resp.json();
8993 yield { role: "assistant", content: data.text };
modified core/llm/llms/Deepseek.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Flowise.ts +7 −3
@@ -132,12 +132,16 @@
132132 ): AsyncGenerator<ChatMessage> {
133133 const requestBody = this._getRequestBody(messages, options);
134134 const { socket, socketInfo } = await this._initializeSocket();
135- const request = this.fetch(this._getChatUrl(), {
135+ const response = await this.fetch(this._getChatUrl(), {
136136 method: "POST",
137137 headers: this._getHeaders(),
138138 body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
139139 signal,
140- }).then((res) => res.json());
140+ });
141+
142+ if (response.status === 499) {
143+ return; // Aborted by user
144+ }
141145
142146 while (await socketInfo.hasNextToken()) {
143147 yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@@ -145,7 +149,7 @@
145149 if (socketInfo.error) {
146150 socket.disconnect();
147151 try {
148- yield { role: "assistant", content: (await request).text };
152+ yield { role: "assistant", content: await response.text() };
149153 } catch (error: any) {
150154 yield { role: "assistant", content: (error as Error).message ?? error };
151155 }
modified core/llm/llms/FreeTrial.ts +1 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
23 import { getHeaders } from "../../continueServer/stubs/headers.js";
34 import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@@ -8,7 +9,6 @@
89 LLMOptions,
910 } from "../../index.js";
1011 import { BaseLLM } from "../index.js";
11-import { streamResponse } from "../stream.js";
1212
1313 class FreeTrial extends BaseLLM {
1414 static providerName = "free-trial";
modified core/llm/llms/Gemini.ts +4 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { v4 as uuidv4 } from "uuid";
23 import {
34 AssistantChatMessage,
@@ -10,7 +11,6 @@
1011 } from "../../index.js";
1112 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
1213 import { BaseLLM } from "../index.js";
13-import { streamResponse } from "../stream.js";
1414 import {
1515 GeminiChatContent,
1616 GeminiChatContentPart,
@@ -438,6 +438,9 @@
438438 body: JSON.stringify(body),
439439 signal,
440440 });
441+ if (response.status === 499) {
442+ return; // Aborted by user
443+ }
441444 const data = await response.json();
442445 yield { role: "assistant", content: data.candidates[0].content };
443446 }
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceInferenceAPI extends BaseLLM {
66 static providerName = "huggingface-inference-api";
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceTGI extends BaseLLM {
66 private static MAX_STOP_TOKENS = 4;
modified core/llm/llms/Inception.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33
44 import OpenAI from "./OpenAI.js";
55
modified core/llm/llms/LlamaCpp.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class LlamaCpp extends BaseLLM {
66 static providerName = "llama.cpp";
modified core/llm/llms/Moonshot.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Ollama.ts +4 −1
@@ -2,6 +2,7 @@
22 import { JSONSchema7, JSONSchema7Object } from "json-schema";
33 import { v4 as uuidv4 } from "uuid";
44
5+import { streamResponse } from "@continuedev/fetch";
56 import {
67 ChatMessage,
78 ChatMessageRole,
@@ -12,7 +13,6 @@
1213 import { renderChatMessage } from "../../util/messageContent.js";
1314 import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
1415 import { BaseLLM } from "../index.js";
15-import { streamResponse } from "../stream.js";
1616
1717 type OllamaChatMessage = {
1818 role: ChatMessageRole;
@@ -457,6 +457,9 @@
457457 }
458458
459459 if (chatOptions.stream === false) {
460+ if (response.status === 499) {
461+ return; // Aborted by user
462+ }
460463 const json = (await response.json()) as OllamaChatResponse;
461464 yield convertChatMessage(json);
462465 } else {
added core/llm/llms/OpenAI.test.ts +34 −0
@@ -0,0 +1,34 @@
1+import OpenAI from "./OpenAI";
2+
3+describe("OpenAI", () => {
4+ test("should identify correct o-series models", () => {
5+ const openai = new OpenAI({
6+ model: "o3-mini",
7+ });
8+ expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
9+ expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
10+ expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
11+ expect(openai.isOSeriesModel("o1")).toBeTruthy();
12+ expect(openai.isOSeriesModel("o3")).toBeTruthy();
13+
14+ // artificially correct samples for future models
15+ expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
16+ expect(openai.isOSeriesModel("o6")).toBeTruthy();
17+ expect(openai.isOSeriesModel("o77")).toBeTruthy();
18+ expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
19+ });
20+ test("should identify incorrect o-series models", () => {
21+ const openai = new OpenAI({
22+ model: "o3-mini",
23+ });
24+ expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
25+ expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
26+ expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
27+
28+ // artificially wrong samples
29+ expect(openai.isOSeriesModel("os1")).toBeFalsy();
30+ expect(openai.isOSeriesModel("so1")).toBeFalsy();
31+ expect(openai.isOSeriesModel("ao31")).toBeFalsy();
32+ expect(openai.isOSeriesModel("1os")).toBeFalsy();
33+ });
34+});
modified core/llm/llms/OpenAI.ts +8 −5
@@ -3,6 +3,7 @@
33 ChatCompletionMessageParam,
44 } from "openai/resources/index";
55
6+import { streamSse } from "@continuedev/fetch";
67 import {
78 ChatMessage,
89 CompletionOptions,
@@ -16,7 +17,6 @@
1617 LlmApiRequestType,
1718 toChatBody,
1819 } from "../openaiTypeConverters.js";
19-import { streamSse } from "../stream.js";
2020
2121 const NON_CHAT_MODELS = [
2222 "text-davinci-002",
@@ -77,8 +77,8 @@
7777 return model;
7878 }
7979
80- private isO3orO1Model(model?: string): boolean {
81- return !!model && (model.startsWith("o1") || model.startsWith("o3"));
80+ public isOSeriesModel(model?: string): boolean {
81+ return !!model && !!model.match(/^o[0-9]+/);
8282 }
8383
8484 private isFireworksAiModel(model?: string): boolean {
@@ -139,7 +139,7 @@
139139 finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
140140
141141 // OpenAI o1-preview and o1-mini or o3-mini:
142- if (this.isO3orO1Model(options.model)) {
142+ if (this.isOSeriesModel(options.model)) {
143143 // a) use max_completion_tokens instead of max_tokens
144144 finalOptions.max_completion_tokens = options.maxTokens;
145145 finalOptions.max_tokens = undefined;
@@ -241,7 +241,7 @@
241241 body.stop = body.stop?.slice(0, this.getMaxStopWords());
242242
243243 // OpenAI o1-preview and o1-mini or o3-mini:
244- if (this.isO3orO1Model(body.model)) {
244+ if (this.isOSeriesModel(body.model)) {
245245 // a) use max_completion_tokens instead of max_tokens
246246 body.max_completion_tokens = body.max_tokens;
247247 body.max_tokens = undefined;
@@ -352,6 +352,9 @@
352352
353353 // Handle non-streaming response
354354 if (body.stream === false) {
355+ if (response.status === 499) {
356+ return; // Aborted by user
357+ }
355358 const data = await response.json();
356359 yield data.choices[0].message;
357360 return;
modified core/llm/llms/SiliconFlow.ts +2 −2
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
@@ -58,7 +58,7 @@
5858 console.warn("[SiliconFlow] rerank: query is empty");
5959 return [];
6060 }
61-
61+
6262 if (!chunks || chunks.length === 0) {
6363 console.warn("[SiliconFlow] rerank: chunks is empty");
6464 return [];
modified core/llm/llms/VertexAI.ts +23 −5
@@ -1,9 +1,9 @@
11 import { GoogleAuth } from "google-auth-library";
22
3+import { streamResponse, streamSse } from "@continuedev/fetch";
34 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
45 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
56 import { BaseLLM } from "../index.js";
6-import { streamResponse, streamSse } from "../stream.js";
77
88 import Anthropic from "./Anthropic.js";
99 import Gemini from "./Gemini.js";
@@ -95,6 +95,7 @@
9595 protected async *StreamChatAnthropic(
9696 messages: ChatMessage[],
9797 options: CompletionOptions,
98+ signal: AbortSignal,
9899 ): AsyncGenerator<ChatMessage> {
99100 const systemMessage = stripImages(
100101 messages.filter((m) => m.role === "system")[0]?.content ?? "",
@@ -128,8 +129,13 @@
128129 ]
129130 : systemMessage,
130131 }),
132+ signal,
131133 });
132134
135+ if (response.status === 499) {
136+ return; // Aborted by user
137+ }
138+
133139 if (options.stream === false) {
134140 const data = await response.json();
135141 yield { role: "assistant", content: data.content[0].text };
@@ -150,6 +156,7 @@
150156 private async *streamChatGemini(
151157 messages: ChatMessage[],
152158 options: CompletionOptions,
159+ signal: AbortSignal,
153160 ): AsyncGenerator<ChatMessage> {
154161 const apiURL = new URL(
155162 `publishers/google/models/${options.model}:streamGenerateContent`,
@@ -160,6 +167,7 @@
160167 const response = await this.fetch(apiURL, {
161168 method: "POST",
162169 body: JSON.stringify(body),
170+ signal,
163171 });
164172 for await (const message of this.geminiInstance.processGeminiResponse(
165173 streamResponse(response),
@@ -171,6 +179,7 @@
171179 private async *streamChatBison(
172180 messages: ChatMessage[],
173181 options: CompletionOptions,
182+ signal: AbortSignal,
174183 ): AsyncGenerator<ChatMessage> {
175184 const instances = messages.map((message) => ({ prompt: message.content }));
176185
@@ -193,7 +202,11 @@
193202 const response = await this.fetch(apiURL, {
194203 method: "POST",
195204 body: JSON.stringify(body),
205+ signal,
196206 });
207+ if (response.status === 499) {
208+ return; // Aborted by user
209+ }
197210 const data = await response.json();
198211 yield { role: "assistant", content: data.predictions[0].content };
199212 }
@@ -203,6 +216,7 @@
203216 protected async *StreamChatMistral(
204217 messages: ChatMessage[],
205218 options: CompletionOptions,
219+ signal: AbortSignal,
206220 ): AsyncGenerator<ChatMessage> {
207221 const apiBase = this.apiBase!;
208222 const apiURL = new URL(
@@ -228,6 +242,7 @@
228242 const response = await this.fetch(apiURL, {
229243 method: "POST",
230244 body: JSON.stringify(body),
245+ signal,
231246 });
232247
233248 for await (const chunk of streamSse(response)) {
@@ -304,6 +319,9 @@
304319 }),
305320 signal,
306321 });
322+ if (resp.status === 499) {
323+ return; // Aborted by user
324+ }
307325 // Streaming is not supported by code-gecko
308326 // TODO: convert to non-streaming fim method when one exist in continue.
309327 yield (await resp.json()).predictions[0].content;
@@ -323,14 +341,14 @@
323341 ? this.geminiInstance.removeSystemMessage(messages)
324342 : messages;
325343 if (this.vertexProvider === "gemini") {
326- yield* this.streamChatGemini(convertedMsgs, options);
344+ yield* this.streamChatGemini(convertedMsgs, options, signal);
327345 } else if (this.vertexProvider === "mistral") {
328- yield* this.StreamChatMistral(messages, options);
346+ yield* this.StreamChatMistral(messages, options, signal);
329347 } else if (this.vertexProvider === "anthropic") {
330- yield* this.StreamChatAnthropic(messages, options);
348+ yield* this.StreamChatAnthropic(messages, options, signal);
331349 } else {
332350 if (options.model.includes("bison")) {
333- yield* this.streamChatBison(convertedMsgs, options);
351+ yield* this.streamChatBison(convertedMsgs, options, signal);
334352 } else {
335353 throw new Error(`Unsupported model: ${options.model}`);
336354 }
modified core/llm/llms/WatsonX.ts +37 −53
@@ -1,15 +1,12 @@
1+import { streamResponse, streamSse } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
45 CompletionOptions,
56 LLMOptions,
67 } from "../../index.js";
7-import {
8- fromChatCompletionChunk,
9-} from "../openaiTypeConverters.js";
10-import { renderChatMessage } from "../../util/messageContent.js";
118 import { BaseLLM } from "../index.js";
12-import { streamResponse, streamSse } from "../stream.js";
9+import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
1310
1411 let watsonxToken = {
1512 expiration: 0,
@@ -86,7 +83,7 @@
8683 }
8784
8885 _getEndpoint(endpoint: string): string {
89- return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
86+ return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
9087 }
9188
9289 static providerName = "watsonx";
@@ -182,7 +179,6 @@
182179 signal: AbortSignal,
183180 options: CompletionOptions,
184181 ): AsyncGenerator<string> {
185-
186182 await this.updateWatsonxToken();
187183
188184 const stopSequences = options.stop?.slice(0, 6) ?? [];
@@ -214,44 +210,38 @@
214210 payload.project_id = this.projectId;
215211 }
216212
217- var response = await this.fetch(url, {
213+ const response = await this.fetch(url, {
218214 method: "POST",
219215 headers: headers,
220216 body: JSON.stringify(payload),
221217 signal,
222218 });
223219
224- if (!response.ok || response.body === null) {
225- throw new Error(
226- "Something went wrong. No response received, check your connection",
227- );
228- } else {
229- for await (const value of streamResponse(response)) {
230- const lines = value.split("\n");
231- let generatedChunk = "";
232- let generatedTextIndex = undefined;
233- lines.forEach((el: string) => {
234- // console.log(`${el}`);
235- if (el.startsWith("id:")) {
236- generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
237- if (isNaN(generatedTextIndex)) {
238- console.error(`Unable to parse stream chunk ID: ${el}`);
239- }
240- } else if (el.startsWith("data:")) {
241- const dataStr = el.replace(/^data:\s+/, "");
242- try {
243- const data = JSON.parse(dataStr);
244- data.results.forEach((result: any) => {
245- generatedChunk += result.generated_text || "";
246- });
247- } catch (e) {
248- // parsing error is expected with streaming response
249- // console.error(`Error parsing JSON string: ${dataStr}`, e);
250- }
220+ for await (const value of streamResponse(response)) {
221+ const lines = value.split("\n");
222+ let generatedChunk = "";
223+ let generatedTextIndex = undefined;
224+ lines.forEach((el: string) => {
225+ // console.log(`${el}`);
226+ if (el.startsWith("id:")) {
227+ generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
228+ if (isNaN(generatedTextIndex)) {
229+ console.error(`Unable to parse stream chunk ID: ${el}`);
251230 }
252- });
253- yield generatedChunk
254- }
231+ } else if (el.startsWith("data:")) {
232+ const dataStr = el.replace(/^data:\s+/, "");
233+ try {
234+ const data = JSON.parse(dataStr);
235+ data.results.forEach((result: any) => {
236+ generatedChunk += result.generated_text || "";
237+ });
238+ } catch (e) {
239+ // parsing error is expected with streaming response
240+ // console.error(`Error parsing JSON string: ${dataStr}`, e);
241+ }
242+ }
243+ });
244+ yield generatedChunk;
255245 }
256246 }
257247
@@ -267,7 +257,7 @@
267257 const headers = this._getHeaders();
268258
269259 const payload: any = {
270- messages: messages,
260+ messages: messages,
271261 max_tokens: options.maxTokens ?? 1024,
272262 stop: stopSequences,
273263 frequency_penalty: options.frequencyPenalty || 1,
@@ -281,36 +271,30 @@
281271
282272 if (!!options.temperature) {
283273 payload.temperature = options.temperature;
284- }
274+ }
285275 if (!!options.topP) {
286276 payload.top_p = options.topP;
287277 }
288278 if (!!options.tools) {
289279 payload.tools = options.tools;
290280 if (options.toolChoice) {
291- payload.tool_choice = options.toolChoice;
281+ payload.tool_choice = options.toolChoice;
292282 } else {
293- payload.tool_choice_option = "auto";
283+ payload.tool_choice_option = "auto";
294284 }
295285 }
296286
297- var response = await this.fetch(url, {
287+ const response = await this.fetch(url, {
298288 method: "POST",
299289 headers: headers,
300290 body: JSON.stringify(payload),
301291 signal,
302292 });
303293
304- if (!response.ok || response.body === null) {
305- throw new Error(
306- "Something went wrong. No response received, check your connection",
307- );
308- } else {
309- for await (const value of streamSse(response)) {
310- const chunk = fromChatCompletionChunk(value);
311- if (chunk) {
312- yield chunk;
313- }
294+ for await (const value of streamSse(response)) {
295+ const chunk = fromChatCompletionChunk(value);
296+ if (chunk) {
297+ yield chunk;
314298 }
315299 }
316300 }
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
@@ -27,8 +27,12 @@
2727 // to call whatever LLM API is chosen
2828 private actualApiBase?: string;
2929
30+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
31+ private configEnv?: Record<string, any>;
32+
3033 constructor(options: LLMOptions) {
3134 super(options);
35+ this.configEnv = options.env;
3236 this.actualApiBase = options.apiBase;
3337 this.apiKeyLocation = options.apiKeyLocation;
3438 this.orgScopeId = options.orgScopeId;
@@ -48,6 +52,7 @@
4852 apiKeyLocation: this.apiKeyLocation,
4953 apiBase: this.actualApiBase,
5054 orgScopeId: this.orgScopeId ?? null,
55+ env: this.configEnv,
5156 };
5257 return {
5358 continueProperties,
modified core/llm/rules/getSystemMessageWithRules.test.ts +207 −3
@@ -1,4 +1,4 @@
1-import { RuleWithSource, UserChatMessage } from "../..";
1+import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
22 import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
33
44 describe("getSystemMessageWithRules", () => {
@@ -25,11 +25,48 @@
2525 source: "rules-block",
2626 };
2727
28+ // JavaScript rule
29+ const jsRule: RuleWithSource = {
30+ name: "JavaScript Rule",
31+ rule: "Follow JavaScript best practices",
32+ globs: "**/*.js",
33+ source: "rules-block",
34+ };
35+
36+ // Empty context items
37+ const emptyContextItems: ContextItemWithId[] = [];
38+
39+ // Context items with file paths
40+ const tsContextItem: ContextItemWithId = {
41+ content: "TypeScript file content",
42+ name: "Component.tsx",
43+ description: "A TypeScript component",
44+ id: { providerTitle: "file", itemId: "src/Component.tsx" },
45+ uri: { type: "file", value: "src/Component.tsx" },
46+ };
47+
48+ const pyContextItem: ContextItemWithId = {
49+ content: "Python file content",
50+ name: "utils.py",
51+ description: "A Python utility file",
52+ id: { providerTitle: "file", itemId: "utils.py" },
53+ uri: { type: "file", value: "utils.py" },
54+ };
55+
56+ const jsContextItem: ContextItemWithId = {
57+ content: "JavaScript file content",
58+ name: "utils.js",
59+ description: "A JavaScript utility file",
60+ id: { providerTitle: "file", itemId: "src/utils.js" },
61+ uri: { type: "file", value: "src/utils.js" },
62+ };
63+
2864 it("should not include pattern-matched rules when no file paths are mentioned", () => {
2965 const result = getSystemMessageWithRules({
3066 baseSystemMessage,
3167 userMessage: undefined,
3268 rules: [tsRule],
69+ contextItems: emptyContextItems,
3370 });
3471
3572 expect(result).toBe(baseSystemMessage);
@@ -40,12 +77,13 @@
4077 baseSystemMessage,
4178 userMessage: undefined,
4279 rules: [generalRule],
80+ contextItems: emptyContextItems,
4381 });
4482
4583 expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
4684 });
4785
48- it("should include only matching rules based on file paths", () => {
86+ it("should include only matching rules based on file paths in message", () => {
4987 const userMessage: UserChatMessage = {
5088 role: "user",
5189 content:
@@ -56,6 +94,20 @@
5694 baseSystemMessage,
5795 userMessage,
5896 rules: [tsRule, pythonRule, generalRule],
97+ contextItems: emptyContextItems,
98+ });
99+
100+ // Should include TS rule and general rule, but not Python rule
101+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
102+ expect(result).toBe(expected);
103+ });
104+
105+ it("should include matching rules based on file paths in context items", () => {
106+ const result = getSystemMessageWithRules({
107+ baseSystemMessage,
108+ userMessage: undefined,
109+ rules: [tsRule, pythonRule, generalRule],
110+ contextItems: [tsContextItem],
59111 });
60112
61113 // Should include TS rule and general rule, but not Python rule
@@ -63,7 +115,25 @@
63115 expect(result).toBe(expected);
64116 });
65117
66- it("should include multiple matching rules", () => {
118+ it("should include matching rules from both message and context items", () => {
119+ const userMessage: UserChatMessage = {
120+ role: "user",
121+ content: "```python test.py\nprint('hello')\n```",
122+ };
123+
124+ const result = getSystemMessageWithRules({
125+ baseSystemMessage,
126+ userMessage,
127+ rules: [tsRule, pythonRule, generalRule],
128+ contextItems: [tsContextItem],
129+ });
130+
131+ // Should include TS rule, Python rule, and general rule
132+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
133+ expect(result).toBe(expected);
134+ });
135+
136+ it("should include multiple matching rules from message", () => {
67137 const userMessage: UserChatMessage = {
68138 role: "user",
69139 content:
@@ -74,6 +144,20 @@
74144 baseSystemMessage,
75145 userMessage,
76146 rules: [tsRule, pythonRule, generalRule],
147+ contextItems: emptyContextItems,
148+ });
149+
150+ // Should include all rules
151+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
152+ expect(result).toBe(expected);
153+ });
154+
155+ it("should include multiple matching rules from context items", () => {
156+ const result = getSystemMessageWithRules({
157+ baseSystemMessage,
158+ userMessage: undefined,
159+ rules: [tsRule, pythonRule, generalRule],
160+ contextItems: [tsContextItem, pyContextItem],
77161 });
78162
79163 // Should include all rules
@@ -91,6 +175,7 @@
91175 baseSystemMessage,
92176 userMessage,
93177 rules: [tsRule, pythonRule, generalRule],
178+ contextItems: emptyContextItems,
94179 });
95180
96181 // Should only include the general rule
@@ -117,6 +202,7 @@
117202 baseSystemMessage,
118203 userMessage,
119204 rules: [commaRule],
205+ contextItems: emptyContextItems,
120206 });
121207
122208 // With the current implementation, the comma-separated pattern is treated as a single string,
@@ -143,6 +229,7 @@
143229 baseSystemMessage,
144230 userMessage,
145231 rules: [arrayGlobRule],
232+ contextItems: emptyContextItems,
146233 });
147234
148235 // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
@@ -168,6 +255,7 @@
168255 baseSystemMessage,
169256 userMessage,
170257 rules: [arrayGlobRule],
258+ contextItems: emptyContextItems,
171259 });
172260
173261 // Should match src/main.ts but not config/settings.ts
@@ -193,9 +281,125 @@
193281 baseSystemMessage,
194282 userMessage,
195283 rules: [arrayGlobRule],
284+ contextItems: emptyContextItems,
196285 });
197286
198287 // Should not match any file paths
199288 expect(result).toBe(baseSystemMessage);
200289 });
290+
291+ // New test for code block with filename only (no language)
292+ it("should handle code blocks with filename only (no language identifier)", () => {
293+ const userMessage: UserChatMessage = {
294+ role: "user",
295+ content: "```test.js\nclass Calculator { /* code */ }\n```",
296+ };
297+
298+ const result = getSystemMessageWithRules({
299+ baseSystemMessage,
300+ userMessage,
301+ rules: [jsRule, tsRule, generalRule],
302+ contextItems: emptyContextItems,
303+ });
304+
305+ // Should include JS rule and general rule
306+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
307+ expect(result).toBe(expected);
308+ });
309+
310+ // New test for code blocks with line ranges
311+ it("should handle code blocks with line ranges", () => {
312+ const userMessage: UserChatMessage = {
313+ role: "user",
314+ content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```",
315+ };
316+
317+ const result = getSystemMessageWithRules({
318+ baseSystemMessage,
319+ userMessage,
320+ rules: [jsRule, tsRule, generalRule],
321+ contextItems: emptyContextItems,
322+ });
323+
324+ // Should include JS rule and general rule
325+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
326+ expect(result).toBe(expected);
327+ });
328+
329+ // New test for mixed code block formats
330+ it("should handle mixed code block formats in the same message", () => {
331+ const userMessage: UserChatMessage = {
332+ role: "user",
333+ content:
334+ "```test.js\nclass Calculator { /* code */ }\n```\n" +
335+ "```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" +
336+ "```ts config/settings.ts\nconst config = {};\n```",
337+ };
338+
339+ const result = getSystemMessageWithRules({
340+ baseSystemMessage,
341+ userMessage,
342+ rules: [jsRule, tsRule, generalRule],
343+ contextItems: emptyContextItems,
344+ });
345+
346+ // Should include JS rule, TS rule, and general rule
347+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
348+ expect(result).toBe(expected);
349+ });
350+
351+ // Test for context items when there's no message
352+ it("should apply rules based on context items only when no message is present", () => {
353+ const result = getSystemMessageWithRules({
354+ baseSystemMessage,
355+ userMessage: undefined,
356+ rules: [jsRule, tsRule, generalRule],
357+ contextItems: [jsContextItem],
358+ });
359+
360+ // Should include JS rule and general rule
361+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
362+ expect(result).toBe(expected);
363+ });
364+
365+ // Test for non-file context items
366+ it("should ignore non-file context items", () => {
367+ const nonFileContextItem: ContextItemWithId = {
368+ content: "Some search result",
369+ name: "Search result",
370+ description: "A search result",
371+ id: { providerTitle: "search", itemId: "search-result" },
372+ // No uri with type "file"
373+ };
374+
375+ const result = getSystemMessageWithRules({
376+ baseSystemMessage,
377+ userMessage: undefined,
378+ rules: [jsRule, tsRule, generalRule],
379+ contextItems: [nonFileContextItem],
380+ });
381+
382+ // Should only include general rule
383+ const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
384+ expect(result).toBe(expected);
385+ });
386+
387+ // Test combining context items with message
388+ it("should match rules from both message code blocks and context items", () => {
389+ const userMessage: UserChatMessage = {
390+ role: "user",
391+ content: "```ts src/main.ts\nconsole.log('hello');\n```",
392+ };
393+
394+ const result = getSystemMessageWithRules({
395+ baseSystemMessage,
396+ userMessage,
397+ rules: [jsRule, tsRule, pythonRule, generalRule],
398+ contextItems: [jsContextItem, pyContextItem],
399+ });
400+
401+ // Should include JS, TS, Python rules and general rule
402+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
403+ expect(result).toBe(expected);
404+ });
201405 });
modified core/llm/rules/getSystemMessageWithRules.ts +56 −16
@@ -1,5 +1,10 @@
11 import { minimatch } from "minimatch";
2-import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
2+import {
3+ ContextItemWithId,
4+ RuleWithSource,
5+ ToolResultChatMessage,
6+ UserChatMessage,
7+} from "../..";
38 import { renderChatMessage } from "../../util/messageContent";
49 import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
510
@@ -23,32 +28,67 @@
2328 return false;
2429 };
2530
31+/**
32+ * Filters rules that apply to the given message and/or context items
33+ *
34+ * @param userMessage - The user or tool message to check for file paths in code blocks
35+ * @param rules - The list of rules to filter
36+ * @param contextItems - Context items to check for file paths
37+ * @returns List of applicable rules
38+ */
39+export const getApplicableRules = (
40+ userMessage: UserChatMessage | ToolResultChatMessage | undefined,
41+ rules: RuleWithSource[],
42+ contextItems: ContextItemWithId[],
43+): RuleWithSource[] => {
44+ const filePathsFromMessage = userMessage
45+ ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
46+ : [];
47+
48+ // Extract file paths from context items
49+ const filePathsFromContextItems = contextItems
50+ .filter((item) => item.uri?.type === "file" && item.uri?.value)
51+ .map((item) => item.uri!.value);
52+ // Combine file paths from both sources
53+ const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
54+
55+ return rules.filter((rule) => {
56+ // A rule is active if it has no globs (applies to all files)
57+ // or if at least one file path matches its globs
58+ const hasNoGlobs = !rule.globs;
59+ const matchesAnyFilePath = allFilePaths.some((path) =>
60+ matchesGlobs(path, rule.globs),
61+ );
62+
63+ return hasNoGlobs || matchesAnyFilePath;
64+ });
65+};
66+
67+/**
68+ * Creates a system message string with applicable rules appended
69+ *
70+ * @param baseSystemMessage - The base system message to start with
71+ * @param userMessage - The user message to check for file paths
72+ * @param rules - The list of rules to filter
73+ * @param contextItems - Context items to check for file paths
74+ * @returns System message with applicable rules appended
75+ */
2676 export const getSystemMessageWithRules = ({
2777 baseSystemMessage,
2878 userMessage,
2979 rules,
80+ contextItems,
3081 }: {
3182 baseSystemMessage?: string;
3283 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
3384 rules: RuleWithSource[];
85+ contextItems: ContextItemWithId[];
3486 }) => {
35- const filePathsFromMessage = userMessage
36- ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
37- : [];
38-
87+ const applicableRules = getApplicableRules(userMessage, rules, contextItems);
3988 let systemMessage = baseSystemMessage ?? "";
4089
41- for (const rule of rules) {
42- // A rule is active if it has no globs (applies to all files)
43- // or if at least one file path matches its globs
44- const hasNoGlobs = !rule.globs;
45- const matchesAnyFilePath = filePathsFromMessage.some((path) =>
46- matchesGlobs(path, rule.globs),
47- );
48-
49- if (hasNoGlobs || matchesAnyFilePath) {
50- systemMessage += `\n\n${rule.rule}`;
51- }
90+ for (const rule of applicableRules) {
91+ systemMessage += `\n\n${rule.rule}`;
5292 }
5393
5494 return systemMessage;
modified core/llm/stream.ts +2 −2
@@ -1,4 +1,4 @@
1-async function* toAsyncIterable(
1+export async function* toAsyncIterable(
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
@@ -58,7 +58,7 @@
5858 }
5959
6060 function parseSseLine(line: string): { done: boolean; data: any } {
61- if (line.startsWith("data: [DONE]")) {
61+ if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
6262 return { done: true, data: undefined };
6363 }
6464 if (line.startsWith("data:")) {
modified core/llm/streamChat.ts +27 −35
@@ -8,7 +8,7 @@
88
99 export async function* llmStreamChat(
1010 configHandler: ConfigHandler,
11- abortedMessageIds: Set<string>,
11+ abortController: AbortController,
1212 msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
1313 ide: IDE,
1414 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@@ -75,52 +75,44 @@
7575 selectedCode,
7676 config,
7777 fetch: (url, init) =>
78- fetchwithRequestOptions(url, init, config.requestOptions),
78+ fetchwithRequestOptions(
79+ url,
80+ {
81+ ...init,
82+ signal: abortController.signal,
83+ },
84+ config.requestOptions,
85+ ),
7986 completionOptions,
8087 });
81- const checkActiveInterval = setInterval(() => {
82- if (abortedMessageIds.has(msg.messageId)) {
83- abortedMessageIds.delete(msg.messageId);
84- clearInterval(checkActiveInterval);
85- }
86- }, 100);
87- try {
88- let next = await gen.next();
89- while (!next.done) {
90- if (abortedMessageIds.has(msg.messageId)) {
91- abortedMessageIds.delete(msg.messageId);
92- next = await gen.return(errorPromptLog);
93- clearInterval(checkActiveInterval);
94- break;
95- }
96- if (next.value) {
97- yield {
98- role: "assistant",
99- content: next.value,
100- };
101- }
102- next = await gen.next();
88+ let next = await gen.next();
89+ while (!next.done) {
90+ if (abortController.signal.aborted) {
91+ next = await gen.return(errorPromptLog);
92+ break;
10393 }
104- if (!next.done) {
105- throw new Error("Will never happen");
94+ if (next.value) {
95+ yield {
96+ role: "assistant",
97+ content: next.value,
98+ };
10699 }
107-
108- return next.value;
109- } catch (e) {
110- throw e;
111- } finally {
112- clearInterval(checkActiveInterval);
100+ next = await gen.next();
113101 }
102+ if (!next.done) {
103+ throw new Error("Will never happen");
104+ }
105+
106+ return next.value;
114107 } else {
115108 const gen = model.streamChat(
116109 messages,
117- new AbortController().signal,
110+ abortController.signal,
118111 completionOptions,
119112 );
120113 let next = await gen.next();
121114 while (!next.done) {
122- if (abortedMessageIds.has(msg.messageId)) {
123- abortedMessageIds.delete(msg.messageId);
115+ if (abortController.signal.aborted) {
124116 next = await gen.return(errorPromptLog);
125117 break;
126118 }
modified core/llm/templates/edit/gpt.ts +2 −0
@@ -64,6 +64,8 @@
6464 \`\`\`
6565
6666 The user's request is: "${otherData.userInput}"
67+
68+ DO NOT output any natural language, only output the code changes.
6769
6870 Here is the rewritten code:`);
6971
modified core/llm/toolSupport.test.ts +3 −0
@@ -155,6 +155,7 @@
155155 expect(supportsFn("pixtral-12b-2409")).toBe(true);
156156 expect(supportsFn("pixtral-large-latest")).toBe(true);
157157 expect(supportsFn("open-mistral-nemo")).toBe(true);
158+ expect(supportsFn("devstral-latest")).toBe(true);
158159 });
159160
160161 it("should return false for other unsupported models", () => {
@@ -170,6 +171,7 @@
170171 expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
171172 expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
172173 expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
174+ expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
173175 });
174176 });
175177
@@ -192,6 +194,7 @@
192194 expect(supportsFn("aya-expanse")).toBe(true);
193195 expect(supportsFn("firefunction-v2")).toBe(true);
194196 expect(supportsFn("mistral-7b")).toBe(true);
197+ expect(supportsFn("devstral-24b")).toBe(true);
195198 });
196199
197200 it("should return false for explicitly unsupported models", () => {
modified core/llm/toolSupport.ts +72 −2
@@ -17,6 +17,7 @@
1717 "claude-3.5",
1818 "claude-3-7",
1919 "claude-3.7",
20+ "claude-sonnet-4",
2021 "gpt-4",
2122 "o3",
2223 "gemini",
@@ -24,7 +25,7 @@
2425 },
2526 anthropic: (model) => {
2627 if (
27- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
28+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
2829 model.toLowerCase().startsWith(part),
2930 )
3031 ) {
@@ -76,7 +77,7 @@
7677 // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
7778 if (
7879 model.toLowerCase().includes("sonnet") &&
79- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
80+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
8081 model.toLowerCase().includes(part),
8182 )
8283 ) {
@@ -88,6 +89,7 @@
8889 return (
8990 !model.toLowerCase().includes("mamba") &&
9091 [
92+ "devstral",
9193 "codestral",
9294 "mistral-large",
9395 "mistral-small",
@@ -136,6 +138,7 @@
136138 "aya-expanse",
137139 "firefunction-v2",
138140 "mistral",
141+ "devstral",
139142 ].some((part) => modelName.toLowerCase().includes(part))
140143 ) {
141144 return true;
@@ -165,4 +168,71 @@
165168 )
166169 return true;
167170 },
171+ openrouter: (model) => {
172+ // https://openrouter.ai/models?fmt=cards&supported_parameters=tools
173+ if (
174+ ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
175+ (part) => model.toLowerCase().includes(part),
176+ )
177+ ) {
178+ return false;
179+ }
180+
181+ const supportedPrefixes = [
182+ "openai/gpt-3.5",
183+ "openai/gpt-4",
184+ "openai/o1",
185+ "openai/o3",
186+ "openai/o4",
187+ "anthropic/claude-3",
188+ "microsoft/phi-3",
189+ "google/gemini-flash-1.5",
190+ "google/gemini-2",
191+ "google/gemini-pro",
192+ "x-ai/grok",
193+ "qwen/qwen3",
194+ "qwen/qwen-",
195+ "cohere/command-r",
196+ "ai21/jamba-1.6",
197+ "mistralai/mistral",
198+ "mistralai/ministral",
199+ "mistralai/codestral",
200+ "mistralai/mixtral",
201+ "mistral/ministral",
202+ "mistralai/pixtral",
203+ "meta-llama/llama-3.3",
204+ "amazon/nova",
205+ "deepseek/deepseek-r1",
206+ "deepseek/deepseek-chat",
207+ "meta-llama/llama-4",
208+ "all-hands/openhands-lm-32b",
209+ ];
210+ for (const prefix of supportedPrefixes) {
211+ if (model.toLowerCase().startsWith(prefix)) {
212+ return true;
213+ }
214+ }
215+
216+ const specificModels = [
217+ "qwen/qwq-32b",
218+ "qwen/qwen-2.5-72b-instruct",
219+ "meta-llama/llama-3.2-3b-instruct",
220+ "meta-llama/llama-3-8b-instruct",
221+ "meta-llama/llama-3-70b-instruct",
222+ "arcee-ai/caller-large",
223+ "nousresearch/hermes-3-llama-3.1-70b",
224+ ];
225+ for (const model of specificModels) {
226+ if (model.toLowerCase() === model) {
227+ return true;
228+ }
229+ }
230+
231+ const supportedContains = ["llama-3.1"];
232+ for (const model of supportedContains) {
233+ if (model.toLowerCase().includes(model)) {
234+ return true;
235+ }
236+ }
237+ },
168238 };
added core/llm/utils/extractPathsFromCodeBlocks.test.ts +35 −0
@@ -0,0 +1,35 @@
1+import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks";
2+
3+describe("extractPathsFromCodeBlocks", () => {
4+ it("should extract paths from code blocks with language and filepath", () => {
5+ const content = "```typescript src/main.ts\nconst x = 1;\n```";
6+ expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]);
7+ });
8+
9+ it("should extract paths from code blocks with filepath only (no language)", () => {
10+ const content = "```test.js\nclass Calculator { }\n```";
11+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
12+ });
13+
14+ it("should extract paths from code blocks with line ranges", () => {
15+ const content = "```js test.js (19-25)\nfunction test() {}\n```";
16+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
17+ });
18+
19+ it("should handle multiple code blocks with different formats", () => {
20+ const content =
21+ "```typescript src/main.ts\nconst x = 1;\n```\n" +
22+ "```test.js\nclass Calculator { }\n```\n" +
23+ "```js utils.js (19-25)\nfunction test() {}\n```";
24+ const result = extractPathsFromCodeBlocks(content);
25+ expect(result).toContain("src/main.ts");
26+ expect(result).toContain("test.js");
27+ expect(result).toContain("utils.js");
28+ expect(result.length).toBe(3);
29+ });
30+
31+ it("should not extract paths from code blocks without file paths", () => {
32+ const content = "```typescript\nconst x = 1;\n```";
33+ expect(extractPathsFromCodeBlocks(content)).toEqual([]);
34+ });
35+});
No newline at the end of the file
modified core/llm/utils/extractPathsFromCodeBlocks.ts +29 −13
@@ -2,21 +2,37 @@
22 * Extracts file paths from markdown code blocks
33 */
44 export function extractPathsFromCodeBlocks(content: string): string[] {
5- // Match:
6- // 1. Starting ```
7- // 2. Optional language identifier
8- // 3. Required whitespace
9- // 4. File path (captured) that must contain a dot and extension
10- const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
5+ console.log("CONTENT", content);
6+
117 const paths: string[] = [];
12- let match;
13-
14- while ((match = codeBlockRegex.exec(content)) !== null) {
15- const path = match[1];
16- if (path && !path.startsWith("```")) {
17- paths.push(path);
8+
9+ // Match code block opening patterns:
10+ // 1. ```language filepath
11+ // 2. ```filepath
12+ // 3. ```language filepath (range)
13+
14+ // First match all code block starts
15+ const codeBlockStarts = content.match(/```[^\n]+/g) || [];
16+
17+ for (const blockStart of codeBlockStarts) {
18+ // Try to extract a valid filename with extension
19+ const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/);
20+
21+ if (filenameMatches && filenameMatches[1]) {
22+ const filename = filenameMatches[1];
23+
24+ // Verify this is a legitimate filename (not part of something else)
25+ if (
26+ // Check if valid extension
27+ /\.[a-zA-Z0-9]+$/.test(filename) &&
28+ // Make sure it's not a URL
29+ !filename.includes("://") &&
30+ // Avoid duplicates
31+ !paths.includes(filename)
32+ ) {
33+ paths.push(filename);
34+ }
1835 }
1936 }
20-
2137 return paths;
2238 }
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 +4 −2
@@ -27,6 +27,7 @@
2727 "@types/mustache": "^4.2.5",
2828 "@types/node-fetch": "^2.6.11",
2929 "@types/pg": "^8.11.6",
30+ "@types/plist": "^3.0.5",
3031 "@types/request": "^2.48.12",
3132 "@types/tar": "^6.1.13",
3233 "@types/uuid": "^9.0.7",
@@ -48,9 +49,9 @@
4849 "@aws-sdk/credential-providers": "^3.778.0",
4950 "@continuedev/config-types": "^1.0.13",
5051 "@continuedev/config-yaml": "file:../packages/config-yaml",
51- "@continuedev/fetch": "^1.0.6",
52+ "@continuedev/fetch": "^1.0.10",
5253 "@continuedev/llm-info": "^1.0.8",
53- "@continuedev/openai-adapters": "^1.0.19",
54+ "@continuedev/openai-adapters": "^1.0.25",
5455 "@modelcontextprotocol/sdk": "^1.5.0",
5556 "@mozilla/readability": "^0.5.0",
5657 "@octokit/rest": "^20.1.1",
@@ -89,6 +90,7 @@
8990 "p-limit": "^6.1.0",
9091 "partial-json": "^0.1.7",
9192 "pg": "^8.11.3",
93+ "plist": "^3.1.0",
9294 "posthog-node": "^3.6.3",
9395 "puppeteer": "^22.4.0",
9496 "puppeteer-chromium-resolver": "^23.0.0",
modified core/promptFiles/v1/slashCommandFromPromptFile.ts +1 −0
@@ -63,6 +63,7 @@
6363 name,
6464 description,
6565 prompt,
66+ promptFile: path,
6667 run: async function* (context) {
6768 const userInput = extractUserInput(context.input, name);
6869 const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
modified core/protocol/core.ts +5 −14
@@ -9,7 +9,7 @@
99 import { SharedConfigSchema } from "../config/sharedConfig";
1010 import { GlobalContextModelSelections } from "../util/GlobalContext";
1111
12-import type {
12+import {
1313 BrowserSerializedContinueConfig,
1414 ChatMessage,
1515 ContextItem,
@@ -29,10 +29,11 @@
2929 SessionMetadata,
3030 SiteIndexingConfig,
3131 SlashCommandDescription,
32+ StreamDiffLinesPayload,
3233 ToolCall,
3334 } from "../";
3435 import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
35-import { ControlPlaneSessionInfo } from "../control-plane/client";
36+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
3637
3738 export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
3839
@@ -45,6 +46,7 @@
4546 // Special
4647 ping: [string, string];
4748 abort: [undefined, void];
49+ cancelApply: [undefined, void];
4850
4951 // History
5052 "history/list": [ListHistoryOptions, SessionMetadata[]];
@@ -142,18 +144,7 @@
142144 },
143145 AsyncGenerator<ChatMessage, PromptLog>,
144146 ];
145- streamDiffLines: [
146- {
147- prefix: string;
148- highlighted: string;
149- suffix: string;
150- input: string;
151- language: string | undefined;
152- modelTitle: string | undefined;
153- includeRulesInSystemMessage: boolean;
154- },
155- AsyncGenerator<DiffLine>,
156- ];
147+ streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
157148 "chatDescriber/describe": [
158149 {
159150 text: string;
modified core/protocol/ide.ts +2 −3
@@ -1,5 +1,3 @@
1-import { ControlPlaneSessionInfo } from "../control-plane/client";
2-
31 import type {
42 ContinueRcJson,
53 DiffLine,
@@ -16,6 +14,7 @@
1614 TerminalOptions,
1715 Thread,
1816 } from "../";
17+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
1918
2019 export interface GetGhTokenArgs {
2120 force?: boolean;
@@ -99,7 +98,7 @@
9998 ControlPlaneSessionInfo | undefined,
10099 ];
101100 logoutOfControlPlane: [undefined, void];
102- reportError:[any, void];
101+ reportError: [any, void];
103102 closeSidebar: [undefined, void];
104103 };
105104
modified core/protocol/ideWebview.ts +11 −15
@@ -1,11 +1,14 @@
11 import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
22 import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
33
4-import type {
4+import {
5+ AcceptOrRejectDiffPayload,
56 ApplyState,
6- CodeToEdit,
7+ HighlightedCodePayload,
78 MessageContent,
89 RangeInFileWithContents,
10+ SetCodeToEditPayload,
11+ ShowFilePayload,
912 } from "../";
1013
1114 export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@@ -21,7 +24,7 @@
2124 ];
2225 overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
2326 showTutorial: [undefined, void];
24- showFile: [{ filepath: string }, void];
27+ showFile: [ShowFilePayload, void];
2528 toggleDevTools: [undefined, void];
2629 reloadWindow: [undefined, void];
2730 focusEditor: [undefined, void];
@@ -39,11 +42,11 @@
3942 vscMediaUrl: string;
4043 },
4144 ];
42- "jetbrains/getColors": [undefined, Record<string, string>];
45+ "jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
4346 "vscode/openMoveRightMarkdown": [undefined, void];
4447 setGitHubAuthToken: [{ token: string }, void];
45- acceptDiff: [{ filepath: string; streamId?: string }, void];
46- rejectDiff: [{ filepath: string; streamId?: string }, void];
48+ acceptDiff: [AcceptOrRejectDiffPayload, void];
49+ rejectDiff: [AcceptOrRejectDiffPayload, void];
4750 "edit/sendPrompt": [
4851 {
4952 prompt: MessageContent;
@@ -63,15 +66,8 @@
6366 focusContinueInput: [undefined, void];
6467 focusContinueInputWithoutClear: [undefined, void];
6568 focusContinueInputWithNewSession: [undefined, void];
66- highlightedCode: [
67- {
68- rangeInFileWithContents: RangeInFileWithContents;
69- prompt?: string;
70- shouldRun?: boolean;
71- },
72- void,
73- ];
74- setCodeToEdit: [CodeToEdit, void];
69+ highlightedCode: [HighlightedCodePayload, void];
70+ setCodeToEdit: [SetCodeToEditPayload, void];
7571 navigateTo: [{ path: string; toggle?: boolean }, void];
7672 addModel: [undefined, void];
7773
modified core/protocol/webview.ts +2 −2
@@ -1,6 +1,6 @@
11 import { ConfigResult } from "@continuedev/config-yaml";
22 import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
3-import { ControlPlaneSessionInfo } from "../control-plane/client.js";
3+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js";
44 import type {
55 BrowserSerializedContinueConfig,
66 ContextItemWithId,
@@ -40,7 +40,7 @@
4040 setTTSActive: [boolean, void];
4141 getWebviewHistoryLength: [undefined, number];
4242 getCurrentSessionId: [undefined, string];
43- "jetbrains/setColors": [Record<string, string>, void];
43+ "jetbrains/setColors": [Record<string, string | null | undefined>, void];
4444 sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
4545 toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
4646 };
modified core/test/testDir.ts +1 −1
@@ -43,7 +43,7 @@
4343 if (Array.isArray(p)) {
4444 fs.writeFileSync(filepath, p[1]);
4545 } else if (p.endsWith("/")) {
46- fs.mkdirSync(p, { recursive: true });
46+ fs.mkdirSync(filepath, { recursive: true });
4747 } else {
4848 fs.writeFileSync(filepath, "");
4949 }
modified core/tools/callTool.ts +39 −40
@@ -29,11 +29,12 @@
2929 }),
3030 });
3131
32+ const data = await response.json();
33+
3234 if (!response.ok) {
33- throw new Error(`Failed to call tool: ${url}`);
35+ throw new Error(`Failed to call tool at ${url}:\n${JSON.stringify(data)}`);
3436 }
3537
36- const data = await response.json();
3738 return data.output;
3839 }
3940
@@ -84,7 +85,7 @@
8485 });
8586
8687 if (response.isError === true) {
87- throw new Error(`Failed to call tool: ${toolName}`);
88+ throw new Error(JSON.stringify(response.content));
8889 }
8990
9091 const contextItems: ContextItem[] = [];
@@ -130,6 +131,37 @@
130131 }
131132 }
132133
134+async function callBuiltInTool(
135+ functionName: string,
136+ args: any,
137+ extras: ToolExtras,
138+): Promise<ContextItem[]> {
139+ switch (functionName) {
140+ case BuiltInToolNames.ReadFile:
141+ return await readFileImpl(args, extras);
142+ case BuiltInToolNames.CreateNewFile:
143+ return await createNewFileImpl(args, extras);
144+ case BuiltInToolNames.GrepSearch:
145+ return await grepSearchImpl(args, extras);
146+ case BuiltInToolNames.FileGlobSearch:
147+ return await fileGlobSearchImpl(args, extras);
148+ case BuiltInToolNames.RunTerminalCommand:
149+ return await runTerminalCommandImpl(args, extras);
150+ case BuiltInToolNames.SearchWeb:
151+ return await searchWebImpl(args, extras);
152+ case BuiltInToolNames.ViewDiff:
153+ return await viewDiffImpl(args, extras);
154+ case BuiltInToolNames.LSTool:
155+ return await lsToolImpl(args, extras);
156+ case BuiltInToolNames.ReadCurrentlyOpenFile:
157+ return await readCurrentlyOpenFileImpl(args, extras);
158+ case BuiltInToolNames.CreateRuleBlock:
159+ return await createRuleBlockImpl(args, extras);
160+ default:
161+ throw new Error(`Tool "${functionName}" not found`);
162+ }
163+}
164+
133165 // Handles calls for core/non-client tools
134166 // Returns an error context item if the tool call fails
135167 // Note: Edit tool is handled on client
@@ -141,44 +173,11 @@
141173 contextItems: ContextItem[];
142174 errorMessage: string | undefined;
143175 }> {
144- const args = JSON.parse(callArgs || "{}");
145- const uri = tool.uri ?? tool.function.name;
146176 try {
147- let contextItems: ContextItem[] = [];
148- switch (uri) {
149- case BuiltInToolNames.ReadFile:
150- contextItems = await readFileImpl(args, extras);
151- break;
152- case BuiltInToolNames.CreateNewFile:
153- contextItems = await createNewFileImpl(args, extras);
154- break;
155- case BuiltInToolNames.GrepSearch:
156- contextItems = await grepSearchImpl(args, extras);
157- break;
158- case BuiltInToolNames.FileGlobSearch:
159- contextItems = await fileGlobSearchImpl(args, extras);
160- break;
161- case BuiltInToolNames.RunTerminalCommand:
162- contextItems = await runTerminalCommandImpl(args, extras);
163- break;
164- case BuiltInToolNames.SearchWeb:
165- contextItems = await searchWebImpl(args, extras);
166- break;
167- case BuiltInToolNames.ViewDiff:
168- contextItems = await viewDiffImpl(args, extras);
169- break;
170- case BuiltInToolNames.LSTool:
171- contextItems = await lsToolImpl(args, extras);
172- break;
173- case BuiltInToolNames.ReadCurrentlyOpenFile:
174- contextItems = await readCurrentlyOpenFileImpl(args, extras);
175- break;
176- case BuiltInToolNames.CreateRuleBlock:
177- contextItems = await createRuleBlockImpl(args, extras);
178- break;
179- default:
180- contextItems = await callToolFromUri(uri, args, extras);
181- }
177+ const args = JSON.parse(callArgs || "{}");
178+ const contextItems = tool.uri
179+ ? await callToolFromUri(tool.uri, args, extras)
180+ : await callBuiltInTool(tool.function.name, args, extras);
182181 if (tool.faviconUrl) {
183182 contextItems.forEach((item) => {
184183 item.icon = tool.faviconUrl;
modified core/tools/definitions/createRuleBlock.ts +5 −1
@@ -13,7 +13,7 @@
1313 function: {
1414 name: BuiltInToolNames.CreateRuleBlock,
1515 description:
16- "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.",
16+ "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
1717 parameters: {
1818 type: "object",
1919 required: ["name", "rule"],
@@ -28,6 +28,10 @@
2828 description:
2929 "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
3030 },
31+ description: {
32+ type: "string",
33+ description: "Short description of the rule",
34+ },
3135 globs: {
3236 type: "string",
3337 description:
modified core/tools/implementations/createRuleBlock.test.ts +54 −36
@@ -1,4 +1,4 @@
1-import * as YAML from "yaml";
1+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
22 import { createRuleBlockImpl } from "./createRuleBlock";
33
44 // Mock the extras parameter with necessary functions
@@ -17,33 +17,6 @@
1717 jest.clearAllMocks();
1818 });
1919
20- it("should create a basic rule with name and rule content", async () => {
21- const args = {
22- name: "Test Rule",
23- rule: "Always write tests",
24- };
25-
26- const result = await createRuleBlockImpl(args, mockExtras as any);
27-
28- // Verify that writeFile was called with the correct YAML
29- expect(mockIde.writeFile).toHaveBeenCalled();
30- const yamlContent = mockIde.writeFile.mock.calls[0][1];
31- const parsedYaml = YAML.parse(yamlContent);
32-
33- // Verify the structure of the YAML
34- expect(parsedYaml).toEqual({
35- name: "Test Rule",
36- version: "0.0.1",
37- schema: "v1",
38- rules: [
39- {
40- name: "Test Rule",
41- rule: "Always write tests",
42- },
43- ],
44- });
45- });
46-
4720 it("should create a rule with glob pattern", async () => {
4821 const args = {
4922 name: "TypeScript Rule",
@@ -53,14 +26,16 @@
5326
5427 await createRuleBlockImpl(args, mockExtras as any);
5528
56- // Verify the YAML structure with globs
57- const yamlContent = mockIde.writeFile.mock.calls[0][1];
58- const parsedYaml = YAML.parse(yamlContent);
59- expect(parsedYaml.rules[0]).toEqual({
60- name: "TypeScript Rule",
61- rule: "Use interfaces for object shapes",
29+ const fileContent = mockIde.writeFile.mock.calls[0][1];
30+
31+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
32+
33+ expect(frontmatter).toEqual({
6234 globs: "**/*.{ts,tsx}",
6335 });
36+
37+ expect(markdown).toContain("# TypeScript Rule");
38+ expect(markdown).toContain("Use interfaces for object shapes");
6439 });
6540
6641 it("should create a filename based on sanitized rule name", async () => {
@@ -71,8 +46,51 @@
7146
7247 await createRuleBlockImpl(args, mockExtras as any);
7348
74- // Check that the filename is sanitized
7549 const fileUri = mockIde.writeFile.mock.calls[0][0];
76- expect(fileUri).toContain("special-chracters-spaces.yaml");
50+ expect(fileUri).toContain("special-chracters-spaces.md");
51+ });
52+
53+ it("should create a rule with description pattern", async () => {
54+ const args = {
55+ name: "Description Test",
56+ rule: "This is the rule content",
57+ description: "This is a detailed explanation of the rule",
58+ };
59+
60+ await createRuleBlockImpl(args, mockExtras as any);
61+
62+ const fileContent = mockIde.writeFile.mock.calls[0][1];
63+
64+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
65+
66+ expect(frontmatter).toEqual({
67+ description: "This is a detailed explanation of the rule",
68+ });
69+
70+ expect(markdown).toContain("# Description Test");
71+ expect(markdown).toContain("This is the rule content");
72+ });
73+
74+ it("should include both globs and description in frontmatter", async () => {
75+ const args = {
76+ name: "Complete Rule",
77+ rule: "Follow this standard",
78+ description: "This rule enforces our team standards",
79+ globs: "**/*.js",
80+ };
81+
82+ await createRuleBlockImpl(args, mockExtras as any);
83+
84+ const fileContent = mockIde.writeFile.mock.calls[0][1];
85+
86+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
87+
88+ expect(frontmatter).toEqual({
89+ description: "This rule enforces our team standards",
90+ globs: "**/*.js",
91+ });
92+
93+ expect(markdown).toContain("# Complete Rule");
94+ expect(markdown).toContain("Follow this standard");
7795 });
7896 });
modified core/tools/implementations/createRuleBlock.ts +22 −17
@@ -1,4 +1,3 @@
1-import { ConfigYaml } from "@continuedev/config-yaml";
21 import * as YAML from "yaml";
32 import { ToolImpl } from ".";
43 import { joinPathsToUri } from "../../util/uri";
@@ -6,6 +5,7 @@
65 export interface CreateRuleBlockArgs {
76 name: string;
87 rule: string;
8+ description: string;
99 globs?: string;
1010 }
1111
@@ -19,41 +19,46 @@
1919 .replace(/[^a-z0-9\s-]/g, "")
2020 .replace(/\s+/g, "-");
2121
22- const ruleObject = {
23- name: args.name,
24- rule: args.rule,
25- ...(args.globs ? { globs: args.globs.trim() } : {}),
26- };
22+ const fileExtension = "md";
2723
28- const ruleBlock: ConfigYaml = {
29- name: args.name,
30- version: "0.0.1",
31- schema: "v1",
32- rules: [ruleObject],
33- };
24+ const frontmatter: Record<string, string> = {};
3425
35- const ruleYaml = YAML.stringify(ruleBlock);
26+ if (args.globs) {
27+ frontmatter.globs = args.globs.trim();
28+ }
3629
30+ if (args.description) {
31+ frontmatter.description = args.description.trim();
32+ }
33+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
34+ let fileContent = `---
35+${frontmatterYaml}
36+---
37+
38+# ${args.name}
39+
40+${args.rule}
41+`;
3742 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
3843 const rulesDirUri = joinPathsToUri(
3944 localContinueDir,
4045 ".continue",
4146 "rules",
42- `${safeRuleName}.yaml`,
47+ `${safeRuleName}.${fileExtension}`,
4348 );
4449
45- await extras.ide.writeFile(rulesDirUri, ruleYaml);
50+ await extras.ide.writeFile(rulesDirUri, fileContent);
4651 await extras.ide.openFile(rulesDirUri);
4752
4853 return [
4954 {
5055 name: "New Rule Block",
51- description: "", // No description throws an error in the GUI
56+ description: args.description || "",
5257 uri: {
5358 type: "file",
5459 value: rulesDirUri,
5560 },
56- content: "Rule created successfully",
61+ content: `Rule created successfully`,
5762 },
5863 ];
5964 };
added core/util/abortManager.ts +37 −0
@@ -0,0 +1,37 @@
1+export class StreamAbortManager {
2+ private static instance: StreamAbortManager;
3+ private controllers: Map<string, AbortController>;
4+
5+ private constructor() {
6+ this.controllers = new Map();
7+ }
8+
9+ public static getInstance(): StreamAbortManager {
10+ if (!StreamAbortManager.instance) {
11+ StreamAbortManager.instance = new StreamAbortManager();
12+ }
13+ return StreamAbortManager.instance;
14+ }
15+
16+ public get(id: string): AbortController {
17+ let controller = this.controllers.get(id);
18+ if (!controller) {
19+ controller = new AbortController();
20+ this.controllers.set(id, controller);
21+ }
22+ return controller;
23+ }
24+
25+ public abort(id: string): void {
26+ const controller = this.controllers.get(id);
27+ if (controller) {
28+ controller.abort();
29+ this.controllers.delete(id);
30+ }
31+ }
32+
33+ public clear(): void {
34+ this.controllers.forEach((controller) => controller.abort());
35+ this.controllers.clear();
36+ }
37+}
modified core/util/parameters.ts +1 −0
@@ -6,6 +6,7 @@
66 prefixPercentage: 0.3,
77 maxSuffixPercentage: 0.2,
88 debounceDelay: 350,
9+ modelTimeout: 150,
910 multilineCompletions: "auto",
1011 // @deprecated TO BE REMOVED
1112 slidingWindowPrefixPercentage: 0.75,
added core/util/shellPath.ts +29 −0
@@ -0,0 +1,29 @@
1+import { execSync } from "child_process";
2+
3+/**
4+ * Gets the PATH env var from the user's login shell on non-Windows platforms.
5+ * Windows is not implemented primarily because it is not needed at the moment.
6+ * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined
7+ */
8+export function getEnvPathFromUserShell(): string | undefined {
9+ if (process.platform === "win32") {
10+ console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
11+ return undefined;
12+ }
13+
14+ if (!process.env.SHELL) {
15+ return undefined;
16+ }
17+
18+ try {
19+ const command = `${process.env.SHELL} -l -c 'echo $PATH'`;
20+
21+ const stdout = execSync(command, {
22+ encoding: "utf8",
23+ });
24+
25+ return stdout.trim();
26+ } catch (error) {
27+ return process.env.PATH; // Fallback to current PATH
28+ }
29+}
modified core/vendor/.gitignore +1 −1
@@ -1,1 +1,1 @@
1-!node_modules
No newline at the end of the file
1+node_modules
No newline at the end of the file
modified core/vendor/package-lock.json +105 −17
@@ -10,6 +10,9 @@
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@xenova/transformers": "^2.14.0"
13+ },
14+ "engines": {
15+ "node": ">=20.19.0"
1316 }
1417 },
1518 "node_modules/@huggingface/jinja": {
@@ -105,6 +108,78 @@
105108 "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
106109 "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
107110 },
111+ "node_modules/bare-events": {
112+ "version": "2.5.4",
113+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
114+ "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
115+ "license": "Apache-2.0",
116+ "optional": true
117+ },
118+ "node_modules/bare-fs": {
119+ "version": "4.1.5",
120+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz",
121+ "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==",
122+ "license": "Apache-2.0",
123+ "optional": true,
124+ "dependencies": {
125+ "bare-events": "^2.5.4",
126+ "bare-path": "^3.0.0",
127+ "bare-stream": "^2.6.4"
128+ },
129+ "engines": {
130+ "bare": ">=1.16.0"
131+ },
132+ "peerDependencies": {
133+ "bare-buffer": "*"
134+ },
135+ "peerDependenciesMeta": {
136+ "bare-buffer": {
137+ "optional": true
138+ }
139+ }
140+ },
141+ "node_modules/bare-os": {
142+ "version": "3.6.1",
143+ "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
144+ "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
145+ "license": "Apache-2.0",
146+ "optional": true,
147+ "engines": {
148+ "bare": ">=1.14.0"
149+ }
150+ },
151+ "node_modules/bare-path": {
152+ "version": "3.0.0",
153+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
154+ "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
155+ "license": "Apache-2.0",
156+ "optional": true,
157+ "dependencies": {
158+ "bare-os": "^3.0.1"
159+ }
160+ },
161+ "node_modules/bare-stream": {
162+ "version": "2.6.5",
163+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
164+ "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
165+ "license": "Apache-2.0",
166+ "optional": true,
167+ "dependencies": {
168+ "streamx": "^2.21.0"
169+ },
170+ "peerDependencies": {
171+ "bare-buffer": "*",
172+ "bare-events": "*"
173+ },
174+ "peerDependenciesMeta": {
175+ "bare-buffer": {
176+ "optional": true
177+ },
178+ "bare-events": {
179+ "optional": true
180+ }
181+ }
182+ },
108183 "node_modules/base64-js": {
109184 "version": "1.5.1",
110185 "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -444,9 +519,10 @@
444519 }
445520 },
446521 "node_modules/prebuild-install/node_modules/tar-fs": {
447- "version": "2.1.1",
448- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
449- "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
522+ "version": "2.1.2",
523+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
524+ "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
525+ "license": "MIT",
450526 "dependencies": {
451527 "chownr": "^1.1.1",
452528 "mkdirp-classic": "^0.5.2",
@@ -503,11 +579,6 @@
503579 "once": "^1.3.1"
504580 }
505581 },
506- "node_modules/queue-tick": {
507- "version": "1.0.1",
508- "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
509- "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
510- },
511582 "node_modules/rc": {
512583 "version": "1.2.8",
513584 "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
@@ -642,12 +713,16 @@
642713 }
643714 },
644715 "node_modules/streamx": {
645- "version": "2.15.6",
646- "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz",
647- "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==",
716+ "version": "2.22.0",
717+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz",
718+ "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==",
719+ "license": "MIT",
648720 "dependencies": {
649- "fast-fifo": "^1.1.0",
650- "queue-tick": "^1.0.1"
721+ "fast-fifo": "^1.3.2",
722+ "text-decoder": "^1.1.0"
723+ },
724+ "optionalDependencies": {
725+ "bare-events": "^2.2.0"
651726 }
652727 },
653728 "node_modules/string_decoder": {
@@ -667,13 +742,17 @@
667742 }
668743 },
669744 "node_modules/tar-fs": {
670- "version": "3.0.4",
671- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz",
672- "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==",
745+ "version": "3.0.8",
746+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
747+ "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
748+ "license": "MIT",
673749 "dependencies": {
674- "mkdirp-classic": "^0.5.2",
675750 "pump": "^3.0.0",
676751 "tar-stream": "^3.1.5"
752+ },
753+ "optionalDependencies": {
754+ "bare-fs": "^4.0.1",
755+ "bare-path": "^3.0.0"
677756 }
678757 },
679758 "node_modules/tar-stream": {
@@ -686,6 +765,15 @@
686765 "streamx": "^2.15.0"
687766 }
688767 },
768+ "node_modules/text-decoder": {
769+ "version": "1.2.3",
770+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz",
771+ "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==",
772+ "license": "Apache-2.0",
773+ "dependencies": {
774+ "b4a": "^1.6.4"
775+ }
776+ },
689777 "node_modules/tunnel-agent": {
690778 "version": "0.6.0",
691779 "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
deleted docs/CHANGELOG.md +0 −7
@@ -1,7 +0,0 @@
1-# Changelog
2-All notable changes to this project will be documented in this file.
3-
4-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
6-and is generated by [Changie](https://github.com/miniscruff/changie).
7-
added docs/docs/CLA.md +48 −0
@@ -0,0 +1,48 @@
1+# Individual Contributor License Agreement (v1.0, Continue)
2+
3+_Based on the Apache Software Foundation Individual CLA v 2.2._
4+
5+By commenting **“I have read the CLA Document and I hereby sign the CLA”**
6+on a Pull Request, **you (“Contributor”) agree to the following terms** for any
7+past and future “Contributions” submitted to **Continue (the “Project”)**.
8+
9+---
10+
11+## 1. Definitions
12+
13+- **“Contribution”** – any original work of authorship submitted to the Project
14+ (code, documentation, designs, etc.).
15+- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
16+ comment.
17+
18+## 2. Copyright License
19+
20+You grant **Continue Dev, Inc.** and all recipients of software distributed by the
21+Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
22+license to reproduce, prepare derivative works of, publicly display, publicly
23+perform, sublicense, and distribute Your Contributions and derivative works.
24+
25+## 3. Patent License
26+
27+You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
28+worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
29+license to make, have made, use, sell, offer to sell, import, and otherwise
30+transfer Your Contributions alone or in combination with the Project.
31+
32+If any entity brings patent litigation alleging that the Project or a
33+Contribution infringes a patent, the patent licenses granted by You to that
34+entity under this CLA terminate.
35+
36+## 4. Representations
37+
38+1. You are legally entitled to grant the licenses above.
39+2. Each Contribution is either Your original creation or You have authority to
40+ submit it under this CLA.
41+3. Your Contributions are provided **“AS IS”** without warranties of any kind.
42+4. You will notify the Project if any statement above becomes inaccurate.
43+
44+## 5. Miscellany
45+
46+This Agreement is governed by the laws of the **State of California**, USA,
47+excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
48+the remaining provisions remain in force.
added docs/docs/customize/changelog.md +13 −0
@@ -0,0 +1,13 @@
1+---
2+title: Continue Changelog
3+description: Redirecting to our Changelog
4+hide_table_of_contents: true
5+---
6+
7+# Redirecting to Changelog
8+
9+If you are not redirected automatically, follow this [link to the changelog](https://changelog.continue.dev).
10+
11+<head>
12+ <meta http-equiv="refresh" content="0;url=https://changelog.continue.dev" />
13+</head>
No newline at the end of the file
deleted docs/docs/customize/changelog.mdx +0 −30
@@ -1,30 +0,0 @@
1----
2-title: Changelog
3-description: Changelogs for the latest releases of the VSCode and JetBrains extensions
4-keywords: [changelog]
5-hide_table_of_contents: true
6----
7-
8-import VSCodeChangelog from "../../../extensions/vscode/CHANGELOG.md";
9-import JetBrainsChangelog from "../../../extensions/intellij/CHANGELOG.md";
10-
11-Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates.
12-
13-import TOCInline from "@theme/TOCInline";
14-
15-<TOCInline
16- toc={toc.filter(
17- (node) =>
18- node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
19- )}
20-/>
21-
22-<hr />
23-
24-## VSCode Changelog
25-
26-<VSCodeChangelog />
27-
28-## JetBrains Changelog
29-
30-<JetBrainsChangelog />
modified docs/docs/customize/deep-dives/settings.md +12 −4
@@ -6,11 +6,11 @@
66
77 # The User Settings Page
88
9-The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar.
9+The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar and then selecting the "Settings" tab.
1010
11-![slash-commands](/img/header-buttons.png)
11+![settings](/img/settings-header.png)
1212
13-Which takes you to this page:
13+Which takes you to this page (select the "Settings" tab):
1414
1515 ![User Settings Page](/img/settings-page.png)
1616
@@ -26,7 +26,15 @@
2626 - `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default.
2727 - `Font Size`: Specifies base font size for UI elements
2828 - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
29-- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"
29+- `Autocomplete timeout`: Maximum time in milliseconds for autocomplete request/retreival. Defaults to 150
30+- `Autocomplete debounce`: Minimum time in milliseconds to trigger an autocomplete request after a change. Defaults to 250
31+- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., `**/*.{txt,md}`
32+
33+### Experimental settings
34+
35+At the bottom of the User Settings page there is an "Experimental Settings" section which contains new or otherwise experimental settings, including:
36+
37+- `Auto-Accept Agent Edits`: **CAUTION: Be very careful with this setting. When turned on, Agent mode's edit tool can make changes to files with no manual review or guaranteed stopping point. If on, diffs generated by the edit tool are automatically accepted and Agent proceeds with the next conversational turn.** Off by default.
3038
3139 <!-- - `Use autocomplete cache`: If on, caches completions. -->
3240 <!-- - `Use Chromium for Docs Crawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to ~/.continue/.utils. Off by default -->
modified docs/docs/reference.md +9 −7
@@ -47,10 +47,6 @@
4747 Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other
4848 `uses` clauses or explicit blocks of that type.
4949
50-:::info
51-Note that local assistants cannot use blocks that require organization-level secrets.
52-:::
53-
5450 For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one.
5551
5652 ```yaml title="Assistant models section"
@@ -85,6 +81,12 @@
8581 You can find many examples of each of these block types on
8682 the [Continue Explore Page](https://hub.continue.dev/explore/models)
8783
84+:::info
85+Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values:
86+- globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`)
87+- per-workspace, from a `.env` file located at the root of the current workspace.
88+:::
89+
8890 ### Inputs
8991
9092 Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use
@@ -111,7 +113,7 @@
111113 TEMP: 0.9
112114 ```
113115
114-Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`.
116+Note that hub secrets can be passed as inputs, using a similar mustache format: `secrets.SECRET_NAME`.
115117
116118 ### Overrides
117119
@@ -186,6 +188,7 @@
186188 not currently used.
187189 - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
188190 provider and model. Supported capabilities include `tool_use` and `image_input`.
191+- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
189192 - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
190193 `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
191194 `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@@ -204,7 +207,6 @@
204207 - `topP`: The cumulative probability for nucleus sampling.
205208 - `topK`: Maximum number of tokens considered at each step.
206209 - `stop`: An array of stop tokens that will terminate the completion.
207- - `n`: Number of completions to generate.
208210 - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
209211 - `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
210212 - `requestOptions`: HTTP request options specific to the model.
@@ -405,7 +407,7 @@
405407 - `destination` (**required**): The destination/endpoint that will receive the data. Can be:
406408 - an HTTP endpoint that will receive a POST request with a JSON blob
407409 - a file URL to a directory in which events will be dumpted to `.jsonl` files
408-- `schema` (**required**): the schema version of the JSON blobs to be sent
410+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
409411 - `events`: an array of event names to include. Defaults to all events if not specified.
410412 - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
411413 contents, prompts, and completions. Defaults to `all`
modified docs/docs/troubleshooting.mdx +2 −2
@@ -7,8 +7,6 @@
77 import TabItem from "@theme/TabItem";
88 import Tabs from "@theme/Tabs";
99
10-The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below.
11-
1210 1. [Check the logs](#check-the-logs)
1311 2. [Try the latest pre-release](#download-the-latest-pre-release)
1412 3. [Download an older version](#download-an-older-version)
@@ -122,6 +120,8 @@
122120
123121 You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
124122
123+***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
124+
125125 #### VS Code Proxy Settings
126126
127127 If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
modified docs/docusaurus.config.js +6 −0
@@ -65,6 +65,12 @@
6565 ],
6666 ],
6767
68+ scripts: [
69+ {
70+ src: "/scripts/custom-reo.js", // it references from static folder
71+ },
72+ ],
73+
6874 themeConfig:
6975 /** @type {import("@docusaurus/preset-classic").ThemeConfig} */
7076 ({
deleted docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx +0 −30
@@ -1,30 +0,0 @@
1----
2-title: 变更日志
3-description: VSCode 和 JetBrains 扩展最新版本的变更日志
4-keywords: [变更日志]
5-hide_table_of_contents: true
6----
7-
8-import VSCodeChangelog from "../../../../../../extensions/vscode/CHANGELOG.md";
9-import JetBrainsChangelog from "../../../../../../extensions/intellij/CHANGELOG.md";
10-
11-以下是 VSCode 和 JetBrains 扩展最新版本的变更日志。在 2024-07-02 之前,变更日志没有反映所有更新。
12-
13-import TOCInline from "@theme/TOCInline";
14-
15-<TOCInline
16- toc={toc.filter(
17- (node) =>
18- node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
19- )}
20-/>
21-
22-<hr />
23-
24-## VSCode 变更日志
25-
26-<VSCodeChangelog />
27-
28-## JetBrains 变更日志
29-
30-<JetBrainsChangelog />
deleted docs/static/img/header-buttons.png +0 −0

Binary content is not shown. View the file.

added docs/static/img/settings-header.png +0 −0

Binary content is not shown. View the file.

added docs/static/scripts/custom-reo.js +1 −0
@@ -0,0 +1,1 @@
1+!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
No newline at the end of the file
modified extensions/intellij/.run/Start Core Dev Server (CE).run.xml +1 −1
@@ -1,6 +1,6 @@
11 <component name="ProjectRunConfigurationManager">
22 <configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
3- <option name="SCRIPT_TEXT" value="cross-env 'PROJECT_DIR=&quot;$PROJECT_DIR$&quot;' node core-dev-server.js" />
3+ <option name="SCRIPT_TEXT" value="npx cross-env 'PROJECT_DIR=&quot;$PROJECT_DIR$&quot;' node core-dev-server.js" />
44 <option name="INDEPENDENT_SCRIPT_PATH" value="true" />
55 <option name="SCRIPT_PATH" value="" />
66 <option name="SCRIPT_OPTIONS" value="" />
deleted extensions/intellij/CHANGELOG.md +0 −104
@@ -1,104 +0,0 @@
1-All notable changes to this project will be documented in this file.
2-
3-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
4-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
5-and is generated by [Changie](https://github.com/miniscruff/changie).
6-
7-
8-## 1.0.0 - 2025-02-26
9-### Added
10-* Introduces hub.continue.dev
11-* Improved theme matching
12-### Fixed
13-* Fixes interference between SonarQube and Continue autocomplete
14-* Numerous reliability improvements
15-
16-## 0.0.92 - 2025-02-26
17-### Fixed
18-* Off-screen rendering to solve white flash on load and lack of changing cursor type
19-* OSR-related fixes for non-Mac users
20-* Fixes for inline edit in JetBrains
21-
22-## 0.0.72 - 2024-10-04
23-### Added
24-* Listen for changes to Intellij settings without requiring window reload
25-### Changed
26-* Updated tutorial file
27-### Fixed
28-* Fix ability to load config.ts in JetBrains IDEs
29-
30-## 0.0.69 - 2024-09-22
31-### Added
32-* Support for the "search" context provider
33-### Fixed
34-* Fixed bug where only first module would be recognized
35-* Improved concurrency handling to avoid freezes
36-* Made compatible with latest JetBrains versions
37-
38-## 0.0.54 - 2024-07-13
39-### Added
40-* Partial autocomplete acceptance
41-* Autocomplete status bar spinner
42-### Fixed
43-* Fixed duplicate completion bug and others
44-
45-## 0.0.53 - 2024-07-10
46-### Added
47-* Support for .prompt files
48-* New onboarding experience
49-### Fixed
50-* Indexing fixes from VS Code versions merged into IntelliJ
51-* Improved codebase indexing reliability and testing
52-* Fixes for autocomplete text positioning and timing
53-
54-## 0.0.42 - 2024-04-12
55-### Added
56-* Inline cmd/ctrl+I in JetBrains
57-### Fixed
58-* Fixed character encoding error causing display issues
59-* Fixed error causing input to constantly demand focus
60-* Fixed automatic reloading of config.json
61-
62-## 0.0.38 - 2024-03-15
63-### Added
64-* Remote config server support
65-* Autocomplete support in JetBrains
66-
67-## 0.0.34 - 2024-03-03
68-### Added
69-* diff context provider
70-### Changed
71-* Allow LLM servers to handle templating
72-### Fixed
73-* Fix a few context providers / slash commands
74-* Fixed issues preventing proper extension startup
75-
76-## v0.0.26 - 2023-12-28
77-### Added
78-* auto-reloading of config on save
79-### Fixed
80-* Fixed /edit bug for versions without Python server
81-
82-## v0.0.25 - 2023-12-25
83-
84-### Changed
85-
86-- Intellij extension no longer relies on the Continue Python server
87-
88-## v0.0.21 - 2023-12-05
89-
90-### Added
91-
92-- updated to match latest VS Code updates
93-
94-## v0.0.19 - 2023-11-19
95-
96-### Changed
97-
98-- migrated to .json config file format
99-
100-## v0.0.1 - 2023-09-01
101-
102-### Added
103-
104-- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
modified extensions/intellij/CONTRIBUTING.md +6 −0
@@ -173,6 +173,12 @@
173173 ./gradlew test
174174 ```
175175
176+Run a single test
177+
178+```sh
179+./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
180+```
181+
176182 #### Identifying selectors
177183
178184 While the `runIdeForUiTests` task is running, you can visit the following URL
modified extensions/intellij/build.gradle.kts +4 −0
@@ -42,10 +42,12 @@
4242 implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
4343 testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
4444 testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
45+ testImplementation("io.mockk:mockk:1.14.2")
4546 testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
4647 testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
4748 testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
4849 implementation("com.automation-remarks:video-recorder-junit5:2.0")
50+ testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
4951
5052
5153 // Exclude vulnerable Log4j from all dependencies
@@ -62,6 +64,7 @@
6264 // Add Log4j 2.x explicitly
6365 implementation("org.apache.logging.log4j:log4j-core:2.20.0")
6466 implementation("org.apache.logging.log4j:log4j-api:2.20.0")
67+ testImplementation(kotlin("test"))
6568 }
6669
6770 // Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
@@ -162,6 +165,7 @@
162165 // This is to ensure we load the GUI with OSR enabled. We have logic that
163166 // renders with OSR disabled below a particular IDE version.
164167 // See ContinueExtensionSettingsService.kt for more info.
168+ // Currently commented out however since test fail in CI with this version
165169 // intellij {
166170 // version.set("2024.1")
167171 // }
modified extensions/intellij/gradle.properties +2 −2
@@ -3,13 +3,13 @@
33 pluginName=continue-intellij-extension
44 pluginRepositoryUrl=https://github.com/continuedev/continue
55 # SemVer format -> https://semver.org
6-pluginVersion=1.0.17
6+pluginVersion=1.0.18
77 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
88 pluginSinceBuild=223
99 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
1010 platformType=IC
1111 platformVersion=2022.3.3
12-#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
12+# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
1313 #platformVersion = LATEST-EAP-SNAPSHOT
1414 # Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
1515 # Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +11 −7
@@ -11,15 +11,19 @@
1111 class ContinueActionPromote : ActionPromoter {
1212
1313 override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
14-
15- if (actions.none { it is AcceptAutocompleteAction }) {
16- return null
17- } else {
14+ // For autocomplete actions
15+ if (actions.any { it is AcceptAutocompleteAction }) {
1816 val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
19- if (!settings.continueState.showIDECompletionSideBySide) {
20- return null;
17+ if (settings.continueState.showIDECompletionSideBySide) {
18+ return actions.filterIsInstance<AcceptAutocompleteAction>()
2119 }
22- return actions.filterIsInstance<AcceptAutocompleteAction>()
2320 }
21+
22+ val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
23+ if (rejectDiffActions.isNotEmpty()) {
24+ return rejectDiffActions
25+ }
26+
27+ return null
2428 }
2529 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +6 −38
@@ -1,25 +1,12 @@
11 package com.github.continuedev.continueintellijextension.actions
22
33 import com.github.continuedev.continueintellijextension.editor.DiffStreamService
4-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
54 import com.intellij.openapi.actionSystem.AnAction
65 import com.intellij.openapi.actionSystem.AnActionEvent
76 import com.intellij.openapi.actionSystem.PlatformDataKeys
8-import com.intellij.openapi.components.ServiceManager
97 import com.intellij.openapi.components.service
108 import com.intellij.openapi.fileEditor.FileEditorManager
11-import com.intellij.openapi.project.Project
12-import com.intellij.openapi.wm.ToolWindowManager
13-
14-fun getPluginService(project: Project?): ContinuePluginService? {
15- if (project == null) {
16- return null
17- }
18- return ServiceManager.getService(
19- project,
20- ContinuePluginService::class.java
21- )
22-}
9+
2310
2411 class AcceptDiffAction : AnAction() {
2512 override fun actionPerformed(e: AnActionEvent) {
@@ -29,7 +16,7 @@
2916
3017 private fun acceptHorizontalDiff(e: AnActionEvent) {
3118 val continuePluginService = getPluginService(e.project) ?: return
32- continuePluginService?.diffManager?.acceptDiff(null)
19+ continuePluginService.diffManager?.acceptDiff(null)
3320 }
3421
3522 private fun acceptVerticalDiff(e: AnActionEvent) {
@@ -61,28 +48,6 @@
6148 }
6249 }
6350
64-fun getContinuePluginService(project: Project?): ContinuePluginService? {
65- if (project != null) {
66- val toolWindowManager = ToolWindowManager.getInstance(project)
67- val toolWindow = toolWindowManager.getToolWindow("Continue")
68-
69- if (toolWindow != null) {
70- if (!toolWindow.isVisible) {
71- toolWindow.activate(null)
72- }
73- }
74- }
75-
76- return getPluginService(project)
77-}
78-
79-fun focusContinueInput(project: Project?) {
80- val continuePluginService = getContinuePluginService(project) ?: return
81- continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
82- continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
83-
84- continuePluginService.ideProtocolClient?.sendHighlightedCode()
85-}
8651
8752 class FocusContinueInputWithoutClearAction : AnAction() {
8853 override fun actionPerformed(e: AnActionEvent) {
@@ -134,8 +99,11 @@
13499 if (logFile.exists()) {
135100 val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
136101 if (virtualFile != null) {
137- com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
102+ FileEditorManager.getInstance(project).openFile(virtualFile, true)
138103 }
139104 }
140105 }
141106 }
107+
108+
109+
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +39 −0
@@ -0,0 +1,39 @@
1+package com.github.continuedev.continueintellijextension.actions
2+
3+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4+import com.intellij.openapi.components.ServiceManager
5+import com.intellij.openapi.project.Project
6+import com.intellij.openapi.wm.ToolWindowManager
7+
8+fun getContinuePluginService(project: Project?): ContinuePluginService? {
9+ if (project != null) {
10+ val toolWindowManager = ToolWindowManager.getInstance(project)
11+ val toolWindow = toolWindowManager.getToolWindow("Continue")
12+
13+ if (toolWindow != null) {
14+ if (!toolWindow.isVisible) {
15+ toolWindow.activate(null)
16+ }
17+ }
18+ }
19+
20+ return getPluginService(project)
21+}
22+
23+fun focusContinueInput(project: Project?) {
24+ val continuePluginService = getContinuePluginService(project) ?: return
25+ continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
26+ continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
27+
28+ continuePluginService.ideProtocolClient?.sendHighlightedCode()
29+}
30+
31+fun getPluginService(project: Project?): ContinuePluginService? {
32+ if (project == null) {
33+ return null
34+ }
35+ return ServiceManager.getService(
36+ project,
37+ ContinuePluginService::class.java
38+ )
39+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +0 −1
@@ -1,6 +1,5 @@
11 package com.github.continuedev.continueintellijextension.activities
22
3-import IntelliJIDE
43 import com.intellij.openapi.fileEditor.FileEditorManagerListener
54 import com.github.continuedev.continueintellijextension.auth.AuthListener
65 import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt +0 −29
@@ -1,29 +0,0 @@
1-package com.github.continuedev.continueintellijextension.autocomplete
2-
3-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
4-import com.intellij.openapi.actionSystem.ActionUpdateThread
5-import com.intellij.openapi.actionSystem.AnActionEvent
6-import com.intellij.openapi.actionSystem.DefaultActionGroup
7-import com.intellij.openapi.components.service
8-
9-class AutocompleteActionGroup : DefaultActionGroup() {
10- override fun getActionUpdateThread(): ActionUpdateThread {
11- return ActionUpdateThread.EDT
12- }
13-
14- override fun update(e: AnActionEvent) {
15- super.update(e)
16- removeAll()
17-
18- val continueSettingsService = service<ContinueExtensionSettings>()
19- if (continueSettingsService.continueState.enableTabAutocomplete) {
20- addAll(
21- DisableTabAutocompleteAction(),
22- )
23- } else {
24- addAll(
25- EnableTabAutocompleteAction(),
26- )
27- }
28- }
29-}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +187 −0
@@ -0,0 +1,187 @@
1+package com.github.continuedev.continueintellijextension.`continue`
2+
3+import com.github.continuedev.continueintellijextension.ApplyState
4+import com.github.continuedev.continueintellijextension.ApplyStateStatus
5+import com.github.continuedev.continueintellijextension.IDE
6+import com.github.continuedev.continueintellijextension.ToastType
7+import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
8+import com.github.continuedev.continueintellijextension.editor.DiffStreamService
9+import com.github.continuedev.continueintellijextension.editor.EditorUtils
10+import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
11+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
12+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
13+import com.intellij.openapi.editor.Editor
14+import com.intellij.openapi.project.Project
15+import kotlinx.coroutines.suspendCancellableCoroutine
16+import kotlin.coroutines.resume
17+import kotlin.coroutines.resumeWithException
18+
19+/**
20+ * Handles applying text to a file with streaming diff preview
21+ */
22+class ApplyToFileHandler(
23+ private val project: Project,
24+ private val continuePluginService: ContinuePluginService,
25+ private val ide: IDE,
26+ private val params: ApplyToFileParams,
27+ private val editorUtils: EditorUtils?,
28+ private val diffStreamService: DiffStreamService
29+) {
30+
31+ suspend fun handleApplyToFile() {
32+ // Notify webview that we're starting to stream
33+ notifyStreamStarted()
34+
35+ if (editorUtils == null) {
36+ ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
37+ notifyStreamClosed()
38+ return
39+ }
40+
41+ if (editorUtils.isDocumentEmpty()) {
42+ editorUtils.insertTextIntoEmptyDocument(params.text)
43+ notifyStreamClosed()
44+ return
45+ }
46+
47+ // Get the LLM configuration for applying edits
48+ val llm = fetchApplyLLMConfig() ?: run {
49+ ide.showToast(ToastType.ERROR, "Failed to fetch model configuration")
50+ notifyStreamClosed()
51+ return
52+ }
53+
54+ setupAndStreamDiffs(editorUtils, llm)
55+ }
56+
57+ private fun notifyStreamStarted() {
58+ sendApplyStateUpdate(ApplyStateStatus.STREAMING)
59+ }
60+
61+ private fun notifyStreamClosed(numDiffs: Int? = 0) {
62+ sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs)
63+ }
64+
65+ private fun sendApplyStateUpdate(
66+ status: ApplyStateStatus,
67+ numDiffs: Int? = null
68+ ) {
69+ val payload = ApplyState(
70+ streamId = params.streamId,
71+ status = status.status,
72+ numDiffs = numDiffs,
73+ filepath = params.filepath,
74+ fileContent = params.text,
75+ toolCallId = params.toolCallId.toString()
76+ )
77+
78+ continuePluginService.sendToWebview("updateApplyState", payload)
79+ }
80+
81+ private suspend fun fetchApplyLLMConfig(): Any? {
82+ return try {
83+ suspendCancellableCoroutine { continuation ->
84+ continuePluginService.coreMessenger?.request(
85+ "config/getSerializedProfileInfo",
86+ null,
87+ null
88+ ) { response ->
89+ try {
90+ val selectedModels = response.castNestedOrNull<Map<String, Any>>(
91+ "content",
92+ "result",
93+ "config",
94+ "selectedModelByRole"
95+ )
96+
97+ // If "apply" role model is not found, try "chat" role
98+ val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
99+
100+ if (applyCodeBlockModel != null) {
101+ continuation.resume(applyCodeBlockModel)
102+ } else {
103+ // If neither "apply" nor "chat" models are available, return with exception
104+ continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
105+ }
106+ } catch (e: Exception) {
107+ continuation.resumeWithException(e)
108+ }
109+ }
110+ }
111+ } catch (_: Exception) {
112+ null
113+ }
114+ }
115+
116+ private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) {
117+ // Clear all diff blocks before running the diff stream
118+ diffStreamService.reject(editorUtils.editor)
119+
120+ val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
121+ val prompt = buildApplyPrompt()
122+
123+ // Extract the code ranges (highlighted or full document)
124+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
125+
126+ // Get the line range for the diff stream
127+ val rif = editorUtils.getHighlightedRIF()
128+ val startLine = rif?.range?.start?.line ?: 0
129+ val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)
130+
131+ // Create and register the diff stream handler
132+ val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine)
133+ diffStreamService.register(diffStreamHandler, editorUtils.editor)
134+
135+ // Stream the diffs
136+ diffStreamHandler.streamDiffLinesToEditor(
137+ prompt, prefix, highlighted, suffix, llmTitle, false
138+ )
139+ }
140+
141+ private fun buildApplyPrompt(): String {
142+ return "The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
143+ }
144+
145+ private fun createDiffStreamHandler(
146+ editor: Editor,
147+ startLine: Int,
148+ endLine: Int
149+ ): DiffStreamHandler {
150+ return DiffStreamHandler(
151+ project,
152+ editor,
153+ startLine,
154+ endLine,
155+ {},
156+ {},
157+ params.streamId,
158+ params.toolCallId.toString()
159+ )
160+ }
161+
162+ companion object {
163+ /**
164+ * Factory method to create and execute a new handler for a single apply-to-file operation
165+ */
166+ suspend fun apply(
167+ project: Project,
168+ continuePluginService: ContinuePluginService,
169+ ide: IDE,
170+ params: ApplyToFileParams
171+ ) {
172+ val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath)
173+ val diffStreamService = project.getService(DiffStreamService::class.java)
174+
175+ val handler = ApplyToFileHandler(
176+ project,
177+ continuePluginService,
178+ ide,
179+ params,
180+ editorUtils,
181+ diffStreamService
182+ )
183+
184+ handler.handleApplyToFile()
185+ }
186+ }
187+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +6 −5
@@ -62,7 +62,7 @@
6262 file.createNewFile()
6363 }
6464 file.writeText(replacement)
65- openDiffWindow(URI(filepath).toString(), file.toURI().toString(), stepIndex)
65+ openDiffWindow(UriUtils.parseUri(filepath).toString(), file.toURI().toString(), stepIndex)
6666 }
6767
6868 private fun cleanUpFile(file2: String) {
@@ -80,7 +80,8 @@
8080 val diffInfo = diffInfoMap[file] ?: return
8181
8282 // Write contents to original file
83- val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(diffInfo.originalFilepath).path) ?: return
83+ val virtualFile =
84+ LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(diffInfo.originalFilepath).path) ?: return
8485 val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return
8586 WriteCommandAction.runWriteCommandAction(project) {
8687 document.setText(File(file).readText())
@@ -107,7 +108,7 @@
107108 )
108109 continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
109110 continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
110-
111+ continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
111112 cleanUpFile(file)
112113 }
113114
@@ -119,8 +120,8 @@
119120 lastFile2 = file2
120121
121122 // Create a DiffContent for each of the texts you want to compare
122- val content1: DiffContent = DiffContentFactory.getInstance().create(File(URI(file1)).readText())
123- val content2: DiffContent = DiffContentFactory.getInstance().create(File(URI(file2)).readText())
123+ val content1: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file1).readText())
124+ val content2: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file2).readText())
124125
125126 // Create a SimpleDiffRequest and populate it with the DiffContents and titles
126127 val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New")
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +146 −35
@@ -2,11 +2,13 @@
22
33 import com.intellij.openapi.editor.colors.EditorColors
44 import com.intellij.openapi.editor.colors.EditorColorsManager
5+import com.intellij.openapi.editor.colors.CodeInsightColors
56 import java.awt.Color
67 import kotlin.math.max
78 import kotlin.math.min
89 import com.intellij.ui.JBColor
910 import com.intellij.ui.ColorUtil
11+import kotlin.math.roundToInt
1012
1113 class GetTheme {
1214 fun getSecondaryDark(): Color {
@@ -38,64 +40,173 @@
3840 return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
3941 }
4042
41- fun getTheme(): Map<String, String> {
42- fun toHex(color: Color): String {
43- return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
43+ fun toHex(color: Color?): String? {
44+ if(color == null) {
45+ return null
4446 }
47+ return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
48+ }
49+
50+ fun namedColor(name: String): Color? {
51+ // JB Color named color will fall back to a default unless we give it a fallback
52+ // We want defaults to be handled on the GUI side, so we give it this filler color
53+ // Which has a very low chance of conflicting with a real one
54+ // And return undefined if it gets the skip color
55+ val SKIP_COLOR = Color (18, 52, 86) // Hex #123456
56+ val color = JBColor.namedColor(name, SKIP_COLOR)
57+ if(toHex(color) == "#123456") {
58+ return null
59+ }
60+ return color
61+ }
62+
63+ fun lighten(color: Color, percentage: Int = 5): Color {
64+ // Increase each RGB component slightly
65+ val factor = 1 + percentage / 100f;
66+ fun lightenInt(value: Int): Int {
67+ return (value * factor).roundToInt().coerceAtMost(255)
68+ }
69+ return Color(
70+ lightenInt(color.red),
71+ lightenInt (color.green),
72+ lightenInt(color.blue),
73+ color.alpha
74+ )
75+ }
76+
77+ fun darken(color: Color, percentage: Int = 5): Color {
78+ // Decrease each RGB component slightly
79+ val factor = 1 - percentage / 100f;
80+ fun darkenInt(value: Int): Int {
81+ return (value * factor).roundToInt().coerceAtLeast(0)
82+ }
83+ return Color(
84+ darkenInt(color.red),
85+ darkenInt(color.green),
86+ darkenInt(color.blue),
87+ color.alpha
88+ )
89+ }
90+
91+ fun slightChange(color: Color?, percentage: Int = 5): Color? {
92+ if(color == null){
93+ return null
94+ }
95+ // If dark, make slightly lighter. If light, make slightly darker
96+ val averageRgb = (color.red + color.green + color.blue) / 3
97+ return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage)
98+ }
99+
100+ fun getTheme(): Map<String, String?> {
45101 try {
102+ val editorScheme = EditorColorsManager.getInstance().globalScheme
103+
46104 val background = JBColor.background()
47105 val foreground = JBColor.foreground()
48106
49- val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230))
50- val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0))
107+ val border = JBColor.border()
108+ val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor")
51109
52- val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150))
53- val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0))
110+ val buttonBackground = namedColor("Button.default.startBackground")
111+ ?: namedColor("Button.default.background")
54112
55- val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255))
113+ val buttonForeground = namedColor("Button.default.startForeground")
114+ ?: namedColor("Button.default.foreground")
56115
57- val border = JBColor.border()
58- val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255))
59- val editorScheme = EditorColorsManager.getInstance().globalScheme
116+ val buttonHoverBackground = namedColor("Button.default.hoverStartBackground")
117+ ?: namedColor("Button.default.hoverBackground")
118+ ?: namedColor("Button.default.startHoverBackground")
119+ ?: slightChange(buttonBackground)
60120
61- val editorBackground = editorScheme.defaultBackground
62- val editorForeground = editorScheme.defaultForeground
121+ val secondaryBackground = namedColor("Button.background") ?: background
122+ val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground)
63123
64- val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220))
124+ val badgeBackground = namedColor("Badge.background")
125+ val badgeForeground = namedColor("Badge.foreground")
65126
66- val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0)
127+ val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background")
128+ val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground")
67129
68- val theme = mapOf(
69- "--vscode-editor-foreground" to toHex(editorForeground),
70- "--vscode-editor-background" to toHex(editorBackground),
130+ val inputBackground = namedColor("TextField.background")
131+ val inputForeground = namedColor("TextField.foreground")
132+ val inputPlaceholder = namedColor("TextField.inactiveForeground")
133+
134+ val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
135+ val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
136+
137+ val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
138+ val listSelectionForeground = namedColor("List.selectionForeground")
71139
72- "--vscode-button-background" to toHex(buttonBackground),
73- "--vscode-button-foreground" to toHex(buttonForeground),
140+ val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
74141
75- "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50",
142+ val mutedDescription = namedColor("Component.infoForeground")
143+ ?: namedColor("ContextHelp.foreground")
144+ ?: namedColor("TextField.placeholderForeground")
145+ ?: namedColor("Label.disabledForeground")
146+ ?: namedColor("ToolTip.foreground")
76147
77- "--vscode-quickInputList-focusForeground" to toHex(foreground),
78- "--vscode-quickInput-background" to toHex(inputBackground),
148+ val link = namedColor("Link.activeForeground")
79149
80- "--vscode-badge-background" to toHex(badgeBackground),
81- "--vscode-badge-foreground" to toHex(badgeForeground),
150+ val successColor = namedColor("ValidationSuccess.successColor")
151+ ?: namedColor("Component.successForeground")
152+ ?: namedColor("Label.successForeground")
153+ val warningColor = namedColor("ValidationWarning.warningColor")
154+ ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor
155+ ?: namedColor("Component.warningForeground")
156+ ?: namedColor("Label.warningForeground")
157+ val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground")
82158
83- "--vscode-input-background" to toHex(inputBackground),
84- "--vscode-input-border" to toHex(border),
85- "--vscode-sideBar-background" to toHex(background),
86- "--vscode-sideBar-border" to toHex(border),
87- "--vscode-focusBorder" to toHex(focusBorder),
159+ val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor")
88160
89- "--vscode-commandCenter-activeBorder" to toHex(focusBorder),
90- "--vscode-commandCenter-inactiveBorder" to toHex(border),
161+ val editorBackground = editorScheme.defaultBackground
162+ val editorForeground = editorScheme.defaultForeground
91163
92- "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40"
93- )
164+ val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
94165
166+ val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
167+ editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
168+
169+ // These should match the keys in GUI's theme.ts
170+ val theme = mapOf(
171+ "background" to background,
172+ "foreground" to foreground,
173+ "editor-background" to editorBackground,
174+ "editor-foreground" to editorForeground,
175+ "primary-background" to buttonBackground,
176+ "primary-foreground" to buttonForeground,
177+ "primary-hover" to buttonHoverBackground,
178+ "secondary-background" to secondaryBackground,
179+ "secondary-foreground" to foreground,
180+ "secondary-hover" to secondaryHoverBackground,
181+ "border" to border,
182+ "border-focus" to focusBorder,
183+ "command-background" to commandBackground,
184+ "command-foreground" to commandForeground,
185+ "command-border" to border,
186+ "command-border-focus" to focusBorder,
187+ "description" to description,
188+ "description-muted" to mutedDescription,
189+ "input-background" to inputBackground,
190+ "input-foreground" to inputForeground,
191+ "input-border" to border,
192+ "input-placeholder" to inputPlaceholder,
193+ "table-oddRow" to tableOddRow,
194+ "badge-background" to badgeBackground,
195+ "badge-foreground" to badgeForeground,
196+ "success" to successColor,
197+ "warning" to warningColor,
198+ "error" to errorColor,
199+ "link" to link,
200+ "accent" to accentColor,
201+ "find-match" to findMatchBackground,
202+ "find-match-selected" to findMatchSelectedBackground,
203+ "list-hover" to listHoverBackground,
204+ "list-active" to actionHoverBackground,
205+ "list-active-foreground" to listSelectionForeground
206+ ).mapValues { toHex(it.value) }
95207 return theme
96208 } catch (error: Error) {
97209 return mapOf()
98210 }
99-
100211 }
101212 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt +1 −3
@@ -7,9 +7,7 @@
77 import kotlinx.coroutines.Dispatchers
88 import kotlinx.coroutines.withContext
99 import java.io.BufferedReader
10-import java.io.File
1110 import java.io.InputStreamReader
12-import java.net.URI
1311
1412 class GitService(
1513 private val project: Project,
@@ -52,7 +50,7 @@
5250 } else {
5351 ProcessBuilder("git", "diff", "--cached")
5452 }
55- builder.directory(File(URI(workspaceDir)))
53+ builder.directory(UriUtils.uriToFile(workspaceDir))
5654 val process = withContext(Dispatchers.IO) {
5755 builder.start()
5856 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +39 −210
@@ -1,13 +1,11 @@
11 package com.github.continuedev.continueintellijextension.`continue`
22
3-import IntelliJIDE
43 import com.github.continuedev.continueintellijextension.*
54 import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
65 import com.github.continuedev.continueintellijextension.activities.showTutorial
7-import com.github.continuedev.continueintellijextension.auth.AuthListener
86 import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
9-import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
107 import com.github.continuedev.continueintellijextension.editor.DiffStreamService
8+import com.github.continuedev.continueintellijextension.editor.EditorUtils
119 import com.github.continuedev.continueintellijextension.protocol.*
1210 import com.github.continuedev.continueintellijextension.services.*
1311 import com.github.continuedev.continueintellijextension.utils.*
@@ -16,21 +14,15 @@
1614 import com.intellij.openapi.command.WriteCommandAction
1715 import com.intellij.openapi.components.ServiceManager
1816 import com.intellij.openapi.components.service
19-import com.intellij.openapi.editor.Editor
2017 import com.intellij.openapi.editor.SelectionModel
21-import com.intellij.openapi.fileEditor.FileDocumentManager
2218 import com.intellij.openapi.fileEditor.FileEditorManager
2319 import com.intellij.openapi.project.DumbAware
2420 import com.intellij.openapi.project.Project
25-import com.intellij.openapi.util.TextRange
2621 import com.intellij.openapi.vfs.VirtualFileManager
2722 import com.intellij.openapi.wm.ToolWindowManager
2823 import kotlinx.coroutines.*
2924 import java.awt.Toolkit
3025 import java.awt.datatransfer.StringSelection
31-import java.lang.IllegalStateException
32-import kotlin.coroutines.resume
33-import kotlin.coroutines.resumeWithException
3426
3527
3628 class IdeProtocolClient(
@@ -39,6 +31,8 @@
3931 private val project: Project
4032 ) : DumbAware {
4133 private val ide: IDE = IntelliJIDE(project, continuePluginService)
34+ private val diffStreamService = project.service<DiffStreamService>()
35+
4236
4337 /**
4438 * Create a dispatcher with limited parallelism to prevent UI freezing.
@@ -46,6 +40,7 @@
4640 *
4741 * See this thread for details: https://github.com/continuedev/continue/issues/4098#issuecomment-2854865310
4842 */
43+ @OptIn(ExperimentalCoroutinesApi::class)
4944 private val limitedDispatcher = Dispatchers.IO.limitedParallelism(4)
5045
5146 init {
@@ -96,6 +91,15 @@
9691 respond(jsonData)
9792 }
9893
94+ "showFile" -> {
95+ val params = Gson().fromJson(
96+ dataElement.toString(),
97+ ShowFilePayload::class.java
98+ )
99+ ide.openFile(params.filepath)
100+ respond(null)
101+ }
102+
99103 "getIdeSettings" -> {
100104 val settings = ide.getIdeSettings()
101105 respond(settings)
@@ -443,20 +447,32 @@
443447 "acceptDiff" -> {
444448 val params = Gson().fromJson(
445449 dataElement.toString(),
446- AcceptDiffParams::class.java
450+ AcceptOrRejectDiffPayload::class.java
447451 )
448452 val filepath = params.filepath;
449453
450- acceptOrRejectDiff(filepath, true)
454+ val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
455+
456+ if (editor != null) {
457+ diffStreamService.accept(editor)
458+ }
459+
460+ respond(null)
451461 }
452462
453463 "rejectDiff" -> {
454464 val params = Gson().fromJson(
455465 dataElement.toString(),
456- RejectDiffParams::class.java
466+ AcceptOrRejectDiffPayload::class.java
457467 )
458468 val filepath = params.filepath;
459- acceptOrRejectDiff(filepath, false)
469+
470+ val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
471+ if (editor != null) {
472+ diffStreamService.reject(editor)
473+ }
474+ respond(null)
475+
460476 }
461477
462478 "applyToFile" -> {
@@ -464,141 +480,13 @@
464480 dataElement.toString(),
465481 ApplyToFileParams::class.java
466482 )
467- val filepath = params.filepath
468-
469- continuePluginService.sendToWebview(
470- "updateApplyState", mapOf(
471- "streamId" to params.streamId,
472- "status" to "streaming",
473- "fileContent" to params.text,
474- "toolCallId" to params.toolCallId,
475- "filepath" to filepath
476- )
477- )
478-
479-
480- fun closeStream() {
481- continuePluginService.sendToWebview(
482- "updateApplyState", mapOf(
483- "numDiffs" to 0,
484- "streamId" to params.streamId,
485- "status" to "closed",
486- "fileContent" to params.text,
487- "toolCallId" to params.toolCallId,
488- "filepath" to filepath
489- )
490- )
491- }
492-
493- var editor: Editor? = null;
494-
495- if (!filepath.isNullOrEmpty()) {
496- val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
497- if (virtualFile != null) {
498- ApplicationManager.getApplication().invokeAndWait {
499- FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
500- }
501- }
502- }
503- editor = FileEditorManager.getInstance(project).selectedTextEditor
504-
505- if (editor == null) {
506- ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
507- closeStream()
508- respond(null)
509- return@launch
510- }
511-
512- if (editor.document.text.trim().isEmpty()) {
513- WriteCommandAction.runWriteCommandAction(project) {
514- editor.document.insertString(0, params.text)
515- }
516- closeStream()
517- respond(null)
518- return@launch
519- }
520483
521- val llm: Any = try {
522- suspendCancellableCoroutine { continuation ->
523- continuePluginService.coreMessenger?.request(
524- "config/getSerializedProfileInfo",
525- null,
526- null
527- ) { response ->
528- try {
529- val selectedModels = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "selectedModelByRole")
530-
531- // If "apply" role model is not found, try "chat" role
532- val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
533-
534- if (applyCodeBlockModel != null) {
535- continuation.resume(applyCodeBlockModel)
536- } else {
537- // If neither "apply" nor "chat" models are available, return with exception
538- continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
539- }
540- } catch (e: Exception) {
541- continuation.resumeWithException(e)
542- }
543- }
544- }
545- } catch (e: Exception) {
546- launch {
547- ide.showToast(
548- ToastType.ERROR, "Failed to fetch model configuration"
549- )
550- }
551- closeStream()
552- respond(null)
553- return@launch
554- }
555-
556- val diffStreamService = project.service<DiffStreamService>()
557- // Clear all diff blocks before running the diff stream
558- diffStreamService.reject(editor)
559-
560- val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
561-
562- val prompt =
563- "The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
564-
565- val rif = getHighlightedCode()
566-
567- val (prefix, highlighted, suffix) = if (rif == null) {
568- // If no highlight, use the whole document as highlighted
569- Triple("", editor.document.text, "")
570- } else {
571- val prefix = editor.document.getText(TextRange(0, rif.range.start.character))
572- val highlighted = rif.contents
573- val suffix =
574- editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength))
575-
576- // Remove the selection after processing
577- ApplicationManager.getApplication().invokeLater {
578- editor.selectionModel.removeSelection()
579- }
580-
581- Triple(prefix, highlighted, suffix)
582- }
583-
584- val diffStreamHandler =
585- DiffStreamHandler(
586- project,
587- editor,
588- rif?.range?.start?.line ?: 0,
589- rif?.range?.end?.line ?: (editor.document.lineCount - 1),
590- {},
591- {},
592- params.streamId,
593- params.toolCallId
594- )
595-
596- diffStreamService.register(diffStreamHandler, editor)
597-
598- diffStreamHandler.streamDiffLinesToEditor(
599- prompt, prefix, highlighted, suffix, llmTitle, false
484+ ApplyToFileHandler.apply(
485+ project,
486+ continuePluginService,
487+ ide,
488+ params
600489 )
601-
602490 respond(null)
603491 }
604492
@@ -612,52 +500,15 @@
612500 }
613501 }
614502
615- private fun getHighlightedCode(): RangeInFileWithContents? {
616- val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
617- // Get the editor instance for the currently active editor window
618- val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null
619- val virtualFile =
620- editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
621-
622- // Get the selection range and content
623- val selectionModel: SelectionModel = editor.selectionModel
624- val selectedText = selectionModel.selectedText ?: ""
625-
626- val document = editor.document
627- val startOffset = selectionModel.selectionStart
628- val endOffset = selectionModel.selectionEnd
629-
630- if (startOffset == endOffset) {
631- return@runReadAction null
632- }
633-
634- val startLine = document.getLineNumber(startOffset)
635- val endLine = document.getLineNumber(endOffset)
636-
637- val startChar = startOffset - document.getLineStartOffset(startLine)
638- val endChar = endOffset - document.getLineStartOffset(endLine)
639-
640- return@runReadAction virtualFile.toUriOrNull()?.let {
641- RangeInFileWithContents(
642- it, Range(
643- Position(startLine, startChar),
644- Position(endLine, endChar)
645- ), selectedText
646- )
647- }
648- }
649-
650- return result
651- }
652-
653503 fun sendHighlightedCode(edit: Boolean = false) {
654- val rif = getHighlightedCode() ?: return
504+ val editor = EditorUtils.getEditor(project)
505+ val rif = editor?.getHighlightedRIF() ?: return
655506
656507 continuePluginService.sendToWebview(
657508 "highlightedCode",
658- mapOf(
659- "rangeInFileWithContents" to rif,
660- "edit" to edit
509+ HighlightedCodePayload(
510+ rangeInFileWithContents = rif,
511+ shouldRun = edit
661512 )
662513 )
663514 }
@@ -667,28 +518,6 @@
667518 continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
668519 }
669520
670- fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
671- val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
672-
673- if (virtualFile != null) {
674- ApplicationManager.getApplication().invokeAndWait {
675- val openedEditor =
676- FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
677- if (openedEditor != null) {
678- val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
679-
680- if (editor != null) {
681- val diffStreamService = project.service<DiffStreamService>()
682- if (accepted) {
683- diffStreamService.accept(editor)
684- } else {
685- diffStreamService.reject(editor)
686- }
687- }
688- }
689- }
690- }
691- }
692521
693522 fun deleteAtIndex(index: Int) {
694523 continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +17 −14
@@ -1,3 +1,5 @@
1+package com.github.continuedev.continueintellijextension.`continue`
2+
13 import com.github.continuedev.continueintellijextension.*
24 import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
35 import com.github.continuedev.continueintellijextension.constants.ContinueConstants
@@ -167,7 +169,7 @@
167169 // Find any .continuerc.json files
168170 for (file in contents) {
169171 if (file.endsWith(".continuerc.json")) {
170- val fileContent = File(URI(file)).readText()
172+ val fileContent = UriUtils.uriToFile(file).readText()
171173 configs.add(fileContent)
172174 }
173175 }
@@ -178,12 +180,12 @@
178180 }
179181
180182 override suspend fun fileExists(filepath: String): Boolean {
181- val file = File(URI(filepath))
183+ val file = UriUtils.uriToFile(filepath)
182184 return file.exists()
183185 }
184186
185187 override suspend fun writeFile(path: String, contents: String) {
186- val file = File(URI(path))
188+ val file = UriUtils.uriToFile(path)
187189 file.parentFile?.mkdirs()
188190 file.writeText(contents)
189191 }
@@ -201,7 +203,7 @@
201203
202204 override suspend fun openFile(path: String) {
203205 // Convert URI path to absolute file path
204- val filePath = File(URI(path)).absolutePath
206+ val filePath = UriUtils.uriToFile(path).absolutePath
205207 // Find the file using the absolute path
206208 val file = withContext(Dispatchers.IO) {
207209 LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
@@ -216,7 +218,7 @@
216218
217219 override suspend fun openUrl(url: String) {
218220 withContext(Dispatchers.IO) {
219- Desktop.browse(java.net.URI(url))
221+ Desktop.browse(URI(url))
220222 }
221223 }
222224
@@ -226,7 +228,8 @@
226228
227229 override suspend fun saveFile(filepath: String) {
228230 ApplicationManager.getApplication().invokeLater {
229- val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path) ?: return@invokeLater
231+ val file =
232+ LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path) ?: return@invokeLater
230233 val fileDocumentManager = FileDocumentManager.getInstance()
231234 val document = fileDocumentManager.getDocument(file)
232235
@@ -239,7 +242,7 @@
239242 override suspend fun readFile(filepath: String): String {
240243 return try {
241244 val content = ApplicationManager.getApplication().runReadAction<String?> {
242- val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
245+ val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
243246 if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
244247 return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
245248 }
@@ -249,7 +252,7 @@
249252 if (content != null) {
250253 content
251254 } else {
252- val file = File(URI(filepath))
255+ val file = UriUtils.uriToFile(filepath)
253256 if (!file.exists() || file.isDirectory) return ""
254257 withContext(Dispatchers.IO) {
255258 FileInputStream(file).use { fis ->
@@ -455,7 +458,7 @@
455458 return withContext(Dispatchers.IO) {
456459 try {
457460 val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
458- builder.directory(File(URI(dir)))
461+ builder.directory(UriUtils.uriToFile(dir))
459462 val process = builder.start()
460463 val reader = BufferedReader(InputStreamReader(process.inputStream))
461464 val output = reader.readLine()
@@ -485,7 +488,7 @@
485488
486489 override suspend fun getRepoName(dir: String): String? {
487490 return withContext(Dispatchers.IO) {
488- val directory = File(URI(dir))
491+ val directory = UriUtils.uriToFile(dir)
489492 val targetDir = if (directory.isFile) directory.parentFile else directory
490493 val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
491494 builder.directory(targetDir)
@@ -549,7 +552,7 @@
549552 override suspend fun getGitRootPath(dir: String): String? {
550553 return withContext(Dispatchers.IO) {
551554 val builder = ProcessBuilder("git", "rev-parse", "--show-toplevel")
552- builder.directory(File(URI(dir)))
555+ builder.directory(UriUtils.uriToFile(dir))
553556 val process = builder.start()
554557
555558 val reader = BufferedReader(InputStreamReader(process.inputStream))
@@ -560,7 +563,7 @@
560563 }
561564
562565 override suspend fun listDir(dir: String): List<List<Any>> {
563- val files = File(URI(dir)).listFiles()?.map {
566+ val files = UriUtils.uriToFile(dir).listFiles()?.map {
564567 listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
565568 } ?: emptyList()
566569
@@ -569,7 +572,7 @@
569572
570573 override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
571574 return files.associateWith { file ->
572- FileStats(File(URI(file)).lastModified(), File(URI(file)).length())
575+ FileStats(UriUtils.uriToFile(file).lastModified(), UriUtils.uriToFile(file).length())
573576 }
574577 }
575578
@@ -587,7 +590,7 @@
587590 }
588591
589592 private fun setFileOpen(filepath: String, open: Boolean = true) {
590- val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
593+ val file = LocalFileSystem.getInstance().findFileByPath(UriUtils.uriToFile(filepath).path)
591594
592595 file?.let {
593596 if (open) {
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/UriUtils.kt +39 −0
@@ -0,0 +1,39 @@
1+package com.github.continuedev.continueintellijextension.`continue`
2+
3+import java.io.File
4+import java.net.URI
5+
6+/**
7+ * Utility class for URI operations
8+ */
9+object UriUtils {
10+ /**
11+ * Parses a URI string into a URI object, handling special cases for Windows file paths
12+ */
13+ fun parseUri(uri: String): URI {
14+ try {
15+ // Remove query parameters if present
16+ val uriStr = uri.substringBefore("?")
17+
18+ // Handle Windows file paths with authority component
19+ if (uriStr.startsWith("file://") && !uriStr.startsWith("file:///")) {
20+ val path = uriStr.substringAfter("file://")
21+ return URI("file:///$path")
22+ }
23+
24+ // Standard URI handling for other cases
25+ val uriWithoutQuery = URI(uriStr)
26+ return uriWithoutQuery
27+ } catch (e: Exception) {
28+ println("Error parsing URI: $uri ${e.message}")
29+ throw Exception("Invalid URI: $uri ${e.message}")
30+ }
31+ }
32+
33+ /**
34+ * Converts a URI string to a File object
35+ */
36+ fun uriToFile(uri: String): File {
37+ return File(parseUri(uri))
38+ }
39+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +77 −64
@@ -1,5 +1,8 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3+import com.github.continuedev.continueintellijextension.ApplyState
4+import com.github.continuedev.continueintellijextension.ApplyStateStatus
5+import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload
36 import com.github.continuedev.continueintellijextension.services.ContinuePluginService
47 import com.intellij.openapi.application.ApplicationManager
58 import com.intellij.openapi.command.WriteCommandAction
@@ -12,7 +15,6 @@
1215 import com.intellij.openapi.fileEditor.FileEditorManager
1316 import com.intellij.openapi.fileEditor.TextEditor
1417 import com.intellij.openapi.project.Project
15-import com.intellij.openapi.vfs.VirtualFile
1618 import kotlin.math.max
1719 import kotlin.math.min
1820
@@ -35,41 +37,41 @@
3537 var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
3638 )
3739
40+ private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
3841 private var curLine = CurLineState(startLine)
3942 private var isRunning: Boolean = false
4043 private var hasAcceptedOrRejectedBlock: Boolean = false
41-
4244 private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
43- private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
45+ private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
46+ private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
4447
45- private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor)
46- private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor)
4748
4849 init {
4950 initUnfinishedRangeHighlights()
5051 }
5152
52- private fun sendUpdate(status: String) {
53- if(this.streamId == null) {
53+ private fun sendUpdate(status: ApplyStateStatus) {
54+ if (streamId == null) {
5455 return
5556 }
56- val virtualFile = getVirtualFile()
57- val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
58- continuePluginService.sendToWebview("updateApplyState", mapOf(
59- "numDiffs" to this.diffBlocks.size,
60- "streamId" to this.streamId,
61- "status" to status,
62- "fileContent" to "not implemented",
63- "toolCallId" to this.toolCallId,
64- "filepath" to virtualFile?.url
65- ))
57+
58+ // Define a single payload and use it for sending
59+ val payload = ApplyState(
60+ streamId = streamId,
61+ status = status.status,
62+ numDiffs = diffBlocks.size,
63+ filepath = virtualFile?.url,
64+ fileContent = "not implemented",
65+ toolCallId = toolCallId?.toString()
66+ )
67+
68+ continuePluginService.sendToWebview("updateApplyState", payload)
6669 }
6770
6871 fun acceptAll() {
69- editor.markupModel.removeAllHighlighters();
70- sendUpdate("closed")
71-
72- resetState()
72+ ApplicationManager.getApplication().invokeLater {
73+ diffBlocks.toList().forEach { it.handleAccept() }
74+ }
7375 }
7476
7577 fun rejectAll() {
@@ -77,26 +79,42 @@
7779 // to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple
7880 // way to undo our changes without also undoing the diff that the user accepted or rejected.
7981 if (hasAcceptedOrRejectedBlock) {
80- diffBlocks.forEach { it.handleReject() }
82+ ApplicationManager.getApplication().invokeLater {
83+ val blocksToReject = diffBlocks.toList()
84+ blocksToReject.toList().forEach { it.handleReject() }
85+ }
8186 } else {
8287 undoChanges()
88+ // We have to manually call `handleClosedState`, but above,
89+ // this is done by invoking the button handlers
90+ setClosed()
8391 }
84- sendUpdate("closed")
85-
86- resetState()
8792 }
8893
8994 fun streamDiffLinesToEditor(
90- input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String, includeRulesInSystemMessage: Boolean
95+ input: String,
96+ prefix: String,
97+ highlighted: String,
98+ suffix: String,
99+ modelTitle: String,
100+ includeRulesInSystemMessage: Boolean
91101 ) {
92102 isRunning = true
93- this.sendUpdate("streaming")
94-
95- val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
96- val virtualFile = getVirtualFile()
103+ sendUpdate(ApplyStateStatus.STREAMING)
97104
98105 continuePluginService.coreMessenger?.request(
99- "streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle, includeRulesInSystemMessage), null
106+ "streamDiffLines",
107+ StreamDiffLinesPayload(
108+ input = input,
109+ prefix = prefix,
110+ highlighted = highlighted,
111+ suffix = suffix,
112+ language = virtualFile?.fileType?.name,
113+ modelTitle = modelTitle,
114+ includeRulesInSystemMessage = includeRulesInSystemMessage,
115+ fileUri = virtualFile?.url
116+ ),
117+ null
100118 ) { response ->
101119 if (!isRunning) return@request
102120
@@ -104,7 +122,6 @@
104122
105123 if (response["done"] as? Boolean == true) {
106124 handleFinishedResponse()
107- sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
108125 return@request
109126 }
110127
@@ -113,6 +130,9 @@
113130 }
114131
115132 private fun initUnfinishedRangeHighlights() {
133+ val editorUtils = EditorUtils(editor)
134+ val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888)
135+
116136 for (i in startLine..endLine) {
117137 val highlighter = editor.markupModel.addLineHighlighter(
118138 unfinishedKey, min(
@@ -155,10 +175,11 @@
155175 }
156176
157177 if (diffBlocks.isEmpty()) {
158- sendUpdate("closed")
159- onClose()
178+ setClosed()
160179 } else {
161- sendUpdate("done")
180+ // TODO: It's confusing that we pass `DONE` here. What we're doing is updating the UI with the latest
181+ // diff count. We should have a dedicated status for this.
182+ sendUpdate(ApplyStateStatus.DONE)
162183 }
163184 }
164185
@@ -169,8 +190,6 @@
169190 )
170191
171192 diffBlocks.add(diffBlock)
172- sendUpdate("streaming")
173-
174193 return diffBlock
175194 }
176195
@@ -203,12 +222,17 @@
203222 }
204223
205224 private fun updateProgressHighlighters(type: DiffLineType) {
225+ val editorUtils = EditorUtils(editor)
226+ val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888)
227+
206228 // Update the highlighter to show the current line
207229 curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
208230 curLine.highlighter = editor.markupModel.addLineHighlighter(
209231 curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST
210232 )
211233
234+ editorUtils.scrollToLine(curLine.index)
235+
212236 // Remove the unfinished lines highlighter
213237 if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) {
214238 editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
@@ -242,15 +266,18 @@
242266 curLine = CurLineState(startLine)
243267 isRunning = false
244268
245- // Close the Edit input
269+ // Close the Edit input if editing
246270 onClose()
247271 }
248272
249273
250274 private fun undoChanges() {
275+ if (virtualFile == null) {
276+ return
277+ }
278+
251279 WriteCommandAction.runWriteCommandAction(project) {
252280 val undoManager = UndoManager.getInstance(project)
253- val virtualFile = getVirtualFile() ?: return@runWriteCommandAction
254281 val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor
255282
256283 if (undoManager.isUndoAvailable(fileEditor)) {
@@ -260,34 +287,9 @@
260287 undoManager.undo(fileEditor)
261288 }
262289 }
263- sendUpdate("done")
264290 }
265291 }
266292
267- private fun getVirtualFile(): VirtualFile? {
268- return FileDocumentManager.getInstance().getFile(editor.document) ?: return null
269- }
270-
271- private fun createRequestParams(
272- input: String,
273- prefix: String,
274- highlighted: String,
275- suffix: String,
276- virtualFile: VirtualFile?,
277- modelTitle: String,
278- includeRulesInSystemMessage: Boolean
279- ): Map<String, Any?> {
280- return mapOf(
281- "input" to input,
282- "prefix" to prefix,
283- "highlighted" to highlighted,
284- "suffix" to suffix,
285- "language" to virtualFile?.fileType?.name,
286- "modelTitle" to modelTitle,
287- "includeRulesInSystemMessage" to includeRulesInSystemMessage,
288- )
289- }
290-
291293 private fun handleFinishedResponse() {
292294 ApplicationManager.getApplication().invokeLater {
293295 // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
@@ -296,6 +298,12 @@
296298
297299 onFinish()
298300 cleanupProgressHighlighters()
301+
302+ if (diffBlocks.isEmpty()) {
303+ setClosed()
304+ } else {
305+ sendUpdate(ApplyStateStatus.DONE)
306+ }
299307 }
300308 }
301309
@@ -325,4 +333,9 @@
325333 else -> throw Exception("Unknown diff line type: $type")
326334 }
327335 }
336+
337+ private fun setClosed() {
338+ sendUpdate(ApplyStateStatus.CLOSED)
339+ resetState()
340+ }
328341 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +157 −9
@@ -1,22 +1,170 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3+import com.github.continuedev.continueintellijextension.utils.toUriOrNull
4+import com.intellij.openapi.application.ApplicationManager
5+import com.intellij.openapi.command.WriteCommandAction
36 import com.intellij.openapi.editor.Editor
7+import com.intellij.openapi.editor.SelectionModel
48 import com.intellij.openapi.editor.colors.TextAttributesKey
59 import com.intellij.openapi.editor.markup.TextAttributes
10+import com.intellij.openapi.fileEditor.FileDocumentManager
11+import com.intellij.openapi.fileEditor.FileEditorManager
12+import com.intellij.openapi.project.Project
13+import com.intellij.openapi.util.TextRange
14+import com.intellij.openapi.vfs.VirtualFileManager
615 import com.intellij.ui.JBColor
16+import com.intellij.openapi.editor.ScrollType
717
8-class EditorUtils {
9- fun isTerminal(editor: Editor): Boolean {
10- return editor.javaClass.name.contains("Terminal")
18+/**
19+ * Utility class for working with Editor instances.
20+ */
21+class EditorUtils(val editor: Editor) {
22+ private val project: Project
23+ get() = editor.project!!
24+
25+ /**
26+ * Checks if the editor is a terminal editor
27+ */
28+ fun isTerminal(): Boolean {
29+ return editor.javaClass.name.contains("Terminal")
30+ }
31+
32+ /**
33+ * Checks if the document is empty (contains only whitespace)
34+ */
35+ fun isDocumentEmpty(): Boolean {
36+ return editor.document.text.trim().isEmpty()
37+ }
38+
39+ /**
40+ * Gets the total number of lines in the document
41+ */
42+ fun getLineCount(): Int {
43+ return editor.document.lineCount
44+ }
45+
46+ /**
47+ * Inserts text at the specified position in the document
48+ */
49+ fun insertTextAtPos(pos: Int, text: String) {
50+ WriteCommandAction.runWriteCommandAction(project) {
51+ editor.document.insertString(pos, text)
52+ }
53+ }
54+
55+ /**
56+ * Inserts text at the beginning of the document
57+ */
58+ fun insertTextIntoEmptyDocument(text: String) {
59+ insertTextAtPos(0, text)
60+ }
61+
62+
63+ /**
64+ * Scrolls the editor to make the specified line visible
65+ */
66+ fun scrollToLine(lineNumber: Int) {
67+ val safeLineNumber = lineNumber.coerceIn(0, editor.document.lineCount - 1)
68+ val lineStartOffset = editor.document.getLineStartOffset(safeLineNumber)
69+ val logicalPosition = editor.offsetToLogicalPosition(lineStartOffset)
70+ editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
71+ }
72+
73+ /**
74+ * Remove the selected range in a thread-safe manner
75+ */
76+ fun removeSelection() {
77+ ApplicationManager.getApplication().invokeLater {
78+ editor.selectionModel.removeSelection()
79+ }
1180 }
12-}
1381
14-fun createTextAttributesKey(name: String, color: Int, editor: Editor): TextAttributesKey {
15- val attributes = TextAttributes().apply {
16- backgroundColor = JBColor(color, color)
82+ /**
83+ * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
84+ */
85+ fun getHighlightedRangeTriplet(): Triple<String, String, String> {
86+ val rif = getHighlightedRIF()
87+
88+ return if (rif == null) {
89+ // If no highlight, use the whole document as highlighted
90+ Triple("", editor.document.text, "")
91+ } else {
92+ // Use the RangeInFileWithContents to get absolute offsets
93+ val (startOffset, endOffset) = rif.offsets
94+
95+ val prefix = editor.document.getText(TextRange(0, startOffset))
96+ val highlighted = rif.contents
97+ val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
98+
99+ removeSelection()
100+
101+ Triple(prefix, highlighted, suffix)
102+ }
103+ }
104+
105+ /**
106+ * Gets the selected code from the current editor.
107+ * Returns null if there is no selection.
108+ */
109+ fun getHighlightedRIF(): RangeInFileWithContents? {
110+ return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
111+ val virtualFile =
112+ FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null
113+
114+ // Get the selection range
115+ val selectionModel: SelectionModel = editor.selectionModel
116+ val startOffset = selectionModel.selectionStart
117+ val endOffset = selectionModel.selectionEnd
118+
119+ if (startOffset == endOffset) {
120+ return@runReadAction null
121+ }
122+
123+ return@runReadAction virtualFile.toUriOrNull()?.let {
124+ RangeInFileWithContents.fromSelection(
125+ it,
126+ editor.document,
127+ startOffset,
128+ endOffset
129+ )
130+ }
131+ }
132+ }
133+
134+ fun createTextAttributesKey(name: String, color: Int): TextAttributesKey {
135+ val attributes = TextAttributes().apply {
136+ backgroundColor = JBColor(color, color)
137+ }
138+
139+ return TextAttributesKey.createTextAttributesKey(name).also {
140+ editor.colorsScheme.setAttributes(it, attributes)
141+ }
17142 }
18143
19- return TextAttributesKey.createTextAttributesKey(name).also {
20- editor.colorsScheme.setAttributes(it, attributes)
144+ companion object {
145+ /**
146+ * Gets an editor for the currently selected file without opening any new files
147+ */
148+ fun getEditor(project: Project): EditorUtils? {
149+ val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
150+ return EditorUtils(editor)
151+ }
152+
153+ /**
154+ * Gets or opens an editor for the specified filepath and returns an EditorUtils instance
155+ */
156+ fun getOrOpenEditor(project: Project, filepath: String?): EditorUtils? {
157+ if (!filepath.isNullOrEmpty()) {
158+ val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
159+ if (virtualFile != null) {
160+ ApplicationManager.getApplication().invokeAndWait {
161+ FileEditorManager.getInstance(project).openFile(virtualFile, true).first()
162+ }
163+ }
164+ }
165+
166+ val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
167+ return EditorUtils(editor)
168+ }
21169 }
22170 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +1 −739
@@ -1,336 +1,11 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3-import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6-import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7-import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8-import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9-import com.intellij.openapi.Disposable
103 import com.intellij.openapi.actionSystem.ActionUpdateThread
114 import com.intellij.openapi.actionSystem.AnAction
125 import com.intellij.openapi.actionSystem.AnActionEvent
136 import com.intellij.openapi.actionSystem.PlatformDataKeys
14-import com.intellij.openapi.components.service
15-import com.intellij.openapi.editor.Editor
16-import com.intellij.openapi.editor.colors.EditorColorsManager
17-import com.intellij.openapi.editor.colors.EditorFontType
18-import com.intellij.openapi.editor.impl.EditorImpl
197 import com.intellij.openapi.project.DumbAware
20-import com.intellij.openapi.project.Project
21-import com.intellij.openapi.util.IconLoader
22-import com.intellij.openapi.util.Ref
23-import com.intellij.openapi.util.TextRange
24-import com.intellij.ui.JBColor
25-import com.intellij.util.ui.JBUI
26-import com.intellij.util.ui.UIUtil
27-import java.awt.*
28-import java.awt.event.*
29-import java.awt.geom.AffineTransform
30-import java.awt.geom.Path2D
31-import java.awt.geom.RoundRectangle2D
32-import javax.swing.*
33-import javax.swing.event.DocumentEvent
34-import javax.swing.event.DocumentListener
35-import javax.swing.event.ListDataListener
36-import javax.swing.plaf.basic.BasicComboBoxUI
37-import kotlin.math.max
38-import net.miginfocom.swing.MigLayout
39-import org.jdesktop.swingx.JXPanel
40-import org.jdesktop.swingx.JXTextArea
418
42-const val MAIN_FONT_SIZE = 13
43-
44-const val DOWN_ARROW = " ▾"
45-
46-fun makeTextArea(): JTextArea {
47- val textArea =
48- CustomTextArea(1, 40).apply {
49- lineWrap = true
50- wrapStyleWord = true
51- isOpaque = false
52- background = GetTheme().getSecondaryDark()
53- maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
54- margin = JBUI.insets(6, 8, 2, 4)
55- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
56- preferredSize = Dimension(400, 75)
57- }
58- textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
59- return textArea
60-}
61-
62-fun makePanel(
63- project: Project,
64- customPanelRef: Ref<CustomPanel>,
65- textArea: JTextArea,
66- inlayRef: Ref<Disposable>,
67- comboBoxRef: Ref<JComboBox<String>>,
68- leftInset: Int,
69- modelTitles: List<String>,
70- onEnter: () -> Unit,
71- onCancel: () -> Unit,
72- onAccept: () -> Unit,
73- onReject: () -> Unit
74-): JPanel {
75- val topPanel =
76- ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
77- background = JBColor(0x20888888, 0x20888888)
78- isOpaque = false
79- }
80-
81- val panel =
82- CustomPanel(
83- MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
84- project,
85- modelTitles,
86- comboBoxRef,
87- onEnter,
88- onCancel,
89- onAccept,
90- onReject,
91- textArea
92- )
93- .apply {
94- val globalScheme = EditorColorsManager.getInstance().globalScheme
95- val defaultBackground = globalScheme.defaultBackground
96- background = defaultBackground
97- add(textArea, "grow, gap 0!, height 100%")
98-
99- putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
100- preferredSize = textArea.preferredSize
101- setup()
102- }
103-
104- customPanelRef.set(panel)
105-
106- textArea.addComponentListener(
107- object : ComponentAdapter() {
108- override fun componentResized(e: ComponentEvent?) {
109- panel.revalidate()
110- panel.repaint()
111- }
112- })
113-
114- topPanel.add(panel, "grow, gap 0!")
115-
116- return topPanel
117-}
118-
119-fun openInlineEdit(project: Project?, editor: Editor) {
120- if (project == null) return
121-
122- // Don't open in terminal
123- if (EditorUtils().isTerminal(editor)) {
124- return
125- }
126-
127- val manager = EditorComponentInlaysManager.from(editor, true)
128-
129- // Get list of model titles
130- val continuePluginService = project.service<ContinuePluginService>()
131- val modelTitles = mutableListOf<String>()
132-
133- continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
134- val modelsByRole = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
135- val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
136- modelsByRole.castNestedOrNull<List<*>>(role)
137- ?.mapNotNull { it.castNestedOrNull<String>("title") }
138- ?.let(modelTitles::addAll)
139- }
140-
141- // This is a hacky way to not complicate getting model titles with coroutines
142- // 1500 feels like way upper limit of "would be weird if panel showed up after that long"
143- // And should always allow enough time to load config
144- val maxWaitTime = 1500
145- val startTime = System.currentTimeMillis()
146- while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
147- Thread.sleep(20)
148- }
149-
150- // Get highlighted range
151- val selectionModel = editor.selectionModel
152- val startOffset = selectionModel.selectionStart
153- val endOffset = selectionModel.selectionEnd
154- val startLineNumber = editor.document.getLineNumber(startOffset)
155- var endLineNumber = editor.document.getLineNumber(endOffset)
156-
157- // Doesn't seem to be any built-in methods to check for a line selection that contains trailing
158- // newlines.
159- // The only case this matters is when a user double-clicks to highlight a full line. Without this
160- // check.
161- // the highlighted range will continue to the following line.
162- val isSingleLineSelection =
163- endLineNumber > startLineNumber &&
164- endLineNumber < editor.document.lineCount &&
165- editor.document.getLineStartOffset(endLineNumber) == endOffset
166-
167- if (isSingleLineSelection) {
168- endLineNumber--
169- }
170-
171- val prefix = editor.document.getText(TextRange(0, startOffset))
172- val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
173- val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
174- val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
175-
176- // Un-highlight the selected text
177- selectionModel.removeSelection()
178-
179- // Get indentation width in pixels
180- val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
181- val lineStart = editor.document.getLineStartOffset(indentationLineNum)
182- val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
183- val text = editor.document.getText(TextRange(lineStart, lineEnd))
184- val indentation = text.takeWhile { it == ' ' }.length
185- val charWidth =
186- editor.contentComponent
187- .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
188- .charWidth(' ')
189- val leftInset = indentation * charWidth * 2 / 3
190-
191- val inlayRef = Ref<Disposable>()
192- val customPanelRef = Ref<CustomPanel>()
193-
194- // Create text area, attach key listener
195- val textArea = makeTextArea()
196-
197- // Create diff stream handler
198- val diffStreamHandler =
199- DiffStreamHandler(
200- project,
201- editor,
202- startLineNumber,
203- endLineNumber,
204- {
205- inlayRef.get()?.dispose()
206- },
207- {
208- textArea.document.insertString(textArea.caretPosition, ", ", null)
209- textArea.requestFocus()
210- customPanelRef.get().finish()
211- },
212- null,
213- null
214- )
215-
216- val diffStreamService = project.service<DiffStreamService>()
217- diffStreamService.register(diffStreamHandler, editor)
218-
219- val comboBoxRef = Ref<JComboBox<String>>()
220-
221- fun onEnter() {
222- val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
223- customPanelRef.get().enter()
224- diffStreamHandler.streamDiffLinesToEditor(
225- textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
226- )
227- }
228-
229- val panel =
230- makePanel(
231- project,
232- customPanelRef,
233- textArea,
234- inlayRef,
235- comboBoxRef,
236- leftInset,
237- modelTitles,
238- { onEnter() },
239- {
240- diffStreamService.reject(editor)
241- selectionModel.setSelection(startOffset, endOffset)
242- },
243- {
244- diffStreamService.accept(editor)
245- inlayRef.get().dispose()
246- },
247- {
248- diffStreamService.reject(editor)
249- inlayRef.get().dispose()
250- })
251-
252- val inlay = manager.insert(startLineNumber, panel, true)
253-
254- panel.revalidate()
255- inlayRef.set(inlay)
256- val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
257- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
258-
259- // Add key listener to text area
260- textArea.addKeyListener(
261- object : KeyAdapter() {
262- override fun keyTyped(e: KeyEvent) {
263- if (customPanelRef.get().isFinished) {
264- customPanelRef.get().setup()
265- }
266- }
267-
268- override fun keyPressed(e: KeyEvent) {
269- when (e.keyCode) {
270- KeyEvent.VK_ESCAPE -> {
271- diffStreamService.reject(editor)
272- selectionModel.setSelection(startOffset, endOffset)
273- }
274-
275- KeyEvent.VK_ENTER -> {
276- when (e.modifiersEx) {
277- KeyEvent.SHIFT_DOWN_MASK -> {
278- textArea.document.insertString(textArea.caretPosition, "\n", null)
279- }
280-
281- 0 -> {
282- onEnter()
283- e.consume()
284- }
285- }
286- }
287- }
288- }
289-
290- // We need this because backspace/delete is not registering properly on keyPressed for an
291- // unknown reason
292- override fun keyReleased(e: KeyEvent) {
293- if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
294- if (customPanelRef.get().isFinished) {
295- customPanelRef.get().setup()
296- }
297- }
298- }
299- })
300-
301- // Listen for changes to textarea line count
302- textArea.document.addDocumentListener(
303- object : DocumentListener {
304- private var lastNumLines: Int = 0
305-
306- private fun updateSize() {
307- val numLines = textArea.text.lines().size
308- if (numLines != lastNumLines) {
309- lastNumLines = numLines
310- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
311- }
312- }
313-
314- override fun insertUpdate(e: DocumentEvent?) {
315- updateSize()
316- }
317-
318- override fun removeUpdate(e: DocumentEvent?) {
319- updateSize()
320- }
321-
322- override fun changedUpdate(e: DocumentEvent?) {
323- updateSize()
324- }
325- })
326-
327- textArea.requestFocus()
328-}
329-
330-/**
331- * Adapted from
332- * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
333- */
3349 class InlineEditAction : AnAction(), DumbAware {
33510 override fun update(e: AnActionEvent) {
33611 e.presentation.isEnabled = true
@@ -346,417 +21,4 @@
34621 val project = e.getData(PlatformDataKeys.PROJECT) ?: return
34722 openInlineEdit(project, editor)
34823 }
349-}
350-
351-class CustomPanel(
352- layout: MigLayout,
353- project: Project,
354- modelTitles: List<String>,
355- comboBoxRef: Ref<JComboBox<String>>,
356- private val onEnter: () -> Unit,
357- private val onCancel: () -> Unit,
358- private val onAccept: () -> Unit,
359- private val onReject: () -> Unit,
360- private val textArea: JTextArea
361-) : JPanel(layout) {
362- private val shadowSize = 5
363- private val cornerRadius = 8
364- private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
365- private val borderColor = Color(128, 128, 128, 128)
366- private val borderThickness = 1
367- private val triangleSize = 6
368- private val rightMargin = 3.0
369- private val closeButton: JComponent = createCloseButton()
370- private val originalTextColor: Color = textArea.foreground
371- private val greyTextColor: Color = Color(128, 128, 128, 200)
372- var isFinished = false
373-
374- init {
375- isOpaque = false
376- add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
377- }
378-
379- private fun createCloseButton(): JComponent {
380- val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
381- return JLabel(closeIcon).apply {
382- background = Color(0, 0, 0, 0)
383- border = JBUI.Borders.empty(2, 6, 2, 0)
384- toolTipText = "`esc` to cancel"
385- isOpaque = false
386- addMouseListener(
387- object : MouseAdapter() {
388- override fun mouseEntered(e: MouseEvent) {
389- cursor = Cursor(Cursor.HAND_CURSOR)
390- }
391-
392- override fun mouseExited(e: MouseEvent) {
393- cursor = Cursor.getDefaultCursor()
394- }
395-
396- override fun mouseClicked(e: MouseEvent) {
397- onCancel()
398- }
399- })
400- }
401- }
402-
403- private val subPanelA: JPanel =
404- JPanel(MigLayout("insets 0, fillx")).apply {
405- val globalScheme = EditorColorsManager.getInstance().globalScheme
406- val defaultBackground = globalScheme.defaultBackground
407- val continueSettingsService = service<ContinueExtensionSettings>()
408- val dropdown =
409- JComboBox(modelTitles.toTypedArray()).apply {
410- setUI(TransparentArrowButtonUI())
411- isEditable = true
412- background = defaultBackground
413- foreground = Color(128, 128, 128, 200)
414- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
415- border = JBUI.Borders.empty(8)
416- isOpaque = false
417- isEditable = false
418- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
419- preferredSize = Dimension(200, 30)
420-
421- renderer = object : DefaultListCellRenderer() {
422- override fun getListCellRendererComponent(
423- list: JList<*>?,
424- value: Any?,
425- index: Int,
426- isSelected: Boolean,
427- cellHasFocus: Boolean
428- ): Component {
429- val component =
430- super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
431- if (component is JLabel) {
432- component.border = JBUI.Borders.empty(4, 6)
433- }
434- return component
435- }
436- }.apply {
437- horizontalAlignment = SwingConstants.LEFT
438- }
439-
440- selectedIndex =
441- if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
442- if (modelTitles.isEmpty()) -1
443- else {
444- val index = modelTitles.indexOf(it)
445- if (index != -1) index else 0
446- }
447- } ?: 0
448-
449- addActionListener {
450- continueSettingsService.continueState.lastSelectedInlineEditModel =
451- (selectedItem as String).removeSuffix(DOWN_ARROW)
452- }
453- }
454-
455- comboBoxRef.set(dropdown)
456-
457- val rightButton =
458- CustomButton("⏎ Enter") { onEnter() }
459- .apply {
460- background = globalScheme.defaultForeground
461- foreground = globalScheme.defaultBackground
462- border = JBUI.Borders.empty(2, 6)
463- }
464-
465- val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
466- isOpaque = false
467- add(rightButton, "align right")
468- }
469-
470- border = JBUI.Borders.empty(0, 0, 16, 12)
471- isOpaque = false
472-
473- add(dropdown, "align left")
474- add(rightPanel, "align right")
475-
476- cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
477- }
478-
479- private val subPanelB: JPanel =
480- JPanel(BorderLayout()).apply {
481- isOpaque = false
482-
483- val progressBar = JProgressBar().apply { isIndeterminate = true }
484-
485- add(progressBar, BorderLayout.CENTER)
486- border = JBUI.Borders.empty(0, 0, 16, 12)
487- }
488-
489- private val subPanelC: JPanel =
490- JPanel(MigLayout("insets 0, fillx")).apply {
491- val leftLabel =
492- JLabel("Type to re-prompt").apply {
493- foreground = Color(156, 163, 175) // text-gray-400
494- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
495- border = JBUI.Borders.emptyLeft(4)
496- }
497-
498- val leftButton =
499- CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
500- .apply {
501- background = JBColor(0x30FF0000, 0x30FF0000)
502- }
503-
504- val rightButton =
505- CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
506- .apply {
507- background = JBColor(0x3000FF00, 0x3000FF00)
508- }
509-
510- val rightPanel =
511- JPanel(MigLayout("insets 0, fillx")).apply {
512- isOpaque = false
513- add(leftButton, "align right")
514- add(rightButton, "align right")
515- border = JBUI.Borders.empty()
516- }
517-
518- add(leftLabel, "align left")
519- add(rightPanel, "align right")
520- border = JBUI.Borders.empty(0, 0, 16, 12)
521- isOpaque = false
522- }
523-
524- fun setup() {
525- remove(subPanelB)
526- remove(subPanelC)
527- add(subPanelA, "grow, gap 0!")
528- isFinished = false
529- revalidate()
530- repaint()
531- textArea.foreground = originalTextColor
532- }
533-
534- fun enter() {
535- remove(subPanelA)
536- remove(subPanelC)
537- add(subPanelB, "grow, gap 0!")
538- revalidate()
539- repaint()
540- }
541-
542- fun finish() {
543- remove(subPanelB)
544- add(subPanelC, "grow, gap 0!")
545- revalidate()
546- repaint()
547- isFinished = true
548- textArea.foreground = greyTextColor
549- }
550-
551- override fun paintComponent(g: Graphics) {
552- super.paintComponent(g)
553-
554- val g2 = g as Graphics2D
555- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
556-
557- val w = width - shadowSize
558- val h = height - shadowSize
559-
560- // Create the shape for the tooltip/triangle
561- val shape = Path2D.Double()
562- shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
563- shape.quadTo(
564- borderThickness / 2.0,
565- borderThickness / 2.0,
566- cornerRadius.toDouble(),
567- borderThickness / 2.0
568- )
569- shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
570- shape.quadTo(
571- w - borderThickness / 2.0 - rightMargin,
572- borderThickness / 2.0,
573- w - borderThickness / 2.0 - rightMargin,
574- cornerRadius.toDouble()
575- )
576- shape.lineTo(
577- w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
578- )
579- shape.quadTo(
580- w - borderThickness / 2.0 - rightMargin,
581- h - triangleSize.toDouble(),
582- w - cornerRadius.toDouble() - rightMargin,
583- h - triangleSize.toDouble()
584- )
585- shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
586- shape.lineTo(borderThickness / 2.0, h.toDouble())
587- shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
588-
589- // Draw shadow
590- g2.color = shadowColor
591- g2.fill(
592- shape.createTransformedShape(
593- AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
594- )
595- )
596-
597- // Draw main shape
598- g2.color = background
599- g2.fill(shape)
600-
601- // Draw border
602- g2.color = borderColor
603- g2.stroke = BasicStroke(borderThickness.toFloat())
604- g2.draw(shape)
605- }
606-}
607-
608-class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
609- private var isHovered = false
610-
611- init {
612- isOpaque = false
613- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
614- addMouseListener(
615- object : MouseAdapter() {
616- override fun mouseEntered(e: MouseEvent?) {
617- isHovered = true
618- repaint()
619- }
620-
621- override fun mouseExited(e: MouseEvent?) {
622- isHovered = false
623- repaint()
624- }
625-
626- override fun mouseClicked(e: MouseEvent?) {
627- onClick()
628- }
629- })
630-
631- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
632- border = JBUI.Borders.empty(2, 6)
633- }
634-
635- override fun paintComponent(g: Graphics) {
636- val g2 = g as Graphics2D
637- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
638-
639- val cornerRadius = 8
640- val rect = Rectangle(0, 0, width, height)
641- val roundRect =
642- RoundRectangle2D.Float(
643- rect.x.toFloat(),
644- rect.y.toFloat(),
645- rect.width.toFloat(),
646- rect.height.toFloat(),
647- cornerRadius.toFloat(),
648- cornerRadius.toFloat()
649- )
650- g2.color = background
651- g2.fill(roundRect)
652- g2.color = foreground
653- g2.drawString(
654- text,
655- (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
656- (height / 2 + g.fontMetrics.ascent / 2).toFloat()
657- )
658- }
659-}
660-
661-class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
662- init {
663- setRows(rows)
664- setColumns(columns)
665- }
666-
667- override fun paintComponent(g: Graphics) {
668- // Draw placeholder
669- if (text.isEmpty()) {
670- g.color = Color(128, 128, 128, 255)
671- g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
672- g.drawString("Enter instructions...", 8, 20)
673- }
674-
675- super.paintComponent(g)
676- }
677-}
678-
679-class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
680- override fun getPreferredSize(): Dimension {
681- val prefSize = super.getPreferredSize()
682- val insets = getInsets()
683- prefSize.width += insets.left + insets.right
684- prefSize.height += insets.top + insets.bottom
685- return prefSize
686- }
687-
688- override fun paintComponent(g: Graphics) {
689- super.paintComponent(g)
690- }
691-}
692-
693-class TransparentArrowButtonUI : BasicComboBoxUI() {
694- override fun createArrowButton() =
695- JButton().apply {
696- isVisible = false
697- preferredSize = Dimension(0, 0)
698- }
699-
700- override fun getInsets(): Insets {
701- return JBUI.insetsLeft(6)
702- }
703-
704- override fun installUI(c: JComponent?) {
705- super.installUI(c)
706- comboBox.isOpaque = false
707- val globalScheme = EditorColorsManager.getInstance().globalScheme
708- val defaultBackground = globalScheme.defaultBackground
709- comboBox.background = defaultBackground
710-
711- // Modify the ComboBoxModel to include the down symbol
712- val originalModel = comboBox.model
713- comboBox.model =
714- object : ComboBoxModel<Any> {
715- override fun getSize(): Int = originalModel.size
716-
717- override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
718-
719- override fun setSelectedItem(anItem: Any?) {
720- originalModel.selectedItem = anItem
721- }
722-
723- override fun getSelectedItem(): Any? {
724- val item = originalModel.selectedItem
725- return "$item$DOWN_ARROW"
726- }
727-
728- override fun addListDataListener(l: ListDataListener?) {
729- originalModel.addListDataListener(l)
730- }
731-
732- override fun removeListDataListener(l: ListDataListener?) {
733- originalModel.removeListDataListener(l)
734- }
735- }
736- }
737-
738- override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
739- // Do nothing to prevent painting the background
740- }
741-
742- override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
743- val renderer = comboBox.renderer
744- val item = comboBox.selectedItem
745-
746- if (item != null) {
747- val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
748- c.font = comboBox.font
749- c.foreground = Color(156, 163, 175) // text-gray-400
750- c.background = comboBox.background
751-
752- if (c is JComponent) {
753- c.isOpaque = false
754- }
755-
756- val currentValuePane = currentValuePane
757- currentValuePane.paintComponent(
758- g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
759- )
760- }
761- }
762-}
24+}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +746 −0
@@ -0,0 +1,746 @@
1+package com.github.continuedev.continueintellijextension.editor
2+
3+import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4+import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7+import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8+import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9+import com.intellij.openapi.Disposable
10+import com.intellij.openapi.components.service
11+import com.intellij.openapi.editor.Editor
12+import com.intellij.openapi.editor.colors.EditorColorsManager
13+import com.intellij.openapi.editor.colors.EditorFontType
14+import com.intellij.openapi.editor.impl.EditorImpl
15+import com.intellij.openapi.project.Project
16+import com.intellij.openapi.util.IconLoader
17+import com.intellij.openapi.util.Ref
18+import com.intellij.openapi.util.TextRange
19+import com.intellij.ui.JBColor
20+import com.intellij.util.ui.JBUI
21+import com.intellij.util.ui.UIUtil
22+import java.awt.*
23+import java.awt.event.*
24+import java.awt.geom.AffineTransform
25+import java.awt.geom.Path2D
26+import java.awt.geom.RoundRectangle2D
27+import javax.swing.*
28+import javax.swing.event.DocumentEvent
29+import javax.swing.event.DocumentListener
30+import javax.swing.event.ListDataListener
31+import javax.swing.plaf.basic.BasicComboBoxUI
32+import kotlin.math.max
33+import net.miginfocom.swing.MigLayout
34+import org.jdesktop.swingx.JXPanel
35+import org.jdesktop.swingx.JXTextArea
36+
37+const val MAIN_FONT_SIZE = 13
38+const val DOWN_ARROW = " ▾"
39+const val MAX_MODEL_WAIT_TIME = 1500
40+
41+/**
42+ * Fetches and combines available model titles from both "edit" and "chat" roles.
43+ * Edit models are prioritized and appear first in the returned list.
44+ * Handles duplicate models by only including them once (prioritizing edit role).
45+ *
46+ * @param continuePluginService The service used to fetch config information
47+ * @return List of model titles with edit models first, duplicates removed
48+ * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
49+ */
50+fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
51+ val modelTitles = mutableListOf<String>()
52+
53+ continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
54+ val modelsByRole =
55+ response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
56+
57+ // Get edit models first
58+ val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
59+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
60+
61+ // Then get chat models
62+ val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
63+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
64+
65+ // Add edit models first, then chat models (avoiding duplicates)
66+ modelTitles.addAll(editModels)
67+ modelTitles.addAll(chatModels.filter { it !in editModels })
68+ }
69+
70+ val startTime = System.currentTimeMillis()
71+ while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
72+ Thread.sleep(20)
73+ }
74+
75+ return modelTitles
76+}
77+
78+fun makeTextArea(): JTextArea {
79+ val textArea =
80+ CustomTextArea(1, 40).apply {
81+ lineWrap = true
82+ wrapStyleWord = true
83+ isOpaque = false
84+ background = GetTheme().getSecondaryDark()
85+ maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
86+ margin = JBUI.insets(6, 8, 2, 4)
87+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
88+ preferredSize = Dimension(400, 75)
89+ }
90+ textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
91+ return textArea
92+}
93+
94+fun makePanel(
95+ project: Project,
96+ customPanelRef: Ref<CustomPanel>,
97+ textArea: JTextArea,
98+ inlayRef: Ref<Disposable>,
99+ comboBoxRef: Ref<JComboBox<String>>,
100+ leftInset: Int,
101+ modelTitles: List<String>,
102+ onEnter: () -> Unit,
103+ onCancel: () -> Unit,
104+ onAccept: () -> Unit,
105+ onReject: () -> Unit
106+): JPanel {
107+ val topPanel =
108+ ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
109+ background = JBColor(0x20888888, 0x20888888)
110+ isOpaque = false
111+ }
112+
113+ val panel =
114+ CustomPanel(
115+ MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
116+ project,
117+ modelTitles,
118+ comboBoxRef,
119+ onEnter,
120+ onCancel,
121+ onAccept,
122+ onReject,
123+ textArea
124+ )
125+ .apply {
126+ val globalScheme = EditorColorsManager.getInstance().globalScheme
127+ val defaultBackground = globalScheme.defaultBackground
128+ background = defaultBackground
129+ add(textArea, "grow, gap 0!, height 100%")
130+
131+ putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
132+ preferredSize = textArea.preferredSize
133+ setup()
134+ }
135+
136+ customPanelRef.set(panel)
137+
138+ textArea.addComponentListener(
139+ object : ComponentAdapter() {
140+ override fun componentResized(e: ComponentEvent?) {
141+ panel.revalidate()
142+ panel.repaint()
143+ }
144+ })
145+
146+ topPanel.add(panel, "grow, gap 0!")
147+
148+ return topPanel
149+}
150+
151+fun openInlineEdit(project: Project?, editor: Editor) {
152+ if (project == null) return
153+
154+ val editorUtils = EditorUtils(editor)
155+
156+ // Don't open in terminal
157+ if (editorUtils.isTerminal()) {
158+ return
159+ }
160+
161+ val manager = EditorComponentInlaysManager.from(editor, true)
162+
163+ val continuePluginService = project.service<ContinuePluginService>()
164+ val modelTitles = getModelTitles(continuePluginService)
165+
166+ val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
167+ val (startLineNumber, endLineNumber) = highlightedRIF.lines
168+ val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets
169+
170+
171+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
172+ val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
173+
174+ editorUtils.removeSelection()
175+
176+ // Get indentation width in pixels
177+ val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
178+ val lineStart = editor.document.getLineStartOffset(indentationLineNum)
179+ val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
180+ val text = editor.document.getText(TextRange(lineStart, lineEnd))
181+ val indentation = text.takeWhile { it == ' ' }.length
182+ val charWidth =
183+ editor.contentComponent
184+ .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
185+ .charWidth(' ')
186+ val leftInset = indentation * charWidth * 2 / 3
187+
188+ val inlayRef = Ref<Disposable>()
189+ val customPanelRef = Ref<CustomPanel>()
190+
191+ // Create text area, attach key listener
192+ val textArea = makeTextArea()
193+
194+ // Create diff stream handler
195+ val diffStreamHandler =
196+ DiffStreamHandler(
197+ project,
198+ editor,
199+ startLineNumber,
200+ endLineNumber,
201+ {
202+ inlayRef.get()?.dispose()
203+ },
204+ {
205+ textArea.document.insertString(textArea.caretPosition, ", ", null)
206+ textArea.requestFocus()
207+ customPanelRef.get().finish()
208+ },
209+ null,
210+ null
211+ )
212+
213+ val diffStreamService = project.service<DiffStreamService>()
214+ diffStreamService.register(diffStreamHandler, editor)
215+
216+ val comboBoxRef = Ref<JComboBox<String>>()
217+
218+ fun onEnter() {
219+ val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
220+ customPanelRef.get().enter()
221+ diffStreamHandler.streamDiffLinesToEditor(
222+ textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
223+ )
224+ }
225+
226+ val panel =
227+ makePanel(
228+ project,
229+ customPanelRef,
230+ textArea,
231+ inlayRef,
232+ comboBoxRef,
233+ leftInset,
234+ modelTitles,
235+ { onEnter() },
236+ {
237+ diffStreamService.reject(editor)
238+ editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset)
239+ },
240+ {
241+ diffStreamService.accept(editor)
242+ inlayRef.get().dispose()
243+ },
244+ {
245+ diffStreamService.reject(editor)
246+ inlayRef.get().dispose()
247+ })
248+
249+ val inlay = manager.insert(startLineNumber, panel, true)
250+
251+ panel.revalidate()
252+ inlayRef.set(inlay)
253+ val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
254+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
255+
256+ // Add key listener to text area
257+ textArea.addKeyListener(
258+ object : KeyAdapter() {
259+ override fun keyTyped(e: KeyEvent) {
260+ if (customPanelRef.get().isFinished) {
261+ customPanelRef.get().setup()
262+ }
263+ }
264+
265+ override fun keyPressed(e: KeyEvent) {
266+ when (e.keyCode) {
267+ KeyEvent.VK_ESCAPE -> {
268+ diffStreamService.reject(editor)
269+ editorUtils.editor.selectionModel.setSelection(
270+ highlightedStartOffset,
271+ highlightedEndOffset
272+ )
273+ }
274+
275+ KeyEvent.VK_ENTER -> {
276+ when (e.modifiersEx) {
277+ KeyEvent.SHIFT_DOWN_MASK -> {
278+ textArea.document.insertString(textArea.caretPosition, "\n", null)
279+ }
280+
281+ 0 -> {
282+ onEnter()
283+ e.consume()
284+ }
285+ }
286+ }
287+ }
288+ }
289+
290+ // We need this because backspace/delete is not registering properly on keyPressed for an
291+ // unknown reason
292+ override fun keyReleased(e: KeyEvent) {
293+ if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
294+ if (customPanelRef.get().isFinished) {
295+ customPanelRef.get().setup()
296+ }
297+ }
298+ }
299+ })
300+
301+ // Listen for changes to textarea line count
302+ textArea.document.addDocumentListener(
303+ object : DocumentListener {
304+ private var lastNumLines: Int = 0
305+
306+ private fun updateSize() {
307+ val numLines = textArea.text.lines().size
308+ if (numLines != lastNumLines) {
309+ lastNumLines = numLines
310+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
311+ }
312+ }
313+
314+ override fun insertUpdate(e: DocumentEvent?) {
315+ updateSize()
316+ }
317+
318+ override fun removeUpdate(e: DocumentEvent?) {
319+ updateSize()
320+ }
321+
322+ override fun changedUpdate(e: DocumentEvent?) {
323+ updateSize()
324+ }
325+ })
326+
327+ textArea.requestFocus()
328+}
329+
330+
331+class CustomPanel(
332+ layout: MigLayout,
333+ project: Project,
334+ modelTitles: List<String>,
335+ comboBoxRef: Ref<JComboBox<String>>,
336+ private val onEnter: () -> Unit,
337+ private val onCancel: () -> Unit,
338+ private val onAccept: () -> Unit,
339+ private val onReject: () -> Unit,
340+ private val textArea: JTextArea
341+) : JPanel(layout) {
342+ private val shadowSize = 5
343+ private val cornerRadius = 8
344+ private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
345+ private val borderColor = Color(128, 128, 128, 128)
346+ private val borderThickness = 1
347+ private val triangleSize = 6
348+ private val rightMargin = 3.0
349+ private val closeButton: JComponent = createCloseButton()
350+ private val originalTextColor: Color = textArea.foreground
351+ private val greyTextColor: Color = Color(128, 128, 128, 200)
352+ var isFinished = false
353+
354+ init {
355+ isOpaque = false
356+ add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
357+ }
358+
359+ private fun createCloseButton(): JComponent {
360+ val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
361+ return JLabel(closeIcon).apply {
362+ background = Color(0, 0, 0, 0)
363+ border = JBUI.Borders.empty(2, 6, 2, 0)
364+ toolTipText = "`esc` to cancel"
365+ isOpaque = false
366+ addMouseListener(
367+ object : MouseAdapter() {
368+ override fun mouseEntered(e: MouseEvent) {
369+ cursor = Cursor(Cursor.HAND_CURSOR)
370+ }
371+
372+ override fun mouseExited(e: MouseEvent) {
373+ cursor = Cursor.getDefaultCursor()
374+ }
375+
376+ override fun mouseClicked(e: MouseEvent) {
377+ onCancel()
378+ }
379+ })
380+ }
381+ }
382+
383+ private val subPanelA: JPanel =
384+ JPanel(MigLayout("insets 0, fillx")).apply {
385+ val globalScheme = EditorColorsManager.getInstance().globalScheme
386+ val defaultBackground = globalScheme.defaultBackground
387+ val continueSettingsService = service<ContinueExtensionSettings>()
388+ val dropdown =
389+ JComboBox(modelTitles.toTypedArray()).apply {
390+ setUI(TransparentArrowButtonUI())
391+ isEditable = true
392+ background = defaultBackground
393+ foreground = Color(128, 128, 128, 200)
394+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
395+ border = JBUI.Borders.empty(8)
396+ isOpaque = false
397+ isEditable = false
398+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
399+ preferredSize = Dimension(200, 30)
400+
401+ renderer = object : DefaultListCellRenderer() {
402+ override fun getListCellRendererComponent(
403+ list: JList<*>?,
404+ value: Any?,
405+ index: Int,
406+ isSelected: Boolean,
407+ cellHasFocus: Boolean
408+ ): Component {
409+ val component =
410+ super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
411+ if (component is JLabel) {
412+ component.border = JBUI.Borders.empty(4, 6)
413+ }
414+ return component
415+ }
416+ }.apply {
417+ horizontalAlignment = SwingConstants.LEFT
418+ }
419+
420+ selectedIndex =
421+ if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
422+ if (modelTitles.isEmpty()) -1
423+ else {
424+ val index = modelTitles.indexOf(it)
425+ if (index != -1) index else 0
426+ }
427+ } ?: 0
428+
429+ addActionListener {
430+ continueSettingsService.continueState.lastSelectedInlineEditModel =
431+ (selectedItem as String).removeSuffix(DOWN_ARROW)
432+ }
433+ }
434+
435+ comboBoxRef.set(dropdown)
436+
437+ val rightButton =
438+ CustomButton("⏎ Enter") { onEnter() }
439+ .apply {
440+ background = JBColor.namedColor("Button.startBackground")
441+ foreground = JBColor.namedColor("Button.foreground")
442+ border = JBUI.Borders.empty(2, 6)
443+ }
444+
445+ val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
446+ isOpaque = false
447+ add(rightButton, "align right")
448+ }
449+
450+ border = JBUI.Borders.empty(0, 0, 16, 12)
451+ isOpaque = false
452+
453+ add(dropdown, "align left")
454+ add(rightPanel, "align right")
455+
456+ cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
457+ }
458+
459+ private val subPanelB: JPanel =
460+ JPanel(BorderLayout()).apply {
461+ isOpaque = false
462+
463+ val progressBar = JProgressBar().apply { isIndeterminate = true }
464+
465+ add(progressBar, BorderLayout.CENTER)
466+ border = JBUI.Borders.empty(0, 0, 16, 12)
467+ }
468+
469+ private val subPanelC: JPanel =
470+ JPanel(MigLayout("insets 0, fillx")).apply {
471+ val leftLabel =
472+ JLabel("Type to re-prompt").apply {
473+ foreground = Color(156, 163, 175) // text-gray-400
474+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
475+ border = JBUI.Borders.emptyLeft(4)
476+ }
477+
478+ val leftButton =
479+ CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
480+ .apply {
481+ background = Color(0, 0, 0, 0)
482+ foreground = JBColor.foreground()
483+ border = JBUI.Borders.empty(2, 6)
484+ }
485+
486+ val rightButton =
487+ CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
488+ .apply {
489+ background = JBColor.namedColor("Button.startBackground")
490+ foreground = JBColor.namedColor("Button.foreground")
491+ border = JBUI.Borders.empty(2, 6)
492+ }
493+
494+ val rightPanel =
495+ JPanel(MigLayout("insets 0, fillx")).apply {
496+ isOpaque = false
497+ add(leftButton, "align right")
498+ add(rightButton, "align right")
499+ border = JBUI.Borders.empty()
500+ }
501+
502+ add(leftLabel, "align left")
503+ add(rightPanel, "align right")
504+ border = JBUI.Borders.empty(0, 0, 16, 12)
505+ isOpaque = false
506+ }
507+
508+ fun setup() {
509+ remove(subPanelB)
510+ remove(subPanelC)
511+ add(subPanelA, "grow, gap 0!")
512+ isFinished = false
513+ revalidate()
514+ repaint()
515+ textArea.foreground = originalTextColor
516+ }
517+
518+ fun enter() {
519+ remove(subPanelA)
520+ remove(subPanelC)
521+ add(subPanelB, "grow, gap 0!")
522+ revalidate()
523+ repaint()
524+ }
525+
526+ fun finish() {
527+ remove(subPanelB)
528+ add(subPanelC, "grow, gap 0!")
529+ revalidate()
530+ repaint()
531+ isFinished = true
532+ textArea.foreground = greyTextColor
533+ }
534+
535+ override fun paintComponent(g: Graphics) {
536+ super.paintComponent(g)
537+
538+ val g2 = g as Graphics2D
539+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
540+
541+ val w = width - shadowSize
542+ val h = height - shadowSize
543+
544+ // Create the shape for the tooltip/triangle
545+ val shape = Path2D.Double()
546+ shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
547+ shape.quadTo(
548+ borderThickness / 2.0,
549+ borderThickness / 2.0,
550+ cornerRadius.toDouble(),
551+ borderThickness / 2.0
552+ )
553+ shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
554+ shape.quadTo(
555+ w - borderThickness / 2.0 - rightMargin,
556+ borderThickness / 2.0,
557+ w - borderThickness / 2.0 - rightMargin,
558+ cornerRadius.toDouble()
559+ )
560+ shape.lineTo(
561+ w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
562+ )
563+ shape.quadTo(
564+ w - borderThickness / 2.0 - rightMargin,
565+ h - triangleSize.toDouble(),
566+ w - cornerRadius.toDouble() - rightMargin,
567+ h - triangleSize.toDouble()
568+ )
569+ shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
570+ shape.lineTo(borderThickness / 2.0, h.toDouble())
571+ shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
572+
573+ // Draw shadow
574+ g2.color = shadowColor
575+ g2.fill(
576+ shape.createTransformedShape(
577+ AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
578+ )
579+ )
580+
581+ // Draw main shape
582+ g2.color = background
583+ g2.fill(shape)
584+
585+ // Draw border
586+ g2.color = borderColor
587+ g2.stroke = BasicStroke(borderThickness.toFloat())
588+ g2.draw(shape)
589+ }
590+}
591+
592+class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
593+ private var isHovered = false
594+
595+ init {
596+ isOpaque = false
597+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
598+ addMouseListener(
599+ object : MouseAdapter() {
600+ override fun mouseEntered(e: MouseEvent?) {
601+ isHovered = true
602+ repaint()
603+ }
604+
605+ override fun mouseExited(e: MouseEvent?) {
606+ isHovered = false
607+ repaint()
608+ }
609+
610+ override fun mouseClicked(e: MouseEvent?) {
611+ onClick()
612+ }
613+ })
614+
615+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
616+ border = JBUI.Borders.empty(2, 6)
617+ }
618+
619+ override fun paintComponent(g: Graphics) {
620+ val g2 = g as Graphics2D
621+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
622+
623+ val cornerRadius = 8
624+ val rect = Rectangle(0, 0, width, height)
625+ val roundRect =
626+ RoundRectangle2D.Float(
627+ rect.x.toFloat(),
628+ rect.y.toFloat(),
629+ rect.width.toFloat(),
630+ rect.height.toFloat(),
631+ cornerRadius.toFloat(),
632+ cornerRadius.toFloat()
633+ )
634+ g2.color = background
635+ g2.fill(roundRect)
636+ g2.color = foreground
637+ g2.drawString(
638+ text,
639+ (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
640+ (height / 2 + g.fontMetrics.ascent / 2).toFloat()
641+ )
642+ }
643+}
644+
645+class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
646+ init {
647+ setRows(rows)
648+ setColumns(columns)
649+ }
650+
651+ override fun paintComponent(g: Graphics) {
652+ // Draw placeholder
653+ if (text.isEmpty()) {
654+ g.color = Color(128, 128, 128, 255)
655+ g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
656+ g.drawString("Enter instructions...", 8, 20)
657+ }
658+
659+ super.paintComponent(g)
660+ }
661+}
662+
663+class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
664+ override fun getPreferredSize(): Dimension {
665+ val prefSize = super.getPreferredSize()
666+ val insets = getInsets()
667+ prefSize.width += insets.left + insets.right
668+ prefSize.height += insets.top + insets.bottom
669+ return prefSize
670+ }
671+
672+ override fun paintComponent(g: Graphics) {
673+ super.paintComponent(g)
674+ }
675+}
676+
677+class TransparentArrowButtonUI : BasicComboBoxUI() {
678+ override fun createArrowButton() =
679+ JButton().apply {
680+ isVisible = false
681+ preferredSize = Dimension(0, 0)
682+ }
683+
684+ override fun getInsets(): Insets {
685+ return JBUI.insetsLeft(6)
686+ }
687+
688+ override fun installUI(c: JComponent?) {
689+ super.installUI(c)
690+ comboBox.isOpaque = false
691+ val globalScheme = EditorColorsManager.getInstance().globalScheme
692+ val defaultBackground = globalScheme.defaultBackground
693+ comboBox.background = defaultBackground
694+
695+ // Modify the ComboBoxModel to include the down symbol
696+ val originalModel = comboBox.model
697+ comboBox.model =
698+ object : ComboBoxModel<Any> {
699+ override fun getSize(): Int = originalModel.size
700+
701+ override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
702+
703+ override fun setSelectedItem(anItem: Any?) {
704+ originalModel.selectedItem = anItem
705+ }
706+
707+ override fun getSelectedItem(): Any? {
708+ val item = originalModel.selectedItem
709+ return "$item$DOWN_ARROW"
710+ }
711+
712+ override fun addListDataListener(l: ListDataListener?) {
713+ originalModel.addListDataListener(l)
714+ }
715+
716+ override fun removeListDataListener(l: ListDataListener?) {
717+ originalModel.removeListDataListener(l)
718+ }
719+ }
720+ }
721+
722+ override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
723+ // Do nothing to prevent painting the background
724+ }
725+
726+ override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
727+ val renderer = comboBox.renderer
728+ val item = comboBox.selectedItem
729+
730+ if (item != null) {
731+ val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
732+ c.font = comboBox.font
733+ c.foreground = Color(156, 163, 175) // text-gray-400
734+ c.background = comboBox.background
735+
736+ if (c is JComponent) {
737+ c.isOpaque = false
738+ }
739+
740+ val currentValuePane = currentValuePane
741+ currentValuePane.paintComponent(
742+ g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
743+ )
744+ }
745+ }
746+}
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt +110 −0
@@ -0,0 +1,110 @@
1+package com.github.continuedev.continueintellijextension.editor
2+
3+import com.github.continuedev.continueintellijextension.Position
4+import com.github.continuedev.continueintellijextension.Range
5+import com.intellij.openapi.editor.Document
6+import com.intellij.openapi.util.TextRange
7+
8+/**
9+ * Represents a range of text in a file with its contents.
10+ * Provides utility methods for working with document positions and offsets.
11+ */
12+class RangeInFileWithContents(
13+ val filepath: String,
14+ val range: Range,
15+ val contents: String,
16+ val document: Document
17+
18+) {
19+ /**
20+ * The absolute document offset for the start position
21+ */
22+ val startOffset: Int
23+ get() = document.getLineStartOffset(range.start.line) + range.start.character
24+
25+ /**
26+ * The absolute document offset for the end position
27+ */
28+ val endOffset: Int
29+ get() = document.getLineStartOffset(range.end.line) + range.end.character
30+
31+ /**
32+ * The line number where the highlighted range starts (zero-based)
33+ */
34+ val startLine: Int
35+ get() = range.start.line
36+
37+ /**
38+ * The line number where the highlighted range ends (zero-based)
39+ * This already accounts for proper line ending calculations.
40+ */
41+ val endLine: Int
42+ get() = range.end.line
43+
44+ /**
45+ * Both the start and end line numbers of the highlighted range as a pair
46+ */
47+ val lines: Pair<Int, Int>
48+ get() = Pair(startLine, endLine)
49+
50+ val offsets: Pair<Int, Int>
51+ get() = Pair(startOffset, endOffset)
52+
53+ companion object {
54+ /**
55+ * Create a RangeInFileWithContents from a document selection
56+ */
57+ fun fromSelection(
58+ filepath: String,
59+ document: Document,
60+ selectionStart: Int,
61+ selectionEnd: Int
62+ ): RangeInFileWithContents {
63+ val startLine = document.getLineNumber(selectionStart)
64+ val endLine = document.getLineNumber(selectionEnd)
65+
66+ val startChar = selectionStart - document.getLineStartOffset(startLine)
67+ val endChar = selectionEnd - document.getLineStartOffset(endLine)
68+
69+ // Adjust end line if it's a single line selection with trailing newlines
70+ val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) {
71+ endLine - 1
72+ } else {
73+ endLine
74+ }
75+
76+ val selectedText = document.getText(
77+ TextRange(selectionStart, selectionEnd)
78+ )
79+
80+ return RangeInFileWithContents(
81+ filepath,
82+ Range(
83+ Position(startLine, startChar),
84+ Position(adjustedEndLine, endChar)
85+ ),
86+ selectedText,
87+ document
88+ )
89+ }
90+
91+ /**
92+ * Checks if the selection spans to the next line only because of trailing newlines.
93+ * This matters when a user double-clicks to highlight a full line.
94+ *
95+ * @return true if the selection is actually a single line selection with trailing newline
96+ */
97+ fun isSelectionWithTrailingNewline(
98+ document: Document,
99+ selectionStart: Int,
100+ selectionEnd: Int
101+ ): Boolean {
102+ val startLine = document.getLineNumber(selectionStart)
103+ val endLine = document.getLineNumber(selectionEnd)
104+
105+ return endLine > startLine &&
106+ endLine < document.lineCount &&
107+ document.getLineStartOffset(endLine) == selectionEnd
108+ }
109+ }
110+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +21 −13
@@ -32,8 +32,6 @@
3232 private var deletionInlay: Disposable? = null
3333 private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons
3434 private var hasRenderedDiffBlock: Boolean = false
35- private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
36- private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor)
3735
3836 init {
3937 val (acceptBtn, rejectBtn) = createButtons()
@@ -78,6 +76,8 @@
7876
7977
8078 fun addNewLine(text: String, line: Int) {
79+ val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00)
80+
8181 if (line == editor.document.lineCount) {
8282 editor.document.insertString(editor.document.textLength, "\n")
8383 }
@@ -97,7 +97,7 @@
9797 return
9898 }
9999
100- if (deletedLines.size > 0) {
100+ if (deletedLines.isNotEmpty()) {
101101 renderDeletedLinesInlay()
102102 }
103103
@@ -107,20 +107,32 @@
107107 }
108108
109109 fun handleReject() {
110+ // Note that the logic for clearing editor UI state assumes that we do it
111+ // prior to undoing the diff changes, changing this order will break things
112+ clearEditorUI()
110113 revertDiff()
114+
115+ onAcceptReject(this@VerticalDiffBlock, false)
116+ }
117+
118+ fun handleAccept() {
111119 clearEditorUI()
120+ onAcceptReject(this@VerticalDiffBlock, true)
112121 }
113122
123+
114124 private fun refreshEditor() {
115125 editor.contentComponent.revalidate()
116126 editor.contentComponent.repaint()
117127 }
118128
119129 private fun renderDeletedLinesInlay() {
120- val textArea = createDeletionTextArea(deletedLines.joinToString("\n"))
121- this.textArea = textArea
130+ val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
131+ val newTextArea = createDeletionTextArea(deletedLines.joinToString("\n"))
132+
133+ textArea = newTextArea
122134
123- val disposable = editorComponentInlaysManager.insert(startLine, textArea, true)
135+ val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true)
124136 deletionInlay = disposable
125137 }
126138
@@ -154,11 +166,10 @@
154166 val rejectBtn =
155167 createButton(
156168 "${getAltKeyLabel()}${getShiftKeyLabel()}N",
157- JBColor(0x77FF0000, 0x77FF0000)
169+ JBColor(0xFF0000, 0xFF0000)
158170 ).apply {
159171 addActionListener {
160172 handleReject()
161- onAcceptReject(this@VerticalDiffBlock, false)
162173 }
163174
164175 }
@@ -167,14 +178,14 @@
167178 createButton(
168179 "${getAltKeyLabel()}${
169180 getShiftKeyLabel()
170- }Y", JBColor(0x7700BB00, 0x7700BB00)
181+ }Y", JBColor(0x00BB00, 0x00BB00)
171182 ).apply {
172183 addActionListener {
173184 handleAccept()
174- onAcceptReject(this@VerticalDiffBlock, true)
175185 }
176186 }
177187
188+
178189 return Pair(acceptBtn, rejectBtn)
179190 }
180191
@@ -185,9 +196,6 @@
185196 refreshEditor()
186197 }
187198
188- private fun handleAccept() {
189- clearEditorUI()
190- }
191199
192200 private fun revertDiff() {
193201 WriteCommandAction.runWriteCommandAction(project) {
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +0 −10
@@ -15,16 +15,6 @@
1515 val toolCallId: String?
1616 )
1717
18-data class AcceptDiffParams(
19- val filepath: String,
20- val streamId: String
21-)
22-
23-data class RejectDiffParams(
24- val filepath: String,
25- val streamId: String
26-)
27-
2818 data class InsertAtCursorParams(
2919 val text: String
3020 )
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +0 −1
@@ -1,6 +1,5 @@
11 package com.github.continuedev.continueintellijextension.services
22
3-import IntelliJIDE
43 import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
54 import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
65 import com.github.continuedev.continueintellijextension.`continue`.DiffManager
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +43 −0
@@ -1,5 +1,6 @@
11 package com.github.continuedev.continueintellijextension
22
3+import com.github.continuedev.continueintellijextension.editor.RangeInFileWithContents
34 import com.google.gson.JsonElement
45
56 enum class ToastType(val value: String) {
@@ -213,3 +214,45 @@
213214 data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int)
214215
215216 data class DeleteAtIndex(val index: Int)
217+
218+enum class ApplyStateStatus(val status: String) {
219+ NOT_STARTED("not-started"),
220+ STREAMING("streaming"),
221+ DONE("done"),
222+ CLOSED("closed");
223+}
224+
225+data class ApplyState(
226+ val streamId: String,
227+ val status: String,
228+ val numDiffs: Int? = null,
229+ val filepath: String? = null,
230+ val fileContent: String? = null,
231+ val toolCallId: String? = null
232+)
233+
234+data class HighlightedCodePayload(
235+ val rangeInFileWithContents: RangeInFileWithContents,
236+ val prompt: String? = null,
237+ val shouldRun: Boolean? = null
238+)
239+
240+data class StreamDiffLinesPayload(
241+ val prefix: String,
242+ val highlighted: String,
243+ val suffix: String,
244+ val input: String,
245+ val language: String?,
246+ val modelTitle: String?,
247+ val includeRulesInSystemMessage: Boolean,
248+ val fileUri: String?
249+)
250+
251+data class AcceptOrRejectDiffPayload(
252+ val filepath: String,
253+ val streamId: String? = null
254+)
255+
256+data class ShowFilePayload(
257+ val filepath: String
258+)
No newline at the end of the file
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +2 −2
@@ -78,9 +78,9 @@
7878 class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
7979 text="Reject Diff" description="Reject Diff">
8080 <keyboard-shortcut keymap="$default"
81- first-keystroke="shift ctrl DELETE"/>
81+ first-keystroke="shift ctrl BACK_SPACE"/>
8282 <keyboard-shortcut keymap="Mac OS X"
83- first-keystroke="shift meta DELETE"/>
83+ first-keystroke="shift meta BACK_SPACE"/>
8484 <override-text place="GoToAction" text="Continue: Reject Diff"/>
8585 </action>
8686
modified extensions/intellij/src/main/resources/continue_tutorial.java +22 −27
@@ -4,22 +4,23 @@
44 // / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
55 // \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
66 //
7-// Chat, Edit, and Autocomplete tutorial
7+// Autocomplete, Edit, Chat, and Agent tutorial
88 //
99
10-// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————-
10+// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— //
11+// Autocomplete provides inline code suggestions as you type.
1112
12-// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon.
13+// 1. Place cursor after `sortingAlgorithm:` below and press [Enter]
14+// 2. Press [Tab] to accept the Autocomplete suggestion
1315
14-// See an example at https://docs.continue.dev/getting-started/install
15-
16-// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model.
16+// Basic assertion for sortingAlgorithm:
1717
18-// ————————————————————————————————————————————————— Chat —————————————————————————————————————————————————
18+// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— //
19+// Edit is a convenient way to make quick changes to specific code and files.
1920
20-// Highlight the code below
21-// Press [Cmd + L] to add to Chat
22-// Try asking Continue "what sorting algorithm is this?"
21+// 1. Highlight the code below
22+// 2. Press [Cmd/Ctrl + I] to Edit
23+// 3. Try asking Continue to "make this more readable"
2324 public static int[] sortingAlgorithm(int[] x) {
2425 for (int i = 0; i < x.length; i++) {
2526 for (int j = 0; j < x.length - 1; j++) {
@@ -33,14 +34,12 @@
3334 return x;
3435 }
3536
36-// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L].
37-// This will add the code into the current chat
37+// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— //
38+// Chat makes it easy to ask for help from an LLM without needing to leave the IDE.
3839
39-// ————————————————————————————————————————————————— Edit —————————————————————————————————————————————————
40-
41-// Highlight the code below
42-// Press [Cmd + I] to Edit
43-// Try asking Continue to "make this more readable"
40+// 1. Highlight the code below
41+// 2. Press [Cmd/Ctrl + J] to add to Chat
42+// 3. Try asking Continue "what sorting algorithm is this?"
4443 public static int[] sortingAlgorithm2(int[] x) {
4544 for (int i = 0; i < x.length; i++) {
4645 for (int j = 0; j < x.length - 1; j++) {
@@ -54,15 +53,11 @@
5453 return x;
5554 }
5655
57-// ————————————————————————————————————————————— Autocomplete ——————————————————————————————————————————————
58-
59-// Place cursor after `sortingAlgorithm:` below and press [Enter]
60-// Press [Tab] to accept the Autocomplete suggestion
61-
62-// Basic assertion for sortingAlgorithm:
63-
64-
56+// ————————————————————————————————————————————————— Agent ————————————————————————————————————————————————— //
57+// Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing
58+// the model to make decisions and save you the work of manually finding context and performing actions.
6559
66-// —————————————————————————————————————————————- Learn More -——————————————————————————————————————————————
60+// 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box
61+// 2. Try asking Continue "Write unit tests for this code in a new file and run the test"
6762
68-// Visit the Continue Docs at https://docs.continue.dev/getting-started/overview
63+// —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— //
No newline at the end of the file
modified extensions/intellij/src/main/resources/continue_tutorial.py +23 −28
@@ -4,22 +4,24 @@
44 / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
55 \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
66
7- Chat, Edit, and Autocomplete tutorial
7+ Autocomplete, Edit, Chat, and Agent tutorial
88 """
99
10-# ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————-
1110
12-# First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon.
11+# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— #
12+# Autocomplete provides inline code suggestions as you type.
1313
14-# See an example at https://docs.continue.dev/getting-started/install
14+# 1. Place cursor after `sorting_algorithm:` below and press [Enter]
15+# 2. Press [Tab] to accept the Autocomplete suggestion
1516
16-# Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model.
17+# Basic assertion for sorting_algorithm:
1718
18-# ————————————————————————————————————————————————— Chat —————————————————————————————————————————————————
19+# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— #
20+# Edit is a convenient way to make quick changes to specific code and files.
1921
20-## Highlight the code below
21-## Press [Cmd + L] to add to Chat
22-## Try asking Continue "what sorting algorithm is this?"
22+# 1. Highlight the code below
23+# 2. Press [Cmd/Ctrl + I] to Edit
24+# 3. Try asking Continue to "make this more readable"
2325 def sorting_algorithm(x):
2426 for i in range(len(x)):
2527 for j in range(len(x) - 1):
@@ -27,31 +29,24 @@
2729 x[j], x[j + 1] = x[j + 1], x[j]
2830 return x
2931
30-# [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L].
31-# This will add the code into the current chat
32-
33-# ————————————————————————————————————————————————— Edit —————————————————————————————————————————————————
32+# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— #
33+# Chat makes it easy to ask for help from an LLM without needing to leave the IDE.
3434
35-## Highlight the code below
36-## Press [Cmd + I] to Edit
37-## Try asking Continue to "make this more readable"
38-def sorting_algorithm(x):
35+# 1. Highlight the code below
36+# 2. Press [Cmd/Ctrl + J] to add to Chat
37+# 3. Try asking Continue "what sorting algorithm is this?"
38+def sorting_algorithm2(x):
3939 for i in range(len(x)):
4040 for j in range(len(x) - 1):
4141 if x[j] > x[j + 1]:
4242 x[j], x[j + 1] = x[j + 1], x[j]
4343 return x
4444
45-# ————————————————————————————————————————————— Autocomplete ——————————————————————————————————————————————
46-
47-## Place cursor after `sorting_algorithm:` below and press [Enter]
48-## Press [Tab] to accept the Autocomplete suggestion
49-
50-# Basic assertion for sorting_algorithm:
51-
52-
53-
45+# ————————————————————————————————————————————————— Agent ————————————————————————————————————————————————— #
46+# Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing
47+# the model to make decisions and save you the work of manually finding context and performing actions.
5448
55-# —————————————————————————————————————————————- Learn More -——————————————————————————————————————————————
49+# 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box
50+# 2. Try asking Continue "Write unit tests for this code in a new file and run the test"
5651
57-# Visit the Continue Docs at https://docs.continue.dev/getting-started/overview
52+# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— #
No newline at the end of the file
modified extensions/intellij/src/main/resources/continue_tutorial.ts +22 −25
@@ -4,22 +4,23 @@
44 // / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
55 // \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
66 //
7-// Chat, Edit, and Autocomplete tutorial
7+// Autocomplete, Edit, Chat, and Agent tutorial
88 //
99
10-// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————-
10+// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— //
11+// Autocomplete provides inline code suggestions as you type.
1112
12-// First, open the Continue sidebar by pressing [Cmd + L] or clicking the Continue icon.
13+// 1. Place cursor after `sortingAlgorithm:` below and press [Enter]
14+// 2. Press [Tab] to accept the Autocomplete suggestion
1315
14-// See an example at https://docs.continue.dev/getting-started/install
15-
16-// Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model.
16+// Basic assertion for sortingAlgorithm:
1717
18-// ————————————————————————————————————————————————— Chat —————————————————————————————————————————————————
18+// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— //
19+// Edit is a convenient way to make quick changes to specific code and files.
1920
20-// Highlight the code below
21-// Press [Cmd + L] to add to Chat
22-// Try asking Continue "what sorting algorithm is this?"
21+// 1. Highlight the code below
22+// 2. Press [Cmd/Ctrl + I] to Edit
23+// 3. Try asking Continue to "make this more readable"
2324 function sortingAlgorithm(x: number[]): number[] {
2425 for (let i = 0; i < x.length; i++) {
2526 for (let j = 0; j < x.length - 1; j++) {
@@ -33,14 +34,12 @@
3334 return x;
3435 }
3536
36-// [Cmd + L] always starts a new chat. Now, try the same thing using [Cmd + Shift + L].
37-// This will add the code into the current chat
38-
39-// ————————————————————————————————————————————————— Edit —————————————————————————————————————————————————
37+// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— //
38+// Chat makes it easy to ask for help from an LLM without needing to leave the IDE.
4039
41-// Highlight the code below
42-// Press [Cmd + I] to Edit
43-// Try asking Continue to "make this more readable"
40+// 1. Highlight the code below
41+// 2. Press [Cmd/Ctrl + J] to add to Chat
42+// 3. Try asking Continue "what sorting algorithm is this?"
4443 function sortingAlgorithm2(x: number[]): number[] {
4544 for (let i = 0; i < x.length; i++) {
4645 for (let j = 0; j < x.length - 1; j++) {
@@ -54,13 +53,11 @@
5453 return x;
5554 }
5655
57-// ————————————————————————————————————————————— Autocomplete ——————————————————————————————————————————————
58-
59-// Place cursor after `sortingAlgorithm:` below and press [Enter]
60-// Press [Tab] to accept the Autocomplete suggestion
61-
62-// Basic assertion for sortingAlgorithm:
56+// ————————————————————————————————————————————————— Agent ————————————————————————————————————————————————— //
57+// Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing
58+// the model to make decisions and save you the work of manually finding context and performing actions.
6359
64-// —————————————————————————————————————————————- Learn More -——————————————————————————————————————————————
60+// 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box
61+// 2. Try asking Continue "Write unit tests for this code in a new file"
6562
66-// Visit the Continue Docs at https://docs.continue.dev/getting-started/overview
63+// —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— //
added extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt +94 −0
@@ -0,0 +1,94 @@
1+package com.github.continuedev.continueintellijextension.unit
2+
3+import com.github.continuedev.continueintellijextension.ApplyStateStatus
4+import com.github.continuedev.continueintellijextension.IDE
5+import com.github.continuedev.continueintellijextension.ApplyState
6+import com.github.continuedev.continueintellijextension.`continue`.ApplyToFileHandler
7+import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
8+import com.github.continuedev.continueintellijextension.editor.DiffStreamService
9+import com.github.continuedev.continueintellijextension.editor.EditorUtils
10+import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
11+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
12+import com.intellij.openapi.editor.Editor
13+import com.intellij.openapi.project.Project
14+import io.mockk.*
15+import kotlinx.coroutines.ExperimentalCoroutinesApi
16+import kotlinx.coroutines.test.runTest
17+import org.junit.jupiter.api.BeforeEach
18+import org.junit.jupiter.api.Test
19+
20+@ExperimentalCoroutinesApi
21+class ApplyToFileHandlerTest {
22+ // Mock all dependencies
23+ private val mockProject = mockk<Project>(relaxed = true)
24+ private val mockContinuePluginService = mockk<ContinuePluginService>(relaxed = true)
25+ private val mockIde = mockk<IDE>(relaxed = true)
26+ private val mockEditorUtils = mockk<EditorUtils>(relaxed = true)
27+ private val mockDiffStreamService = mockk<DiffStreamService>(relaxed = true)
28+ private val mockEditor = mockk<Editor>(relaxed = true)
29+ private val mockCoreMessenger = mockk<CoreMessenger>(relaxed = true)
30+
31+ // Test subject
32+ private lateinit var handler: ApplyToFileHandler
33+
34+ // Constants for testing
35+ private val testParams = ApplyToFileParams(
36+ "Sample text to apply",
37+ "stream123",
38+ "test/file.kt",
39+ "tool-call-123"
40+ )
41+
42+ @BeforeEach
43+ fun setUp() {
44+ // Common setup
45+ every { mockEditorUtils.editor } returns mockEditor
46+ every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
47+
48+ // Create the handler with mocked dependencies
49+ handler = ApplyToFileHandler(
50+ mockProject,
51+ mockContinuePluginService,
52+ mockIde,
53+ testParams,
54+ mockEditorUtils,
55+ mockDiffStreamService
56+ )
57+ }
58+
59+ @Test
60+ fun `should insert text directly when document is empty`() = runTest {
61+ // Given
62+ every { mockEditorUtils.isDocumentEmpty() } returns true
63+
64+ // When
65+ handler.handleApplyToFile()
66+
67+ // Then
68+ verify { mockEditorUtils.insertTextIntoEmptyDocument(testParams.text) }
69+ verify(exactly = 0) { mockDiffStreamService.register(any(), any()) } // Ensure no diff streaming happened
70+
71+ // Verify notifications sent
72+ verify {
73+ mockContinuePluginService.sendToWebview(
74+ eq("updateApplyState"),
75+ withArg { payload ->
76+ assert(payload is ApplyState)
77+ assert((payload as ApplyState).status == ApplyStateStatus.STREAMING.status)
78+ },
79+ any()
80+ )
81+ }
82+
83+ verify {
84+ mockContinuePluginService.sendToWebview(
85+ eq("updateApplyState"),
86+ withArg { payload ->
87+ assert(payload is ApplyState)
88+ assert((payload as ApplyState).status == ApplyStateStatus.CLOSED.status)
89+ },
90+ any()
91+ )
92+ }
93+ }
94+}
added extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/UriUtilsTest.kt +66 −0
@@ -0,0 +1,66 @@
1+package com.github.continuedev.continueintellijextension.unit
2+
3+import com.github.continuedev.continueintellijextension.`continue`.UriUtils
4+import org.junit.jupiter.api.Disabled
5+import org.junit.jupiter.api.Test
6+import java.io.File
7+import kotlin.test.assertEquals
8+
9+class UriUtilsTest {
10+ @Test
11+ fun testUriToFile() {
12+ val uri = "file:///path/to/file"
13+ val file = UriUtils.uriToFile(uri)
14+ assertEquals(File("/path/to/file"), file)
15+ }
16+
17+ @Disabled("Not working")
18+ @Test
19+ fun testUriToFileWithWindowsPath() {
20+ val uri = "file:///C:/path/to/file"
21+ val file = UriUtils.uriToFile(uri)
22+ assertEquals(File("C:/path/to/file"), file)
23+ }
24+
25+ @Test
26+ fun shouldHandleAuthorityComponent() {
27+ val uri = "file://C:/path/to/file"
28+ val file = UriUtils.uriToFile(uri)
29+ assertEquals(File("/C:/path/to/file"), file)
30+ }
31+
32+ @Test
33+ fun testUriToFileWithSpaces() {
34+ val uri = "file:///path/to/file%20with%20spaces"
35+ val file = UriUtils.uriToFile(uri)
36+ assertEquals(File("/path/to/file with spaces"), file)
37+ }
38+
39+ @Test
40+ fun testUriToFileWithSpecialCharacters() {
41+ val uri = "file:///path/to/file%23with%25special%26chars"
42+ val file = UriUtils.uriToFile(uri)
43+ assertEquals(File("/path/to/file#with%special&chars"), file)
44+ }
45+
46+ @Test
47+ fun testUriToFileWithQueryParams() {
48+ val uri = "file:///path/to/file?param=value"
49+ val file = UriUtils.uriToFile(uri)
50+ assertEquals(File("/path/to/file"), file)
51+ }
52+
53+ @Test
54+ fun testUriToFileWithWSLPath() {
55+ val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
56+ val file = UriUtils.uriToFile(uri)
57+ assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
58+ }
59+
60+ @Test
61+ fun testUriToFileWithWSLLocalhostPath() {
62+ val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
63+ val file = UriUtils.uriToFile(uri)
64+ assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
65+ }
66+}
added extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/utils/BrowserUtils.kt +76 −0
@@ -0,0 +1,76 @@
1+/**
2+ * Notes:
3+ * - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement
4+ * - Below is an AI generated summary of what the problem might be based on troubleshooting attempts
5+ * - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491
6+ *
7+ *
8+ * The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution.
9+ * When trying to call window.postIntellijMessage, we're encountering these challenges:
10+ *
11+ * 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally.
12+ * When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection
13+ * mechanism, creating nested injections that break.
14+ *
15+ * 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax
16+ * errors in the final JavaScript that gets executed.
17+ *
18+ * 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the
19+ * function was defined, causing scope/reference issues.
20+ *
21+ * The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test
22+ * framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser
23+ * context, not through another layer of script injection.
24+ */
25+package com.github.continuedev.continueintellijextension.utils
26+
27+import com.intellij.remoterobot.fixtures.JCefBrowserFixture
28+
29+/**
30+ * Utility functions for interacting with browser components in tests
31+ */
32+object BrowserUtils {
33+
34+ /**
35+ * Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser
36+ *
37+ * @param browser The JCefBrowserFixture to execute JavaScript in
38+ * @param messageType The type of message to send
39+ * @param messageData The data object to send as message payload
40+ * @param messageId A unique ID for the message
41+ */
42+ fun sendIntellijMessage(
43+ browser: JCefBrowserFixture,
44+ messageType: String,
45+ messageData: Any,
46+ messageId: String = "test-message-id"
47+ ) {
48+ // Convert the messageData to a JSON string
49+ val dataJson = when (messageData) {
50+ is String -> "\"$messageData\""
51+ else -> messageData.toString()
52+ }
53+
54+ val jsCode = """
55+ (function() {
56+ window.postIntellijMessage(
57+ "$messageType",
58+ $dataJson,
59+ "$messageId"
60+ );
61+ return true;
62+ })();
63+ """.trimIndent()
64+
65+ browser.executeJsInBrowser(jsCode)
66+ }
67+}
68+
69+// Extension function for JCefBrowserFixture for easier usage
70+fun JCefBrowserFixture.sendIntellijMessage(
71+ messageType: String,
72+ messageData: Any,
73+ messageId: String = "test-message-id"
74+) {
75+ BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId)
76+}
No newline at the end of the file
deleted extensions/vscode/CHANGELOG.md +0 −256
@@ -1,256 +0,0 @@
1-All notable changes to this project will be documented in this file.
2-
3-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
4-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
5-and is generated by [Changie](https://github.com/miniscruff/changie).
6-
7-
8-## 1.0.0 - 2025-02-26
9-### Added
10-* Introduces hub.continue.dev
11-* Improved apply quality
12-### Fixed
13-* Numerous reliability improvements
14-
15-## 0.8.66 - 2024-12-20
16-### Changed
17-* Improved autocomplete in untitled files
18-### Fixed
19-* Display more mid-line completions
20-* Restored syntax highlighting
21-* Fix tool use bug for models that don't support tools
22-* Autodetect mistral API key type
23-* Fixes Azure OpenAI regressions
24-
25-## 0.8.62 - 2024-12-10
26-### Added
27-* Tool use
28-* Support for Model Context Protocol
29-### Fixed
30-* hotfix: context providers no longer hidden when not in edit mode
31-
32-## 0.8.59 - 2024-11-25
33-### Fixed
34-* Hotfix for Ollama onboarding
35-
36-## 0.8.58 - 2024-11-22
37-### Added
38-* OpenAI predicted outputs support
39-* Improve codebase retrieval with BM25
40-* Support for Grok from xAI
41-* Chat enhancements including sticking input to bottom
42-* New UI for cmd+I in sidebar
43-* Support for Nebius LLM provider
44-* Support for Ask Sage LLM provider
45-* Improved reference for config.json
46-* New @web context provider
47-* Updates for llama3.2
48-* .continuerules file to set system prompt
49-* .prompt files v2
50-* Dedicated UI for docs indexing
51-* Clickable code symbols in chat
52-* Use clipboard content as autocomplete context
53-### Changed
54-* Improved @docs crawler
55-* Many improvements to make autocomplete more eager
56-* Near complete type definition retrieval for TypeScript autocomplete
57-* Remove footer from chat sidebar
58-### Fixed
59-* Brought back the Apply button for all code blocks
60-* Automatically update codebase index on removed files
61-
62-## 0.8.56 - 2024-11-08
63-### Added
64-* New Edit mode in sidebar (cmd/ctrl+I)
65-* Significantly faster and more accurate docs crawler by default
66-
67-## 0.8.55 - 2024-10-25
68-### Added
69-* Web context provider
70-* Cerebras inference provider
71-* Automatic descriptions for previous chats
72-* Discord context provider
73-* Improved full screen UI
74-### Changed
75-* Easier way to accept/reject/re-prompt after cmd/ctrl+I
76-
77-## 0.8.54 - 2024-10-15
78-### Fixed
79-* Hotfix: throttle transformers.js embeddings provider
80-
81-## 0.8.53 - 2024-10-11
82-### Added
83-* Improved loading/accept/reject UI for apply
84-* Polished chat sidebar, especially context dropdown
85-* Further prompt caching with Anthropic
86-### Changed
87-* Updated tutorial file
88-* Improved styling on "More" page
89-### Fixed
90-* Continue for teams auth bug fix
91-* Fixed a number of apply bugs
92-* Fixed autoscrolling behavior
93-
94-## 0.8.52 - 2024-09-16
95-### Changed
96-* Use Chromium only as a fallback after asking user
97-* Redesigned onboarding flow
98-
99-## 0.8.51 - 2024-09-05
100-### Fixed
101-* Fixed CRLF bug causing diff streams to treat every line as changed on Windows
102-
103-## 0.8.50 - 2024-09-02
104-### Fixed
105-* Hotfix for ability to use more than one inline context provider
106-
107-## 0.8.49 - 2024-09-01
108-### Fixed
109-* Hotfix: submenu context providers
110-
111-## 0.8.48 - 2024-09-01
112-### Added
113-* Improved indexing progress UI
114-* Improved @codebase using repomap
115-* Repo map context provider
116-### Fixed
117-* Many small UI improvements
118-* Fixes db.search not a function
119-
120-## 0.8.47 - 2024-08-27
121-### Added
122-* Use headless browser for crawling to get better results
123-* TTS support in the chat window
124-### Changed
125-* Improved support for WatsonX models
126-### Fixed
127-* Fixed several small indexing bugs
128-
129-## 0.8.46 - 2024-08-11
130-### Added
131-* new /onboard slash command
132-### Fixed
133-* Fixed problem loading config.ts
134-* Fixed bug causing duplicate indexing work
135-
136-## 0.8.45 - 2024-08-05
137-### Added
138-* Support for Llama 3.1 and gpt-4o-mini
139-* Support for WatsonX+Granite models
140-### Changed
141-* Significant improvements to indexing performance
142-* Improved @codebase quality by more accurately searching over file names and paths
143-* Improved @codebase accuracy
144-* Further improvements to indexing performance
145-### Fixed
146-* Improved docs indexing and management
147-* Fixed Gemini embeddings provider
148-
149-## 0.8.43 - 2024-07-08
150-### Added
151-* Improved indexing reliability and testing
152-* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
153-
154-## 0.8.42 - 2024-07-02
155-
156-### Added
157-
158-- Support for Gemini 1.5 Pro
159-- Link to code in the sidebar when using codebase retrieval
160-- Smoother onboarding experience
161-- .prompt files, a way of saving and sharing slash commands
162-- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
163-- Support for comments in config.json
164-- Specify multiple autocomplete models and switch between them
165-- Improved bracket matching strategy reduces noisy completions
166-
167-### Fixed
168-
169-- Numerous reliability upgrades to codebase indexing
170-
171-## 0.8.24 - 2024-04-12
172-### Added
173-* Support for improved retrieval models (Voyage embeddings/reranking)
174-* New @code context provider
175-* Personal usage analytics
176-
177-## 0.8.15 - 2024-03-05
178-### Added
179-* Tab-autocomplete in beta
180-
181-## 0.8.14 - 2024-03-03
182-### Added
183-* Image support
184-* Full-text search index for retrieval
185-* Docs context provider
186-* CodeLlama-70b support
187-### Changed
188-* config.ts only runs in NodeJS, not browser
189-### Fixed
190-* Fixed proxy setting in config.json
191-
192-## v0.8.2 - 2024-01-23
193-### Added
194-* Add codellama and gemini to free trial, using new server
195-* Local codebase syncing and embeddings using LanceDB
196-* Improved VS Code theme matching
197-### Changed
198-* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
199-* Context providers now run from the extension side (in Node.js instead of browser javascript)
200-
201-## v0.8.1 - 2024-01-08
202-
203-### Added
204-
205-- disableSessionTitles option in config.json
206-
207-### Changed
208-
209-- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
210-
211-## v0.6.19 - 2024-01-05
212-
213-### Added
214-
215-- support for .continuerc.json in root of workspace to override config.json
216-- Inline context providers
217-- cmd+shift+L with new diff streaming UI for edits
218-
219-### Changed
220-
221-- Allow certain LLM servers to handle templating
222-
223-## v0.6.16 - 2023-12-25
224-
225-### Changed
226-
227-- Context items are now kept around as a part of past messages, instead of staying at the main input
228-- No more Python server - Continue runs entirely in Typescript
229-
230-## v0.6.4 - 2023-11-19
231-
232-### Changed
233-
234-- migrated to .json config file format
235-
236-## v0.6.0 - 2023-11-10
237-
238-### Added
239-
240-- Full screen mode
241-- StackOverflow slash command to augment with web search
242-- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
243-
244-### Fixed
245-
246-- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor
247-
248-## v0.5.0 - 2023-11-09
249-
250-### Added
251-
252-- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
253-
254-### Changed
255-
256-- Switch from Websockets to Socket.io
modified extensions/vscode/CONTRIBUTING.md +0 −4
@@ -12,7 +12,3 @@
1212 # How to run and debug tests
1313
1414 After following the setup in [Environment Setup](../../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code.
15-
16-## Notes
17-
18-- We require vscode engine `^1.67.0` and use `@types/vscode` version `1.67.0` because this is the earliest version that doesn't break any of the APIs we are using. If you go back to `1.66.0`, then it will break `vscode.window.tabGroups`.
modified extensions/vscode/continue_tutorial.py +28 −19
@@ -4,15 +4,24 @@
44 / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
55 \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
66
7- Chat, Edit, and Autocomplete tutorial
7+ Autocomplete, Edit, Chat, and Agent tutorial
88 """
99
1010
11-# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— #
11+# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— #
12+# Autocomplete provides inline code suggestions as you type.
13+
14+# 1. Place cursor after `sorting_algorithm:` below and press [Enter]
15+# 2. Press [Tab] to accept the Autocomplete suggestion
1216
13-## Highlight the code below
14-## Press [Cmd/Ctrl + L] to add to Chat
15-## Try asking Continue "what sorting algorithm is this?"
17+# Basic assertion for sorting_algorithm:
18+
19+# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— #
20+# Edit is a convenient way to make quick changes to specific code and files.
21+
22+# 1. Highlight the code below
23+# 2. Press [Cmd/Ctrl + I] to Edit
24+# 3. Try asking Continue to "make this more readable"
1625 def sorting_algorithm(x):
1726 for i in range(len(x)):
1827 for j in range(len(x) - 1):
@@ -20,25 +29,25 @@
2029 x[j], x[j + 1] = x[j + 1], x[j]
2130 return x
2231
23-
24-# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— #
25-
26-## Highlight the code below
27-## Press [Cmd/Ctrl + I] to Edit
28-## Try asking Continue to "make this more readable"
29-def sorting_algorithm(x):
32+# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— #
33+# Chat makes it easy to ask for help from an LLM without needing to leave the IDE.
34+
35+# 1. Highlight the code below
36+# 2. Press [Cmd/Ctrl + L] to add to Chat
37+# 3. Try asking Continue "what sorting algorithm is this?"
38+def sorting_algorithm2(x):
3039 for i in range(len(x)):
3140 for j in range(len(x) - 1):
3241 if x[j] > x[j + 1]:
3342 x[j], x[j + 1] = x[j + 1], x[j]
3443 return x
3544
36-# ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— #
37-
38-## Place cursor after `sorting_algorithm...` below and press [Enter]
39-## Press [Tab] to accept the Autocomplete suggestion
40-
41-# Basic assertion for sorting_algorithm...
45+# ————————————————————————————————————————————————— Agent ————————————————————————————————————————————————— #
46+# Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing
47+# the model to make decisions and save you the work of manually finding context and performing actions.
4248
49+# 1. Switch from "Chat" to "Agent" mode using the dropdown in the bottom left of the input box
50+# 2. Try asking Continue "Write unit tests for this code in a new file",
51+# or if you have Python installed, "Write unit tests for this code in a new file and run the test"
4352
44-# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— #
53+# —————————————————— Learn more at https://docs.continue.dev/getting-started/overview ——————————————————— #
No newline at the end of the file
modified extensions/vscode/e2e/selectors/GUI.selectors.ts +9 −1
@@ -46,7 +46,7 @@
4646 }
4747
4848 public static getToolCallStatusMessage(view: WebView) {
49- return SelectorUtils.getElementByDataTestId(view, "toggle-div-title");
49+ return SelectorUtils.getElementByDataTestId(view, "tool-call-title");
5050 }
5151
5252 public static getToolButton(view: WebView) {
@@ -89,6 +89,14 @@
8989 );
9090 }
9191
92+ public static getRulesPeek(view: WebView) {
93+ return SelectorUtils.getElementByDataTestId(view, "rules-peek");
94+ }
95+
96+ public static getFirstRulesPeekItem(view: WebView) {
97+ return SelectorUtils.getElementByDataTestId(view, "rules-peek-item");
98+ }
99+
92100 public static getNthHistoryTableRow(view: WebView, index: number) {
93101 return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`);
94102 }
modified extensions/vscode/e2e/tests/GUI.test.ts +44 −1
@@ -245,6 +245,47 @@
245245 await GUIActions.selectModeFromDropdown(view, "Agent");
246246 });
247247
248+ it("should display rules peek and show rule details", async () => {
249+ // Send a message to trigger the model response
250+ const [messageInput] = await GUISelectors.getMessageInputFields(view);
251+ await messageInput.sendKeys("Hello");
252+ await messageInput.sendKeys(Key.ENTER);
253+
254+ // Wait for the response to appear
255+ await TestUtils.waitForSuccess(() =>
256+ GUISelectors.getThreadMessageByText(view, "I'm going to call a tool:"),
257+ );
258+
259+ // Verify that "1 rule" text appears
260+ const rulesPeek = await TestUtils.waitForSuccess(() =>
261+ GUISelectors.getRulesPeek(view),
262+ );
263+ const rulesPeekText = await rulesPeek.getText();
264+ expect(rulesPeekText).to.include("1 rule");
265+
266+ // Click on the rules peek to expand it
267+ await rulesPeek.click();
268+
269+ // Wait for the rule details to appear
270+ const ruleItem = await TestUtils.waitForSuccess(() =>
271+ GUISelectors.getFirstRulesPeekItem(view),
272+ );
273+
274+ await TestUtils.waitForSuccess(async () => {
275+ const text = await ruleItem.getText();
276+ if (!text || text.trim() === "") {
277+ throw new Error("Rule item text is empty");
278+ }
279+ return ruleItem;
280+ });
281+
282+ // Verify the rule content
283+ const ruleItemText = await ruleItem.getText();
284+ expect(ruleItemText).to.include("Assistant rule");
285+ expect(ruleItemText).to.include("Always applied");
286+ expect(ruleItemText).to.include("TEST_SYS_MSG");
287+ }).timeout(DEFAULT_TIMEOUT.MD);
288+
248289 it("should render tool call", async () => {
249290 const [messageInput] = await GUISelectors.getMessageInputFields(view);
250291 await messageInput.sendKeys("Hello");
@@ -258,7 +299,9 @@
258299 expect(await statusMessage.getText()).contain(
259300 "Continue viewed the git diff",
260301 );
261- }).timeout(DEFAULT_TIMEOUT.MD);
302+ // wait for 30 seconds, promise
303+ await new Promise((resolve) => setTimeout(resolve, 30000));
304+ }).timeout(DEFAULT_TIMEOUT.MD * 100);
262305
263306 it("should call tool after approval", async () => {
264307 await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
modified extensions/vscode/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 extensions/vscode/package.json +5 −6
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.34",
5+ "version": "1.1.39",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -105,7 +105,7 @@
105105 "continue.enableQuickActions": {
106106 "type": "boolean",
107107 "default": false,
108- "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/features/quick-actions)"
108+ "markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/customize/deep-dives/vscode-actions#quick-actions)"
109109 },
110110 "continue.enableTabAutocomplete": {
111111 "type": "boolean",
@@ -631,7 +631,7 @@
631631 "devDependencies": {
632632 "@biomejs/biome": "1.6.4",
633633 "@nestjs/common": "^11.0.16",
634- "@openapitools/openapi-generator-cli": "^2.5.2",
634+ "@openapitools/openapi-generator-cli": "^2.20.0",
635635 "@types/chai": "^5.0.1",
636636 "@types/cors": "^2.8.17",
637637 "@types/express": "^4.17.21",
@@ -657,12 +657,11 @@
657657 "rimraf": "^5.0.5",
658658 "typescript": "^5.6.3",
659659 "vite": "^4.5.14",
660- "vsce": "^2.15.0",
661660 "vscode-extension-tester": "^8.14.1"
662661 },
663662 "dependencies": {
664663 "@continuedev/config-types": "^1.0.14",
665- "@continuedev/fetch": "^1.0.3",
664+ "@continuedev/fetch": "^1.0.10",
666665 "@electron/rebuild": "^3.2.10",
667666 "@reduxjs/toolkit": "^1.9.3",
668667 "@types/node-fetch": "^2.6.11",
@@ -705,7 +704,7 @@
705704 "svg-builder": "^2.0.0",
706705 "systeminformation": "^5.23.7",
707706 "tailwindcss": "^3.3.2",
708- "undici": "^6.2.0",
707+ "undici": "^6.21.3",
709708 "uuid": "^9.0.1",
710709 "uuidv4": "^6.2.13",
711710 "vectordb": "^0.4.20",
modified extensions/vscode/scripts/package.js +2 −2
@@ -19,8 +19,8 @@
1919 const isPreRelease = args.includes("--pre-release");
2020
2121 let command = isPreRelease
22- ? "npx vsce package --out ./build --pre-release --no-dependencies" // --yarn"
23- : "npx vsce package --out ./build --no-dependencies"; // --yarn";
22+ ? "npx @vscode/vsce package --out ./build --pre-release --no-dependencies" // --yarn"
23+ : "npx @vscode/vsce package --out ./build --no-dependencies"; // --yarn";
2424
2525 if (target) {
2626 command += ` --target ${target}`;
modified extensions/vscode/src/commands.ts +14 −4
@@ -97,6 +97,7 @@
9797 action: "accept" | "reject",
9898 sidebar: ContinueGUIWebviewViewProvider,
9999 ide: VsCodeIde,
100+ core: Core,
100101 verticalDiffManager: VerticalDiffManager,
101102 newFileUri?: string,
102103 streamId?: string,
@@ -121,6 +122,9 @@
121122
122123 // Clear vertical diffs depending on action
123124 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
125+ if (action === "reject") {
126+ core.invoke("cancelApply", undefined);
127+ }
124128
125129 if (streamId) {
126130 const fileContent = await ide.readFile(newOrCurrentUri);
@@ -236,18 +240,20 @@
236240 "accept",
237241 sidebar,
238242 ide,
243+ core,
239244 verticalDiffManager,
240245 newFileUri,
241246 streamId,
242247 ),
243248
244- "continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
249+ "continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
245250 processDiff(
246251 "reject",
247252 sidebar,
248253 ide,
254+ core,
249255 verticalDiffManager,
250- newFilepath,
256+ newFileUri,
251257 streamId,
252258 ),
253259 "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@@ -573,11 +579,15 @@
573579 await addEntireFileToContext(
574580 vscode.Uri.parse(fileUri),
575581 sidebar.webviewProtocol,
576- ide.ideUtils
582+ ide.ideUtils,
577583 );
578584 }
579585 } else {
580- await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
586+ await addEntireFileToContext(
587+ uri,
588+ sidebar.webviewProtocol,
589+ ide.ideUtils,
590+ );
581591 }
582592 }
583593 },
modified extensions/vscode/src/diff/vertical/handler.ts +204 −194
@@ -23,22 +23,16 @@
2323 }
2424
2525 export class VerticalDiffHandler implements vscode.Disposable {
26+ public insertedInCurrentBlock = 0;
27+ disposables: vscode.Disposable[] = [];
2628 private currentLineIndex: number;
2729 private cancelled = false;
2830 private newLinesAdded = 0;
2931 private deletionBuffer: string[] = [];
3032 private removedLineDecorations: RemovedLineDecorationManager;
3133 private addedLineDecorations: AddedLineDecorationManager;
32-
33- private get fileUri() {
34- return this.editor.document.uri.toString();
35- }
36- public insertedInCurrentBlock = 0;
37- public get range(): vscode.Range {
38- const startLine = Math.min(this.startLine, this.endLine);
39- const endLine = Math.max(this.startLine, this.endLine);
40- return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
41- }
34+ private _diffLinesQueue: DiffLine[] = [];
35+ private _queueLock = false;
4236
4337 constructor(
4438 private startLine: number,
@@ -79,149 +73,18 @@
7973 this.disposables.push(disposable);
8074 }
8175
82- private async insertDeletionBuffer() {
83- if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
84- const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
85-
86- blocks.push({
87- start: this.currentLineIndex - this.insertedInCurrentBlock,
88- numRed: this.deletionBuffer.length,
89- numGreen: this.insertedInCurrentBlock,
90- });
91-
92- this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
93- }
94-
95- if (this.deletionBuffer.length === 0) {
96- this.insertedInCurrentBlock = 0;
97- return;
98- }
99-
100- // Insert the block of deleted lines as empty new lines
101- await this.insertTextAboveLine(
102- this.currentLineIndex - this.insertedInCurrentBlock,
103- "\n".repeat(this.deletionBuffer.length - 1),
104- );
105-
106- this.removedLineDecorations.addLines(
107- this.currentLineIndex - this.insertedInCurrentBlock,
108- this.deletionBuffer,
109- );
110-
111- // Shift green decorations downward
112- this.addedLineDecorations.shiftDownAfterLine(
113- this.currentLineIndex - this.insertedInCurrentBlock,
114- this.deletionBuffer.length,
115- );
116-
117- // Update line index, clear buffer
118- for (let i = 0; i < this.deletionBuffer.length; i++) {
119- this.incrementCurrentLineIndex();
120- }
121-
122- this.deletionBuffer = [];
123- this.insertedInCurrentBlock = 0;
124- this.refreshCodeLens();
125- }
126-
127- private incrementCurrentLineIndex() {
128- this.currentLineIndex++;
129- this.updateIndexLineDecorations();
130- }
131-
132- private async insertTextAboveLine(index: number, text: string) {
133- await this.editor.edit(
134- (editBuilder) => {
135- const lineCount = this.editor.document.lineCount;
136- if (index >= lineCount) {
137- // Append to end of file
138- editBuilder.insert(
139- new vscode.Position(
140- lineCount,
141- this.editor.document.lineAt(lineCount - 1).text.length,
142- ),
143- `\n${text}`,
144- );
145- } else {
146- editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
147- }
148- },
149- {
150- undoStopAfter: false,
151- undoStopBefore: false,
152- },
153- );
154- }
155-
156- private async insertLineAboveIndex(index: number, line: string) {
157- await this.insertTextAboveLine(index, line);
158- this.addedLineDecorations.addLine(index);
159- this.newLinesAdded++;
160- }
161-
162- private async deleteLinesAt(index: number, numLines = 1) {
163- const startLine = new vscode.Position(index, 0);
164- await this.editor.edit(
165- (editBuilder) => {
166- editBuilder.delete(
167- new vscode.Range(startLine, startLine.translate(numLines)),
168- );
169- },
170- {
171- undoStopAfter: false,
172- undoStopBefore: false,
173- },
174- );
175- }
176-
177- private async deleteRangeLines(ranges: vscode.Range[]) {
178- await this.editor.edit(
179- (editBuilder) => {
180- for (const range of ranges) {
181- editBuilder.delete(
182- new vscode.Range(
183- range.start,
184- new vscode.Position(range.end.line + 1, 0),
185- ),
186- );
187- }
188- },
189- {
190- undoStopAfter: false,
191- undoStopBefore: false,
192- },
193- );
76+ public get range(): vscode.Range {
77+ const startLine = Math.min(this.startLine, this.endLine);
78+ const endLine = Math.max(this.startLine, this.endLine);
79+ return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
19480 }
19581
196- private updateIndexLineDecorations() {
197- if (this.options.instant) {
198- // We don't show progress on instant apply
199- return;
200- }
201-
202- // Highlight the line at the currentLineIndex
203- // And lightly highlight all lines between that and endLine
204- if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
205- this.editor.setDecorations(indexDecorationType, []);
206- this.editor.setDecorations(belowIndexDecorationType, []);
207- } else {
208- const start = new vscode.Position(this.currentLineIndex, 0);
209- this.editor.setDecorations(indexDecorationType, [
210- new vscode.Range(
211- start,
212- new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
213- ),
214- ]);
215- const end = new vscode.Position(this.endLine, 0);
216- this.editor.setDecorations(belowIndexDecorationType, [
217- new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
218- ]);
219- }
82+ get isCancelled() {
83+ return this.cancelled;
22084 }
22185
222- private clearIndexLineDecorations() {
223- this.editor.setDecorations(belowIndexDecorationType, []);
224- this.editor.setDecorations(indexDecorationType, []);
86+ private get fileUri() {
87+ return this.editor.document.uri.toString();
22588 }
22689
22790 async clear(accept: boolean) {
@@ -257,19 +120,10 @@
257120 this.dispose();
258121 }
259122
260- disposables: vscode.Disposable[] = [];
261-
262123 dispose() {
263124 this.disposables.forEach((disposable) => disposable.dispose());
264125 }
265126
266- get isCancelled() {
267- return this.cancelled;
268- }
269-
270- private _diffLinesQueue: DiffLine[] = [];
271- private _queueLock = false;
272-
273127 async queueDiffLine(diffLine: DiffLine | undefined) {
274128 if (diffLine) {
275129 this._diffLinesQueue.push(diffLine);
@@ -299,25 +153,6 @@
299153 this._queueLock = false;
300154 }
301155
302- private async _handleDiffLine(diffLine: DiffLine) {
303- switch (diffLine.type) {
304- case "same":
305- await this.insertDeletionBuffer();
306- this.incrementCurrentLineIndex();
307- break;
308- case "old":
309- // Add to deletion buffer and delete the line for now
310- this.deletionBuffer.push(diffLine.line);
311- await this.deleteLinesAt(this.currentLineIndex);
312- break;
313- case "new":
314- await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
315- this.incrementCurrentLineIndex();
316- this.insertedInCurrentBlock++;
317- break;
318- }
319- }
320-
321156 async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
322157 let diffLines = [];
323158
@@ -338,6 +173,12 @@
338173
339174 await this.reapplyWithMyersDiff(diffLines);
340175
176+ const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
177+ this.editor.revealRange(
178+ range,
179+ vscode.TextEditorRevealType.Default,
180+ );
181+
341182 this.options.onStatusUpdate(
342183 "done",
343184 this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
@@ -410,23 +251,6 @@
410251 }
411252 }
412253
413- private shiftCodeLensObjects(startLine: number, offset: number) {
414- // Shift the codelens objects
415- const blocks =
416- this.editorToVerticalDiffCodeLens
417- .get(this.fileUri)
418- ?.filter((x) => x.start !== startLine)
419- .map((x) => {
420- if (x.start > startLine) {
421- return { ...x, start: x.start + offset };
422- }
423- return x;
424- }) || [];
425- this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
426-
427- this.refreshCodeLens();
428- }
429-
430254 public updateLineDelta(
431255 fileUri: string,
432256 startLine: number,
@@ -550,4 +374,190 @@
550374 this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
551375 this.refreshCodeLens();
552376 }
377+
378+ private async insertDeletionBuffer() {
379+ if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
380+ const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
381+
382+ blocks.push({
383+ start: this.currentLineIndex - this.insertedInCurrentBlock,
384+ numRed: this.deletionBuffer.length,
385+ numGreen: this.insertedInCurrentBlock,
386+ });
387+
388+ this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
389+ }
390+
391+ if (this.deletionBuffer.length === 0) {
392+ this.insertedInCurrentBlock = 0;
393+ return;
394+ }
395+
396+ // Insert the block of deleted lines as empty new lines
397+ await this.insertTextAboveLine(
398+ this.currentLineIndex - this.insertedInCurrentBlock,
399+ "\n".repeat(this.deletionBuffer.length - 1),
400+ );
401+
402+ this.removedLineDecorations.addLines(
403+ this.currentLineIndex - this.insertedInCurrentBlock,
404+ this.deletionBuffer,
405+ );
406+
407+ // Shift green decorations downward
408+ this.addedLineDecorations.shiftDownAfterLine(
409+ this.currentLineIndex - this.insertedInCurrentBlock,
410+ this.deletionBuffer.length,
411+ );
412+
413+ // Update line index, clear buffer
414+ for (let i = 0; i < this.deletionBuffer.length; i++) {
415+ this.incrementCurrentLineIndex();
416+ }
417+
418+ this.deletionBuffer = [];
419+ this.insertedInCurrentBlock = 0;
420+ this.refreshCodeLens();
421+ }
422+
423+ private incrementCurrentLineIndex() {
424+ this.currentLineIndex++;
425+ this.updateIndexLineDecorations();
426+ const range = new vscode.Range(this.currentLineIndex, 0, this.currentLineIndex, 0);
427+ this.editor.revealRange(
428+ range,
429+ vscode.TextEditorRevealType.Default,
430+ );
431+ }
432+
433+ private async insertTextAboveLine(index: number, text: string) {
434+ await this.editor.edit(
435+ (editBuilder) => {
436+ const lineCount = this.editor.document.lineCount;
437+ if (index >= lineCount) {
438+ // Append to end of file
439+ editBuilder.insert(
440+ new vscode.Position(
441+ lineCount,
442+ this.editor.document.lineAt(lineCount - 1).text.length,
443+ ),
444+ `\n${text}`,
445+ );
446+ } else {
447+ editBuilder.insert(new vscode.Position(index, 0), `${text}\n`);
448+ }
449+ },
450+ {
451+ undoStopAfter: false,
452+ undoStopBefore: false,
453+ },
454+ );
455+ }
456+
457+ private async insertLineAboveIndex(index: number, line: string) {
458+ await this.insertTextAboveLine(index, line);
459+ this.addedLineDecorations.addLine(index);
460+ this.newLinesAdded++;
461+ }
462+
463+ private async deleteLinesAt(index: number, numLines = 1) {
464+ const startLine = new vscode.Position(index, 0);
465+ await this.editor.edit(
466+ (editBuilder) => {
467+ editBuilder.delete(
468+ new vscode.Range(startLine, startLine.translate(numLines)),
469+ );
470+ },
471+ {
472+ undoStopAfter: false,
473+ undoStopBefore: false,
474+ },
475+ );
476+ }
477+
478+ private async deleteRangeLines(ranges: vscode.Range[]) {
479+ await this.editor.edit(
480+ (editBuilder) => {
481+ for (const range of ranges) {
482+ editBuilder.delete(
483+ new vscode.Range(
484+ range.start,
485+ new vscode.Position(range.end.line + 1, 0),
486+ ),
487+ );
488+ }
489+ },
490+ {
491+ undoStopAfter: false,
492+ undoStopBefore: false,
493+ },
494+ );
495+ }
496+
497+ private updateIndexLineDecorations() {
498+ if (this.options.instant) {
499+ // We don't show progress on instant apply
500+ return;
501+ }
502+
503+ // Highlight the line at the currentLineIndex
504+ // And lightly highlight all lines between that and endLine
505+ if (this.currentLineIndex - this.newLinesAdded >= this.endLine) {
506+ this.editor.setDecorations(indexDecorationType, []);
507+ this.editor.setDecorations(belowIndexDecorationType, []);
508+ } else {
509+ const start = new vscode.Position(this.currentLineIndex, 0);
510+ this.editor.setDecorations(indexDecorationType, [
511+ new vscode.Range(
512+ start,
513+ new vscode.Position(start.line, Number.MAX_SAFE_INTEGER),
514+ ),
515+ ]);
516+ const end = new vscode.Position(this.endLine, 0);
517+ this.editor.setDecorations(belowIndexDecorationType, [
518+ new vscode.Range(start.translate(1), end.translate(this.newLinesAdded)),
519+ ]);
520+ }
521+ }
522+
523+ private clearIndexLineDecorations() {
524+ this.editor.setDecorations(belowIndexDecorationType, []);
525+ this.editor.setDecorations(indexDecorationType, []);
526+ }
527+
528+ private async _handleDiffLine(diffLine: DiffLine) {
529+ switch (diffLine.type) {
530+ case "same":
531+ await this.insertDeletionBuffer();
532+ this.incrementCurrentLineIndex();
533+ break;
534+ case "old":
535+ // Add to deletion buffer and delete the line for now
536+ this.deletionBuffer.push(diffLine.line);
537+ await this.deleteLinesAt(this.currentLineIndex);
538+ break;
539+ case "new":
540+ await this.insertLineAboveIndex(this.currentLineIndex, diffLine.line);
541+ this.incrementCurrentLineIndex();
542+ this.insertedInCurrentBlock++;
543+ break;
544+ }
545+ }
546+
547+ private shiftCodeLensObjects(startLine: number, offset: number) {
548+ // Shift the codelens objects
549+ const blocks =
550+ this.editorToVerticalDiffCodeLens
551+ .get(this.fileUri)
552+ ?.filter((x) => x.start !== startLine)
553+ .map((x) => {
554+ if (x.start > startLine) {
555+ return { ...x, start: x.start + offset };
556+ }
557+ return x;
558+ }) || [];
559+ this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks);
560+
561+ this.refreshCodeLens();
562+ }
553563 }
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
@@ -1,5 +1,4 @@
11 import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
2-import { ConfigHandler } from "core/config/ConfigHandler";
32 import { streamDiffLines } from "core/edit/streamDiffLines";
43 import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
54 import { getMarkdownLanguageTagForFile } from "core/util";
@@ -31,7 +30,6 @@
3130 logDiffs: DiffLine[] | undefined;
3231
3332 constructor(
34- private readonly configHandler: ConfigHandler,
3533 private readonly webviewProtocol: VsCodeWebviewProtocol,
3634 private readonly editDecorationManager: EditDecorationManager,
3735 ) {
@@ -43,12 +41,12 @@
4341 startLine: number,
4442 endLine: number,
4543 options: VerticalDiffHandlerOptions,
46- ) {
44+ ): VerticalDiffHandler | undefined {
4745 if (this.fileUriToHandler.has(fileUri)) {
4846 this.fileUriToHandler.get(fileUri)?.clear(false);
4947 this.fileUriToHandler.delete(fileUri);
5048 }
51- const editor = vscode.window.activeTextEditor; // TODO
49+ const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
5250 if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
5351 const handler = new VerticalDiffHandler(
5452 startLine,
@@ -453,6 +451,7 @@
453451 language: getMarkdownLanguageTagForFile(fileUri),
454452 onlyOneInsertion: !!onlyOneInsertion,
455453 overridePrompt,
454+ abortControllerId: fileUri,
456455 });
457456
458457 for await (const line of stream) {
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
@@ -130,7 +130,6 @@
130130 this.configHandler.loadConfig();
131131
132132 this.verticalDiffManager = new VerticalDiffManager(
133- this.configHandler,
134133 this.sidebar.webviewProtocol,
135134 this.editDecorationManager,
136135 );
modified extensions/vscode/src/extension/VsCodeMessenger.ts +13 −0
@@ -15,6 +15,7 @@
1515 import { stripImages } from "core/util/messageContent";
1616 import * as vscode from "vscode";
1717
18+import { DataLogger } from "core/data/log";
1819 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
1920 import { ApplyManager } from "../apply";
2021 import { VerticalDiffManager } from "../diff/vertical/manager";
@@ -228,6 +229,18 @@
228229 ),
229230 rulesToInclude: config.rules,
230231 });
232+
233+ // Log dev data
234+ await DataLogger.getInstance().logDevData({
235+ name: "editInteraction",
236+ data: {
237+ prompt: stripImages(prompt),
238+ completion: fileAfterEdit ?? "",
239+ modelProvider: model.providerName,
240+ modelTitle: model.title ?? "",
241+ },
242+ });
243+
231244 return fileAfterEdit;
232245 });
233246
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +36 −7
@@ -1,6 +1,5 @@
11 import crypto from "crypto";
22
3-import { ControlPlaneSessionInfo } from "core/control-plane/client";
43 import { getControlPlaneEnvSync } from "core/control-plane/env";
54 import fetch from "node-fetch";
65 import { v4 as uuidv4 } from "uuid";
@@ -18,6 +17,12 @@
1817 window,
1918 } from "vscode";
2019
20+import {
21+ AuthType,
22+ ControlPlaneSessionInfo,
23+ HubEnv,
24+ isHubEnv,
25+} from "core/control-plane/AuthTypes";
2126 import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
2227 import { SecretStorage } from "./SecretStorage";
2328 import { UriEventHandler } from "./uriHandler";
@@ -280,12 +285,21 @@
280285 try {
281286 const codeVerifier = generateRandomString(64);
282287 const codeChallenge = await generateCodeChallenge(codeVerifier);
283- const token = await this.login(codeChallenge, scopes);
288+
289+ if (!isHubEnv(controlPlaneEnv)) {
290+ throw new Error("Login is disabled");
291+ }
292+
293+ const token = await this.login(codeChallenge, controlPlaneEnv, scopes);
284294 if (!token) {
285295 throw new Error(`Continue login failure`);
286296 }
287297
288- const userInfo = (await this.getUserInfo(token, codeVerifier)) as any;
298+ const userInfo = (await this.getUserInfo(
299+ token,
300+ codeVerifier,
301+ controlPlaneEnv,
302+ )) as any;
289303 const { user, access_token, refresh_token } = userInfo;
290304
291305 const session: ContinueAuthenticationSession = {
@@ -352,7 +366,11 @@
352366 /**
353367 * Log in to Continue
354368 */
355- private async login(codeChallenge: string, scopes: string[] = []) {
369+ private async login(
370+ codeChallenge: string,
371+ hubEnv: HubEnv,
372+ scopes: string[] = [],
373+ ) {
356374 return await window.withProgress<string>(
357375 {
358376 location: ProgressLocation.Notification,
@@ -369,7 +387,7 @@
369387 const url = new URL("https://api.workos.com/user_management/authorize");
370388 const params = {
371389 response_type: "code",
372- client_id: controlPlaneEnv.WORKOS_CLIENT_ID,
390+ client_id: hubEnv.WORKOS_CLIENT_ID,
373391 redirect_uri: this.redirectUri,
374392 state: stateId,
375393 code_challenge: codeChallenge,
@@ -458,7 +476,11 @@
458476 * @param token
459477 * @returns
460478 */
461- private async getUserInfo(token: string, codeVerifier: string) {
479+ private async getUserInfo(
480+ token: string,
481+ codeVerifier: string,
482+ hubEnv: HubEnv,
483+ ) {
462484 const resp = await fetch(
463485 "https://api.workos.com/user_management/authenticate",
464486 {
@@ -467,7 +489,7 @@
467489 "Content-Type": "application/json",
468490 },
469491 body: JSON.stringify({
470- client_id: controlPlaneEnv.WORKOS_CLIENT_ID,
492+ client_id: hubEnv.WORKOS_CLIENT_ID,
471493 code_verifier: codeVerifier,
472494 grant_type: "authorization_code",
473495 code: token,
@@ -484,6 +506,12 @@
484506 silent: boolean,
485507 useOnboarding: boolean,
486508 ): Promise<ControlPlaneSessionInfo | undefined> {
509+ if (!isHubEnv(controlPlaneEnv)) {
510+ return {
511+ AUTH_TYPE: AuthType.OnPrem,
512+ };
513+ }
514+
487515 try {
488516 if (useOnboarding) {
489517 WorkOsAuthProvider.useOnboardingUri = true;
@@ -498,6 +526,7 @@
498526 return undefined;
499527 }
500528 return {
529+ AUTH_TYPE: controlPlaneEnv.AUTH_TYPE,
501530 accessToken: session.accessToken,
502531 account: {
503532 id: session.account.id,
modified gui/.eslintrc.json +1 −1
@@ -3,7 +3,7 @@
33 "parser": "@typescript-eslint/parser",
44 "plugins": ["@typescript-eslint", "eslint-plugin-react"],
55 "parserOptions": {
6- "project": "gui/tsconfig.json"
6+ "project": ["tsconfig.json", "tsconfig.node.json"]
77 },
88 "extends": [
99 // "eslint:recommended",
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 +2 −1
@@ -12,7 +12,8 @@
1212 "test": "vitest run",
1313 "test:coverage": "vitest run --coverage",
1414 "test:ui": "vitest --ui",
15- "test:watch": "vitest"
15+ "test:watch": "vitest",
16+ "lint": "eslint --ext ts"
1617 },
1718 "dependencies": {
1819 "@continuedev/config-yaml": "file:../packages/config-yaml",
modified gui/src/App.tsx +5 −0
@@ -9,6 +9,7 @@
99 import Chat from "./pages/gui";
1010 import History from "./pages/history";
1111 import Stats from "./pages/stats";
12+import ThemePage from "./styles/ThemePage";
1213 import { ROUTES } from "./util/navigation";
1314
1415 const router = createMemoryRouter([
@@ -37,6 +38,10 @@
3738 path: ROUTES.CONFIG,
3839 element: <ConfigPage />,
3940 },
41+ {
42+ path: ROUTES.THEME,
43+ element: <ThemePage />,
44+ },
4045 ],
4146 },
4247 ]);
deleted gui/src/components/AcceptRejectAllButtons.tsx +0 −85
@@ -1,85 +0,0 @@
1-import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
2-import { ApplyState } from "core";
3-import { useContext } from "react";
4-import { IdeMessengerContext } from "../context/IdeMessenger";
5-import { getMetaKeyLabel } from "../util";
6-import { useFontSize } from "./ui/font";
7-
8-export interface AcceptRejectAllButtonsProps {
9- applyStates: ApplyState[];
10- onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
11-}
12-
13-export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
14-
15-export default function AcceptRejectAllButtons({
16- applyStates,
17- onAcceptOrReject,
18-}: AcceptRejectAllButtonsProps) {
19- const pendingApplyStates = applyStates.filter(
20- (state) => state.status === "done",
21- );
22- const ideMessenger = useContext(IdeMessengerContext);
23-
24- const tinyFont = useFontSize(-3);
25- async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
26- for (const { filepath = "", streamId } of pendingApplyStates) {
27- ideMessenger.post(status, {
28- filepath,
29- streamId,
30- });
31- }
32-
33- if (onAcceptOrReject) {
34- onAcceptOrReject(status);
35- }
36- }
37-
38- if (!pendingApplyStates.length) {
39- return null;
40- }
41-
42- return (
43- <div className="flex flex-row items-center justify-evenly gap-2 p-1 px-3">
44- <button
45- className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
46- onClick={() => handleAcceptOrReject("rejectDiff")}
47- data-testid="edit-reject-button"
48- >
49- <div className="flex flex-row items-center gap-1">
50- <XMarkIcon className="h-4 w-4 text-red-600" />
51- <span>Reject</span>
52- <span className="xs:inline-block hidden">All</span>
53- </div>
54-
55- <span
56- className="xs:inline-block hidden text-gray-400"
57- style={{
58- fontSize: tinyFont,
59- }}
60- >
61- ({getMetaKeyLabel()}⇧⌫)
62- </span>
63- </button>
64- <button
65- className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
66- onClick={() => handleAcceptOrReject("acceptDiff")}
67- data-testid="edit-accept-button"
68- >
69- <div className="flex flex-row items-center gap-1">
70- <CheckIcon className="h-4 w-4 text-green-600" />
71- <span>Accept</span>
72- <span className="xs:inline-block hidden">All</span>
73- </div>
74- <span
75- className="xs:inline-block hidden text-gray-400"
76- style={{
77- fontSize: tinyFont,
78- }}
79- >
80- ({getMetaKeyLabel()}⇧⏎)
81- </span>
82- </button>
83- </div>
84- );
85-}
added gui/src/components/AcceptRejectDiffButtons.tsx +89 −0
@@ -0,0 +1,89 @@
1+import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
2+import { ApplyState } from "core";
3+import { useContext } from "react";
4+import { IdeMessengerContext } from "../context/IdeMessenger";
5+import { getMetaKeyLabel } from "../util";
6+import { useFontSize } from "./ui/font";
7+
8+export interface AcceptRejectAllButtonsProps {
9+ applyStates: ApplyState[];
10+ onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
11+}
12+
13+export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
14+
15+export default function AcceptRejectAllButtons({
16+ applyStates,
17+ onAcceptOrReject,
18+}: AcceptRejectAllButtonsProps) {
19+ const pendingApplyStates = applyStates.filter(
20+ (state) => state.status === "done",
21+ );
22+ const ideMessenger = useContext(IdeMessengerContext);
23+
24+ const tinyFont = useFontSize(-3);
25+
26+ async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
27+ for (const { filepath = "", streamId } of pendingApplyStates) {
28+ ideMessenger.post(status, {
29+ filepath,
30+ streamId,
31+ });
32+ }
33+
34+ if (onAcceptOrReject) {
35+ onAcceptOrReject(status);
36+ }
37+ }
38+
39+ if (!pendingApplyStates.length) {
40+ return null;
41+ }
42+
43+ return (
44+ <div
45+ className="flex flex-row items-center justify-evenly gap-2 p-1 px-3"
46+ data-testid="accept-reject-all-buttons"
47+ >
48+ <button
49+ className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
50+ onClick={() => handleAcceptOrReject("rejectDiff")}
51+ data-testid="edit-reject-button"
52+ >
53+ <div className="flex flex-row items-center gap-1">
54+ <XMarkIcon className="h-4 w-4 text-red-600" />
55+ <span>Reject</span>
56+ <span className="xs:inline-block hidden">All</span>
57+ </div>
58+
59+ <span
60+ className="xs:inline-block hidden text-gray-400"
61+ style={{
62+ fontSize: tinyFont,
63+ }}
64+ >
65+ ({getMetaKeyLabel()}⇧⌫)
66+ </span>
67+ </button>
68+ <button
69+ className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
70+ onClick={() => handleAcceptOrReject("acceptDiff")}
71+ data-testid="edit-accept-button"
72+ >
73+ <div className="flex flex-row items-center gap-1">
74+ <CheckIcon className="h-4 w-4 text-green-600" />
75+ <span>Accept</span>
76+ <span className="xs:inline-block hidden">All</span>
77+ </div>
78+ <span
79+ className="xs:inline-block hidden text-gray-400"
80+ style={{
81+ fontSize: tinyFont,
82+ }}
83+ >
84+ ({getMetaKeyLabel()}⇧⏎)
85+ </span>
86+ </button>
87+ </div>
88+ );
89+}
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +21 −58
@@ -1,6 +1,5 @@
11 import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
22 import { ApplyState } from "core";
3-import { useEffect, useState } from "react";
43 import { getMetaKeyLabel } from "../../../util";
54 import Spinner from "../../gui/Spinner";
65 import { ToolTip } from "../../gui/Tooltip";
@@ -16,56 +15,11 @@
1615 }
1716
1817 export function ApplyActions(props: ApplyActionsProps) {
19- const [hasRejected, setHasRejected] = useState(false);
20- const [showApplied, setShowApplied] = useState(false);
21- const isClosed = props.applyState?.status === "closed";
22- const isSuccessful = !hasRejected && props.applyState?.numDiffs === 0;
23-
24- useEffect(() => {
25- if (isClosed && isSuccessful) {
26- setShowApplied(true);
27- const timer = setTimeout(() => {
28- setShowApplied(false);
29- }, 3_000);
30- return () => clearTimeout(timer);
31- }
32- }, [isClosed, isSuccessful]);
33-
3418 function onClickReject() {
3519 props.onClickReject();
36- setHasRejected(true);
3720 }
3821
39- const applyButton = (text: string) => (
40- <HoverItem
41- data-tooltip-id="codeblock-apply-code-button-tooltip"
42- className="!p-0"
43- >
44- <button
45- data-testid="codeblock-toolbar-apply"
46- className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
47- onClick={props.onClickApply}
48- >
49- <div className="text-lightgray flex items-center gap-1">
50- <PlayIcon className="h-3.5 w-3.5" />
51- <span className="xs:inline hidden">{text}</span>
52- </div>
53- </button>
54- <ToolTip id="codeblock-apply-code-button-tooltip" place="top">
55- {text} Code
56- </ToolTip>
57- </HoverItem>
58- );
59-
6022 switch (props.applyState ? props.applyState.status : null) {
61- case "not-started":
62- return (
63- <div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
64- <span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
65- Pending
66- </span>
67- </div>
68- );
6923 case "streaming":
7024 return (
7125 <div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
@@ -102,21 +56,30 @@
10256 </div>
10357 );
10458 case "closed":
105- if (isSuccessful) {
106- if (showApplied || props.disableManualApply) {
107- return (
108- <span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
109- <span className="max-sm:hidden">Applied</span>
110- <CheckIcon className="h-3.5 w-3.5 hover:brightness-125 sm:px-1" />
111- </span>
112- );
113- }
114- return applyButton("Reapply");
115- }
11659 default:
11760 if (props.disableManualApply) {
11861 return null;
11962 }
120- return applyButton("Apply");
63+
64+ return (
65+ <HoverItem
66+ data-tooltip-id="codeblock-apply-code-button-tooltip"
67+ className="!p-0"
68+ >
69+ <button
70+ data-testid="codeblock-toolbar-apply"
71+ className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
72+ onClick={props.onClickApply}
73+ >
74+ <div className="text-lightgray flex items-center gap-1">
75+ <PlayIcon className="h-3.5 w-3.5" />
76+ <span className="xs:inline hidden">Apply</span>
77+ </div>
78+ </button>
79+ <ToolTip id="codeblock-apply-code-button-tooltip" place="top">
80+ Apply Code
81+ </ToolTip>
82+ </HoverItem>
83+ );
12184 }
12285 }
deleted gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx +0 −26
@@ -1,26 +0,0 @@
1-import Spinner from "../../gui/Spinner";
2-
3-export interface GeneratingCodeLoaderProps {
4- showLineCount: boolean;
5- codeBlockContent: string;
6- isPending: boolean;
7-}
8-
9-export function GeneratingCodeLoader({
10- showLineCount,
11- codeBlockContent,
12- isPending,
13-}: GeneratingCodeLoaderProps) {
14- const numLinesCodeBlock = codeBlockContent.split("\n").length;
15- const linesGeneratedText =
16- numLinesCodeBlock === 1
17- ? `1 line generated`
18- : `${numLinesCodeBlock} lines ${isPending ? "pending" : "generated"}`;
19-
20- return (
21- <span className="text-lightgray inline-flex items-center gap-2">
22- {showLineCount ? linesGeneratedText : "Generating"}
23- {!isPending && <Spinner />}
24- </span>
25- );
26-}
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +1 −12
@@ -3,6 +3,7 @@
33 import { lightGray, vscForeground } from "../..";
44 import { IdeMessengerContext } from "../../../context/IdeMessenger";
55 import { isJetBrains } from "../../../util";
6+import { extractCommand } from "../utils/commandExtractor";
67
78 interface RunInTerminalButtonProps {
89 command: string;
@@ -16,18 +17,6 @@
1617 return null;
1718 }
1819
19- // Extract just the command line (the line after $ or the first line)
20- function extractCommand(cmd: string): string {
21- // If the command contains a $ prompt, extract the line after it
22- if (cmd.includes("$")) {
23- const match = cmd.match(/\$\s*([^\n]+)/);
24- return match ? match[1].trim() : "";
25- }
26-
27- // Otherwise, just take the first line
28- return cmd.split("\n")[0].trim();
29- }
30-
3120 function runInTerminal() {
3221 // Extract just the command line
3322 const extractedCommand = extractCommand(command);
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +43 −15
@@ -11,14 +11,15 @@
1111 import { useIdeMessengerRequest } from "../../../hooks";
1212 import { useWebviewListener } from "../../../hooks/useWebviewListener";
1313 import { useAppSelector } from "../../../redux/hooks";
14+import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall";
1415 import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
1516 import { getFontSize } from "../../../util";
17+import Spinner from "../../gui/Spinner";
1618 import { isTerminalCodeBlock } from "../utils";
1719 import { ApplyActions } from "./ApplyActions";
1820 import { CopyButton } from "./CopyButton";
1921 import { CreateFileButton } from "./CreateFileButton";
2022 import { FileInfo } from "./FileInfo";
21-import { GeneratingCodeLoader } from "./GeneratingCodeLoader";
2223 import { InsertButton } from "./InsertButton";
2324 import { RunInTerminalButton } from "./RunInTerminalButton";
2425
@@ -49,8 +50,9 @@
4950 codeBlockContent: string;
5051 language: string | null;
5152 relativeFilepath?: string;
52- isFinalCodeblock: boolean;
53+ itemIndex?: number;
5354 codeBlockIndex: number; // To track which codeblock we are applying
55+ isLastCodeblock: boolean;
5456 codeBlockStreamId: string;
5557 range?: string;
5658 children: any;
@@ -62,8 +64,9 @@
6264 codeBlockContent,
6365 language,
6466 relativeFilepath,
65- isFinalCodeblock,
67+ itemIndex,
6668 codeBlockIndex,
69+ isLastCodeblock,
6770 codeBlockStreamId,
6871 range,
6972 children,
@@ -71,6 +74,7 @@
7174 disableManualApply,
7275 }: StepContainerPreToolbarProps) {
7376 const ideMessenger = useContext(IdeMessengerContext);
77+ const history = useAppSelector((state) => state.session.history);
7478 const [isExpanded, setIsExpanded] = useState(expanded ?? true);
7579
7680 const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>(
@@ -95,6 +99,9 @@
9599 const applyState = useAppSelector((state) =>
96100 selectApplyStateByStreamId(state, codeBlockStreamId),
97101 );
102+ const currentToolCallApplyState = useAppSelector(
103+ selectCurrentToolCallApplyState,
104+ );
98105
99106 /**
100107 * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`.
@@ -110,7 +117,12 @@
110117 relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath);
111118
112119 const isStreaming = useAppSelector((store) => store.session.isStreaming);
113- const isGeneratingCodeBlock = isFinalCodeblock && isStreaming;
120+
121+ const isLastItem = useMemo(() => {
122+ return itemIndex === history.length - 1;
123+ }, [history.length, itemIndex]);
124+
125+ const isGeneratingCodeBlock = isLastItem && isLastCodeblock && isStreaming;
114126
115127 // If we are creating a file, we already render that in the button
116128 // so we don't want to dispaly it twice here
@@ -221,6 +233,32 @@
221233 }
222234
223235 const renderActionButtons = () => {
236+ const isPendingToolCall =
237+ currentToolCallApplyState &&
238+ currentToolCallApplyState.streamId === applyState?.streamId &&
239+ currentToolCallApplyState.status === "not-started";
240+
241+ if (isGeneratingCodeBlock || isPendingToolCall) {
242+ const numLines = codeBlockContent.split("\n").length;
243+ const plural = numLines === 1 ? "" : "s";
244+ if (isGeneratingCodeBlock) {
245+ return (
246+ <span className="text-lightgray inline-flex items-center gap-2 text-right">
247+ {!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
248+ <div>
249+ <Spinner />
250+ </div>
251+ </span>
252+ );
253+ } else {
254+ return (
255+ <span className="text-lightgray inline-flex items-center gap-2 text-right">
256+ {`${numLines} line${plural} pending`}
257+ </span>
258+ );
259+ }
260+ }
261+
224262 if (isTerminalCodeBlock(language, codeBlockContent)) {
225263 return <RunInTerminalButton command={codeBlockContent} />;
226264 }
@@ -281,17 +319,7 @@
281319 </div>
282320 )}
283321
284- {isGeneratingCodeBlock || applyState?.status === "not-started" ? (
285- <GeneratingCodeLoader
286- showLineCount={!isExpanded}
287- codeBlockContent={codeBlockContent}
288- isPending={
289- applyState?.status === "not-started" && !isGeneratingCodeBlock
290- }
291- />
292- ) : (
293- renderActionButtons()
294- )}
322+ {renderActionButtons()}
295323 </div>
296324 </ToolbarDiv>
297325
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
@@ -44,14 +44,7 @@
4444 data-tooltip-id={id}
4545 data-tooltip-delay-show={500}
4646 >
47- <code
48- className="align-middle"
49- style={{
50- color: "var(--vscode-textLink-foreground)",
51- }}
52- >
53- {content}
54- </code>
47+ <code className="text-link align-middle">{content}</code>
5548 </span>
5649 <ToolTip id={id} place="top" className="m-0 p-0">
5750 <pre className="text-left">{processedContent ?? symbol.filepath}</pre>
modified gui/src/components/StyledMarkdownPreview/index.tsx +4 −8
@@ -193,11 +193,7 @@
193193 };
194194 }, [props.itemIndex, history, allSymbols]);
195195 const pastFileInfoRef = useUpdatingRef(pastFileInfo);
196-
197- const isLastItem = useMemo(() => {
198- return props.itemIndex === history.length - 1;
199- }, [history.length, props.itemIndex]);
200- const isLastItemRef = useUpdatingRef(isLastItem);
196+ const itemIndexRef = useUpdatingRef(props.itemIndex);
201197
202198 const codeblockStreamIds = useRef<string[]>([]);
203199 useEffect(() => {
@@ -296,8 +292,7 @@
296292
297293 const language = getLanguageFromClassName(className);
298294
299- const isFinalCodeblock =
300- preChildProps["data-islastcodeblock"] && isLastItemRef.current;
295+ const isLastCodeblock = preChildProps["data-islastcodeblock"];
301296
302297 if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
303298 codeblockStreamIds.current[codeBlockIndex] =
@@ -307,10 +302,11 @@
307302 return (
308303 <StepContainerPreToolbar
309304 codeBlockContent={codeBlockContent}
305+ itemIndex={itemIndexRef.current}
310306 codeBlockIndex={codeBlockIndex}
311307 language={language}
312308 relativeFilepath={relativeFilePath}
313- isFinalCodeblock={isFinalCodeblock}
309+ isLastCodeblock={isLastCodeblock}
314310 range={range}
315311 codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
316312 expanded={props.expandCodeblocks}
modified gui/src/components/StyledMarkdownPreview/rehypeHighlightPlugin.ts +2 −0
@@ -1,6 +1,7 @@
11 // Feel free to add more!
22 // See gui/node_modules/highlight.js/lib/languages for the full available list
33 import clojure from "highlight.js/lib/languages/clojure";
4+import delphi from "highlight.js/lib/languages/delphi";
45 import elixir from "highlight.js/lib/languages/elixir";
56 import julia from "highlight.js/lib/languages/julia";
67 import lisp from "highlight.js/lib/languages/lisp";
@@ -19,6 +20,7 @@
1920 languages: {
2021 ...common,
2122 clojure,
23+ delphi,
2224 elixir,
2325 julia,
2426 protobuf,
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts +80 −0
@@ -0,0 +1,80 @@
1+import { extractCommand } from './commandExtractor';
2+
3+describe('extractCommand', () => {
4+ // Test basic command extraction
5+ it('should extract command from $ prompt', () => {
6+ expect(extractCommand('$ echo hello')).toBe('echo hello');
7+ expect(extractCommand('$ echo hello')).toBe('echo hello');
8+ expect(extractCommand('$echo hello')).toBe('echo hello');
9+ });
10+
11+ // Test comment removal
12+ it('should remove comments at beginning of lines', () => {
13+ expect(extractCommand('# shell comment\necho hello')).toBe('echo hello');
14+ expect(extractCommand('// js comment\necho hello')).toBe('echo hello');
15+ expect(extractCommand('/* multi-line\ncomment */\necho hello')).toBe('echo hello');
16+ });
17+
18+ // Test multiline comment removal
19+ it('should remove multiline comments anywhere in the text', () => {
20+ expect(extractCommand('echo /* comment */ hello')).toBe('echo hello');
21+ expect(extractCommand('echo hello /* comment */')).toBe('echo hello');
22+ expect(extractCommand('echo /* multiple\nline\ncomment */ hello')).toBe('echo hello');
23+ });
24+
25+ // Test line continuation handling
26+ it('should handle line continuations correctly', () => {
27+ expect(extractCommand('echo hello && \\\necho world')).toBe('echo hello && echo world');
28+ expect(extractCommand('echo hello | \\\ngrep h')).toBe('echo hello | grep h');
29+ expect(extractCommand('echo hello \\\nworld')).toBe('echo hello world');
30+ });
31+
32+ // Test complex command combinations
33+ it('should handle complex command combinations', () => {
34+ expect(extractCommand(`
35+ # shell comment
36+ echo hello /* inline comment */ && \\
37+ // js comment
38+ echo world
39+ `)).toBe('echo hello && echo world');
40+ });
41+
42+ // Test empty and whitespace handling
43+ it('should handle empty and whitespace inputs', () => {
44+ expect(extractCommand('')).toBe('');
45+ expect(extractCommand(' \n \t ')).toBe('');
46+ });
47+
48+ // Test comment-only inputs
49+ it('should handle comment-only inputs', () => {
50+ expect(extractCommand('/* comment */')).toBe('');
51+ expect(extractCommand('# comment')).toBe('');
52+ expect(extractCommand('// comment')).toBe('');
53+ expect(extractCommand('/* multi\nline\ncomment */')).toBe('');
54+ });
55+
56+ // Test inline comments
57+ it('should handle inline comments correctly according to implementation', () => {
58+ // But removes multiline comments even when inline
59+ expect(extractCommand('/* inline */ echo hello world')).toBe('echo hello world');
60+ });
61+
62+ // Test multiple line continuations
63+ it('should handle multiple line continuations', () => {
64+ expect(extractCommand(`
65+ echo hello && \\
66+ echo world && \\
67+ echo test
68+ `)).toBe('echo hello && echo world && echo test');
69+ });
70+
71+ // Test nested line continuations
72+ it('should handle nested line continuations', () => {
73+ expect(extractCommand(`
74+ echo hello && \\
75+ (echo nested && \\
76+ echo more) && \\
77+ echo final
78+ `)).toBe('echo hello && (echo nested && echo more) && echo final');
79+ });
80+});
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts +50 −0
@@ -0,0 +1,50 @@
1+/**
2+ * Extracts and processes command strings, handling comments and line continuations.
3+ * @param cmd The command string to process
4+ * @returns The processed command string
5+ */
6+export function extractCommand(cmd: string): string {
7+ if (!cmd || cmd.trim() === '') {
8+ return '';
9+ }
10+
11+ // Remove multi-line comments (/* ... */) and replace with a single space
12+ cmd = cmd.replace(/\/\*[\s\S]*?\*\//g, " ");
13+
14+ // Handle the $ prompt case first
15+ if (cmd.includes("$")) {
16+ const match = cmd.match(/\$\s*([^\n]+)/);
17+ if (match) {
18+ // Return just the command after $ without further processing
19+ return match[1].trim();
20+ }
21+ }
22+
23+ // Process lines - remove single-line comments only at beginning of lines
24+ const lines = cmd.split('\n')
25+ .map(line => line.replace(/^\s*#.*$/, '').replace(/^\s*\/\/.*$/, ''))
26+ .map(line => line.trim())
27+ .filter(line => line);
28+
29+ // Join lines with proper handling of continuations
30+ let result = '';
31+ for (let i = 0; i < lines.length; i++) {
32+ let line = lines[i];
33+
34+ // Remove trailing continuation characters and join with next line
35+ while (
36+ (line.endsWith('&&') || line.endsWith('|') || line.endsWith('\\')) &&
37+ i < lines.length - 1
38+ ) {
39+ // Remove the continuation character(s) and any trailing spaces
40+ line = line.replace(/(&&|\||\\)\s*$/, '').trim();
41+ // Join with the next line
42+ i++;
43+ line += ' ' + lines[i];
44+ }
45+
46+ result += line + ' ';
47+ }
48+
49+ return result.trim().replace(/\s+/g, ' ');
50+}
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +65 −0
@@ -0,0 +1,65 @@
1+import { headerIsMarkdown } from './headerIsMarkdown';
2+
3+describe('headerIsMarkdown', () => {
4+ // Test exact match with common Markdown identifiers
5+ it('should identify exact matches with common Markdown identifiers', () => {
6+ expect(headerIsMarkdown('md')).toBe(true);
7+ expect(headerIsMarkdown('markdown')).toBe(true);
8+ expect(headerIsMarkdown('gfm')).toBe(true);
9+ expect(headerIsMarkdown('github-markdown')).toBe(true);
10+ });
11+
12+ // Test identifiers preceded by a space
13+ it('should identify identifiers preceded by a space', () => {
14+ expect(headerIsMarkdown('lang md')).toBe(true);
15+ expect(headerIsMarkdown('something markdown')).toBe(true);
16+ expect(headerIsMarkdown('language gfm')).toBe(true);
17+ expect(headerIsMarkdown('spec github-markdown')).toBe(true);
18+ });
19+
20+ // Test file extensions
21+ it('should identify file names with markdown extensions', () => {
22+ expect(headerIsMarkdown('example.md')).toBe(true);
23+ expect(headerIsMarkdown('document.markdown')).toBe(true);
24+ expect(headerIsMarkdown('readme.gfm')).toBe(true);
25+ });
26+
27+ // Test more complex cases with extensions
28+ it('should identify file names with markdown extensions followed by other text', () => {
29+ expect(headerIsMarkdown('example.md additional text')).toBe(true);
30+ expect(headerIsMarkdown('document.markdown with some description')).toBe(true);
31+ expect(headerIsMarkdown('readme.gfm v2.0')).toBe(true);
32+ });
33+
34+ // Test non-markdown cases
35+ it('should not identify non-markdown headers', () => {
36+ expect(headerIsMarkdown('javascript')).toBe(false);
37+ expect(headerIsMarkdown('typescript')).toBe(false);
38+ expect(headerIsMarkdown('plain')).toBe(false);
39+ expect(headerIsMarkdown('python')).toBe(false);
40+ });
41+
42+ // Test edge cases
43+ it('should handle edge cases correctly', () => {
44+ expect(headerIsMarkdown('')).toBe(false);
45+ expect(headerIsMarkdown('mdx')).toBe(false); // Similar but not exactly "md"
46+ expect(headerIsMarkdown('readme md')).toBe(true);
47+ expect(headerIsMarkdown('md.js')).toBe(false); // "md" is not the extension
48+ });
49+
50+ // Test case sensitivity
51+ it('should respect case sensitivity', () => {
52+ expect(headerIsMarkdown('MD')).toBe(false);
53+ expect(headerIsMarkdown('MARKDOWN')).toBe(false);
54+ expect(headerIsMarkdown('example.MD')).toBe(false);
55+ expect(headerIsMarkdown('lang MD')).toBe(false);
56+ });
57+
58+ // Test with special characters and spacing
59+ it('should handle special characters and spacing correctly', () => {
60+ expect(headerIsMarkdown(' md')).toBe(true); // Space before "md"
61+ expect(headerIsMarkdown('md ')).toBe(true); // Space after "md"
62+ expect(headerIsMarkdown('hello-md')).toBe(false); // "md" with hyphen prefix
63+ expect(headerIsMarkdown('markdown:')).toBe(false); // "markdown" with suffix
64+ });
65+});
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +26 −0
@@ -0,0 +1,26 @@
1+/**
2+ * Determines if a given header string represents Markdown content.
3+ *
4+ * The function checks various patterns to identify Markdown headers:
5+ * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
6+ * - Contains these identifiers preceded by a space
7+ * - First word has a file extension of md, markdown, or gfm
8+ *
9+ * @param header - The string to check for Markdown indicators
10+ * @returns True if the header represents Markdown content, false otherwise
11+ */
12+export function headerIsMarkdown(header: string): boolean {
13+ return (
14+ header === "md" ||
15+ header === "markdown" ||
16+ header === "gfm" ||
17+ header === "github-markdown" ||
18+ header.includes(" md") ||
19+ header.includes(" markdown") ||
20+ header.includes(" gfm") ||
21+ header.includes(" github-markdown") ||
22+ (header.split(" ")[0]?.split(".").pop() === "md") ||
23+ (header.split(" ")[0]?.split(".").pop() === "markdown") ||
24+ (header.split(" ")[0]?.split(".").pop() === "gfm")
25+ );
26+}
No newline at the end of the file
added gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +105 −0
@@ -0,0 +1,105 @@
1+import { patchNestedMarkdown } from './patchNestedMarkdown';
2+
3+describe('patchNestedMarkdown', () => {
4+ it('should return unchanged content when no markdown codeblocks are present', () => {
5+ const source = 'Regular text\n```javascript\nconsole.log("hello");\n```';
6+ expect(patchNestedMarkdown(source)).toBe(source);
7+ });
8+
9+ it('should replace backticks with tildes for markdown codeblocks', () => {
10+ const source = '```markdown\n# Header\nSome text\n```';
11+ const expected = '~~~markdown\n# Header\nSome text\n~~~';
12+ expect(patchNestedMarkdown(source)).toBe(expected);
13+ });
14+
15+ it('should handle nested codeblocks within markdown blocks', () => {
16+ const source = '```markdown\n# Example\n```js\nconsole.log("nested");\n```\n```';
17+ const expected = '~~~markdown\n# Example\n```js\nconsole.log("nested");\n```\n~~~';
18+ expect(patchNestedMarkdown(source)).toBe(expected);
19+ });
20+
21+ it('should handle .md file extension', () => {
22+ const source = '```test.md\nContent\n```';
23+ const expected = '~~~test.md\nContent\n~~~';
24+ expect(patchNestedMarkdown(source)).toBe(expected);
25+ });
26+
27+ it('should handle multiple levels of nesting', () => {
28+ const source = '```markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n```';
29+ const expected = '~~~markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n~~~';
30+ expect(patchNestedMarkdown(source)).toBe(expected);
31+ });
32+
33+ it('should handle blocks that start with md', () => {
34+ const source = '```md\n# Header\nSome text\n```';
35+ const expected = '~~~md\n# Header\nSome text\n~~~';
36+ expect(patchNestedMarkdown(source)).toBe(expected);
37+ });
38+
39+ it('should handle blocks with language specifier followed by md', () => {
40+ const source = '```lang md\n# Header\nSome text\n```';
41+ const expected = '~~~lang md\n# Header\nSome text\n~~~';
42+ expect(patchNestedMarkdown(source)).toBe(expected);
43+ });
44+
45+ it('should handle blocks with language specifier followed by markdown', () => {
46+ const source = '```lang markdown\n# Header\nSome text\n```';
47+ const expected = '~~~lang markdown\n# Header\nSome text\n~~~';
48+ expect(patchNestedMarkdown(source)).toBe(expected);
49+ });
50+
51+ it('should not replace backticks for non-markdown file extensions', () => {
52+ const source = '```test.js\nContent\n```';
53+ expect(patchNestedMarkdown(source)).toBe(source);
54+ });
55+
56+ it('should check the file extension branch when extension is not md/markdown/gfm', () => {
57+ // This tests the extension check branch with an unrecognized extension
58+ const source = '```test.txt\nContent with md keyword\n```';
59+ expect(patchNestedMarkdown(source)).toBe(source);
60+ });
61+
62+ it('should handle empty file name in code block header', () => {
63+ // This covers the branch where file is empty or undefined
64+ const source = '``` \nSome content\n```';
65+ expect(patchNestedMarkdown(source)).toBe(source);
66+ });
67+
68+ it('should handle file names with no extension', () => {
69+ // This covers the branch where ext might be undefined
70+ const source = '```filename\nContent\n```';
71+ expect(patchNestedMarkdown(source)).toBe(source);
72+ });
73+
74+ it('should correctly identify .markdown extension', () => {
75+ // This specifically tests the ext === "markdown" condition in the extension check
76+ const source = '```example.markdown\n# Some markdown content\n```';
77+ const expected = '~~~example.markdown\n# Some markdown content\n~~~';
78+ expect(patchNestedMarkdown(source)).toBe(expected);
79+ });
80+
81+ // GitHub-specific tests
82+ it('should handle gfm language identifier', () => {
83+ const source = '```gfm\n# Header\nSome text\n```';
84+ const expected = '~~~gfm\n# Header\nSome text\n~~~';
85+ expect(patchNestedMarkdown(source)).toBe(expected);
86+ });
87+
88+ it('should handle github-markdown language identifier', () => {
89+ const source = '```github-markdown\n# Header\nSome text\n```';
90+ const expected = '~~~github-markdown\n# Header\nSome text\n~~~';
91+ expect(patchNestedMarkdown(source)).toBe(expected);
92+ });
93+
94+ it('should handle language specifier followed by gfm', () => {
95+ const source = '```lang gfm\n# Header\nSome text\n```';
96+ const expected = '~~~lang gfm\n# Header\nSome text\n~~~';
97+ expect(patchNestedMarkdown(source)).toBe(expected);
98+ });
99+
100+ it('should handle .gfm file extension', () => {
101+ const source = '```example.gfm\n# Some GitHub markdown content\n```';
102+ const expected = '~~~example.gfm\n# Some GitHub markdown content\n~~~';
103+ expect(patchNestedMarkdown(source)).toBe(expected);
104+ });
105+});
modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +25 −20
@@ -1,47 +1,52 @@
11 /*
22 This is a patch for outputing markdown code that contains codeblocks
33
4- It notices markdown blocks, keeps track of when that specific block is closed,
4+ It notices markdown blocks (including GitHub-specific variants),
5+ keeps track of when that specific block is closed,
56 and uses ~~~ instead of ``` for that block
67
78 Note, this was benchmarked at sub-millisecond
8-
9- // TODO support github-specific markdown as well, edge case
109 */
10+import { headerIsMarkdown } from './headerIsMarkdown';
11+
1112 export const patchNestedMarkdown = (source: string): string => {
12- if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
13- // const start = Date.now();
13+ // Early return if no markdown codeblock pattern is found (including GitHub variants)
14+ if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) return source;
15+
1416 let nestCount = 0;
1517 const lines = source.split("\n");
1618 const trimmedLines = lines.map((l) => l.trim());
19+
1720 for (let i = 0; i < trimmedLines.length; i++) {
1821 const line = trimmedLines[i];
19- if (nestCount) {
22+
23+ if (nestCount > 0) {
24+ // Inside a markdown block
2025 if (line.match(/^`+$/)) {
21- // Ending a block
22- if (nestCount === 1) lines[i] = "~~~"; // End of markdown block
26+ // Ending a block with just backticks (```)
2327 nestCount--;
28+ if (nestCount === 0) {
29+ lines[i] = "~~~"; // End of markdown block
30+ }
2431 } else if (line.startsWith("```")) {
2532 // Going into a nested codeblock
2633 nestCount++;
2734 }
2835 } else {
29- // Enter the markdown block, start tracking nesting
36+ // Not inside a markdown block yet
3037 if (line.startsWith("```")) {
3138 const header = line.replaceAll("`", "");
32- const file = header.split(" ")[0];
33-
34- if (file) {
35- const ext = file.split(".").at(-1);
36- if (ext === "md" || ext === "markdown") {
37- nestCount = 1;
38- lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
39- }
39+
40+ // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants)
41+ const isMarkdown = headerIsMarkdown(header);
42+
43+ if (isMarkdown) {
44+ nestCount = 1;
45+ lines[i] = lines[i].replaceAll("`", "~");
4046 }
4147 }
4248 }
4349 }
44- const out = lines.join("\n");
45- // console.log(`patched in ${Date.now() - start}ms`);
46- return out;
50+
51+ return lines.join("\n");
4752 };
modified gui/src/components/TabBar/TabBar.tsx +35 −50
@@ -1,5 +1,5 @@
11 import { XMarkIcon } from "@heroicons/react/24/outline";
2-import { useCallback, useEffect } from "react";
2+import React, { useCallback, useEffect } from "react";
33 import { useDispatch, useSelector } from "react-redux";
44 import styled from "styled-components";
55 import { defaultBorderRadius } from "..";
@@ -13,16 +13,30 @@
1313 } from "../../redux/slices/tabsSlice";
1414 import { AppDispatch, RootState } from "../../redux/store";
1515 import { loadSession, saveCurrentSession } from "../../redux/thunks/session";
16+import { varWithFallback } from "../../styles/theme";
17+
18+// Haven't set up theme colors for tabs yet
19+// Will keep it simple and choose from existing ones. Comments show vars we could use
20+const tabBorderVar = varWithFallback("border"); // --vscode-tab-border
21+const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground
22+const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground
23+const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground
24+const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground
25+const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground
26+const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground
27+const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop
1628
1729 const TabBarContainer = styled.div`
1830 display: flex;
1931 flex-wrap: wrap;
2032 flex-shrink: 0;
2133 flex-grow: 0;
22- background-color: var(--vscode-tab-inactiveBackground);
34+ background-color: ${tabBackgroundVar};
2335 border-bottom: none;
2436 position: relative;
2537 margin-top: 2px;
38+ max-height: 100px;
39+ overflow: auto;
2640
2741 /* Hide scrollbar but keep functionality */
2842 scrollbar-width: none;
@@ -41,24 +55,18 @@
4155 max-width: 150px;
4256 height: 25px;
4357 background-color: ${(props) =>
44- props.isActive
45- ? "var(--vscode-tab-activeBackground)"
46- : "var(--vscode-tab-inactiveBackground)"};
58+ props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
4759 color: ${(props) =>
48- props.isActive
49- ? "var(--vscode-tab-activeForeground)"
50- : "var(--vscode-tab-inactiveForeground)"};
60+ props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
5161 cursor: pointer;
52- border: 1px solid var(--vscode-tab-border);
62+ border: 1px solid ${tabBorderVar};
5363 border-bottom: ${(props) =>
54- props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
64+ props.isActive ? "none" : `1px solid ${tabBorderVar}`};
5565 user-select: none;
5666 position: relative;
5767 transition: background-color 0.2s;
5868 border-top: ${(props) =>
59- props.isActive
60- ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
61- : `1px solid var(--vscode-tab-border)`};
69+ props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
6270 &:first-child {
6371 border-left: none;
6472 }
@@ -68,13 +76,9 @@
6876
6977 &:hover {
7078 background-color: ${(props) =>
71- props.isActive
72- ? "var(--vscode-tab-activeBackground)"
73- : "var(--vscode-tab-hoverBackground)"};
79+ props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
7480 color: ${(props) =>
75- props.isActive
76- ? "var(--vscode-tab-activeForeground)"
77- : "var(--vscode-tab-hoverForeground)"};
81+ props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
7882 }
7983 `;
8084
@@ -104,7 +108,7 @@
104108
105109 &:hover {
106110 opacity: 1;
107- background-color: var(--vscode-tab-hoverBackground);
111+ background-color: ${tabHoverBackgroundVar};
108112 }
109113
110114 ${Tab}:hover & {
@@ -119,33 +123,12 @@
119123 const TabBarSpace = styled.div`
120124 flex: 1;
121125 display: flex;
122- border-bottom: 1px solid var(--vscode-tab-border);
123- background-color: var(--vscode-tab-inactiveBackground);
126+ border-bottom: 1px solid ${tabBorderVar};
127+ background-color: ${tabBackgroundVar};
124128 `;
125129
126-const NewTabButton = styled.button`
127- display: flex;
128- align-items: center;
129- justify-content: center;
130- width: 35px;
131- height: 100%;
132- border: none;
133- background: transparent;
134- color: var(--vscode-tab-inactiveForeground);
135- cursor: pointer;
136- opacity: 0.7;
137- transition: opacity 0.2s;
138-
139- &:hover {
140- opacity: 1;
141- background-color: var(--vscode-tab-hoverBackground);
142- color: var(--vscode-tab-hoverForeground);
143- }
144-`;
145-
146-export function TabBar() {
130+export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
147131 const dispatch = useDispatch<AppDispatch>();
148- const currentSession = useSelector((state: RootState) => state.session);
149132 const currentSessionId = useSelector((state: RootState) => state.session.id);
150133 const currentSessionTitle = useSelector(
151134 (state: RootState) => state.session.title,
@@ -160,7 +143,6 @@
160143 return Date.now().toString(36) + Math.random().toString(36).substring(2);
161144 }, []);
162145
163- // Handle session changes
164146 useEffect(() => {
165147 if (!currentSessionId) return;
166148
@@ -243,10 +225,13 @@
243225 }
244226 };
245227
246- return tabs.length === 1 ? (
247- <></>
248- ) : (
249- <TabBarContainer>
228+ return (
229+ <TabBarContainer
230+ ref={ref}
231+ style={{
232+ display: tabs.length === 1 ? "none" : "flex",
233+ }}
234+ >
250235 {tabs.map((tab) => (
251236 <Tab
252237 key={tab.id}
@@ -272,4 +257,4 @@
272257 </TabBarSpace>
273258 </TabBarContainer>
274259 );
275-}
260+});
modified gui/src/components/ToggleDiv.tsx +10 −7
@@ -6,15 +6,21 @@
66 children: React.ReactNode;
77 title: React.ReactNode;
88 icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
9+ testId?: string;
910 }
1011
11-function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
12+function ToggleDiv({
13+ children,
14+ title,
15+ icon: Icon,
16+ testId = "context-items-peek",
17+}: ToggleProps) {
1218 const [open, setOpen] = useState(false);
1319 const [isHovered, setIsHovered] = useState(false);
1420
1521 return (
1622 <div
17- className={`pl-2 pt-2`}
23+ className={`pl-2`}
1824 style={{
1925 backgroundColor: vscBackground,
2026 }}
@@ -24,7 +30,7 @@
2430 onClick={() => setOpen((prev) => !prev)}
2531 onMouseEnter={() => setIsHovered(true)}
2632 onMouseLeave={() => setIsHovered(false)}
27- data-testid="context-items-peek"
33+ data-testid={testId}
2834 >
2935 <div className="relative mr-1 h-4 w-4">
3036 {Icon && !isHovered && !open ? (
@@ -44,10 +50,7 @@
4450 </>
4551 )}
4652 </div>
47- <span
48- className="ml-1 text-xs text-gray-400 transition-colors duration-200"
49- data-testid="toggle-div-title"
50- >
53+ <span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
5154 {title}
5255 </span>
5356 </div>
modified gui/src/components/console/Details.tsx +27 −9
@@ -1,4 +1,4 @@
1-import { useEffect, useRef } from "react";
1+import { useEffect, useRef, useState } from "react";
22 import { LLMInteraction } from "../../hooks/useLLMLog";
33 import useLLMSummary from "../../hooks/useLLMSummary";
44 import End from "./End";
@@ -50,6 +50,18 @@
5050 const scrollTop = useRef<HTMLDivElement>(null);
5151 const lastResult = useRef<any>(null);
5252 const summary = useLLMSummary(interaction);
53+ const [isAtBottom, setIsAtBottom] = useState(true);
54+
55+ // Handler to check if user is at the bottom
56+ function handleScroll() {
57+ const elt = scrollTop.current;
58+ if (!elt) {
59+ return;
60+ }
61+ // Allow a small threshold for floating point errors
62+ const threshold = 5;
63+ setIsAtBottom((elt.scrollHeight - elt.scrollTop - elt.clientHeight) < threshold);
64+ }
5365
5466 useEffect(() => {
5567 if (interaction.end) {
@@ -59,15 +71,17 @@
5971 const last = interaction.results[interaction.results.length - 1];
6072 if (last != lastResult.current) {
6173 lastResult.current = last;
62- const lastChild = scrollTop.current?.lastChild;
63- if (lastChild) {
64- (lastChild as HTMLElement).scrollIntoView({
65- behavior: "auto",
66- block: "end",
67- });
74+ if (isAtBottom) {
75+ const lastChild = scrollTop.current?.lastChild;
76+ if (lastChild) {
77+ (lastChild as HTMLElement).scrollIntoView({
78+ behavior: "auto",
79+ block: "end",
80+ });
81+ }
6882 }
6983 }
70- });
84+ }, [interaction, isAtBottom]);
7185
7286 return (
7387 <div className="m-0 flex min-w-0 flex-1 shrink grow flex-col">
@@ -102,7 +116,11 @@
102116 ></Cell>
103117 </div>
104118 </div>
105- <div ref={scrollTop} className="grow overflow-auto">
119+ <div
120+ ref={scrollTop}
121+ className="grow overflow-auto"
122+ onScroll={handleScroll}
123+ >
106124 {interaction.start ? <Start item={interaction.start}></Start> : ""}
107125 <div className="whitespace-pre-wrap p-2">
108126 {interaction.results.map((group, i) => {
modified gui/src/components/dialogs/index.tsx +2 −3
@@ -4,12 +4,11 @@
44 import styled from "styled-components";
55 import {
66 CloseButton,
7- VSC_BACKGROUND_VAR,
87 defaultBorderRadius,
9- parseColorForHex,
108 vscBackground,
119 vscForeground,
1210 } from "..";
11+import { varWithFallback } from "../../styles/theme";
1312
1413 interface TextDialogProps {
1514 showDialog: boolean;
@@ -22,7 +21,7 @@
2221 position: fixed;
2322 width: 100%;
2423 height: 100%;
25- background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa;
24+ background-color: ${varWithFallback("background")}aa;
2625 z-index: 100000;
2726 flex-direction: column;
2827 `;
modified gui/src/components/find/FindWidget.tsx +126 −292
@@ -13,35 +13,24 @@
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
1515 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
16-import { useAppSelector } from "../../redux/hooks";
17-
18-interface SearchMatch {
19- index: number;
20- textNode: Text;
21- overlayRectangle: Rectangle;
22-}
23-
24-type ScrollToMatchOption = "closest" | "first" | "none";
25-
26-const SEARCH_DEBOUNCE = 300;
27-const RESIZE_DEBOUNCE = 200;
28-
29-interface Rectangle {
30- top: number;
31- left: number;
32- width: number;
33- height: number;
34-}
35-
36-interface HighlightOverlayProps extends Rectangle {
16+import {
17+ Rectangle,
18+ SearchMatch,
19+ searchWithinContainer,
20+} from "./findWidgetSearch";
21+import useDebounceValue from "./useDebounce";
22+import { useElementSize } from "./useElementSize";
23+
24+interface HighlightOverlayProps {
25+ rectangle: Rectangle;
3726 isCurrent: boolean;
3827 }
3928
4029 const HighlightOverlay = (props: HighlightOverlayProps) => {
41- const { isCurrent, top, left, width, height } = props;
30+ const { top, left, width, height } = props.rectangle;
4231 return (
4332 <div
44- className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
33+ className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
4534 key={`highlight-${top}-${left}`}
4635 style={{
4736 position: "absolute",
@@ -56,6 +45,8 @@
5645 );
5746 };
5847
48+type ScrollToMatchOption = "closest" | "first" | "none";
49+
5950 /*
6051 useFindWidget takes a container ref and returns
6152 1. A widget that can be placed anywhere to search the contents of that container
@@ -64,18 +55,22 @@
6455
6556 Container must have relative positioning
6657 */
67-export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
58+export const useFindWidget = (
59+ searchRef: RefObject<HTMLDivElement>,
60+ headerRef: RefObject<HTMLDivElement>,
61+ disabled: boolean,
62+) => {
6863 // Search input, debounced
69- const [input, setInput] = useState<string>("");
70- const debouncedInput = useRef<string>("");
7164 const inputRef = useRef<HTMLInputElement>(null);
65+ const [currentValue, setCurrentValue] = useState<string>("");
66+ const searchTerm = useDebounceValue(currentValue, 300);
7267
7368 // Widget open/closed state
7469 const [open, setOpen] = useState<boolean>(false);
7570 const openWidget = useCallback(() => {
7671 setOpen(true);
7772 inputRef?.current?.select();
78- }, [setOpen, inputRef]);
73+ }, [inputRef]);
7974
8075 // Search settings and results
8176 const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@@ -97,7 +92,7 @@
9792 behavior: "smooth",
9893 });
9994 },
100- [searchRef.current],
95+ [searchRef],
10196 );
10297
10398 const nextMatch = useCallback(() => {
@@ -143,327 +138,166 @@
143138 }, [inputRef, matches, nextMatch]);
144139
145140 // Handle container resize changes - highlight positions must adjust
146- const [isResizing, setIsResizing] = useState(false);
147- useEffect(() => {
148- let timeoutId: NodeJS.Timeout | null = null;
149- if (!searchRef?.current) return;
150-
151- const resizeObserver = new ResizeObserver((entries) => {
152- if (timeoutId) {
153- clearTimeout(timeoutId);
154- }
155- setIsResizing(true);
156- timeoutId = setTimeout(() => {
157- setIsResizing(false);
158- }, RESIZE_DEBOUNCE);
159- });
160-
161- resizeObserver.observe(searchRef.current);
162- return () => {
163- if (timeoutId) {
164- clearTimeout(timeoutId);
165- }
166- if (searchRef.current) resizeObserver.unobserve(searchRef.current);
167- };
168- }, [searchRef.current]);
141+ const { clientHeight: headerHeight, isResizing: headerResizing } =
142+ useElementSize(headerRef);
143+ const { isResizing: containerResizing } = useElementSize(searchRef);
144+ const isResizing = useMemo(() => {
145+ return containerResizing || headerResizing;
146+ }, [containerResizing, headerResizing]);
169147
170148 // Main function for finding matches and generating highlight overlays
171149 const refreshSearch = useCallback(
172- (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
173- if (clearFirst) setMatches([]);
174-
175- const searchContainer = searchRef.current;
176-
177- const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
178- if (!searchContainer || !_query) {
179- setMatches([]);
180- return;
181- }
182- const query = caseSensitive ? _query : _query.toLowerCase();
183-
184- // First grab all text nodes
185- // Skips any elements with the "find-widget-skip" class
186- const textNodes: Text[] = [];
187- const walker = document.createTreeWalker(
188- searchRef.current,
189- NodeFilter.SHOW_ALL,
150+ (scrollTo: ScrollToMatchOption = "none") => {
151+ const { results, closestToMiddle } = searchWithinContainer(
152+ searchRef,
153+ searchTerm,
190154 {
191- acceptNode: (node) => {
192- if (node.nodeType === Node.ELEMENT_NODE) {
193- if ((node as Element).classList.contains("find-widget-skip"))
194- return NodeFilter.FILTER_REJECT;
195- return NodeFilter.FILTER_ACCEPT;
196- } else if (node.nodeType === Node.TEXT_NODE) {
197- if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
198- const nodeValue = caseSensitive
199- ? node.nodeValue
200- : node.nodeValue.toLowerCase();
201- if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
202- }
203- return NodeFilter.FILTER_REJECT;
204- },
155+ caseSensitive,
156+ useRegex,
157+ offsetHeight: headerHeight,
205158 },
206159 );
207-
208- while (walker.nextNode()) {
209- if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
210- textNodes.push(walker.currentNode as Text);
211- }
212-
213- // Now walk through each node match and extract search results
214- // One node can have several matches
215- const newMatches: SearchMatch[] = [];
216- textNodes.forEach((textNode, idx) => {
217- // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
218- const highlightFullLine =
219- textNode.parentElement?.className.includes("hljs");
220-
221- let nodeTextValue = caseSensitive
222- ? textNode.nodeValue
223- : textNode.nodeValue.toLowerCase();
224- let startIndex = 0;
225- while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
226- // Create a range to measure the size and position of the match
227- const range = document.createRange();
228- range.setStart(textNode, startIndex);
229- const endIndex = startIndex + query.length;
230- range.setEnd(textNode, endIndex);
231- const rect = range.getBoundingClientRect();
232- range.detach();
233- startIndex = endIndex;
234-
235- const top =
236- rect.top + searchContainer.clientTop + searchContainer.scrollTop;
237- const left =
238- rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
239-
240- // Build a match result and push to matches
241- const newMatch: SearchMatch = {
242- index: 0, // will set later
243- textNode,
244- overlayRectangle: {
245- top,
246- left: highlightFullLine ? 2 : left,
247- width: highlightFullLine
248- ? searchContainer.clientWidth - 4
249- : rect.width, // equivalent of adding 2 px x padding
250- height: rect.height,
251- },
252- };
253- newMatches.push(newMatch);
254-
255- if (highlightFullLine) {
256- break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
257- }
258- }
259- });
260-
261- // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
262- // Filter them out by using the overlay rectangle as a hash key
263- const matchHash = Object.fromEntries(
264- newMatches.map((match) => [
265- JSON.stringify(match.overlayRectangle),
266- match,
267- ]),
268- );
269- const filteredMatches = Object.values(matchHash).map((match, index) => ({
270- ...match,
271- index,
272- }));
273-
160+ setMatches(results);
274161 // Find match closest to the middle of the view
275- const verticalMiddle =
276- searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
277- let closestDist = Infinity;
278- let closestMatchToMiddle: SearchMatch | null = null;
279- filteredMatches.forEach((match) => {
280- const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
281- if (dist < closestDist) {
282- closestDist = dist;
283- closestMatchToMiddle = match;
284- }
285- });
286-
287- // Update matches and scroll to the closest or first match
288- setMatches(filteredMatches);
289- if (query.length > 1 && filteredMatches.length) {
162+ if (searchTerm.length > 1 && results.length) {
290163 if (scrollTo === "first") {
291- scrollToMatch(filteredMatches[0]);
164+ scrollToMatch(results[0]);
292165 }
293166 if (scrollTo === "closest") {
294- if (closestMatchToMiddle) {
295- scrollToMatch(closestMatchToMiddle);
167+ if (closestToMiddle) {
168+ scrollToMatch(closestToMiddle);
296169 }
297170 }
298171 if (scrollTo === "none") {
299- if (closestMatchToMiddle) {
300- setCurrentMatch(closestMatchToMiddle);
172+ if (closestToMiddle) {
173+ setCurrentMatch(closestToMiddle);
301174 } else {
302- setCurrentMatch(filteredMatches[0]);
175+ setCurrentMatch(results[0]);
303176 }
304177 }
305178 }
306179 },
307- [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
180+ [
181+ searchTerm,
182+ caseSensitive,
183+ useRegex,
184+ searchRef,
185+ headerHeight,
186+ scrollToMatch,
187+ ],
308188 );
309189
310190 // Triggers that should cause immediate refresh of results to closest search value:
311- // Input change (debounced) and window click
312- const lastUpdateRef = useRef(0);
313191 useEffect(() => {
314- const debounce = () => {
315- debouncedInput.current = input;
316- lastUpdateRef.current = Date.now();
317- refreshSearch("closest");
318- };
319- const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
320- if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
321- debounce();
192+ if (disabled || isResizing || !open) {
193+ setMatches([]);
322194 } else {
323- const handler = setTimeout(() => {
324- debounce();
325- }, SEARCH_DEBOUNCE - timeSinceLastUpdate);
326- return () => {
327- clearTimeout(handler);
328- };
195+ refreshSearch("closest");
329196 }
330- }, [refreshSearch, input]);
197+ }, [refreshSearch, open, disabled, isResizing]);
331198
332- // Could consider doing any window click but I only handled search div here
333- // Since usually only clicks in search div will cause content changes in search div
199+ // Clicks in search div can cause content changes that for some reason don't trigger resize
200+ // Refresh clicking within container
334201 useEffect(() => {
335202 const searchContainer = searchRef.current;
336203 if (!open || !searchContainer) return;
337204 const handleSearchRefClick = () => {
338- refreshSearch("none");
205+ setTimeout(() => {
206+ refreshSearch("none");
207+ }, 150);
339208 };
340209 searchContainer.addEventListener("click", handleSearchRefClick);
341210 return () => {
342211 searchContainer.removeEventListener("click", handleSearchRefClick);
343212 };
344- }, [searchRef.current, refreshSearch, open]);
345-
346- // Triggers that should cause results to temporarily disappear and then reload
347- // Active = LLM is generating, etc.
348- const active = useAppSelector((state) => state.session.isStreaming);
349-
350- useEffect(() => {
351- if (active || isResizing) setMatches([]);
352- else refreshSearch("none");
353- }, [refreshSearch, active]);
354-
355- useEffect(() => {
356- if (!open) setMatches([]);
357- else refreshSearch("closest");
358- }, [refreshSearch, open]);
359-
360- useEffect(() => {
361- refreshSearch("closest");
362- }, [refreshSearch, caseSensitive, useRegex]);
213+ }, [searchRef, refreshSearch, open]);
363214
364215 // Find widget component
365- const widget = useMemo(() => {
366- return (
367- <div
368- className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
369- >
370- <Input
371- disabled={active}
372- type="text"
373- ref={inputRef}
374- value={input}
375- onChange={(e) => {
376- setInput(e.target.value);
377- }}
378- placeholder="Search..."
379- />
380- <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
381- {matches.length === 0
382- ? "No results"
383- : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
384- </p>
385- <div className="hidden flex-row gap-0.5 sm:flex">
386- <HeaderButtonWithToolTip
387- tooltipPlacement="top-end"
388- text={"Previous Match"}
389- onClick={(e) => {
390- e.stopPropagation();
391- previousMatch();
392- }}
393- className="h-4 w-4 focus:ring"
394- disabled={matches.length < 2 || active}
395- >
396- <ArrowUpIcon className="h-4 w-4" />
397- </HeaderButtonWithToolTip>
398- <HeaderButtonWithToolTip
399- tooltipPlacement="top-end"
400- text={"Next Match"}
401- onClick={(e) => {
402- e.stopPropagation();
403- nextMatch();
404- }}
405- className="h-4 w-4 focus:ring"
406- disabled={matches.length < 2 || active}
407- >
408- <ArrowDownIcon className="h-4 w-4" />
409- </HeaderButtonWithToolTip>
410- </div>
216+ const widget = (
217+ <div
218+ className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
219+ >
220+ <Input
221+ disabled={disabled}
222+ type="text"
223+ ref={inputRef}
224+ value={currentValue}
225+ onChange={(e) => {
226+ setCurrentValue(e.target.value);
227+ }}
228+ placeholder="Search..."
229+ />
230+ <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
231+ {matches.length === 0
232+ ? "No results"
233+ : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
234+ </p>
235+ <div className="hidden flex-row gap-0.5 sm:flex">
411236 <HeaderButtonWithToolTip
412- disabled={active}
413- inverted={caseSensitive}
414237 tooltipPlacement="top-end"
415- text={
416- caseSensitive
417- ? "Turn off case sensitivity"
418- : "Turn on case sensitivity"
419- }
238+ text={"Previous Match"}
420239 onClick={(e) => {
421240 e.stopPropagation();
422- setCaseSensitive((curr) => !curr);
241+ previousMatch();
423242 }}
424- className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
243+ className="h-4 w-4 focus:ring"
244+ disabled={matches.length < 2 || disabled}
425245 >
426- Aa
246+ <ArrowUpIcon className="h-4 w-4" />
427247 </HeaderButtonWithToolTip>
428- {/* TODO - add useRegex functionality */}
429- <HeaderButton
430- inverted={false}
431- onClick={() => setOpen(false)}
432- className="focus:ring"
248+ <HeaderButtonWithToolTip
249+ tooltipPlacement="top-end"
250+ text={"Next Match"}
251+ onClick={(e) => {
252+ e.stopPropagation();
253+ nextMatch();
254+ }}
255+ className="h-4 w-4 focus:ring"
256+ disabled={matches.length < 2 || disabled}
433257 >
434- <XMarkIcon className="h-4 w-4" />
435- </HeaderButton>
258+ <ArrowDownIcon className="h-4 w-4" />
259+ </HeaderButtonWithToolTip>
436260 </div>
437- );
438- }, [
439- open,
440- input,
441- inputRef,
442- caseSensitive,
443- matches,
444- currentMatch,
445- previousMatch,
446- nextMatch,
447- ]);
261+ <HeaderButtonWithToolTip
262+ disabled={disabled}
263+ inverted={caseSensitive}
264+ tooltipPlacement="top-end"
265+ text={
266+ caseSensitive
267+ ? "Turn off case sensitivity"
268+ : "Turn on case sensitivity"
269+ }
270+ onClick={(e) => {
271+ e.stopPropagation();
272+ setCaseSensitive((curr) => !curr);
273+ }}
274+ className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
275+ >
276+ Aa
277+ </HeaderButtonWithToolTip>
278+ {/* TODO - add useRegex functionality */}
279+ <HeaderButton
280+ inverted={false}
281+ onClick={() => setOpen(false)}
282+ className="focus:ring"
283+ >
284+ <XMarkIcon className="h-4 w-4" />
285+ </HeaderButton>
286+ </div>
287+ );
448288
449289 // Generate the highlight overlay elements
450290 const highlights = useMemo(() => {
451291 return matches.map((match) => (
452292 <HighlightOverlay
453- {...match.overlayRectangle}
293+ rectangle={match.overlayRectangle}
454294 isCurrent={currentMatch?.index === match.index}
455295 />
456296 ));
457297 }, [matches, currentMatch]);
458298
459299 return {
460- matches,
461300 highlights,
462- inputRef,
463- input: debouncedInput,
464- setInput,
465- open,
466- setOpen,
467301 widget,
468302 };
469303 };
added gui/src/components/find/findWidgetSearch.ts +146 −0
@@ -0,0 +1,146 @@
1+export interface Rectangle {
2+ top: number;
3+ left: number;
4+ width: number;
5+ height: number;
6+}
7+
8+export interface SearchMatch {
9+ index: number;
10+ textNode: Text;
11+ overlayRectangle: Rectangle;
12+}
13+
14+interface SearchOptions {
15+ caseSensitive: boolean;
16+ useRegex: boolean;
17+ offsetHeight: number;
18+}
19+
20+export const searchWithinContainer = (
21+ containerRef: React.RefObject<HTMLDivElement>,
22+ searchQuery: string,
23+ options: SearchOptions,
24+): {
25+ results: SearchMatch[];
26+ closestToMiddle: SearchMatch | null;
27+} => {
28+ const searchContainer = containerRef.current;
29+
30+ if (!searchContainer || !searchQuery) {
31+ return {
32+ results: [],
33+ closestToMiddle: null,
34+ };
35+ }
36+ const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
37+
38+ // First grab all text nodes
39+ // Skips any elements with the "find-widget-skip" class
40+ const textNodes: Text[] = [];
41+ const walker = document.createTreeWalker(
42+ searchContainer,
43+ NodeFilter.SHOW_ALL,
44+ {
45+ acceptNode: (node) => {
46+ if (node.nodeType === Node.ELEMENT_NODE) {
47+ if ((node as Element).classList.contains("find-widget-skip"))
48+ return NodeFilter.FILTER_REJECT;
49+ return NodeFilter.FILTER_ACCEPT;
50+ } else if (node.nodeType === Node.TEXT_NODE) {
51+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
52+ const nodeValue = options.caseSensitive
53+ ? node.nodeValue
54+ : node.nodeValue.toLowerCase();
55+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
56+ }
57+ return NodeFilter.FILTER_REJECT;
58+ },
59+ },
60+ );
61+
62+ while (walker.nextNode()) {
63+ if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
64+ textNodes.push(walker.currentNode as Text);
65+ }
66+
67+ // Now walk through each node match and extract search results
68+ // One node can have several matches
69+ const newMatches: SearchMatch[] = [];
70+ textNodes.forEach((textNode, idx) => {
71+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
72+ const highlightFullLine =
73+ textNode.parentElement?.className.includes("hljs");
74+
75+ let nodeTextValue = options.caseSensitive
76+ ? textNode.nodeValue
77+ : textNode.nodeValue.toLowerCase();
78+ let startIndex = 0;
79+ while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
80+ // Create a range to measure the size and position of the match
81+ const range = document.createRange();
82+ range.setStart(textNode, startIndex);
83+ const endIndex = startIndex + query.length;
84+ range.setEnd(textNode, endIndex);
85+ const rect = range.getBoundingClientRect();
86+ range.detach();
87+ startIndex = endIndex;
88+
89+ const top =
90+ rect.top +
91+ searchContainer.clientTop +
92+ searchContainer.scrollTop -
93+ options.offsetHeight;
94+
95+ const left =
96+ rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
97+
98+ // Build a match result and push to matches
99+ const newMatch: SearchMatch = {
100+ index: 0, // will set later
101+ textNode,
102+ overlayRectangle: {
103+ top,
104+ left: highlightFullLine ? 2 : left,
105+ width: highlightFullLine
106+ ? searchContainer.clientWidth - 4
107+ : rect.width, // equivalent of adding 2 px x padding
108+ height: rect.height,
109+ },
110+ };
111+ newMatches.push(newMatch);
112+
113+ if (highlightFullLine) {
114+ break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
115+ }
116+ }
117+ });
118+
119+ // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
120+ // Filter them out by using the overlay rectangle as a hash key
121+ const matchHash = Object.fromEntries(
122+ newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
123+ );
124+ const filteredMatches = Object.values(matchHash).map((match, index) => ({
125+ ...match,
126+ index,
127+ }));
128+
129+ // Find the match closest to the vertical middle of the container
130+ const verticalMiddle =
131+ searchContainer.scrollTop + searchContainer.clientHeight / 2;
132+ let closestDist = Infinity;
133+ let closestMatchToMiddle: SearchMatch | null = null;
134+ filteredMatches.forEach((match) => {
135+ const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
136+ if (dist < closestDist) {
137+ closestDist = dist;
138+ closestMatchToMiddle = match;
139+ }
140+ });
141+
142+ return {
143+ results: filteredMatches,
144+ closestToMiddle: closestMatchToMiddle,
145+ };
146+};
added gui/src/components/find/useDebounce.ts +19 −0
@@ -0,0 +1,19 @@
1+import { useEffect, useState } from "react";
2+
3+function useDebounceValue<T>(value: T, delay: number = 500): T {
4+ const [debouncedValue, setDebouncedValue] = useState<T>(value);
5+
6+ useEffect(() => {
7+ const timer = setTimeout(() => {
8+ setDebouncedValue(value);
9+ }, delay);
10+
11+ return () => {
12+ clearTimeout(timer);
13+ };
14+ }, [value, delay]);
15+
16+ return debouncedValue;
17+}
18+
19+export default useDebounceValue;
added gui/src/components/find/useElementSize.ts +81 −0
@@ -0,0 +1,81 @@
1+import { RefObject, useCallback, useEffect, useState } from "react";
2+
3+interface ElementSize {
4+ clientWidth: number;
5+ clientHeight: number;
6+ scrollWidth: number;
7+ scrollHeight: number;
8+ isResizing: boolean;
9+}
10+
11+interface UseElementSizeOptions {
12+ debounceMs?: number;
13+}
14+
15+export const useElementSize = (
16+ ref: RefObject<HTMLElement>,
17+ debounceMs = 250,
18+): ElementSize => {
19+ const [size, setSize] = useState<ElementSize>({
20+ clientWidth: 0,
21+ clientHeight: 0,
22+ scrollWidth: 0,
23+ scrollHeight: 0,
24+ isResizing: false,
25+ });
26+
27+ // Debounced update function
28+ const debouncedSetSize = useCallback(
29+ (measurements: Omit<ElementSize, "isResizing">) => {
30+ let timeoutId: NodeJS.Timeout;
31+
32+ setSize((prev) => ({ ...prev, isResizing: true }));
33+
34+ timeoutId = setTimeout(() => {
35+ setSize({
36+ ...measurements,
37+ isResizing: false,
38+ });
39+ }, debounceMs);
40+
41+ return () => clearTimeout(timeoutId);
42+ },
43+ [debounceMs],
44+ );
45+
46+ useEffect(() => {
47+ if (!ref.current) return;
48+
49+ const updateSize = () => {
50+ const element = ref.current;
51+ if (!element) return;
52+
53+ const measurements = {
54+ clientWidth: element.clientWidth,
55+ clientHeight: element.clientHeight,
56+ scrollWidth: element.scrollWidth,
57+ scrollHeight: element.scrollHeight,
58+ };
59+
60+ debouncedSetSize(measurements);
61+ };
62+
63+ // Create ResizeObserver instance
64+ const resizeObserver = new ResizeObserver(() => {
65+ updateSize();
66+ });
67+
68+ // Start observing the element
69+ resizeObserver.observe(ref.current);
70+
71+ // Initial size calculation
72+ updateSize();
73+
74+ // Cleanup
75+ return () => {
76+ resizeObserver.disconnect();
77+ };
78+ }, [ref, debouncedSetSize]);
79+
80+ return size;
81+};
modified gui/src/components/gui/Alert.tsx +1 −1
@@ -39,7 +39,7 @@
3939 const { Icon } = ALERT_CONFIGS[type];
4040
4141 return (
42- <div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none">
42+ <div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
4343 <div className="flex items-start">
4444 <Icon
4545 className="h-6 min-h-5 w-6 min-w-5"
modified gui/src/components/gui/NumberInput.tsx +36 −8
@@ -1,4 +1,4 @@
1-import React from "react";
1+import React, { useState } from "react";
22
33 interface NumberInputProps {
44 value: number;
@@ -13,34 +13,62 @@
1313 max,
1414 min,
1515 }) => {
16+ const [inputValue, setInputValue] = useState(value.toString());
17+
1618 const handleIncrement = () => {
1719 if (value < max) {
18- onChange(value + 1);
20+ const newValue = value + 1;
21+ onChange(newValue);
22+ setInputValue(newValue.toString());
1923 }
2024 };
2125
2226 const handleDecrement = () => {
2327 if (value > min) {
24- onChange(value - 1);
28+ const newValue = value - 1;
29+ onChange(newValue);
30+ setInputValue(newValue.toString());
31+ }
32+ };
33+
34+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
35+ const newInputValue = e.target.value;
36+ setInputValue(newInputValue);
37+
38+ // Only update the actual value if it's a valid number
39+ const numValue = parseInt(newInputValue, 10);
40+ if (!isNaN(numValue)) {
41+ // Apply min/max constraints
42+ const constrainedValue = Math.min(Math.max(numValue, min), max);
43+ onChange(constrainedValue);
2544 }
2645 };
2746
47+ const handleBlur = () => {
48+ // When input loses focus, ensure the displayed value matches the actual value
49+ // This handles cases where the user entered an invalid value
50+ setInputValue(value.toString());
51+ };
52+
2853 return (
2954 <div className="border-vsc-input-border bg-vsc-input-background flex flex-row overflow-hidden rounded-md border border-solid">
3055 <input
3156 type="text"
32- value={value}
33- readOnly
34- className="text-vsc-foreground max-w-7 border-none bg-inherit pr-1.5 text-right outline-none ring-0 focus:border-none focus:outline-none focus:ring-0"
57+ value={inputValue}
58+ onChange={handleInputChange}
59+ onBlur={handleBlur}
60+ className="text-vsc-foreground max-w-9 border-none bg-inherit pr-1.5 text-right outline-none ring-0 focus:border-none focus:outline-none focus:ring-0"
3561 style={{
3662 appearance: "none",
3763 WebkitAppearance: "none",
3864 MozAppearance: "none",
3965 }}
66+ min={min}
67+ max={max}
4068 />
4169 <div className="flex flex-col">
4270 <button
43- style={{ fontSize: "10px" }}
71+ style={{ fontSize: "9px" }}
4472 onClick={handleIncrement}
4573 disabled={value >= max}
4674 className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
@@ -48,7 +76,7 @@
4876 ▲
4977 </button>
5078 <button
51- style={{ fontSize: "10px" }}
79+ style={{ fontSize: "9px" }}
5280 className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
5381 onClick={handleDecrement}
5482 disabled={value <= min}
modified gui/src/components/gui/Switch.tsx +5 −2
@@ -1,4 +1,4 @@
1-import React from "react";
1+import React, { ReactNode } from "react";
22 import { vscButtonBackground } from "..";
33
44 type ToggleSwitchProps = {
@@ -6,6 +6,7 @@
66 onToggle: () => void;
77 text: string;
88 size?: number;
9+ showIfToggled?: ReactNode;
910 };
1011
1112 const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
@@ -13,11 +14,13 @@
1314 onToggle,
1415 text,
1516 size = 16,
17+ showIfToggled,
1618 }) => {
1719 return (
1820 <div className="flex cursor-pointer select-none items-center justify-between gap-3">
1921 <span className="truncate-right">{text}</span>
20- <div>
22+ <div className="flex flex-row items-center gap-1">
23+ {isToggled && !!showIfToggled && showIfToggled}
2124 <div
2225 className={`border-vsc-input-border bg-vsc-input-background flex items-center rounded-full border border-solid`}
2326 onClick={onToggle}
modified gui/src/components/index.ts +23 −110
@@ -1,114 +1,31 @@
11 import styled from "styled-components";
2-import { getFontSize } from "../util";
3-
4-export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
5-export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
6-export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
7-export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
8-export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground";
9-export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
10-export const VSC_LIST_SELECTION_BACKGROUND_VAR =
11- "--vscode-list-activeSelectionBackground";
12-export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder";
13-export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
14- "--vscode-quickInputList-focusForeground";
15-export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
16-export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
17-export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
18-export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
19-export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR =
20- "--vscode-commandCenter-activeBorder";
21-export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR =
22- "--vscode-commandCenter-inactiveBorder";
23-export const VSC_FIND_MATCH_SELECTED_VAR =
24- "--vscode-editor-findMatchHighlightBackground";
25-
26-export const VSC_THEME_COLOR_VARS = [
27- VSC_INPUT_BACKGROUND_VAR,
28- VSC_BACKGROUND_VAR,
29- VSC_FOREGROUND_VAR,
30- VSC_BUTTON_BACKGROUND_VAR,
31- VSC_BUTTON_FOREGROUND_VAR,
32- VSC_EDITOR_BACKGROUND_VAR,
33- VSC_LIST_SELECTION_BACKGROUND_VAR,
34- VSC_FOCUS_BORDER_VAR,
35- VSC_LIST_ACTIVE_FOREGROUND_VAR,
36- VSC_QUICK_INPUT_BACKGROUND_VAR,
37- VSC_INPUT_BORDER_VAR,
38- VSC_BADGE_BACKGROUND_VAR,
39- VSC_BADGE_FOREGROUND_VAR,
40- VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR,
41- VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR,
42- VSC_FIND_MATCH_SELECTED_VAR,
43-];
2+import { varWithFallback } from "../styles/theme";
443
4+// DEPRECATED - avoid using these where possible, use tailwind classes instead
455 export const defaultBorderRadius = "5px";
466 export const lightGray = "#999998";
477 export const greenButtonColor = "#189e72";
488
49-export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
50-export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
51-export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
52-export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
53-export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
54-export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`;
55-export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
56-export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`;
57-export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`;
58-export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
59-export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
60-export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
61-export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
62-export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
63-export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
64-export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
65-export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
66-
67-export function parseHexColor(hexColor: string): {
68- r: number;
69- g: number;
70- b: number;
71-} {
72- if (hexColor.startsWith("#")) {
73- hexColor = hexColor.slice(1);
74- }
75-
76- if (hexColor.length > 6) {
77- hexColor = hexColor.slice(0, 6);
78- }
79-
80- const r = parseInt(hexColor.substring(0, 2), 16);
81- const g = parseInt(hexColor.substring(2, 4), 16);
82- const b = parseInt(hexColor.substring(4, 6), 16);
83-
84- return { r, g, b };
85-}
86-
87-export function parseColorForHex(colorVar: string): string {
88- const value = getComputedStyle(document.documentElement).getPropertyValue(
89- colorVar,
90- );
91- if (value.startsWith("#")) {
92- return value.slice(0, 7);
93- }
94-
95- // Parse rgb/rgba
96- const rgbValues = value
97- .slice(value.startsWith("rgba") ? 5 : 4, -1)
98- .split(",")
99- .map((x) => x.trim())
100- .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
101- .map((x) => parseInt(x, 10));
102-
103- let hex =
104- "#" +
105- rgbValues
106- .map((x) => x.toString(16))
107- .map((x) => (x.length === 1 ? "0" + x : x))
108- .join("");
109-
110- return hex;
111-}
9+export const vscInputBackground = varWithFallback("input-background");
10+export const vscQuickInputBackground = varWithFallback("input-background");
11+export const vscBackground = varWithFallback("background");
12+export const vscForeground = varWithFallback("foreground");
13+export const vscButtonBackground = varWithFallback("primary-background");
14+export const vscButtonForeground = varWithFallback("primary-foreground");
15+export const vscEditorBackground = varWithFallback("editor-background");
16+export const vscListActiveBackground = varWithFallback("list-active");
17+export const vscFocusBorder = varWithFallback("border-focus");
18+export const vscListActiveForeground = varWithFallback(
19+ "list-active-foreground",
20+);
21+export const vscInputBorder = varWithFallback("input-border");
22+export const vscInputBorderFocus = varWithFallback("border-focus");
23+export const vscBadgeBackground = varWithFallback("badge-background");
24+export const vscBadgeForeground = varWithFallback("badge-foreground");
25+export const vscCommandCenterActiveBorder = varWithFallback(
26+ "command-border-focus",
27+);
28+export const vscCommandCenterInactiveBorder = varWithFallback("command-border");
11229
11330 export const Button = styled.button`
11431 padding: 6px 12px;
@@ -158,7 +75,7 @@
15875
15976 border: none;
16077 color: ${vscForeground};
161- background-color: rgba(255, 255, 255, 0.08);
78+ background-color: rgba(128, 128, 128, 0.4);
16279 &:disabled {
16380 color: gray;
16481 pointer-events: none;
@@ -226,10 +143,6 @@
226143 }
227144 `;
228145
229-export const Label = styled.label<{ fontSize?: number }>`
230- font-size: ${(props) => props.fontSize || getFontSize()}px;
231-`;
232-
233146 export const HeaderButton = styled.button<{
234147 inverted: boolean | undefined;
235148 backgroundColor?: string;
modified gui/src/components/mainInput/CodeToEditCard.tsx +3 −2
@@ -1,5 +1,5 @@
11 import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
2-import { CodeToEdit } from "core";
2+import { SetCodeToEditPayload } from "core";
33 import { getMarkdownLanguageTagForFile } from "core/util";
44 import { getUriPathBasename } from "core/util/uri";
55 import { useContext, useMemo, useState } from "react";
@@ -26,7 +26,7 @@
2626 `;
2727
2828 interface CodeToEditItemProps {
29- code: CodeToEdit;
29+ code: SetCodeToEditPayload;
3030 }
3131
3232 function CodeToEditItem({ code }: CodeToEditItemProps) {
@@ -143,6 +143,7 @@
143143 </div>
144144 );
145145 }
146+
146147 export default function CodeToEditCard() {
147148 // Array from previous multi-file edit
148149 const codeToEditArray = useAppSelector(
modified gui/src/components/mainInput/ContinueInputBox.tsx +14 −5
@@ -1,11 +1,12 @@
11 import { Editor, JSONContent } from "@tiptap/react";
2-import { ContextItemWithId, InputModifiers } from "core";
2+import { ContextItemWithId, InputModifiers, RuleWithSource } from "core";
33 import { useMemo } from "react";
44 import styled, { keyframes } from "styled-components";
55 import { defaultBorderRadius, vscBackground } from "..";
66 import { useAppSelector } from "../../redux/hooks";
77 import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
88 import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek";
9+import { RulesPeek } from "./belowMainInput/RulesPeek";
910 import { ToolbarOptions } from "./InputToolbar";
1011 import { Lump } from "./Lump";
1112 import { TipTapEditor } from "./TipTapEditor";
@@ -20,6 +21,7 @@
2021 ) => void;
2122 editorState?: JSONContent;
2223 contextItems?: ContextItemWithId[];
24+ appliedRules?: RuleWithSource[];
2325 hidden?: boolean;
2426 inputId: string; // used to keep track of things per input in redux
2527 }
@@ -116,6 +118,8 @@
116118 }
117119 : {};
118120
121+ const { appliedRules = [], contextItems = [] } = props;
122+
119123 return (
120124 <div
121125 className={`${props.hidden ? "hidden" : ""}`}
@@ -143,10 +147,15 @@
143147 />
144148 </GradientBorder>
145149 </div>
146- <ContextItemsPeek
147- contextItems={props.contextItems}
148- isCurrentContextPeek={props.isLastUserInput}
149- />
150+ {(appliedRules.length > 0 || contextItems.length > 0) && (
151+ <div className="mt-2 flex flex-col">
152+ <RulesPeek appliedRules={props.appliedRules} />
153+ <ContextItemsPeek
154+ contextItems={props.contextItems}
155+ isCurrentContextPeek={props.isLastUserInput}
156+ />
157+ </div>
158+ )}
150159 </div>
151160 );
152161 }
modified gui/src/components/mainInput/EditModeDetails.tsx +2 −2
@@ -2,7 +2,7 @@
22 import { IdeMessengerContext } from "../../context/IdeMessenger";
33 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
44 import { exitEditMode } from "../../redux/thunks/editMode";
5-import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
5+import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
66 import { useMainEditor } from "./TipTapEditor";
77
88 const EditModeDetails = () => {
@@ -28,7 +28,7 @@
2828 <div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
2929 <span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
3030 </div>
31- <AcceptRejectAllButtons
31+ <AcceptRejectDiffButtons
3232 applyStates={[editApplyState]}
3333 onAcceptOrReject={async (outcome) => {
3434 if (outcome === "acceptDiff") {
modified gui/src/components/mainInput/Lump/LumpToolbar.tsx +36 −1
@@ -1,4 +1,4 @@
1-import { useContext, useEffect } from "react";
1+import { useContext, useEffect, useMemo } from "react";
22 import { useSelector } from "react-redux";
33 import styled from "styled-components";
44 import { AnimatedEllipsis } from "../..";
@@ -40,12 +40,27 @@
4040 );
4141 }
4242
43+function ApplyingIndicator() {
44+ return (
45+ <div className="text-xs text-gray-400">
46+ <span>Applying</span>
47+ <AnimatedEllipsis />
48+ </div>
49+ );
50+}
51+
4352 export function LumpToolbar() {
4453 const dispatch = useAppDispatch();
4554 const ideMessenger = useContext(IdeMessengerContext);
4655 const ttsActive = useAppSelector((state) => state.ui.ttsActive);
4756 const isStreaming = useAppSelector((state) => state.session.isStreaming);
4857 const jetbrains = isJetBrains();
58+ const applyStates = useAppSelector(
59+ (store) => store.session.codeBlockApplyStates.states,
60+ );
61+ const isApplying = useMemo(() => {
62+ return applyStates.find((state) => state.status === "streaming");
63+ }, [applyStates]);
4964
5065 const toolCallState = useSelector(selectCurrentToolCall);
5166
@@ -89,6 +104,26 @@
89104 );
90105 }
91106
107+ if (isApplying) {
108+ return (
109+ <Container>
110+ <ApplyingIndicator />
111+ <StopButton
112+ className="text-gray-400"
113+ onClick={() => {
114+ // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
115+ // Apply is prioritized because it can be more catastrophic
116+ // Intentional to be more WYSIWYG for now
117+ ideMessenger.post("cancelApply", undefined);
118+ }}
119+ >
120+ {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
121+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
122+ </StopButton>
123+ </Container>
124+ );
125+ }
126+
92127 if (isStreaming) {
93128 return (
94129 <Container>
modified gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +1 −1
@@ -49,7 +49,7 @@
4949
5050 return (
5151 <GhostButton
52- className="w-full cursor-pointer rounded px-2 py-0.5 text-center text-gray-400 hover:text-gray-300"
52+ className="w-full cursor-pointer rounded px-2 py-0.5 text-center"
5353 style={{
5454 fontSize: fontSize(-3),
5555 }}
modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +57 −11
@@ -1,9 +1,13 @@
1+import { parseConfigYaml } from "@continuedev/config-yaml";
12 import {
23 BookmarkIcon as BookmarkOutline,
34 PencilIcon,
45 } from "@heroicons/react/24/outline";
56 import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
67 import { SlashCommandDescription } from "core";
8+import { useContext, useMemo } from "react";
9+import { useAuth } from "../../../../context/Auth";
10+import { IdeMessengerContext } from "../../../../context/IdeMessenger";
711 import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands";
812 import { useAppSelector } from "../../../../redux/hooks";
913 import { fontSize } from "../../../../util";
@@ -11,8 +15,10 @@
1115 import { useLump } from "../LumpContext";
1216 import { ExploreBlocksButton } from "./ExploreBlocksButton";
1317
18+type PromptWithSlug = SlashCommandDescription & { slug?: string };
19+
1420 interface PromptRowProps {
15- prompt: SlashCommandDescription;
21+ prompt: PromptWithSlug;
1622 isBookmarked: boolean;
1723 setIsBookmarked: (isBookmarked: boolean) => void;
1824 onEdit?: () => void;
@@ -88,24 +94,64 @@
8894 * Section that displays all available prompts with bookmarking functionality
8995 */
9096 export function PromptsSection() {
97+ const { selectedProfile } = useAuth();
9198 const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands();
99+ const ideMessenger = useContext(IdeMessengerContext);
92100
93101 const slashCommands = useAppSelector(
94102 (state) => state.config.config.slashCommands ?? [],
95103 );
96104
97- const handleEdit = (prompt: any) => {
98- // Handle edit action here
99- console.log("Editing prompt:", prompt);
105+ const handleEdit = (prompt: PromptWithSlug) => {
106+ if (prompt.promptFile) {
107+ ideMessenger.post("openFile", {
108+ path: prompt.promptFile,
109+ });
110+ } else if (prompt.slug) {
111+ void ideMessenger.request("controlPlane/openUrl", {
112+ path: `${prompt.slug}/new-version`,
113+ orgSlug: undefined,
114+ });
115+ } else {
116+ ideMessenger.post("config/openProfile", {
117+ profileId: undefined,
118+ });
119+ }
100120 };
101121
102- const sortedCommands = [...slashCommands].sort((a, b) => {
103- const aBookmarked = isCommandBookmarked(a.name);
104- const bBookmarked = isCommandBookmarked(b.name);
105- if (aBookmarked && !bBookmarked) return -1;
106- if (!aBookmarked && bBookmarked) return 1;
107- return 0;
108- });
122+ const sortedCommands = useMemo(() => {
123+ const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands);
124+ // get the slugs from rawYaml
125+ if (selectedProfile?.rawYaml) {
126+ const parsed = parseConfigYaml(selectedProfile.rawYaml);
127+ const parsedPrompts = parsed.prompts ?? [];
128+
129+ let index = 0;
130+ for (const prompt of promptsWithSlug) {
131+ // skip for local prompt files
132+ if (prompt.promptFile) continue;
133+
134+ const yamlPrompt = parsedPrompts[index];
135+ if (yamlPrompt) {
136+ if ("uses" in yamlPrompt) {
137+ prompt.slug = yamlPrompt.uses;
138+ } else {
139+ prompt.slug =
140+ `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
141+ }
142+ }
143+ index = index + 1;
144+ }
145+ }
146+
147+ return promptsWithSlug.sort((a, b) => {
148+ const aBookmarked = isCommandBookmarked(a.name);
149+ const bBookmarked = isCommandBookmarked(b.name);
150+ if (aBookmarked && !bBookmarked) return -1;
151+ if (!aBookmarked && bBookmarked) return 1;
152+ return 0;
153+ });
154+ }, [slashCommands, isCommandBookmarked, selectedProfile]);
109155
110156 return (
111157 <div className="flex flex-col">
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
@@ -159,7 +159,7 @@
159159 contentEditable={false}
160160 >
161161 <div
162- className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
162+ className="border-b-command-border m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
163163 style={{
164164 fontSize: getFontSize() - 3,
165165 }}
added gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +122 −0
@@ -0,0 +1,122 @@
1+import { DocumentTextIcon, GlobeAltIcon } from "@heroicons/react/24/outline";
2+import { RuleSource, RuleWithSource } from "core";
3+import { ComponentType, useMemo, useState } from "react";
4+import ToggleDiv from "../../ToggleDiv";
5+
6+interface RulesPeekProps {
7+ appliedRules?: RuleWithSource[];
8+ icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
9+}
10+
11+interface RulesPeekItemProps {
12+ rule: RuleWithSource;
13+}
14+
15+// Convert technical source to user-friendly text
16+const getSourceLabel = (source: RuleSource): string => {
17+ switch (source) {
18+ case "default-chat":
19+ return "Default Chat";
20+ case "default-agent":
21+ return "Default Agent";
22+ case "model-chat-options":
23+ return "Model Chat Options";
24+ case "model-agent-options":
25+ return "Model Agent Options";
26+ case "rules-block":
27+ return "Rules Block";
28+ case "json-systemMessage":
29+ return "System Message";
30+ case ".continuerules":
31+ return "Project Rules";
32+ default:
33+ return source;
34+ }
35+};
36+
37+export function RulesPeekItem({ rule }: RulesPeekItemProps) {
38+ const isGlobal = !rule.globs;
39+ const [expanded, setExpanded] = useState(false);
40+
41+ // Define maximum length for rule text display
42+ const maxRuleLength = 100;
43+ const isRuleLong = rule.rule.length > maxRuleLength;
44+
45+ // Get the displayed rule text based on expanded state
46+ const displayedRule =
47+ isRuleLong && !expanded
48+ ? `${rule.rule.slice(0, maxRuleLength)}...`
49+ : rule.rule;
50+
51+ const toggleExpand = () => {
52+ if (isRuleLong) {
53+ setExpanded(!expanded);
54+ }
55+ };
56+
57+ return (
58+ <div
59+ className={`group mr-2 flex flex-col overflow-hidden rounded px-1.5 py-1 text-xs hover:bg-white/10 ${isRuleLong ? "cursor-pointer hover:text-gray-200" : ""}`}
60+ data-testid="rules-peek-item"
61+ onClick={toggleExpand}
62+ >
63+ <div className="flex w-full items-center">
64+ {isGlobal ? (
65+ <GlobeAltIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
66+ ) : (
67+ <DocumentTextIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
68+ )}
69+
70+ <div className="flex min-w-0 flex-1 gap-2 text-xs">
71+ <div className="max-w-[50%] flex-shrink-0 truncate font-medium">
72+ {rule.name || "Assistant rule"}
73+ </div>
74+
75+ <div className="min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-500">
76+ {isGlobal
77+ ? "Always applied"
78+ : `Pattern: ${typeof rule.globs === "string" ? rule.globs : Array.isArray(rule.globs) ? rule.globs.join(", ") : ""}`}
79+ </div>
80+ </div>
81+ </div>
82+ <div
83+ className={`mt-1 whitespace-pre-line pl-6 pr-2 text-xs italic text-gray-300`}
84+ title={
85+ isRuleLong ? (expanded ? "Click to collapse" : "Click to expand") : ""
86+ }
87+ >
88+ {displayedRule}
89+ {isRuleLong && (
90+ <span className="ml-1 text-gray-400 opacity-0 transition-opacity group-hover:opacity-100">
91+ {expanded ? "(collapse)" : "(expand)"}
92+ </span>
93+ )}
94+ </div>
95+ <div className="mt-1 pl-6 pr-2 text-xs text-gray-500">
96+ Source: {getSourceLabel(rule.source)}
97+ </div>
98+ </div>
99+ );
100+}
101+
102+export function RulesPeek({ appliedRules, icon }: RulesPeekProps) {
103+ const rules = useMemo(() => {
104+ return appliedRules ?? [];
105+ }, [appliedRules]);
106+
107+ if (!rules || rules.length === 0) {
108+ return null;
109+ }
110+
111+ return (
112+ <ToggleDiv
113+ icon={icon}
114+ title={`${rules.length} rule${rules.length > 1 ? "s" : ""}`}
115+ testId="rules-peek"
116+ >
117+ {rules.map((rule, idx) => (
118+ <RulesPeekItem key={`rule-${idx}`} rule={rule} />
119+ ))}
120+ </ToggleDiv>
121+ );
122+}
modified gui/src/components/modelSelection/ModeSelect.tsx +11 −4
@@ -173,17 +173,24 @@
173173 {mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
174174 </ListboxOption>
175175
176- <ListboxOption value="agent" disabled={!agentModeSupported}>
176+ <ListboxOption
177+ value="agent"
178+ disabled={!agentModeSupported}
179+ className={"gap-1"}
180+ >
177181 <div className="flex flex-row items-center gap-1.5">
178182 <SparklesIcon className="h-3 w-3" />
179183 <span className="">Agent</span>
180184 </div>
181- {mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
182- {!agentModeSupported && <span> (Not supported)</span>}
185+ {agentModeSupported ? (
186+ mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />
187+ ) : (
188+ <span>(Not supported)</span>
189+ )}
183190 </ListboxOption>
184191
185192 <div className="text-lightgray px-2 py-1">
186- {metaKeyLabel}. for next mode
193+ {`${metaKeyLabel} . for next mode`}
187194 </div>
188195 </ListboxOptions>
189196 </div>
modified gui/src/components/modelSelection/ModelSelect.tsx +7 −3
@@ -166,7 +166,11 @@
166166
167167 useEffect(() => {
168168 const handleKeyDown = (event: KeyboardEvent) => {
169- if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) {
169+ if (
170+ event.key === "'" &&
171+ isMetaEquivalentKeyPressed(event as any) &&
172+ !event.shiftKey // To prevent collisions w/ assistant toggle logic
173+ ) {
170174 if (!selectedProfile) {
171175 return;
172176 }
@@ -179,7 +183,7 @@
179183 if (nextIndex < 0) nextIndex = options.length - 1;
180184 const newModelTitle = options[nextIndex].value;
181185
182- dispatch(
186+ void dispatch(
183187 updateSelectedModelByRole({
184188 selectedProfile,
185189 role: "chat",
@@ -219,7 +223,7 @@
219223 <Listbox
220224 onChange={async (val: string) => {
221225 if (val === selectedModel?.title) return;
222- dispatch(
226+ void dispatch(
223227 updateSelectedModelByRole({
224228 selectedProfile,
225229 role: mode === "edit" ? "edit" : "chat",
modified gui/src/context/Auth.tsx +1 −1
@@ -2,7 +2,7 @@
22 OrganizationDescription,
33 ProfileDescription,
44 } from "core/config/ProfileLifecycleManager";
5-import { ControlPlaneSessionInfo } from "core/control-plane/client";
5+import { ControlPlaneSessionInfo } from "core/control-plane/AuthTypes";
66 import React, {
77 createContext,
88 useCallback,
modified gui/src/context/LocalStorage.tsx +0 −1
@@ -19,7 +19,6 @@
1919 const [values, setValues] = useState<LocalStorageType>(DEFAULT_LOCAL_STORAGE);
2020
2121 // TODO setvalue
22-
2322 useEffect(() => {
2423 const isJetbrains = getLocalStorage("ide") === "jetbrains";
2524 let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14);
modified gui/src/context/MockIdeMessenger.ts +40 −2
@@ -1,9 +1,12 @@
11 import { IDE, PromptLog } from "core";
2+import { AuthType } from "core/control-plane/AuthTypes";
23 import {
4+ FromIdeProtocol,
35 FromWebviewProtocol,
46 ToCoreProtocol,
57 ToWebviewProtocol,
68 } from "core/protocol";
9+import { Message } from "core/protocol/messenger";
710 import { MessageIde } from "core/protocol/messenger/messageIde";
811 import {
912 GeneratorReturnType,
@@ -36,6 +39,7 @@
3639 ]);
3740 case "getControlPlaneSessionInfo":
3841 return returnFor("getControlPlaneSessionInfo", {
42+ AUTH_TYPE: AuthType.WorkOsStaging,
3943 accessToken: "",
4044 account: {
4145 label: "",
@@ -60,13 +64,48 @@
6064
6165 export class MockIdeMessenger implements IIdeMessenger {
6266 ide: IDE;
67+ private messageHandlers: Map<
68+ keyof FromIdeProtocol,
69+ Array<(data: any) => void>
70+ > = new Map();
6371
6472 constructor() {
6573 this.ide = new MessageIde(
6674 (messageType, data) => {
6775 throw new Error("Not implemented");
6876 },
69- (messageType, callback) => {},
77+ (messageType, callback) => {
78+ // Store the callback in our handlers map
79+ if (!this.messageHandlers.has(messageType)) {
80+ this.messageHandlers.set(messageType, []);
81+ }
82+ this.messageHandlers.get(messageType)?.push(callback);
83+ },
84+ );
85+ }
86+
87+ /**
88+ * Simulates a message being sent from the IDE to the webview
89+ * @param messageType The type of message to send
90+ * @param data The data to send with the message
91+ */
92+ mockMessageToWebview<T extends keyof ToWebviewProtocol>(
93+ messageType: T,
94+ data: ToWebviewProtocol[T][0],
95+ ): void {
96+ // Create a message object that matches what the useWebviewListener hook expects
97+ const messageData: Message<ToWebviewProtocol[T][0]> = {
98+ messageType,
99+ data,
100+ messageId: `mock-${Date.now()}-${Math.random().toString(36).substring(2)}`,
101+ };
102+
103+ // Dispatch a custom message event that the window event listener will pick up
104+ window.dispatchEvent(
105+ new MessageEvent("message", {
106+ data: messageData,
107+ origin: window.location.origin,
108+ }),
70109 );
71110 }
72111
@@ -80,7 +119,6 @@
80119 content: "This is a test",
81120 },
82121 ];
83-
84122 return undefined;
85123 }
86124
modified gui/src/context/VscTheme.tsx +1 −1
@@ -1,6 +1,6 @@
11 import { createContext, useContext, useState } from "react";
2-import { parseHexColor } from "../components";
32 import { useWebviewListener } from "../hooks/useWebviewListener";
3+import { parseHexColor } from "../styles/utils";
44
55 const hljsToTextMate: Record<string, string[]> = {
66 ".hljs-comment": ["comment"],
modified gui/src/hooks/ParallelListeners.tsx +7 −34
@@ -1,5 +1,4 @@
11 import { useCallback, useContext, useEffect, useRef } from "react";
2-import { VSC_THEME_COLOR_VARS } from "../components";
32 import { IdeMessengerContext } from "../context/IdeMessenger";
43
54 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
@@ -29,6 +28,10 @@
2928 import { refreshSessionMetadata } from "../redux/thunks/session";
3029 import { streamResponseThunk } from "../redux/thunks/streamResponse";
3130 import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
31+import {
32+ setDocumentStylesFromLocalStorage,
33+ setDocumentStylesFromTheme,
34+} from "../styles/theme";
3235 import { isJetBrains } from "../util";
3336 import { setLocalStorage } from "../util/localStorage";
3437 import { useWebviewListener } from "./useWebviewListener";
@@ -139,31 +142,13 @@
139142 dispatch(cancelStream());
140143
141144 const jetbrains = isJetBrains();
142- for (const colorVar of VSC_THEME_COLOR_VARS) {
143- if (jetbrains) {
144- const cached = localStorage.getItem(colorVar);
145- if (cached) {
146- document.body.style.setProperty(colorVar, cached);
147- }
148- }
149-
150- // Remove alpha channel from colors
151- const value = getComputedStyle(document.documentElement).getPropertyValue(
152- colorVar,
153- );
154- if (colorVar.startsWith("#") && value.length > 7) {
155- document.body.style.setProperty(colorVar, value.slice(0, 7));
156- }
157- }
145+ setDocumentStylesFromLocalStorage(jetbrains);
158146
159147 if (jetbrains) {
160148 // Save theme colors to local storage for immediate loading in JetBrains
161149 ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
162150 if (result.status === "success") {
163- Object.entries(result.content).forEach(([key, value]) => {
164- document.body.style.setProperty(key, value);
165- document.documentElement.style.setProperty(key, value);
166- });
151+ setDocumentStylesFromTheme(result.content);
167152 }
168153 });
169154
@@ -180,25 +165,13 @@
180165 (window as any).vscMachineId = msg.vscMachineId;
181166 (window as any).vscMediaUrl = msg.vscMediaUrl;
182167 });
183-
184- for (const colorVar of VSC_THEME_COLOR_VARS) {
185- if (document.body.style.getPropertyValue(colorVar)) {
186- localStorage.setItem(
187- colorVar,
188- document.body.style.getPropertyValue(colorVar),
189- );
190- }
191- }
192168 }
193169 }, []);
194170
195171 useWebviewListener(
196172 "jetbrains/setColors",
197173 async (data) => {
198- Object.entries(data).forEach(([key, value]) => {
199- document.body.style.setProperty(key, value);
200- document.documentElement.style.setProperty(key, value);
201- });
174+ setDocumentStylesFromTheme(data);
202175 },
203176 [],
204177 );
modified gui/src/pages/config/AccountButton.tsx +6 −0
@@ -1,5 +1,6 @@
11 import { UserCircleIcon } from "@heroicons/react/24/solid";
22
3+import { isHubSession } from "core/control-plane/AuthTypes";
34 import { SecondaryButton } from "../../components";
45 import {
56 Popover,
@@ -27,6 +28,11 @@
2728 );
2829 }
2930
31+ // No login button for on-prem deployments
32+ if (!isHubSession(session)) {
33+ return null;
34+ }
35+
3036 return (
3137 <Popover className="relative">
3238 {({ close }) => (
modified gui/src/pages/config/HelpCenterSection.tsx +21 −0
@@ -1,6 +1,7 @@
11 import {
22 ArrowTopRightOnSquareIcon,
33 DocumentArrowUpIcon,
4+ PaintBrushIcon,
45 TableCellsIcon,
56 } from "@heroicons/react/24/outline";
67 import { useContext } from "react";
@@ -9,6 +10,7 @@
910 import { useAppDispatch } from "../../redux/hooks";
1011 import { setOnboardingCard } from "../../redux/slices/uiSlice";
1112 import { saveCurrentSession } from "../../redux/thunks/session";
13+import { ROUTES } from "../../util/navigation";
1214 import MoreHelpRow from "./MoreHelpRow";
1315
1416 export function HelpCenterSection() {
@@ -20,6 +22,15 @@
2022 <div className="py-5">
2123 <h3 className="mb-4 mt-0 text-xl">Help center</h3>
2224 <div className="-mx-4 flex flex-col">
25+ <MoreHelpRow
26+ title="Continue Hub"
27+ description="Visit hub.continue.dev to explore custom assistants and blocks"
28+ Icon={ArrowTopRightOnSquareIcon}
29+ onClick={() =>
30+ ideMessenger.post("openUrl", "https://hub.continue.dev/")
31+ }
32+ />
33+
2334 <MoreHelpRow
2435 title="Documentation"
2536 description="Learn how to configure and use Continue"
@@ -74,6 +85,16 @@
7485 ideMessenger.post("showTutorial", undefined);
7586 }}
7687 />
88+ {process.env.NODE_ENV === "development" && (
89+ <MoreHelpRow
90+ title="Theme Test Page"
91+ description="Development page for testing themes"
92+ Icon={PaintBrushIcon}
93+ onClick={async () => {
94+ navigate(ROUTES.THEME);
95+ }}
96+ />
97+ )}
7798 </div>
7899 </div>
79100 );
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
@@ -11,7 +11,7 @@
1111 function KeyboardShortcut(props: KeyboardShortcutProps) {
1212 return (
1313 <div
14- className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "bg-list-active" : ""}`}
14+ className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-oddRow"}`}
1515 >
1616 <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0">
1717 <span className="block break-words text-xs">{props.description}:</span>
modified gui/src/pages/config/UserSettingsForm.tsx +88 −11
@@ -1,4 +1,9 @@
1-import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
1+import {
2+ CheckIcon,
3+ ChevronRightIcon,
4+ ExclamationTriangleIcon,
5+ XMarkIcon,
6+} from "@heroicons/react/24/outline";
27 import {
38 SharedConfigSchema,
49 modifyAnyConfigWithSharedConfig,
@@ -8,16 +13,19 @@
813 import NumberInput from "../../components/gui/NumberInput";
914 import { Select } from "../../components/gui/Select";
1015 import ToggleSwitch from "../../components/gui/Switch";
16+import { ToolTip } from "../../components/gui/Tooltip";
17+import { useFontSize } from "../../components/ui/font";
1118 import { IdeMessengerContext } from "../../context/IdeMessenger";
1219 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
1320 import { updateConfig } from "../../redux/slices/configSlice";
14-import { getFontSize } from "../../util";
21+import { setLocalStorage } from "../../util/localStorage";
1522
1623 export function UserSettingsForm() {
1724 /////// User settings section //////
1825 const dispatch = useAppDispatch();
1926 const ideMessenger = useContext(IdeMessengerContext);
2027 const config = useAppSelector((state) => state.config.config);
28+ const [showExperimental, setShowExperimental] = useState(false);
2129
2230 function handleUpdate(sharedConfig: SharedConfigSchema) {
2331 // Optimistic update
@@ -65,6 +73,7 @@
6573 const codeWrap = config.ui?.codeWrap ?? false;
6674 const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
6775 const readResponseTTS = config.experimental?.readResponseTTS ?? false;
76+ const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false;
6877 const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
6978 const disableSessionTitles = config.disableSessionTitles ?? false;
7079
@@ -77,7 +86,9 @@
7786 // const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top";
7887 const useAutocompleteMultilineCompletions =
7988 config.tabAutocompleteOptions?.multilineCompletions ?? "auto";
80- const fontSize = getFontSize();
89+ const modelTimeout = config.tabAutocompleteOptions?.modelTimeout ?? 150;
90+ const debounceDelay = config.tabAutocompleteOptions?.debounceDelay ?? 250;
91+ const fontSize = useFontSize();
8192
8293 const cancelChangeDisableAutocomplete = () => {
8394 setFormDisableAutocomplete(disableAutocompleteInFiles);
@@ -99,7 +110,7 @@
99110 }, [ideMessenger]);
100111
101112 return (
102- <div className="flex flex-col pt-3">
113+ <div className="flex flex-col">
103114 {/* {selectedProfile && isLocalProfile(selectedProfile) ? (
104115 <div className="flex items-center justify-center">
105116 <SecondaryButton
@@ -160,7 +171,6 @@
160171 }
161172 text="Text-to-Speech Output"
162173 />
163-
164174 {/* <ToggleSwitch
165175 isToggled={useChromiumForDocsCrawling}
166176 onToggle={() =>
@@ -223,18 +233,18 @@
223233 <span className="text-left">Font Size</span>
224234 <NumberInput
225235 value={fontSize}
226- onChange={(val) =>
236+ onChange={(val) => {
237+ setLocalStorage("fontSize", val);
227238 handleUpdate({
228239 fontSize: val,
229- })
230- }
240+ });
241+ }}
231242 min={7}
232243 max={50}
233244 />
234245 </label>
235-
236246 <label className="flex items-center justify-between gap-3">
237- <span className="line-clamp-1 text-left">
247+ <span className="lines lines-1 text-left">
238248 Multiline Autocompletions
239249 </span>
240250 <Select
@@ -253,7 +263,32 @@
253263 <option value="never">Never</option>
254264 </Select>
255265 </label>
256-
266+ <label className="flex items-center justify-between gap-3">
267+ <span className="text-left">Autocomplete Timeout (ms)</span>
268+ <NumberInput
269+ value={modelTimeout}
270+ onChange={(val) =>
271+ handleUpdate({
272+ modelTimeout: val,
273+ })
274+ }
275+ min={100}
276+ max={5000}
277+ />
278+ </label>
279+ <label className="flex items-center justify-between gap-3">
280+ <span className="text-left">Autocomplete Debounce (ms)</span>
281+ <NumberInput
282+ value={debounceDelay}
283+ onChange={(val) =>
284+ handleUpdate({
285+ debounceDelay: val,
286+ })
287+ }
288+ min={0}
289+ max={2500}
290+ />
291+ </label>
257292 <form
258293 className="flex flex-col gap-1"
259294 onSubmit={(e) => {
@@ -300,6 +335,48 @@
300335 </span>
301336 </form>
302337 </div>
338+
339+ <div className="flex flex-col gap-2">
340+ <div
341+ className="flex cursor-pointer items-center gap-2 text-left text-sm font-semibold"
342+ onClick={() => setShowExperimental(!showExperimental)}
343+ >
344+ <ChevronRightIcon
345+ className={`h-4 w-4 transition-transform ${
346+ showExperimental ? "rotate-90" : ""
347+ }`}
348+ />
349+ <span>Experimental Settings</span>
350+ </div>
351+ <div
352+ className={`duration-400 overflow-hidden transition-all ease-in-out ${
353+ showExperimental ? "max-h-40" : "max-h-0"
354+ }`}
355+ >
356+ <div className="flex flex-col gap-1 pl-6">
357+ <ToggleSwitch
358+ isToggled={autoAcceptEditToolDiffs}
359+ onToggle={() =>
360+ handleUpdate({
361+ autoAcceptEditToolDiffs: !autoAcceptEditToolDiffs,
362+ })
363+ }
364+ text="Auto-Accept Agent Edits"
365+ showIfToggled={
366+ <>
367+ <ExclamationTriangleIcon
368+ data-tooltip-id={`auto-accept-diffs-warning-tooltip`}
369+ className="h-3 w-3 text-yellow-500"
370+ />
371+ <ToolTip id={`auto-accept-diffs-warning-tooltip`}>
372+ {`Be very careful with this setting. When turned on, Agent mode's edit tool can make changes to files with no manual review or guaranteed stopping point`}
373+ </ToolTip>
374+ </>
375+ }
376+ />
377+ </div>
378+ </div>
379+ </div>
303380 </div>
304381 ) : null}
305382 </div>
modified gui/src/pages/config/index.tsx +4 −4
@@ -1,5 +1,5 @@
11 import {
2- AcademicCapIcon,
2+ BoltIcon,
33 CircleStackIcon,
44 Cog6ToothIcon,
55 QuestionMarkCircleIcon,
@@ -52,7 +52,7 @@
5252 id: "shortcuts",
5353 label: "Shortcuts",
5454 component: <KeyboardShortcuts />,
55- icon: <AcademicCapIcon className="xs:h-4 xs:w-4 h-3 w-3 flex-shrink-0" />,
55+ icon: <BoltIcon className="xs:h-4 xs:w-4 h-3 w-3 flex-shrink-0" />,
5656 },
5757 ];
5858
@@ -67,14 +67,14 @@
6767 />
6868
6969 {/* Tab Headers */}
70- <div className="grid grid-cols-2 border-0 border-b-[1px] border-solid border-b-zinc-700 p-0.5 sm:flex sm:justify-center md:gap-x-2">
70+ <div className="bg-vsc-input-background grid cursor-pointer grid-cols-2 border-0 border-b-[1px] border-solid border-b-zinc-700 p-0.5 sm:flex sm:justify-center md:gap-x-2">
7171 {tabs.map((tab) => (
7272 <div
7373 style={{
7474 fontSize: fontSize(-2),
7575 }}
7676 key={tab.id}
77- className={`hover:bg-vsc-input-background flex cursor-pointer items-center justify-center gap-1.5 rounded-md px-2 py-2 ${
77+ className={`flex cursor-pointer items-center justify-center gap-1.5 rounded-md px-2 py-2 hover:brightness-125 ${
7878 activeTab === tab.id ? "" : "text-gray-400"
7979 }`}
8080 onClick={() => setActiveTab(tab.id)}
modified gui/src/pages/gui/Chat.test.tsx +47 −0
@@ -59,4 +59,51 @@
5959 });
6060 expect(await screen.findByText("Hello, world!")).toBeInTheDocument();
6161 });
62+
63+ it("should handle apply updates and display the accept / reject all buttons", async () => {
64+ const { ideMessenger } = await renderWithProviders(<Chat />);
65+
66+ // Use queryByText which returns null when element isn't found
67+ const acceptAllButton = screen.queryByText("Accept All");
68+ const rejectAllButton = screen.queryByText("Reject All");
69+
70+ // Assert that the buttons don't exist
71+ expect(acceptAllButton).not.toBeInTheDocument();
72+ expect(rejectAllButton).not.toBeInTheDocument();
73+
74+ for (let i = 0; i < 5; i++) {
75+ ideMessenger.mockMessageToWebview("updateApplyState", {
76+ status: "streaming",
77+ streamId: `12345`,
78+ });
79+ }
80+
81+ ideMessenger.mockMessageToWebview("updateApplyState", {
82+ status: "done",
83+ streamId: "12345",
84+ });
85+
86+ // Wait for the buttons to appear
87+ await waitFor(() => {
88+ expect(
89+ screen.getByTestId("accept-reject-all-buttons"),
90+ ).toBeInTheDocument();
91+ });
92+
93+ // IDE sends back message that it is done
94+ ideMessenger.mockMessageToWebview("updateApplyState", {
95+ status: "closed",
96+ streamId: "12345",
97+ });
98+
99+ // Wait for the buttons to disappear
100+ await waitFor(() => {
101+ expect(
102+ screen.queryByTestId("edit-accept-button"),
103+ ).not.toBeInTheDocument();
104+ expect(
105+ screen.queryByTestId("edit-reject-button"),
106+ ).not.toBeInTheDocument();
107+ });
108+ });
62109 });
modified gui/src/pages/gui/Chat.tsx +21 −29
@@ -1,8 +1,6 @@
11 import {
22 ArrowLeftIcon,
33 ChatBubbleOvalLeftIcon,
4- CodeBracketSquareIcon,
5- ExclamationTriangleIcon,
64 } from "@heroicons/react/24/outline";
75 import { Editor, JSONContent } from "@tiptap/react";
86 import { InputModifiers } from "core";
@@ -20,7 +18,6 @@
2018 import { ErrorBoundary } from "react-error-boundary";
2119 import styled from "styled-components";
2220 import { Button, lightGray, vscBackground } from "../../components";
23-import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
2421 import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
2522 import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
2623 import { useFindWidget } from "../../components/find/FindWidget";
@@ -47,16 +44,17 @@
4744 setDialogMessage,
4845 setShowDialog,
4946 } from "../../redux/slices/uiSlice";
47+import { streamResponseThunk } from "../../redux/thunks";
5048 import { cancelStream } from "../../redux/thunks/cancelStream";
5149 import { streamEditThunk } from "../../redux/thunks/editMode";
5250 import { loadLastSession } from "../../redux/thunks/session";
53-import { streamResponseThunk } from "../../redux/thunks/streamResponse";
5451 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
5552 import {
5653 FREE_TRIAL_LIMIT_REQUESTS,
5754 incrementFreeTrialCount,
5855 } from "../../util/freeTrial";
5956
57+import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
6058 import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
6159 import EditModeDetails from "../../components/mainInput/EditModeDetails";
6260 import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
@@ -74,7 +72,7 @@
7472 }
7573
7674 .thread-message {
77- margin: 0px 0px 0px 1px;
75+ margin: 0 0 0 1px;
7876 }
7977 `;
8078
@@ -112,9 +110,10 @@
112110 (store) => store.config?.config.selectedModelByRole,
113111 );
114112 const isStreaming = useAppSelector((state) => state.session.isStreaming);
115- const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
113+ const [stepsOpen] = useState<(boolean | undefined)[]>([]);
116114 const mainTextInputRef = useRef<HTMLInputElement>(null);
117115 const stepsDivRef = useRef<HTMLDivElement>(null);
116+ const tabsRef = useRef<HTMLDivElement>(null);
118117 const history = useAppSelector((state) => state.session.history);
119118 const showChatScrollbar = useAppSelector(
120119 (state) => state.config.config.ui?.showChatScrollbar,
@@ -134,6 +133,8 @@
134133 return isJetBrains();
135134 }, []);
136135
136+ useAutoScroll(stepsDivRef, history);
137+
137138 useEffect(() => {
138139 // Cmd + Backspace to delete current step
139140 const listener = (e: any) => {
@@ -143,6 +144,7 @@
143144 !e.shiftKey
144145 ) {
145146 dispatch(cancelStream());
147+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
146148 }
147149 };
148150 window.addEventListener("keydown", listener);
@@ -152,7 +154,11 @@
152154 };
153155 }, [isStreaming, jetbrains]);
154156
155- const { widget, highlights } = useFindWidget(stepsDivRef);
157+ const { widget, highlights } = useFindWidget(
158+ stepsDivRef,
159+ tabsRef,
160+ isStreaming,
161+ );
156162
157163 const currentToolCallApplyState = useAppSelector(
158164 selectCurrentToolCallApplyState,
@@ -200,7 +206,7 @@
200206 if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) {
201207 // Show this message whether using platform or not
202208 // So that something happens if in new chat
203- ideMessenger.ide.showToast(
209+ void ideMessenger.ide.showToast(
204210 "error",
205211 "You've reached the free trial limit. Please configure a model to continue.",
206212 );
@@ -284,24 +290,21 @@
284290
285291 const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000;
286292
287- useAutoScroll(stepsDivRef, history);
288-
289293 return (
290294 <>
295+ {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
291296 {widget}
292297
293- {!!showSessionTabs && mode !== "edit" && <TabBar />}
294-
295298 <StepsDiv
296299 ref={stepsDivRef}
297- className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
300+ className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
298301 >
299302 {highlights}
300303 {history.map((item, index: number) => (
301304 <div
302305 key={item.message.id}
303306 style={{
304- minHeight: index === history.length - 1 ? "25vh" : 0,
307+ minHeight: index === history.length - 1 ? "200px" : 0,
305308 }}
306309 >
307310 <ErrorBoundary
@@ -320,6 +323,7 @@
320323 isMainInput={false}
321324 editorState={item.editorState}
322325 contextItems={item.contextItems}
326+ appliedRules={item.appliedRules}
323327 inputId={item.message.id}
324328 />
325329 </>
@@ -355,23 +359,11 @@
355359 <TimelineItem
356360 item={item}
357361 iconElement={
358- false ? (
359- <CodeBracketSquareIcon width="16px" height="16px" />
360- ) : false ? (
361- <ExclamationTriangleIcon
362- width="16px"
363- height="16px"
364- color="red"
365- />
366- ) : (
367- <ChatBubbleOvalLeftIcon width="16px" height="16px" />
368- )
362+ <ChatBubbleOvalLeftIcon width="16px" height="16px" />
369363 }
370364 open={
371365 typeof stepsOpen[index] === "undefined"
372- ? false
373- ? false
374- : true
366+ ? true
375367 : stepsOpen[index]!
376368 }
377369 onToggle={() => {}}
@@ -391,7 +383,7 @@
391383 <div className={"relative"}>
392384 <>
393385 {!isStreaming && mode !== "edit" && (
394- <AcceptRejectAllButtons
386+ <AcceptRejectDiffButtons
395387 applyStates={applyStates}
396388 onAcceptOrReject={async () => {}}
397389 />
modified gui/src/pages/gui/StreamError.tsx +86 −47
@@ -1,12 +1,15 @@
11 import {
22 ArrowTopRightOnSquareIcon,
3- Cog8ToothIcon,
3+ ClipboardIcon,
4+ Cog6ToothIcon,
5+ KeyIcon,
46 } from "@heroicons/react/24/outline";
57 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
68 import { useContext, useMemo } from "react";
7-import { Button, SecondaryButton } from "../../components";
9+import { GhostButton, SecondaryButton } from "../../components";
810 import { DiscordIcon } from "../../components/svg/DiscordIcon";
911 import { GithubIcon } from "../../components/svg/GithubIcon";
12+import ToggleDiv from "../../components/ToggleDiv";
1013 import { useAuth } from "../../context/Auth";
1114 import { IdeMessengerContext } from "../../context/IdeMessenger";
1215 import { selectSelectedProfile } from "../../redux/";
@@ -48,11 +51,15 @@
4851 );
4952
5053 const handleRefreshProfiles = () => {
51- refreshProfiles();
54+ void refreshProfiles();
5255 dispatch(setShowDialog(false));
5356 dispatch(setDialogMessage(undefined));
5457 };
5558
59+ const copyErrorToClipboard = () => {
60+ void navigator.clipboard.writeText(parsedError);
61+ };
62+
5663 // Collect model information to display useful error info
5764 let modelTitle = "Chat model";
5865 let providerName = "the model provider";
@@ -99,30 +106,29 @@
99106 }
100107
101108 const checkKeysButton = apiKeyUrl ? (
102- <Button
103- className="cursor-pointer hover:underline"
109+ <GhostButton
110+ className="flex items-center"
104111 onClick={() => {
105112 ideMessenger.post("openUrl", apiKeyUrl!);
106113 }}
107114 >
108- Check keys/usage
109- </Button>
115+ <KeyIcon className="mr-1.5 h-3.5 w-3.5" />
116+ <span>View key</span>
117+ </GhostButton>
110118 ) : null;
111119
112120 const configButton = (
113- <SecondaryButton
114- className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
121+ <GhostButton
122+ className="flex items-center"
115123 onClick={() => {
116124 ideMessenger.post("config/openProfile", {
117125 profileId: undefined,
118126 });
119127 }}
120128 >
121- <div>
122- <Cog8ToothIcon className="h-4 w-4" />
123- </div>
124- <span>Open Assistant configuration</span>
125- </SecondaryButton>
129+ <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
130+ <span>View config</span>
131+ </GhostButton>
126132 );
127133
128134 if (
@@ -131,7 +137,20 @@
131137 return <ModelsAddOnLimitDialog />;
132138 }
133139
134- let errorContent: React.ReactNode = <></>;
140+ let errorContent = (
141+ <div className="mb-3 mt-1">
142+ <div className="m-0 p-0">
143+ <p className="m-0 mb-2 p-0">
144+ There was an error handling the response from{" "}
145+ {selectedModel?.title || "the model"}.
146+ </p>
147+ <p className="m-0 p-0">
148+ Please try to submit your message again, and if the error persists,
149+ let us know by reporting the issue using the buttons below.
150+ </p>
151+ </div>
152+ </div>
153+ );
135154
136155 // Display components for specific errors
137156 if (statusCode === 429) {
@@ -141,7 +160,7 @@
141160 {`This might mean your ${modelTitle} usage has been rate limited
142161 by ${providerName}.`}
143162 </span>
144- <div className="flex flex-row flex-wrap gap-2">
163+ <div className="flex flex-row flex-wrap justify-start gap-3 py-4">
145164 {checkKeysButton}
146165 {configButton}
147166 </div>
@@ -230,51 +249,71 @@
230249 );
231250 }
232251
252+ console.log({ message });
253+
233254 return (
234- <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
235- <p className="m-0 p-0 text-lg text-red-500">
236- {statusCode ? `Error (status code ${statusCode})` : "Error"}
237- </p>
238-
239- {message ? (
240- <div className="mt-2 flex flex-col gap-0 rounded-sm">
241- <code className="max-h-20 overflow-y-auto p-2 font-mono">
242- {parsedError}
243- </code>
244- <div
245- className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
246- onClick={() => {
247- ideMessenger.post("toggleDevTools", undefined);
248- }}
249- >
250- <span className="px-2">View Logs</span>
251- <ArrowTopRightOnSquareIcon className="h-4 w-4" />
252- </div>
255+ <div className="flex flex-col gap-4 px-3 pb-3 pt-3">
256+ {/* Concise error title */}
257+ <h3 className="text-error m-0 p-0 text-lg font-medium">
258+ Error handling model response
259+ </h3>
260+
261+ {errorContent}
262+
263+ {/* Expandable technical details using ToggleDiv */}
264+ {message && (
265+ <div className="mb-2">
266+ <ToggleDiv title="View error output" testId="error-output-toggle">
267+ <div className="flex flex-col gap-0 rounded-sm">
268+ <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
269+ {parsedError}
270+ </code>
271+
272+ <div className="flex flex-row items-center justify-end gap-2 p-2">
273+ <GhostButton
274+ onClick={copyErrorToClipboard}
275+ className="flex items-center"
276+ >
277+ <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
278+ <span>Copy output</span>
279+ </GhostButton>
280+
281+ <GhostButton
282+ onClick={() => {
283+ ideMessenger.post("toggleDevTools", undefined);
284+ }}
285+ className="flex items-center"
286+ >
287+ <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
288+ <span className="text-xs">View Logs</span>
289+ </GhostButton>
290+ </div>
291+ </div>
292+ </ToggleDiv>
253293 </div>
254- ) : null}
255- <div className="mt-3">{errorContent}</div>
256-
257- <div className="mt-2 flex flex-col gap-1.5">
258- <span>Report this error:</span>
259- <div className="flex flex-row flex-wrap items-center gap-2">
260- <SecondaryButton
261- className="flex flex-row items-center gap-2 hover:opacity-70"
294+ )}
295+
296+ <div>
297+ <span className="text-base font-medium">Report this error</span>
298+ <div className="mt-2 flex flex-row flex-wrap items-center gap-2">
299+ <GhostButton
300+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
262301 onClick={() => {
263302 ideMessenger.post("openUrl", GITHUB_LINK);
264303 }}
265304 >
266305 <GithubIcon className="h-5 w-5" />
267306 <span className="xs:flex hidden">Github</span>
268- </SecondaryButton>
269- <SecondaryButton
270- className="flex flex-row items-center gap-2 hover:opacity-70"
307+ </GhostButton>
308+ <GhostButton
309+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
271310 onClick={() => {
272311 ideMessenger.post("openUrl", DISCORD_LINK);
273312 }}
274313 >
275314 <DiscordIcon className="h-5 w-5" />
276315 <span className="xs:flex hidden">Discord</span>
277- </SecondaryButton>
316+ </GhostButton>
278317 </div>
279318 </div>
280319 </div>
modified gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +4 −0
@@ -8,6 +8,10 @@
88 }
99
1010 export function CreateFile(props: CreateFileToolCallProps) {
11+ if (!props.fileContents) {
12+ return null;
13+ }
14+
1115 const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
1216
1317 return props.relativeFilepath ? (
modified gui/src/pages/gui/ToolCallDiv/EditFile.tsx +5 −4
@@ -16,13 +16,12 @@
1616 };
1717
1818 export function EditFile(props: EditToolCallProps) {
19- const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes ?? ""}\n\`\`\``;
20-
2119 const dispatch = useAppDispatch();
22- const isStreaming = useAppSelector((state) => state.session.isStreaming);
20+
2321 const applyState = useAppSelector((state) =>
2422 selectApplyStateByToolCallId(state, props.toolCallId),
2523 );
24+
2625 useEffect(() => {
2726 if (!applyState) {
2827 dispatch(
@@ -35,10 +34,12 @@
3534 }
3635 }, [applyState, props.toolCallId]);
3736
38- if (!props.relativeFilePath) {
37+ if (!props.relativeFilePath || !props.changes) {
3938 return null;
4039 }
4140
41+ const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
42+
4243 return (
4344 <StyledMarkdownPreview
4445 isRenderingInStepContainer
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +2 −2
@@ -27,8 +27,8 @@
2727 case BuiltInToolNames.EditExistingFile:
2828 return (
2929 <EditFile
30- relativeFilePath={args.filepath}
31- changes={args.changes}
30+ relativeFilePath={args.filepath ?? ""}
31+ changes={args.changes ?? ""}
3232 toolCallId={toolCall.id}
3333 historyIndex={historyIndex}
3434 />
modified gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +1 −1
@@ -61,7 +61,7 @@
6161 </div>
6262 <span
6363 className="ml-1 text-xs text-gray-400 transition-colors duration-200"
64- data-testid="toggle-div-title"
64+ data-testid="tool-call-title"
6565 >
6666 <ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
6767 </span>
modified gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx +4 −1
@@ -1,6 +1,8 @@
11 import { Tool, ToolCallState } from "core";
22 import Mustache from "mustache";
33 import { ReactNode } from "react";
4+import { getFontSize } from "../../../util";
5+import { useFontSize } from "../../../components/ui/font";
46
57 interface ToolCallStatusMessageProps {
68 tool: Tool | undefined;
@@ -11,6 +13,7 @@
1113 tool,
1214 toolCallState,
1315 }: ToolCallStatusMessageProps) {
16+ const fontSize = useFontSize();
1417 if (!tool) return "Agent tool use";
1518
1619 const defaultToolDescription = (
@@ -65,7 +68,7 @@
6568 message = futureMessage;
6669 }
6770 return (
68- <div className="block">
71+ <div className="block" style={{ fontSize }}>
6972 <span>Continue</span> {intro} {message}
7073 </div>
7174 );
modified gui/src/pages/gui/useAutoScroll.ts +14 −6
@@ -1,16 +1,24 @@
1-import { useEffect, useState } from "react";
1+import { useEffect, useMemo, useState } from "react";
2+import { ChatHistoryItemWithMessageId } from "../../redux/slices/sessionSlice";
3+
4+/**
5+ * Only reset scroll state when a new user message is added to the chat.
6+ * We don't want to auto-scroll on new tool response messages.
7+ */
8+function getNumUserMsgs(history: ChatHistoryItemWithMessageId[]) {
9+ return history.filter((msg) => msg.message.role === "user").length;
10+}
211
312 export const useAutoScroll = (
413 ref: React.RefObject<HTMLDivElement>,
5- history: unknown[],
14+ history: ChatHistoryItemWithMessageId[],
615 ) => {
716 const [userHasScrolled, setUserHasScrolled] = useState(false);
17+ const numUserMsgs = useMemo(() => getNumUserMsgs(history), [history.length]);
818
919 useEffect(() => {
10- if (history.length) {
11- setUserHasScrolled(false);
12- }
13- }, [history.length]);
20+ setUserHasScrolled(false);
21+ }, [numUserMsgs]);
1422
1523 useEffect(() => {
1624 if (!ref.current || history.length === 0) return;
modified gui/src/redux/slices/editModeState.ts +4 −3
@@ -1,10 +1,11 @@
11 import { createSlice, PayloadAction } from "@reduxjs/toolkit";
2-import { ApplyState, CodeToEdit, MessageModes } from "core";
2+import { ApplyState, SetCodeToEditPayload, MessageModes } from "core";
33 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
4+
45 export interface EditModeState {
56 // Array because of previous multi-file edit functionality
67 // Keeping array to not break persisted redux for now
7- codeToEdit: CodeToEdit[];
8+ codeToEdit: SetCodeToEditPayload[];
89 applyState: ApplyState;
910 returnToMode: MessageModes;
1011 lastNonEditSessionWasEmpty: boolean;
@@ -46,7 +47,7 @@
4647 {
4748 payload,
4849 }: PayloadAction<{
49- codeToEdit: CodeToEdit | CodeToEdit[];
50+ codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[];
5051 }>,
5152 ) => {
5253 state.codeToEdit = Array.isArray(payload.codeToEdit)
modified gui/src/redux/slices/sessionSlice.ts +16 −1
@@ -15,6 +15,7 @@
1515 FileSymbolMap,
1616 MessageModes,
1717 PromptLog,
18+ RuleWithSource,
1819 Session,
1920 SessionMetadata,
2021 ToolCallDelta,
@@ -31,7 +32,7 @@
3132
3233 // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
3334 // The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
34-type ChatHistoryItemWithMessageId = ChatHistoryItem & {
35+export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
3536 message: ChatMessage & { id: string };
3637 };
3738
@@ -247,6 +248,19 @@
247248 ...payload.contextItems,
248249 ];
249250 },
251+ setAppliedRulesAtIndex: (
252+ state,
253+ {
254+ payload,
255+ }: PayloadAction<{
256+ index: number;
257+ appliedRules: RuleWithSource[];
258+ }>,
259+ ) => {
260+ if (state.history[payload.index]) {
261+ state.history[payload.index].appliedRules = payload.appliedRules;
262+ }
263+ },
250264 setInactive: (state) => {
251265 const curMessage = state.history.at(-1);
252266
@@ -698,6 +712,7 @@
698712 updateFileSymbols,
699713 setContextItemsAtIndex,
700714 addContextItemsAtIndex,
715+ setAppliedRulesAtIndex,
701716 setInactive,
702717 streamUpdate,
703718 newSession,
modified gui/src/redux/thunks/editMode.ts +6 −2
@@ -1,6 +1,10 @@
11 import { createAsyncThunk } from "@reduxjs/toolkit";
22 import { JSONContent } from "@tiptap/core";
3-import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core";
3+import {
4+ SetCodeToEditPayload,
5+ MessageModes,
6+ RangeInFileWithContents,
7+} from "core";
48 import { stripImages } from "core/util/messageContent";
59 import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
610 import {
@@ -18,7 +22,7 @@
1822 void,
1923 {
2024 editorState: JSONContent;
21- codeToEdit: CodeToEdit[];
25+ codeToEdit: SetCodeToEditPayload[];
2226 },
2327 ThunkApiType
2428 >(
modified gui/src/redux/thunks/streamResponse.ts +32 −5
@@ -1,12 +1,14 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
22 import { JSONContent } from "@tiptap/core";
3-import { InputModifiers } from "core";
3+import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
44 import { constructMessages } from "core/llm/constructMessages";
5+import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
56 import posthog from "posthog-js";
67 import { v4 as uuidv4 } from "uuid";
78 import { getBaseSystemMessage } from "../../util";
89 import { selectSelectedChatModel } from "../slices/configSlice";
910 import {
11+ setAppliedRulesAtIndex,
1012 submitEditorAndInitAtIndex,
1113 updateHistoryItemAtIndex,
1214 } from "../slices/sessionSlice";
@@ -84,17 +86,42 @@
8486 }),
8587 );
8688
87- // Construct messages from updated history
89+ // Get updated history after the update
8890 const updatedHistory = getState().session.history;
89- const messageMode = getState().session.mode
9091
91- const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode)
92+ // Determine which rules apply to this message
93+ const userMsg = updatedHistory[inputIndex].message;
94+ const rules = getState().config.config.rules;
95+
96+ // Calculate applicable rules once
97+ // We need to check the message type to match what getApplicableRules expects
98+ const applicableRules = getApplicableRules(
99+ userMsg.role === "user" || userMsg.role === "tool"
100+ ? (userMsg as UserChatMessage | ToolResultChatMessage)
101+ : undefined,
102+ rules,
103+ selectedContextItems,
104+ );
105+
106+ // Store in history for UI display
107+ dispatch(
108+ setAppliedRulesAtIndex({
109+ index: inputIndex,
110+ appliedRules: applicableRules,
111+ }),
112+ );
113+
114+ const messageMode = getState().session.mode;
115+ const baseChatOrAgentSystemMessage = getBaseSystemMessage(
116+ selectedChatModel,
117+ messageMode,
118+ );
92119
93120 const messages = constructMessages(
94121 messageMode,
95122 [...updatedHistory],
96123 baseChatOrAgentSystemMessage,
97- state.config.config.rules,
124+ applicableRules,
98125 );
99126
100127 posthog.capture("step run", {
added gui/src/styles/ThemePage.tsx +232 −0
@@ -0,0 +1,232 @@
1+import {
2+ CheckCircleIcon,
3+ ExclamationCircleIcon,
4+ ExclamationTriangleIcon,
5+} from "@heroicons/react/24/outline";
6+import { useContext, useEffect, useMemo, useState } from "react";
7+import { useNavigate } from "react-router-dom";
8+import { Button } from "../components";
9+import { IdeMessengerContext } from "../context/IdeMessenger";
10+import { isJetBrains } from "../util";
11+import { ROUTES } from "../util/navigation";
12+import {
13+ clearThemeLocalCache,
14+ setDocumentStylesFromTheme,
15+ THEME_COLORS,
16+ varWithFallback,
17+} from "./theme";
18+
19+const ThemeTailwindClassExample = ({
20+ colorName,
21+ varNames,
22+ defaultColor,
23+ isMissing,
24+}: {
25+ colorName: string;
26+ varNames: string[];
27+ defaultColor: string;
28+ isMissing?: boolean;
29+}) => {
30+ return (
31+ <>
32+ <div className={`line-clamp-1 break-all px-2 text-right`}>
33+ {colorName}
34+ </div>
35+ <div
36+ className={`line-clamp-1 break-all p-1 text-[9px] ${isMissing ? "text-error" : ""}`}
37+ style={{
38+ backgroundColor: varWithFallback(
39+ colorName as keyof typeof THEME_COLORS,
40+ ),
41+ }}
42+ >
43+ {varNames.join(", ")}
44+ </div>
45+ <div
46+ className={`line-clamp-1 break-all p-1 text-[9px]`}
47+ style={{
48+ backgroundColor: defaultColor,
49+ }}
50+ >
51+ {defaultColor}
52+ </div>
53+ </>
54+ );
55+};
56+
57+function ThemePage() {
58+ const navigate = useNavigate();
59+ const [listToggled, setListToggled] = useState(false);
60+ const ideMessenger = useContext(IdeMessengerContext);
61+ const jetbrains = useMemo(() => {
62+ return isJetBrains();
63+ }, []);
64+
65+ const [missingVars, setMissingVars] = useState<string[]>([]);
66+ const refreshColors = () => {
67+ if (jetbrains) {
68+ // Jetbrains: get colors and check which ones are missing from theme
69+ void ideMessenger
70+ .request("jetbrains/getColors", undefined)
71+ .then((result) => {
72+ console.log(result);
73+ if (result.status === "success") {
74+ const missingColors = setDocumentStylesFromTheme(result.content);
75+ setMissingVars(missingColors);
76+ }
77+ });
78+ } else {
79+ // VS Code: find actual missing CSS variables
80+ const notFound: string[] = [];
81+ Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => {
82+ let found = false;
83+ themeVals.vars.forEach((cssVar) => {
84+ const value = getComputedStyle(
85+ document.documentElement,
86+ ).getPropertyValue(cssVar);
87+ if (!value) {
88+ notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`);
89+ }
90+ });
91+ });
92+ setMissingVars(notFound);
93+ }
94+ };
95+
96+ useEffect(() => {
97+ refreshColors();
98+ }, []);
99+
100+ return (
101+ <div className="flex flex-1 flex-col gap-3 px-2 py-2">
102+ <span
103+ className="flex cursor-pointer flex-row items-center gap-2"
104+ onClick={() => navigate(ROUTES.HOME)}
105+ >
106+ <span className="">←</span>
107+ Back to Chat
108+ </span>
109+ <h2 className="mb-2 mt-0 p-0 text-center text-xl font-semibold">
110+ Theme Tester
111+ </h2>
112+ <div className="bg-background border-border grid grid-cols-1 gap-4 rounded-md border border-solid p-4 md:grid-cols-2">
113+ <div className="col-span-2 flex gap-4">
114+ <p className="">Normal text</p>
115+ <p className="text-description">Description text</p>
116+ <p className="text-description-muted">Muted text</p>
117+ </div>
118+
119+ <button className="bg-primary text-primary-foreground hover:bg-primary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
120+ Primary Button
121+ </button>
122+ <button className="bg-secondary text-secondary-foreground hover:bg-secondary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
123+ Secondary Button
124+ </button>
125+
126+ <div className="border-border rounded-md border border-solid p-3">
127+ Normal border
128+ </div>
129+
130+ <div className="border-border-focus rounded-md border border-solid p-3">
131+ Focus border
132+ </div>
133+
134+ <input
135+ className="bg-input text-input-foreground border-input-border placeholder:text-input-placeholder focus:border-border-focus rounded-md border border-solid p-2 focus:outline-none"
136+ placeholder="Input example"
137+ />
138+
139+ <div className="bg-badge text-badge-foreground border-border inline-block rounded-full border border-solid p-2">
140+ <span className="px-2">Badge</span>
141+ </div>
142+
143+ <div className="flex items-center gap-2">
144+ <CheckCircleIcon className="text-success h-4 w-4" />
145+ <span className="text-success">Success</span>
146+ </div>
147+ <div className="flex items-center gap-2">
148+ <ExclamationCircleIcon className="text-warning h-4 w-4" />
149+ <span className="text-warning">Warning</span>
150+ </div>
151+ <div className="flex items-center gap-2">
152+ <ExclamationTriangleIcon className="text-error h-4 w-4" />
153+ <span className="text-error">Error</span>
154+ </div>
155+
156+ <div
157+ onClick={() => setListToggled(!listToggled)}
158+ className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`}
159+ >
160+ List item (clickable)
161+ </div>
162+ <div className="bg-editor text-editor-foreground border-border rounded-sm border border-solid p-2">
163+ <span>Editor</span>
164+ </div>
165+ <table>
166+ <tbody>
167+ <tr>
168+ <td className="border-border border-b border-solid p-2">
169+ <span>even table row</span>
170+ </td>
171+ </tr>
172+ <tr className="bg-table-oddRow">
173+ <td className="border-border border-b border-solid p-2">
174+ <span>odd table row</span>
175+ </td>
176+ </tr>
177+ </tbody>
178+ </table>
179+ <div>
180+ <span className="text-link">Link</span>
181+ </div>
182+ <div className="flex items-center gap-2">
183+ <span className="bg-findMatch">find match</span>
184+ <span className="bg-findMatch-selected">current match</span>
185+ </div>
186+ <div className="flex items-center gap-2">
187+ <span className="">Accent</span>
188+ <div className="bg-accent h-3 w-3" />
189+ </div>
190+ </div>
191+ <h2 className="mb-2 mt-6 text-xl font-semibold">Manage Theme</h2>
192+ <h2 className="mb-2 text-lg font-semibold">Missing Theme Colors</h2>
193+ {missingVars.length > 0 ? (
194+ <div className="flex flex-col gap-1">
195+ {missingVars.map((varName) => (
196+ <div key={varName} className="">
197+ {varName}
198+ </div>
199+ ))}
200+ </div>
201+ ) : (
202+ <div className="">No missing variables</div>
203+ )}
204+ <Button onClick={refreshColors}>Refresh Missing Colors</Button>
205+ {jetbrains ? (
206+ <Button onClick={clearThemeLocalCache}>Clear Theme Cache</Button>
207+ ) : null}
208+ <h2 className="mb-2 mt-6 text-xl font-semibold">All Theme Colors</h2>
209+ <div className="grid grid-cols-3">
210+ <div className="p-1">
211+ <span className="font-bold">Theme Color</span>
212+ </div>
213+ <div className="p-1">
214+ <span className="font-bold">CSS Var</span>
215+ </div>
216+ <div className="p-1">
217+ <span className="font-bold">Default</span>
218+ </div>
219+ {Object.entries(THEME_COLORS).map(([colorName, val]) => (
220+ <ThemeTailwindClassExample
221+ isMissing={missingVars.includes(colorName)}
222+ key={colorName}
223+ colorName={colorName}
224+ defaultColor={val.default}
225+ varNames={val.vars}
226+ />
227+ ))}
228+ </div>
229+ </div>
230+ );
231+}
232+export default ThemePage;
added gui/src/styles/theme.test.ts +24 −0
@@ -0,0 +1,24 @@
1+import { getRecursiveVar } from "./theme";
2+
3+test("getRecursiveVar returns single var with default for one variable", () => {
4+ const vars = ["--test-var"];
5+ const defaultColor = "#ffffff";
6+ const result = getRecursiveVar(vars, defaultColor);
7+ expect(result).toBe("var(--test-var, #ffffff)");
8+});
9+
10+test("getRecursiveVar returns nested vars in correct order for multiple variables", () => {
11+ const vars = ["--first-var", "--second-var", "--third-var"];
12+ const defaultColor = "#000000";
13+ const result = getRecursiveVar(vars, defaultColor);
14+ expect(result).toBe(
15+ "var(--first-var, var(--second-var, var(--third-var, #000000)))",
16+ );
17+});
18+
19+test("getRecursiveVar handles empty vars array", () => {
20+ const vars: string[] = [];
21+ const defaultColor = "#123456";
22+ const result = getRecursiveVar(vars, defaultColor);
23+ expect(result).toBe("#123456");
24+});
added gui/src/styles/theme.ts +271 −0
@@ -0,0 +1,271 @@
1+// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a
2+// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js
3+
4+// The current default theme is dark with blue accents
5+export const THEME_COLORS = {
6+ background: {
7+ vars: [
8+ "--vscode-sideBar-background",
9+ "--vscode-editor-background",
10+ "--vscode-panel-background",
11+ ],
12+ default: "#1e1e1e", // dark gray
13+ },
14+ foreground: {
15+ vars: [
16+ "--vscode-sideBar-foreground",
17+ "--vscode-editor-foreground",
18+ "--vscode-panel-foreground",
19+ ],
20+ default: "#e6e6e6", // light gray
21+ },
22+ "editor-background": {
23+ vars: ["--vscode-editor-background"],
24+ default: "#1e1e1e", // dark gray
25+ },
26+ "editor-foreground": {
27+ vars: ["--vscode-editor-foreground"],
28+ default: "#e6e6e6", // light gray
29+ },
30+ "primary-background": {
31+ vars: ["--vscode-button-background"],
32+ default: "#2c5aa0", // medium blue
33+ },
34+ "primary-foreground": {
35+ vars: ["--vscode-button-foreground"],
36+ default: "#ffffff", // white
37+ },
38+ "primary-hover": {
39+ vars: ["--vscode-button-hoverBackground"],
40+ default: "#3a6db3", // lighter blue
41+ },
42+ "secondary-background": {
43+ vars: ["--vscode-button-secondaryBackground"],
44+ default: "#303030", // medium dark gray
45+ },
46+ "secondary-foreground": {
47+ vars: ["--vscode-button-secondaryForeground"],
48+ default: "#e6e6e6", // light gray
49+ },
50+ "secondary-hover": {
51+ vars: ["--vscode-button-secondaryHoverBackground"],
52+ default: "#3a3a3a", // medium gray
53+ },
54+ border: {
55+ vars: ["--vscode-sideBar-border", "--vscode-panel-border"],
56+ default: "#2a2a2a", // dark gray border
57+ },
58+ "border-focus": {
59+ vars: ["--vscode-focusBorder"],
60+ default: "#3a6db3", // lighter blue
61+ },
62+ // Command styles are used for tip-tap editor
63+ "command-background": {
64+ vars: ["--vscode-commandCenter-background"],
65+ default: "#252525", // dark gray
66+ },
67+ "command-foreground": {
68+ vars: ["--vscode-commandCenter-foreground"],
69+ default: "#e6e6e6", // light gray
70+ },
71+ "command-border": {
72+ vars: ["--vscode-commandCenter-inactiveBorder"],
73+ default: "#555555", // medium gray
74+ },
75+ "command-border-focus": {
76+ vars: ["--vscode-commandCenter-activeBorder"],
77+ default: "#4d8bf0", // bright blue
78+ },
79+ description: {
80+ vars: ["--vscode-descriptionForeground"],
81+ default: "#b3b3b3", // medium light gray
82+ },
83+ "description-muted": {
84+ vars: ["--vscode-list-deemphasizedForeground"],
85+ default: "#8c8c8c", // medium gray
86+ },
87+ "input-background": {
88+ vars: ["--vscode-input-background"],
89+ default: "#2d2d2d", // dark gray
90+ },
91+ "input-foreground": {
92+ vars: ["--vscode-input-foreground"],
93+ default: "#e6e6e6", // light gray
94+ },
95+ "input-border": {
96+ vars: [
97+ "--vscode-input-border",
98+ "--vscode-commandCenter-inactiveBorder",
99+ "vscode-border",
100+ ],
101+ default: "#555555", // medium gray
102+ },
103+ "input-placeholder": {
104+ vars: ["--vscode-input-placeholderForeground"],
105+ default: "#9e9e9e", // medium light gray
106+ },
107+ "table-oddRow": {
108+ vars: ["--vscode-tree-tableOddRowsBackground"],
109+ default: "#2d2d2d", // dark gray
110+ },
111+ "badge-background": {
112+ vars: ["--vscode-badge-background"],
113+ default: "#4d4d4d", // medium dark gray
114+ },
115+ "badge-foreground": {
116+ vars: ["--vscode-badge-foreground"],
117+ default: "#ffffff", // white
118+ },
119+ success: {
120+ vars: [
121+ "--vscode-notebookStatusSuccessIcon-foreground",
122+ "--vscode-testing-iconPassed",
123+ "--vscode-gitDecoration-addedResourceForeground",
124+ "--vscode-charts-green",
125+ ],
126+ default: "#4caf50", // green
127+ },
128+ warning: {
129+ vars: [
130+ "--vscode-editorWarning-foreground",
131+ "--vscode-list-warningForeground",
132+ ],
133+ default: "#ffb74d", // amber/yellow
134+ },
135+ error: {
136+ vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"],
137+ default: "#f44336", // red
138+ },
139+ link: {
140+ vars: ["--vscode-textLink-foreground"],
141+ default: "#5c9ce6", // medium blue
142+ },
143+ accent: {
144+ vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"],
145+ default: "#4d8bf0", // bright blue
146+ },
147+ "find-match": {
148+ vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work
149+ default: "#264f7840", // translucent blue
150+ },
151+ "find-match-selected": {
152+ vars: ["--vscode-editor-findMatchHighlightBackground"],
153+ default: "#ffb74d40", // translucent amber
154+ },
155+ "list-hover": {
156+ // --vscode-tab-hoverBackground
157+ vars: ["--vscode-list-hoverBackground"],
158+ default: "#383838", // medium dark gray
159+ },
160+ "list-active": {
161+ vars: ["--vscode-list-activeSelectionBackground"],
162+ default: "#2c5aa050", // translucent medium blue
163+ },
164+ "list-active-foreground": {
165+ vars: ["--vscode-list-activeSelectionForeground"],
166+ default: "#ffffff", // white
167+ },
168+};
169+
170+// TODO: add fonts - GUI fonts in jetbrains differ from IDE:
171+// --vscode-editor-font-family;
172+// --vscode-font-family;
173+export const THEME_CSS_VARS = Object.values(THEME_COLORS)
174+ .map((value) => value.vars)
175+ .flat();
176+
177+export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce(
178+ (acc, [_, value]) => {
179+ value.vars.forEach((varName) => {
180+ acc[varName] = value.default;
181+ });
182+ return acc;
183+ },
184+ {} as Record<string, string>,
185+);
186+
187+export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce(
188+ (acc, [key, value]) => {
189+ acc[key] = value.default;
190+ return acc;
191+ },
192+ {} as Record<string, string>,
193+);
194+
195+// Generates recursive CSS variable fallback for a given color name
196+// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff))
197+export const getRecursiveVar = (vars: string[], defaultColor: string) => {
198+ return [...vars].reverse().reduce((curr, varName) => {
199+ return `var(${varName}, ${curr})`;
200+ }, defaultColor);
201+};
202+
203+export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => {
204+ const themeVals = THEME_COLORS[colorName];
205+ if (!themeVals) {
206+ throw new Error(`Invalid theme color name ${colorName}`);
207+ }
208+ return getRecursiveVar(themeVals.vars, themeVals.default);
209+};
210+
211+export const setDocumentStylesFromTheme = (
212+ theme: Record<string, string | undefined | null>,
213+) => {
214+ // Check for extraneous theme items
215+ Object.entries(theme).forEach(([colorName, value]) => {
216+ const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS];
217+ if (!themeVals) {
218+ console.warn(
219+ `Receieved theme color ${colorName} which is not used by the theme`,
220+ );
221+ return;
222+ }
223+ });
224+
225+ // Write theme values to document
226+ const missingColors: string[] = [];
227+ Object.entries(THEME_COLORS).forEach(([colorName, settings]) => {
228+ let colorVal = settings.default;
229+ const newColor = theme[colorName];
230+ if (newColor) {
231+ colorVal = newColor;
232+ // Remove alpha channel from all hex colors (seems to cause bad colors)
233+ if (newColor.startsWith("#") && newColor.length > 7) {
234+ colorVal = colorVal.slice(0, 7);
235+ }
236+ } else {
237+ missingColors.push(colorName);
238+ // console.warn(
239+ // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`,
240+ // );
241+ }
242+
243+ localStorage.setItem(colorName, colorVal);
244+ for (const cssVar of settings.vars) {
245+ document.body.style.setProperty(cssVar, colorVal);
246+ document.documentElement.style.setProperty(cssVar, colorVal);
247+ }
248+ });
249+
250+ return missingColors;
251+};
252+
253+export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => {
254+ for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) {
255+ for (const cssVar of themeVals.vars) {
256+ // Get cached values (for non-vscode IDEs)
257+ if (checkCache) {
258+ const cached = localStorage.getItem(colorName);
259+ if (cached) {
260+ document.body.style.setProperty(cssVar, cached);
261+ }
262+ }
263+ }
264+ }
265+};
266+
267+export const clearThemeLocalCache = () => {
268+ for (const colorName of Object.keys(THEME_COLORS)) {
269+ localStorage.removeItem(colorName);
270+ }
271+};
added gui/src/styles/utils.ts +45 −0
@@ -0,0 +1,45 @@
1+export function parseHexColor(hexColor: string): {
2+ r: number;
3+ g: number;
4+ b: number;
5+} {
6+ if (hexColor.startsWith("#")) {
7+ hexColor = hexColor.slice(1);
8+ }
9+
10+ if (hexColor.length > 6) {
11+ hexColor = hexColor.slice(0, 6);
12+ }
13+
14+ const r = parseInt(hexColor.substring(0, 2), 16);
15+ const g = parseInt(hexColor.substring(2, 4), 16);
16+ const b = parseInt(hexColor.substring(4, 6), 16);
17+
18+ return { r, g, b };
19+}
20+
21+export function parseColorForHex(colorVar: string): string {
22+ const value = getComputedStyle(document.documentElement).getPropertyValue(
23+ colorVar,
24+ );
25+ if (value.startsWith("#")) {
26+ return value.slice(0, 7);
27+ }
28+
29+ // Parse rgb/rgba
30+ const rgbValues = value
31+ .slice(value.startsWith("rgba") ? 5 : 4, -1)
32+ .split(",")
33+ .map((x) => x.trim())
34+ .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
35+ .map((x) => parseInt(x, 10));
36+
37+ let hex =
38+ "#" +
39+ rgbValues
40+ .map((x) => x.toString(16))
41+ .map((x) => (x.length === 1 ? "0" + x : x))
42+ .join("");
43+
44+ return hex;
45+}
modified gui/src/util/clientTools/editImpl.ts +15 −1
@@ -25,7 +25,21 @@
2525 if (apply.status === "error") {
2626 throw new Error(apply.error);
2727 }
28-
28+ const state = extras.getState();
29+ const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs;
30+ if (autoAccept) {
31+ const out = await extras.ideMessenger.request("acceptDiff", {
32+ streamId: extras.streamId,
33+ filepath: firstUriMatch,
34+ });
35+ if (out.status === "error") {
36+ throw new Error(out.error);
37+ }
38+ return {
39+ respondImmediately: true,
40+ output: undefined, // TODO - feed edit results back to model (also in parallel listeners)
41+ };
42+ }
2943 return {
3044 respondImmediately: false,
3145 output: undefined, // No immediate output.
modified gui/src/util/navigation.ts +1 −0
@@ -2,5 +2,6 @@
22 export const ROUTES = {
33 HOME: "/",
44 CONFIG: "/config",
5+ THEME: "/theme",
56 // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`,
67 };
modified gui/src/util/test/render.tsx +1 −0
@@ -72,6 +72,7 @@
7272 return {
7373 user,
7474 store,
75+ ideMessenger,
7576 ...rendered!,
7677 };
7778 }
modified gui/tailwind.config.cjs +69 −17
@@ -1,5 +1,6 @@
11 /** @type {import('tailwindcss').Config} */
22 const defaultTheme = require("tailwindcss/defaultTheme");
3+const { varWithFallback, THEME_COLORS } = require("./src/styles/theme");
34
45 module.exports = {
56 content: [
@@ -29,24 +30,75 @@
2930 default: "5px",
3031 },
3132 colors: {
32- lightgray: "#999998",
33- "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))",
34- "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))",
35- "vsc-foreground": "var(--vscode-editor-foreground, #fff)",
36- "vsc-editor-background":
37- "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))",
38- "vsc-input-border": "var(--vscode-input-border, #999998)",
39- "vsc-commandCenter-inactiveBorder":
40- "var(--vscode-commandCenter-inactiveBorder, #999998)",
33+ background: varWithFallback("background"),
34+ foreground: varWithFallback("foreground"),
35+ editor: {
36+ DEFAULT: varWithFallback("editor-background"),
37+ foreground: varWithFallback("editor-foreground"),
38+ },
39+ primary: {
40+ DEFAULT: varWithFallback("primary-background"),
41+ foreground: varWithFallback("primary-foreground"),
42+ hover: varWithFallback("primary-hover"),
43+ },
44+ secondary: {
45+ DEFAULT: varWithFallback("secondary-background"),
46+ foreground: varWithFallback("secondary-foreground"),
47+ hover: varWithFallback("secondary-hover"),
48+ },
49+ border: {
50+ DEFAULT: varWithFallback("border"),
51+ focus: varWithFallback("border-focus"),
52+ },
53+ command: {
54+ DEFAULT: varWithFallback("command-background"),
55+ foreground: varWithFallback("command-foreground"),
56+ border: {
57+ DEFAULT: varWithFallback("command-border"),
58+ focus: varWithFallback("command-border-focus"),
59+ },
60+ },
61+ description: {
62+ DEFAULT: varWithFallback("description"),
63+ muted: varWithFallback("description-muted"),
64+ },
65+ input: {
66+ DEFAULT: varWithFallback("input-background"),
67+ foreground: varWithFallback("input-foreground"),
68+ border: varWithFallback("input-border"),
69+ placeholder: varWithFallback("input-placeholder"),
70+ },
71+ table: {
72+ oddRow: varWithFallback("table-oddRow"),
73+ },
74+ badge: {
75+ DEFAULT: varWithFallback("badge-background"),
76+ foreground: varWithFallback("badge-foreground"),
77+ },
78+ success: varWithFallback("success"),
79+ warning: varWithFallback("warning"),
80+ error: varWithFallback("error"),
81+ link: varWithFallback("link"),
82+ accent: varWithFallback("accent"),
83+ findMatch: {
84+ DEFAULT: THEME_COLORS["find-match"].default,
85+ selected: varWithFallback("find-match-selected"),
86+ },
87+ list: {
88+ hover: varWithFallback("list-hover"),
89+ active: {
90+ DEFAULT: varWithFallback("list-active"),
91+ foreground: varWithFallback("list-active-foreground"),
92+ },
93+ },
4194
42- // Starting to make things less vsc-specific
43- // TODO make it all non-IDE-specific naming
44- "find-match-selected":
45- "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))",
46- "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)",
47- "list-active-foreground":
48- "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))",
49- badge: "var(--vscode-badge-background, #1bbe84)",
95+ // DEPRECATED, slowly remove usages of these ide-named or explicit colors
96+ lightgray: "#999998", // use border, description, or description-muted instead - AVOID
97+ "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead
98+ "vsc-background": varWithFallback("background"), // use "background" instead
99+ "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead
100+ "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead
101+ "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead
50102 },
51103 },
52104 },
modified manual-testing-sandbox/AdvancedPage.tsx +1 −4
@@ -13,10 +13,7 @@
1313 className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
1414 >
1515 <header className="mb-4 flex items-center justify-between border-b-2 pb-4">
16- I apologize, but there seems to be a misunderstanding. The user's
17- request doesn't appear to be related to rewriting the code section you
18- provided. The request mentions editing a readme.md file, which is not
19- part of the React component code you've shown.
16+ {" "}
2017 <button
2118 className="rounded bg-blue-500 px-4 py-2 text-white"
2219 onClick={toggleDarkMode}
modified manual-testing-sandbox/test.kt +3 −0
@@ -30,4 +30,7 @@
3030 return this
3131 }
3232 }
33+
34+
35+
3336
modified manual-testing-sandbox/test.ts +2 −2
@@ -9,7 +9,7 @@
99 this.result += number;
1010 return this;
1111 }
12-
12+
1313 subtract(number: number): Calculator {
1414 this.result -= number;
1515 return this;
@@ -38,4 +38,4 @@
3838 }
3939 }
4040
41-export default Calculator;
No newline at the end of the file
41+export default Calculator;
modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/__tests__/index.test.ts +5 −1
@@ -143,7 +143,7 @@
143143 );
144144
145145 // Test that packages were correctly unrolled and params replaced
146- expect(unrolledConfig.models?.length).toBe(3);
146+ expect(unrolledConfig.models?.length).toBe(4);
147147
148148 const openAiModel = unrolledConfig.models?.[0]!;
149149 expect(openAiModel.apiKey).toBe("sk-123");
@@ -163,6 +163,10 @@
163163 anthropicSecretLocation,
164164 );
165165
166+ const proxyOllamaModel = unrolledConfig.models?.[3]!;
167+ expect(proxyOllamaModel.provider).toBe('ollama')
168+ expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false);
169+
166170 expect(unrolledConfig.rules?.length).toBe(2);
167171 expect(unrolledConfig.docs?.[0]?.startUrl).toBe(
168172 "https://docs.python.org/release/3.13.1",
modified packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml +6 −0
@@ -27,3 +27,9 @@
2727 - uses: test-org/claude35sonnet
2828 with:
2929 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
30+
31+ - name: proxy-ollama
32+ provider: ollama
33+ model: llama3.1
34+ defaultCompletionOptions:
35+ stream: false

Next files