Changesets · Branches · Tags · Compare
| Changeset | ef601eb11092ff5ba1ae8f56c9e46214e0bef3e51bf670eea49b4271218a1963 |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-05-25 18:09 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-05-25 18:09 -07:00 |
| Parents | 9d8db5fc402e, f8a28b58727d |
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 @@ | ||
| 12 | 12 | |
| 13 | 13 | [ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ] |
| 14 | 14 | |
| 15 | -## Testing instructions | |
| 15 | +## Tests | |
| 16 | 16 | |
| 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 @@ | ||
| 63 | 63 | |
| 64 | 64 | - name: Bump version in gradle.properties |
| 65 | 65 | run: | |
| 66 | - cd extensions/intelllij | |
| 66 | + cd extensions/intellij | |
| 67 | 67 | 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 |
| 68 | 68 | rm -rf tmp |
| 69 | 69 | NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) |
modified .github/workflows/main.yaml +1 −1
| @@ -235,7 +235,7 @@ | ||
| 235 | 235 | - name: Publish to VS Code Marketplace |
| 236 | 236 | run: | |
| 237 | 237 | cd extensions/vscode |
| 238 | - npx vsce publish --packagePath ../../vsix-artifacts/*.vsix | |
| 238 | + npx @vscode/vsce publish --packagePath ../../vsix-artifacts/*.vsix | |
| 239 | 239 | env: |
| 240 | 240 | VSCE_PAT: ${{ secrets.VSCE_TOKEN }} |
| 241 | 241 |
modified .github/workflows/pr_checks.yaml +2 −1
| @@ -235,10 +235,11 @@ | ||
| 235 | 235 | cd packages/config-yaml |
| 236 | 236 | npm run build |
| 237 | 237 | |
| 238 | - - name: Type check | |
| 238 | + - name: Type check and lint | |
| 239 | 239 | run: | |
| 240 | 240 | cd gui |
| 241 | 241 | npx tsc --noEmit |
| 242 | + npm run lint | |
| 242 | 243 | |
| 243 | 244 | binary-checks: |
| 244 | 245 | needs: [install-root, install-core, install-config-yaml] |
modified .github/workflows/preview.yaml +1 −1
| @@ -232,7 +232,7 @@ | ||
| 232 | 232 | - name: Publish to VS Code Marketplace |
| 233 | 233 | run: | |
| 234 | 234 | cd extensions/vscode |
| 235 | - npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix | |
| 235 | + npx @vscode/vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix | |
| 236 | 236 | env: |
| 237 | 237 | VSCE_PAT: ${{ secrets.VSCE_TOKEN }} |
| 238 | 238 |
modified .gitignore +5 −1
| @@ -162,5 +162,9 @@ | ||
| 162 | 162 | |
| 163 | 163 | *.vsix |
| 164 | 164 | |
| 165 | +# intellij module library files | |
| 166 | +*.iml | |
| 167 | + | |
| 165 | 168 | .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 @@ | ||
| 2 | 2 | <project version="4"> |
| 3 | 3 | <component name="PrettierConfiguration"> |
| 4 | 4 | <option name="myConfigurationMode" value="AUTOMATIC" /> |
| 5 | + <option name="myRunOnSave" value="true" /> | |
| 5 | 6 | </component> |
| 6 | 7 | </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 @@ | ||
| 1 | 1 | <?xml version="1.0" encoding="UTF-8"?> |
| 2 | 2 | <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> | |
| 3 | 9 | <component name="VcsDirectoryMappings"> |
| 4 | 10 | <mapping directory="" vcs="Git" /> |
| 5 | 11 | </component> |
modified .vscode/extensions.json +2 −1
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | "dbaeumer.vscode-eslint", |
| 6 | 6 | "esbenp.prettier-vscode", |
| 7 | 7 | "bradlc.vscode-tailwindcss", |
| 8 | - "YoavBls.pretty-ts-errors" | |
| 8 | + "YoavBls.pretty-ts-errors", | |
| 9 | + "github.vscode-github-actions" | |
| 9 | 10 | ] |
| 10 | 11 | } |
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 @@ | ||
| 3 | 3 | ## Table of Contents |
| 4 | 4 | |
| 5 | 5 | - [Contributing to Continue](#contributing-to-continue) |
| 6 | - - [Table of Contents](#table-of-contents) | |
| 6 | + - [Table of Contents](#table-of-contents) | |
| 7 | 7 | - [❤️ 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) | |
| 34 | 35 | |
| 35 | 36 | # ❤️ Ways to Contribute |
| 36 | 37 | |
| 37 | 38 | ## 👋 Continue Contribution Ideas |
| 38 | 39 | |
| 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). | |
| 40 | 44 | |
| 41 | 45 | ## 🐛 Report Bugs |
| 42 | 46 | |
| 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: | |
| 44 | 49 | |
| 45 | 50 | - A description of the bug |
| 46 | 51 | - Steps to reproduce |
| @@ -50,19 +55,22 @@ | ||
| 50 | 55 | |
| 51 | 56 | ## ✨ Suggest Enhancements |
| 52 | 57 | |
| 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: | |
| 54 | 60 | |
| 55 | 61 | - Create an issue |
| 56 | 62 | |
| 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 | |
| 60 | 66 | |
| 61 | 67 | - Join the [Continue Discord](https://discord.gg/NWtdYexhMs) and tell us about your idea in the `#feedback` channel |
| 62 | 68 | |
| 63 | 69 | ## 📖 Updating / Improving Documentation |
| 64 | 70 | |
| 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). | |
| 66 | 74 | |
| 67 | 75 | ### Running the Documentation Server Locally |
| 68 | 76 | |
| @@ -70,7 +78,8 @@ | ||
| 70 | 78 | |
| 71 | 79 | #### Method 1: NPM Script |
| 72 | 80 | |
| 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. | |
| 74 | 83 | |
| 75 | 84 | 2. Run the following command to install the necessary dependencies for the documentation server: |
| 76 | 85 | |
| @@ -92,17 +101,22 @@ | ||
| 92 | 101 | |
| 93 | 102 | 3. Look for the `docs:start` task and select it. |
| 94 | 103 | |
| 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`. | |
| 96 | 106 | |
| 97 | 107 | ## 🧑💻 Contributing Code |
| 98 | 108 | |
| 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. | |
| 100 | 112 | |
| 101 | 113 | ### Environment Setup |
| 102 | 114 | |
| 103 | 115 | #### Pre-requisites |
| 104 | 116 | |
| 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: | |
| 106 | 120 | |
| 107 | 121 | ```bash |
| 108 | 122 | nvm use |
| @@ -114,32 +128,39 @@ | ||
| 114 | 128 | |
| 115 | 129 | 2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git` |
| 116 | 130 | |
| 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` | |
| 118 | 133 | |
| 119 | 134 | 4. Send your pull request to the main branch. |
| 120 | 135 | |
| 121 | 136 | #### VS Code |
| 122 | 137 | |
| 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` | |
| 124 | 140 | |
| 125 | 141 | 2. Start debugging: |
| 126 | 142 | |
| 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_ | |
| 133 | 149 | |
| 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". | |
| 135 | 153 | |
| 136 | 154 | ##### Debugging |
| 137 | 155 | |
| 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. | |
| 139 | 158 | |
| 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. | |
| 141 | 161 | |
| 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". | |
| 143 | 164 | |
| 144 | 165 | #### JetBrains |
| 145 | 166 | |
| @@ -147,11 +168,20 @@ | ||
| 147 | 168 | |
| 148 | 169 | ### Our Git Workflow |
| 149 | 170 | |
| 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>. | |
| 151 | 178 | |
| 152 | -### Development workflow | |
| 179 | +### What makes a good PR? | |
| 153 | 180 | |
| 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 | |
| 155 | 185 | - Keep changes focused. Multiple unrelated fixes should be opened as separate PRs |
| 156 | 186 | - Write or update tests for new functionality |
| 157 | 187 | - Update relevant documentation in the `docs` folder |
| @@ -159,18 +189,22 @@ | ||
| 159 | 189 | |
| 160 | 190 | ### Formatting |
| 161 | 191 | |
| 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. | |
| 163 | 194 | |
| 164 | 195 | ### Testing |
| 165 | 196 | |
| 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. | |
| 167 | 200 | |
| 168 | 201 | When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton. |
| 169 | 202 | |
| 170 | 203 | ### Review Process |
| 171 | 204 | |
| 172 | 205 | - **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. | |
| 174 | 208 | - **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch. |
| 175 | 209 | |
| 176 | 210 | ### Getting help |
| @@ -181,42 +215,53 @@ | ||
| 181 | 215 | |
| 182 | 216 | ### Adding an LLM Provider |
| 183 | 217 | |
| 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. | |
| 191 | 227 | 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. | |
| 195 | 233 | |
| 196 | 234 | ### Adding Models |
| 197 | 235 | |
| 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 | + ``` | |
| 221 | 266 | |
| 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 @@ | ||
| 8 | 8 | |
| 9 | 9 | <div align="center"> |
| 10 | 10 | |
| 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)** | |
| 12 | 15 | |
| 13 | 16 | </div> |
| 14 | 17 | |
| @@ -20,15 +23,25 @@ | ||
| 20 | 23 | <a target="_blank" href="https://docs.continue.dev" style="background:none"> |
| 21 | 24 | <img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" /> |
| 22 | 25 | </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> | |
| 23 | 29 | <a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none"> |
| 24 | 30 | <img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" /> |
| 25 | 31 | </a> |
| 26 | 32 | |
| 27 | 33 | <p></p> |
| 28 | 34 | |
| 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 | + | |
| 40 | + | |
| 29 | 41 | ## Chat |
| 30 | 42 | |
| 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 | |
| 32 | 45 | |
| 33 | 46 |  |
| 34 | 47 | |
| @@ -40,15 +53,11 @@ | ||
| 40 | 53 | |
| 41 | 54 | ## Edit |
| 42 | 55 | |
| 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 | |
| 44 | 58 | |
| 45 | 59 |  |
| 46 | 60 | |
| 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 | - | |
| 52 | 61 | |
| 53 | 62 | </div> |
| 54 | 63 | |
| @@ -58,7 +67,8 @@ | ||
| 58 | 67 | |
| 59 | 68 | ## Contributing |
| 60 | 69 | |
| 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). | |
| 62 | 72 | |
| 63 | 73 | ## License |
| 64 | 74 |
modified binary/build.js +1 −1
| @@ -64,7 +64,7 @@ | ||
| 64 | 64 | format: "cjs", |
| 65 | 65 | platform: "node", |
| 66 | 66 | sourcemap: true, |
| 67 | - minify: true, | |
| 67 | + minify: !esbuildOnly, | |
| 68 | 68 | treeShaking: true, |
| 69 | 69 | loader: { |
| 70 | 70 | // eslint-disable-next-line @typescript-eslint/naming-convention |
modified binary/package-lock.json +25 −3
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | "@types/jest": "^29.5.12", |
| 34 | 34 | "@types/uuid": "^9.0.8", |
| 35 | 35 | "@vercel/ncc": "^0.38.1", |
| 36 | + "cross-env": "^7.0.3", | |
| 36 | 37 | "esbuild": "0.19.11", |
| 37 | 38 | "jest": "^29.7.0", |
| 38 | 39 | "pkg": "^5.8.1", |
| @@ -92,6 +93,7 @@ | ||
| 92 | 93 | "p-limit": "^6.1.0", |
| 93 | 94 | "partial-json": "^0.1.7", |
| 94 | 95 | "pg": "^8.11.3", |
| 96 | + "plist": "^3.1.0", | |
| 95 | 97 | "posthog-node": "^3.6.3", |
| 96 | 98 | "puppeteer": "^22.4.0", |
| 97 | 99 | "puppeteer-chromium-resolver": "^23.0.0", |
| @@ -128,6 +130,7 @@ | ||
| 128 | 130 | "@types/mustache": "^4.2.5", |
| 129 | 131 | "@types/node-fetch": "^2.6.11", |
| 130 | 132 | "@types/pg": "^8.11.6", |
| 133 | + "@types/plist": "^3.0.5", | |
| 131 | 134 | "@types/request": "^2.48.12", |
| 132 | 135 | "@types/tar": "^6.1.13", |
| 133 | 136 | "@types/uuid": "^9.0.7", |
| @@ -2586,9 +2589,9 @@ | ||
| 2586 | 2589 | } |
| 2587 | 2590 | }, |
| 2588 | 2591 | "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==", | |
| 2592 | 2595 | "license": "MIT", |
| 2593 | 2596 | "dependencies": { |
| 2594 | 2597 | "follow-redirects": "^1.15.6", |
| @@ -3196,6 +3199,25 @@ | ||
| 3196 | 3199 | "node": "^14.15.0 || ^16.10.0 || >=18.0.0" |
| 3197 | 3200 | } |
| 3198 | 3201 | }, |
| 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 | + }, | |
| 3199 | 3221 | "node_modules/cross-spawn": { |
| 3200 | 3222 | "version": "7.0.6", |
| 3201 | 3223 | "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", |
modified binary/package.json +1 −0
| @@ -33,6 +33,7 @@ | ||
| 33 | 33 | "@types/jest": "^29.5.12", |
| 34 | 34 | "@types/uuid": "^9.0.8", |
| 35 | 35 | "@vercel/ncc": "^0.38.1", |
| 36 | + "cross-env": "^7.0.3", | |
| 36 | 37 | "esbuild": "0.19.11", |
| 37 | 38 | "jest": "^29.7.0", |
| 38 | 39 | "pkg": "^5.8.1", |
modified core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +2 −1
| @@ -72,7 +72,8 @@ | ||
| 72 | 72 | fullStop, |
| 73 | 73 | ); |
| 74 | 74 | |
| 75 | - const timeoutValue = helper.options.showWhateverWeHaveAtXMs; | |
| 75 | + const timeoutValue = helper.options.modelTimeout; | |
| 76 | + | |
| 76 | 77 | |
| 77 | 78 | lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!); |
| 78 | 79 |
modified core/autocomplete/filtering/streamTransforms/lineStream.test.ts +81 −1
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import * as lineStream from "./lineStream"; |
| 4 | 4 | |
| 5 | +// eslint-disable-next-line max-lines-per-function | |
| 5 | 6 | describe("lineStream", () => { |
| 6 | 7 | let mockFullStop: jest.Mock; |
| 7 | 8 | |
| @@ -204,6 +205,33 @@ | ||
| 204 | 205 | }); |
| 205 | 206 | |
| 206 | 207 | 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 | + | |
| 207 | 235 | it("should remove lines before the first valid line", async () => { |
| 208 | 236 | const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); |
| 209 | 237 | |
| @@ -213,7 +241,59 @@ | ||
| 213 | 241 | expect(filteredLines).toEqual(["const x = 5;"]); |
| 214 | 242 | }); |
| 215 | 243 | |
| 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 | + }); | |
| 217 | 297 | }); |
| 218 | 298 | |
| 219 | 299 | describe("filterEnglishLinesAtStart", () => { |
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +40 −26
| @@ -55,8 +55,8 @@ | ||
| 55 | 55 | return line; |
| 56 | 56 | } |
| 57 | 57 | |
| 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(); | |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | 62 | return undefined; |
| @@ -71,9 +71,9 @@ | ||
| 71 | 71 | return hasUselessLine || trimmed.startsWith("// end"); |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | -export const USELESS_LINES = ["", "```"]; | |
| 74 | +export const USELESS_LINES = [""]; | |
| 75 | 75 | export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; |
| 76 | -export const CODE_START_BLOCK = "[/CODE]"; | |
| 76 | +export const CODE_STOP_BLOCK = "[/CODE]"; | |
| 77 | 77 | export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; |
| 78 | 78 | export const PREFIXES_TO_SKIP = ["<COMPLETION>"]; |
| 79 | 79 | export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"]; |
| @@ -343,34 +343,48 @@ | ||
| 343 | 343 | * 4. Yields processed lines that are part of the actual code block content. |
| 344 | 344 | */ |
| 345 | 345 | 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; | |
| 348 | 351 | |
| 349 | 352 | for await (const line of rawLines) { |
| 350 | - // Filter out starting ``` | |
| 351 | - if (!seenValidLine) { | |
| 353 | + | |
| 354 | + | |
| 355 | + if (!seenFirstFence) { | |
| 352 | 356 | if (shouldRemoveLineBeforeStart(line)) { |
| 353 | - continue; | |
| 357 | + // Filter out starting ``` or START block | |
| 358 | + continue | |
| 354 | 359 | } |
| 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; | |
| 362 | 363 | } |
| 363 | 364 | |
| 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 | + } | |
| 374 | 388 | } |
| 375 | 389 | } |
| 376 | 390 | } |
modified core/autocomplete/generation/CompletionStreamer.ts +22 −7
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import { HelperVars } from "../util/HelperVars"; |
| 4 | 4 | |
| 5 | 5 | import { GeneratorReuseManager } from "./GeneratorReuseManager"; |
| 6 | +import { stopAfterMaxProcessingTime } from "./utils"; | |
| 6 | 7 | |
| 7 | 8 | export class CompletionStreamer { |
| 8 | 9 | private streamTransformPipeline = new StreamTransformPipeline(); |
| @@ -22,23 +23,37 @@ | ||
| 22 | 23 | completionOptions: Partial<CompletionOptions> | undefined, |
| 23 | 24 | helper: HelperVars, |
| 24 | 25 | ) { |
| 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 | + | |
| 25 | 30 | // Try to reuse pending requests if what the user typed matches start of completion |
| 26 | 31 | const generator = this.generatorReuseManager.getGenerator( |
| 27 | 32 | prefix, |
| 28 | - (abortSignal: AbortSignal) => | |
| 29 | - llm.supportsFim() | |
| 33 | + (abortSignal: AbortSignal) => { | |
| 34 | + const generator = llm.supportsFim() | |
| 30 | 35 | ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) |
| 31 | 36 | : llm.streamComplete(prompt, abortSignal, { |
| 32 | 37 | ...completionOptions, |
| 33 | 38 | 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 | + }, | |
| 35 | 54 | multiline, |
| 36 | 55 | ); |
| 37 | 56 | |
| 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 | - | |
| 42 | 57 | // LLM |
| 43 | 58 | const generatorWithCancellation = async function* () { |
| 44 | 59 | 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 @@ | ||
| 71 | 71 | }, |
| 72 | 72 | }; |
| 73 | 73 | |
| 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 | + | |
| 74 | 89 | const codestralFimTemplate: AutocompleteTemplate = { |
| 75 | 90 | template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}", |
| 76 | 91 | completionOptions: { |
| @@ -426,6 +441,10 @@ | ||
| 426 | 441 | return qwenCoderFimTemplate; |
| 427 | 442 | } |
| 428 | 443 | |
| 444 | + if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) { | |
| 445 | + return seedCoderFimTemplate; | |
| 446 | + } | |
| 447 | + | |
| 429 | 448 | if ( |
| 430 | 449 | lowerCaseModel.includes("starcoder") || |
| 431 | 450 | lowerCaseModel.includes("star-coder") || |
modified core/autocomplete/util/AutocompleteDebouncer.ts +24 −24
| @@ -1,32 +1,32 @@ | ||
| 1 | 1 | import { v4 as uuidv4 } from "uuid"; |
| 2 | + | |
| 2 | 3 | export class AutocompleteDebouncer { |
| 3 | 4 | private debounceTimeout: NodeJS.Timeout | undefined = undefined; |
| 4 | - private debouncing = false; | |
| 5 | - private lastUUID: string | undefined = undefined; | |
| 5 | + private currentRequestId: string | undefined = undefined; | |
| 6 | 6 | |
| 7 | 7 | 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); | |
| 28 | 15 | } |
| 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 | + }); | |
| 31 | 31 | } |
| 32 | 32 | } |
modified core/commands/slash/http.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { SlashCommand } from "../../index.js"; |
| 2 | 3 | import { removeQuotesAndEscapes } from "../../util/index.js"; |
| 3 | -import { streamResponse } from "../../llm/stream.js"; | |
| 4 | 4 | |
| 5 | 5 | const HttpSlashCommand: SlashCommand = { |
| 6 | 6 | name: "http", |
modified core/config/ConfigHandler.ts +17 −10
| @@ -1,10 +1,6 @@ | ||
| 1 | 1 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 2 | 2 | |
| 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"; | |
| 8 | 4 | import { |
| 9 | 5 | BrowserSerializedContinueConfig, |
| 10 | 6 | ContinueConfig, |
| @@ -15,10 +11,15 @@ | ||
| 15 | 11 | } from "../index.js"; |
| 16 | 12 | import { GlobalContext } from "../util/GlobalContext.js"; |
| 17 | 13 | |
| 14 | +import { | |
| 15 | + AuthType, | |
| 16 | + ControlPlaneSessionInfo, | |
| 17 | +} from "../control-plane/AuthTypes.js"; | |
| 18 | +import { getControlPlaneEnv } from "../control-plane/env.js"; | |
| 18 | 19 | import { logger } from "../util/logger.js"; |
| 19 | 20 | import { |
| 20 | 21 | ASSISTANTS, |
| 21 | - getAllDotContinueYamlFiles, | |
| 22 | + getAllDotContinueDefinitionFiles, | |
| 22 | 23 | LoadAssistantFilesOptions, |
| 23 | 24 | } from "./loadLocalAssistants.js"; |
| 24 | 25 | import LocalProfileLoader from "./profile/LocalProfileLoader.js"; |
| @@ -136,8 +137,7 @@ | ||
| 136 | 137 | } |
| 137 | 138 | |
| 138 | 139 | private async getOrgs(): Promise<OrgWithProfiles[]> { |
| 139 | - const userId = await this.controlPlaneClient.userId; | |
| 140 | - if (userId) { | |
| 140 | + if (await this.controlPlaneClient.isSignedIn()) { | |
| 141 | 141 | const orgDescs = await this.controlPlaneClient.listOrganizations(); |
| 142 | 142 | const personalHubOrg = await this.getPersonalHubOrg(); |
| 143 | 143 | const hubOrgs = await Promise.all( |
| @@ -255,7 +255,7 @@ | ||
| 255 | 255 | if (currentProfile) { |
| 256 | 256 | this.globalContext.update("lastSelectedProfileForWorkspace", { |
| 257 | 257 | ...selectedProfiles, |
| 258 | - [profileKey]: selectedProfiles.id ?? null, | |
| 258 | + [profileKey]: currentProfile.profileDescription.id, | |
| 259 | 259 | }); |
| 260 | 260 | } |
| 261 | 261 | |
| @@ -270,6 +270,13 @@ | ||
| 270 | 270 | /** |
| 271 | 271 | * Users can define as many local assistants as they want in a `.continue/assistants` folder |
| 272 | 272 | */ |
| 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 | + | |
| 273 | 280 | const localProfiles: ProfileLifecycleManager[] = []; |
| 274 | 281 | |
| 275 | 282 | if (options.includeGlobal) { |
| @@ -277,7 +284,7 @@ | ||
| 277 | 284 | } |
| 278 | 285 | |
| 279 | 286 | if (options.includeWorkspace) { |
| 280 | - const assistantFiles = await getAllDotContinueYamlFiles( | |
| 287 | + const assistantFiles = await getAllDotContinueDefinitionFiles( | |
| 281 | 288 | this.ide, |
| 282 | 289 | options, |
| 283 | 290 | ASSISTANTS, |
modified core/config/load.ts +9 −3
| @@ -101,7 +101,14 @@ | ||
| 101 | 101 | |
| 102 | 102 | const configMergeKeys = { |
| 103 | 103 | 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 | + }, | |
| 105 | 112 | slashCommands: (a: any, b: any) => a.name === b.name, |
| 106 | 113 | customCommands: (a: any, b: any) => a.name === b.name, |
| 107 | 114 | }; |
| @@ -970,6 +977,5 @@ | ||
| 970 | 977 | finalToBrowserConfig, |
| 971 | 978 | intermediateToFinalConfig, |
| 972 | 979 | loadContinueConfigFromJson, |
| 973 | - type BrowserSerializedContinueConfig | |
| 980 | + type BrowserSerializedContinueConfig, | |
| 974 | 981 | }; |
| 975 | - |
modified core/config/loadLocalAssistants.ts +5 −5
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; |
| 14 | 14 | |
| 15 | 15 | 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")) { | |
| 17 | 17 | return false; |
| 18 | 18 | } |
| 19 | 19 | |
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); |
| 22 | 22 | } |
| 23 | 23 | |
| 24 | -export async function listYamlFilesInDir( | |
| 24 | +async function getDefinitionFilesInDir( | |
| 25 | 25 | ide: IDE, |
| 26 | 26 | dir: string, |
| 27 | 27 | ): Promise<{ path: string; content: string }[]> { |
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | source: "get assistant files", |
| 42 | 42 | }); |
| 43 | 43 | const assistantFilePaths = uris.filter( |
| 44 | - (p) => p.endsWith(".yaml") || p.endsWith(".yml"), | |
| 44 | + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), | |
| 45 | 45 | ); |
| 46 | 46 | const results = assistantFilePaths.map(async (uri) => { |
| 47 | 47 | const content = await ide.readFile(uri); // make a try catch |
| @@ -86,7 +86,7 @@ | ||
| 86 | 86 | * This method searches in both ~/.continue and workspace .continue |
| 87 | 87 | * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts |
| 88 | 88 | */ |
| 89 | -export async function getAllDotContinueYamlFiles( | |
| 89 | +export async function getAllDotContinueDefinitionFiles( | |
| 90 | 90 | ide: IDE, |
| 91 | 91 | options: LoadAssistantFilesOptions, |
| 92 | 92 | subDirName: string, |
| @@ -103,7 +103,7 @@ | ||
| 103 | 103 | |
| 104 | 104 | // Get all assistant files from the directories |
| 105 | 105 | const assistantFiles = ( |
| 106 | - await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) | |
| 106 | + await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) | |
| 107 | 107 | ).flat(); |
| 108 | 108 | |
| 109 | 109 | 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 @@ | ||
| 173 | 173 | effected = true; |
| 174 | 174 | } |
| 175 | 175 | |
| 176 | + const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI; | |
| 177 | + if (autoAcceptEditToolDiffs !== undefined) { | |
| 178 | + shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs; | |
| 179 | + migratedUI = withoutAutoApply; | |
| 180 | + effected = true; | |
| 181 | + } | |
| 182 | + | |
| 176 | 183 | const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI; |
| 177 | 184 | if (showChatScrollbar !== undefined) { |
| 178 | 185 | shareConfigUpdates.showChatScrollbar = showChatScrollbar; |
modified core/config/profile/doLoadConfig.ts +7 −0
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | import { TTS } from "../../util/tts"; |
| 33 | 33 | import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; |
| 34 | 34 | import { loadContinueConfigFromJson } from "../load"; |
| 35 | +import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; | |
| 35 | 36 | import { migrateJsonSharedConfig } from "../migrateSharedConfig"; |
| 36 | 37 | import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; |
| 37 | 38 | import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; |
| @@ -128,6 +129,12 @@ | ||
| 128 | 129 | newConfig.rules.unshift(...rules); |
| 129 | 130 | errors.push(...continueRulesErrors); |
| 130 | 131 | |
| 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 | + | |
| 131 | 138 | // Rectify model selections for each role |
| 132 | 139 | newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); |
| 133 | 140 |
modified core/config/sharedConfig.ts +14 −0
| @@ -26,11 +26,14 @@ | ||
| 26 | 26 | codeWrap: z.boolean(), |
| 27 | 27 | displayRawMarkdown: z.boolean(), |
| 28 | 28 | showChatScrollbar: z.boolean(), |
| 29 | + autoAcceptEditToolDiffs: z.boolean(), | |
| 29 | 30 | |
| 30 | 31 | // `tabAutocompleteOptions` in `ContinueConfig` |
| 31 | 32 | useAutocompleteCache: z.boolean(), |
| 32 | 33 | useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]), |
| 33 | 34 | disableAutocompleteInFiles: z.array(z.string()), |
| 35 | + modelTimeout: z.number(), | |
| 36 | + debounceDelay: z.number(), | |
| 34 | 37 | }) |
| 35 | 38 | .partial(); |
| 36 | 39 | |
| @@ -103,6 +106,13 @@ | ||
| 103 | 106 | configCopy.tabAutocompleteOptions.disableInFiles = |
| 104 | 107 | sharedConfig.disableAutocompleteInFiles; |
| 105 | 108 | } |
| 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 | + } | |
| 106 | 116 | |
| 107 | 117 | configCopy.ui = { |
| 108 | 118 | ...configCopy.ui, |
| @@ -124,6 +134,10 @@ | ||
| 124 | 134 | if (sharedConfig.showChatScrollbar !== undefined) { |
| 125 | 135 | configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar; |
| 126 | 136 | } |
| 137 | + if (sharedConfig.autoAcceptEditToolDiffs !== undefined) { | |
| 138 | + configCopy.ui.autoAcceptEditToolDiffs = | |
| 139 | + sharedConfig.autoAcceptEditToolDiffs; | |
| 140 | + } | |
| 127 | 141 | |
| 128 | 142 | if (sharedConfig.allowAnonymousTelemetry !== undefined) { |
| 129 | 143 | configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; |
modified core/config/util.ts +1 −0
| @@ -77,6 +77,7 @@ | ||
| 77 | 77 | model: model.model, |
| 78 | 78 | apiKey: model.apiKey, |
| 79 | 79 | apiBase: model.apiBase, |
| 80 | + maxStopWords: model.maxStopWords, | |
| 80 | 81 | defaultCompletionOptions: model.completionOptions, |
| 81 | 82 | }; |
| 82 | 83 | if (model.systemMessage) { |
modified core/config/yaml/loadYaml.ts +25 −10
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | PackageIdentifier, |
| 10 | 10 | RegistryClient, |
| 11 | 11 | Rule, |
| 12 | + TEMPLATE_VAR_REGEX, | |
| 12 | 13 | unrollAssistant, |
| 13 | 14 | validateConfigYaml, |
| 14 | 15 | } from "@continuedev/config-yaml"; |
| @@ -40,9 +41,8 @@ | ||
| 40 | 41 | import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; |
| 41 | 42 | |
| 42 | 43 | import { getControlPlaneEnvSync } from "../../control-plane/env"; |
| 43 | -import { logger } from "../../util/logger"; | |
| 44 | 44 | import { getCleanUriPath } from "../../util/uri"; |
| 45 | -import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; | |
| 45 | +import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; | |
| 46 | 46 | import { LocalPlatformClient } from "./LocalPlatformClient"; |
| 47 | 47 | import { llmsFromModelConfig } from "./models"; |
| 48 | 48 | |
| @@ -71,8 +71,8 @@ | ||
| 71 | 71 | command: server.command, |
| 72 | 72 | args: server.args ?? [], |
| 73 | 73 | 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, | |
| 76 | 76 | }; |
| 77 | 77 | } |
| 78 | 78 | |
| @@ -96,7 +96,7 @@ | ||
| 96 | 96 | // Add local .continue blocks |
| 97 | 97 | const allLocalBlocks: PackageIdentifier[] = []; |
| 98 | 98 | for (const blockType of BLOCK_TYPES) { |
| 99 | - const localBlocks = await getAllDotContinueYamlFiles( | |
| 99 | + const localBlocks = await getAllDotContinueDefinitionFiles( | |
| 100 | 100 | ide, |
| 101 | 101 | { includeGlobal: true, includeWorkspace: true }, |
| 102 | 102 | blockType, |
| @@ -114,9 +114,9 @@ | ||
| 114 | 114 | ? dirname(getCleanUriPath(packageIdentifier.filePath)) |
| 115 | 115 | : undefined; |
| 116 | 116 | |
| 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 | + // ); | |
| 120 | 120 | |
| 121 | 121 | let config = |
| 122 | 122 | overrideConfigYaml ?? |
| @@ -241,6 +241,21 @@ | ||
| 241 | 241 | rootUrl: doc.rootUrl, |
| 242 | 242 | faviconUrl: doc.faviconUrl, |
| 243 | 243 | })); |
| 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 | + | |
| 244 | 259 | continueConfig.experimental = { |
| 245 | 260 | modelContextProtocolServers: config.mcpServers?.map( |
| 246 | 261 | convertYamlMcpToContinueMcp, |
| @@ -443,9 +458,9 @@ | ||
| 443 | 458 | transport: { |
| 444 | 459 | type: "stdio", |
| 445 | 460 | args: [], |
| 446 | - ...server, | |
| 461 | + ...(server as any), // TODO: fix the types on mcpServers in config-yaml | |
| 447 | 462 | }, |
| 448 | - timeout: server.connectionTimeout | |
| 463 | + timeout: server.connectionTimeout, | |
| 449 | 464 | })), |
| 450 | 465 | false, |
| 451 | 466 | ); |
modified core/context/mcp/MCPConnection.test.ts +6 −6
| @@ -64,10 +64,10 @@ | ||
| 64 | 64 | url: "http://test.com/events", |
| 65 | 65 | requestOptions: { |
| 66 | 66 | 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 | + }, | |
| 71 | 71 | }, |
| 72 | 72 | }; |
| 73 | 73 | |
| @@ -172,7 +172,7 @@ | ||
| 172 | 172 | expect(mockConnect).toHaveBeenCalled(); |
| 173 | 173 | }); |
| 174 | 174 | |
| 175 | - it('should handle custom connection timeout', async () => { | |
| 175 | + it("should handle custom connection timeout", async () => { | |
| 176 | 176 | const conn = new MCPConnection({ ...options, timeout: 11 }); |
| 177 | 177 | const mockConnect = jest |
| 178 | 178 | .spyOn(Client.prototype, "connect") |
| @@ -199,7 +199,7 @@ | ||
| 199 | 199 | await conn.connectClient(false, abortController.signal); |
| 200 | 200 | |
| 201 | 201 | 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"); | |
| 203 | 203 | expect(mockConnect).toHaveBeenCalled(); |
| 204 | 204 | }); |
| 205 | 205 |
modified core/context/mcp/MCPConnection.ts +104 −45
| @@ -13,22 +13,31 @@ | ||
| 13 | 13 | MCPServerStatus, |
| 14 | 14 | MCPTool, |
| 15 | 15 | } from "../.."; |
| 16 | +import { getEnvPathFromUserShell } from "../../util/shellPath"; | |
| 16 | 17 | |
| 17 | 18 | const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds |
| 18 | 19 | |
| 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 | + | |
| 19 | 31 | class MCPConnection { |
| 20 | 32 | public client: Client; |
| 21 | - private transport: Transport; | |
| 22 | - | |
| 23 | - private connectionPromise: Promise<unknown> | null = null; | |
| 24 | 33 | public abortController: AbortController; |
| 25 | - | |
| 26 | 34 | public status: MCPConnectionStatus = "not-connected"; |
| 27 | 35 | public errors: string[] = []; |
| 28 | - | |
| 29 | 36 | public prompts: MCPPrompt[] = []; |
| 30 | 37 | public tools: MCPTool[] = []; |
| 31 | 38 | public resources: MCPResource[] = []; |
| 39 | + private transport: Transport; | |
| 40 | + private connectionPromise: Promise<unknown> | null = null; | |
| 32 | 41 | |
| 33 | 42 | constructor(public options: MCPOptions) { |
| 34 | 43 | this.transport = this.constructTransport(options); |
| @@ -52,43 +61,6 @@ | ||
| 52 | 61 | await this.transport.close(); |
| 53 | 62 | } |
| 54 | 63 | |
| 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 | - | |
| 92 | 64 | getStatus(): MCPServerStatus { |
| 93 | 65 | return { |
| 94 | 66 | ...this.options, |
| @@ -232,14 +204,14 @@ | ||
| 232 | 204 | ]); |
| 233 | 205 | } catch (error) { |
| 234 | 206 | // 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`; | |
| 236 | 208 | if (error instanceof Error) { |
| 237 | 209 | const msg = error.message.toLowerCase(); |
| 238 | 210 | if (msg.includes("spawn") && msg.includes("enoent")) { |
| 239 | 211 | 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.`; | |
| 241 | 213 | } else { |
| 242 | - errorMessage += ": " + error.message; | |
| 214 | + errorMessage += "Error: " + error.message; | |
| 243 | 215 | } |
| 244 | 216 | } |
| 245 | 217 | |
| @@ -254,6 +226,93 @@ | ||
| 254 | 226 | |
| 255 | 227 | await this.connectionPromise; |
| 256 | 228 | } |
| 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 | + } | |
| 257 | 316 | } |
| 258 | 317 | |
| 259 | 318 | 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 @@ | ||
| 1 | 1 | import { v4 as uuidv4 } from "uuid"; |
| 2 | 2 | import { IdeSettings } from "../.."; |
| 3 | +import { isHubEnv } from "../AuthTypes"; | |
| 3 | 4 | import { getControlPlaneEnv } from "../env"; |
| 4 | 5 | |
| 5 | 6 | export async function getAuthUrlForTokenPage( |
| @@ -7,6 +8,11 @@ | ||
| 7 | 8 | useOnboarding: boolean, |
| 8 | 9 | ): Promise<string> { |
| 9 | 10 | const env = await getControlPlaneEnv(ideSettingsPromise); |
| 11 | + | |
| 12 | + if (!isHubEnv(env)) { | |
| 13 | + throw new Error("Sign in disabled"); | |
| 14 | + } | |
| 15 | + | |
| 10 | 16 | const url = new URL("https://api.workos.com/user_management/authorize"); |
| 11 | 17 | const params = { |
| 12 | 18 | response_type: "code", |
modified core/control-plane/client.ts +17 −52
| @@ -12,16 +12,9 @@ | ||
| 12 | 12 | import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; |
| 13 | 13 | import { IdeSettings, ModelDescription } from "../index.js"; |
| 14 | 14 | |
| 15 | +import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js"; | |
| 15 | 16 | import { getControlPlaneEnv } from "./env.js"; |
| 16 | 17 | |
| 17 | -export interface ControlPlaneSessionInfo { | |
| 18 | - accessToken: string; | |
| 19 | - account: { | |
| 20 | - label: string; | |
| 21 | - id: string; | |
| 22 | - }; | |
| 23 | -} | |
| 24 | - | |
| 25 | 18 | export interface ControlPlaneWorkspace { |
| 26 | 19 | id: string; |
| 27 | 20 | name: string; |
| @@ -45,8 +38,7 @@ | ||
| 45 | 38 | fqsns: FQSN[], |
| 46 | 39 | orgScopeId: string | null, |
| 47 | 40 | ): Promise<(SecretResult | undefined)[]> { |
| 48 | - const userId = await this.userId; | |
| 49 | - if (!userId) { | |
| 41 | + if (!(await this.isSignedIn())) { | |
| 50 | 42 | return fqsns.map((fqsn) => ({ |
| 51 | 43 | found: false, |
| 52 | 44 | fqsn, |
| @@ -64,19 +56,24 @@ | ||
| 64 | 56 | return (await resp.json()) as any; |
| 65 | 57 | } |
| 66 | 58 | |
| 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; | |
| 71 | 62 | } |
| 72 | 63 | |
| 73 | 64 | async getAccessToken(): Promise<string | undefined> { |
| 74 | - return (await this.sessionInfoPromise)?.accessToken; | |
| 65 | + const sessionInfo = await this.sessionInfoPromise; | |
| 66 | + return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined; | |
| 75 | 67 | } |
| 76 | 68 | |
| 77 | 69 | 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) { | |
| 80 | 77 | throw new Error("No access token"); |
| 81 | 78 | } |
| 82 | 79 | |
| @@ -99,22 +96,6 @@ | ||
| 99 | 96 | return resp; |
| 100 | 97 | } |
| 101 | 98 | |
| 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 | - | |
| 118 | 99 | public async listAssistants(organizationId: string | null): Promise< |
| 119 | 100 | { |
| 120 | 101 | configResult: ConfigResult<AssistantUnrolled>; |
| @@ -124,8 +105,7 @@ | ||
| 124 | 105 | rawYaml: string; |
| 125 | 106 | }[] |
| 126 | 107 | > { |
| 127 | - const userId = await this.userId; | |
| 128 | - if (!userId) { | |
| 108 | + if (!(await this.isSignedIn())) { | |
| 129 | 109 | return []; |
| 130 | 110 | } |
| 131 | 111 | |
| @@ -144,9 +124,7 @@ | ||
| 144 | 124 | } |
| 145 | 125 | |
| 146 | 126 | public async listOrganizations(): Promise<Array<OrganizationDescription>> { |
| 147 | - const userId = await this.userId; | |
| 148 | - | |
| 149 | - if (!userId) { | |
| 127 | + if (!(await this.isSignedIn())) { | |
| 150 | 128 | return []; |
| 151 | 129 | } |
| 152 | 130 | |
| @@ -164,8 +142,7 @@ | ||
| 164 | 142 | public async listAssistantFullSlugs( |
| 165 | 143 | organizationId: string | null, |
| 166 | 144 | ): Promise<FullSlug[] | null> { |
| 167 | - const userId = await this.userId; | |
| 168 | - if (!userId) { | |
| 145 | + if (!(await this.isSignedIn())) { | |
| 169 | 146 | return null; |
| 170 | 147 | } |
| 171 | 148 | |
| @@ -183,16 +160,4 @@ | ||
| 183 | 160 | return null; |
| 184 | 161 | } |
| 185 | 162 | } |
| 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 | - } | |
| 198 | 163 | } |
modified core/control-plane/env.ts +18 −15
| @@ -4,27 +4,18 @@ | ||
| 4 | 4 | getLocalEnvironmentDotFilePath, |
| 5 | 5 | getStagingEnvironmentDotFilePath, |
| 6 | 6 | } 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"; | |
| 15 | 9 | |
| 16 | 10 | export const EXTENSION_NAME = "continue"; |
| 17 | 11 | |
| 18 | 12 | const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; |
| 19 | 13 | const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; |
| 20 | 14 | |
| 21 | -const WORKOS_ENV_ID_PRODUCTION = "continue"; | |
| 22 | -const WORKOS_ENV_ID_STAGING = "continue-staging"; | |
| 23 | - | |
| 24 | 15 | const PRODUCTION_HUB_ENV: ControlPlaneEnv = { |
| 25 | 16 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", |
| 26 | 17 | CONTROL_PLANE_URL: "https://api.continue.dev/", |
| 27 | - AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, | |
| 18 | + AUTH_TYPE: AuthType.WorkOsProd, | |
| 28 | 19 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, |
| 29 | 20 | APP_URL: "https://hub.continue.dev/", |
| 30 | 21 | }; |
| @@ -32,7 +23,7 @@ | ||
| 32 | 23 | const STAGING_ENV: ControlPlaneEnv = { |
| 33 | 24 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/", |
| 34 | 25 | CONTROL_PLANE_URL: "https://api.continue-stage.tools/", |
| 35 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 26 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 36 | 27 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 37 | 28 | APP_URL: "https://hub.continue-stage.tools/", |
| 38 | 29 | }; |
| @@ -40,7 +31,7 @@ | ||
| 40 | 31 | const TEST_ENV: ControlPlaneEnv = { |
| 41 | 32 | DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/", |
| 42 | 33 | CONTROL_PLANE_URL: "https://api-test.continue.dev/", |
| 43 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 34 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 44 | 35 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 45 | 36 | APP_URL: "https://app-test.continue.dev/", |
| 46 | 37 | }; |
| @@ -48,7 +39,7 @@ | ||
| 48 | 39 | const LOCAL_ENV: ControlPlaneEnv = { |
| 49 | 40 | DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/", |
| 50 | 41 | CONTROL_PLANE_URL: "http://localhost:3001/", |
| 51 | - AUTH_TYPE: WORKOS_ENV_ID_STAGING, | |
| 42 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 52 | 43 | WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, |
| 53 | 44 | APP_URL: "http://localhost:3000/", |
| 54 | 45 | }; |
| @@ -67,6 +58,18 @@ | ||
| 67 | 58 | export function getControlPlaneEnvSync( |
| 68 | 59 | ideTestEnvironment: IdeSettings["continueTestEnvironment"], |
| 69 | 60 | ): 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 | + | |
| 70 | 73 | // Note .local overrides .staging |
| 71 | 74 | if (fs.existsSync(getLocalEnvironmentDotFilePath())) { |
| 72 | 75 | 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 @@ | ||
| 26 | 26 | apiKey: z.string().optional(), |
| 27 | 27 | apiBase: z.string().optional(), |
| 28 | 28 | contextLength: z.number().optional(), |
| 29 | + maxStopWords: z.number().optional(), | |
| 29 | 30 | template: z |
| 30 | 31 | .enum([ |
| 31 | 32 | "llama2", |
modified core/core.ts +65 −70
| @@ -35,7 +35,6 @@ | ||
| 35 | 35 | |
| 36 | 36 | import { |
| 37 | 37 | ContextItemWithId, |
| 38 | - DiffLine, | |
| 39 | 38 | IdeSettings, |
| 40 | 39 | ModelDescription, |
| 41 | 40 | RangeInFile, |
| @@ -62,61 +61,7 @@ | ||
| 62 | 61 | import { llmStreamChat } from "./llm/streamChat"; |
| 63 | 62 | import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; |
| 64 | 63 | 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"; | |
| 120 | 65 | |
| 121 | 66 | export class Core { |
| 122 | 67 | configHandler: ConfigHandler; |
| @@ -132,7 +77,18 @@ | ||
| 132 | 77 | this.globalContext.get("indexingPaused") === true, |
| 133 | 78 | ); |
| 134 | 79 | |
| 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 | + } | |
| 136 | 92 | |
| 137 | 93 | invoke<T extends keyof ToCoreProtocol>( |
| 138 | 94 | messageType: T, |
| @@ -301,7 +257,7 @@ | ||
| 301 | 257 | }); |
| 302 | 258 | |
| 303 | 259 | on("abort", (msg) => { |
| 304 | - this.abortedMessageIds.add(msg.messageId); | |
| 260 | + this.abortById(msg.data ?? msg.messageId); | |
| 305 | 261 | }); |
| 306 | 262 | |
| 307 | 263 | on("ping", (msg) => { |
| @@ -470,27 +426,28 @@ | ||
| 470 | 426 | } |
| 471 | 427 | }); |
| 472 | 428 | |
| 473 | - on("llm/streamChat", (msg) => | |
| 474 | - llmStreamChat( | |
| 429 | + on("llm/streamChat", (msg) => { | |
| 430 | + const abortController = this.addMessageAbortController(msg.messageId); | |
| 431 | + return llmStreamChat( | |
| 475 | 432 | this.configHandler, |
| 476 | - this.abortedMessageIds, | |
| 433 | + abortController, | |
| 477 | 434 | msg, |
| 478 | 435 | this.ide, |
| 479 | 436 | this.messenger, |
| 480 | - ), | |
| 481 | - ); | |
| 437 | + ); | |
| 438 | + }); | |
| 482 | 439 | |
| 483 | 440 | 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; | |
| 487 | 443 | if (!model) { |
| 488 | 444 | throw new Error("No chat model selected"); |
| 489 | 445 | } |
| 446 | + const abortController = this.addMessageAbortController(msg.messageId); | |
| 490 | 447 | |
| 491 | 448 | const completion = await model.complete( |
| 492 | 449 | msg.data.prompt, |
| 493 | - new AbortController().signal, | |
| 450 | + abortController.signal, | |
| 494 | 451 | msg.data.completionOptions, |
| 495 | 452 | ); |
| 496 | 453 | return completion; |
| @@ -532,9 +489,47 @@ | ||
| 532 | 489 | this.completionProvider.cancel(); |
| 533 | 490 | }); |
| 534 | 491 | |
| 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 | + }); | |
| 538 | 533 | |
| 539 | 534 | on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); |
| 540 | 535 |
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 @@ | ||
| 12 | 12 | import { fileURLToPath } from "url"; |
| 13 | 13 | import { AnyZodObject } from "zod"; |
| 14 | 14 | import { Core } from "../core.js"; |
| 15 | -import { IdeInfo, IdeSettings } from "../index.js"; | |
| 15 | +import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js"; | |
| 16 | 16 | import { getDevDataFilePath } from "../util/paths.js"; |
| 17 | 17 | import { joinPathsToUri } from "../util/uri.js"; |
| 18 | 18 | |
| @@ -68,8 +68,7 @@ | ||
| 68 | 68 | return newBody; |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | - async logDevData(event: DevDataLogEvent) { | |
| 72 | - // Local logs (always on for all levels) | |
| 71 | + async logLocalData(event: DevDataLogEvent) { | |
| 73 | 72 | try { |
| 74 | 73 | const filepath: string = getDevDataFilePath( |
| 75 | 74 | event.name, |
| @@ -100,126 +99,144 @@ | ||
| 100 | 99 | } catch (error) { |
| 101 | 100 | console.error("Error logging local dev data:", error); |
| 102 | 101 | } |
| 102 | + } | |
| 103 | + | |
| 104 | + async logDevData(event: DevDataLogEvent) { | |
| 105 | + // Local logs (always on for all levels) | |
| 106 | + await this.logLocalData(event); | |
| 103 | 107 | |
| 104 | 108 | // Remote logs |
| 105 | 109 | const config = (await this.core?.configHandler.loadConfig())?.config; |
| 106 | 110 | if (config?.data?.length) { |
| 107 | 111 | 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, | |
| 145 | 211 | 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}`, | |
| 223 | 240 | ); |
| 224 | 241 | } |
| 225 | 242 | } |
modified core/edit/recursiveStream.ts +5 −2
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | export async function* recursiveStream( |
| 18 | 18 | llm: ILLM, |
| 19 | + abortController: AbortController, | |
| 19 | 20 | prompt: ChatMessage[] | string, |
| 20 | 21 | prediction: Prediction | undefined, |
| 21 | 22 | currentBuffer = "", |
| @@ -28,7 +29,7 @@ | ||
| 28 | 29 | // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries |
| 29 | 30 | |
| 30 | 31 | if (typeof prompt === "string") { |
| 31 | - const generator = llm.streamComplete(prompt, new AbortController().signal, { | |
| 32 | + const generator = llm.streamComplete(prompt, abortController.signal, { | |
| 32 | 33 | raw: true, |
| 33 | 34 | prediction: undefined, |
| 34 | 35 | reasoning: false, |
| @@ -50,6 +51,7 @@ | ||
| 50 | 51 | // // TODO - Prediction capabilities lost because of partial input |
| 51 | 52 | // yield* recursiveStream( |
| 52 | 53 | // llm, |
| 54 | + // abortController, | |
| 53 | 55 | // continuationPrompt, |
| 54 | 56 | // undefined, |
| 55 | 57 | // buffer, |
| @@ -60,7 +62,7 @@ | ||
| 60 | 62 | } |
| 61 | 63 | } |
| 62 | 64 | } else { |
| 63 | - const generator = llm.streamChat(prompt, new AbortController().signal, { | |
| 65 | + const generator = llm.streamChat(prompt, abortController.signal, { | |
| 64 | 66 | prediction, |
| 65 | 67 | reasoning: false, |
| 66 | 68 | }); |
| @@ -90,6 +92,7 @@ | ||
| 90 | 92 | // await generator.return(DUD_PROMPT_LOG); |
| 91 | 93 | // yield* recursiveStream( |
| 92 | 94 | // llm, |
| 95 | + // abortController, | |
| 93 | 96 | // continuationPrompt, |
| 94 | 97 | // undefined, |
| 95 | 98 | // buffer, |
modified core/edit/streamDiffLines.ts +7 −1
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | import { streamLines } from "../diff/util"; |
| 21 | 21 | import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; |
| 22 | 22 | import { gptEditPrompt } from "../llm/templates/edit"; |
| 23 | +import { StreamAbortManager } from "../util/abortManager"; | |
| 23 | 24 | import { findLast } from "../util/findLast"; |
| 24 | 25 | import { Telemetry } from "../util/posthog"; |
| 25 | 26 | import { recursiveStream } from "./recursiveStream"; |
| @@ -63,6 +64,7 @@ | ||
| 63 | 64 | highlighted, |
| 64 | 65 | suffix, |
| 65 | 66 | llm, |
| 67 | + abortControllerId, | |
| 66 | 68 | input, |
| 67 | 69 | language, |
| 68 | 70 | onlyOneInsertion, |
| @@ -73,12 +75,15 @@ | ||
| 73 | 75 | highlighted: string; |
| 74 | 76 | suffix: string; |
| 75 | 77 | llm: ILLM; |
| 78 | + abortControllerId: string; | |
| 76 | 79 | input: string; |
| 77 | 80 | language: string | undefined; |
| 78 | 81 | onlyOneInsertion: boolean; |
| 79 | 82 | overridePrompt: ChatMessage[] | undefined; |
| 80 | 83 | rulesToInclude: RuleWithSource[] | undefined; |
| 81 | 84 | }): AsyncGenerator<DiffLine> { |
| 85 | + const abortManager = StreamAbortManager.getInstance(); | |
| 86 | + const abortController = abortManager.get(abortControllerId); | |
| 82 | 87 | void Telemetry.capture( |
| 83 | 88 | "inlineEdit", |
| 84 | 89 | { |
| @@ -122,6 +127,7 @@ | ||
| 122 | 127 | (msg) => msg.role === "user" || msg.role === "tool", |
| 123 | 128 | ) as UserChatMessage | ToolResultChatMessage | undefined), |
| 124 | 129 | baseSystemMessage: undefined, |
| 130 | + contextItems: [], | |
| 125 | 131 | }) |
| 126 | 132 | : undefined; |
| 127 | 133 | |
| @@ -157,7 +163,7 @@ | ||
| 157 | 163 | content: highlighted, |
| 158 | 164 | }; |
| 159 | 165 | |
| 160 | - const completion = recursiveStream(llm, prompt, prediction); | |
| 166 | + const completion = recursiveStream(llm, abortController, prompt, prediction); | |
| 161 | 167 | |
| 162 | 168 | let lines = streamLines(completion); |
| 163 | 169 |
modified core/index.d.ts +46 −13
| @@ -197,15 +197,14 @@ | ||
| 197 | 197 | description?: string; |
| 198 | 198 | renderInlineAs?: string; |
| 199 | 199 | type?: ContextProviderType; |
| 200 | + loadSubmenuItems?: ( | |
| 201 | + args: LoadSubmenuItemsArgs, | |
| 202 | + ) => Promise<ContextSubmenuItem[]>; | |
| 200 | 203 | |
| 201 | 204 | getContextItems( |
| 202 | 205 | query: string, |
| 203 | 206 | extras: ContextProviderExtras, |
| 204 | 207 | ): Promise<ContextItem[]>; |
| 205 | - | |
| 206 | - loadSubmenuItems?: ( | |
| 207 | - args: LoadSubmenuItemsArgs, | |
| 208 | - ) => Promise<ContextSubmenuItem[]>; | |
| 209 | 208 | } |
| 210 | 209 | |
| 211 | 210 | export interface ContextSubmenuItem { |
| @@ -459,6 +458,7 @@ | ||
| 459 | 458 | toolCallState?: ToolCallState; |
| 460 | 459 | isGatheringContext?: boolean; |
| 461 | 460 | reasoning?: Reasoning; |
| 461 | + appliedRules?: RuleWithSource[]; | |
| 462 | 462 | } |
| 463 | 463 | |
| 464 | 464 | export interface LLMFullCompletionOptions extends BaseCompletionOptions { |
| @@ -842,6 +842,7 @@ | ||
| 842 | 842 | description: string; |
| 843 | 843 | prompt?: string; |
| 844 | 844 | params?: { [key: string]: any }; |
| 845 | + promptFile?: string; | |
| 845 | 846 | run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; |
| 846 | 847 | } |
| 847 | 848 | |
| @@ -1023,6 +1024,7 @@ | ||
| 1023 | 1024 | toolChoice?: ToolChoice; |
| 1024 | 1025 | reasoning?: boolean; |
| 1025 | 1026 | reasoningBudgetTokens?: number; |
| 1027 | + promptCaching?: boolean; | |
| 1026 | 1028 | } |
| 1027 | 1029 | |
| 1028 | 1030 | export interface ModelCapability { |
| @@ -1090,6 +1092,7 @@ | ||
| 1090 | 1092 | disable: boolean; |
| 1091 | 1093 | maxPromptTokens: number; |
| 1092 | 1094 | debounceDelay: number; |
| 1095 | + modelTimeout: number; | |
| 1093 | 1096 | maxSuffixPercentage: number; |
| 1094 | 1097 | prefixPercentage: number; |
| 1095 | 1098 | transform?: boolean; |
| @@ -1165,6 +1168,7 @@ | ||
| 1165 | 1168 | description?: string; |
| 1166 | 1169 | mimeType?: string; |
| 1167 | 1170 | } |
| 1171 | + | |
| 1168 | 1172 | export interface MCPTool { |
| 1169 | 1173 | name: string; |
| 1170 | 1174 | description?: string; |
| @@ -1190,6 +1194,7 @@ | ||
| 1190 | 1194 | showChatScrollbar?: boolean; |
| 1191 | 1195 | codeWrap?: boolean; |
| 1192 | 1196 | showSessionTabs?: boolean; |
| 1197 | + autoAcceptEditToolDiffs?: boolean; | |
| 1193 | 1198 | } |
| 1194 | 1199 | |
| 1195 | 1200 | export interface ContextMenuConfig { |
| @@ -1227,6 +1232,32 @@ | ||
| 1227 | 1232 | toolCallId?: string; |
| 1228 | 1233 | } |
| 1229 | 1234 | |
| 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 | + | |
| 1230 | 1261 | export interface RangeInFileWithContents { |
| 1231 | 1262 | filepath: string; |
| 1232 | 1263 | range: { |
| @@ -1236,7 +1267,7 @@ | ||
| 1236 | 1267 | contents: string; |
| 1237 | 1268 | } |
| 1238 | 1269 | |
| 1239 | -export type CodeToEdit = RangeInFileWithContents | FileWithContents; | |
| 1270 | +export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; | |
| 1240 | 1271 | |
| 1241 | 1272 | /** |
| 1242 | 1273 | * Represents the configuration for a quick action in the Code Lens. |
| @@ -1495,17 +1526,19 @@ | ||
| 1495 | 1526 | waitForCompletion?: boolean; |
| 1496 | 1527 | } |
| 1497 | 1528 | |
| 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 | + | |
| 1498 | 1538 | export interface RuleWithSource { |
| 1499 | 1539 | name?: string; |
| 1500 | 1540 | 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; | |
| 1509 | 1542 | globs?: string | string[]; |
| 1510 | 1543 | rule: string; |
| 1511 | 1544 | description?: string; |
modified core/indexing/CodeSnippetsIndex.ts +2 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | getQueryForFile, |
| 8 | 8 | } from "../util/treeSitter"; |
| 9 | 9 | |
| 10 | -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; | |
| 10 | +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; | |
| 11 | 11 | import { |
| 12 | 12 | IndexResultType, |
| 13 | 13 | MarkCompleteCallback, |
| @@ -29,6 +29,7 @@ | ||
| 29 | 29 | getLastNUriRelativePathParts, |
| 30 | 30 | getUriPathBasename, |
| 31 | 31 | } from "../util/uri"; |
| 32 | +import { tagToString } from "./utils"; | |
| 32 | 33 | |
| 33 | 34 | type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; |
| 34 | 35 |
modified core/indexing/FullTextSearchCodebaseIndex.ts +7 −3
| @@ -3,13 +3,14 @@ | ||
| 3 | 3 | import { getUriPathBasename } from "../util/uri"; |
| 4 | 4 | |
| 5 | 5 | import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; |
| 6 | -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; | |
| 6 | +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; | |
| 7 | 7 | import { |
| 8 | 8 | IndexResultType, |
| 9 | 9 | MarkCompleteCallback, |
| 10 | 10 | RefreshIndexResults, |
| 11 | 11 | type CodebaseIndex, |
| 12 | 12 | } from "./types"; |
| 13 | +import { tagToString } from "./utils"; | |
| 13 | 14 | |
| 14 | 15 | export interface RetrieveConfig { |
| 15 | 16 | tags: BranchAndDir[]; |
| @@ -97,11 +98,14 @@ | ||
| 97 | 98 | |
| 98 | 99 | // Delete |
| 99 | 100 | for (const item of results.del) { |
| 100 | - await db.run(` | |
| 101 | + await db.run( | |
| 102 | + ` | |
| 101 | 103 | DELETE FROM fts WHERE rowid IN ( |
| 102 | 104 | SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ? |
| 103 | 105 | ) |
| 104 | - `,[item.path, item.cacheKey]); | |
| 106 | + `, | |
| 107 | + [item.path, item.cacheKey], | |
| 108 | + ); | |
| 105 | 109 | await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ |
| 106 | 110 | item.path, |
| 107 | 111 | item.cacheKey, |
modified core/indexing/LanceDbIndex.ts +2 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | import { basicChunker } from "./chunk/basic.js"; |
| 16 | 16 | import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; |
| 17 | -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; | |
| 17 | +import { DatabaseConnection, SqliteDb } from "./refreshIndex.js"; | |
| 18 | 18 | import { |
| 19 | 19 | CodebaseIndex, |
| 20 | 20 | IndexResultType, |
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | } from "./types"; |
| 25 | 25 | |
| 26 | 26 | import type * as LanceType from "vectordb"; |
| 27 | +import { tagToString } from "./utils"; | |
| 27 | 28 | |
| 28 | 29 | interface LanceDbRow { |
| 29 | 30 | uuid: string; |
modified core/indexing/chunk/ChunkCodebaseIndex.ts +3 −2
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | import { IContinueServerClient } from "../../continueServer/interface.js"; |
| 6 | 6 | import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; |
| 7 | -import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js"; | |
| 7 | +import { DatabaseConnection, SqliteDb } from "../refreshIndex.js"; | |
| 8 | 8 | import { |
| 9 | 9 | IndexResultType, |
| 10 | 10 | MarkCompleteCallback, |
| @@ -13,8 +13,9 @@ | ||
| 13 | 13 | type CodebaseIndex, |
| 14 | 14 | } from "../types.js"; |
| 15 | 15 | |
| 16 | -import { chunkDocument, shouldChunk } from "./chunk.js"; | |
| 17 | 16 | import { getUriPathBasename } from "../../util/uri.js"; |
| 17 | +import { tagToString } from "../utils.js"; | |
| 18 | +import { chunkDocument, shouldChunk } from "./chunk.js"; | |
| 18 | 19 | |
| 19 | 20 | export class ChunkCodebaseIndex implements CodebaseIndex { |
| 20 | 21 | relativeExpectedTime: number = 1; |
modified core/indexing/refreshIndex.ts +0 −4
| @@ -18,10 +18,6 @@ | ||
| 18 | 18 | |
| 19 | 19 | export type DatabaseConnection = Database<sqlite3.Database>; |
| 20 | 20 | |
| 21 | -export function tagToString(tag: IndexTag): string { | |
| 22 | - return `${tag.directory}::${tag.branch}::${tag.artifactId}`; | |
| 23 | -} | |
| 24 | - | |
| 25 | 21 | export class SqliteDb { |
| 26 | 22 | static db: DatabaseConnection | null = null; |
| 27 | 23 |
modified core/indexing/test/indexing.ts +1 −1
| @@ -3,11 +3,11 @@ | ||
| 3 | 3 | import { IndexTag } from "../.."; |
| 4 | 4 | import { IContinueServerClient } from "../../continueServer/interface"; |
| 5 | 5 | import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex"; |
| 6 | -import { tagToString } from "../refreshIndex"; | |
| 7 | 6 | import { CodebaseIndex, RefreshIndexResults } from "../types"; |
| 8 | 7 | |
| 9 | 8 | import { testIde } from "../../test/fixtures"; |
| 10 | 9 | import { addToTestDir, TEST_DIR } from "../../test/testDir"; |
| 10 | +import { tagToString } from "../utils"; | |
| 11 | 11 | |
| 12 | 12 | export const mockFilename = "test.py"; |
| 13 | 13 | 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 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ChatHistoryItem, |
| 3 | 3 | ChatMessage, |
| 4 | + ContextItemWithId, | |
| 4 | 5 | RuleWithSource, |
| 5 | 6 | TextMessagePart, |
| 6 | 7 | ToolResultChatMessage, |
| @@ -58,7 +59,7 @@ | ||
| 58 | 59 | at the beginning, middle, or end of files using these "lazy" comments. Only |
| 59 | 60 | provide the complete file when explicitly requested. Include a concise explanation |
| 60 | 61 | of changes unless the user specifically asks for code only. |
| 61 | -` | |
| 62 | +`; | |
| 62 | 63 | |
| 63 | 64 | export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ |
| 64 | 65 | <important_rules> |
| @@ -77,6 +78,31 @@ | ||
| 77 | 78 | ${EDIT_MESSAGE} |
| 78 | 79 | </important_rules>`; |
| 79 | 80 | |
| 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 | + | |
| 80 | 106 | export function constructMessages( |
| 81 | 107 | messageMode: string, |
| 82 | 108 | history: ChatHistoryItem[], |
| @@ -92,7 +118,8 @@ | ||
| 92 | 118 | const historyItem = filteredHistory[i]; |
| 93 | 119 | |
| 94 | 120 | if (messageMode === "chat") { |
| 95 | - const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage; | |
| 121 | + const toolMessage: ToolResultChatMessage = | |
| 122 | + historyItem.message as ToolResultChatMessage; | |
| 96 | 123 | if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { |
| 97 | 124 | // remove all tool calls from the history |
| 98 | 125 | continue; |
| @@ -127,10 +154,16 @@ | ||
| 127 | 154 | | ToolResultChatMessage |
| 128 | 155 | | undefined; |
| 129 | 156 | |
| 157 | + // Get context items for the last user message | |
| 158 | + const lastUserContextItems = getUserContextItems( | |
| 159 | + lastUserMsg, | |
| 160 | + filteredHistory, | |
| 161 | + ); | |
| 130 | 162 | const systemMessage = getSystemMessageWithRules({ |
| 131 | 163 | baseSystemMessage: baseChatOrAgentSystemMessage, |
| 132 | 164 | rules, |
| 133 | 165 | userMessage: lastUserMsg, |
| 166 | + contextItems: lastUserContextItems, | |
| 134 | 167 | }); |
| 135 | 168 | |
| 136 | 169 | if (systemMessage.trim()) { |
modified core/llm/index.ts +3 −0
| @@ -382,6 +382,9 @@ | ||
| 382 | 382 | |
| 383 | 383 | // Error mapping to be more helpful |
| 384 | 384 | if (!resp.ok) { |
| 385 | + if (resp.status === 499) { | |
| 386 | + return resp; // client side cancellation | |
| 387 | + } | |
| 385 | 388 | let text = await resp.text(); |
| 386 | 389 | if (resp.status === 404 && !resp.url.includes("/v1")) { |
| 387 | 390 | const error = JSON.parse(text)?.error?.replace(/"/g, "'"); |
modified core/llm/llm.test.ts +25 −10
| @@ -22,6 +22,20 @@ | ||
| 22 | 22 | // maxTokens: 5, |
| 23 | 23 | }; |
| 24 | 24 | |
| 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 | + | |
| 25 | 39 | function testLLM( |
| 26 | 40 | llm: BaseLLM, |
| 27 | 41 | { |
| @@ -47,7 +61,7 @@ | ||
| 47 | 61 | describe(llm.providerName + "/" + llm.model, () => { |
| 48 | 62 | test( |
| 49 | 63 | "Stream Chat works", |
| 50 | - async () => { | |
| 64 | + retryOnce(async () => { | |
| 51 | 65 | let total = ""; |
| 52 | 66 | for await (const chunk of llm.streamChat( |
| 53 | 67 | [{ role: "user", content: "Hi" }], |
| @@ -58,13 +72,13 @@ | ||
| 58 | 72 | |
| 59 | 73 | expect(total.length).toBeGreaterThan(0); |
| 60 | 74 | return; |
| 61 | - }, | |
| 75 | + }), | |
| 62 | 76 | timeout, |
| 63 | 77 | ); |
| 64 | 78 | |
| 65 | 79 | test( |
| 66 | 80 | "Stream Complete works", |
| 67 | - async () => { | |
| 81 | + retryOnce(async () => { | |
| 68 | 82 | let total = ""; |
| 69 | 83 | for await (const chunk of llm.streamComplete( |
| 70 | 84 | "Hi", |
| @@ -75,13 +89,13 @@ | ||
| 75 | 89 | |
| 76 | 90 | expect(total.length).toBeGreaterThan(0); |
| 77 | 91 | return; |
| 78 | - }, | |
| 92 | + }), | |
| 79 | 93 | timeout, |
| 80 | 94 | ); |
| 81 | 95 | |
| 82 | 96 | test( |
| 83 | 97 | "Complete works", |
| 84 | - async () => { | |
| 98 | + retryOnce(async () => { | |
| 85 | 99 | const completion = await llm.complete( |
| 86 | 100 | "Hi", |
| 87 | 101 | new AbortController().signal, |
| @@ -89,14 +103,14 @@ | ||
| 89 | 103 | |
| 90 | 104 | expect(completion.length).toBeGreaterThan(0); |
| 91 | 105 | return; |
| 92 | - }, | |
| 106 | + }), | |
| 93 | 107 | timeout, |
| 94 | 108 | ); |
| 95 | 109 | |
| 96 | 110 | if (testFim) { |
| 97 | 111 | test( |
| 98 | 112 | "FIM works", |
| 99 | - async () => { | |
| 113 | + retryOnce(async () => { | |
| 100 | 114 | let total = ""; |
| 101 | 115 | for await (const chunk of llm.streamFim( |
| 102 | 116 | "Hi", |
| @@ -108,7 +122,7 @@ | ||
| 108 | 122 | |
| 109 | 123 | expect(total.length).toBeGreaterThan(0); |
| 110 | 124 | return; |
| 111 | - }, | |
| 125 | + }), | |
| 112 | 126 | timeout, |
| 113 | 127 | ); |
| 114 | 128 | } |
| @@ -116,7 +130,7 @@ | ||
| 116 | 130 | if (testToolCall) { |
| 117 | 131 | test( |
| 118 | 132 | "Tool Call works", |
| 119 | - async () => { | |
| 133 | + retryOnce(async () => { | |
| 120 | 134 | let args = ""; |
| 121 | 135 | let isFirstChunk = true; |
| 122 | 136 | for await (const chunk of llm.streamChat( |
| @@ -175,7 +189,7 @@ | ||
| 175 | 189 | |
| 176 | 190 | const parsedArgs = JSON.parse(args); |
| 177 | 191 | expect(parsedArgs.name).toBe("Nate"); |
| 178 | - }, | |
| 192 | + }), | |
| 179 | 193 | timeout, |
| 180 | 194 | ); |
| 181 | 195 | } |
| @@ -230,6 +244,7 @@ | ||
| 230 | 244 | testFim: true, |
| 231 | 245 | skip: false, |
| 232 | 246 | testToolCall: true, |
| 247 | + timeout: 60000, | |
| 233 | 248 | }, |
| 234 | 249 | ); |
| 235 | 250 | testLLM( |
modified core/llm/llms/Anthropic.ts +5 −1
| @@ -1,7 +1,7 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 3 | 4 | import { BaseLLM } from "../index.js"; |
| 4 | -import { streamSse } from "../stream.js"; | |
| 5 | 5 | |
| 6 | 6 | class Anthropic extends BaseLLM { |
| 7 | 7 | static providerName = "anthropic"; |
| @@ -213,6 +213,10 @@ | ||
| 213 | 213 | signal, |
| 214 | 214 | }); |
| 215 | 215 | |
| 216 | + if (response.status === 499) { | |
| 217 | + return; // Aborted by user | |
| 218 | + } | |
| 219 | + | |
| 216 | 220 | if (!response.ok) { |
| 217 | 221 | const json = await response.json(); |
| 218 | 222 | if (json.type === "error") { |
modified core/llm/llms/Asksage.ts +4 −8
| @@ -134,10 +134,8 @@ | ||
| 134 | 134 | body: JSON.stringify(args), |
| 135 | 135 | }); |
| 136 | 136 | |
| 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 | |
| 141 | 139 | } |
| 142 | 140 | |
| 143 | 141 | const data = await response.json(); |
| @@ -167,10 +165,8 @@ | ||
| 167 | 165 | signal, |
| 168 | 166 | }); |
| 169 | 167 | |
| 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 | |
| 174 | 170 | } |
| 175 | 171 | |
| 176 | 172 | const data = await response.json(); |
modified core/llm/llms/Bedrock.ts +26 −18
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | ConverseStreamCommandOutput, |
| 6 | 6 | InvokeModelCommand, |
| 7 | 7 | Message, |
| 8 | + ToolConfiguration, | |
| 8 | 9 | } from "@aws-sdk/client-bedrock-runtime"; |
| 9 | 10 | import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; |
| 10 | 11 | |
| @@ -291,9 +292,10 @@ | ||
| 291 | 292 | const convertedMessages = this._convertMessages(messages); |
| 292 | 293 | |
| 293 | 294 | const shouldCacheSystemMessage = |
| 294 | - !!systemMessage && this.cacheBehavior?.cacheSystemMessage; | |
| 295 | + !!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching; | |
| 295 | 296 | const enablePromptCaching = |
| 296 | - shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; | |
| 297 | + shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching; | |
| 298 | + const shouldCacheToolsConfig = this.completionOptions.promptCaching; | |
| 297 | 299 | |
| 298 | 300 | // Add header for prompt caching |
| 299 | 301 | if (enablePromptCaching) { |
| @@ -304,29 +306,35 @@ | ||
| 304 | 306 | } |
| 305 | 307 | |
| 306 | 308 | 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 | + | |
| 308 | 329 | return { |
| 309 | 330 | modelId: options.model, |
| 310 | - messages: convertedMessages, | |
| 311 | 331 | system: systemMessage |
| 312 | 332 | ? shouldCacheSystemMessage |
| 313 | 333 | ? [{ text: systemMessage }, { cachePoint: { type: "default" } }] |
| 314 | 334 | : [{ text: systemMessage }] |
| 315 | 335 | : 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, | |
| 330 | 338 | inferenceConfig: { |
| 331 | 339 | maxTokens: options.maxTokens, |
| 332 | 340 | temperature: options.temperature, |
modified core/llm/llms/Cloudflare.ts +1 −1
| @@ -1,7 +1,7 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { ChatMessage, CompletionOptions } from "../../index.js"; |
| 2 | 3 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 3 | 4 | import { BaseLLM } from "../index.js"; |
| 4 | -import { streamSse } from "../stream.js"; | |
| 5 | 5 | |
| 6 | 6 | export default class Cloudflare extends BaseLLM { |
| 7 | 7 | static providerName = "cloudflare"; |
modified core/llm/llms/Cohere.ts +5 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamJSON } from "@continuedev/fetch"; | |
| 1 | 2 | import { |
| 2 | 3 | ChatMessage, |
| 3 | 4 | Chunk, |
| @@ -6,7 +7,6 @@ | ||
| 6 | 7 | } from "../../index.js"; |
| 7 | 8 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 8 | 9 | import { BaseLLM } from "../index.js"; |
| 9 | -import { streamJSON } from "../stream.js"; | |
| 10 | 10 | |
| 11 | 11 | class Cohere extends BaseLLM { |
| 12 | 12 | static providerName = "cohere"; |
| @@ -84,6 +84,10 @@ | ||
| 84 | 84 | signal, |
| 85 | 85 | }); |
| 86 | 86 | |
| 87 | + if (resp.status === 499) { | |
| 88 | + return; // Aborted by user | |
| 89 | + } | |
| 90 | + | |
| 87 | 91 | if (options.stream === false) { |
| 88 | 92 | const data = await resp.json(); |
| 89 | 93 | yield { role: "assistant", content: data.text }; |
modified core/llm/llms/Deepseek.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
modified core/llm/llms/Flowise.ts +7 −3
| @@ -132,12 +132,16 @@ | ||
| 132 | 132 | ): AsyncGenerator<ChatMessage> { |
| 133 | 133 | const requestBody = this._getRequestBody(messages, options); |
| 134 | 134 | const { socket, socketInfo } = await this._initializeSocket(); |
| 135 | - const request = this.fetch(this._getChatUrl(), { | |
| 135 | + const response = await this.fetch(this._getChatUrl(), { | |
| 136 | 136 | method: "POST", |
| 137 | 137 | headers: this._getHeaders(), |
| 138 | 138 | body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), |
| 139 | 139 | signal, |
| 140 | - }).then((res) => res.json()); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + if (response.status === 499) { | |
| 143 | + return; // Aborted by user | |
| 144 | + } | |
| 141 | 145 | |
| 142 | 146 | while (await socketInfo.hasNextToken()) { |
| 143 | 147 | yield { role: "assistant", content: socketInfo.getCurrentMessage() }; |
| @@ -145,7 +149,7 @@ | ||
| 145 | 149 | if (socketInfo.error) { |
| 146 | 150 | socket.disconnect(); |
| 147 | 151 | try { |
| 148 | - yield { role: "assistant", content: (await request).text }; | |
| 152 | + yield { role: "assistant", content: await response.text() }; | |
| 149 | 153 | } catch (error: any) { |
| 150 | 154 | yield { role: "assistant", content: (error as Error).message ?? error }; |
| 151 | 155 | } |
modified core/llm/llms/FreeTrial.ts +1 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; |
| 2 | 3 | import { getHeaders } from "../../continueServer/stubs/headers.js"; |
| 3 | 4 | import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; |
| @@ -8,7 +9,6 @@ | ||
| 8 | 9 | LLMOptions, |
| 9 | 10 | } from "../../index.js"; |
| 10 | 11 | import { BaseLLM } from "../index.js"; |
| 11 | -import { streamResponse } from "../stream.js"; | |
| 12 | 12 | |
| 13 | 13 | class FreeTrial extends BaseLLM { |
| 14 | 14 | static providerName = "free-trial"; |
modified core/llm/llms/Gemini.ts +4 −1
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { streamResponse } from "@continuedev/fetch"; | |
| 1 | 2 | import { v4 as uuidv4 } from "uuid"; |
| 2 | 3 | import { |
| 3 | 4 | AssistantChatMessage, |
| @@ -10,7 +11,6 @@ | ||
| 10 | 11 | } from "../../index.js"; |
| 11 | 12 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 12 | 13 | import { BaseLLM } from "../index.js"; |
| 13 | -import { streamResponse } from "../stream.js"; | |
| 14 | 14 | import { |
| 15 | 15 | GeminiChatContent, |
| 16 | 16 | GeminiChatContentPart, |
| @@ -438,6 +438,9 @@ | ||
| 438 | 438 | body: JSON.stringify(body), |
| 439 | 439 | signal, |
| 440 | 440 | }); |
| 441 | + if (response.status === 499) { | |
| 442 | + return; // Aborted by user | |
| 443 | + } | |
| 441 | 444 | const data = await response.json(); |
| 442 | 445 | yield { role: "assistant", content: data.candidates[0].content }; |
| 443 | 446 | } |
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class HuggingFaceInferenceAPI extends BaseLLM { |
| 6 | 6 | static providerName = "huggingface-inference-api"; |
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class HuggingFaceTGI extends BaseLLM { |
| 6 | 6 | private static MAX_STOP_TOKENS = 4; |
modified core/llm/llms/Inception.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | |
| 4 | 4 | import OpenAI from "./OpenAI.js"; |
| 5 | 5 |
modified core/llm/llms/LlamaCpp.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | 3 | import { BaseLLM } from "../index.js"; |
| 3 | -import { streamSse } from "../stream.js"; | |
| 4 | 4 | |
| 5 | 5 | class LlamaCpp extends BaseLLM { |
| 6 | 6 | static providerName = "llama.cpp"; |
modified core/llm/llms/Moonshot.ts +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
modified core/llm/llms/Ollama.ts +4 −1
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { JSONSchema7, JSONSchema7Object } from "json-schema"; |
| 3 | 3 | import { v4 as uuidv4 } from "uuid"; |
| 4 | 4 | |
| 5 | +import { streamResponse } from "@continuedev/fetch"; | |
| 5 | 6 | import { |
| 6 | 7 | ChatMessage, |
| 7 | 8 | ChatMessageRole, |
| @@ -12,7 +13,6 @@ | ||
| 12 | 13 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 13 | 14 | import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; |
| 14 | 15 | import { BaseLLM } from "../index.js"; |
| 15 | -import { streamResponse } from "../stream.js"; | |
| 16 | 16 | |
| 17 | 17 | type OllamaChatMessage = { |
| 18 | 18 | role: ChatMessageRole; |
| @@ -457,6 +457,9 @@ | ||
| 457 | 457 | } |
| 458 | 458 | |
| 459 | 459 | if (chatOptions.stream === false) { |
| 460 | + if (response.status === 499) { | |
| 461 | + return; // Aborted by user | |
| 462 | + } | |
| 460 | 463 | const json = (await response.json()) as OllamaChatResponse; |
| 461 | 464 | yield convertChatMessage(json); |
| 462 | 465 | } 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 @@ | ||
| 3 | 3 | ChatCompletionMessageParam, |
| 4 | 4 | } from "openai/resources/index"; |
| 5 | 5 | |
| 6 | +import { streamSse } from "@continuedev/fetch"; | |
| 6 | 7 | import { |
| 7 | 8 | ChatMessage, |
| 8 | 9 | CompletionOptions, |
| @@ -16,7 +17,6 @@ | ||
| 16 | 17 | LlmApiRequestType, |
| 17 | 18 | toChatBody, |
| 18 | 19 | } from "../openaiTypeConverters.js"; |
| 19 | -import { streamSse } from "../stream.js"; | |
| 20 | 20 | |
| 21 | 21 | const NON_CHAT_MODELS = [ |
| 22 | 22 | "text-davinci-002", |
| @@ -77,8 +77,8 @@ | ||
| 77 | 77 | return model; |
| 78 | 78 | } |
| 79 | 79 | |
| 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]+/); | |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | 84 | private isFireworksAiModel(model?: string): boolean { |
| @@ -139,7 +139,7 @@ | ||
| 139 | 139 | finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); |
| 140 | 140 | |
| 141 | 141 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 142 | - if (this.isO3orO1Model(options.model)) { | |
| 142 | + if (this.isOSeriesModel(options.model)) { | |
| 143 | 143 | // a) use max_completion_tokens instead of max_tokens |
| 144 | 144 | finalOptions.max_completion_tokens = options.maxTokens; |
| 145 | 145 | finalOptions.max_tokens = undefined; |
| @@ -241,7 +241,7 @@ | ||
| 241 | 241 | body.stop = body.stop?.slice(0, this.getMaxStopWords()); |
| 242 | 242 | |
| 243 | 243 | // OpenAI o1-preview and o1-mini or o3-mini: |
| 244 | - if (this.isO3orO1Model(body.model)) { | |
| 244 | + if (this.isOSeriesModel(body.model)) { | |
| 245 | 245 | // a) use max_completion_tokens instead of max_tokens |
| 246 | 246 | body.max_completion_tokens = body.max_tokens; |
| 247 | 247 | body.max_tokens = undefined; |
| @@ -352,6 +352,9 @@ | ||
| 352 | 352 | |
| 353 | 353 | // Handle non-streaming response |
| 354 | 354 | if (body.stream === false) { |
| 355 | + if (response.status === 499) { | |
| 356 | + return; // Aborted by user | |
| 357 | + } | |
| 355 | 358 | const data = await response.json(); |
| 356 | 359 | yield data.choices[0].message; |
| 357 | 360 | return; |
modified core/llm/llms/SiliconFlow.ts +2 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | +import { streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { Chunk, CompletionOptions, LLMOptions } from "../../index.js"; |
| 2 | -import { streamSse } from "../stream.js"; | |
| 3 | 3 | import { osModelsEditPrompt } from "../templates/edit.js"; |
| 4 | 4 | |
| 5 | 5 | import OpenAI from "./OpenAI.js"; |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | console.warn("[SiliconFlow] rerank: query is empty"); |
| 59 | 59 | return []; |
| 60 | 60 | } |
| 61 | - | |
| 61 | + | |
| 62 | 62 | if (!chunks || chunks.length === 0) { |
| 63 | 63 | console.warn("[SiliconFlow] rerank: chunks is empty"); |
| 64 | 64 | return []; |
modified core/llm/llms/VertexAI.ts +23 −5
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | import { GoogleAuth } from "google-auth-library"; |
| 2 | 2 | |
| 3 | +import { streamResponse, streamSse } from "@continuedev/fetch"; | |
| 3 | 4 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 4 | 5 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 5 | 6 | import { BaseLLM } from "../index.js"; |
| 6 | -import { streamResponse, streamSse } from "../stream.js"; | |
| 7 | 7 | |
| 8 | 8 | import Anthropic from "./Anthropic.js"; |
| 9 | 9 | import Gemini from "./Gemini.js"; |
| @@ -95,6 +95,7 @@ | ||
| 95 | 95 | protected async *StreamChatAnthropic( |
| 96 | 96 | messages: ChatMessage[], |
| 97 | 97 | options: CompletionOptions, |
| 98 | + signal: AbortSignal, | |
| 98 | 99 | ): AsyncGenerator<ChatMessage> { |
| 99 | 100 | const systemMessage = stripImages( |
| 100 | 101 | messages.filter((m) => m.role === "system")[0]?.content ?? "", |
| @@ -128,8 +129,13 @@ | ||
| 128 | 129 | ] |
| 129 | 130 | : systemMessage, |
| 130 | 131 | }), |
| 132 | + signal, | |
| 131 | 133 | }); |
| 132 | 134 | |
| 135 | + if (response.status === 499) { | |
| 136 | + return; // Aborted by user | |
| 137 | + } | |
| 138 | + | |
| 133 | 139 | if (options.stream === false) { |
| 134 | 140 | const data = await response.json(); |
| 135 | 141 | yield { role: "assistant", content: data.content[0].text }; |
| @@ -150,6 +156,7 @@ | ||
| 150 | 156 | private async *streamChatGemini( |
| 151 | 157 | messages: ChatMessage[], |
| 152 | 158 | options: CompletionOptions, |
| 159 | + signal: AbortSignal, | |
| 153 | 160 | ): AsyncGenerator<ChatMessage> { |
| 154 | 161 | const apiURL = new URL( |
| 155 | 162 | `publishers/google/models/${options.model}:streamGenerateContent`, |
| @@ -160,6 +167,7 @@ | ||
| 160 | 167 | const response = await this.fetch(apiURL, { |
| 161 | 168 | method: "POST", |
| 162 | 169 | body: JSON.stringify(body), |
| 170 | + signal, | |
| 163 | 171 | }); |
| 164 | 172 | for await (const message of this.geminiInstance.processGeminiResponse( |
| 165 | 173 | streamResponse(response), |
| @@ -171,6 +179,7 @@ | ||
| 171 | 179 | private async *streamChatBison( |
| 172 | 180 | messages: ChatMessage[], |
| 173 | 181 | options: CompletionOptions, |
| 182 | + signal: AbortSignal, | |
| 174 | 183 | ): AsyncGenerator<ChatMessage> { |
| 175 | 184 | const instances = messages.map((message) => ({ prompt: message.content })); |
| 176 | 185 | |
| @@ -193,7 +202,11 @@ | ||
| 193 | 202 | const response = await this.fetch(apiURL, { |
| 194 | 203 | method: "POST", |
| 195 | 204 | body: JSON.stringify(body), |
| 205 | + signal, | |
| 196 | 206 | }); |
| 207 | + if (response.status === 499) { | |
| 208 | + return; // Aborted by user | |
| 209 | + } | |
| 197 | 210 | const data = await response.json(); |
| 198 | 211 | yield { role: "assistant", content: data.predictions[0].content }; |
| 199 | 212 | } |
| @@ -203,6 +216,7 @@ | ||
| 203 | 216 | protected async *StreamChatMistral( |
| 204 | 217 | messages: ChatMessage[], |
| 205 | 218 | options: CompletionOptions, |
| 219 | + signal: AbortSignal, | |
| 206 | 220 | ): AsyncGenerator<ChatMessage> { |
| 207 | 221 | const apiBase = this.apiBase!; |
| 208 | 222 | const apiURL = new URL( |
| @@ -228,6 +242,7 @@ | ||
| 228 | 242 | const response = await this.fetch(apiURL, { |
| 229 | 243 | method: "POST", |
| 230 | 244 | body: JSON.stringify(body), |
| 245 | + signal, | |
| 231 | 246 | }); |
| 232 | 247 | |
| 233 | 248 | for await (const chunk of streamSse(response)) { |
| @@ -304,6 +319,9 @@ | ||
| 304 | 319 | }), |
| 305 | 320 | signal, |
| 306 | 321 | }); |
| 322 | + if (resp.status === 499) { | |
| 323 | + return; // Aborted by user | |
| 324 | + } | |
| 307 | 325 | // Streaming is not supported by code-gecko |
| 308 | 326 | // TODO: convert to non-streaming fim method when one exist in continue. |
| 309 | 327 | yield (await resp.json()).predictions[0].content; |
| @@ -323,14 +341,14 @@ | ||
| 323 | 341 | ? this.geminiInstance.removeSystemMessage(messages) |
| 324 | 342 | : messages; |
| 325 | 343 | if (this.vertexProvider === "gemini") { |
| 326 | - yield* this.streamChatGemini(convertedMsgs, options); | |
| 344 | + yield* this.streamChatGemini(convertedMsgs, options, signal); | |
| 327 | 345 | } else if (this.vertexProvider === "mistral") { |
| 328 | - yield* this.StreamChatMistral(messages, options); | |
| 346 | + yield* this.StreamChatMistral(messages, options, signal); | |
| 329 | 347 | } else if (this.vertexProvider === "anthropic") { |
| 330 | - yield* this.StreamChatAnthropic(messages, options); | |
| 348 | + yield* this.StreamChatAnthropic(messages, options, signal); | |
| 331 | 349 | } else { |
| 332 | 350 | if (options.model.includes("bison")) { |
| 333 | - yield* this.streamChatBison(convertedMsgs, options); | |
| 351 | + yield* this.streamChatBison(convertedMsgs, options, signal); | |
| 334 | 352 | } else { |
| 335 | 353 | throw new Error(`Unsupported model: ${options.model}`); |
| 336 | 354 | } |
modified core/llm/llms/WatsonX.ts +37 −53
| @@ -1,15 +1,12 @@ | ||
| 1 | +import { streamResponse, streamSse } from "@continuedev/fetch"; | |
| 1 | 2 | import { |
| 2 | 3 | ChatMessage, |
| 3 | 4 | Chunk, |
| 4 | 5 | CompletionOptions, |
| 5 | 6 | LLMOptions, |
| 6 | 7 | } from "../../index.js"; |
| 7 | -import { | |
| 8 | - fromChatCompletionChunk, | |
| 9 | -} from "../openaiTypeConverters.js"; | |
| 10 | -import { renderChatMessage } from "../../util/messageContent.js"; | |
| 11 | 8 | import { BaseLLM } from "../index.js"; |
| 12 | -import { streamResponse, streamSse } from "../stream.js"; | |
| 9 | +import { fromChatCompletionChunk } from "../openaiTypeConverters.js"; | |
| 13 | 10 | |
| 14 | 11 | let watsonxToken = { |
| 15 | 12 | expiration: 0, |
| @@ -86,7 +83,7 @@ | ||
| 86 | 83 | } |
| 87 | 84 | |
| 88 | 85 | _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}`; | |
| 90 | 87 | } |
| 91 | 88 | |
| 92 | 89 | static providerName = "watsonx"; |
| @@ -182,7 +179,6 @@ | ||
| 182 | 179 | signal: AbortSignal, |
| 183 | 180 | options: CompletionOptions, |
| 184 | 181 | ): AsyncGenerator<string> { |
| 185 | - | |
| 186 | 182 | await this.updateWatsonxToken(); |
| 187 | 183 | |
| 188 | 184 | const stopSequences = options.stop?.slice(0, 6) ?? []; |
| @@ -214,44 +210,38 @@ | ||
| 214 | 210 | payload.project_id = this.projectId; |
| 215 | 211 | } |
| 216 | 212 | |
| 217 | - var response = await this.fetch(url, { | |
| 213 | + const response = await this.fetch(url, { | |
| 218 | 214 | method: "POST", |
| 219 | 215 | headers: headers, |
| 220 | 216 | body: JSON.stringify(payload), |
| 221 | 217 | signal, |
| 222 | 218 | }); |
| 223 | 219 | |
| 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}`); | |
| 251 | 230 | } |
| 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; | |
| 255 | 245 | } |
| 256 | 246 | } |
| 257 | 247 | |
| @@ -267,7 +257,7 @@ | ||
| 267 | 257 | const headers = this._getHeaders(); |
| 268 | 258 | |
| 269 | 259 | const payload: any = { |
| 270 | - messages: messages, | |
| 260 | + messages: messages, | |
| 271 | 261 | max_tokens: options.maxTokens ?? 1024, |
| 272 | 262 | stop: stopSequences, |
| 273 | 263 | frequency_penalty: options.frequencyPenalty || 1, |
| @@ -281,36 +271,30 @@ | ||
| 281 | 271 | |
| 282 | 272 | if (!!options.temperature) { |
| 283 | 273 | payload.temperature = options.temperature; |
| 284 | - } | |
| 274 | + } | |
| 285 | 275 | if (!!options.topP) { |
| 286 | 276 | payload.top_p = options.topP; |
| 287 | 277 | } |
| 288 | 278 | if (!!options.tools) { |
| 289 | 279 | payload.tools = options.tools; |
| 290 | 280 | if (options.toolChoice) { |
| 291 | - payload.tool_choice = options.toolChoice; | |
| 281 | + payload.tool_choice = options.toolChoice; | |
| 292 | 282 | } else { |
| 293 | - payload.tool_choice_option = "auto"; | |
| 283 | + payload.tool_choice_option = "auto"; | |
| 294 | 284 | } |
| 295 | 285 | } |
| 296 | 286 | |
| 297 | - var response = await this.fetch(url, { | |
| 287 | + const response = await this.fetch(url, { | |
| 298 | 288 | method: "POST", |
| 299 | 289 | headers: headers, |
| 300 | 290 | body: JSON.stringify(payload), |
| 301 | 291 | signal, |
| 302 | 292 | }); |
| 303 | 293 | |
| 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; | |
| 314 | 298 | } |
| 315 | 299 | } |
| 316 | 300 | } |
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
| @@ -27,8 +27,12 @@ | ||
| 27 | 27 | // to call whatever LLM API is chosen |
| 28 | 28 | private actualApiBase?: string; |
| 29 | 29 | |
| 30 | + // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions | |
| 31 | + private configEnv?: Record<string, any>; | |
| 32 | + | |
| 30 | 33 | constructor(options: LLMOptions) { |
| 31 | 34 | super(options); |
| 35 | + this.configEnv = options.env; | |
| 32 | 36 | this.actualApiBase = options.apiBase; |
| 33 | 37 | this.apiKeyLocation = options.apiKeyLocation; |
| 34 | 38 | this.orgScopeId = options.orgScopeId; |
| @@ -48,6 +52,7 @@ | ||
| 48 | 52 | apiKeyLocation: this.apiKeyLocation, |
| 49 | 53 | apiBase: this.actualApiBase, |
| 50 | 54 | orgScopeId: this.orgScopeId ?? null, |
| 55 | + env: this.configEnv, | |
| 51 | 56 | }; |
| 52 | 57 | return { |
| 53 | 58 | 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 "../.."; | |
| 2 | 2 | import { getSystemMessageWithRules } from "./getSystemMessageWithRules"; |
| 3 | 3 | |
| 4 | 4 | describe("getSystemMessageWithRules", () => { |
| @@ -25,11 +25,48 @@ | ||
| 25 | 25 | source: "rules-block", |
| 26 | 26 | }; |
| 27 | 27 | |
| 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 | + | |
| 28 | 64 | it("should not include pattern-matched rules when no file paths are mentioned", () => { |
| 29 | 65 | const result = getSystemMessageWithRules({ |
| 30 | 66 | baseSystemMessage, |
| 31 | 67 | userMessage: undefined, |
| 32 | 68 | rules: [tsRule], |
| 69 | + contextItems: emptyContextItems, | |
| 33 | 70 | }); |
| 34 | 71 | |
| 35 | 72 | expect(result).toBe(baseSystemMessage); |
| @@ -40,12 +77,13 @@ | ||
| 40 | 77 | baseSystemMessage, |
| 41 | 78 | userMessage: undefined, |
| 42 | 79 | rules: [generalRule], |
| 80 | + contextItems: emptyContextItems, | |
| 43 | 81 | }); |
| 44 | 82 | |
| 45 | 83 | expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`); |
| 46 | 84 | }); |
| 47 | 85 | |
| 48 | - it("should include only matching rules based on file paths", () => { | |
| 86 | + it("should include only matching rules based on file paths in message", () => { | |
| 49 | 87 | const userMessage: UserChatMessage = { |
| 50 | 88 | role: "user", |
| 51 | 89 | content: |
| @@ -56,6 +94,20 @@ | ||
| 56 | 94 | baseSystemMessage, |
| 57 | 95 | userMessage, |
| 58 | 96 | 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], | |
| 59 | 111 | }); |
| 60 | 112 | |
| 61 | 113 | // Should include TS rule and general rule, but not Python rule |
| @@ -63,7 +115,25 @@ | ||
| 63 | 115 | expect(result).toBe(expected); |
| 64 | 116 | }); |
| 65 | 117 | |
| 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", () => { | |
| 67 | 137 | const userMessage: UserChatMessage = { |
| 68 | 138 | role: "user", |
| 69 | 139 | content: |
| @@ -74,6 +144,20 @@ | ||
| 74 | 144 | baseSystemMessage, |
| 75 | 145 | userMessage, |
| 76 | 146 | 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], | |
| 77 | 161 | }); |
| 78 | 162 | |
| 79 | 163 | // Should include all rules |
| @@ -91,6 +175,7 @@ | ||
| 91 | 175 | baseSystemMessage, |
| 92 | 176 | userMessage, |
| 93 | 177 | rules: [tsRule, pythonRule, generalRule], |
| 178 | + contextItems: emptyContextItems, | |
| 94 | 179 | }); |
| 95 | 180 | |
| 96 | 181 | // Should only include the general rule |
| @@ -117,6 +202,7 @@ | ||
| 117 | 202 | baseSystemMessage, |
| 118 | 203 | userMessage, |
| 119 | 204 | rules: [commaRule], |
| 205 | + contextItems: emptyContextItems, | |
| 120 | 206 | }); |
| 121 | 207 | |
| 122 | 208 | // With the current implementation, the comma-separated pattern is treated as a single string, |
| @@ -143,6 +229,7 @@ | ||
| 143 | 229 | baseSystemMessage, |
| 144 | 230 | userMessage, |
| 145 | 231 | rules: [arrayGlobRule], |
| 232 | + contextItems: emptyContextItems, | |
| 146 | 233 | }); |
| 147 | 234 | |
| 148 | 235 | // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts |
| @@ -168,6 +255,7 @@ | ||
| 168 | 255 | baseSystemMessage, |
| 169 | 256 | userMessage, |
| 170 | 257 | rules: [arrayGlobRule], |
| 258 | + contextItems: emptyContextItems, | |
| 171 | 259 | }); |
| 172 | 260 | |
| 173 | 261 | // Should match src/main.ts but not config/settings.ts |
| @@ -193,9 +281,125 @@ | ||
| 193 | 281 | baseSystemMessage, |
| 194 | 282 | userMessage, |
| 195 | 283 | rules: [arrayGlobRule], |
| 284 | + contextItems: emptyContextItems, | |
| 196 | 285 | }); |
| 197 | 286 | |
| 198 | 287 | // Should not match any file paths |
| 199 | 288 | expect(result).toBe(baseSystemMessage); |
| 200 | 289 | }); |
| 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 | + }); | |
| 201 | 405 | }); |
modified core/llm/rules/getSystemMessageWithRules.ts +56 −16
| @@ -1,5 +1,10 @@ | ||
| 1 | 1 | import { minimatch } from "minimatch"; |
| 2 | -import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; | |
| 2 | +import { | |
| 3 | + ContextItemWithId, | |
| 4 | + RuleWithSource, | |
| 5 | + ToolResultChatMessage, | |
| 6 | + UserChatMessage, | |
| 7 | +} from "../.."; | |
| 3 | 8 | import { renderChatMessage } from "../../util/messageContent"; |
| 4 | 9 | import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; |
| 5 | 10 | |
| @@ -23,32 +28,67 @@ | ||
| 23 | 28 | return false; |
| 24 | 29 | }; |
| 25 | 30 | |
| 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 | + */ | |
| 26 | 76 | export const getSystemMessageWithRules = ({ |
| 27 | 77 | baseSystemMessage, |
| 28 | 78 | userMessage, |
| 29 | 79 | rules, |
| 80 | + contextItems, | |
| 30 | 81 | }: { |
| 31 | 82 | baseSystemMessage?: string; |
| 32 | 83 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 33 | 84 | rules: RuleWithSource[]; |
| 85 | + contextItems: ContextItemWithId[]; | |
| 34 | 86 | }) => { |
| 35 | - const filePathsFromMessage = userMessage | |
| 36 | - ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) | |
| 37 | - : []; | |
| 38 | - | |
| 87 | + const applicableRules = getApplicableRules(userMessage, rules, contextItems); | |
| 39 | 88 | let systemMessage = baseSystemMessage ?? ""; |
| 40 | 89 | |
| 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}`; | |
| 52 | 92 | } |
| 53 | 93 | |
| 54 | 94 | return systemMessage; |
modified core/llm/stream.ts +2 −2
| @@ -1,4 +1,4 @@ | ||
| 1 | -async function* toAsyncIterable( | |
| 1 | +export async function* toAsyncIterable( | |
| 2 | 2 | nodeReadable: NodeJS.ReadableStream, |
| 3 | 3 | ): AsyncGenerator<Uint8Array> { |
| 4 | 4 | for await (const chunk of nodeReadable) { |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | } |
| 59 | 59 | |
| 60 | 60 | function parseSseLine(line: string): { done: boolean; data: any } { |
| 61 | - if (line.startsWith("data: [DONE]")) { | |
| 61 | + if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { | |
| 62 | 62 | return { done: true, data: undefined }; |
| 63 | 63 | } |
| 64 | 64 | if (line.startsWith("data:")) { |
modified core/llm/streamChat.ts +27 −35
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | export async function* llmStreamChat( |
| 10 | 10 | configHandler: ConfigHandler, |
| 11 | - abortedMessageIds: Set<string>, | |
| 11 | + abortController: AbortController, | |
| 12 | 12 | msg: Message<ToCoreProtocol["llm/streamChat"][0]>, |
| 13 | 13 | ide: IDE, |
| 14 | 14 | messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| @@ -75,52 +75,44 @@ | ||
| 75 | 75 | selectedCode, |
| 76 | 76 | config, |
| 77 | 77 | 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 | + ), | |
| 79 | 86 | completionOptions, |
| 80 | 87 | }); |
| 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; | |
| 103 | 93 | } |
| 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 | + }; | |
| 106 | 99 | } |
| 107 | - | |
| 108 | - return next.value; | |
| 109 | - } catch (e) { | |
| 110 | - throw e; | |
| 111 | - } finally { | |
| 112 | - clearInterval(checkActiveInterval); | |
| 100 | + next = await gen.next(); | |
| 113 | 101 | } |
| 102 | + if (!next.done) { | |
| 103 | + throw new Error("Will never happen"); | |
| 104 | + } | |
| 105 | + | |
| 106 | + return next.value; | |
| 114 | 107 | } else { |
| 115 | 108 | const gen = model.streamChat( |
| 116 | 109 | messages, |
| 117 | - new AbortController().signal, | |
| 110 | + abortController.signal, | |
| 118 | 111 | completionOptions, |
| 119 | 112 | ); |
| 120 | 113 | let next = await gen.next(); |
| 121 | 114 | while (!next.done) { |
| 122 | - if (abortedMessageIds.has(msg.messageId)) { | |
| 123 | - abortedMessageIds.delete(msg.messageId); | |
| 115 | + if (abortController.signal.aborted) { | |
| 124 | 116 | next = await gen.return(errorPromptLog); |
| 125 | 117 | break; |
| 126 | 118 | } |
modified core/llm/templates/edit/gpt.ts +2 −0
| @@ -64,6 +64,8 @@ | ||
| 64 | 64 | \`\`\` |
| 65 | 65 | |
| 66 | 66 | The user's request is: "${otherData.userInput}" |
| 67 | + | |
| 68 | + DO NOT output any natural language, only output the code changes. | |
| 67 | 69 | |
| 68 | 70 | Here is the rewritten code:`); |
| 69 | 71 |
modified core/llm/toolSupport.test.ts +3 −0
| @@ -155,6 +155,7 @@ | ||
| 155 | 155 | expect(supportsFn("pixtral-12b-2409")).toBe(true); |
| 156 | 156 | expect(supportsFn("pixtral-large-latest")).toBe(true); |
| 157 | 157 | expect(supportsFn("open-mistral-nemo")).toBe(true); |
| 158 | + expect(supportsFn("devstral-latest")).toBe(true); | |
| 158 | 159 | }); |
| 159 | 160 | |
| 160 | 161 | it("should return false for other unsupported models", () => { |
| @@ -170,6 +171,7 @@ | ||
| 170 | 171 | expect(supportsFn("CODESTRAL-LATEST")).toBe(true); |
| 171 | 172 | expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true); |
| 172 | 173 | expect(supportsFn("PIXTRAL-12B-2409")).toBe(true); |
| 174 | + expect(supportsFn("DEVSTRAL-LATEST")).toBe(true); | |
| 173 | 175 | }); |
| 174 | 176 | }); |
| 175 | 177 | |
| @@ -192,6 +194,7 @@ | ||
| 192 | 194 | expect(supportsFn("aya-expanse")).toBe(true); |
| 193 | 195 | expect(supportsFn("firefunction-v2")).toBe(true); |
| 194 | 196 | expect(supportsFn("mistral-7b")).toBe(true); |
| 197 | + expect(supportsFn("devstral-24b")).toBe(true); | |
| 195 | 198 | }); |
| 196 | 199 | |
| 197 | 200 | it("should return false for explicitly unsupported models", () => { |
modified core/llm/toolSupport.ts +72 −2
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | "claude-3.5", |
| 18 | 18 | "claude-3-7", |
| 19 | 19 | "claude-3.7", |
| 20 | + "claude-sonnet-4", | |
| 20 | 21 | "gpt-4", |
| 21 | 22 | "o3", |
| 22 | 23 | "gemini", |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | }, |
| 25 | 26 | anthropic: (model) => { |
| 26 | 27 | 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) => | |
| 28 | 29 | model.toLowerCase().startsWith(part), |
| 29 | 30 | ) |
| 30 | 31 | ) { |
| @@ -76,7 +77,7 @@ | ||
| 76 | 77 | // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 |
| 77 | 78 | if ( |
| 78 | 79 | 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) => | |
| 80 | 81 | model.toLowerCase().includes(part), |
| 81 | 82 | ) |
| 82 | 83 | ) { |
| @@ -88,6 +89,7 @@ | ||
| 88 | 89 | return ( |
| 89 | 90 | !model.toLowerCase().includes("mamba") && |
| 90 | 91 | [ |
| 92 | + "devstral", | |
| 91 | 93 | "codestral", |
| 92 | 94 | "mistral-large", |
| 93 | 95 | "mistral-small", |
| @@ -136,6 +138,7 @@ | ||
| 136 | 138 | "aya-expanse", |
| 137 | 139 | "firefunction-v2", |
| 138 | 140 | "mistral", |
| 141 | + "devstral", | |
| 139 | 142 | ].some((part) => modelName.toLowerCase().includes(part)) |
| 140 | 143 | ) { |
| 141 | 144 | return true; |
| @@ -165,4 +168,71 @@ | ||
| 165 | 168 | ) |
| 166 | 169 | return true; |
| 167 | 170 | }, |
| 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 | + }, | |
| 168 | 238 | }; |
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 @@ | ||
| 2 | 2 | * Extracts file paths from markdown code blocks |
| 3 | 3 | */ |
| 4 | 4 | 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 | + | |
| 11 | 7 | 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 | + } | |
| 18 | 35 | } |
| 19 | 36 | } |
| 20 | - | |
| 21 | 37 | return paths; |
| 22 | 38 | } |
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 @@ | ||
| 27 | 27 | "@types/mustache": "^4.2.5", |
| 28 | 28 | "@types/node-fetch": "^2.6.11", |
| 29 | 29 | "@types/pg": "^8.11.6", |
| 30 | + "@types/plist": "^3.0.5", | |
| 30 | 31 | "@types/request": "^2.48.12", |
| 31 | 32 | "@types/tar": "^6.1.13", |
| 32 | 33 | "@types/uuid": "^9.0.7", |
| @@ -48,9 +49,9 @@ | ||
| 48 | 49 | "@aws-sdk/credential-providers": "^3.778.0", |
| 49 | 50 | "@continuedev/config-types": "^1.0.13", |
| 50 | 51 | "@continuedev/config-yaml": "file:../packages/config-yaml", |
| 51 | - "@continuedev/fetch": "^1.0.6", | |
| 52 | + "@continuedev/fetch": "^1.0.10", | |
| 52 | 53 | "@continuedev/llm-info": "^1.0.8", |
| 53 | - "@continuedev/openai-adapters": "^1.0.19", | |
| 54 | + "@continuedev/openai-adapters": "^1.0.25", | |
| 54 | 55 | "@modelcontextprotocol/sdk": "^1.5.0", |
| 55 | 56 | "@mozilla/readability": "^0.5.0", |
| 56 | 57 | "@octokit/rest": "^20.1.1", |
| @@ -89,6 +90,7 @@ | ||
| 89 | 90 | "p-limit": "^6.1.0", |
| 90 | 91 | "partial-json": "^0.1.7", |
| 91 | 92 | "pg": "^8.11.3", |
| 93 | + "plist": "^3.1.0", | |
| 92 | 94 | "posthog-node": "^3.6.3", |
| 93 | 95 | "puppeteer": "^22.4.0", |
| 94 | 96 | "puppeteer-chromium-resolver": "^23.0.0", |
modified core/promptFiles/v1/slashCommandFromPromptFile.ts +1 −0
| @@ -63,6 +63,7 @@ | ||
| 63 | 63 | name, |
| 64 | 64 | description, |
| 65 | 65 | prompt, |
| 66 | + promptFile: path, | |
| 66 | 67 | run: async function* (context) { |
| 67 | 68 | const userInput = extractUserInput(context.input, name); |
| 68 | 69 | const [_, renderedPrompt] = await renderPromptFileV2(prompt, { |
modified core/protocol/core.ts +5 −14
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | import { SharedConfigSchema } from "../config/sharedConfig"; |
| 10 | 10 | import { GlobalContextModelSelections } from "../util/GlobalContext"; |
| 11 | 11 | |
| 12 | -import type { | |
| 12 | +import { | |
| 13 | 13 | BrowserSerializedContinueConfig, |
| 14 | 14 | ChatMessage, |
| 15 | 15 | ContextItem, |
| @@ -29,10 +29,11 @@ | ||
| 29 | 29 | SessionMetadata, |
| 30 | 30 | SiteIndexingConfig, |
| 31 | 31 | SlashCommandDescription, |
| 32 | + StreamDiffLinesPayload, | |
| 32 | 33 | ToolCall, |
| 33 | 34 | } from "../"; |
| 34 | 35 | import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; |
| 35 | -import { ControlPlaneSessionInfo } from "../control-plane/client"; | |
| 36 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; | |
| 36 | 37 | |
| 37 | 38 | export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; |
| 38 | 39 | |
| @@ -45,6 +46,7 @@ | ||
| 45 | 46 | // Special |
| 46 | 47 | ping: [string, string]; |
| 47 | 48 | abort: [undefined, void]; |
| 49 | + cancelApply: [undefined, void]; | |
| 48 | 50 | |
| 49 | 51 | // History |
| 50 | 52 | "history/list": [ListHistoryOptions, SessionMetadata[]]; |
| @@ -142,18 +144,7 @@ | ||
| 142 | 144 | }, |
| 143 | 145 | AsyncGenerator<ChatMessage, PromptLog>, |
| 144 | 146 | ]; |
| 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>]; | |
| 157 | 148 | "chatDescriber/describe": [ |
| 158 | 149 | { |
| 159 | 150 | text: string; |
modified core/protocol/ide.ts +2 −3
| @@ -1,5 +1,3 @@ | ||
| 1 | -import { ControlPlaneSessionInfo } from "../control-plane/client"; | |
| 2 | - | |
| 3 | 1 | import type { |
| 4 | 2 | ContinueRcJson, |
| 5 | 3 | DiffLine, |
| @@ -16,6 +14,7 @@ | ||
| 16 | 14 | TerminalOptions, |
| 17 | 15 | Thread, |
| 18 | 16 | } from "../"; |
| 17 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; | |
| 19 | 18 | |
| 20 | 19 | export interface GetGhTokenArgs { |
| 21 | 20 | force?: boolean; |
| @@ -99,7 +98,7 @@ | ||
| 99 | 98 | ControlPlaneSessionInfo | undefined, |
| 100 | 99 | ]; |
| 101 | 100 | logoutOfControlPlane: [undefined, void]; |
| 102 | - reportError:[any, void]; | |
| 101 | + reportError: [any, void]; | |
| 103 | 102 | closeSidebar: [undefined, void]; |
| 104 | 103 | }; |
| 105 | 104 |
modified core/protocol/ideWebview.ts +11 −15
| @@ -1,11 +1,14 @@ | ||
| 1 | 1 | import { ToIdeFromWebviewOrCoreProtocol } from "./ide"; |
| 2 | 2 | import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; |
| 3 | 3 | |
| 4 | -import type { | |
| 4 | +import { | |
| 5 | + AcceptOrRejectDiffPayload, | |
| 5 | 6 | ApplyState, |
| 6 | - CodeToEdit, | |
| 7 | + HighlightedCodePayload, | |
| 7 | 8 | MessageContent, |
| 8 | 9 | RangeInFileWithContents, |
| 10 | + SetCodeToEditPayload, | |
| 11 | + ShowFilePayload, | |
| 9 | 12 | } from "../"; |
| 10 | 13 | |
| 11 | 14 | export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { |
| @@ -21,7 +24,7 @@ | ||
| 21 | 24 | ]; |
| 22 | 25 | overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; |
| 23 | 26 | showTutorial: [undefined, void]; |
| 24 | - showFile: [{ filepath: string }, void]; | |
| 27 | + showFile: [ShowFilePayload, void]; | |
| 25 | 28 | toggleDevTools: [undefined, void]; |
| 26 | 29 | reloadWindow: [undefined, void]; |
| 27 | 30 | focusEditor: [undefined, void]; |
| @@ -39,11 +42,11 @@ | ||
| 39 | 42 | vscMediaUrl: string; |
| 40 | 43 | }, |
| 41 | 44 | ]; |
| 42 | - "jetbrains/getColors": [undefined, Record<string, string>]; | |
| 45 | + "jetbrains/getColors": [undefined, Record<string, string | null | undefined>]; | |
| 43 | 46 | "vscode/openMoveRightMarkdown": [undefined, void]; |
| 44 | 47 | 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]; | |
| 47 | 50 | "edit/sendPrompt": [ |
| 48 | 51 | { |
| 49 | 52 | prompt: MessageContent; |
| @@ -63,15 +66,8 @@ | ||
| 63 | 66 | focusContinueInput: [undefined, void]; |
| 64 | 67 | focusContinueInputWithoutClear: [undefined, void]; |
| 65 | 68 | 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]; | |
| 75 | 71 | navigateTo: [{ path: string; toggle?: boolean }, void]; |
| 76 | 72 | addModel: [undefined, void]; |
| 77 | 73 |
modified core/protocol/webview.ts +2 −2
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { ConfigResult } from "@continuedev/config-yaml"; |
| 2 | 2 | import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; |
| 3 | -import { ControlPlaneSessionInfo } from "../control-plane/client.js"; | |
| 3 | +import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; | |
| 4 | 4 | import type { |
| 5 | 5 | BrowserSerializedContinueConfig, |
| 6 | 6 | ContextItemWithId, |
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | setTTSActive: [boolean, void]; |
| 41 | 41 | getWebviewHistoryLength: [undefined, number]; |
| 42 | 42 | getCurrentSessionId: [undefined, string]; |
| 43 | - "jetbrains/setColors": [Record<string, string>, void]; | |
| 43 | + "jetbrains/setColors": [Record<string, string | null | undefined>, void]; | |
| 44 | 44 | sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; |
| 45 | 45 | toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; |
| 46 | 46 | }; |
modified core/test/testDir.ts +1 −1
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | if (Array.isArray(p)) { |
| 44 | 44 | fs.writeFileSync(filepath, p[1]); |
| 45 | 45 | } else if (p.endsWith("/")) { |
| 46 | - fs.mkdirSync(p, { recursive: true }); | |
| 46 | + fs.mkdirSync(filepath, { recursive: true }); | |
| 47 | 47 | } else { |
| 48 | 48 | fs.writeFileSync(filepath, ""); |
| 49 | 49 | } |
modified core/tools/callTool.ts +39 −40
| @@ -29,11 +29,12 @@ | ||
| 29 | 29 | }), |
| 30 | 30 | }); |
| 31 | 31 | |
| 32 | + const data = await response.json(); | |
| 33 | + | |
| 32 | 34 | 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)}`); | |
| 34 | 36 | } |
| 35 | 37 | |
| 36 | - const data = await response.json(); | |
| 37 | 38 | return data.output; |
| 38 | 39 | } |
| 39 | 40 | |
| @@ -84,7 +85,7 @@ | ||
| 84 | 85 | }); |
| 85 | 86 | |
| 86 | 87 | if (response.isError === true) { |
| 87 | - throw new Error(`Failed to call tool: ${toolName}`); | |
| 88 | + throw new Error(JSON.stringify(response.content)); | |
| 88 | 89 | } |
| 89 | 90 | |
| 90 | 91 | const contextItems: ContextItem[] = []; |
| @@ -130,6 +131,37 @@ | ||
| 130 | 131 | } |
| 131 | 132 | } |
| 132 | 133 | |
| 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 | + | |
| 133 | 165 | // Handles calls for core/non-client tools |
| 134 | 166 | // Returns an error context item if the tool call fails |
| 135 | 167 | // Note: Edit tool is handled on client |
| @@ -141,44 +173,11 @@ | ||
| 141 | 173 | contextItems: ContextItem[]; |
| 142 | 174 | errorMessage: string | undefined; |
| 143 | 175 | }> { |
| 144 | - const args = JSON.parse(callArgs || "{}"); | |
| 145 | - const uri = tool.uri ?? tool.function.name; | |
| 146 | 176 | 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); | |
| 182 | 181 | if (tool.faviconUrl) { |
| 183 | 182 | contextItems.forEach((item) => { |
| 184 | 183 | item.icon = tool.faviconUrl; |
modified core/tools/definitions/createRuleBlock.ts +5 −1
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | function: { |
| 14 | 14 | name: BuiltInToolNames.CreateRuleBlock, |
| 15 | 15 | 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.", | |
| 17 | 17 | parameters: { |
| 18 | 18 | type: "object", |
| 19 | 19 | required: ["name", "rule"], |
| @@ -28,6 +28,10 @@ | ||
| 28 | 28 | description: |
| 29 | 29 | "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", |
| 30 | 30 | }, |
| 31 | + description: { | |
| 32 | + type: "string", | |
| 33 | + description: "Short description of the rule", | |
| 34 | + }, | |
| 31 | 35 | globs: { |
| 32 | 36 | type: "string", |
| 33 | 37 | 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"; | |
| 2 | 2 | import { createRuleBlockImpl } from "./createRuleBlock"; |
| 3 | 3 | |
| 4 | 4 | // Mock the extras parameter with necessary functions |
| @@ -17,33 +17,6 @@ | ||
| 17 | 17 | jest.clearAllMocks(); |
| 18 | 18 | }); |
| 19 | 19 | |
| 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 | - | |
| 47 | 20 | it("should create a rule with glob pattern", async () => { |
| 48 | 21 | const args = { |
| 49 | 22 | name: "TypeScript Rule", |
| @@ -53,14 +26,16 @@ | ||
| 53 | 26 | |
| 54 | 27 | await createRuleBlockImpl(args, mockExtras as any); |
| 55 | 28 | |
| 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({ | |
| 62 | 34 | globs: "**/*.{ts,tsx}", |
| 63 | 35 | }); |
| 36 | + | |
| 37 | + expect(markdown).toContain("# TypeScript Rule"); | |
| 38 | + expect(markdown).toContain("Use interfaces for object shapes"); | |
| 64 | 39 | }); |
| 65 | 40 | |
| 66 | 41 | it("should create a filename based on sanitized rule name", async () => { |
| @@ -71,8 +46,51 @@ | ||
| 71 | 46 | |
| 72 | 47 | await createRuleBlockImpl(args, mockExtras as any); |
| 73 | 48 | |
| 74 | - // Check that the filename is sanitized | |
| 75 | 49 | 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"); | |
| 77 | 95 | }); |
| 78 | 96 | }); |
modified core/tools/implementations/createRuleBlock.ts +22 −17
| @@ -1,4 +1,3 @@ | ||
| 1 | -import { ConfigYaml } from "@continuedev/config-yaml"; | |
| 2 | 1 | import * as YAML from "yaml"; |
| 3 | 2 | import { ToolImpl } from "."; |
| 4 | 3 | import { joinPathsToUri } from "../../util/uri"; |
| @@ -6,6 +5,7 @@ | ||
| 6 | 5 | export interface CreateRuleBlockArgs { |
| 7 | 6 | name: string; |
| 8 | 7 | rule: string; |
| 8 | + description: string; | |
| 9 | 9 | globs?: string; |
| 10 | 10 | } |
| 11 | 11 | |
| @@ -19,41 +19,46 @@ | ||
| 19 | 19 | .replace(/[^a-z0-9\s-]/g, "") |
| 20 | 20 | .replace(/\s+/g, "-"); |
| 21 | 21 | |
| 22 | - const ruleObject = { | |
| 23 | - name: args.name, | |
| 24 | - rule: args.rule, | |
| 25 | - ...(args.globs ? { globs: args.globs.trim() } : {}), | |
| 26 | - }; | |
| 22 | + const fileExtension = "md"; | |
| 27 | 23 | |
| 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> = {}; | |
| 34 | 25 | |
| 35 | - const ruleYaml = YAML.stringify(ruleBlock); | |
| 26 | + if (args.globs) { | |
| 27 | + frontmatter.globs = args.globs.trim(); | |
| 28 | + } | |
| 36 | 29 | |
| 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 | +`; | |
| 37 | 42 | const [localContinueDir] = await extras.ide.getWorkspaceDirs(); |
| 38 | 43 | const rulesDirUri = joinPathsToUri( |
| 39 | 44 | localContinueDir, |
| 40 | 45 | ".continue", |
| 41 | 46 | "rules", |
| 42 | - `${safeRuleName}.yaml`, | |
| 47 | + `${safeRuleName}.${fileExtension}`, | |
| 43 | 48 | ); |
| 44 | 49 | |
| 45 | - await extras.ide.writeFile(rulesDirUri, ruleYaml); | |
| 50 | + await extras.ide.writeFile(rulesDirUri, fileContent); | |
| 46 | 51 | await extras.ide.openFile(rulesDirUri); |
| 47 | 52 | |
| 48 | 53 | return [ |
| 49 | 54 | { |
| 50 | 55 | name: "New Rule Block", |
| 51 | - description: "", // No description throws an error in the GUI | |
| 56 | + description: args.description || "", | |
| 52 | 57 | uri: { |
| 53 | 58 | type: "file", |
| 54 | 59 | value: rulesDirUri, |
| 55 | 60 | }, |
| 56 | - content: "Rule created successfully", | |
| 61 | + content: `Rule created successfully`, | |
| 57 | 62 | }, |
| 58 | 63 | ]; |
| 59 | 64 | }; |
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 @@ | ||
| 6 | 6 | prefixPercentage: 0.3, |
| 7 | 7 | maxSuffixPercentage: 0.2, |
| 8 | 8 | debounceDelay: 350, |
| 9 | + modelTimeout: 150, | |
| 9 | 10 | multilineCompletions: "auto", |
| 10 | 11 | // @deprecated TO BE REMOVED |
| 11 | 12 | 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 @@ | ||
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@xenova/transformers": "^2.14.0" |
| 13 | + }, | |
| 14 | + "engines": { | |
| 15 | + "node": ">=20.19.0" | |
| 13 | 16 | } |
| 14 | 17 | }, |
| 15 | 18 | "node_modules/@huggingface/jinja": { |
| @@ -105,6 +108,78 @@ | ||
| 105 | 108 | "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz", |
| 106 | 109 | "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==" |
| 107 | 110 | }, |
| 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 | + }, | |
| 108 | 183 | "node_modules/base64-js": { |
| 109 | 184 | "version": "1.5.1", |
| 110 | 185 | "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", |
| @@ -444,9 +519,10 @@ | ||
| 444 | 519 | } |
| 445 | 520 | }, |
| 446 | 521 | "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", | |
| 450 | 526 | "dependencies": { |
| 451 | 527 | "chownr": "^1.1.1", |
| 452 | 528 | "mkdirp-classic": "^0.5.2", |
| @@ -503,11 +579,6 @@ | ||
| 503 | 579 | "once": "^1.3.1" |
| 504 | 580 | } |
| 505 | 581 | }, |
| 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 | - }, | |
| 511 | 582 | "node_modules/rc": { |
| 512 | 583 | "version": "1.2.8", |
| 513 | 584 | "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", |
| @@ -642,12 +713,16 @@ | ||
| 642 | 713 | } |
| 643 | 714 | }, |
| 644 | 715 | "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", | |
| 648 | 720 | "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" | |
| 651 | 726 | } |
| 652 | 727 | }, |
| 653 | 728 | "node_modules/string_decoder": { |
| @@ -667,13 +742,17 @@ | ||
| 667 | 742 | } |
| 668 | 743 | }, |
| 669 | 744 | "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", | |
| 673 | 749 | "dependencies": { |
| 674 | - "mkdirp-classic": "^0.5.2", | |
| 675 | 750 | "pump": "^3.0.0", |
| 676 | 751 | "tar-stream": "^3.1.5" |
| 752 | + }, | |
| 753 | + "optionalDependencies": { | |
| 754 | + "bare-fs": "^4.0.1", | |
| 755 | + "bare-path": "^3.0.0" | |
| 677 | 756 | } |
| 678 | 757 | }, |
| 679 | 758 | "node_modules/tar-stream": { |
| @@ -686,6 +765,15 @@ | ||
| 686 | 765 | "streamx": "^2.15.0" |
| 687 | 766 | } |
| 688 | 767 | }, |
| 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 | + }, | |
| 689 | 777 | "node_modules/tunnel-agent": { |
| 690 | 778 | "version": "0.6.0", |
| 691 | 779 | "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 @@ | ||
| 6 | 6 | |
| 7 | 7 | # The User Settings Page |
| 8 | 8 | |
| 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. | |
| 10 | 10 | |
| 11 | - | |
| 11 | + | |
| 12 | 12 | |
| 13 | -Which takes you to this page: | |
| 13 | +Which takes you to this page (select the "Settings" tab): | |
| 14 | 14 | |
| 15 | 15 |  |
| 16 | 16 | |
| @@ -26,7 +26,15 @@ | ||
| 26 | 26 | - `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default. |
| 27 | 27 | - `Font Size`: Specifies base font size for UI elements |
| 28 | 28 | - `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. | |
| 30 | 38 | |
| 31 | 39 | <!-- - `Use autocomplete cache`: If on, caches completions. --> |
| 32 | 40 | <!-- - `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 @@ | ||
| 47 | 47 | Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other |
| 48 | 48 | `uses` clauses or explicit blocks of that type. |
| 49 | 49 | |
| 50 | -:::info | |
| 51 | -Note that local assistants cannot use blocks that require organization-level secrets. | |
| 52 | -::: | |
| 53 | - | |
| 54 | 50 | For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. |
| 55 | 51 | |
| 56 | 52 | ```yaml title="Assistant models section" |
| @@ -85,6 +81,12 @@ | ||
| 85 | 81 | You can find many examples of each of these block types on |
| 86 | 82 | the [Continue Explore Page](https://hub.continue.dev/explore/models) |
| 87 | 83 | |
| 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 | + | |
| 88 | 90 | ### Inputs |
| 89 | 91 | |
| 90 | 92 | 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 @@ | ||
| 111 | 113 | TEMP: 0.9 |
| 112 | 114 | ``` |
| 113 | 115 | |
| 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`. | |
| 115 | 117 | |
| 116 | 118 | ### Overrides |
| 117 | 119 | |
| @@ -186,6 +188,7 @@ | ||
| 186 | 188 | not currently used. |
| 187 | 189 | - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on |
| 188 | 190 | 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. | |
| 189 | 192 | - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are |
| 190 | 193 | `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ |
| 191 | 194 | `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ |
| @@ -204,7 +207,6 @@ | ||
| 204 | 207 | - `topP`: The cumulative probability for nucleus sampling. |
| 205 | 208 | - `topK`: Maximum number of tokens considered at each step. |
| 206 | 209 | - `stop`: An array of stop tokens that will terminate the completion. |
| 207 | - - `n`: Number of completions to generate. | |
| 208 | 210 | - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models. |
| 209 | 211 | - `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. |
| 210 | 212 | - `requestOptions`: HTTP request options specific to the model. |
| @@ -405,7 +407,7 @@ | ||
| 405 | 407 | - `destination` (**required**): The destination/endpoint that will receive the data. Can be: |
| 406 | 408 | - an HTTP endpoint that will receive a POST request with a JSON blob |
| 407 | 409 | - 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` | |
| 409 | 411 | - `events`: an array of event names to include. Defaults to all events if not specified. |
| 410 | 412 | - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file |
| 411 | 413 | contents, prompts, and completions. Defaults to `all` |
modified docs/docs/troubleshooting.mdx +2 −2
| @@ -7,8 +7,6 @@ | ||
| 7 | 7 | import TabItem from "@theme/TabItem"; |
| 8 | 8 | import Tabs from "@theme/Tabs"; |
| 9 | 9 | |
| 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 | - | |
| 12 | 10 | 1. [Check the logs](#check-the-logs) |
| 13 | 11 | 2. [Try the latest pre-release](#download-the-latest-pre-release) |
| 14 | 12 | 3. [Download an older version](#download-an-older-version) |
| @@ -122,6 +120,8 @@ | ||
| 122 | 120 | |
| 123 | 121 | You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. |
| 124 | 122 | |
| 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 | + | |
| 125 | 125 | #### VS Code Proxy Settings |
| 126 | 126 | |
| 127 | 127 | 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 @@ | ||
| 65 | 65 | ], |
| 66 | 66 | ], |
| 67 | 67 | |
| 68 | + scripts: [ | |
| 69 | + { | |
| 70 | + src: "/scripts/custom-reo.js", // it references from static folder | |
| 71 | + }, | |
| 72 | + ], | |
| 73 | + | |
| 68 | 74 | themeConfig: |
| 69 | 75 | /** @type {import("@docusaurus/preset-classic").ThemeConfig} */ |
| 70 | 76 | ({ |
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 @@ | ||
| 1 | 1 | <component name="ProjectRunConfigurationManager"> |
| 2 | 2 | <configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType"> |
| 3 | - <option name="SCRIPT_TEXT" value="cross-env 'PROJECT_DIR="$PROJECT_DIR$"' node core-dev-server.js" /> | |
| 3 | + <option name="SCRIPT_TEXT" value="npx cross-env 'PROJECT_DIR="$PROJECT_DIR$"' node core-dev-server.js" /> | |
| 4 | 4 | <option name="INDEPENDENT_SCRIPT_PATH" value="true" /> |
| 5 | 5 | <option name="SCRIPT_PATH" value="" /> |
| 6 | 6 | <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 @@ | ||
| 173 | 173 | ./gradlew test |
| 174 | 174 | ``` |
| 175 | 175 | |
| 176 | +Run a single test | |
| 177 | + | |
| 178 | +```sh | |
| 179 | +./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME" | |
| 180 | +``` | |
| 181 | + | |
| 176 | 182 | #### Identifying selectors |
| 177 | 183 | |
| 178 | 184 | While the `runIdeForUiTests` task is running, you can visit the following URL |
modified extensions/intellij/build.gradle.kts +4 −0
| @@ -42,10 +42,12 @@ | ||
| 42 | 42 | implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0") |
| 43 | 43 | testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") |
| 44 | 44 | testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion") |
| 45 | + testImplementation("io.mockk:mockk:1.14.2") | |
| 45 | 46 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0") |
| 46 | 47 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2") |
| 47 | 48 | testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0") |
| 48 | 49 | implementation("com.automation-remarks:video-recorder-junit5:2.0") |
| 50 | + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") | |
| 49 | 51 | |
| 50 | 52 | |
| 51 | 53 | // Exclude vulnerable Log4j from all dependencies |
| @@ -62,6 +64,7 @@ | ||
| 62 | 64 | // Add Log4j 2.x explicitly |
| 63 | 65 | implementation("org.apache.logging.log4j:log4j-core:2.20.0") |
| 64 | 66 | implementation("org.apache.logging.log4j:log4j-api:2.20.0") |
| 67 | + testImplementation(kotlin("test")) | |
| 65 | 68 | } |
| 66 | 69 | |
| 67 | 70 | // Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for |
| @@ -162,6 +165,7 @@ | ||
| 162 | 165 | // This is to ensure we load the GUI with OSR enabled. We have logic that |
| 163 | 166 | // renders with OSR disabled below a particular IDE version. |
| 164 | 167 | // See ContinueExtensionSettingsService.kt for more info. |
| 168 | + // Currently commented out however since test fail in CI with this version | |
| 165 | 169 | // intellij { |
| 166 | 170 | // version.set("2024.1") |
| 167 | 171 | // } |
modified extensions/intellij/gradle.properties +2 −2
| @@ -3,13 +3,13 @@ | ||
| 3 | 3 | pluginName=continue-intellij-extension |
| 4 | 4 | pluginRepositoryUrl=https://github.com/continuedev/continue |
| 5 | 5 | # SemVer format -> https://semver.org |
| 6 | -pluginVersion=1.0.17 | |
| 6 | +pluginVersion=1.0.18 | |
| 7 | 7 | # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html |
| 8 | 8 | pluginSinceBuild=223 |
| 9 | 9 | # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension |
| 10 | 10 | platformType=IC |
| 11 | 11 | platformVersion=2022.3.3 |
| 12 | -#org.gradle.java.home=/opt/homebrew/opt/openjdk@17 | |
| 12 | +# org.gradle.java.home=/opt/homebrew/opt/openjdk@17 | |
| 13 | 13 | #platformVersion = LATEST-EAP-SNAPSHOT |
| 14 | 14 | # Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html |
| 15 | 15 | # 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 @@ | ||
| 11 | 11 | class ContinueActionPromote : ActionPromoter { |
| 12 | 12 | |
| 13 | 13 | 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 }) { | |
| 18 | 16 | 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>() | |
| 21 | 19 | } |
| 22 | - return actions.filterIsInstance<AcceptAutocompleteAction>() | |
| 23 | 20 | } |
| 21 | + | |
| 22 | + val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>() | |
| 23 | + if (rejectDiffActions.isNotEmpty()) { | |
| 24 | + return rejectDiffActions | |
| 25 | + } | |
| 26 | + | |
| 27 | + return null | |
| 24 | 28 | } |
| 25 | 29 | } |
| 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.actions |
| 2 | 2 | |
| 3 | 3 | import com.github.continuedev.continueintellijextension.editor.DiffStreamService |
| 4 | -import com.github.continuedev.continueintellijextension.services.ContinuePluginService | |
| 5 | 4 | import com.intellij.openapi.actionSystem.AnAction |
| 6 | 5 | import com.intellij.openapi.actionSystem.AnActionEvent |
| 7 | 6 | import com.intellij.openapi.actionSystem.PlatformDataKeys |
| 8 | -import com.intellij.openapi.components.ServiceManager | |
| 9 | 7 | import com.intellij.openapi.components.service |
| 10 | 8 | 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 | + | |
| 23 | 10 | |
| 24 | 11 | class AcceptDiffAction : AnAction() { |
| 25 | 12 | override fun actionPerformed(e: AnActionEvent) { |
| @@ -29,7 +16,7 @@ | ||
| 29 | 16 | |
| 30 | 17 | private fun acceptHorizontalDiff(e: AnActionEvent) { |
| 31 | 18 | val continuePluginService = getPluginService(e.project) ?: return |
| 32 | - continuePluginService?.diffManager?.acceptDiff(null) | |
| 19 | + continuePluginService.diffManager?.acceptDiff(null) | |
| 33 | 20 | } |
| 34 | 21 | |
| 35 | 22 | private fun acceptVerticalDiff(e: AnActionEvent) { |
| @@ -61,28 +48,6 @@ | ||
| 61 | 48 | } |
| 62 | 49 | } |
| 63 | 50 | |
| 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 | -} | |
| 86 | 51 | |
| 87 | 52 | class FocusContinueInputWithoutClearAction : AnAction() { |
| 88 | 53 | override fun actionPerformed(e: AnActionEvent) { |
| @@ -134,8 +99,11 @@ | ||
| 134 | 99 | if (logFile.exists()) { |
| 135 | 100 | val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile) |
| 136 | 101 | if (virtualFile != null) { |
| 137 | - com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true) | |
| 102 | + FileEditorManager.getInstance(project).openFile(virtualFile, true) | |
| 138 | 103 | } |
| 139 | 104 | } |
| 140 | 105 | } |
| 141 | 106 | } |
| 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.activities |
| 2 | 2 | |
| 3 | -import IntelliJIDE | |
| 4 | 3 | import com.intellij.openapi.fileEditor.FileEditorManagerListener |
| 5 | 4 | import com.github.continuedev.continueintellijextension.auth.AuthListener |
| 6 | 5 | 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 @@ | ||
| 62 | 62 | file.createNewFile() |
| 63 | 63 | } |
| 64 | 64 | file.writeText(replacement) |
| 65 | - openDiffWindow(URI(filepath).toString(), file.toURI().toString(), stepIndex) | |
| 65 | + openDiffWindow(UriUtils.parseUri(filepath).toString(), file.toURI().toString(), stepIndex) | |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | 68 | private fun cleanUpFile(file2: String) { |
| @@ -80,7 +80,8 @@ | ||
| 80 | 80 | val diffInfo = diffInfoMap[file] ?: return |
| 81 | 81 | |
| 82 | 82 | // 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 | |
| 84 | 85 | val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return |
| 85 | 86 | WriteCommandAction.runWriteCommandAction(project) { |
| 86 | 87 | document.setText(File(file).readText()) |
| @@ -107,7 +108,7 @@ | ||
| 107 | 108 | ) |
| 108 | 109 | continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex) |
| 109 | 110 | continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex) |
| 110 | - | |
| 111 | + continuePluginService.coreMessenger?.request("cancelApply", null, null) {} | |
| 111 | 112 | cleanUpFile(file) |
| 112 | 113 | } |
| 113 | 114 | |
| @@ -119,8 +120,8 @@ | ||
| 119 | 120 | lastFile2 = file2 |
| 120 | 121 | |
| 121 | 122 | // 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()) | |
| 124 | 125 | |
| 125 | 126 | // Create a SimpleDiffRequest and populate it with the DiffContents and titles |
| 126 | 127 | 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 @@ | ||
| 2 | 2 | |
| 3 | 3 | import com.intellij.openapi.editor.colors.EditorColors |
| 4 | 4 | import com.intellij.openapi.editor.colors.EditorColorsManager |
| 5 | +import com.intellij.openapi.editor.colors.CodeInsightColors | |
| 5 | 6 | import java.awt.Color |
| 6 | 7 | import kotlin.math.max |
| 7 | 8 | import kotlin.math.min |
| 8 | 9 | import com.intellij.ui.JBColor |
| 9 | 10 | import com.intellij.ui.ColorUtil |
| 11 | +import kotlin.math.roundToInt | |
| 10 | 12 | |
| 11 | 13 | class GetTheme { |
| 12 | 14 | fun getSecondaryDark(): Color { |
| @@ -38,64 +40,173 @@ | ||
| 38 | 40 | return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground |
| 39 | 41 | } |
| 40 | 42 | |
| 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 | |
| 44 | 46 | } |
| 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?> { | |
| 45 | 101 | try { |
| 102 | + val editorScheme = EditorColorsManager.getInstance().globalScheme | |
| 103 | + | |
| 46 | 104 | val background = JBColor.background() |
| 47 | 105 | val foreground = JBColor.foreground() |
| 48 | 106 | |
| 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") | |
| 51 | 109 | |
| 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") | |
| 54 | 112 | |
| 55 | - val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255)) | |
| 113 | + val buttonForeground = namedColor("Button.default.startForeground") | |
| 114 | + ?: namedColor("Button.default.foreground") | |
| 56 | 115 | |
| 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) | |
| 60 | 120 | |
| 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) | |
| 63 | 123 | |
| 64 | - val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220)) | |
| 124 | + val badgeBackground = namedColor("Badge.background") | |
| 125 | + val badgeForeground = namedColor("Badge.foreground") | |
| 65 | 126 | |
| 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") | |
| 67 | 129 | |
| 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") | |
| 71 | 139 | |
| 72 | - "--vscode-button-background" to toHex(buttonBackground), | |
| 73 | - "--vscode-button-foreground" to toHex(buttonForeground), | |
| 140 | + val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground") | |
| 74 | 141 | |
| 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") | |
| 76 | 147 | |
| 77 | - "--vscode-quickInputList-focusForeground" to toHex(foreground), | |
| 78 | - "--vscode-quickInput-background" to toHex(inputBackground), | |
| 148 | + val link = namedColor("Link.activeForeground") | |
| 79 | 149 | |
| 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") | |
| 82 | 158 | |
| 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") | |
| 88 | 160 | |
| 89 | - "--vscode-commandCenter-activeBorder" to toHex(focusBorder), | |
| 90 | - "--vscode-commandCenter-inactiveBorder" to toHex(border), | |
| 161 | + val editorBackground = editorScheme.defaultBackground | |
| 162 | + val editorForeground = editorScheme.defaultForeground | |
| 91 | 163 | |
| 92 | - "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40" | |
| 93 | - ) | |
| 164 | + val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor | |
| 94 | 165 | |
| 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) } | |
| 95 | 207 | return theme |
| 96 | 208 | } catch (error: Error) { |
| 97 | 209 | return mapOf() |
| 98 | 210 | } |
| 99 | - | |
| 100 | 211 | } |
| 101 | 212 | } |
| 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 @@ | ||
| 7 | 7 | import kotlinx.coroutines.Dispatchers |
| 8 | 8 | import kotlinx.coroutines.withContext |
| 9 | 9 | import java.io.BufferedReader |
| 10 | -import java.io.File | |
| 11 | 10 | import java.io.InputStreamReader |
| 12 | -import java.net.URI | |
| 13 | 11 | |
| 14 | 12 | class GitService( |
| 15 | 13 | private val project: Project, |
| @@ -52,7 +50,7 @@ | ||
| 52 | 50 | } else { |
| 53 | 51 | ProcessBuilder("git", "diff", "--cached") |
| 54 | 52 | } |
| 55 | - builder.directory(File(URI(workspaceDir))) | |
| 53 | + builder.directory(UriUtils.uriToFile(workspaceDir)) | |
| 56 | 54 | val process = withContext(Dispatchers.IO) { |
| 57 | 55 | builder.start() |
| 58 | 56 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +39 −210
| @@ -1,13 +1,11 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.`continue` |
| 2 | 2 | |
| 3 | -import IntelliJIDE | |
| 4 | 3 | import com.github.continuedev.continueintellijextension.* |
| 5 | 4 | import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable |
| 6 | 5 | import com.github.continuedev.continueintellijextension.activities.showTutorial |
| 7 | -import com.github.continuedev.continueintellijextension.auth.AuthListener | |
| 8 | 6 | import com.github.continuedev.continueintellijextension.auth.ContinueAuthService |
| 9 | -import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler | |
| 10 | 7 | import com.github.continuedev.continueintellijextension.editor.DiffStreamService |
| 8 | +import com.github.continuedev.continueintellijextension.editor.EditorUtils | |
| 11 | 9 | import com.github.continuedev.continueintellijextension.protocol.* |
| 12 | 10 | import com.github.continuedev.continueintellijextension.services.* |
| 13 | 11 | import com.github.continuedev.continueintellijextension.utils.* |
| @@ -16,21 +14,15 @@ | ||
| 16 | 14 | import com.intellij.openapi.command.WriteCommandAction |
| 17 | 15 | import com.intellij.openapi.components.ServiceManager |
| 18 | 16 | import com.intellij.openapi.components.service |
| 19 | -import com.intellij.openapi.editor.Editor | |
| 20 | 17 | import com.intellij.openapi.editor.SelectionModel |
| 21 | -import com.intellij.openapi.fileEditor.FileDocumentManager | |
| 22 | 18 | import com.intellij.openapi.fileEditor.FileEditorManager |
| 23 | 19 | import com.intellij.openapi.project.DumbAware |
| 24 | 20 | import com.intellij.openapi.project.Project |
| 25 | -import com.intellij.openapi.util.TextRange | |
| 26 | 21 | import com.intellij.openapi.vfs.VirtualFileManager |
| 27 | 22 | import com.intellij.openapi.wm.ToolWindowManager |
| 28 | 23 | import kotlinx.coroutines.* |
| 29 | 24 | import java.awt.Toolkit |
| 30 | 25 | import java.awt.datatransfer.StringSelection |
| 31 | -import java.lang.IllegalStateException | |
| 32 | -import kotlin.coroutines.resume | |
| 33 | -import kotlin.coroutines.resumeWithException | |
| 34 | 26 | |
| 35 | 27 | |
| 36 | 28 | class IdeProtocolClient( |
| @@ -39,6 +31,8 @@ | ||
| 39 | 31 | private val project: Project |
| 40 | 32 | ) : DumbAware { |
| 41 | 33 | private val ide: IDE = IntelliJIDE(project, continuePluginService) |
| 34 | + private val diffStreamService = project.service<DiffStreamService>() | |
| 35 | + | |
| 42 | 36 | |
| 43 | 37 | /** |
| 44 | 38 | * Create a dispatcher with limited parallelism to prevent UI freezing. |
| @@ -46,6 +40,7 @@ | ||
| 46 | 40 | * |
| 47 | 41 | * See this thread for details: https://github.com/continuedev/continue/issues/4098#issuecomment-2854865310 |
| 48 | 42 | */ |
| 43 | + @OptIn(ExperimentalCoroutinesApi::class) | |
| 49 | 44 | private val limitedDispatcher = Dispatchers.IO.limitedParallelism(4) |
| 50 | 45 | |
| 51 | 46 | init { |
| @@ -96,6 +91,15 @@ | ||
| 96 | 91 | respond(jsonData) |
| 97 | 92 | } |
| 98 | 93 | |
| 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 | + | |
| 99 | 103 | "getIdeSettings" -> { |
| 100 | 104 | val settings = ide.getIdeSettings() |
| 101 | 105 | respond(settings) |
| @@ -443,20 +447,32 @@ | ||
| 443 | 447 | "acceptDiff" -> { |
| 444 | 448 | val params = Gson().fromJson( |
| 445 | 449 | dataElement.toString(), |
| 446 | - AcceptDiffParams::class.java | |
| 450 | + AcceptOrRejectDiffPayload::class.java | |
| 447 | 451 | ) |
| 448 | 452 | val filepath = params.filepath; |
| 449 | 453 | |
| 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) | |
| 451 | 461 | } |
| 452 | 462 | |
| 453 | 463 | "rejectDiff" -> { |
| 454 | 464 | val params = Gson().fromJson( |
| 455 | 465 | dataElement.toString(), |
| 456 | - RejectDiffParams::class.java | |
| 466 | + AcceptOrRejectDiffPayload::class.java | |
| 457 | 467 | ) |
| 458 | 468 | 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 | + | |
| 460 | 476 | } |
| 461 | 477 | |
| 462 | 478 | "applyToFile" -> { |
| @@ -464,141 +480,13 @@ | ||
| 464 | 480 | dataElement.toString(), |
| 465 | 481 | ApplyToFileParams::class.java |
| 466 | 482 | ) |
| 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 | - } | |
| 520 | 483 | |
| 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 | |
| 600 | 489 | ) |
| 601 | - | |
| 602 | 490 | respond(null) |
| 603 | 491 | } |
| 604 | 492 | |
| @@ -612,52 +500,15 @@ | ||
| 612 | 500 | } |
| 613 | 501 | } |
| 614 | 502 | |
| 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 | - | |
| 653 | 503 | fun sendHighlightedCode(edit: Boolean = false) { |
| 654 | - val rif = getHighlightedCode() ?: return | |
| 504 | + val editor = EditorUtils.getEditor(project) | |
| 505 | + val rif = editor?.getHighlightedRIF() ?: return | |
| 655 | 506 | |
| 656 | 507 | continuePluginService.sendToWebview( |
| 657 | 508 | "highlightedCode", |
| 658 | - mapOf( | |
| 659 | - "rangeInFileWithContents" to rif, | |
| 660 | - "edit" to edit | |
| 509 | + HighlightedCodePayload( | |
| 510 | + rangeInFileWithContents = rif, | |
| 511 | + shouldRun = edit | |
| 661 | 512 | ) |
| 662 | 513 | ) |
| 663 | 514 | } |
| @@ -667,28 +518,6 @@ | ||
| 667 | 518 | continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) |
| 668 | 519 | } |
| 669 | 520 | |
| 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 | - } | |
| 692 | 521 | |
| 693 | 522 | fun deleteAtIndex(index: Int) { |
| 694 | 523 | 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 | + | |
| 1 | 3 | import com.github.continuedev.continueintellijextension.* |
| 2 | 4 | import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath |
| 3 | 5 | import com.github.continuedev.continueintellijextension.constants.ContinueConstants |
| @@ -167,7 +169,7 @@ | ||
| 167 | 169 | // Find any .continuerc.json files |
| 168 | 170 | for (file in contents) { |
| 169 | 171 | if (file.endsWith(".continuerc.json")) { |
| 170 | - val fileContent = File(URI(file)).readText() | |
| 172 | + val fileContent = UriUtils.uriToFile(file).readText() | |
| 171 | 173 | configs.add(fileContent) |
| 172 | 174 | } |
| 173 | 175 | } |
| @@ -178,12 +180,12 @@ | ||
| 178 | 180 | } |
| 179 | 181 | |
| 180 | 182 | override suspend fun fileExists(filepath: String): Boolean { |
| 181 | - val file = File(URI(filepath)) | |
| 183 | + val file = UriUtils.uriToFile(filepath) | |
| 182 | 184 | return file.exists() |
| 183 | 185 | } |
| 184 | 186 | |
| 185 | 187 | override suspend fun writeFile(path: String, contents: String) { |
| 186 | - val file = File(URI(path)) | |
| 188 | + val file = UriUtils.uriToFile(path) | |
| 187 | 189 | file.parentFile?.mkdirs() |
| 188 | 190 | file.writeText(contents) |
| 189 | 191 | } |
| @@ -201,7 +203,7 @@ | ||
| 201 | 203 | |
| 202 | 204 | override suspend fun openFile(path: String) { |
| 203 | 205 | // Convert URI path to absolute file path |
| 204 | - val filePath = File(URI(path)).absolutePath | |
| 206 | + val filePath = UriUtils.uriToFile(path).absolutePath | |
| 205 | 207 | // Find the file using the absolute path |
| 206 | 208 | val file = withContext(Dispatchers.IO) { |
| 207 | 209 | LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath) |
| @@ -216,7 +218,7 @@ | ||
| 216 | 218 | |
| 217 | 219 | override suspend fun openUrl(url: String) { |
| 218 | 220 | withContext(Dispatchers.IO) { |
| 219 | - Desktop.browse(java.net.URI(url)) | |
| 221 | + Desktop.browse(URI(url)) | |
| 220 | 222 | } |
| 221 | 223 | } |
| 222 | 224 | |
| @@ -226,7 +228,8 @@ | ||
| 226 | 228 | |
| 227 | 229 | override suspend fun saveFile(filepath: String) { |
| 228 | 230 | 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 | |
| 230 | 233 | val fileDocumentManager = FileDocumentManager.getInstance() |
| 231 | 234 | val document = fileDocumentManager.getDocument(file) |
| 232 | 235 | |
| @@ -239,7 +242,7 @@ | ||
| 239 | 242 | override suspend fun readFile(filepath: String): String { |
| 240 | 243 | return try { |
| 241 | 244 | 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) | |
| 243 | 246 | if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) { |
| 244 | 247 | return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text |
| 245 | 248 | } |
| @@ -249,7 +252,7 @@ | ||
| 249 | 252 | if (content != null) { |
| 250 | 253 | content |
| 251 | 254 | } else { |
| 252 | - val file = File(URI(filepath)) | |
| 255 | + val file = UriUtils.uriToFile(filepath) | |
| 253 | 256 | if (!file.exists() || file.isDirectory) return "" |
| 254 | 257 | withContext(Dispatchers.IO) { |
| 255 | 258 | FileInputStream(file).use { fis -> |
| @@ -455,7 +458,7 @@ | ||
| 455 | 458 | return withContext(Dispatchers.IO) { |
| 456 | 459 | try { |
| 457 | 460 | val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD") |
| 458 | - builder.directory(File(URI(dir))) | |
| 461 | + builder.directory(UriUtils.uriToFile(dir)) | |
| 459 | 462 | val process = builder.start() |
| 460 | 463 | val reader = BufferedReader(InputStreamReader(process.inputStream)) |
| 461 | 464 | val output = reader.readLine() |
| @@ -485,7 +488,7 @@ | ||
| 485 | 488 | |
| 486 | 489 | override suspend fun getRepoName(dir: String): String? { |
| 487 | 490 | return withContext(Dispatchers.IO) { |
| 488 | - val directory = File(URI(dir)) | |
| 491 | + val directory = UriUtils.uriToFile(dir) | |
| 489 | 492 | val targetDir = if (directory.isFile) directory.parentFile else directory |
| 490 | 493 | val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url") |
| 491 | 494 | builder.directory(targetDir) |
| @@ -549,7 +552,7 @@ | ||
| 549 | 552 | override suspend fun getGitRootPath(dir: String): String? { |
| 550 | 553 | return withContext(Dispatchers.IO) { |
| 551 | 554 | val builder = ProcessBuilder("git", "rev-parse", "--show-toplevel") |
| 552 | - builder.directory(File(URI(dir))) | |
| 555 | + builder.directory(UriUtils.uriToFile(dir)) | |
| 553 | 556 | val process = builder.start() |
| 554 | 557 | |
| 555 | 558 | val reader = BufferedReader(InputStreamReader(process.inputStream)) |
| @@ -560,7 +563,7 @@ | ||
| 560 | 563 | } |
| 561 | 564 | |
| 562 | 565 | 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 { | |
| 564 | 567 | listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value) |
| 565 | 568 | } ?: emptyList() |
| 566 | 569 | |
| @@ -569,7 +572,7 @@ | ||
| 569 | 572 | |
| 570 | 573 | override suspend fun getFileStats(files: List<String>): Map<String, FileStats> { |
| 571 | 574 | return files.associateWith { file -> |
| 572 | - FileStats(File(URI(file)).lastModified(), File(URI(file)).length()) | |
| 575 | + FileStats(UriUtils.uriToFile(file).lastModified(), UriUtils.uriToFile(file).length()) | |
| 573 | 576 | } |
| 574 | 577 | } |
| 575 | 578 | |
| @@ -587,7 +590,7 @@ | ||
| 587 | 590 | } |
| 588 | 591 | |
| 589 | 592 | 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) | |
| 591 | 594 | |
| 592 | 595 | file?.let { |
| 593 | 596 | 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 2 | |
| 3 | +import com.github.continuedev.continueintellijextension.ApplyState | |
| 4 | +import com.github.continuedev.continueintellijextension.ApplyStateStatus | |
| 5 | +import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload | |
| 3 | 6 | import com.github.continuedev.continueintellijextension.services.ContinuePluginService |
| 4 | 7 | import com.intellij.openapi.application.ApplicationManager |
| 5 | 8 | import com.intellij.openapi.command.WriteCommandAction |
| @@ -12,7 +15,6 @@ | ||
| 12 | 15 | import com.intellij.openapi.fileEditor.FileEditorManager |
| 13 | 16 | import com.intellij.openapi.fileEditor.TextEditor |
| 14 | 17 | import com.intellij.openapi.project.Project |
| 15 | -import com.intellij.openapi.vfs.VirtualFile | |
| 16 | 18 | import kotlin.math.max |
| 17 | 19 | import kotlin.math.min |
| 18 | 20 | |
| @@ -35,41 +37,41 @@ | ||
| 35 | 37 | var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null |
| 36 | 38 | ) |
| 37 | 39 | |
| 40 | + private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf() | |
| 38 | 41 | private var curLine = CurLineState(startLine) |
| 39 | 42 | private var isRunning: Boolean = false |
| 40 | 43 | private var hasAcceptedOrRejectedBlock: Boolean = false |
| 41 | - | |
| 42 | 44 | 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) | |
| 44 | 47 | |
| 45 | - private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor) | |
| 46 | - private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor) | |
| 47 | 48 | |
| 48 | 49 | init { |
| 49 | 50 | initUnfinishedRangeHighlights() |
| 50 | 51 | } |
| 51 | 52 | |
| 52 | - private fun sendUpdate(status: String) { | |
| 53 | - if(this.streamId == null) { | |
| 53 | + private fun sendUpdate(status: ApplyStateStatus) { | |
| 54 | + if (streamId == null) { | |
| 54 | 55 | return |
| 55 | 56 | } |
| 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) | |
| 66 | 69 | } |
| 67 | 70 | |
| 68 | 71 | fun acceptAll() { |
| 69 | - editor.markupModel.removeAllHighlighters(); | |
| 70 | - sendUpdate("closed") | |
| 71 | - | |
| 72 | - resetState() | |
| 72 | + ApplicationManager.getApplication().invokeLater { | |
| 73 | + diffBlocks.toList().forEach { it.handleAccept() } | |
| 74 | + } | |
| 73 | 75 | } |
| 74 | 76 | |
| 75 | 77 | fun rejectAll() { |
| @@ -77,26 +79,42 @@ | ||
| 77 | 79 | // to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple |
| 78 | 80 | // way to undo our changes without also undoing the diff that the user accepted or rejected. |
| 79 | 81 | if (hasAcceptedOrRejectedBlock) { |
| 80 | - diffBlocks.forEach { it.handleReject() } | |
| 82 | + ApplicationManager.getApplication().invokeLater { | |
| 83 | + val blocksToReject = diffBlocks.toList() | |
| 84 | + blocksToReject.toList().forEach { it.handleReject() } | |
| 85 | + } | |
| 81 | 86 | } else { |
| 82 | 87 | undoChanges() |
| 88 | + // We have to manually call `handleClosedState`, but above, | |
| 89 | + // this is done by invoking the button handlers | |
| 90 | + setClosed() | |
| 83 | 91 | } |
| 84 | - sendUpdate("closed") | |
| 85 | - | |
| 86 | - resetState() | |
| 87 | 92 | } |
| 88 | 93 | |
| 89 | 94 | 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 | |
| 91 | 101 | ) { |
| 92 | 102 | isRunning = true |
| 93 | - this.sendUpdate("streaming") | |
| 94 | - | |
| 95 | - val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) | |
| 96 | - val virtualFile = getVirtualFile() | |
| 103 | + sendUpdate(ApplyStateStatus.STREAMING) | |
| 97 | 104 | |
| 98 | 105 | 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 | |
| 100 | 118 | ) { response -> |
| 101 | 119 | if (!isRunning) return@request |
| 102 | 120 | |
| @@ -104,7 +122,6 @@ | ||
| 104 | 122 | |
| 105 | 123 | if (response["done"] as? Boolean == true) { |
| 106 | 124 | handleFinishedResponse() |
| 107 | - sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") | |
| 108 | 125 | return@request |
| 109 | 126 | } |
| 110 | 127 | |
| @@ -113,6 +130,9 @@ | ||
| 113 | 130 | } |
| 114 | 131 | |
| 115 | 132 | private fun initUnfinishedRangeHighlights() { |
| 133 | + val editorUtils = EditorUtils(editor) | |
| 134 | + val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888) | |
| 135 | + | |
| 116 | 136 | for (i in startLine..endLine) { |
| 117 | 137 | val highlighter = editor.markupModel.addLineHighlighter( |
| 118 | 138 | unfinishedKey, min( |
| @@ -155,10 +175,11 @@ | ||
| 155 | 175 | } |
| 156 | 176 | |
| 157 | 177 | if (diffBlocks.isEmpty()) { |
| 158 | - sendUpdate("closed") | |
| 159 | - onClose() | |
| 178 | + setClosed() | |
| 160 | 179 | } 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) | |
| 162 | 183 | } |
| 163 | 184 | } |
| 164 | 185 | |
| @@ -169,8 +190,6 @@ | ||
| 169 | 190 | ) |
| 170 | 191 | |
| 171 | 192 | diffBlocks.add(diffBlock) |
| 172 | - sendUpdate("streaming") | |
| 173 | - | |
| 174 | 193 | return diffBlock |
| 175 | 194 | } |
| 176 | 195 | |
| @@ -203,12 +222,17 @@ | ||
| 203 | 222 | } |
| 204 | 223 | |
| 205 | 224 | private fun updateProgressHighlighters(type: DiffLineType) { |
| 225 | + val editorUtils = EditorUtils(editor) | |
| 226 | + val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888) | |
| 227 | + | |
| 206 | 228 | // Update the highlighter to show the current line |
| 207 | 229 | curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) } |
| 208 | 230 | curLine.highlighter = editor.markupModel.addLineHighlighter( |
| 209 | 231 | curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST |
| 210 | 232 | ) |
| 211 | 233 | |
| 234 | + editorUtils.scrollToLine(curLine.index) | |
| 235 | + | |
| 212 | 236 | // Remove the unfinished lines highlighter |
| 213 | 237 | if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) { |
| 214 | 238 | editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0)) |
| @@ -242,15 +266,18 @@ | ||
| 242 | 266 | curLine = CurLineState(startLine) |
| 243 | 267 | isRunning = false |
| 244 | 268 | |
| 245 | - // Close the Edit input | |
| 269 | + // Close the Edit input if editing | |
| 246 | 270 | onClose() |
| 247 | 271 | } |
| 248 | 272 | |
| 249 | 273 | |
| 250 | 274 | private fun undoChanges() { |
| 275 | + if (virtualFile == null) { | |
| 276 | + return | |
| 277 | + } | |
| 278 | + | |
| 251 | 279 | WriteCommandAction.runWriteCommandAction(project) { |
| 252 | 280 | val undoManager = UndoManager.getInstance(project) |
| 253 | - val virtualFile = getVirtualFile() ?: return@runWriteCommandAction | |
| 254 | 281 | val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor |
| 255 | 282 | |
| 256 | 283 | if (undoManager.isUndoAvailable(fileEditor)) { |
| @@ -260,34 +287,9 @@ | ||
| 260 | 287 | undoManager.undo(fileEditor) |
| 261 | 288 | } |
| 262 | 289 | } |
| 263 | - sendUpdate("done") | |
| 264 | 290 | } |
| 265 | 291 | } |
| 266 | 292 | |
| 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 | - | |
| 291 | 293 | private fun handleFinishedResponse() { |
| 292 | 294 | ApplicationManager.getApplication().invokeLater { |
| 293 | 295 | // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where |
| @@ -296,6 +298,12 @@ | ||
| 296 | 298 | |
| 297 | 299 | onFinish() |
| 298 | 300 | cleanupProgressHighlighters() |
| 301 | + | |
| 302 | + if (diffBlocks.isEmpty()) { | |
| 303 | + setClosed() | |
| 304 | + } else { | |
| 305 | + sendUpdate(ApplyStateStatus.DONE) | |
| 306 | + } | |
| 299 | 307 | } |
| 300 | 308 | } |
| 301 | 309 | |
| @@ -325,4 +333,9 @@ | ||
| 325 | 333 | else -> throw Exception("Unknown diff line type: $type") |
| 326 | 334 | } |
| 327 | 335 | } |
| 336 | + | |
| 337 | + private fun setClosed() { | |
| 338 | + sendUpdate(ApplyStateStatus.CLOSED) | |
| 339 | + resetState() | |
| 340 | + } | |
| 328 | 341 | } |
| 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 2 | |
| 3 | +import com.github.continuedev.continueintellijextension.utils.toUriOrNull | |
| 4 | +import com.intellij.openapi.application.ApplicationManager | |
| 5 | +import com.intellij.openapi.command.WriteCommandAction | |
| 3 | 6 | import com.intellij.openapi.editor.Editor |
| 7 | +import com.intellij.openapi.editor.SelectionModel | |
| 4 | 8 | import com.intellij.openapi.editor.colors.TextAttributesKey |
| 5 | 9 | 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 | |
| 6 | 15 | import com.intellij.ui.JBColor |
| 16 | +import com.intellij.openapi.editor.ScrollType | |
| 7 | 17 | |
| 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 | + } | |
| 11 | 80 | } |
| 12 | -} | |
| 13 | 81 | |
| 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 | + } | |
| 17 | 142 | } |
| 18 | 143 | |
| 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 | + } | |
| 21 | 169 | } |
| 22 | 170 | } |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +1 −739
| @@ -1,336 +1,11 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.editor |
| 2 | 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 | 3 | import com.intellij.openapi.actionSystem.ActionUpdateThread |
| 11 | 4 | import com.intellij.openapi.actionSystem.AnAction |
| 12 | 5 | import com.intellij.openapi.actionSystem.AnActionEvent |
| 13 | 6 | 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 | |
| 19 | 7 | 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 | |
| 41 | 8 | |
| 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 | - */ | |
| 334 | 9 | class InlineEditAction : AnAction(), DumbAware { |
| 335 | 10 | override fun update(e: AnActionEvent) { |
| 336 | 11 | e.presentation.isEnabled = true |
| @@ -346,417 +21,4 @@ | ||
| 346 | 21 | val project = e.getData(PlatformDataKeys.PROJECT) ?: return |
| 347 | 22 | openInlineEdit(project, editor) |
| 348 | 23 | } |
| 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 @@ | ||
| 32 | 32 | private var deletionInlay: Disposable? = null |
| 33 | 33 | private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons |
| 34 | 34 | private var hasRenderedDiffBlock: Boolean = false |
| 35 | - private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false) | |
| 36 | - private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor) | |
| 37 | 35 | |
| 38 | 36 | init { |
| 39 | 37 | val (acceptBtn, rejectBtn) = createButtons() |
| @@ -78,6 +76,8 @@ | ||
| 78 | 76 | |
| 79 | 77 | |
| 80 | 78 | fun addNewLine(text: String, line: Int) { |
| 79 | + val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00) | |
| 80 | + | |
| 81 | 81 | if (line == editor.document.lineCount) { |
| 82 | 82 | editor.document.insertString(editor.document.textLength, "\n") |
| 83 | 83 | } |
| @@ -97,7 +97,7 @@ | ||
| 97 | 97 | return |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | - if (deletedLines.size > 0) { | |
| 100 | + if (deletedLines.isNotEmpty()) { | |
| 101 | 101 | renderDeletedLinesInlay() |
| 102 | 102 | } |
| 103 | 103 | |
| @@ -107,20 +107,32 @@ | ||
| 107 | 107 | } |
| 108 | 108 | |
| 109 | 109 | 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() | |
| 110 | 113 | revertDiff() |
| 114 | + | |
| 115 | + onAcceptReject(this@VerticalDiffBlock, false) | |
| 116 | + } | |
| 117 | + | |
| 118 | + fun handleAccept() { | |
| 111 | 119 | clearEditorUI() |
| 120 | + onAcceptReject(this@VerticalDiffBlock, true) | |
| 112 | 121 | } |
| 113 | 122 | |
| 123 | + | |
| 114 | 124 | private fun refreshEditor() { |
| 115 | 125 | editor.contentComponent.revalidate() |
| 116 | 126 | editor.contentComponent.repaint() |
| 117 | 127 | } |
| 118 | 128 | |
| 119 | 129 | 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 | |
| 122 | 134 | |
| 123 | - val disposable = editorComponentInlaysManager.insert(startLine, textArea, true) | |
| 135 | + val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true) | |
| 124 | 136 | deletionInlay = disposable |
| 125 | 137 | } |
| 126 | 138 | |
| @@ -154,11 +166,10 @@ | ||
| 154 | 166 | val rejectBtn = |
| 155 | 167 | createButton( |
| 156 | 168 | "${getAltKeyLabel()}${getShiftKeyLabel()}N", |
| 157 | - JBColor(0x77FF0000, 0x77FF0000) | |
| 169 | + JBColor(0xFF0000, 0xFF0000) | |
| 158 | 170 | ).apply { |
| 159 | 171 | addActionListener { |
| 160 | 172 | handleReject() |
| 161 | - onAcceptReject(this@VerticalDiffBlock, false) | |
| 162 | 173 | } |
| 163 | 174 | |
| 164 | 175 | } |
| @@ -167,14 +178,14 @@ | ||
| 167 | 178 | createButton( |
| 168 | 179 | "${getAltKeyLabel()}${ |
| 169 | 180 | getShiftKeyLabel() |
| 170 | - }Y", JBColor(0x7700BB00, 0x7700BB00) | |
| 181 | + }Y", JBColor(0x00BB00, 0x00BB00) | |
| 171 | 182 | ).apply { |
| 172 | 183 | addActionListener { |
| 173 | 184 | handleAccept() |
| 174 | - onAcceptReject(this@VerticalDiffBlock, true) | |
| 175 | 185 | } |
| 176 | 186 | } |
| 177 | 187 | |
| 188 | + | |
| 178 | 189 | return Pair(acceptBtn, rejectBtn) |
| 179 | 190 | } |
| 180 | 191 | |
| @@ -185,9 +196,6 @@ | ||
| 185 | 196 | refreshEditor() |
| 186 | 197 | } |
| 187 | 198 | |
| 188 | - private fun handleAccept() { | |
| 189 | - clearEditorUI() | |
| 190 | - } | |
| 191 | 199 | |
| 192 | 200 | private fun revertDiff() { |
| 193 | 201 | WriteCommandAction.runWriteCommandAction(project) { |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +0 −10
| @@ -15,16 +15,6 @@ | ||
| 15 | 15 | val toolCallId: String? |
| 16 | 16 | ) |
| 17 | 17 | |
| 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 | - | |
| 28 | 18 | data class InsertAtCursorParams( |
| 29 | 19 | val text: String |
| 30 | 20 | ) |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +0 −1
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension.services |
| 2 | 2 | |
| 3 | -import IntelliJIDE | |
| 4 | 3 | import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger |
| 5 | 4 | import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager |
| 6 | 5 | 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 @@ | ||
| 1 | 1 | package com.github.continuedev.continueintellijextension |
| 2 | 2 | |
| 3 | +import com.github.continuedev.continueintellijextension.editor.RangeInFileWithContents | |
| 3 | 4 | import com.google.gson.JsonElement |
| 4 | 5 | |
| 5 | 6 | enum class ToastType(val value: String) { |
| @@ -213,3 +214,45 @@ | ||
| 213 | 214 | data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int) |
| 214 | 215 | |
| 215 | 216 | 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 @@ | ||
| 78 | 78 | class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction" |
| 79 | 79 | text="Reject Diff" description="Reject Diff"> |
| 80 | 80 | <keyboard-shortcut keymap="$default" |
| 81 | - first-keystroke="shift ctrl DELETE"/> | |
| 81 | + first-keystroke="shift ctrl BACK_SPACE"/> | |
| 82 | 82 | <keyboard-shortcut keymap="Mac OS X" |
| 83 | - first-keystroke="shift meta DELETE"/> | |
| 83 | + first-keystroke="shift meta BACK_SPACE"/> | |
| 84 | 84 | <override-text place="GoToAction" text="Continue: Reject Diff"/> |
| 85 | 85 | </action> |
| 86 | 86 |
modified extensions/intellij/src/main/resources/continue_tutorial.java +22 −27
| @@ -4,22 +4,23 @@ | ||
| 4 | 4 | // / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ |
| 5 | 5 | // \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ |
| 6 | 6 | // |
| 7 | -// Chat, Edit, and Autocomplete tutorial | |
| 7 | +// Autocomplete, Edit, Chat, and Agent tutorial | |
| 8 | 8 | // |
| 9 | 9 | |
| 10 | -// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- | |
| 10 | +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— // | |
| 11 | +// Autocomplete provides inline code suggestions as you type. | |
| 11 | 12 | |
| 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 | |
| 13 | 15 | |
| 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: | |
| 17 | 17 | |
| 18 | -// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— | |
| 18 | +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // | |
| 19 | +// Edit is a convenient way to make quick changes to specific code and files. | |
| 19 | 20 | |
| 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" | |
| 23 | 24 | public static int[] sortingAlgorithm(int[] x) { |
| 24 | 25 | for (int i = 0; i < x.length; i++) { |
| 25 | 26 | for (int j = 0; j < x.length - 1; j++) { |
| @@ -33,14 +34,12 @@ | ||
| 33 | 34 | return x; |
| 34 | 35 | } |
| 35 | 36 | |
| 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. | |
| 38 | 39 | |
| 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?" | |
| 44 | 43 | public static int[] sortingAlgorithm2(int[] x) { |
| 45 | 44 | for (int i = 0; i < x.length; i++) { |
| 46 | 45 | for (int j = 0; j < x.length - 1; j++) { |
| @@ -54,15 +53,11 @@ | ||
| 54 | 53 | return x; |
| 55 | 54 | } |
| 56 | 55 | |
| 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. | |
| 65 | 59 | |
| 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" | |
| 67 | 62 | |
| 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 @@ | ||
| 4 | 4 | / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ |
| 5 | 5 | \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ |
| 6 | 6 | |
| 7 | - Chat, Edit, and Autocomplete tutorial | |
| 7 | + Autocomplete, Edit, Chat, and Agent tutorial | |
| 8 | 8 | """ |
| 9 | 9 | |
| 10 | -# ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- | |
| 11 | 10 | |
| 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. | |
| 13 | 13 | |
| 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 | |
| 15 | 16 | |
| 16 | -# Follow the instructions in the sidebar to set up a Chat/Edit modela and an Autocomplete model. | |
| 17 | +# Basic assertion for sorting_algorithm: | |
| 17 | 18 | |
| 18 | -# ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— | |
| 19 | +# ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— # | |
| 20 | +# Edit is a convenient way to make quick changes to specific code and files. | |
| 19 | 21 | |
| 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" | |
| 23 | 25 | def sorting_algorithm(x): |
| 24 | 26 | for i in range(len(x)): |
| 25 | 27 | for j in range(len(x) - 1): |
| @@ -27,31 +29,24 @@ | ||
| 27 | 29 | x[j], x[j + 1] = x[j + 1], x[j] |
| 28 | 30 | return x |
| 29 | 31 | |
| 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. | |
| 34 | 34 | |
| 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): | |
| 39 | 39 | for i in range(len(x)): |
| 40 | 40 | for j in range(len(x) - 1): |
| 41 | 41 | if x[j] > x[j + 1]: |
| 42 | 42 | x[j], x[j + 1] = x[j + 1], x[j] |
| 43 | 43 | return x |
| 44 | 44 | |
| 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. | |
| 54 | 48 | |
| 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" | |
| 56 | 51 | |
| 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 @@ | ||
| 4 | 4 | // / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ |
| 5 | 5 | // \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ |
| 6 | 6 | // |
| 7 | -// Chat, Edit, and Autocomplete tutorial | |
| 7 | +// Autocomplete, Edit, Chat, and Agent tutorial | |
| 8 | 8 | // |
| 9 | 9 | |
| 10 | -// ———————————————————————————————————————————————— Setup ————————————————————————————————————————————————- | |
| 10 | +// ————————————————————————————————————————————— Autocomplete —————————————————————————————————————————————— // | |
| 11 | +// Autocomplete provides inline code suggestions as you type. | |
| 11 | 12 | |
| 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 | |
| 13 | 15 | |
| 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: | |
| 17 | 17 | |
| 18 | -// ————————————————————————————————————————————————— Chat ————————————————————————————————————————————————— | |
| 18 | +// ————————————————————————————————————————————————— Edit ————————————————————————————————————————————————— // | |
| 19 | +// Edit is a convenient way to make quick changes to specific code and files. | |
| 19 | 20 | |
| 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" | |
| 23 | 24 | function sortingAlgorithm(x: number[]): number[] { |
| 24 | 25 | for (let i = 0; i < x.length; i++) { |
| 25 | 26 | for (let j = 0; j < x.length - 1; j++) { |
| @@ -33,14 +34,12 @@ | ||
| 33 | 34 | return x; |
| 34 | 35 | } |
| 35 | 36 | |
| 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. | |
| 40 | 39 | |
| 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?" | |
| 44 | 43 | function sortingAlgorithm2(x: number[]): number[] { |
| 45 | 44 | for (let i = 0; i < x.length; i++) { |
| 46 | 45 | for (let j = 0; j < x.length - 1; j++) { |
| @@ -54,13 +53,11 @@ | ||
| 54 | 53 | return x; |
| 55 | 54 | } |
| 56 | 55 | |
| 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. | |
| 63 | 59 | |
| 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" | |
| 65 | 62 | |
| 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 @@ | ||
| 12 | 12 | # How to run and debug tests |
| 13 | 13 | |
| 14 | 14 | 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 @@ | ||
| 4 | 4 | / /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ |
| 5 | 5 | \____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ |
| 6 | 6 | |
| 7 | - Chat, Edit, and Autocomplete tutorial | |
| 7 | + Autocomplete, Edit, Chat, and Agent tutorial | |
| 8 | 8 | """ |
| 9 | 9 | |
| 10 | 10 | |
| 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 | |
| 12 | 16 | |
| 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" | |
| 16 | 25 | def sorting_algorithm(x): |
| 17 | 26 | for i in range(len(x)): |
| 18 | 27 | for j in range(len(x) - 1): |
| @@ -20,25 +29,25 @@ | ||
| 20 | 29 | x[j], x[j + 1] = x[j + 1], x[j] |
| 21 | 30 | return x |
| 22 | 31 | |
| 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): | |
| 30 | 39 | for i in range(len(x)): |
| 31 | 40 | for j in range(len(x) - 1): |
| 32 | 41 | if x[j] > x[j + 1]: |
| 33 | 42 | x[j], x[j + 1] = x[j + 1], x[j] |
| 34 | 43 | return x |
| 35 | 44 | |
| 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. | |
| 42 | 48 | |
| 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" | |
| 43 | 52 | |
| 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 @@ | ||
| 46 | 46 | } |
| 47 | 47 | |
| 48 | 48 | public static getToolCallStatusMessage(view: WebView) { |
| 49 | - return SelectorUtils.getElementByDataTestId(view, "toggle-div-title"); | |
| 49 | + return SelectorUtils.getElementByDataTestId(view, "tool-call-title"); | |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | public static getToolButton(view: WebView) { |
| @@ -89,6 +89,14 @@ | ||
| 89 | 89 | ); |
| 90 | 90 | } |
| 91 | 91 | |
| 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 | + | |
| 92 | 100 | public static getNthHistoryTableRow(view: WebView, index: number) { |
| 93 | 101 | return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`); |
| 94 | 102 | } |
modified extensions/vscode/e2e/tests/GUI.test.ts +44 −1
| @@ -245,6 +245,47 @@ | ||
| 245 | 245 | await GUIActions.selectModeFromDropdown(view, "Agent"); |
| 246 | 246 | }); |
| 247 | 247 | |
| 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 | + | |
| 248 | 289 | it("should render tool call", async () => { |
| 249 | 290 | const [messageInput] = await GUISelectors.getMessageInputFields(view); |
| 250 | 291 | await messageInput.sendKeys("Hello"); |
| @@ -258,7 +299,9 @@ | ||
| 258 | 299 | expect(await statusMessage.getText()).contain( |
| 259 | 300 | "Continue viewed the git diff", |
| 260 | 301 | ); |
| 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); | |
| 262 | 305 | |
| 263 | 306 | it("should call tool after approval", async () => { |
| 264 | 307 | 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 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.34", | |
| 5 | + "version": "1.1.39", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
| @@ -105,7 +105,7 @@ | ||
| 105 | 105 | "continue.enableQuickActions": { |
| 106 | 106 | "type": "boolean", |
| 107 | 107 | "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)" | |
| 109 | 109 | }, |
| 110 | 110 | "continue.enableTabAutocomplete": { |
| 111 | 111 | "type": "boolean", |
| @@ -631,7 +631,7 @@ | ||
| 631 | 631 | "devDependencies": { |
| 632 | 632 | "@biomejs/biome": "1.6.4", |
| 633 | 633 | "@nestjs/common": "^11.0.16", |
| 634 | - "@openapitools/openapi-generator-cli": "^2.5.2", | |
| 634 | + "@openapitools/openapi-generator-cli": "^2.20.0", | |
| 635 | 635 | "@types/chai": "^5.0.1", |
| 636 | 636 | "@types/cors": "^2.8.17", |
| 637 | 637 | "@types/express": "^4.17.21", |
| @@ -657,12 +657,11 @@ | ||
| 657 | 657 | "rimraf": "^5.0.5", |
| 658 | 658 | "typescript": "^5.6.3", |
| 659 | 659 | "vite": "^4.5.14", |
| 660 | - "vsce": "^2.15.0", | |
| 661 | 660 | "vscode-extension-tester": "^8.14.1" |
| 662 | 661 | }, |
| 663 | 662 | "dependencies": { |
| 664 | 663 | "@continuedev/config-types": "^1.0.14", |
| 665 | - "@continuedev/fetch": "^1.0.3", | |
| 664 | + "@continuedev/fetch": "^1.0.10", | |
| 666 | 665 | "@electron/rebuild": "^3.2.10", |
| 667 | 666 | "@reduxjs/toolkit": "^1.9.3", |
| 668 | 667 | "@types/node-fetch": "^2.6.11", |
| @@ -705,7 +704,7 @@ | ||
| 705 | 704 | "svg-builder": "^2.0.0", |
| 706 | 705 | "systeminformation": "^5.23.7", |
| 707 | 706 | "tailwindcss": "^3.3.2", |
| 708 | - "undici": "^6.2.0", | |
| 707 | + "undici": "^6.21.3", | |
| 709 | 708 | "uuid": "^9.0.1", |
| 710 | 709 | "uuidv4": "^6.2.13", |
| 711 | 710 | "vectordb": "^0.4.20", |
modified extensions/vscode/scripts/package.js +2 −2
| @@ -19,8 +19,8 @@ | ||
| 19 | 19 | const isPreRelease = args.includes("--pre-release"); |
| 20 | 20 | |
| 21 | 21 | 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"; | |
| 24 | 24 | |
| 25 | 25 | if (target) { |
| 26 | 26 | command += ` --target ${target}`; |
modified extensions/vscode/src/commands.ts +14 −4
| @@ -97,6 +97,7 @@ | ||
| 97 | 97 | action: "accept" | "reject", |
| 98 | 98 | sidebar: ContinueGUIWebviewViewProvider, |
| 99 | 99 | ide: VsCodeIde, |
| 100 | + core: Core, | |
| 100 | 101 | verticalDiffManager: VerticalDiffManager, |
| 101 | 102 | newFileUri?: string, |
| 102 | 103 | streamId?: string, |
| @@ -121,6 +122,9 @@ | ||
| 121 | 122 | |
| 122 | 123 | // Clear vertical diffs depending on action |
| 123 | 124 | verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); |
| 125 | + if (action === "reject") { | |
| 126 | + core.invoke("cancelApply", undefined); | |
| 127 | + } | |
| 124 | 128 | |
| 125 | 129 | if (streamId) { |
| 126 | 130 | const fileContent = await ide.readFile(newOrCurrentUri); |
| @@ -236,18 +240,20 @@ | ||
| 236 | 240 | "accept", |
| 237 | 241 | sidebar, |
| 238 | 242 | ide, |
| 243 | + core, | |
| 239 | 244 | verticalDiffManager, |
| 240 | 245 | newFileUri, |
| 241 | 246 | streamId, |
| 242 | 247 | ), |
| 243 | 248 | |
| 244 | - "continue.rejectDiff": async (newFilepath?: string, streamId?: string) => | |
| 249 | + "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => | |
| 245 | 250 | processDiff( |
| 246 | 251 | "reject", |
| 247 | 252 | sidebar, |
| 248 | 253 | ide, |
| 254 | + core, | |
| 249 | 255 | verticalDiffManager, |
| 250 | - newFilepath, | |
| 256 | + newFileUri, | |
| 251 | 257 | streamId, |
| 252 | 258 | ), |
| 253 | 259 | "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => { |
| @@ -573,11 +579,15 @@ | ||
| 573 | 579 | await addEntireFileToContext( |
| 574 | 580 | vscode.Uri.parse(fileUri), |
| 575 | 581 | sidebar.webviewProtocol, |
| 576 | - ide.ideUtils | |
| 582 | + ide.ideUtils, | |
| 577 | 583 | ); |
| 578 | 584 | } |
| 579 | 585 | } else { |
| 580 | - await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils); | |
| 586 | + await addEntireFileToContext( | |
| 587 | + uri, | |
| 588 | + sidebar.webviewProtocol, | |
| 589 | + ide.ideUtils, | |
| 590 | + ); | |
| 581 | 591 | } |
| 582 | 592 | } |
| 583 | 593 | }, |
modified extensions/vscode/src/diff/vertical/handler.ts +204 −194
| @@ -23,22 +23,16 @@ | ||
| 23 | 23 | } |
| 24 | 24 | |
| 25 | 25 | export class VerticalDiffHandler implements vscode.Disposable { |
| 26 | + public insertedInCurrentBlock = 0; | |
| 27 | + disposables: vscode.Disposable[] = []; | |
| 26 | 28 | private currentLineIndex: number; |
| 27 | 29 | private cancelled = false; |
| 28 | 30 | private newLinesAdded = 0; |
| 29 | 31 | private deletionBuffer: string[] = []; |
| 30 | 32 | private removedLineDecorations: RemovedLineDecorationManager; |
| 31 | 33 | 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; | |
| 42 | 36 | |
| 43 | 37 | constructor( |
| 44 | 38 | private startLine: number, |
| @@ -79,149 +73,18 @@ | ||
| 79 | 73 | this.disposables.push(disposable); |
| 80 | 74 | } |
| 81 | 75 | |
| 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); | |
| 194 | 80 | } |
| 195 | 81 | |
| 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; | |
| 220 | 84 | } |
| 221 | 85 | |
| 222 | - private clearIndexLineDecorations() { | |
| 223 | - this.editor.setDecorations(belowIndexDecorationType, []); | |
| 224 | - this.editor.setDecorations(indexDecorationType, []); | |
| 86 | + private get fileUri() { | |
| 87 | + return this.editor.document.uri.toString(); | |
| 225 | 88 | } |
| 226 | 89 | |
| 227 | 90 | async clear(accept: boolean) { |
| @@ -257,19 +120,10 @@ | ||
| 257 | 120 | this.dispose(); |
| 258 | 121 | } |
| 259 | 122 | |
| 260 | - disposables: vscode.Disposable[] = []; | |
| 261 | - | |
| 262 | 123 | dispose() { |
| 263 | 124 | this.disposables.forEach((disposable) => disposable.dispose()); |
| 264 | 125 | } |
| 265 | 126 | |
| 266 | - get isCancelled() { | |
| 267 | - return this.cancelled; | |
| 268 | - } | |
| 269 | - | |
| 270 | - private _diffLinesQueue: DiffLine[] = []; | |
| 271 | - private _queueLock = false; | |
| 272 | - | |
| 273 | 127 | async queueDiffLine(diffLine: DiffLine | undefined) { |
| 274 | 128 | if (diffLine) { |
| 275 | 129 | this._diffLinesQueue.push(diffLine); |
| @@ -299,25 +153,6 @@ | ||
| 299 | 153 | this._queueLock = false; |
| 300 | 154 | } |
| 301 | 155 | |
| 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 | - | |
| 321 | 156 | async run(diffLineGenerator: AsyncGenerator<DiffLine>) { |
| 322 | 157 | let diffLines = []; |
| 323 | 158 | |
| @@ -338,6 +173,12 @@ | ||
| 338 | 173 | |
| 339 | 174 | await this.reapplyWithMyersDiff(diffLines); |
| 340 | 175 | |
| 176 | + const range = new vscode.Range(this.startLine, 0, this.startLine, 0); | |
| 177 | + this.editor.revealRange( | |
| 178 | + range, | |
| 179 | + vscode.TextEditorRevealType.Default, | |
| 180 | + ); | |
| 181 | + | |
| 341 | 182 | this.options.onStatusUpdate( |
| 342 | 183 | "done", |
| 343 | 184 | this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0, |
| @@ -410,23 +251,6 @@ | ||
| 410 | 251 | } |
| 411 | 252 | } |
| 412 | 253 | |
| 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 | - | |
| 430 | 254 | public updateLineDelta( |
| 431 | 255 | fileUri: string, |
| 432 | 256 | startLine: number, |
| @@ -550,4 +374,190 @@ | ||
| 550 | 374 | this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); |
| 551 | 375 | this.refreshCodeLens(); |
| 552 | 376 | } |
| 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 | + } | |
| 553 | 563 | } |
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
| @@ -1,5 +1,4 @@ | ||
| 1 | 1 | import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; |
| 2 | -import { ConfigHandler } from "core/config/ConfigHandler"; | |
| 3 | 2 | import { streamDiffLines } from "core/edit/streamDiffLines"; |
| 4 | 3 | import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; |
| 5 | 4 | import { getMarkdownLanguageTagForFile } from "core/util"; |
| @@ -31,7 +30,6 @@ | ||
| 31 | 30 | logDiffs: DiffLine[] | undefined; |
| 32 | 31 | |
| 33 | 32 | constructor( |
| 34 | - private readonly configHandler: ConfigHandler, | |
| 35 | 33 | private readonly webviewProtocol: VsCodeWebviewProtocol, |
| 36 | 34 | private readonly editDecorationManager: EditDecorationManager, |
| 37 | 35 | ) { |
| @@ -43,12 +41,12 @@ | ||
| 43 | 41 | startLine: number, |
| 44 | 42 | endLine: number, |
| 45 | 43 | options: VerticalDiffHandlerOptions, |
| 46 | - ) { | |
| 44 | + ): VerticalDiffHandler | undefined { | |
| 47 | 45 | if (this.fileUriToHandler.has(fileUri)) { |
| 48 | 46 | this.fileUriToHandler.get(fileUri)?.clear(false); |
| 49 | 47 | this.fileUriToHandler.delete(fileUri); |
| 50 | 48 | } |
| 51 | - const editor = vscode.window.activeTextEditor; // TODO | |
| 49 | + const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files | |
| 52 | 50 | if (editor && URI.equal(editor.document.uri.toString(), fileUri)) { |
| 53 | 51 | const handler = new VerticalDiffHandler( |
| 54 | 52 | startLine, |
| @@ -453,6 +451,7 @@ | ||
| 453 | 451 | language: getMarkdownLanguageTagForFile(fileUri), |
| 454 | 452 | onlyOneInsertion: !!onlyOneInsertion, |
| 455 | 453 | overridePrompt, |
| 454 | + abortControllerId: fileUri, | |
| 456 | 455 | }); |
| 457 | 456 | |
| 458 | 457 | for await (const line of stream) { |
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
| @@ -130,7 +130,6 @@ | ||
| 130 | 130 | this.configHandler.loadConfig(); |
| 131 | 131 | |
| 132 | 132 | this.verticalDiffManager = new VerticalDiffManager( |
| 133 | - this.configHandler, | |
| 134 | 133 | this.sidebar.webviewProtocol, |
| 135 | 134 | this.editDecorationManager, |
| 136 | 135 | ); |
modified extensions/vscode/src/extension/VsCodeMessenger.ts +13 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | import { stripImages } from "core/util/messageContent"; |
| 16 | 16 | import * as vscode from "vscode"; |
| 17 | 17 | |
| 18 | +import { DataLogger } from "core/data/log"; | |
| 18 | 19 | import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; |
| 19 | 20 | import { ApplyManager } from "../apply"; |
| 20 | 21 | import { VerticalDiffManager } from "../diff/vertical/manager"; |
| @@ -228,6 +229,18 @@ | ||
| 228 | 229 | ), |
| 229 | 230 | rulesToInclude: config.rules, |
| 230 | 231 | }); |
| 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 | + | |
| 231 | 244 | return fileAfterEdit; |
| 232 | 245 | }); |
| 233 | 246 |
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +36 −7
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import crypto from "crypto"; |
| 2 | 2 | |
| 3 | -import { ControlPlaneSessionInfo } from "core/control-plane/client"; | |
| 4 | 3 | import { getControlPlaneEnvSync } from "core/control-plane/env"; |
| 5 | 4 | import fetch from "node-fetch"; |
| 6 | 5 | import { v4 as uuidv4 } from "uuid"; |
| @@ -18,6 +17,12 @@ | ||
| 18 | 17 | window, |
| 19 | 18 | } from "vscode"; |
| 20 | 19 | |
| 20 | +import { | |
| 21 | + AuthType, | |
| 22 | + ControlPlaneSessionInfo, | |
| 23 | + HubEnv, | |
| 24 | + isHubEnv, | |
| 25 | +} from "core/control-plane/AuthTypes"; | |
| 21 | 26 | import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; |
| 22 | 27 | import { SecretStorage } from "./SecretStorage"; |
| 23 | 28 | import { UriEventHandler } from "./uriHandler"; |
| @@ -280,12 +285,21 @@ | ||
| 280 | 285 | try { |
| 281 | 286 | const codeVerifier = generateRandomString(64); |
| 282 | 287 | 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); | |
| 284 | 294 | if (!token) { |
| 285 | 295 | throw new Error(`Continue login failure`); |
| 286 | 296 | } |
| 287 | 297 | |
| 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; | |
| 289 | 303 | const { user, access_token, refresh_token } = userInfo; |
| 290 | 304 | |
| 291 | 305 | const session: ContinueAuthenticationSession = { |
| @@ -352,7 +366,11 @@ | ||
| 352 | 366 | /** |
| 353 | 367 | * Log in to Continue |
| 354 | 368 | */ |
| 355 | - private async login(codeChallenge: string, scopes: string[] = []) { | |
| 369 | + private async login( | |
| 370 | + codeChallenge: string, | |
| 371 | + hubEnv: HubEnv, | |
| 372 | + scopes: string[] = [], | |
| 373 | + ) { | |
| 356 | 374 | return await window.withProgress<string>( |
| 357 | 375 | { |
| 358 | 376 | location: ProgressLocation.Notification, |
| @@ -369,7 +387,7 @@ | ||
| 369 | 387 | const url = new URL("https://api.workos.com/user_management/authorize"); |
| 370 | 388 | const params = { |
| 371 | 389 | response_type: "code", |
| 372 | - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, | |
| 390 | + client_id: hubEnv.WORKOS_CLIENT_ID, | |
| 373 | 391 | redirect_uri: this.redirectUri, |
| 374 | 392 | state: stateId, |
| 375 | 393 | code_challenge: codeChallenge, |
| @@ -458,7 +476,11 @@ | ||
| 458 | 476 | * @param token |
| 459 | 477 | * @returns |
| 460 | 478 | */ |
| 461 | - private async getUserInfo(token: string, codeVerifier: string) { | |
| 479 | + private async getUserInfo( | |
| 480 | + token: string, | |
| 481 | + codeVerifier: string, | |
| 482 | + hubEnv: HubEnv, | |
| 483 | + ) { | |
| 462 | 484 | const resp = await fetch( |
| 463 | 485 | "https://api.workos.com/user_management/authenticate", |
| 464 | 486 | { |
| @@ -467,7 +489,7 @@ | ||
| 467 | 489 | "Content-Type": "application/json", |
| 468 | 490 | }, |
| 469 | 491 | body: JSON.stringify({ |
| 470 | - client_id: controlPlaneEnv.WORKOS_CLIENT_ID, | |
| 492 | + client_id: hubEnv.WORKOS_CLIENT_ID, | |
| 471 | 493 | code_verifier: codeVerifier, |
| 472 | 494 | grant_type: "authorization_code", |
| 473 | 495 | code: token, |
| @@ -484,6 +506,12 @@ | ||
| 484 | 506 | silent: boolean, |
| 485 | 507 | useOnboarding: boolean, |
| 486 | 508 | ): Promise<ControlPlaneSessionInfo | undefined> { |
| 509 | + if (!isHubEnv(controlPlaneEnv)) { | |
| 510 | + return { | |
| 511 | + AUTH_TYPE: AuthType.OnPrem, | |
| 512 | + }; | |
| 513 | + } | |
| 514 | + | |
| 487 | 515 | try { |
| 488 | 516 | if (useOnboarding) { |
| 489 | 517 | WorkOsAuthProvider.useOnboardingUri = true; |
| @@ -498,6 +526,7 @@ | ||
| 498 | 526 | return undefined; |
| 499 | 527 | } |
| 500 | 528 | return { |
| 529 | + AUTH_TYPE: controlPlaneEnv.AUTH_TYPE, | |
| 501 | 530 | accessToken: session.accessToken, |
| 502 | 531 | account: { |
| 503 | 532 | id: session.account.id, |
modified gui/.eslintrc.json +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | "parser": "@typescript-eslint/parser", |
| 4 | 4 | "plugins": ["@typescript-eslint", "eslint-plugin-react"], |
| 5 | 5 | "parserOptions": { |
| 6 | - "project": "gui/tsconfig.json" | |
| 6 | + "project": ["tsconfig.json", "tsconfig.node.json"] | |
| 7 | 7 | }, |
| 8 | 8 | "extends": [ |
| 9 | 9 | // "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 @@ | ||
| 12 | 12 | "test": "vitest run", |
| 13 | 13 | "test:coverage": "vitest run --coverage", |
| 14 | 14 | "test:ui": "vitest --ui", |
| 15 | - "test:watch": "vitest" | |
| 15 | + "test:watch": "vitest", | |
| 16 | + "lint": "eslint --ext ts" | |
| 16 | 17 | }, |
| 17 | 18 | "dependencies": { |
| 18 | 19 | "@continuedev/config-yaml": "file:../packages/config-yaml", |
modified gui/src/App.tsx +5 −0
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import Chat from "./pages/gui"; |
| 10 | 10 | import History from "./pages/history"; |
| 11 | 11 | import Stats from "./pages/stats"; |
| 12 | +import ThemePage from "./styles/ThemePage"; | |
| 12 | 13 | import { ROUTES } from "./util/navigation"; |
| 13 | 14 | |
| 14 | 15 | const router = createMemoryRouter([ |
| @@ -37,6 +38,10 @@ | ||
| 37 | 38 | path: ROUTES.CONFIG, |
| 38 | 39 | element: <ConfigPage />, |
| 39 | 40 | }, |
| 41 | + { | |
| 42 | + path: ROUTES.THEME, | |
| 43 | + element: <ThemePage />, | |
| 44 | + }, | |
| 40 | 45 | ], |
| 41 | 46 | }, |
| 42 | 47 | ]); |
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 @@ | ||
| 1 | 1 | import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; |
| 2 | 2 | import { ApplyState } from "core"; |
| 3 | -import { useEffect, useState } from "react"; | |
| 4 | 3 | import { getMetaKeyLabel } from "../../../util"; |
| 5 | 4 | import Spinner from "../../gui/Spinner"; |
| 6 | 5 | import { ToolTip } from "../../gui/Tooltip"; |
| @@ -16,56 +15,11 @@ | ||
| 16 | 15 | } |
| 17 | 16 | |
| 18 | 17 | 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 | - | |
| 34 | 18 | function onClickReject() { |
| 35 | 19 | props.onClickReject(); |
| 36 | - setHasRejected(true); | |
| 37 | 20 | } |
| 38 | 21 | |
| 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 | - | |
| 60 | 22 | 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 | - ); | |
| 69 | 23 | case "streaming": |
| 70 | 24 | return ( |
| 71 | 25 | <div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1"> |
| @@ -102,21 +56,30 @@ | ||
| 102 | 56 | </div> |
| 103 | 57 | ); |
| 104 | 58 | 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 | - } | |
| 116 | 59 | default: |
| 117 | 60 | if (props.disableManualApply) { |
| 118 | 61 | return null; |
| 119 | 62 | } |
| 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 | + ); | |
| 121 | 84 | } |
| 122 | 85 | } |
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 @@ | ||
| 3 | 3 | import { lightGray, vscForeground } from "../.."; |
| 4 | 4 | import { IdeMessengerContext } from "../../../context/IdeMessenger"; |
| 5 | 5 | import { isJetBrains } from "../../../util"; |
| 6 | +import { extractCommand } from "../utils/commandExtractor"; | |
| 6 | 7 | |
| 7 | 8 | interface RunInTerminalButtonProps { |
| 8 | 9 | command: string; |
| @@ -16,18 +17,6 @@ | ||
| 16 | 17 | return null; |
| 17 | 18 | } |
| 18 | 19 | |
| 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 | - | |
| 31 | 20 | function runInTerminal() { |
| 32 | 21 | // Extract just the command line |
| 33 | 22 | const extractedCommand = extractCommand(command); |
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +43 −15
| @@ -11,14 +11,15 @@ | ||
| 11 | 11 | import { useIdeMessengerRequest } from "../../../hooks"; |
| 12 | 12 | import { useWebviewListener } from "../../../hooks/useWebviewListener"; |
| 13 | 13 | import { useAppSelector } from "../../../redux/hooks"; |
| 14 | +import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall"; | |
| 14 | 15 | import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; |
| 15 | 16 | import { getFontSize } from "../../../util"; |
| 17 | +import Spinner from "../../gui/Spinner"; | |
| 16 | 18 | import { isTerminalCodeBlock } from "../utils"; |
| 17 | 19 | import { ApplyActions } from "./ApplyActions"; |
| 18 | 20 | import { CopyButton } from "./CopyButton"; |
| 19 | 21 | import { CreateFileButton } from "./CreateFileButton"; |
| 20 | 22 | import { FileInfo } from "./FileInfo"; |
| 21 | -import { GeneratingCodeLoader } from "./GeneratingCodeLoader"; | |
| 22 | 23 | import { InsertButton } from "./InsertButton"; |
| 23 | 24 | import { RunInTerminalButton } from "./RunInTerminalButton"; |
| 24 | 25 | |
| @@ -49,8 +50,9 @@ | ||
| 49 | 50 | codeBlockContent: string; |
| 50 | 51 | language: string | null; |
| 51 | 52 | relativeFilepath?: string; |
| 52 | - isFinalCodeblock: boolean; | |
| 53 | + itemIndex?: number; | |
| 53 | 54 | codeBlockIndex: number; // To track which codeblock we are applying |
| 55 | + isLastCodeblock: boolean; | |
| 54 | 56 | codeBlockStreamId: string; |
| 55 | 57 | range?: string; |
| 56 | 58 | children: any; |
| @@ -62,8 +64,9 @@ | ||
| 62 | 64 | codeBlockContent, |
| 63 | 65 | language, |
| 64 | 66 | relativeFilepath, |
| 65 | - isFinalCodeblock, | |
| 67 | + itemIndex, | |
| 66 | 68 | codeBlockIndex, |
| 69 | + isLastCodeblock, | |
| 67 | 70 | codeBlockStreamId, |
| 68 | 71 | range, |
| 69 | 72 | children, |
| @@ -71,6 +74,7 @@ | ||
| 71 | 74 | disableManualApply, |
| 72 | 75 | }: StepContainerPreToolbarProps) { |
| 73 | 76 | const ideMessenger = useContext(IdeMessengerContext); |
| 77 | + const history = useAppSelector((state) => state.session.history); | |
| 74 | 78 | const [isExpanded, setIsExpanded] = useState(expanded ?? true); |
| 75 | 79 | |
| 76 | 80 | const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>( |
| @@ -95,6 +99,9 @@ | ||
| 95 | 99 | const applyState = useAppSelector((state) => |
| 96 | 100 | selectApplyStateByStreamId(state, codeBlockStreamId), |
| 97 | 101 | ); |
| 102 | + const currentToolCallApplyState = useAppSelector( | |
| 103 | + selectCurrentToolCallApplyState, | |
| 104 | + ); | |
| 98 | 105 | |
| 99 | 106 | /** |
| 100 | 107 | * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. |
| @@ -110,7 +117,12 @@ | ||
| 110 | 117 | relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); |
| 111 | 118 | |
| 112 | 119 | 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; | |
| 114 | 126 | |
| 115 | 127 | // If we are creating a file, we already render that in the button |
| 116 | 128 | // so we don't want to dispaly it twice here |
| @@ -221,6 +233,32 @@ | ||
| 221 | 233 | } |
| 222 | 234 | |
| 223 | 235 | 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 | + | |
| 224 | 262 | if (isTerminalCodeBlock(language, codeBlockContent)) { |
| 225 | 263 | return <RunInTerminalButton command={codeBlockContent} />; |
| 226 | 264 | } |
| @@ -281,17 +319,7 @@ | ||
| 281 | 319 | </div> |
| 282 | 320 | )} |
| 283 | 321 | |
| 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()} | |
| 295 | 323 | </div> |
| 296 | 324 | </ToolbarDiv> |
| 297 | 325 |
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
| @@ -44,14 +44,7 @@ | ||
| 44 | 44 | data-tooltip-id={id} |
| 45 | 45 | data-tooltip-delay-show={500} |
| 46 | 46 | > |
| 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> | |
| 55 | 48 | </span> |
| 56 | 49 | <ToolTip id={id} place="top" className="m-0 p-0"> |
| 57 | 50 | <pre className="text-left">{processedContent ?? symbol.filepath}</pre> |
modified gui/src/components/StyledMarkdownPreview/index.tsx +4 −8
| @@ -193,11 +193,7 @@ | ||
| 193 | 193 | }; |
| 194 | 194 | }, [props.itemIndex, history, allSymbols]); |
| 195 | 195 | 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); | |
| 201 | 197 | |
| 202 | 198 | const codeblockStreamIds = useRef<string[]>([]); |
| 203 | 199 | useEffect(() => { |
| @@ -296,8 +292,7 @@ | ||
| 296 | 292 | |
| 297 | 293 | const language = getLanguageFromClassName(className); |
| 298 | 294 | |
| 299 | - const isFinalCodeblock = | |
| 300 | - preChildProps["data-islastcodeblock"] && isLastItemRef.current; | |
| 295 | + const isLastCodeblock = preChildProps["data-islastcodeblock"]; | |
| 301 | 296 | |
| 302 | 297 | if (codeblockStreamIds.current[codeBlockIndex] === undefined) { |
| 303 | 298 | codeblockStreamIds.current[codeBlockIndex] = |
| @@ -307,10 +302,11 @@ | ||
| 307 | 302 | return ( |
| 308 | 303 | <StepContainerPreToolbar |
| 309 | 304 | codeBlockContent={codeBlockContent} |
| 305 | + itemIndex={itemIndexRef.current} | |
| 310 | 306 | codeBlockIndex={codeBlockIndex} |
| 311 | 307 | language={language} |
| 312 | 308 | relativeFilepath={relativeFilePath} |
| 313 | - isFinalCodeblock={isFinalCodeblock} | |
| 309 | + isLastCodeblock={isLastCodeblock} | |
| 314 | 310 | range={range} |
| 315 | 311 | codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} |
| 316 | 312 | expanded={props.expandCodeblocks} |
modified gui/src/components/StyledMarkdownPreview/rehypeHighlightPlugin.ts +2 −0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | // Feel free to add more! |
| 2 | 2 | // See gui/node_modules/highlight.js/lib/languages for the full available list |
| 3 | 3 | import clojure from "highlight.js/lib/languages/clojure"; |
| 4 | +import delphi from "highlight.js/lib/languages/delphi"; | |
| 4 | 5 | import elixir from "highlight.js/lib/languages/elixir"; |
| 5 | 6 | import julia from "highlight.js/lib/languages/julia"; |
| 6 | 7 | import lisp from "highlight.js/lib/languages/lisp"; |
| @@ -19,6 +20,7 @@ | ||
| 19 | 20 | languages: { |
| 20 | 21 | ...common, |
| 21 | 22 | clojure, |
| 23 | + delphi, | |
| 22 | 24 | elixir, |
| 23 | 25 | julia, |
| 24 | 26 | 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 @@ | ||
| 1 | 1 | /* |
| 2 | 2 | This is a patch for outputing markdown code that contains codeblocks |
| 3 | 3 | |
| 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, | |
| 5 | 6 | and uses ~~~ instead of ``` for that block |
| 6 | 7 | |
| 7 | 8 | Note, this was benchmarked at sub-millisecond |
| 8 | - | |
| 9 | - // TODO support github-specific markdown as well, edge case | |
| 10 | 9 | */ |
| 10 | +import { headerIsMarkdown } from './headerIsMarkdown'; | |
| 11 | + | |
| 11 | 12 | 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 | + | |
| 14 | 16 | let nestCount = 0; |
| 15 | 17 | const lines = source.split("\n"); |
| 16 | 18 | const trimmedLines = lines.map((l) => l.trim()); |
| 19 | + | |
| 17 | 20 | for (let i = 0; i < trimmedLines.length; i++) { |
| 18 | 21 | const line = trimmedLines[i]; |
| 19 | - if (nestCount) { | |
| 22 | + | |
| 23 | + if (nestCount > 0) { | |
| 24 | + // Inside a markdown block | |
| 20 | 25 | if (line.match(/^`+$/)) { |
| 21 | - // Ending a block | |
| 22 | - if (nestCount === 1) lines[i] = "~~~"; // End of markdown block | |
| 26 | + // Ending a block with just backticks (```) | |
| 23 | 27 | nestCount--; |
| 28 | + if (nestCount === 0) { | |
| 29 | + lines[i] = "~~~"; // End of markdown block | |
| 30 | + } | |
| 24 | 31 | } else if (line.startsWith("```")) { |
| 25 | 32 | // Going into a nested codeblock |
| 26 | 33 | nestCount++; |
| 27 | 34 | } |
| 28 | 35 | } else { |
| 29 | - // Enter the markdown block, start tracking nesting | |
| 36 | + // Not inside a markdown block yet | |
| 30 | 37 | if (line.startsWith("```")) { |
| 31 | 38 | 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("`", "~"); | |
| 40 | 46 | } |
| 41 | 47 | } |
| 42 | 48 | } |
| 43 | 49 | } |
| 44 | - const out = lines.join("\n"); | |
| 45 | - // console.log(`patched in ${Date.now() - start}ms`); | |
| 46 | - return out; | |
| 50 | + | |
| 51 | + return lines.join("\n"); | |
| 47 | 52 | }; |
modified gui/src/components/TabBar/TabBar.tsx +35 −50
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { XMarkIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { useCallback, useEffect } from "react"; | |
| 2 | +import React, { useCallback, useEffect } from "react"; | |
| 3 | 3 | import { useDispatch, useSelector } from "react-redux"; |
| 4 | 4 | import styled from "styled-components"; |
| 5 | 5 | import { defaultBorderRadius } from ".."; |
| @@ -13,16 +13,30 @@ | ||
| 13 | 13 | } from "../../redux/slices/tabsSlice"; |
| 14 | 14 | import { AppDispatch, RootState } from "../../redux/store"; |
| 15 | 15 | 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 | |
| 16 | 28 | |
| 17 | 29 | const TabBarContainer = styled.div` |
| 18 | 30 | display: flex; |
| 19 | 31 | flex-wrap: wrap; |
| 20 | 32 | flex-shrink: 0; |
| 21 | 33 | flex-grow: 0; |
| 22 | - background-color: var(--vscode-tab-inactiveBackground); | |
| 34 | + background-color: ${tabBackgroundVar}; | |
| 23 | 35 | border-bottom: none; |
| 24 | 36 | position: relative; |
| 25 | 37 | margin-top: 2px; |
| 38 | + max-height: 100px; | |
| 39 | + overflow: auto; | |
| 26 | 40 | |
| 27 | 41 | /* Hide scrollbar but keep functionality */ |
| 28 | 42 | scrollbar-width: none; |
| @@ -41,24 +55,18 @@ | ||
| 41 | 55 | max-width: 150px; |
| 42 | 56 | height: 25px; |
| 43 | 57 | background-color: ${(props) => |
| 44 | - props.isActive | |
| 45 | - ? "var(--vscode-tab-activeBackground)" | |
| 46 | - : "var(--vscode-tab-inactiveBackground)"}; | |
| 58 | + props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar}; | |
| 47 | 59 | color: ${(props) => |
| 48 | - props.isActive | |
| 49 | - ? "var(--vscode-tab-activeForeground)" | |
| 50 | - : "var(--vscode-tab-inactiveForeground)"}; | |
| 60 | + props.isActive ? tabSelectedForegroundVar : tabForegroundVar}; | |
| 51 | 61 | cursor: pointer; |
| 52 | - border: 1px solid var(--vscode-tab-border); | |
| 62 | + border: 1px solid ${tabBorderVar}; | |
| 53 | 63 | border-bottom: ${(props) => |
| 54 | - props.isActive ? "none" : `1px solid var(--vscode-tab-border)`}; | |
| 64 | + props.isActive ? "none" : `1px solid ${tabBorderVar}`}; | |
| 55 | 65 | user-select: none; |
| 56 | 66 | position: relative; |
| 57 | 67 | transition: background-color 0.2s; |
| 58 | 68 | 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}`}; | |
| 62 | 70 | &:first-child { |
| 63 | 71 | border-left: none; |
| 64 | 72 | } |
| @@ -68,13 +76,9 @@ | ||
| 68 | 76 | |
| 69 | 77 | &:hover { |
| 70 | 78 | background-color: ${(props) => |
| 71 | - props.isActive | |
| 72 | - ? "var(--vscode-tab-activeBackground)" | |
| 73 | - : "var(--vscode-tab-hoverBackground)"}; | |
| 79 | + props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar}; | |
| 74 | 80 | color: ${(props) => |
| 75 | - props.isActive | |
| 76 | - ? "var(--vscode-tab-activeForeground)" | |
| 77 | - : "var(--vscode-tab-hoverForeground)"}; | |
| 81 | + props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar}; | |
| 78 | 82 | } |
| 79 | 83 | `; |
| 80 | 84 | |
| @@ -104,7 +108,7 @@ | ||
| 104 | 108 | |
| 105 | 109 | &:hover { |
| 106 | 110 | opacity: 1; |
| 107 | - background-color: var(--vscode-tab-hoverBackground); | |
| 111 | + background-color: ${tabHoverBackgroundVar}; | |
| 108 | 112 | } |
| 109 | 113 | |
| 110 | 114 | ${Tab}:hover & { |
| @@ -119,33 +123,12 @@ | ||
| 119 | 123 | const TabBarSpace = styled.div` |
| 120 | 124 | flex: 1; |
| 121 | 125 | 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}; | |
| 124 | 128 | `; |
| 125 | 129 | |
| 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) => { | |
| 147 | 131 | const dispatch = useDispatch<AppDispatch>(); |
| 148 | - const currentSession = useSelector((state: RootState) => state.session); | |
| 149 | 132 | const currentSessionId = useSelector((state: RootState) => state.session.id); |
| 150 | 133 | const currentSessionTitle = useSelector( |
| 151 | 134 | (state: RootState) => state.session.title, |
| @@ -160,7 +143,6 @@ | ||
| 160 | 143 | return Date.now().toString(36) + Math.random().toString(36).substring(2); |
| 161 | 144 | }, []); |
| 162 | 145 | |
| 163 | - // Handle session changes | |
| 164 | 146 | useEffect(() => { |
| 165 | 147 | if (!currentSessionId) return; |
| 166 | 148 | |
| @@ -243,10 +225,13 @@ | ||
| 243 | 225 | } |
| 244 | 226 | }; |
| 245 | 227 | |
| 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 | + > | |
| 250 | 235 | {tabs.map((tab) => ( |
| 251 | 236 | <Tab |
| 252 | 237 | key={tab.id} |
| @@ -272,4 +257,4 @@ | ||
| 272 | 257 | </TabBarSpace> |
| 273 | 258 | </TabBarContainer> |
| 274 | 259 | ); |
| 275 | -} | |
| 260 | +}); |
modified gui/src/components/ToggleDiv.tsx +10 −7
| @@ -6,15 +6,21 @@ | ||
| 6 | 6 | children: React.ReactNode; |
| 7 | 7 | title: React.ReactNode; |
| 8 | 8 | icon?: ComponentType<React.SVGProps<SVGSVGElement>>; |
| 9 | + testId?: string; | |
| 9 | 10 | } |
| 10 | 11 | |
| 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) { | |
| 12 | 18 | const [open, setOpen] = useState(false); |
| 13 | 19 | const [isHovered, setIsHovered] = useState(false); |
| 14 | 20 | |
| 15 | 21 | return ( |
| 16 | 22 | <div |
| 17 | - className={`pl-2 pt-2`} | |
| 23 | + className={`pl-2`} | |
| 18 | 24 | style={{ |
| 19 | 25 | backgroundColor: vscBackground, |
| 20 | 26 | }} |
| @@ -24,7 +30,7 @@ | ||
| 24 | 30 | onClick={() => setOpen((prev) => !prev)} |
| 25 | 31 | onMouseEnter={() => setIsHovered(true)} |
| 26 | 32 | onMouseLeave={() => setIsHovered(false)} |
| 27 | - data-testid="context-items-peek" | |
| 33 | + data-testid={testId} | |
| 28 | 34 | > |
| 29 | 35 | <div className="relative mr-1 h-4 w-4"> |
| 30 | 36 | {Icon && !isHovered && !open ? ( |
| @@ -44,10 +50,7 @@ | ||
| 44 | 50 | </> |
| 45 | 51 | )} |
| 46 | 52 | </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"> | |
| 51 | 54 | {title} |
| 52 | 55 | </span> |
| 53 | 56 | </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"; | |
| 2 | 2 | import { LLMInteraction } from "../../hooks/useLLMLog"; |
| 3 | 3 | import useLLMSummary from "../../hooks/useLLMSummary"; |
| 4 | 4 | import End from "./End"; |
| @@ -50,6 +50,18 @@ | ||
| 50 | 50 | const scrollTop = useRef<HTMLDivElement>(null); |
| 51 | 51 | const lastResult = useRef<any>(null); |
| 52 | 52 | 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 | + } | |
| 53 | 65 | |
| 54 | 66 | useEffect(() => { |
| 55 | 67 | if (interaction.end) { |
| @@ -59,15 +71,17 @@ | ||
| 59 | 71 | const last = interaction.results[interaction.results.length - 1]; |
| 60 | 72 | if (last != lastResult.current) { |
| 61 | 73 | 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 | + } | |
| 68 | 82 | } |
| 69 | 83 | } |
| 70 | - }); | |
| 84 | + }, [interaction, isAtBottom]); | |
| 71 | 85 | |
| 72 | 86 | return ( |
| 73 | 87 | <div className="m-0 flex min-w-0 flex-1 shrink grow flex-col"> |
| @@ -102,7 +116,11 @@ | ||
| 102 | 116 | ></Cell> |
| 103 | 117 | </div> |
| 104 | 118 | </div> |
| 105 | - <div ref={scrollTop} className="grow overflow-auto"> | |
| 119 | + <div | |
| 120 | + ref={scrollTop} | |
| 121 | + className="grow overflow-auto" | |
| 122 | + onScroll={handleScroll} | |
| 123 | + > | |
| 106 | 124 | {interaction.start ? <Start item={interaction.start}></Start> : ""} |
| 107 | 125 | <div className="whitespace-pre-wrap p-2"> |
| 108 | 126 | {interaction.results.map((group, i) => { |
modified gui/src/components/dialogs/index.tsx +2 −3
| @@ -4,12 +4,11 @@ | ||
| 4 | 4 | import styled from "styled-components"; |
| 5 | 5 | import { |
| 6 | 6 | CloseButton, |
| 7 | - VSC_BACKGROUND_VAR, | |
| 8 | 7 | defaultBorderRadius, |
| 9 | - parseColorForHex, | |
| 10 | 8 | vscBackground, |
| 11 | 9 | vscForeground, |
| 12 | 10 | } from ".."; |
| 11 | +import { varWithFallback } from "../../styles/theme"; | |
| 13 | 12 | |
| 14 | 13 | interface TextDialogProps { |
| 15 | 14 | showDialog: boolean; |
| @@ -22,7 +21,7 @@ | ||
| 22 | 21 | position: fixed; |
| 23 | 22 | width: 100%; |
| 24 | 23 | height: 100%; |
| 25 | - background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa; | |
| 24 | + background-color: ${varWithFallback("background")}aa; | |
| 26 | 25 | z-index: 100000; |
| 27 | 26 | flex-direction: column; |
| 28 | 27 | `; |
modified gui/src/components/find/FindWidget.tsx +126 −292
| @@ -13,35 +13,24 @@ | ||
| 13 | 13 | } from "react"; |
| 14 | 14 | import { HeaderButton, Input } from ".."; |
| 15 | 15 | 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; | |
| 37 | 26 | isCurrent: boolean; |
| 38 | 27 | } |
| 39 | 28 | |
| 40 | 29 | const HighlightOverlay = (props: HighlightOverlayProps) => { |
| 41 | - const { isCurrent, top, left, width, height } = props; | |
| 30 | + const { top, left, width, height } = props.rectangle; | |
| 42 | 31 | return ( |
| 43 | 32 | <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"} | |
| 45 | 34 | key={`highlight-${top}-${left}`} |
| 46 | 35 | style={{ |
| 47 | 36 | position: "absolute", |
| @@ -56,6 +45,8 @@ | ||
| 56 | 45 | ); |
| 57 | 46 | }; |
| 58 | 47 | |
| 48 | +type ScrollToMatchOption = "closest" | "first" | "none"; | |
| 49 | + | |
| 59 | 50 | /* |
| 60 | 51 | useFindWidget takes a container ref and returns |
| 61 | 52 | 1. A widget that can be placed anywhere to search the contents of that container |
| @@ -64,18 +55,22 @@ | ||
| 64 | 55 | |
| 65 | 56 | Container must have relative positioning |
| 66 | 57 | */ |
| 67 | -export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => { | |
| 58 | +export const useFindWidget = ( | |
| 59 | + searchRef: RefObject<HTMLDivElement>, | |
| 60 | + headerRef: RefObject<HTMLDivElement>, | |
| 61 | + disabled: boolean, | |
| 62 | +) => { | |
| 68 | 63 | // Search input, debounced |
| 69 | - const [input, setInput] = useState<string>(""); | |
| 70 | - const debouncedInput = useRef<string>(""); | |
| 71 | 64 | const inputRef = useRef<HTMLInputElement>(null); |
| 65 | + const [currentValue, setCurrentValue] = useState<string>(""); | |
| 66 | + const searchTerm = useDebounceValue(currentValue, 300); | |
| 72 | 67 | |
| 73 | 68 | // Widget open/closed state |
| 74 | 69 | const [open, setOpen] = useState<boolean>(false); |
| 75 | 70 | const openWidget = useCallback(() => { |
| 76 | 71 | setOpen(true); |
| 77 | 72 | inputRef?.current?.select(); |
| 78 | - }, [setOpen, inputRef]); | |
| 73 | + }, [inputRef]); | |
| 79 | 74 | |
| 80 | 75 | // Search settings and results |
| 81 | 76 | const [caseSensitive, setCaseSensitive] = useState<boolean>(false); |
| @@ -97,7 +92,7 @@ | ||
| 97 | 92 | behavior: "smooth", |
| 98 | 93 | }); |
| 99 | 94 | }, |
| 100 | - [searchRef.current], | |
| 95 | + [searchRef], | |
| 101 | 96 | ); |
| 102 | 97 | |
| 103 | 98 | const nextMatch = useCallback(() => { |
| @@ -143,327 +138,166 @@ | ||
| 143 | 138 | }, [inputRef, matches, nextMatch]); |
| 144 | 139 | |
| 145 | 140 | // 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]); | |
| 169 | 147 | |
| 170 | 148 | // Main function for finding matches and generating highlight overlays |
| 171 | 149 | 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, | |
| 190 | 154 | { |
| 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, | |
| 205 | 158 | }, |
| 206 | 159 | ); |
| 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); | |
| 274 | 161 | // 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) { | |
| 290 | 163 | if (scrollTo === "first") { |
| 291 | - scrollToMatch(filteredMatches[0]); | |
| 164 | + scrollToMatch(results[0]); | |
| 292 | 165 | } |
| 293 | 166 | if (scrollTo === "closest") { |
| 294 | - if (closestMatchToMiddle) { | |
| 295 | - scrollToMatch(closestMatchToMiddle); | |
| 167 | + if (closestToMiddle) { | |
| 168 | + scrollToMatch(closestToMiddle); | |
| 296 | 169 | } |
| 297 | 170 | } |
| 298 | 171 | if (scrollTo === "none") { |
| 299 | - if (closestMatchToMiddle) { | |
| 300 | - setCurrentMatch(closestMatchToMiddle); | |
| 172 | + if (closestToMiddle) { | |
| 173 | + setCurrentMatch(closestToMiddle); | |
| 301 | 174 | } else { |
| 302 | - setCurrentMatch(filteredMatches[0]); | |
| 175 | + setCurrentMatch(results[0]); | |
| 303 | 176 | } |
| 304 | 177 | } |
| 305 | 178 | } |
| 306 | 179 | }, |
| 307 | - [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], | |
| 180 | + [ | |
| 181 | + searchTerm, | |
| 182 | + caseSensitive, | |
| 183 | + useRegex, | |
| 184 | + searchRef, | |
| 185 | + headerHeight, | |
| 186 | + scrollToMatch, | |
| 187 | + ], | |
| 308 | 188 | ); |
| 309 | 189 | |
| 310 | 190 | // Triggers that should cause immediate refresh of results to closest search value: |
| 311 | - // Input change (debounced) and window click | |
| 312 | - const lastUpdateRef = useRef(0); | |
| 313 | 191 | 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([]); | |
| 322 | 194 | } else { |
| 323 | - const handler = setTimeout(() => { | |
| 324 | - debounce(); | |
| 325 | - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); | |
| 326 | - return () => { | |
| 327 | - clearTimeout(handler); | |
| 328 | - }; | |
| 195 | + refreshSearch("closest"); | |
| 329 | 196 | } |
| 330 | - }, [refreshSearch, input]); | |
| 197 | + }, [refreshSearch, open, disabled, isResizing]); | |
| 331 | 198 | |
| 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 | |
| 334 | 201 | useEffect(() => { |
| 335 | 202 | const searchContainer = searchRef.current; |
| 336 | 203 | if (!open || !searchContainer) return; |
| 337 | 204 | const handleSearchRefClick = () => { |
| 338 | - refreshSearch("none"); | |
| 205 | + setTimeout(() => { | |
| 206 | + refreshSearch("none"); | |
| 207 | + }, 150); | |
| 339 | 208 | }; |
| 340 | 209 | searchContainer.addEventListener("click", handleSearchRefClick); |
| 341 | 210 | return () => { |
| 342 | 211 | searchContainer.removeEventListener("click", handleSearchRefClick); |
| 343 | 212 | }; |
| 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]); | |
| 363 | 214 | |
| 364 | 215 | // 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"> | |
| 411 | 236 | <HeaderButtonWithToolTip |
| 412 | - disabled={active} | |
| 413 | - inverted={caseSensitive} | |
| 414 | 237 | tooltipPlacement="top-end" |
| 415 | - text={ | |
| 416 | - caseSensitive | |
| 417 | - ? "Turn off case sensitivity" | |
| 418 | - : "Turn on case sensitivity" | |
| 419 | - } | |
| 238 | + text={"Previous Match"} | |
| 420 | 239 | onClick={(e) => { |
| 421 | 240 | e.stopPropagation(); |
| 422 | - setCaseSensitive((curr) => !curr); | |
| 241 | + previousMatch(); | |
| 423 | 242 | }} |
| 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} | |
| 425 | 245 | > |
| 426 | - Aa | |
| 246 | + <ArrowUpIcon className="h-4 w-4" /> | |
| 427 | 247 | </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} | |
| 433 | 257 | > |
| 434 | - <XMarkIcon className="h-4 w-4" /> | |
| 435 | - </HeaderButton> | |
| 258 | + <ArrowDownIcon className="h-4 w-4" /> | |
| 259 | + </HeaderButtonWithToolTip> | |
| 436 | 260 | </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 | + ); | |
| 448 | 288 | |
| 449 | 289 | // Generate the highlight overlay elements |
| 450 | 290 | const highlights = useMemo(() => { |
| 451 | 291 | return matches.map((match) => ( |
| 452 | 292 | <HighlightOverlay |
| 453 | - {...match.overlayRectangle} | |
| 293 | + rectangle={match.overlayRectangle} | |
| 454 | 294 | isCurrent={currentMatch?.index === match.index} |
| 455 | 295 | /> |
| 456 | 296 | )); |
| 457 | 297 | }, [matches, currentMatch]); |
| 458 | 298 | |
| 459 | 299 | return { |
| 460 | - matches, | |
| 461 | 300 | highlights, |
| 462 | - inputRef, | |
| 463 | - input: debouncedInput, | |
| 464 | - setInput, | |
| 465 | - open, | |
| 466 | - setOpen, | |
| 467 | 301 | widget, |
| 468 | 302 | }; |
| 469 | 303 | }; |
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 @@ | ||
| 39 | 39 | const { Icon } = ALERT_CONFIGS[type]; |
| 40 | 40 | |
| 41 | 41 | 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"> | |
| 43 | 43 | <div className="flex items-start"> |
| 44 | 44 | <Icon |
| 45 | 45 | 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"; | |
| 2 | 2 | |
| 3 | 3 | interface NumberInputProps { |
| 4 | 4 | value: number; |
| @@ -13,34 +13,62 @@ | ||
| 13 | 13 | max, |
| 14 | 14 | min, |
| 15 | 15 | }) => { |
| 16 | + const [inputValue, setInputValue] = useState(value.toString()); | |
| 17 | + | |
| 16 | 18 | const handleIncrement = () => { |
| 17 | 19 | if (value < max) { |
| 18 | - onChange(value + 1); | |
| 20 | + const newValue = value + 1; | |
| 21 | + onChange(newValue); | |
| 22 | + setInputValue(newValue.toString()); | |
| 19 | 23 | } |
| 20 | 24 | }; |
| 21 | 25 | |
| 22 | 26 | const handleDecrement = () => { |
| 23 | 27 | 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); | |
| 25 | 44 | } |
| 26 | 45 | }; |
| 27 | 46 | |
| 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 | + | |
| 28 | 53 | return ( |
| 29 | 54 | <div className="border-vsc-input-border bg-vsc-input-background flex flex-row overflow-hidden rounded-md border border-solid"> |
| 30 | 55 | <input |
| 31 | 56 | 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" | |
| 35 | 61 | style={{ |
| 36 | 62 | appearance: "none", |
| 37 | 63 | WebkitAppearance: "none", |
| 38 | 64 | MozAppearance: "none", |
| 39 | 65 | }} |
| 66 | + min={min} | |
| 67 | + max={max} | |
| 40 | 68 | /> |
| 41 | 69 | <div className="flex flex-col"> |
| 42 | 70 | <button |
| 43 | - style={{ fontSize: "10px" }} | |
| 71 | + style={{ fontSize: "9px" }} | |
| 44 | 72 | onClick={handleIncrement} |
| 45 | 73 | disabled={value >= max} |
| 46 | 74 | 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 @@ | ||
| 48 | 76 | ▲ |
| 49 | 77 | </button> |
| 50 | 78 | <button |
| 51 | - style={{ fontSize: "10px" }} | |
| 79 | + style={{ fontSize: "9px" }} | |
| 52 | 80 | className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80" |
| 53 | 81 | onClick={handleDecrement} |
| 54 | 82 | 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"; | |
| 2 | 2 | import { vscButtonBackground } from ".."; |
| 3 | 3 | |
| 4 | 4 | type ToggleSwitchProps = { |
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | onToggle: () => void; |
| 7 | 7 | text: string; |
| 8 | 8 | size?: number; |
| 9 | + showIfToggled?: ReactNode; | |
| 9 | 10 | }; |
| 10 | 11 | |
| 11 | 12 | const ToggleSwitch: React.FC<ToggleSwitchProps> = ({ |
| @@ -13,11 +14,13 @@ | ||
| 13 | 14 | onToggle, |
| 14 | 15 | text, |
| 15 | 16 | size = 16, |
| 17 | + showIfToggled, | |
| 16 | 18 | }) => { |
| 17 | 19 | return ( |
| 18 | 20 | <div className="flex cursor-pointer select-none items-center justify-between gap-3"> |
| 19 | 21 | <span className="truncate-right">{text}</span> |
| 20 | - <div> | |
| 22 | + <div className="flex flex-row items-center gap-1"> | |
| 23 | + {isToggled && !!showIfToggled && showIfToggled} | |
| 21 | 24 | <div |
| 22 | 25 | className={`border-vsc-input-border bg-vsc-input-background flex items-center rounded-full border border-solid`} |
| 23 | 26 | onClick={onToggle} |
modified gui/src/components/index.ts +23 −110
| @@ -1,114 +1,31 @@ | ||
| 1 | 1 | 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"; | |
| 44 | 3 | |
| 4 | +// DEPRECATED - avoid using these where possible, use tailwind classes instead | |
| 45 | 5 | export const defaultBorderRadius = "5px"; |
| 46 | 6 | export const lightGray = "#999998"; |
| 47 | 7 | export const greenButtonColor = "#189e72"; |
| 48 | 8 | |
| 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"); | |
| 112 | 29 | |
| 113 | 30 | export const Button = styled.button` |
| 114 | 31 | padding: 6px 12px; |
| @@ -158,7 +75,7 @@ | ||
| 158 | 75 | |
| 159 | 76 | border: none; |
| 160 | 77 | color: ${vscForeground}; |
| 161 | - background-color: rgba(255, 255, 255, 0.08); | |
| 78 | + background-color: rgba(128, 128, 128, 0.4); | |
| 162 | 79 | &:disabled { |
| 163 | 80 | color: gray; |
| 164 | 81 | pointer-events: none; |
| @@ -226,10 +143,6 @@ | ||
| 226 | 143 | } |
| 227 | 144 | `; |
| 228 | 145 | |
| 229 | -export const Label = styled.label<{ fontSize?: number }>` | |
| 230 | - font-size: ${(props) => props.fontSize || getFontSize()}px; | |
| 231 | -`; | |
| 232 | - | |
| 233 | 146 | export const HeaderButton = styled.button<{ |
| 234 | 147 | inverted: boolean | undefined; |
| 235 | 148 | backgroundColor?: string; |
modified gui/src/components/mainInput/CodeToEditCard.tsx +3 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline"; |
| 2 | -import { CodeToEdit } from "core"; | |
| 2 | +import { SetCodeToEditPayload } from "core"; | |
| 3 | 3 | import { getMarkdownLanguageTagForFile } from "core/util"; |
| 4 | 4 | import { getUriPathBasename } from "core/util/uri"; |
| 5 | 5 | import { useContext, useMemo, useState } from "react"; |
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | `; |
| 27 | 27 | |
| 28 | 28 | interface CodeToEditItemProps { |
| 29 | - code: CodeToEdit; | |
| 29 | + code: SetCodeToEditPayload; | |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | 32 | function CodeToEditItem({ code }: CodeToEditItemProps) { |
| @@ -143,6 +143,7 @@ | ||
| 143 | 143 | </div> |
| 144 | 144 | ); |
| 145 | 145 | } |
| 146 | + | |
| 146 | 147 | export default function CodeToEditCard() { |
| 147 | 148 | // Array from previous multi-file edit |
| 148 | 149 | const codeToEditArray = useAppSelector( |
modified gui/src/components/mainInput/ContinueInputBox.tsx +14 −5
| @@ -1,11 +1,12 @@ | ||
| 1 | 1 | import { Editor, JSONContent } from "@tiptap/react"; |
| 2 | -import { ContextItemWithId, InputModifiers } from "core"; | |
| 2 | +import { ContextItemWithId, InputModifiers, RuleWithSource } from "core"; | |
| 3 | 3 | import { useMemo } from "react"; |
| 4 | 4 | import styled, { keyframes } from "styled-components"; |
| 5 | 5 | import { defaultBorderRadius, vscBackground } from ".."; |
| 6 | 6 | import { useAppSelector } from "../../redux/hooks"; |
| 7 | 7 | import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; |
| 8 | 8 | import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; |
| 9 | +import { RulesPeek } from "./belowMainInput/RulesPeek"; | |
| 9 | 10 | import { ToolbarOptions } from "./InputToolbar"; |
| 10 | 11 | import { Lump } from "./Lump"; |
| 11 | 12 | import { TipTapEditor } from "./TipTapEditor"; |
| @@ -20,6 +21,7 @@ | ||
| 20 | 21 | ) => void; |
| 21 | 22 | editorState?: JSONContent; |
| 22 | 23 | contextItems?: ContextItemWithId[]; |
| 24 | + appliedRules?: RuleWithSource[]; | |
| 23 | 25 | hidden?: boolean; |
| 24 | 26 | inputId: string; // used to keep track of things per input in redux |
| 25 | 27 | } |
| @@ -116,6 +118,8 @@ | ||
| 116 | 118 | } |
| 117 | 119 | : {}; |
| 118 | 120 | |
| 121 | + const { appliedRules = [], contextItems = [] } = props; | |
| 122 | + | |
| 119 | 123 | return ( |
| 120 | 124 | <div |
| 121 | 125 | className={`${props.hidden ? "hidden" : ""}`} |
| @@ -143,10 +147,15 @@ | ||
| 143 | 147 | /> |
| 144 | 148 | </GradientBorder> |
| 145 | 149 | </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 | + )} | |
| 150 | 159 | </div> |
| 151 | 160 | ); |
| 152 | 161 | } |
modified gui/src/components/mainInput/EditModeDetails.tsx +2 −2
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 3 | 3 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| 4 | 4 | import { exitEditMode } from "../../redux/thunks/editMode"; |
| 5 | -import AcceptRejectAllButtons from "../AcceptRejectAllButtons"; | |
| 5 | +import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons"; | |
| 6 | 6 | import { useMainEditor } from "./TipTapEditor"; |
| 7 | 7 | |
| 8 | 8 | const EditModeDetails = () => { |
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | <div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400"> |
| 29 | 29 | <span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span> |
| 30 | 30 | </div> |
| 31 | - <AcceptRejectAllButtons | |
| 31 | + <AcceptRejectDiffButtons | |
| 32 | 32 | applyStates={[editApplyState]} |
| 33 | 33 | onAcceptOrReject={async (outcome) => { |
| 34 | 34 | 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"; | |
| 2 | 2 | import { useSelector } from "react-redux"; |
| 3 | 3 | import styled from "styled-components"; |
| 4 | 4 | import { AnimatedEllipsis } from "../.."; |
| @@ -40,12 +40,27 @@ | ||
| 40 | 40 | ); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | +function ApplyingIndicator() { | |
| 44 | + return ( | |
| 45 | + <div className="text-xs text-gray-400"> | |
| 46 | + <span>Applying</span> | |
| 47 | + <AnimatedEllipsis /> | |
| 48 | + </div> | |
| 49 | + ); | |
| 50 | +} | |
| 51 | + | |
| 43 | 52 | export function LumpToolbar() { |
| 44 | 53 | const dispatch = useAppDispatch(); |
| 45 | 54 | const ideMessenger = useContext(IdeMessengerContext); |
| 46 | 55 | const ttsActive = useAppSelector((state) => state.ui.ttsActive); |
| 47 | 56 | const isStreaming = useAppSelector((state) => state.session.isStreaming); |
| 48 | 57 | 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]); | |
| 49 | 64 | |
| 50 | 65 | const toolCallState = useSelector(selectCurrentToolCall); |
| 51 | 66 | |
| @@ -89,6 +104,26 @@ | ||
| 89 | 104 | ); |
| 90 | 105 | } |
| 91 | 106 | |
| 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 | + | |
| 92 | 127 | if (isStreaming) { |
| 93 | 128 | return ( |
| 94 | 129 | <Container> |
modified gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +1 −1
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | |
| 50 | 50 | return ( |
| 51 | 51 | <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" | |
| 53 | 53 | style={{ |
| 54 | 54 | fontSize: fontSize(-3), |
| 55 | 55 | }} |
modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +57 −11
| @@ -1,9 +1,13 @@ | ||
| 1 | +import { parseConfigYaml } from "@continuedev/config-yaml"; | |
| 1 | 2 | import { |
| 2 | 3 | BookmarkIcon as BookmarkOutline, |
| 3 | 4 | PencilIcon, |
| 4 | 5 | } from "@heroicons/react/24/outline"; |
| 5 | 6 | import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid"; |
| 6 | 7 | import { SlashCommandDescription } from "core"; |
| 8 | +import { useContext, useMemo } from "react"; | |
| 9 | +import { useAuth } from "../../../../context/Auth"; | |
| 10 | +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; | |
| 7 | 11 | import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands"; |
| 8 | 12 | import { useAppSelector } from "../../../../redux/hooks"; |
| 9 | 13 | import { fontSize } from "../../../../util"; |
| @@ -11,8 +15,10 @@ | ||
| 11 | 15 | import { useLump } from "../LumpContext"; |
| 12 | 16 | import { ExploreBlocksButton } from "./ExploreBlocksButton"; |
| 13 | 17 | |
| 18 | +type PromptWithSlug = SlashCommandDescription & { slug?: string }; | |
| 19 | + | |
| 14 | 20 | interface PromptRowProps { |
| 15 | - prompt: SlashCommandDescription; | |
| 21 | + prompt: PromptWithSlug; | |
| 16 | 22 | isBookmarked: boolean; |
| 17 | 23 | setIsBookmarked: (isBookmarked: boolean) => void; |
| 18 | 24 | onEdit?: () => void; |
| @@ -88,24 +94,64 @@ | ||
| 88 | 94 | * Section that displays all available prompts with bookmarking functionality |
| 89 | 95 | */ |
| 90 | 96 | export function PromptsSection() { |
| 97 | + const { selectedProfile } = useAuth(); | |
| 91 | 98 | const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands(); |
| 99 | + const ideMessenger = useContext(IdeMessengerContext); | |
| 92 | 100 | |
| 93 | 101 | const slashCommands = useAppSelector( |
| 94 | 102 | (state) => state.config.config.slashCommands ?? [], |
| 95 | 103 | ); |
| 96 | 104 | |
| 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 | + } | |
| 100 | 120 | }; |
| 101 | 121 | |
| 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]); | |
| 109 | 155 | |
| 110 | 156 | return ( |
| 111 | 157 | <div className="flex flex-col"> |
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
| @@ -159,7 +159,7 @@ | ||
| 159 | 159 | contentEditable={false} |
| 160 | 160 | > |
| 161 | 161 | <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" | |
| 163 | 163 | style={{ |
| 164 | 164 | fontSize: getFontSize() - 3, |
| 165 | 165 | }} |
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 @@ | ||
| 173 | 173 | {mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />} |
| 174 | 174 | </ListboxOption> |
| 175 | 175 | |
| 176 | - <ListboxOption value="agent" disabled={!agentModeSupported}> | |
| 176 | + <ListboxOption | |
| 177 | + value="agent" | |
| 178 | + disabled={!agentModeSupported} | |
| 179 | + className={"gap-1"} | |
| 180 | + > | |
| 177 | 181 | <div className="flex flex-row items-center gap-1.5"> |
| 178 | 182 | <SparklesIcon className="h-3 w-3" /> |
| 179 | 183 | <span className="">Agent</span> |
| 180 | 184 | </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 | + )} | |
| 183 | 190 | </ListboxOption> |
| 184 | 191 | |
| 185 | 192 | <div className="text-lightgray px-2 py-1"> |
| 186 | - {metaKeyLabel}. for next mode | |
| 193 | + {`${metaKeyLabel} . for next mode`} | |
| 187 | 194 | </div> |
| 188 | 195 | </ListboxOptions> |
| 189 | 196 | </div> |
modified gui/src/components/modelSelection/ModelSelect.tsx +7 −3
| @@ -166,7 +166,11 @@ | ||
| 166 | 166 | |
| 167 | 167 | useEffect(() => { |
| 168 | 168 | 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 | + ) { | |
| 170 | 174 | if (!selectedProfile) { |
| 171 | 175 | return; |
| 172 | 176 | } |
| @@ -179,7 +183,7 @@ | ||
| 179 | 183 | if (nextIndex < 0) nextIndex = options.length - 1; |
| 180 | 184 | const newModelTitle = options[nextIndex].value; |
| 181 | 185 | |
| 182 | - dispatch( | |
| 186 | + void dispatch( | |
| 183 | 187 | updateSelectedModelByRole({ |
| 184 | 188 | selectedProfile, |
| 185 | 189 | role: "chat", |
| @@ -219,7 +223,7 @@ | ||
| 219 | 223 | <Listbox |
| 220 | 224 | onChange={async (val: string) => { |
| 221 | 225 | if (val === selectedModel?.title) return; |
| 222 | - dispatch( | |
| 226 | + void dispatch( | |
| 223 | 227 | updateSelectedModelByRole({ |
| 224 | 228 | selectedProfile, |
| 225 | 229 | role: mode === "edit" ? "edit" : "chat", |
modified gui/src/context/Auth.tsx +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | OrganizationDescription, |
| 3 | 3 | ProfileDescription, |
| 4 | 4 | } from "core/config/ProfileLifecycleManager"; |
| 5 | -import { ControlPlaneSessionInfo } from "core/control-plane/client"; | |
| 5 | +import { ControlPlaneSessionInfo } from "core/control-plane/AuthTypes"; | |
| 6 | 6 | import React, { |
| 7 | 7 | createContext, |
| 8 | 8 | useCallback, |
modified gui/src/context/LocalStorage.tsx +0 −1
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | const [values, setValues] = useState<LocalStorageType>(DEFAULT_LOCAL_STORAGE); |
| 20 | 20 | |
| 21 | 21 | // TODO setvalue |
| 22 | - | |
| 23 | 22 | useEffect(() => { |
| 24 | 23 | const isJetbrains = getLocalStorage("ide") === "jetbrains"; |
| 25 | 24 | let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14); |
modified gui/src/context/MockIdeMessenger.ts +40 −2
| @@ -1,9 +1,12 @@ | ||
| 1 | 1 | import { IDE, PromptLog } from "core"; |
| 2 | +import { AuthType } from "core/control-plane/AuthTypes"; | |
| 2 | 3 | import { |
| 4 | + FromIdeProtocol, | |
| 3 | 5 | FromWebviewProtocol, |
| 4 | 6 | ToCoreProtocol, |
| 5 | 7 | ToWebviewProtocol, |
| 6 | 8 | } from "core/protocol"; |
| 9 | +import { Message } from "core/protocol/messenger"; | |
| 7 | 10 | import { MessageIde } from "core/protocol/messenger/messageIde"; |
| 8 | 11 | import { |
| 9 | 12 | GeneratorReturnType, |
| @@ -36,6 +39,7 @@ | ||
| 36 | 39 | ]); |
| 37 | 40 | case "getControlPlaneSessionInfo": |
| 38 | 41 | return returnFor("getControlPlaneSessionInfo", { |
| 42 | + AUTH_TYPE: AuthType.WorkOsStaging, | |
| 39 | 43 | accessToken: "", |
| 40 | 44 | account: { |
| 41 | 45 | label: "", |
| @@ -60,13 +64,48 @@ | ||
| 60 | 64 | |
| 61 | 65 | export class MockIdeMessenger implements IIdeMessenger { |
| 62 | 66 | ide: IDE; |
| 67 | + private messageHandlers: Map< | |
| 68 | + keyof FromIdeProtocol, | |
| 69 | + Array<(data: any) => void> | |
| 70 | + > = new Map(); | |
| 63 | 71 | |
| 64 | 72 | constructor() { |
| 65 | 73 | this.ide = new MessageIde( |
| 66 | 74 | (messageType, data) => { |
| 67 | 75 | throw new Error("Not implemented"); |
| 68 | 76 | }, |
| 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 | + }), | |
| 70 | 109 | ); |
| 71 | 110 | } |
| 72 | 111 | |
| @@ -80,7 +119,6 @@ | ||
| 80 | 119 | content: "This is a test", |
| 81 | 120 | }, |
| 82 | 121 | ]; |
| 83 | - | |
| 84 | 122 | return undefined; |
| 85 | 123 | } |
| 86 | 124 |
modified gui/src/context/VscTheme.tsx +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { createContext, useContext, useState } from "react"; |
| 2 | -import { parseHexColor } from "../components"; | |
| 3 | 2 | import { useWebviewListener } from "../hooks/useWebviewListener"; |
| 3 | +import { parseHexColor } from "../styles/utils"; | |
| 4 | 4 | |
| 5 | 5 | const hljsToTextMate: Record<string, string[]> = { |
| 6 | 6 | ".hljs-comment": ["comment"], |
modified gui/src/hooks/ParallelListeners.tsx +7 −34
| @@ -1,5 +1,4 @@ | ||
| 1 | 1 | import { useCallback, useContext, useEffect, useRef } from "react"; |
| 2 | -import { VSC_THEME_COLOR_VARS } from "../components"; | |
| 3 | 2 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 4 | 3 | |
| 5 | 4 | import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; |
| @@ -29,6 +28,10 @@ | ||
| 29 | 28 | import { refreshSessionMetadata } from "../redux/thunks/session"; |
| 30 | 29 | import { streamResponseThunk } from "../redux/thunks/streamResponse"; |
| 31 | 30 | import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; |
| 31 | +import { | |
| 32 | + setDocumentStylesFromLocalStorage, | |
| 33 | + setDocumentStylesFromTheme, | |
| 34 | +} from "../styles/theme"; | |
| 32 | 35 | import { isJetBrains } from "../util"; |
| 33 | 36 | import { setLocalStorage } from "../util/localStorage"; |
| 34 | 37 | import { useWebviewListener } from "./useWebviewListener"; |
| @@ -139,31 +142,13 @@ | ||
| 139 | 142 | dispatch(cancelStream()); |
| 140 | 143 | |
| 141 | 144 | 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); | |
| 158 | 146 | |
| 159 | 147 | if (jetbrains) { |
| 160 | 148 | // Save theme colors to local storage for immediate loading in JetBrains |
| 161 | 149 | ideMessenger.request("jetbrains/getColors", undefined).then((result) => { |
| 162 | 150 | 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); | |
| 167 | 152 | } |
| 168 | 153 | }); |
| 169 | 154 | |
| @@ -180,25 +165,13 @@ | ||
| 180 | 165 | (window as any).vscMachineId = msg.vscMachineId; |
| 181 | 166 | (window as any).vscMediaUrl = msg.vscMediaUrl; |
| 182 | 167 | }); |
| 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 | - } | |
| 192 | 168 | } |
| 193 | 169 | }, []); |
| 194 | 170 | |
| 195 | 171 | useWebviewListener( |
| 196 | 172 | "jetbrains/setColors", |
| 197 | 173 | 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); | |
| 202 | 175 | }, |
| 203 | 176 | [], |
| 204 | 177 | ); |
modified gui/src/pages/config/AccountButton.tsx +6 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import { UserCircleIcon } from "@heroicons/react/24/solid"; |
| 2 | 2 | |
| 3 | +import { isHubSession } from "core/control-plane/AuthTypes"; | |
| 3 | 4 | import { SecondaryButton } from "../../components"; |
| 4 | 5 | import { |
| 5 | 6 | Popover, |
| @@ -27,6 +28,11 @@ | ||
| 27 | 28 | ); |
| 28 | 29 | } |
| 29 | 30 | |
| 31 | + // No login button for on-prem deployments | |
| 32 | + if (!isHubSession(session)) { | |
| 33 | + return null; | |
| 34 | + } | |
| 35 | + | |
| 30 | 36 | return ( |
| 31 | 37 | <Popover className="relative"> |
| 32 | 38 | {({ close }) => ( |
modified gui/src/pages/config/HelpCenterSection.tsx +21 −0
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | 3 | DocumentArrowUpIcon, |
| 4 | + PaintBrushIcon, | |
| 4 | 5 | TableCellsIcon, |
| 5 | 6 | } from "@heroicons/react/24/outline"; |
| 6 | 7 | import { useContext } from "react"; |
| @@ -9,6 +10,7 @@ | ||
| 9 | 10 | import { useAppDispatch } from "../../redux/hooks"; |
| 10 | 11 | import { setOnboardingCard } from "../../redux/slices/uiSlice"; |
| 11 | 12 | import { saveCurrentSession } from "../../redux/thunks/session"; |
| 13 | +import { ROUTES } from "../../util/navigation"; | |
| 12 | 14 | import MoreHelpRow from "./MoreHelpRow"; |
| 13 | 15 | |
| 14 | 16 | export function HelpCenterSection() { |
| @@ -20,6 +22,15 @@ | ||
| 20 | 22 | <div className="py-5"> |
| 21 | 23 | <h3 className="mb-4 mt-0 text-xl">Help center</h3> |
| 22 | 24 | <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 | + | |
| 23 | 34 | <MoreHelpRow |
| 24 | 35 | title="Documentation" |
| 25 | 36 | description="Learn how to configure and use Continue" |
| @@ -74,6 +85,16 @@ | ||
| 74 | 85 | ideMessenger.post("showTutorial", undefined); |
| 75 | 86 | }} |
| 76 | 87 | /> |
| 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 | + )} | |
| 77 | 98 | </div> |
| 78 | 99 | </div> |
| 79 | 100 | ); |
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | function KeyboardShortcut(props: KeyboardShortcutProps) { |
| 12 | 12 | return ( |
| 13 | 13 | <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"}`} | |
| 15 | 15 | > |
| 16 | 16 | <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0"> |
| 17 | 17 | <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"; | |
| 2 | 7 | import { |
| 3 | 8 | SharedConfigSchema, |
| 4 | 9 | modifyAnyConfigWithSharedConfig, |
| @@ -8,16 +13,19 @@ | ||
| 8 | 13 | import NumberInput from "../../components/gui/NumberInput"; |
| 9 | 14 | import { Select } from "../../components/gui/Select"; |
| 10 | 15 | import ToggleSwitch from "../../components/gui/Switch"; |
| 16 | +import { ToolTip } from "../../components/gui/Tooltip"; | |
| 17 | +import { useFontSize } from "../../components/ui/font"; | |
| 11 | 18 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 12 | 19 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| 13 | 20 | import { updateConfig } from "../../redux/slices/configSlice"; |
| 14 | -import { getFontSize } from "../../util"; | |
| 21 | +import { setLocalStorage } from "../../util/localStorage"; | |
| 15 | 22 | |
| 16 | 23 | export function UserSettingsForm() { |
| 17 | 24 | /////// User settings section ////// |
| 18 | 25 | const dispatch = useAppDispatch(); |
| 19 | 26 | const ideMessenger = useContext(IdeMessengerContext); |
| 20 | 27 | const config = useAppSelector((state) => state.config.config); |
| 28 | + const [showExperimental, setShowExperimental] = useState(false); | |
| 21 | 29 | |
| 22 | 30 | function handleUpdate(sharedConfig: SharedConfigSchema) { |
| 23 | 31 | // Optimistic update |
| @@ -65,6 +73,7 @@ | ||
| 65 | 73 | const codeWrap = config.ui?.codeWrap ?? false; |
| 66 | 74 | const showChatScrollbar = config.ui?.showChatScrollbar ?? false; |
| 67 | 75 | const readResponseTTS = config.experimental?.readResponseTTS ?? false; |
| 76 | + const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false; | |
| 68 | 77 | const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false; |
| 69 | 78 | const disableSessionTitles = config.disableSessionTitles ?? false; |
| 70 | 79 | |
| @@ -77,7 +86,9 @@ | ||
| 77 | 86 | // const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top"; |
| 78 | 87 | const useAutocompleteMultilineCompletions = |
| 79 | 88 | 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(); | |
| 81 | 92 | |
| 82 | 93 | const cancelChangeDisableAutocomplete = () => { |
| 83 | 94 | setFormDisableAutocomplete(disableAutocompleteInFiles); |
| @@ -99,7 +110,7 @@ | ||
| 99 | 110 | }, [ideMessenger]); |
| 100 | 111 | |
| 101 | 112 | return ( |
| 102 | - <div className="flex flex-col pt-3"> | |
| 113 | + <div className="flex flex-col"> | |
| 103 | 114 | {/* {selectedProfile && isLocalProfile(selectedProfile) ? ( |
| 104 | 115 | <div className="flex items-center justify-center"> |
| 105 | 116 | <SecondaryButton |
| @@ -160,7 +171,6 @@ | ||
| 160 | 171 | } |
| 161 | 172 | text="Text-to-Speech Output" |
| 162 | 173 | /> |
| 163 | - | |
| 164 | 174 | {/* <ToggleSwitch |
| 165 | 175 | isToggled={useChromiumForDocsCrawling} |
| 166 | 176 | onToggle={() => |
| @@ -223,18 +233,18 @@ | ||
| 223 | 233 | <span className="text-left">Font Size</span> |
| 224 | 234 | <NumberInput |
| 225 | 235 | value={fontSize} |
| 226 | - onChange={(val) => | |
| 236 | + onChange={(val) => { | |
| 237 | + setLocalStorage("fontSize", val); | |
| 227 | 238 | handleUpdate({ |
| 228 | 239 | fontSize: val, |
| 229 | - }) | |
| 230 | - } | |
| 240 | + }); | |
| 241 | + }} | |
| 231 | 242 | min={7} |
| 232 | 243 | max={50} |
| 233 | 244 | /> |
| 234 | 245 | </label> |
| 235 | - | |
| 236 | 246 | <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"> | |
| 238 | 248 | Multiline Autocompletions |
| 239 | 249 | </span> |
| 240 | 250 | <Select |
| @@ -253,7 +263,32 @@ | ||
| 253 | 263 | <option value="never">Never</option> |
| 254 | 264 | </Select> |
| 255 | 265 | </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> | |
| 257 | 292 | <form |
| 258 | 293 | className="flex flex-col gap-1" |
| 259 | 294 | onSubmit={(e) => { |
| @@ -300,6 +335,48 @@ | ||
| 300 | 335 | </span> |
| 301 | 336 | </form> |
| 302 | 337 | </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> | |
| 303 | 380 | </div> |
| 304 | 381 | ) : null} |
| 305 | 382 | </div> |
modified gui/src/pages/config/index.tsx +4 −4
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { |
| 2 | - AcademicCapIcon, | |
| 2 | + BoltIcon, | |
| 3 | 3 | CircleStackIcon, |
| 4 | 4 | Cog6ToothIcon, |
| 5 | 5 | QuestionMarkCircleIcon, |
| @@ -52,7 +52,7 @@ | ||
| 52 | 52 | id: "shortcuts", |
| 53 | 53 | label: "Shortcuts", |
| 54 | 54 | 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" />, | |
| 56 | 56 | }, |
| 57 | 57 | ]; |
| 58 | 58 | |
| @@ -67,14 +67,14 @@ | ||
| 67 | 67 | /> |
| 68 | 68 | |
| 69 | 69 | {/* 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"> | |
| 71 | 71 | {tabs.map((tab) => ( |
| 72 | 72 | <div |
| 73 | 73 | style={{ |
| 74 | 74 | fontSize: fontSize(-2), |
| 75 | 75 | }} |
| 76 | 76 | 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 ${ | |
| 78 | 78 | activeTab === tab.id ? "" : "text-gray-400" |
| 79 | 79 | }`} |
| 80 | 80 | onClick={() => setActiveTab(tab.id)} |
modified gui/src/pages/gui/Chat.test.tsx +47 −0
| @@ -59,4 +59,51 @@ | ||
| 59 | 59 | }); |
| 60 | 60 | expect(await screen.findByText("Hello, world!")).toBeInTheDocument(); |
| 61 | 61 | }); |
| 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 | + }); | |
| 62 | 109 | }); |
modified gui/src/pages/gui/Chat.tsx +21 −29
| @@ -1,8 +1,6 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowLeftIcon, |
| 3 | 3 | ChatBubbleOvalLeftIcon, |
| 4 | - CodeBracketSquareIcon, | |
| 5 | - ExclamationTriangleIcon, | |
| 6 | 4 | } from "@heroicons/react/24/outline"; |
| 7 | 5 | import { Editor, JSONContent } from "@tiptap/react"; |
| 8 | 6 | import { InputModifiers } from "core"; |
| @@ -20,7 +18,6 @@ | ||
| 20 | 18 | import { ErrorBoundary } from "react-error-boundary"; |
| 21 | 19 | import styled from "styled-components"; |
| 22 | 20 | import { Button, lightGray, vscBackground } from "../../components"; |
| 23 | -import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons"; | |
| 24 | 21 | import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; |
| 25 | 22 | import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; |
| 26 | 23 | import { useFindWidget } from "../../components/find/FindWidget"; |
| @@ -47,16 +44,17 @@ | ||
| 47 | 44 | setDialogMessage, |
| 48 | 45 | setShowDialog, |
| 49 | 46 | } from "../../redux/slices/uiSlice"; |
| 47 | +import { streamResponseThunk } from "../../redux/thunks"; | |
| 50 | 48 | import { cancelStream } from "../../redux/thunks/cancelStream"; |
| 51 | 49 | import { streamEditThunk } from "../../redux/thunks/editMode"; |
| 52 | 50 | import { loadLastSession } from "../../redux/thunks/session"; |
| 53 | -import { streamResponseThunk } from "../../redux/thunks/streamResponse"; | |
| 54 | 51 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 55 | 52 | import { |
| 56 | 53 | FREE_TRIAL_LIMIT_REQUESTS, |
| 57 | 54 | incrementFreeTrialCount, |
| 58 | 55 | } from "../../util/freeTrial"; |
| 59 | 56 | |
| 57 | +import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; | |
| 60 | 58 | import CodeToEditCard from "../../components/mainInput/CodeToEditCard"; |
| 61 | 59 | import EditModeDetails from "../../components/mainInput/EditModeDetails"; |
| 62 | 60 | import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; |
| @@ -74,7 +72,7 @@ | ||
| 74 | 72 | } |
| 75 | 73 | |
| 76 | 74 | .thread-message { |
| 77 | - margin: 0px 0px 0px 1px; | |
| 75 | + margin: 0 0 0 1px; | |
| 78 | 76 | } |
| 79 | 77 | `; |
| 80 | 78 | |
| @@ -112,9 +110,10 @@ | ||
| 112 | 110 | (store) => store.config?.config.selectedModelByRole, |
| 113 | 111 | ); |
| 114 | 112 | const isStreaming = useAppSelector((state) => state.session.isStreaming); |
| 115 | - const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); | |
| 113 | + const [stepsOpen] = useState<(boolean | undefined)[]>([]); | |
| 116 | 114 | const mainTextInputRef = useRef<HTMLInputElement>(null); |
| 117 | 115 | const stepsDivRef = useRef<HTMLDivElement>(null); |
| 116 | + const tabsRef = useRef<HTMLDivElement>(null); | |
| 118 | 117 | const history = useAppSelector((state) => state.session.history); |
| 119 | 118 | const showChatScrollbar = useAppSelector( |
| 120 | 119 | (state) => state.config.config.ui?.showChatScrollbar, |
| @@ -134,6 +133,8 @@ | ||
| 134 | 133 | return isJetBrains(); |
| 135 | 134 | }, []); |
| 136 | 135 | |
| 136 | + useAutoScroll(stepsDivRef, history); | |
| 137 | + | |
| 137 | 138 | useEffect(() => { |
| 138 | 139 | // Cmd + Backspace to delete current step |
| 139 | 140 | const listener = (e: any) => { |
| @@ -143,6 +144,7 @@ | ||
| 143 | 144 | !e.shiftKey |
| 144 | 145 | ) { |
| 145 | 146 | dispatch(cancelStream()); |
| 147 | + ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter | |
| 146 | 148 | } |
| 147 | 149 | }; |
| 148 | 150 | window.addEventListener("keydown", listener); |
| @@ -152,7 +154,11 @@ | ||
| 152 | 154 | }; |
| 153 | 155 | }, [isStreaming, jetbrains]); |
| 154 | 156 | |
| 155 | - const { widget, highlights } = useFindWidget(stepsDivRef); | |
| 157 | + const { widget, highlights } = useFindWidget( | |
| 158 | + stepsDivRef, | |
| 159 | + tabsRef, | |
| 160 | + isStreaming, | |
| 161 | + ); | |
| 156 | 162 | |
| 157 | 163 | const currentToolCallApplyState = useAppSelector( |
| 158 | 164 | selectCurrentToolCallApplyState, |
| @@ -200,7 +206,7 @@ | ||
| 200 | 206 | if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) { |
| 201 | 207 | // Show this message whether using platform or not |
| 202 | 208 | // So that something happens if in new chat |
| 203 | - ideMessenger.ide.showToast( | |
| 209 | + void ideMessenger.ide.showToast( | |
| 204 | 210 | "error", |
| 205 | 211 | "You've reached the free trial limit. Please configure a model to continue.", |
| 206 | 212 | ); |
| @@ -284,24 +290,21 @@ | ||
| 284 | 290 | |
| 285 | 291 | const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000; |
| 286 | 292 | |
| 287 | - useAutoScroll(stepsDivRef, history); | |
| 288 | - | |
| 289 | 293 | return ( |
| 290 | 294 | <> |
| 295 | + {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />} | |
| 291 | 296 | {widget} |
| 292 | 297 | |
| 293 | - {!!showSessionTabs && mode !== "edit" && <TabBar />} | |
| 294 | - | |
| 295 | 298 | <StepsDiv |
| 296 | 299 | 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" : ""}`} | |
| 298 | 301 | > |
| 299 | 302 | {highlights} |
| 300 | 303 | {history.map((item, index: number) => ( |
| 301 | 304 | <div |
| 302 | 305 | key={item.message.id} |
| 303 | 306 | style={{ |
| 304 | - minHeight: index === history.length - 1 ? "25vh" : 0, | |
| 307 | + minHeight: index === history.length - 1 ? "200px" : 0, | |
| 305 | 308 | }} |
| 306 | 309 | > |
| 307 | 310 | <ErrorBoundary |
| @@ -320,6 +323,7 @@ | ||
| 320 | 323 | isMainInput={false} |
| 321 | 324 | editorState={item.editorState} |
| 322 | 325 | contextItems={item.contextItems} |
| 326 | + appliedRules={item.appliedRules} | |
| 323 | 327 | inputId={item.message.id} |
| 324 | 328 | /> |
| 325 | 329 | </> |
| @@ -355,23 +359,11 @@ | ||
| 355 | 359 | <TimelineItem |
| 356 | 360 | item={item} |
| 357 | 361 | 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" /> | |
| 369 | 363 | } |
| 370 | 364 | open={ |
| 371 | 365 | typeof stepsOpen[index] === "undefined" |
| 372 | - ? false | |
| 373 | - ? false | |
| 374 | - : true | |
| 366 | + ? true | |
| 375 | 367 | : stepsOpen[index]! |
| 376 | 368 | } |
| 377 | 369 | onToggle={() => {}} |
| @@ -391,7 +383,7 @@ | ||
| 391 | 383 | <div className={"relative"}> |
| 392 | 384 | <> |
| 393 | 385 | {!isStreaming && mode !== "edit" && ( |
| 394 | - <AcceptRejectAllButtons | |
| 386 | + <AcceptRejectDiffButtons | |
| 395 | 387 | applyStates={applyStates} |
| 396 | 388 | onAcceptOrReject={async () => {}} |
| 397 | 389 | /> |
modified gui/src/pages/gui/StreamError.tsx +86 −47
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | - Cog8ToothIcon, | |
| 3 | + ClipboardIcon, | |
| 4 | + Cog6ToothIcon, | |
| 5 | + KeyIcon, | |
| 4 | 6 | } from "@heroicons/react/24/outline"; |
| 5 | 7 | import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; |
| 6 | 8 | import { useContext, useMemo } from "react"; |
| 7 | -import { Button, SecondaryButton } from "../../components"; | |
| 9 | +import { GhostButton, SecondaryButton } from "../../components"; | |
| 8 | 10 | import { DiscordIcon } from "../../components/svg/DiscordIcon"; |
| 9 | 11 | import { GithubIcon } from "../../components/svg/GithubIcon"; |
| 12 | +import ToggleDiv from "../../components/ToggleDiv"; | |
| 10 | 13 | import { useAuth } from "../../context/Auth"; |
| 11 | 14 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 12 | 15 | import { selectSelectedProfile } from "../../redux/"; |
| @@ -48,11 +51,15 @@ | ||
| 48 | 51 | ); |
| 49 | 52 | |
| 50 | 53 | const handleRefreshProfiles = () => { |
| 51 | - refreshProfiles(); | |
| 54 | + void refreshProfiles(); | |
| 52 | 55 | dispatch(setShowDialog(false)); |
| 53 | 56 | dispatch(setDialogMessage(undefined)); |
| 54 | 57 | }; |
| 55 | 58 | |
| 59 | + const copyErrorToClipboard = () => { | |
| 60 | + void navigator.clipboard.writeText(parsedError); | |
| 61 | + }; | |
| 62 | + | |
| 56 | 63 | // Collect model information to display useful error info |
| 57 | 64 | let modelTitle = "Chat model"; |
| 58 | 65 | let providerName = "the model provider"; |
| @@ -99,30 +106,29 @@ | ||
| 99 | 106 | } |
| 100 | 107 | |
| 101 | 108 | const checkKeysButton = apiKeyUrl ? ( |
| 102 | - <Button | |
| 103 | - className="cursor-pointer hover:underline" | |
| 109 | + <GhostButton | |
| 110 | + className="flex items-center" | |
| 104 | 111 | onClick={() => { |
| 105 | 112 | ideMessenger.post("openUrl", apiKeyUrl!); |
| 106 | 113 | }} |
| 107 | 114 | > |
| 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> | |
| 110 | 118 | ) : null; |
| 111 | 119 | |
| 112 | 120 | 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" | |
| 115 | 123 | onClick={() => { |
| 116 | 124 | ideMessenger.post("config/openProfile", { |
| 117 | 125 | profileId: undefined, |
| 118 | 126 | }); |
| 119 | 127 | }} |
| 120 | 128 | > |
| 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> | |
| 126 | 132 | ); |
| 127 | 133 | |
| 128 | 134 | if ( |
| @@ -131,7 +137,20 @@ | ||
| 131 | 137 | return <ModelsAddOnLimitDialog />; |
| 132 | 138 | } |
| 133 | 139 | |
| 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 | + ); | |
| 135 | 154 | |
| 136 | 155 | // Display components for specific errors |
| 137 | 156 | if (statusCode === 429) { |
| @@ -141,7 +160,7 @@ | ||
| 141 | 160 | {`This might mean your ${modelTitle} usage has been rate limited |
| 142 | 161 | by ${providerName}.`} |
| 143 | 162 | </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"> | |
| 145 | 164 | {checkKeysButton} |
| 146 | 165 | {configButton} |
| 147 | 166 | </div> |
| @@ -230,51 +249,71 @@ | ||
| 230 | 249 | ); |
| 231 | 250 | } |
| 232 | 251 | |
| 252 | + console.log({ message }); | |
| 253 | + | |
| 233 | 254 | 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> | |
| 253 | 293 | </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" | |
| 262 | 301 | onClick={() => { |
| 263 | 302 | ideMessenger.post("openUrl", GITHUB_LINK); |
| 264 | 303 | }} |
| 265 | 304 | > |
| 266 | 305 | <GithubIcon className="h-5 w-5" /> |
| 267 | 306 | <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" | |
| 271 | 310 | onClick={() => { |
| 272 | 311 | ideMessenger.post("openUrl", DISCORD_LINK); |
| 273 | 312 | }} |
| 274 | 313 | > |
| 275 | 314 | <DiscordIcon className="h-5 w-5" /> |
| 276 | 315 | <span className="xs:flex hidden">Discord</span> |
| 277 | - </SecondaryButton> | |
| 316 | + </GhostButton> | |
| 278 | 317 | </div> |
| 279 | 318 | </div> |
| 280 | 319 | </div> |
modified gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +4 −0
| @@ -8,6 +8,10 @@ | ||
| 8 | 8 | } |
| 9 | 9 | |
| 10 | 10 | export function CreateFile(props: CreateFileToolCallProps) { |
| 11 | + if (!props.fileContents) { | |
| 12 | + return null; | |
| 13 | + } | |
| 14 | + | |
| 11 | 15 | const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; |
| 12 | 16 | |
| 13 | 17 | return props.relativeFilepath ? ( |
modified gui/src/pages/gui/ToolCallDiv/EditFile.tsx +5 −4
| @@ -16,13 +16,12 @@ | ||
| 16 | 16 | }; |
| 17 | 17 | |
| 18 | 18 | export function EditFile(props: EditToolCallProps) { |
| 19 | - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes ?? ""}\n\`\`\``; | |
| 20 | - | |
| 21 | 19 | const dispatch = useAppDispatch(); |
| 22 | - const isStreaming = useAppSelector((state) => state.session.isStreaming); | |
| 20 | + | |
| 23 | 21 | const applyState = useAppSelector((state) => |
| 24 | 22 | selectApplyStateByToolCallId(state, props.toolCallId), |
| 25 | 23 | ); |
| 24 | + | |
| 26 | 25 | useEffect(() => { |
| 27 | 26 | if (!applyState) { |
| 28 | 27 | dispatch( |
| @@ -35,10 +34,12 @@ | ||
| 35 | 34 | } |
| 36 | 35 | }, [applyState, props.toolCallId]); |
| 37 | 36 | |
| 38 | - if (!props.relativeFilePath) { | |
| 37 | + if (!props.relativeFilePath || !props.changes) { | |
| 39 | 38 | return null; |
| 40 | 39 | } |
| 41 | 40 | |
| 41 | + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``; | |
| 42 | + | |
| 42 | 43 | return ( |
| 43 | 44 | <StyledMarkdownPreview |
| 44 | 45 | isRenderingInStepContainer |
modified gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +2 −2
| @@ -27,8 +27,8 @@ | ||
| 27 | 27 | case BuiltInToolNames.EditExistingFile: |
| 28 | 28 | return ( |
| 29 | 29 | <EditFile |
| 30 | - relativeFilePath={args.filepath} | |
| 31 | - changes={args.changes} | |
| 30 | + relativeFilePath={args.filepath ?? ""} | |
| 31 | + changes={args.changes ?? ""} | |
| 32 | 32 | toolCallId={toolCall.id} |
| 33 | 33 | historyIndex={historyIndex} |
| 34 | 34 | /> |
modified gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +1 −1
| @@ -61,7 +61,7 @@ | ||
| 61 | 61 | </div> |
| 62 | 62 | <span |
| 63 | 63 | className="ml-1 text-xs text-gray-400 transition-colors duration-200" |
| 64 | - data-testid="toggle-div-title" | |
| 64 | + data-testid="tool-call-title" | |
| 65 | 65 | > |
| 66 | 66 | <ToolCallStatusMessage tool={tool} toolCallState={toolCallState} /> |
| 67 | 67 | </span> |
modified gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx +4 −1
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | import { Tool, ToolCallState } from "core"; |
| 2 | 2 | import Mustache from "mustache"; |
| 3 | 3 | import { ReactNode } from "react"; |
| 4 | +import { getFontSize } from "../../../util"; | |
| 5 | +import { useFontSize } from "../../../components/ui/font"; | |
| 4 | 6 | |
| 5 | 7 | interface ToolCallStatusMessageProps { |
| 6 | 8 | tool: Tool | undefined; |
| @@ -11,6 +13,7 @@ | ||
| 11 | 13 | tool, |
| 12 | 14 | toolCallState, |
| 13 | 15 | }: ToolCallStatusMessageProps) { |
| 16 | + const fontSize = useFontSize(); | |
| 14 | 17 | if (!tool) return "Agent tool use"; |
| 15 | 18 | |
| 16 | 19 | const defaultToolDescription = ( |
| @@ -65,7 +68,7 @@ | ||
| 65 | 68 | message = futureMessage; |
| 66 | 69 | } |
| 67 | 70 | return ( |
| 68 | - <div className="block"> | |
| 71 | + <div className="block" style={{ fontSize }}> | |
| 69 | 72 | <span>Continue</span> {intro} {message} |
| 70 | 73 | </div> |
| 71 | 74 | ); |
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 | +} | |
| 2 | 11 | |
| 3 | 12 | export const useAutoScroll = ( |
| 4 | 13 | ref: React.RefObject<HTMLDivElement>, |
| 5 | - history: unknown[], | |
| 14 | + history: ChatHistoryItemWithMessageId[], | |
| 6 | 15 | ) => { |
| 7 | 16 | const [userHasScrolled, setUserHasScrolled] = useState(false); |
| 17 | + const numUserMsgs = useMemo(() => getNumUserMsgs(history), [history.length]); | |
| 8 | 18 | |
| 9 | 19 | useEffect(() => { |
| 10 | - if (history.length) { | |
| 11 | - setUserHasScrolled(false); | |
| 12 | - } | |
| 13 | - }, [history.length]); | |
| 20 | + setUserHasScrolled(false); | |
| 21 | + }, [numUserMsgs]); | |
| 14 | 22 | |
| 15 | 23 | useEffect(() => { |
| 16 | 24 | if (!ref.current || history.length === 0) return; |
modified gui/src/redux/slices/editModeState.ts +4 −3
| @@ -1,10 +1,11 @@ | ||
| 1 | 1 | import { createSlice, PayloadAction } from "@reduxjs/toolkit"; |
| 2 | -import { ApplyState, CodeToEdit, MessageModes } from "core"; | |
| 2 | +import { ApplyState, SetCodeToEditPayload, MessageModes } from "core"; | |
| 3 | 3 | import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; |
| 4 | + | |
| 4 | 5 | export interface EditModeState { |
| 5 | 6 | // Array because of previous multi-file edit functionality |
| 6 | 7 | // Keeping array to not break persisted redux for now |
| 7 | - codeToEdit: CodeToEdit[]; | |
| 8 | + codeToEdit: SetCodeToEditPayload[]; | |
| 8 | 9 | applyState: ApplyState; |
| 9 | 10 | returnToMode: MessageModes; |
| 10 | 11 | lastNonEditSessionWasEmpty: boolean; |
| @@ -46,7 +47,7 @@ | ||
| 46 | 47 | { |
| 47 | 48 | payload, |
| 48 | 49 | }: PayloadAction<{ |
| 49 | - codeToEdit: CodeToEdit | CodeToEdit[]; | |
| 50 | + codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[]; | |
| 50 | 51 | }>, |
| 51 | 52 | ) => { |
| 52 | 53 | state.codeToEdit = Array.isArray(payload.codeToEdit) |
modified gui/src/redux/slices/sessionSlice.ts +16 −1
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | FileSymbolMap, |
| 16 | 16 | MessageModes, |
| 17 | 17 | PromptLog, |
| 18 | + RuleWithSource, | |
| 18 | 19 | Session, |
| 19 | 20 | SessionMetadata, |
| 20 | 21 | ToolCallDelta, |
| @@ -31,7 +32,7 @@ | ||
| 31 | 32 | |
| 32 | 33 | // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. |
| 33 | 34 | // 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 & { | |
| 35 | 36 | message: ChatMessage & { id: string }; |
| 36 | 37 | }; |
| 37 | 38 | |
| @@ -247,6 +248,19 @@ | ||
| 247 | 248 | ...payload.contextItems, |
| 248 | 249 | ]; |
| 249 | 250 | }, |
| 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 | + }, | |
| 250 | 264 | setInactive: (state) => { |
| 251 | 265 | const curMessage = state.history.at(-1); |
| 252 | 266 | |
| @@ -698,6 +712,7 @@ | ||
| 698 | 712 | updateFileSymbols, |
| 699 | 713 | setContextItemsAtIndex, |
| 700 | 714 | addContextItemsAtIndex, |
| 715 | + setAppliedRulesAtIndex, | |
| 701 | 716 | setInactive, |
| 702 | 717 | streamUpdate, |
| 703 | 718 | newSession, |
modified gui/src/redux/thunks/editMode.ts +6 −2
| @@ -1,6 +1,10 @@ | ||
| 1 | 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | 2 | import { JSONContent } from "@tiptap/core"; |
| 3 | -import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core"; | |
| 3 | +import { | |
| 4 | + SetCodeToEditPayload, | |
| 5 | + MessageModes, | |
| 6 | + RangeInFileWithContents, | |
| 7 | +} from "core"; | |
| 4 | 8 | import { stripImages } from "core/util/messageContent"; |
| 5 | 9 | import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; |
| 6 | 10 | import { |
| @@ -18,7 +22,7 @@ | ||
| 18 | 22 | void, |
| 19 | 23 | { |
| 20 | 24 | editorState: JSONContent; |
| 21 | - codeToEdit: CodeToEdit[]; | |
| 25 | + codeToEdit: SetCodeToEditPayload[]; | |
| 22 | 26 | }, |
| 23 | 27 | ThunkApiType |
| 24 | 28 | >( |
modified gui/src/redux/thunks/streamResponse.ts +32 −5
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | 2 | import { JSONContent } from "@tiptap/core"; |
| 3 | -import { InputModifiers } from "core"; | |
| 3 | +import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; | |
| 4 | 4 | import { constructMessages } from "core/llm/constructMessages"; |
| 5 | +import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; | |
| 5 | 6 | import posthog from "posthog-js"; |
| 6 | 7 | import { v4 as uuidv4 } from "uuid"; |
| 7 | 8 | import { getBaseSystemMessage } from "../../util"; |
| 8 | 9 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 9 | 10 | import { |
| 11 | + setAppliedRulesAtIndex, | |
| 10 | 12 | submitEditorAndInitAtIndex, |
| 11 | 13 | updateHistoryItemAtIndex, |
| 12 | 14 | } from "../slices/sessionSlice"; |
| @@ -84,17 +86,42 @@ | ||
| 84 | 86 | }), |
| 85 | 87 | ); |
| 86 | 88 | |
| 87 | - // Construct messages from updated history | |
| 89 | + // Get updated history after the update | |
| 88 | 90 | const updatedHistory = getState().session.history; |
| 89 | - const messageMode = getState().session.mode | |
| 90 | 91 | |
| 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 | + ); | |
| 92 | 119 | |
| 93 | 120 | const messages = constructMessages( |
| 94 | 121 | messageMode, |
| 95 | 122 | [...updatedHistory], |
| 96 | 123 | baseChatOrAgentSystemMessage, |
| 97 | - state.config.config.rules, | |
| 124 | + applicableRules, | |
| 98 | 125 | ); |
| 99 | 126 | |
| 100 | 127 | 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 @@ | ||
| 25 | 25 | if (apply.status === "error") { |
| 26 | 26 | throw new Error(apply.error); |
| 27 | 27 | } |
| 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 | + } | |
| 29 | 43 | return { |
| 30 | 44 | respondImmediately: false, |
| 31 | 45 | output: undefined, // No immediate output. |
modified gui/src/util/navigation.ts +1 −0
| @@ -2,5 +2,6 @@ | ||
| 2 | 2 | export const ROUTES = { |
| 3 | 3 | HOME: "/", |
| 4 | 4 | CONFIG: "/config", |
| 5 | + THEME: "/theme", | |
| 5 | 6 | // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`, |
| 6 | 7 | }; |
modified gui/src/util/test/render.tsx +1 −0
| @@ -72,6 +72,7 @@ | ||
| 72 | 72 | return { |
| 73 | 73 | user, |
| 74 | 74 | store, |
| 75 | + ideMessenger, | |
| 75 | 76 | ...rendered!, |
| 76 | 77 | }; |
| 77 | 78 | } |
modified gui/tailwind.config.cjs +69 −17
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | /** @type {import('tailwindcss').Config} */ |
| 2 | 2 | const defaultTheme = require("tailwindcss/defaultTheme"); |
| 3 | +const { varWithFallback, THEME_COLORS } = require("./src/styles/theme"); | |
| 3 | 4 | |
| 4 | 5 | module.exports = { |
| 5 | 6 | content: [ |
| @@ -29,24 +30,75 @@ | ||
| 29 | 30 | default: "5px", |
| 30 | 31 | }, |
| 31 | 32 | 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 | + }, | |
| 41 | 94 | |
| 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 | |
| 50 | 102 | }, |
| 51 | 103 | }, |
| 52 | 104 | }, |
modified manual-testing-sandbox/AdvancedPage.tsx +1 −4
| @@ -13,10 +13,7 @@ | ||
| 13 | 13 | className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`} |
| 14 | 14 | > |
| 15 | 15 | <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 | + {" "} | |
| 20 | 17 | <button |
| 21 | 18 | className="rounded bg-blue-500 px-4 py-2 text-white" |
| 22 | 19 | onClick={toggleDarkMode} |
modified manual-testing-sandbox/test.kt +3 −0
| @@ -30,4 +30,7 @@ | ||
| 30 | 30 | return this |
| 31 | 31 | } |
| 32 | 32 | } |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 33 | 36 |
modified manual-testing-sandbox/test.ts +2 −2
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | this.result += number; |
| 10 | 10 | return this; |
| 11 | 11 | } |
| 12 | - | |
| 12 | + | |
| 13 | 13 | subtract(number: number): Calculator { |
| 14 | 14 | this.result -= number; |
| 15 | 15 | return this; |
| @@ -38,4 +38,4 @@ | ||
| 38 | 38 | } |
| 39 | 39 | } |
| 40 | 40 | |
| 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 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "@continuedev/config-yaml", |
| 9 | - "version": "1.0.87", | |
| 9 | + "version": "1.0.88", | |
| 10 | 10 | "license": "Apache-2.0", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@continuedev/config-types": "^1.0.14", |
modified packages/config-yaml/package.json +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/config-yaml", |
| 3 | - "version": "1.0.87", | |
| 3 | + "version": "1.0.88", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
modified packages/config-yaml/src/__tests__/index.test.ts +5 −1
| @@ -143,7 +143,7 @@ | ||
| 143 | 143 | ); |
| 144 | 144 | |
| 145 | 145 | // Test that packages were correctly unrolled and params replaced |
| 146 | - expect(unrolledConfig.models?.length).toBe(3); | |
| 146 | + expect(unrolledConfig.models?.length).toBe(4); | |
| 147 | 147 | |
| 148 | 148 | const openAiModel = unrolledConfig.models?.[0]!; |
| 149 | 149 | expect(openAiModel.apiKey).toBe("sk-123"); |
| @@ -163,6 +163,10 @@ | ||
| 163 | 163 | anthropicSecretLocation, |
| 164 | 164 | ); |
| 165 | 165 | |
| 166 | + const proxyOllamaModel = unrolledConfig.models?.[3]!; | |
| 167 | + expect(proxyOllamaModel.provider).toBe('ollama') | |
| 168 | + expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false); | |
| 169 | + | |
| 166 | 170 | expect(unrolledConfig.rules?.length).toBe(2); |
| 167 | 171 | expect(unrolledConfig.docs?.[0]?.startUrl).toBe( |
| 168 | 172 | "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 @@ | ||
| 27 | 27 | - uses: test-org/claude35sonnet |
| 28 | 28 | with: |
| 29 | 29 | ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} |
| 30 | + | |
| 31 | + - name: proxy-ollama | |
| 32 | + provider: ollama | |
| 33 | + model: llama3.1 | |
| 34 | + defaultCompletionOptions: | |
| 35 | + stream: false |