Merge branch 'main' into docs-clean-reset
This commit is contained in:
commit
a38982f381
771 changed files with 77227 additions and 62563 deletions
|
|
@ -1,8 +0,0 @@
|
|||
## 0.0.34 - 2024-03-03
|
||||
### Added
|
||||
* diff context provider
|
||||
### Changed
|
||||
* Allow LLM servers to handle templating
|
||||
### Fixed
|
||||
* Fix a few context providers / slash commands
|
||||
* Fixed issues preventing proper extension startup
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.0.38 - 2024-03-15
|
||||
### Added
|
||||
* Remote config server support
|
||||
* Autocomplete support in JetBrains
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
## 0.0.42 - 2024-04-12
|
||||
### Added
|
||||
* Inline cmd/ctrl+I in JetBrains
|
||||
### Fixed
|
||||
* Fixed character encoding error causing display issues
|
||||
* Fixed error causing input to constantly demand focus
|
||||
* Fixed automatic reloading of config.json
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
## 0.0.53 - 2024-07-10
|
||||
### Added
|
||||
* Support for .prompt files
|
||||
* New onboarding experience
|
||||
### Fixed
|
||||
* Indexing fixes from VS Code versions merged into IntelliJ
|
||||
* Improved codebase indexing reliability and testing
|
||||
* Fixes for autocomplete text positioning and timing
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## 0.0.54 - 2024-07-13
|
||||
### Added
|
||||
* Partial autocomplete acceptance
|
||||
* Autocomplete status bar spinner
|
||||
### Fixed
|
||||
* Fixed duplicate completion bug and others
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
## 0.0.69 - 2024-09-22
|
||||
### Added
|
||||
* Support for the "search" context provider
|
||||
### Fixed
|
||||
* Fixed bug where only first module would be recognized
|
||||
* Improved concurrency handling to avoid freezes
|
||||
* Made compatible with latest JetBrains versions
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
## 0.0.72 - 2024-10-04
|
||||
### Added
|
||||
* Listen for changes to Intellij settings without requiring window reload
|
||||
### Changed
|
||||
* Updated tutorial file
|
||||
### Fixed
|
||||
* Fix ability to load config.ts in JetBrains IDEs
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## 0.0.92 - 2025-02-26
|
||||
### Fixed
|
||||
* Off-screen rendering to solve white flash on load and lack of changing cursor type
|
||||
* OSR-related fixes for non-Mac users
|
||||
* Fixes for inline edit in JetBrains
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
## 1.0.0 - 2025-02-26
|
||||
### Added
|
||||
* Introduces hub.continue.dev
|
||||
* Improved theme matching
|
||||
### Fixed
|
||||
* Fixes interference between SonarQube and Continue autocomplete
|
||||
* Numerous reliability improvements
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.1 - 2023-09-01
|
||||
|
||||
### Added
|
||||
|
||||
- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.19 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.21 - 2023-12-05
|
||||
|
||||
### Added
|
||||
|
||||
- updated to match latest VS Code updates
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.25 - 2023-12-25
|
||||
|
||||
### Changed
|
||||
|
||||
- Intellij extension no longer relies on the Continue Python server
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.26 - 2023-12-28
|
||||
### Added
|
||||
* auto-reloading of config on save
|
||||
### Fixed
|
||||
* Fixed /edit bug for versions without Python server
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
## 0.8.14 - 2024-03-03
|
||||
### Added
|
||||
* Image support
|
||||
* Full-text search index for retrieval
|
||||
* Docs context provider
|
||||
* CodeLlama-70b support
|
||||
### Changed
|
||||
* config.ts only runs in NodeJS, not browser
|
||||
### Fixed
|
||||
* Fixed proxy setting in config.json
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.15 - 2024-03-05
|
||||
### Added
|
||||
* Tab-autocomplete in beta
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## 0.8.24 - 2024-04-12
|
||||
### Added
|
||||
* Support for improved retrieval models (Voyage embeddings/reranking)
|
||||
* New @code context provider
|
||||
* Personal usage analytics
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
## 0.8.42 - 2024-07-02
|
||||
|
||||
### Added
|
||||
|
||||
- Support for Gemini 1.5 Pro
|
||||
- Link to code in the sidebar when using codebase retrieval
|
||||
- Smoother onboarding experience
|
||||
- .prompt files, a way of saving and sharing slash commands
|
||||
- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
|
||||
- Support for comments in config.json
|
||||
- Specify multiple autocomplete models and switch between them
|
||||
- Improved bracket matching strategy reduces noisy completions
|
||||
|
||||
### Fixed
|
||||
|
||||
- Numerous reliability upgrades to codebase indexing
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.8.43 - 2024-07-08
|
||||
### Added
|
||||
* Improved indexing reliability and testing
|
||||
* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
## 0.8.45 - 2024-08-05
|
||||
### Added
|
||||
* Support for Llama 3.1 and gpt-4o-mini
|
||||
* Support for WatsonX+Granite models
|
||||
### Changed
|
||||
* Significant improvements to indexing performance
|
||||
* Improved @codebase quality by more accurately searching over file names and paths
|
||||
* Improved @codebase accuracy
|
||||
* Further improvements to indexing performance
|
||||
### Fixed
|
||||
* Improved docs indexing and management
|
||||
* Fixed Gemini embeddings provider
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## 0.8.46 - 2024-08-11
|
||||
### Added
|
||||
* new /onboard slash command
|
||||
### Fixed
|
||||
* Fixed problem loading config.ts
|
||||
* Fixed bug causing duplicate indexing work
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
## 0.8.47 - 2024-08-27
|
||||
### Added
|
||||
* Use headless browser for crawling to get better results
|
||||
* TTS support in the chat window
|
||||
### Changed
|
||||
* Improved support for WatsonX models
|
||||
### Fixed
|
||||
* Fixed several small indexing bugs
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
## 0.8.48 - 2024-09-01
|
||||
### Added
|
||||
* Improved indexing progress UI
|
||||
* Improved @codebase using repomap
|
||||
* Repo map context provider
|
||||
### Fixed
|
||||
* Many small UI improvements
|
||||
* Fixes db.search not a function
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.49 - 2024-09-01
|
||||
### Fixed
|
||||
* Hotfix: submenu context providers
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.50 - 2024-09-02
|
||||
### Fixed
|
||||
* Hotfix for ability to use more than one inline context provider
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.51 - 2024-09-05
|
||||
### Fixed
|
||||
* Fixed CRLF bug causing diff streams to treat every line as changed on Windows
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.8.52 - 2024-09-16
|
||||
### Changed
|
||||
* Use Chromium only as a fallback after asking user
|
||||
* Redesigned onboarding flow
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
## 0.8.53 - 2024-10-11
|
||||
### Added
|
||||
* Improved loading/accept/reject UI for apply
|
||||
* Polished chat sidebar, especially context dropdown
|
||||
* Further prompt caching with Anthropic
|
||||
### Changed
|
||||
* Updated tutorial file
|
||||
* Improved styling on "More" page
|
||||
### Fixed
|
||||
* Continue for teams auth bug fix
|
||||
* Fixed a number of apply bugs
|
||||
* Fixed autoscrolling behavior
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.54 - 2024-10-15
|
||||
### Fixed
|
||||
* Hotfix: throttle transformers.js embeddings provider
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## 0.8.55 - 2024-10-25
|
||||
### Added
|
||||
* Web context provider
|
||||
* Cerebras inference provider
|
||||
* Automatic descriptions for previous chats
|
||||
* Discord context provider
|
||||
* Improved full screen UI
|
||||
### Changed
|
||||
* Easier way to accept/reject/re-prompt after cmd/ctrl+I
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.8.56 - 2024-11-08
|
||||
### Added
|
||||
* New Edit mode in sidebar (cmd/ctrl+I)
|
||||
* Significantly faster and more accurate docs crawler by default
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
## 0.8.58 - 2024-11-22
|
||||
### Added
|
||||
* OpenAI predicted outputs support
|
||||
* Improve codebase retrieval with BM25
|
||||
* Support for Grok from xAI
|
||||
* Chat enhancements including sticking input to bottom
|
||||
* New UI for cmd+I in sidebar
|
||||
* Support for Nebius LLM provider
|
||||
* Support for Ask Sage LLM provider
|
||||
* Improved reference for config.json
|
||||
* New @web context provider
|
||||
* Updates for llama3.2
|
||||
* .continuerules file to set system prompt
|
||||
* .prompt files v2
|
||||
* Dedicated UI for docs indexing
|
||||
* Clickable code symbols in chat
|
||||
* Use clipboard content as autocomplete context
|
||||
### Changed
|
||||
* Improved @docs crawler
|
||||
* Many improvements to make autocomplete more eager
|
||||
* Near complete type definition retrieval for TypeScript autocomplete
|
||||
* Remove footer from chat sidebar
|
||||
### Fixed
|
||||
* Brought back the Apply button for all code blocks
|
||||
* Automatically update codebase index on removed files
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.59 - 2024-11-25
|
||||
### Fixed
|
||||
* Hotfix for Ollama onboarding
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## 0.8.62 - 2024-12-10
|
||||
### Added
|
||||
* Tool use
|
||||
* Support for Model Context Protocol
|
||||
### Fixed
|
||||
* hotfix: context providers no longer hidden when not in edit mode
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## 0.8.66 - 2024-12-20
|
||||
### Changed
|
||||
* Improved autocomplete in untitled files
|
||||
### Fixed
|
||||
* Display more mid-line completions
|
||||
* Restored syntax highlighting
|
||||
* Fix tool use bug for models that don't support tools
|
||||
* Autodetect mistral API key type
|
||||
* Fixes Azure OpenAI regressions
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## 1.0.0 - 2025-02-26
|
||||
### Added
|
||||
* Introduces hub.continue.dev
|
||||
* Improved apply quality
|
||||
### Fixed
|
||||
* Numerous reliability improvements
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## v0.5.0 - 2023-11-09
|
||||
|
||||
### Added
|
||||
|
||||
- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
|
||||
|
||||
### Changed
|
||||
|
||||
- Switch from Websockets to Socket.io
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
## v0.6.0 - 2023-11-10
|
||||
|
||||
### Added
|
||||
|
||||
- Full screen mode
|
||||
- StackOverflow slash command to augment with web search
|
||||
- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
|
||||
|
||||
### Fixed
|
||||
|
||||
- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## v0.6.16 - 2023-12-25
|
||||
|
||||
### Changed
|
||||
|
||||
- Context items are now kept around as a part of past messages, instead of staying at the main input
|
||||
- No more Python server - Continue runs entirely in Typescript
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
## v0.6.19 - 2024-01-05
|
||||
|
||||
### Added
|
||||
|
||||
- support for .continuerc.json in root of workspace to override config.json
|
||||
- Inline context providers
|
||||
- cmd+shift+L with new diff streaming UI for edits
|
||||
|
||||
### Changed
|
||||
|
||||
- Allow certain LLM servers to handle templating
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.6.4 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## v0.8.1 - 2024-01-08
|
||||
|
||||
### Added
|
||||
|
||||
- disableSessionTitles option in config.json
|
||||
|
||||
### Changed
|
||||
|
||||
- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
## v0.8.2 - 2024-01-23
|
||||
### Added
|
||||
* Add codellama and gemini to free trial, using new server
|
||||
* Local codebase syncing and embeddings using LanceDB
|
||||
* Improved VS Code theme matching
|
||||
### Changed
|
||||
* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
|
||||
* Context providers now run from the extension side (in Node.js instead of browser javascript)
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
|
||||
and is generated by [Changie](https://github.com/miniscruff/changie).
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
changesDir: .changes
|
||||
unreleasedDir: unreleased
|
||||
headerPath: header.tpl.md
|
||||
changelogPath: CHANGELOG.md
|
||||
versionExt: md
|
||||
versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
|
||||
kindFormat: "### {{.Kind}}"
|
||||
changeFormat: "* {{.Body}}"
|
||||
kinds:
|
||||
- label: Added
|
||||
auto: minor
|
||||
- label: Changed
|
||||
auto: major
|
||||
- label: Deprecated
|
||||
auto: minor
|
||||
- label: Removed
|
||||
auto: major
|
||||
- label: Fixed
|
||||
auto: patch
|
||||
- label: Security
|
||||
auto: patch
|
||||
newlines:
|
||||
afterChangelogHeader: 1
|
||||
beforeChangelogVersion: 1
|
||||
endOfVersion: 1
|
||||
envPrefix: CHANGIE_
|
||||
|
||||
projects:
|
||||
- label: extensions/intellij
|
||||
key: extensions/intellij
|
||||
changelog: extensions/intellij/CHANGELOG.md
|
||||
|
||||
- label: extensions/vscode
|
||||
key: extensions/vscode
|
||||
changelog: extensions/vscode/CHANGELOG.md
|
||||
79
.continue/prompts/update-llm-info.prompt
Normal file
79
.continue/prompts/update-llm-info.prompt
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
name: Update LLM Info
|
||||
description: Updates Gemini blocks with latest information
|
||||
version: 2
|
||||
---
|
||||
I need you to update this repo with the latest information about large language models from certain providers.
|
||||
The information is stored in the `packages/llm-info` directory, which operates as its own npm package.
|
||||
Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc).
|
||||
For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`.
|
||||
|
||||
To make these updates for a given provider, perform the following steps one at a time:
|
||||
|
||||
1. VIEW CURRENT INFORMATION
|
||||
|
||||
To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool.
|
||||
If you do not see a tool for reading files, let me know.
|
||||
|
||||
For reference, here is the LLMInfo interface used to store the information:
|
||||
|
||||
```typescript
|
||||
export interface LlmInfo {
|
||||
model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06"
|
||||
displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview"
|
||||
description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website
|
||||
contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length"
|
||||
maxCompletionTokens?: number; // The maximum number of tokens the model can output
|
||||
regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i
|
||||
mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image]
|
||||
}
|
||||
|
||||
export enum MediaType {
|
||||
Text = "text",
|
||||
Image = "image",
|
||||
Audio = "audio",
|
||||
Video = "video",
|
||||
}
|
||||
|
||||
export const AllMediaTypes = [
|
||||
MediaType.Text,
|
||||
MediaType.Image,
|
||||
MediaType.Audio,
|
||||
MediaType.Video,
|
||||
];
|
||||
```
|
||||
|
||||
2. EXTRACT NEW INFORMATION
|
||||
|
||||
Fetch information from the internet using the search web and read url tools.
|
||||
If you do not see either of these tools, stop and let me know.
|
||||
|
||||
Retrieve the following sites per these providers, and consider these notes on how to extract the information:
|
||||
- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit"
|
||||
// TODO: add info for openai, ollama, etc
|
||||
|
||||
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
|
||||
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
|
||||
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
|
||||
|
||||
3. UPDATE THE INFORMATION
|
||||
|
||||
Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`).
|
||||
Let me know if you do not see a tool for editing files.
|
||||
|
||||
Generally, avoid making changes to existing information, as it is probably up to date.
|
||||
Primarily, focus on adding new models or adding missing information to existing models.
|
||||
NEVER delete any existing models, but let me know if you think one should be removed.
|
||||
Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable.
|
||||
Provide a summary of changes after the fact.
|
||||
|
||||
4. ASK IF I WANT TO PUBLISH TO NPM
|
||||
After you are done updating everything, remind me that I need to publish the changes to npm.
|
||||
|
||||
// TODO too sensitive for now
|
||||
// If yes, update `packages/llm-info/package.json` with the new version number and then
|
||||
// - use the terminal tool to commit the changes
|
||||
// - use the terminal tool to publish changes to npm
|
||||
// If you do not see a tool for running terminal commands, let me know.
|
||||
|
||||
// User input
|
||||
Please update LLM Info for the following providers. If "all", update all providers mentioned above:
|
||||
13
.continue/rules/bigger-picture-description-rules.yaml
Normal file
13
.continue/rules/bigger-picture-description-rules.yaml
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
name: bigger-picture-description-rules
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: bigger-picture-description-rules
|
||||
rule: >-
|
||||
When a user asks how a certain part of the code works:
|
||||
|
||||
1. Describe what the code does in isolation.
|
||||
|
||||
2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
|
||||
|
||||
3. When describing each use-case, include the parent function for clarity.
|
||||
27
.continue/rules/colors.yaml
Normal file
27
.continue/rules/colors.yaml
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
name: GUI
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: Extension Color Themes
|
||||
rule: |
|
||||
When adding colors to components, use tailwind color classes.
|
||||
Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
|
||||
|
||||
The common available theme colors are:
|
||||
- For normal text: foreground, description, description-muted
|
||||
- For other text, icons, etc: success, warning, error, accent, link
|
||||
- For general components background, border, border-focus
|
||||
- For specific components:
|
||||
- Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover
|
||||
- Input: input, input-foreground, input-border, input-placeholder
|
||||
- Badge: badge, badge-foreground
|
||||
- List/Dropdown items: list-hover, list-active, list-active-foreground
|
||||
- Code Editor: editor, editor-foreground
|
||||
|
||||
Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc.
|
||||
globs: "gui/**/*.tsx"
|
||||
# Excluding the following less-used colors:
|
||||
# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus
|
||||
# Find widget colors: find-match, find-match-selected
|
||||
# table-oddRow
|
||||
|
||||
9
.continue/rules/continue-specificity.md
Normal file
9
.continue/rules/continue-specificity.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
globs: /**/*.
|
||||
description: General questions about code completion should be answered specific to Continue
|
||||
---
|
||||
|
||||
# Continue Specificity
|
||||
|
||||
- In chat mode, if the user asks generally about code completion or developer tools, answer specifically regarding Continue and not other similar software.
|
||||
- Keep all suggestions and comments concentrated on Continue, unless the user asks otherwise. If the user does this, answer with no particular specificity to Continue.
|
||||
16
.continue/rules/documentation-standards.md
Normal file
16
.continue/rules/documentation-standards.md
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
---
|
||||
globs: docs/**/*.{md,mdx}
|
||||
description: Standards for writing and maintaining Continue Docs
|
||||
---
|
||||
|
||||
# Continue Docs Standards
|
||||
|
||||
- Follow Docusaurus documentation standards
|
||||
- Include YAML frontmatter with title, description, and keywords
|
||||
- Use consistent heading hierarchy starting with h2 (##)
|
||||
- Include relevant Admonition components for tips, warnings, and info
|
||||
- Use descriptive alt text for images
|
||||
- Include cross-references to related documentation
|
||||
- Reference other docs with relative paths
|
||||
- Keep paragraphs concise and scannable
|
||||
- Use code blocks with appropriate language tags
|
||||
10
.continue/rules/gui-link-opening.md
Normal file
10
.continue/rules/gui-link-opening.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
globs: gui/**/*
|
||||
description: Ensures consistent URL opening behavior in GUI components using the
|
||||
IDE messenger pattern
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# GUI Link Opening
|
||||
|
||||
When adding functionality to open external links in GUI components, use `ideMessenger.post("openUrl", url)` where `ideMessenger` is obtained from `useContext(IdeMessengerContext)`
|
||||
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
name: IntelliJ Plugin Test Execution
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: IntelliJ Plugin Test Execution
|
||||
rule: |-
|
||||
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
|
||||
```bash
|
||||
# Run test class
|
||||
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
|
||||
|
||||
# Run specific test method
|
||||
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
|
||||
```
|
||||
globs: extensions/intellij/**/*Test.kt
|
||||
10
.continue/rules/intellij-test-standards.yaml
Normal file
10
.continue/rules/intellij-test-standards.yaml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
name: IntelliJ Test Standards
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: IntelliJ Test Standards
|
||||
rule: When writing tests for the IntelliJ plugin, use the mockk library for
|
||||
mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
|
||||
Always structure tests with clear Arrange-Act-Assert patterns and use
|
||||
descriptive test names that indicate the scenario being tested.
|
||||
globs: "**/test/**/*.kt"
|
||||
11
.continue/rules/llm-specificity.md
Normal file
11
.continue/rules/llm-specificity.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
globs: core/llm/llms/**/*.{ts,test.ts}
|
||||
description: Tailor recommendations for LLM code based on which specific LLM is being used.
|
||||
---
|
||||
|
||||
# LLM Model Specificity
|
||||
|
||||
- Refer to the file name and names of big classes to determine which LLM is being used in a file.
|
||||
- Ground all observations and recommendations with knowledge of that LLM.
|
||||
- Consider items such as context length, architecture, speed, and such.
|
||||
- Pay attention to the parent classes in these files.
|
||||
30
.continue/rules/unit-testing-rules.yaml
Normal file
30
.continue/rules/unit-testing-rules.yaml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: unit-testing-rules
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: unit-testing-rules
|
||||
rule: >-
|
||||
For unit testing in this project:
|
||||
|
||||
|
||||
1. The project uses Jest as the testing framework
|
||||
|
||||
2. Run tests using `npm test` from within the specific package/module
|
||||
directory
|
||||
|
||||
3. Command structure: `cd [directory] && npm test -- [test file path]`
|
||||
|
||||
4. The test script uses experimental VM modules via NODE_OPTIONS flag
|
||||
|
||||
5. Test files follow the pattern `*.test.ts`
|
||||
|
||||
6. Tests must import Jest with `import { jest } from "@jest/globals";`
|
||||
|
||||
7. Run tests from within the specific package directory (e.g., `cd core`
|
||||
for core module tests)
|
||||
|
||||
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
|
||||
blocks
|
||||
|
||||
9. Include the function name being tested in the test description for
|
||||
clarity
|
||||
|
|
@ -6,6 +6,7 @@
|
|||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"no-negated-condition": "warn",
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
|
|
|
|||
30
.github/workflows/cla.yaml
vendored
Normal file
30
.github/workflows/cla.yaml
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
name: "CLA Assistant"
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_target:
|
||||
types: [opened, closed, synchronize]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
CLAAssistant:
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
steps:
|
||||
- name: "CLA Assistant"
|
||||
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'
|
||||
uses: contributor-assistant/github-action@v2.6.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
path-to-signatures: "signatures/version1/cla.json"
|
||||
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
|
||||
branch: cla-signatures
|
||||
allowlist: dependabot[bot]
|
||||
signed-commit-message: "CLA signed in $pullRequestNo"
|
||||
2
.github/workflows/jetbrains-release.yaml
vendored
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -63,7 +63,7 @@ jobs:
|
|||
|
||||
- name: Bump version in gradle.properties
|
||||
run: |
|
||||
cd extensions/intelllij
|
||||
cd extensions/intellij
|
||||
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
|
||||
rm -rf tmp
|
||||
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
|
||||
|
|
|
|||
2
.github/workflows/main.yaml
vendored
2
.github/workflows/main.yaml
vendored
|
|
@ -235,7 +235,7 @@ jobs:
|
|||
- name: Publish to VS Code Marketplace
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npx vsce publish --packagePath ../../vsix-artifacts/*.vsix
|
||||
npx @vscode/vsce publish --packagePath ../../vsix-artifacts/*.vsix
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
|
||||
|
||||
|
|
|
|||
75
.github/workflows/metrics.yaml
vendored
Normal file
75
.github/workflows/metrics.yaml
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
name: Monthly issue metrics
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
# Runs every Monday at 9:00 AM PST (17:00 UTC)
|
||||
- cron: "0 17 * * 1"
|
||||
|
||||
push:
|
||||
branches:
|
||||
- nate/metrics-action
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: issue metrics
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: read
|
||||
steps:
|
||||
- name: Get dates for last month
|
||||
shell: bash
|
||||
run: |
|
||||
# Calculate the first day of the previous month
|
||||
first_day=$(date -d "last month" +%Y-%m-01)
|
||||
|
||||
# Calculate the last day of the previous month
|
||||
last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d)
|
||||
|
||||
#Set an environment variable with the date range
|
||||
echo "$first_day..$last_day"
|
||||
echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Run issue-metrics tool
|
||||
uses: github/issue-metrics@v3
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SEARCH_QUERY: 'repo:continuedev/continue created:${{ env.last_month }} -reason:"not planned"'
|
||||
|
||||
- name: Read metrics file content
|
||||
id: read-metrics
|
||||
run: |
|
||||
content=$(cat ./issue_metrics.md)
|
||||
# This prepares the content in a way that can be used in GitHub Actions
|
||||
content="${content//'%'/'%25'}"
|
||||
content="${content//$'\n'/'%0A'}"
|
||||
# content="${content//$'\r'/'%0D'}"
|
||||
echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Post a message in a channel
|
||||
uses: slackapi/slack-github-action@v2.1.0
|
||||
with:
|
||||
webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
|
||||
webhook-type: incoming-webhook
|
||||
payload: |
|
||||
text: "Issue / PR Metrics Report"
|
||||
blocks:
|
||||
- type: "header"
|
||||
text:
|
||||
type: "plain_text"
|
||||
text: "Monthly Issue Metrics Report"
|
||||
emoji: true
|
||||
- type: "section"
|
||||
text:
|
||||
type: "mrkdwn"
|
||||
text: |
|
||||
${{ steps.read-metrics.outputs.metrics_content }}
|
||||
|
||||
- name: Upload metrics report as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: issue-metrics-report
|
||||
path: ./issue_metrics.md
|
||||
25
.github/workflows/pr_checks.yaml
vendored
25
.github/workflows/pr_checks.yaml
vendored
|
|
@ -30,6 +30,24 @@ jobs:
|
|||
if: steps.root-cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
|
||||
prettier-check:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- name: Check code formatting with Prettier
|
||||
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
|
||||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -235,10 +253,11 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Type check
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd gui
|
||||
npx tsc --noEmit
|
||||
npm run lint
|
||||
|
||||
binary-checks:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
|
|
@ -407,6 +426,7 @@ jobs:
|
|||
run: |
|
||||
cd core
|
||||
npm test
|
||||
npm run vitest
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
|
@ -415,6 +435,8 @@ jobs:
|
|||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
|
||||
package-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -858,6 +880,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- install-root
|
||||
- prettier-check
|
||||
- install-core
|
||||
- core-checks
|
||||
- install-gui
|
||||
|
|
|
|||
2
.github/workflows/preview.yaml
vendored
2
.github/workflows/preview.yaml
vendored
|
|
@ -232,7 +232,7 @@ jobs:
|
|||
- name: Publish to VS Code Marketplace
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
|
||||
npx @vscode/vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
|
||||
env:
|
||||
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ name: Submit Gradle Dependency Graph For Dependabot
|
|||
|
||||
on:
|
||||
push:
|
||||
branches: ['main']
|
||||
branches: ["main"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
|
@ -11,15 +11,15 @@ jobs:
|
|||
dependency-submission:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 17
|
||||
- name: Generate and submit dependency graph
|
||||
uses: gradle/actions/dependency-submission@v4
|
||||
with:
|
||||
# The gradle project is not in the root of the repository.
|
||||
build-root-directory: extensions/intellij
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
- name: Generate and submit dependency graph
|
||||
uses: gradle/actions/dependency-submission@v4
|
||||
with:
|
||||
# The gradle project is not in the root of the repository.
|
||||
build-root-directory: extensions/intellij
|
||||
|
|
|
|||
8
.gitignore
vendored
8
.gitignore
vendored
|
|
@ -144,7 +144,9 @@ Icon?
|
|||
.continuerc.json
|
||||
.aider*
|
||||
|
||||
*.notes.md
|
||||
notes.md
|
||||
*.notes.md
|
||||
|
||||
manual-testing-sandbox/.idea/**
|
||||
manual-testing-sandbox/.continue/**
|
||||
|
|
@ -162,5 +164,9 @@ extensions/.continue-debug/
|
|||
|
||||
*.vsix
|
||||
|
||||
# intellij module library files
|
||||
*.iml
|
||||
|
||||
.continuerules
|
||||
**/.continue/assistants/
|
||||
**/.continue/assistants/
|
||||
keys
|
||||
6
.idea/jsLinters/eslint.xml
generated
Normal file
6
.idea/jsLinters/eslint.xml
generated
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EslintConfiguration">
|
||||
<option name="fix-on-save" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
1
.idea/prettier.xml
generated
1
.idea/prettier.xml
generated
|
|
@ -2,5 +2,6 @@
|
|||
<project version="4">
|
||||
<component name="PrettierConfiguration">
|
||||
<option name="myConfigurationMode" value="AUTOMATIC" />
|
||||
<option name="myRunOnSave" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
22
.idea/runConfigurations/config_yaml_tests.xml
generated
Normal file
22
.idea/runConfigurations/config_yaml_tests.xml
generated
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="config-yaml tests" type="JavaScriptTestRunnerJest">
|
||||
<config-file value="$PROJECT_DIR$/packages/config-yaml/jest.config.mjs" />
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/packages/config-yaml" />
|
||||
<envs />
|
||||
<scope-kind value="ALL" />
|
||||
<method v="2">
|
||||
<option name="NpmBeforeRunTask" enabled="true">
|
||||
<package-json value="$PROJECT_DIR$/packages/config-yaml/package.json" />
|
||||
<command value="run" />
|
||||
<scripts>
|
||||
<script value="build" />
|
||||
</scripts>
|
||||
<node-interpreter value="project" />
|
||||
<envs />
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
12
.idea/runConfigurations/core_tests.xml
generated
Normal file
12
.idea/runConfigurations/core_tests.xml
generated
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="core tests" type="JavaScriptTestRunnerJest">
|
||||
<config-file value="$PROJECT_DIR$/core/jest.config.js" />
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/core" />
|
||||
<envs />
|
||||
<scope-kind value="ALL" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
25
.idea/runConfigurations/openai_adapters_configuration.xml
generated
Normal file
25
.idea/runConfigurations/openai_adapters_configuration.xml
generated
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="openai-adapters configuration" type="JavaScriptTestRunnerJest">
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/packages/openai-adapters" />
|
||||
<envs />
|
||||
<scope-kind value="SUITE" />
|
||||
<test-file value="$PROJECT_DIR$/packages/openai-adapters/src/test/main.test.ts" />
|
||||
<test-names>
|
||||
<test-name value="openai configuration" />
|
||||
</test-names>
|
||||
<method v="2">
|
||||
<option name="NpmBeforeRunTask" enabled="true">
|
||||
<package-json value="$PROJECT_DIR$/packages/openai-adapters/package.json" />
|
||||
<command value="run" />
|
||||
<scripts>
|
||||
<script value="build" />
|
||||
</scripts>
|
||||
<node-interpreter value="project" />
|
||||
<envs />
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
|
|
@ -1,5 +1,11 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CommitMessageInspectionProfile">
|
||||
<profile version="1.0">
|
||||
<inspection_tool class="CommitFormat" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="CommitNamingConvention" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
|
|
|
|||
|
|
@ -15,4 +15,11 @@ gui/dist
|
|||
CHANGELOG.md
|
||||
**/continue_tutorial.py
|
||||
**/node_modules
|
||||
**/CODEOWNERS
|
||||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
extensions/vscode/gui
|
||||
extensions/vscode/models
|
||||
extensions/intellij/src/main/resources
|
||||
packages/continue-sdk
|
||||
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
|
@ -45,6 +45,7 @@
|
|||
"extensions/.continue-debug": true
|
||||
// "sync/**": true
|
||||
},
|
||||
"editor.formatOnSave": true,
|
||||
"eslint.workingDirectories": ["./core"],
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"conventionalCommits.showNewVersionNotes": false,
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
Separate changelogs are kept for each extension:
|
||||
|
||||
- [VS Code Extension](./extensions/vscode/CHANGELOG.md)
|
||||
- [JetBrains Extension](./extensions/intellij/CHANGELOG.md)
|
||||
|
|
@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
|
|||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
|
|
|||
147
CONTRIBUTING.md
147
CONTRIBUTING.md
|
|
@ -22,6 +22,7 @@
|
|||
- [Our Git Workflow](#our-git-workflow)
|
||||
- [Development workflow](#development-workflow)
|
||||
- [Formatting](#formatting)
|
||||
- [Theme Colors](#theme-colors)
|
||||
- [Testing](#testing)
|
||||
- [Review Process](#review-process)
|
||||
- [Getting help](#getting-help)
|
||||
|
|
@ -31,16 +32,21 @@
|
|||
- [📐 Continue Architecture](#-continue-architecture)
|
||||
- [Continue VS Code Extension](#continue-vs-code-extension)
|
||||
- [Continue JetBrains Extension](#continue-jetbrains-extension)
|
||||
- [Contibutor License Agreement](#contributor-license-agreement-cla)
|
||||
|
||||
# ❤️ Ways to Contribute
|
||||
|
||||
## 👋 Continue Contribution Ideas
|
||||
|
||||
[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. You can also browse the list of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
|
||||
[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. You
|
||||
can also browse the list
|
||||
of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
|
||||
|
||||
## 🐛 Report Bugs
|
||||
|
||||
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug report includes:
|
||||
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug
|
||||
report includes:
|
||||
|
||||
- A description of the bug
|
||||
- Steps to reproduce
|
||||
|
|
@ -50,7 +56,8 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
|
|||
|
||||
## ✨ Suggest Enhancements
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
- Create an issue
|
||||
|
||||
|
|
@ -62,7 +69,9 @@ Continue is quickly adding features, and we'd love to hear which are the most im
|
|||
|
||||
## 📖 Updating / Improving Documentation
|
||||
|
||||
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).
|
||||
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).
|
||||
|
||||
### Running the Documentation Server Locally
|
||||
|
||||
|
|
@ -70,7 +79,8 @@ You can run the documentation server locally using either of the following metho
|
|||
|
||||
#### Method 1: NPM Script
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
2. Run the following command to install the necessary dependencies for the documentation server:
|
||||
|
||||
|
|
@ -92,35 +102,48 @@ You can run the documentation server locally using either of the following metho
|
|||
|
||||
3. Look for the `docs:start` task and select it.
|
||||
|
||||
This will start a local server and you can see the documentation rendered in your default browser, typically accessible at `http://localhost:3000`.
|
||||
This will start a local server and you can see the documentation rendered in your default browser, typically accessible
|
||||
at `http://localhost:3000`.
|
||||
|
||||
## 🧑💻 Contributing Code
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
### Environment Setup
|
||||
|
||||
#### Pre-requisites
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
```bash
|
||||
nvm use
|
||||
```
|
||||
|
||||
Then, install Vite globally
|
||||
|
||||
```bash
|
||||
npm i -g vite
|
||||
```
|
||||
|
||||
#### Fork the Continue Repository
|
||||
|
||||
1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account.
|
||||
|
||||
2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
|
||||
|
||||
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`
|
||||
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`
|
||||
|
||||
4. Send your pull request to the main branch.
|
||||
|
||||
#### VS Code
|
||||
|
||||
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
|
||||
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select
|
||||
`install-all-dependencies`
|
||||
|
||||
2. Start debugging:
|
||||
|
||||
|
|
@ -131,15 +154,20 @@ nvm use
|
|||
1. The new VS Code window with the extension is referred to as the _Host VS Code_
|
||||
2. The window you started debugging from is referred to as the _Main VS Code_
|
||||
|
||||
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".
|
||||
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".
|
||||
|
||||
##### Debugging
|
||||
|
||||
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code.
|
||||
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently
|
||||
supported inside of `gui` code.
|
||||
|
||||
**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.
|
||||
**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.
|
||||
|
||||
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".
|
||||
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".
|
||||
|
||||
#### JetBrains
|
||||
|
||||
|
|
@ -147,13 +175,20 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
|
|||
|
||||
### Our Git Workflow
|
||||
|
||||
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 `v1.1.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 `v1.0x-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>.
|
||||
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 `v1.1.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 `v1.0x-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>.
|
||||
|
||||
### What makes a good PR?
|
||||
|
||||
To keep the Continue codebase clean and maintainable, we expect the following from our own team and all contributors:
|
||||
|
||||
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction
|
||||
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned
|
||||
with the project direction
|
||||
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
|
||||
- Write or update tests for new functionality
|
||||
- Update relevant documentation in the `docs` folder
|
||||
|
|
@ -161,18 +196,38 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
|
|||
|
||||
### Formatting
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
### Theme Colors
|
||||
|
||||
Continue has a set of named theme colors that we map to extension colors and tailwind classes, which can be found in [gui/src/styles/theme.ts](gui/src/styles/theme.ts)
|
||||
|
||||
Guidelines for using theme colors:
|
||||
|
||||
- Use Tailwind colors whenever possible. If developing in VS Code, download the [Tailwind CSS Intellisense extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) for great suggestions
|
||||
- Avoid using any explicit classes and CSS variables outside the theme (e.g. `text-yellow-400`)
|
||||
|
||||
Guidelines for adding/updating theme colors:
|
||||
|
||||
- Choose sensible VS Code variables to add/update in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) (see [here](https://code.visualstudio.com/api/references/theme-color) and [here](https://www.notion.so/1fa1d55165f78097b551e3bc296fcf76?pvs=25) for inspiration)
|
||||
- Choose sensible Jetbrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try)
|
||||
- Update `tailwind.config.js` if needed
|
||||
- Use the Theme Test Page to check colors. This can be accessed by going to `Settings` -> `Help` -> `Theme Test Page` in dev/debug mode.
|
||||
|
||||
### Testing
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
|
||||
|
||||
### Review Process
|
||||
|
||||
- **Initial Review** - A maintainer will be assigned as primary reviewer
|
||||
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
|
||||
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is
|
||||
maintainable and follows our patterns.
|
||||
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
|
||||
|
||||
### Getting help
|
||||
|
|
@ -183,19 +238,53 @@ Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with main
|
|||
|
||||
### Adding an LLM Provider
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
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.
|
||||
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.
|
||||
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
|
||||
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
|
||||
4. Add a documentation page for your provider in [`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example of configuring your provider in `config.yaml` and explain what options are available.
|
||||
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
|
||||
in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
|
||||
4. Add a documentation page for your provider in [
|
||||
`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
|
||||
of configuring your provider in `config.yaml` and explain what options are available.
|
||||
|
||||
### Adding Models
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
|
||||
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
|
||||
2. Add the model within its provider's array to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
|
||||
- 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).
|
||||
- [Prompt Templates](./core/llm/autodetect.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.
|
||||
- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the
|
||||
side bar model selection UI. To add a new model:
|
||||
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
|
||||
2. Add the model within its provider's array
|
||||
to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
|
||||
- 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).
|
||||
- [Prompt Templates](./core/llm/autodetect.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.
|
||||
|
||||
## Contributor License Agreement (CLA)
|
||||
|
||||
We require all contributors to accept the CLA and have made it as easy as commenting on your PR:
|
||||
|
||||
1. Open your pull request.
|
||||
2. Paste the following comment (or reply `recheck` if you’ve signed before):
|
||||
|
||||
```text
|
||||
I have read the CLA Document and I hereby sign the CLA
|
||||
```
|
||||
|
||||
3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.
|
||||
|
|
|
|||
29
README.md
29
README.md
|
|
@ -8,7 +8,10 @@
|
|||
|
||||
<div align="center">
|
||||
|
||||
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
|
||||
**[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)**
|
||||
|
||||
</div>
|
||||
|
||||
|
|
@ -20,15 +23,25 @@
|
|||
<a target="_blank" href="https://docs.continue.dev" style="background:none">
|
||||
<img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" />
|
||||
</a>
|
||||
<a target="_blank" href="https://changelog.continue.dev" style="background:none">
|
||||
<img src="https://img.shields.io/badge/changelog-%96EFF3" style="height: 22px;" />
|
||||
</a>
|
||||
<a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
|
||||
<img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
|
||||
</a>
|
||||
|
||||
<p></p>
|
||||
|
||||
## Agent
|
||||
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||
|
||||
## Chat
|
||||
|
||||
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE
|
||||
[Chat](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
|
||||
|
||||

|
||||
|
||||
|
|
@ -40,16 +53,11 @@
|
|||
|
||||
## Edit
|
||||
|
||||
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
|
||||
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
|
||||
file
|
||||
|
||||

|
||||
|
||||
## Agent
|
||||
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||
|
||||
</div>
|
||||
|
||||
## Getting Started
|
||||
|
|
@ -58,7 +66,8 @@ Learn about how to install and use Continue in the docs [here](https://continue.
|
|||
|
||||
## Contributing
|
||||
|
||||
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
|
||||
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
|
||||
join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
|
||||
|
||||
## License
|
||||
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ async function buildWithEsbuild() {
|
|||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
minify: !esbuildOnly,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const path = require('path');
|
||||
const path = require("path");
|
||||
process.env.CONTINUE_DEVELOPMENT = true;
|
||||
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(
|
||||
process.env.PROJECT_DIR,
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
);
|
||||
|
||||
require('./out/index.js');
|
||||
require("./out/index.js");
|
||||
|
|
|
|||
37
binary/package-lock.json
generated
37
binary/package-lock.json
generated
|
|
@ -33,6 +33,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.19.11",
|
||||
"jest": "^29.7.0",
|
||||
"pkg": "^5.8.1",
|
||||
|
|
@ -51,10 +52,10 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.6",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.19",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@continuedev/openai-adapters": "^1.0.25",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
|
|
@ -92,6 +93,7 @@
|
|||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
"plist": "^3.1.0",
|
||||
"posthog-node": "^3.6.3",
|
||||
"puppeteer": "^22.4.0",
|
||||
"puppeteer-chromium-resolver": "^23.0.0",
|
||||
|
|
@ -128,6 +130,7 @@
|
|||
"@types/mustache": "^4.2.5",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
|
|
@ -141,7 +144,8 @@
|
|||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3"
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
|
|
@ -2586,9 +2590,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.7.9",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
|
||||
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
|
||||
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
|
|
@ -3196,6 +3200,25 @@
|
|||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-env": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
|
||||
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cross-spawn": "^7.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"cross-env": "src/bin/cross-env.js",
|
||||
"cross-env-shell": "src/bin/cross-env-shell.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.14",
|
||||
"npm": ">=6",
|
||||
"yarn": ">=1"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.19.11",
|
||||
"jest": "^29.7.0",
|
||||
"pkg": "^5.8.1",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
|
||||
const logDirPath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
"logs",
|
||||
);
|
||||
const logFilePath = path.join(logDirPath, "prompt.log");
|
||||
|
||||
// Ensure the log directory exists
|
||||
|
|
@ -12,7 +18,7 @@ if (!fs.existsSync(logDirPath)) {
|
|||
|
||||
// Create the log file if it doesn't exist
|
||||
if (!fs.existsSync(logFilePath)) {
|
||||
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
|
||||
fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
|
||||
console.log("Created empty log file at " + logFilePath);
|
||||
}
|
||||
|
||||
|
|
@ -25,14 +31,16 @@ try {
|
|||
// console.clear();
|
||||
const stream = fs.createReadStream(logFilePath);
|
||||
stream.pipe(process.stdout);
|
||||
stream.on('error', (err) => {
|
||||
console.error('Error reading log file:', err.message);
|
||||
stream.on("error", (err) => {
|
||||
console.error("Error reading log file:", err.message);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error while handling file change:', err.message);
|
||||
console.error("Error while handling file change:", err.message);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error setting up file watcher:', err.message);
|
||||
console.log('You may need to restart the script after the extension generates the first log entry.');
|
||||
}
|
||||
console.error("Error setting up file watcher:", err.message);
|
||||
console.log(
|
||||
"You may need to restart the script after the extension generates the first log entry.",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -226,6 +226,7 @@ describe("Test Suite", () => {
|
|||
title: "Test Model",
|
||||
provider: "openai",
|
||||
model: "gpt-3.5-turbo",
|
||||
underlyingProviderName: "openai",
|
||||
};
|
||||
await messenger.request("config/addModel", {
|
||||
model,
|
||||
|
|
@ -252,6 +253,7 @@ describe("Test Suite", () => {
|
|||
title: "Test Model",
|
||||
provider: "mock",
|
||||
model: "gpt-3.5-turbo",
|
||||
underlyingProviderName: "mock",
|
||||
};
|
||||
await messenger.request("config/addModel", {
|
||||
model,
|
||||
|
|
|
|||
|
|
@ -39,4 +39,4 @@ module.exports = {
|
|||
TARGET_TO_RIPGREP_RELEASE,
|
||||
TARGET_TO_LANCEDB,
|
||||
RIPGREP_VERSION,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
16
core/__mocks__/@continuedev/fetch/index.ts
Normal file
16
core/__mocks__/@continuedev/fetch/index.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
export const fetchwithRequestOptions = vi.fn(
|
||||
async (url, options, requestOptions) => {
|
||||
console.log("Mocked fetch called with:", url, options, requestOptions);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
export const streamSse = vi.fn(function* () {
|
||||
yield "";
|
||||
});
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
|
|
@ -75,11 +74,6 @@ export class CompletionProvider {
|
|||
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
return llm;
|
||||
|
|
@ -120,11 +114,12 @@ export class CompletionProvider {
|
|||
this.loggingService.markDisplayed(completionId, outcome);
|
||||
}
|
||||
|
||||
private async _getAutocompleteOptions() {
|
||||
private async _getAutocompleteOptions(llm: ILLM) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config?.tabAutocompleteOptions,
|
||||
...llm.autocompleteOptions,
|
||||
};
|
||||
return options;
|
||||
}
|
||||
|
|
@ -132,6 +127,7 @@ export class CompletionProvider {
|
|||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
force?: boolean,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
// Create abort signal if not given
|
||||
|
|
@ -142,18 +138,23 @@ export class CompletionProvider {
|
|||
token = controller.signal;
|
||||
}
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
// Debounce
|
||||
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const options = await this._getAutocompleteOptions(llm);
|
||||
|
||||
// Debounce
|
||||
if (!force) {
|
||||
if (
|
||||
await this.debouncer.delayAndShouldDebounce(options.debounceDelay)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (llm.promptTemplates?.autocomplete) {
|
||||
options.template = llm.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
|
@ -244,7 +245,7 @@ export class CompletionProvider {
|
|||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelProvider: llm.underlyingProviderName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
|
|
|
|||
|
|
@ -74,7 +74,6 @@ export class StreamTransformPipeline {
|
|||
|
||||
const timeoutValue = helper.options.modelTimeout;
|
||||
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { jest } from "@jest/globals";
|
|||
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function
|
||||
describe("lineStream", () => {
|
||||
let mockFullStop: jest.Mock;
|
||||
|
||||
|
|
@ -204,6 +205,59 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
describe("filterCodeBlockLines", () => {
|
||||
it("should handle unfenced code", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;"]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with a code block", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with two code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should remove lines before the first valid line", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
|
||||
|
||||
|
|
@ -213,7 +267,134 @@ describe("lineStream", () => {
|
|||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it.todo("Need some sample inputs to properly test this");
|
||||
it("should remove outer blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```ts",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave single inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave double inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact but not return trailing or leading text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"[CODE]",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"[/CODE]",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterEnglishLinesAtStart", () => {
|
||||
|
|
|
|||
|
|
@ -55,8 +55,8 @@ function shouldChangeLineAndStop(line: string): string | undefined {
|
|||
return line;
|
||||
}
|
||||
|
||||
if (line.includes(CODE_START_BLOCK)) {
|
||||
return line.split(CODE_START_BLOCK)[0].trimEnd();
|
||||
if (line.includes(CODE_STOP_BLOCK)) {
|
||||
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -71,9 +71,9 @@ function isUselessLine(line: string): boolean {
|
|||
return hasUselessLine || trimmed.startsWith("// end");
|
||||
}
|
||||
|
||||
export const USELESS_LINES = ["", "```"];
|
||||
export const USELESS_LINES = [""];
|
||||
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
|
||||
export const CODE_START_BLOCK = "[/CODE]";
|
||||
export const CODE_STOP_BLOCK = "[/CODE]";
|
||||
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
|
||||
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
|
||||
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
|
||||
|
|
@ -343,34 +343,46 @@ export async function* removeTrailingWhitespace(
|
|||
* 4. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
||||
let seenValidLine = false;
|
||||
let waitingToSeeIfLineIsLast = undefined;
|
||||
let seenFirstFence = false;
|
||||
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
|
||||
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
|
||||
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
|
||||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
// Filter out starting ```
|
||||
if (!seenValidLine) {
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
// Filter out starting ``` or START block
|
||||
continue;
|
||||
}
|
||||
seenValidLine = true;
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
// Filter out ending ```
|
||||
if (typeof waitingToSeeIfLineIsLast !== "undefined") {
|
||||
yield waitingToSeeIfLineIsLast;
|
||||
waitingToSeeIfLineIsLast = undefined;
|
||||
}
|
||||
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
yield changedEndLine;
|
||||
return;
|
||||
}
|
||||
|
||||
if (line.startsWith("```")) {
|
||||
waitingToSeeIfLineIsLast = line;
|
||||
} else {
|
||||
yield line;
|
||||
if (nestCount > 0) {
|
||||
// Inside a block including the outer block
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
// Ending a block with just backticks (```) or STOP
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
// if we are closing the outer block then exit early
|
||||
// only exit early if the outer block was started with a block
|
||||
// it it was text, we will never exit early
|
||||
return;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
nestCount++;
|
||||
yield line;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTra
|
|||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import { GeneratorReuseManager } from "./GeneratorReuseManager";
|
||||
import { stopAfterMaxProcessingTime } from "./utils";
|
||||
|
||||
export class CompletionStreamer {
|
||||
private streamTransformPipeline = new StreamTransformPipeline();
|
||||
|
|
@ -22,23 +23,37 @@ export class CompletionStreamer {
|
|||
completionOptions: Partial<CompletionOptions> | undefined,
|
||||
helper: HelperVars,
|
||||
) {
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
const generator = this.generatorReuseManager.getGenerator(
|
||||
prefix,
|
||||
(abortSignal: AbortSignal) =>
|
||||
llm.supportsFim()
|
||||
(abortSignal: AbortSignal) => {
|
||||
const generator = llm.supportsFim()
|
||||
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
|
||||
: llm.streamComplete(prompt, abortSignal, {
|
||||
...completionOptions,
|
||||
raw: true,
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* This transformer applies even on reused generator. We are deliberately
|
||||
* not using streamTransformPipeline because we want to capture and stop
|
||||
* the request even if the generator is being reused.
|
||||
*/
|
||||
return helper.options.transform
|
||||
? stopAfterMaxProcessingTime(
|
||||
generator,
|
||||
helper.options.modelTimeout * 2.5,
|
||||
fullStop,
|
||||
)
|
||||
: generator;
|
||||
},
|
||||
multiline,
|
||||
);
|
||||
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// LLM
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ export class GeneratorReuseManager {
|
|||
) {
|
||||
this.currentGenerator?.cancel();
|
||||
|
||||
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
|
||||
const listenableGen = new ListenableGenerator(
|
||||
gen,
|
||||
this.onError,
|
||||
abortController,
|
||||
);
|
||||
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
|
||||
|
||||
this.pendingGeneratorPrefix = prefix;
|
||||
|
|
@ -43,7 +47,11 @@ export class GeneratorReuseManager {
|
|||
if (!this.shouldReuseExistingGenerator(prefix)) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
const abortController = new AbortController();
|
||||
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
|
||||
this._createListenableGenerator(
|
||||
abortController,
|
||||
newGenerator(abortController.signal),
|
||||
prefix,
|
||||
);
|
||||
}
|
||||
|
||||
// Already typed characters are those that are new in the prefix from the old generator
|
||||
|
|
|
|||
138
core/autocomplete/generation/utils.test.ts
Normal file
138
core/autocomplete/generation/utils.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { stopAfterMaxProcessingTime } from "./utils";
|
||||
|
||||
describe("stopAfterMaxProcessingTime", () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
|
||||
for (const chunk of chunks) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
||||
async function streamToString(
|
||||
stream: AsyncGenerator<string>,
|
||||
): Promise<string> {
|
||||
let result = "";
|
||||
for await (const chunk of stream) {
|
||||
result += chunk;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
it("should yield all chunks when maxTimeMs is not reached", async () => {
|
||||
const mockStream = createMockStream(["Hello", " world", "!"]);
|
||||
const fullStop = jest.fn();
|
||||
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
|
||||
|
||||
const output = await streamToString(result);
|
||||
|
||||
expect(output).toBe("Hello world!");
|
||||
expect(fullStop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.only("should stop processing after max time is reached", async () => {
|
||||
// Mock implementation of Date.now
|
||||
let currentTime = 0;
|
||||
const originalDateNow = Date.now;
|
||||
Date.now = jest.fn(() => currentTime);
|
||||
|
||||
// Create a generator that we can control
|
||||
async function* controlledGenerator(): AsyncGenerator<string> {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
// After yielding 10 chunks, simulate time passing beyond our limit
|
||||
if (i === 10) {
|
||||
currentTime = 1000; // This exceeds our 500ms limit
|
||||
}
|
||||
yield `chunk-${i}`;
|
||||
}
|
||||
}
|
||||
|
||||
const fullStop = jest.fn();
|
||||
const maxTimeMs = 500;
|
||||
|
||||
const transformedGenerator = stopAfterMaxProcessingTime(
|
||||
controlledGenerator(),
|
||||
maxTimeMs,
|
||||
fullStop,
|
||||
);
|
||||
|
||||
// Consume the generator and collect outputs
|
||||
const outputs: string[] = [];
|
||||
for await (const chunk of transformedGenerator) {
|
||||
outputs.push(chunk);
|
||||
}
|
||||
|
||||
// We expect:
|
||||
// 1. Not all chunks were processed (less than 100)
|
||||
// 2. fullStop was called
|
||||
// 3. We processed at least the chunks before time was exceeded
|
||||
expect(outputs.length).toBeLessThan(100);
|
||||
expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
|
||||
expect(fullStop).toHaveBeenCalled();
|
||||
|
||||
// Restore Date.now
|
||||
Date.now = originalDateNow;
|
||||
});
|
||||
|
||||
it("should check time only periodically based on checkInterval", async () => {
|
||||
const chunks = Array(100).fill("x");
|
||||
const mockStream = createMockStream(chunks);
|
||||
const fullStop = jest.fn();
|
||||
|
||||
// Spy on Date.now to count how many times it's called
|
||||
const dateSpy = jest.spyOn(Date, "now");
|
||||
|
||||
// Stream should complete normally (not hitting the timeout)
|
||||
await streamToString(
|
||||
stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
|
||||
);
|
||||
|
||||
// The first call is to set startTime, then once every checkInterval (10) chunks
|
||||
// So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
|
||||
// We use a range because implementation details might vary slightly
|
||||
expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
|
||||
expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
|
||||
|
||||
dateSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle empty stream gracefully", async () => {
|
||||
const mockStream = createMockStream([]);
|
||||
const fullStop = jest.fn();
|
||||
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
|
||||
|
||||
const output = await streamToString(result);
|
||||
|
||||
expect(output).toBe("");
|
||||
expect(fullStop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should pass through all chunks if there's no timeout", async () => {
|
||||
const chunks = Array(100).fill("test chunk");
|
||||
const mockStream = createMockStream(chunks);
|
||||
const fullStop = jest.fn();
|
||||
|
||||
// Use undefined as timeout to simulate no timeout
|
||||
const result = stopAfterMaxProcessingTime(
|
||||
mockStream,
|
||||
undefined as any,
|
||||
fullStop,
|
||||
);
|
||||
|
||||
// Process the stream
|
||||
const processedChunks = [];
|
||||
for await (const chunk of result) {
|
||||
processedChunks.push(chunk);
|
||||
}
|
||||
|
||||
expect(processedChunks.length).toBe(chunks.length);
|
||||
expect(fullStop).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
27
core/autocomplete/generation/utils.ts
Normal file
27
core/autocomplete/generation/utils.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
export async function* stopAfterMaxProcessingTime(
|
||||
stream: AsyncGenerator<string>,
|
||||
maxTimeMs: number,
|
||||
fullStop: () => void,
|
||||
): AsyncGenerator<string> {
|
||||
const startTime = Date.now();
|
||||
/**
|
||||
* Check every 10 chunks to avoid performance overhead.
|
||||
*/
|
||||
const checkInterval = 10;
|
||||
let chunkCount = 0;
|
||||
let totalCharCount = 0;
|
||||
|
||||
for await (const chunk of stream) {
|
||||
yield chunk;
|
||||
|
||||
chunkCount++;
|
||||
totalCharCount += chunk.length;
|
||||
|
||||
if (chunkCount % checkInterval === 0) {
|
||||
if (Date.now() - startTime > maxTimeMs) {
|
||||
fullStop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,10 @@
|
|||
import ignore from "ignore";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import {
|
||||
getGlobalContinueIgArray,
|
||||
getWorkspaceContinueIgArray,
|
||||
} from "../../indexing/ignore";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
|
@ -50,7 +54,12 @@ export async function shouldPrefilter(
|
|||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
const disableInFiles = [...(helper.options.disableInFiles ?? []), "*.prompt"];
|
||||
const disableInFiles = [
|
||||
...(helper.options.disableInFiles ?? []),
|
||||
"*.prompt",
|
||||
...getGlobalContinueIgArray(),
|
||||
...(await getWorkspaceContinueIgArray(ide)),
|
||||
];
|
||||
if (await isDisabledForFile(helper.filepath, disableInFiles, ide)) {
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import { findUriInDirs } from "../../util/uri";
|
|||
import { ContextRetrievalService } from "../context/ContextRetrievalService";
|
||||
import { GetLspDefinitionsFunction } from "../types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { openedFilesLruCache } from "../util/openedFilesLruCache";
|
||||
import { getDiffsFromCache } from "./gitDiffCache";
|
||||
|
||||
import {
|
||||
AutocompleteClipboardSnippet,
|
||||
|
|
@ -21,37 +23,17 @@ export interface SnippetPayload {
|
|||
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
|
||||
diffSnippets: AutocompleteDiffSnippet[];
|
||||
clipboardSnippets: AutocompleteClipboardSnippet[];
|
||||
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
|
||||
}
|
||||
|
||||
function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
|
||||
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
|
||||
const timeoutPromise = new Promise<T[]>((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
setTimeout(() => resolve([]), timeout);
|
||||
});
|
||||
|
||||
return Promise.race([promise, timeoutPromise]);
|
||||
}
|
||||
|
||||
class DiffSnippetsCache {
|
||||
private cache: Map<number, any> = new Map();
|
||||
private lastTimestamp: number = 0;
|
||||
|
||||
public set<T>(timestamp: number, value: T): T {
|
||||
// Clear old cache entry if exists
|
||||
if (this.lastTimestamp !== timestamp) {
|
||||
this.cache.clear();
|
||||
}
|
||||
this.lastTimestamp = timestamp;
|
||||
this.cache.set(timestamp, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public get(timestamp: number): any | undefined {
|
||||
return this.cache.get(timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
const diffSnippetsCache = new DiffSnippetsCache();
|
||||
|
||||
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
|
||||
// or they might separately track recently edited ranges)
|
||||
async function getIdeSnippets(
|
||||
|
|
@ -113,31 +95,73 @@ const getClipboardSnippets = async (
|
|||
const getDiffSnippets = async (
|
||||
ide: IDE,
|
||||
): Promise<AutocompleteDiffSnippet[]> => {
|
||||
const currentTimestamp = ide.getLastFileSaveTimestamp ?
|
||||
ide.getLastFileSaveTimestamp() :
|
||||
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
|
||||
const diffs = await getDiffsFromCache(ide);
|
||||
|
||||
// Check cache first
|
||||
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
|
||||
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
let diff: string[] = [];
|
||||
try {
|
||||
diff = await ide.getDiff(true);
|
||||
} catch (e) {
|
||||
console.error("Error getting diff for autocomplete", e);
|
||||
}
|
||||
|
||||
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
|
||||
return diffs.map((item) => {
|
||||
return {
|
||||
content: item,
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
};
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
const getSnippetsFromRecentlyOpenedFiles = async (
|
||||
helper: HelperVars,
|
||||
ide: IDE,
|
||||
): Promise<AutocompleteCodeSnippet[]> => {
|
||||
if (helper.options.useRecentlyOpened === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const currentFileUri = `${helper.filepath}`;
|
||||
|
||||
// Get all file URIs excluding the current file
|
||||
const fileUrisToRead = [...openedFilesLruCache.entriesDescending()]
|
||||
.filter(([fileUri, _]) => fileUri !== currentFileUri)
|
||||
.map(([fileUri, _]) => fileUri);
|
||||
|
||||
// Create an array of promises that each read a file with timeout
|
||||
const fileReadPromises = fileUrisToRead.map((fileUri) => {
|
||||
// Create a promise that resolves to a snippet or null
|
||||
const readPromise = new Promise<AutocompleteCodeSnippet | null>(
|
||||
(resolve) => {
|
||||
ide
|
||||
.readFile(fileUri)
|
||||
.then((fileContent) => {
|
||||
if (!fileContent || fileContent.trim() === "") {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
filepath: fileUri,
|
||||
content: fileContent,
|
||||
type: AutocompleteSnippetType.Code,
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(`Failed to read file ${fileUri}:`, e);
|
||||
resolve(null);
|
||||
});
|
||||
},
|
||||
);
|
||||
// Cut off at 80ms via racing promises
|
||||
return Promise.race([
|
||||
readPromise,
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 80)),
|
||||
]);
|
||||
});
|
||||
|
||||
// Execute all file reads in parallel
|
||||
const results = await Promise.all(fileReadPromises);
|
||||
|
||||
// Filter out null results
|
||||
return results.filter(Boolean) as AutocompleteCodeSnippet[];
|
||||
} catch (e) {
|
||||
console.error("Error processing opened files cache:", e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllSnippets = async ({
|
||||
|
|
@ -160,12 +184,18 @@ export const getAllSnippets = async ({
|
|||
ideSnippets,
|
||||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
] = await Promise.all([
|
||||
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
|
||||
racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
|
||||
IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
|
||||
racePromise(getDiffSnippets(ide)),
|
||||
racePromise(
|
||||
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
|
||||
),
|
||||
IDE_SNIPPETS_ENABLED
|
||||
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
|
||||
: [],
|
||||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
racePromise(getClipboardSnippets(ide)),
|
||||
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -176,5 +206,6 @@ export const getAllSnippets = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
84
core/autocomplete/snippets/gitDiffCache.test.ts
Normal file
84
core/autocomplete/snippets/gitDiffCache.test.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { GitDiffCache } from "./gitDiffCache";
|
||||
|
||||
beforeEach(() => {
|
||||
// Add this line to GitDiffCache class to make instance accessible
|
||||
(GitDiffCache as any).instance = null;
|
||||
});
|
||||
|
||||
test("GitDiffCache returns cached results within cache time", async () => {
|
||||
const mockDiff = ["file1.ts", "file2.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
|
||||
|
||||
const result1 = await cache.get();
|
||||
const result2 = await cache.get();
|
||||
|
||||
expect(result1).toEqual(mockDiff);
|
||||
expect(result2).toEqual(mockDiff);
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("GitDiffCache refreshes cache after expiration", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
|
||||
|
||||
const result1 = await cache.get();
|
||||
await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
|
||||
const result2 = await cache.get();
|
||||
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("GitDiffCache returns empty array on error", async () => {
|
||||
const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
const result = await cache.get();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("GitDiffCache reuses pending request", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
let resolvePromise: (value: string[]) => void;
|
||||
const getDiffFn = jest.fn().mockImplementation(() => {
|
||||
return new Promise((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
const promise1 = cache.get();
|
||||
const promise2 = cache.get();
|
||||
|
||||
resolvePromise!(mockDiff);
|
||||
|
||||
const [result1, result2] = await Promise.all([promise1, promise2]);
|
||||
|
||||
expect(result1).toEqual(mockDiff);
|
||||
expect(result2).toEqual(mockDiff);
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("GitDiffCache invalidate clears cache", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
await cache.get();
|
||||
cache.invalidate();
|
||||
await cache.get();
|
||||
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("GitDiffCache maintains singleton instance", () => {
|
||||
const getDiffFn1 = jest.fn();
|
||||
const getDiffFn2 = jest.fn();
|
||||
|
||||
const instance1 = GitDiffCache.getInstance(getDiffFn1);
|
||||
const instance2 = GitDiffCache.getInstance(getDiffFn2);
|
||||
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
73
core/autocomplete/snippets/gitDiffCache.ts
Normal file
73
core/autocomplete/snippets/gitDiffCache.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { IDE } from "../..";
|
||||
|
||||
type GetDiffFn = () => Promise<string[]>;
|
||||
|
||||
export class GitDiffCache {
|
||||
private static instance: GitDiffCache | null = null;
|
||||
private cachedDiff: string[] | undefined = undefined;
|
||||
private lastFetchTime: number = 0;
|
||||
private pendingRequest: Promise<string[]> | null = null;
|
||||
private getDiffFn: GetDiffFn;
|
||||
private cacheTimeMs: number;
|
||||
|
||||
private constructor(getDiffFn: GetDiffFn, cacheTimeSeconds: number = 60) {
|
||||
this.getDiffFn = getDiffFn;
|
||||
this.cacheTimeMs = cacheTimeSeconds * 1000;
|
||||
}
|
||||
|
||||
public static getInstance(
|
||||
getDiffFn: GetDiffFn,
|
||||
cacheTimeSeconds?: number,
|
||||
): GitDiffCache {
|
||||
if (!GitDiffCache.instance) {
|
||||
GitDiffCache.instance = new GitDiffCache(getDiffFn, cacheTimeSeconds);
|
||||
}
|
||||
return GitDiffCache.instance;
|
||||
}
|
||||
|
||||
private async getDiffPromise(): Promise<string[]> {
|
||||
try {
|
||||
const diff = await this.getDiffFn();
|
||||
this.cachedDiff = diff;
|
||||
this.lastFetchTime = Date.now();
|
||||
return this.cachedDiff;
|
||||
} catch (e) {
|
||||
console.error("Error fetching git diff:", e);
|
||||
return [];
|
||||
} finally {
|
||||
this.pendingRequest = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async get(): Promise<string[]> {
|
||||
if (
|
||||
this.cachedDiff !== undefined &&
|
||||
Date.now() - this.lastFetchTime < this.cacheTimeMs
|
||||
) {
|
||||
return this.cachedDiff;
|
||||
}
|
||||
|
||||
// If there's already a request in progress, return that instead of starting a new one
|
||||
if (this.pendingRequest) {
|
||||
return this.pendingRequest;
|
||||
}
|
||||
|
||||
this.pendingRequest = this.getDiffPromise();
|
||||
return this.pendingRequest;
|
||||
}
|
||||
|
||||
public invalidate(): void {
|
||||
this.cachedDiff = undefined;
|
||||
this.pendingRequest = null;
|
||||
}
|
||||
}
|
||||
|
||||
// factory to make diff cache more testable
|
||||
export function getDiffFn(ide: IDE): GetDiffFn {
|
||||
return () => ide.getDiff(true);
|
||||
}
|
||||
|
||||
export async function getDiffsFromCache(ide: IDE): Promise<string[]> {
|
||||
const diffCache = GitDiffCache.getInstance(getDiffFn(ide));
|
||||
return await diffCache.get();
|
||||
}
|
||||
|
|
@ -71,6 +71,22 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
const seedCoderFimTemplate: AutocompleteTemplate = {
|
||||
template:
|
||||
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<[end▁of▁sentence]>",
|
||||
"<[fim-prefix]>",
|
||||
"<[fim-middle]>",
|
||||
"<[fim-suffix]>",
|
||||
"<[PAD▁TOKEN]>",
|
||||
"<[SEP▁TOKEN]>",
|
||||
"<[begin▁of▁sentence]>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const codestralFimTemplate: AutocompleteTemplate = {
|
||||
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
|
||||
completionOptions: {
|
||||
|
|
@ -426,6 +442,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
return qwenCoderFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
|
||||
return seedCoderFimTemplate;
|
||||
}
|
||||
|
||||
if (
|
||||
lowerCaseModel.includes("starcoder") ||
|
||||
lowerCaseModel.includes("star-coder") ||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,434 @@
|
|||
/**
|
||||
* Comprehensive tests for formatOpenedFilesContext.ts
|
||||
*
|
||||
*/
|
||||
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../../snippets/types";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
|
||||
|
||||
// Import the now-exported internal functions
|
||||
import {
|
||||
getRecencyAndSizeScore,
|
||||
rankByScore,
|
||||
setLogStats,
|
||||
trimSnippetForContext,
|
||||
} from "../formatOpenedFilesContext";
|
||||
|
||||
describe("formatOpenedFilesContext main function tests", () => {
|
||||
const mockHelper = {
|
||||
modelName: "test-model",
|
||||
} as HelperVars;
|
||||
|
||||
const TOKEN_BUFFER = 50;
|
||||
|
||||
// Create sample code snippets with various sizes
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return empty array when no snippets are provided", () => {
|
||||
const result = formatOpenedFilesContext(
|
||||
[],
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should handle zero remaining token count", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "content of file 1"),
|
||||
createCodeSnippet("file2.ts", "content of file 2"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
0,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should handle snippets with empty content", () => {
|
||||
const emptySnippets = [
|
||||
createCodeSnippet("empty1.ts", ""),
|
||||
createCodeSnippet("empty2.ts", ""),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
emptySnippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(emptySnippets.length);
|
||||
});
|
||||
|
||||
test("should return all snippets when they all fit within token limit", () => {
|
||||
const smallSnippets = [
|
||||
createCodeSnippet("small1.ts", "a"),
|
||||
createCodeSnippet("small2.ts", "b"),
|
||||
createCodeSnippet("small3.ts", "c"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
smallSnippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(smallSnippets.length);
|
||||
});
|
||||
|
||||
test("should handle limited token count", () => {
|
||||
const snippets = Array(10)
|
||||
.fill(0)
|
||||
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1, // Extremely small token count
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
});
|
||||
|
||||
test("should accept valid inputs with adequate token count", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "Some content here"),
|
||||
createCodeSnippet("file2.ts", "More content here"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should handle already added snippets parameter", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "content of file 1"),
|
||||
createCodeSnippet("file2.ts", "content of file 2"),
|
||||
];
|
||||
|
||||
const alreadyAddedSnippets = [createDiffSnippet("diff content")];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
alreadyAddedSnippets,
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(snippets.length);
|
||||
});
|
||||
|
||||
test("should handle large snippets by trimming them", () => {
|
||||
const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
[largeSnippet],
|
||||
200,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].filepath).toBe(largeSnippet.filepath);
|
||||
expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
|
||||
});
|
||||
|
||||
test("should prioritize more recent snippets when not all fit", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("recent1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("recent2.ts", "b".repeat(10000)),
|
||||
createCodeSnippet("recent3.ts", "c".repeat(10000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
200,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
|
||||
});
|
||||
|
||||
test("should handle a mix of large and small snippets effectively", () => {
|
||||
const mixedSnippets = [
|
||||
createCodeSnippet("small1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("large1.ts", "b".repeat(5000)),
|
||||
createCodeSnippet("small2.ts", "c".repeat(10)),
|
||||
createCodeSnippet("large2.ts", "d".repeat(5000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
mixedSnippets,
|
||||
500,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
|
||||
});
|
||||
|
||||
test("should respect minimum token threshold when trimming", () => {
|
||||
const largeSnippets = [
|
||||
createCodeSnippet("large1.ts", "a".repeat(5000)),
|
||||
createCodeSnippet("large2.ts", "b".repeat(5000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
largeSnippets,
|
||||
150,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.length > 0) {
|
||||
expect(result[0].content.length).toBeLessThan(
|
||||
largeSnippets[0].content.length,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for rankByScore function
|
||||
describe("rankByScore function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return empty array when given empty array", () => {
|
||||
const result = rankByScore([]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should rank snippets by score", () => {
|
||||
// Initialize logMin and logMax by calling setLogStats first
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("file2.ts", "b".repeat(1000)),
|
||||
createCodeSnippet("file3.ts", "c".repeat(100)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
const result = rankByScore(snippets);
|
||||
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
|
||||
// The snippets should be ranked in some order, which may not match input order
|
||||
expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
|
||||
snippets.map((s) => s.filepath),
|
||||
);
|
||||
});
|
||||
|
||||
test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
|
||||
// Create more snippets than the default limit
|
||||
const manySnippets = Array(10)
|
||||
.fill(0)
|
||||
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
|
||||
setLogStats(manySnippets);
|
||||
|
||||
const result = rankByScore(manySnippets);
|
||||
|
||||
// The function should limit the number of snippets (defaultNumFilesUsed is 5)
|
||||
expect(result.length).toBeLessThanOrEqual(5);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for getRecencyAndSizeScore function
|
||||
describe("getRecencyAndSizeScore function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("recency score should decrease with higher index", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "a".repeat(100)),
|
||||
createCodeSnippet("file2.ts", "b".repeat(100)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test that score decreases with increasing index
|
||||
const score0 = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const score1 = getRecencyAndSizeScore(1, snippets[0]);
|
||||
const score2 = getRecencyAndSizeScore(2, snippets[0]);
|
||||
|
||||
expect(score0).toBeGreaterThan(score1);
|
||||
expect(score1).toBeGreaterThan(score2);
|
||||
});
|
||||
|
||||
test("size score should be higher for smaller snippets", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("small.ts", "a".repeat(50)),
|
||||
createCodeSnippet("medium.ts", "b".repeat(200)),
|
||||
createCodeSnippet("large.ts", "c".repeat(1000)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test with same recency index but different sizes
|
||||
const smallScore = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
|
||||
const largeScore = getRecencyAndSizeScore(0, snippets[2]);
|
||||
|
||||
// Scores should reflect preference for smaller snippets
|
||||
expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
|
||||
expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
|
||||
});
|
||||
|
||||
test("recency and size both affect the score with recency having more weight", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("recent_large.ts", "a".repeat(1000)),
|
||||
createCodeSnippet("old_small.ts", "b".repeat(50)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test that recency and size both contribute to the score
|
||||
const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
|
||||
|
||||
// We're not making a direct comparison, just verifying the scoring mechanism works
|
||||
expect(recentLargeScore).toBeGreaterThan(0);
|
||||
expect(oldSmallScore).toBeGreaterThan(0);
|
||||
expect(oldSmallScore).toBeLessThan(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for setLogStats function
|
||||
describe("setLogStats function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should set logMin and logMax based on snippet sizes", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("small.ts", "a".repeat(50)),
|
||||
createCodeSnippet("medium.ts", "b".repeat(200)),
|
||||
createCodeSnippet("large.ts", "c".repeat(1000)),
|
||||
];
|
||||
|
||||
// We can't directly test logMin and logMax as they're private
|
||||
// but we can verify that the function runs without errors
|
||||
expect(() => setLogStats(snippets)).not.toThrow();
|
||||
});
|
||||
|
||||
test("should handle empty snippets", () => {
|
||||
const emptySnippets = [
|
||||
createCodeSnippet("empty1.ts", ""),
|
||||
createCodeSnippet("empty2.ts", ""),
|
||||
];
|
||||
|
||||
expect(() => setLogStats(emptySnippets)).not.toThrow();
|
||||
});
|
||||
|
||||
test("should handle single snippet", () => {
|
||||
const singleSnippet = [createCodeSnippet("single.ts", "content")];
|
||||
|
||||
expect(() => setLogStats(singleSnippet)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for trimSnippetForContext function
|
||||
describe("trimSnippetForContext function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return original snippet if it fits within token limit", () => {
|
||||
const snippet = createCodeSnippet("small.ts", "small content");
|
||||
const modelName = "test-model";
|
||||
const maxTokens = 1000; // Large enough to fit the snippet
|
||||
|
||||
const result = trimSnippetForContext(snippet, maxTokens, modelName);
|
||||
|
||||
// Should return the original snippet with its token count
|
||||
expect(result.newSnippet).toEqual(snippet);
|
||||
expect(typeof result.newTokens).toBe("number");
|
||||
expect(result.newTokens).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should trim snippet content if it exceeds token limit", () => {
|
||||
const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
|
||||
const modelName = "test-model";
|
||||
const maxTokens = 10; // Small enough to require trimming
|
||||
|
||||
const result = trimSnippetForContext(snippet, maxTokens, modelName);
|
||||
|
||||
// Should return a trimmed snippet
|
||||
expect(result.newSnippet.filepath).toBe(snippet.filepath);
|
||||
expect(result.newSnippet.type).toBe(snippet.type);
|
||||
expect(result.newSnippet.content.length).toBeLessThanOrEqual(
|
||||
snippet.content.length,
|
||||
);
|
||||
|
||||
// Token count should be less than or equal to maxTokens
|
||||
expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,8 +3,10 @@ import { SnippetPayload } from "../snippets";
|
|||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
|
||||
|
||||
import { isValidSnippet } from "./validation";
|
||||
|
||||
|
|
@ -42,17 +44,19 @@ export const getSnippets = (
|
|||
helper: HelperVars,
|
||||
payload: SnippetPayload,
|
||||
): AutocompleteSnippet[] => {
|
||||
|
||||
const snippets = {
|
||||
"clipboard": payload.clipboardSnippets,
|
||||
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
|
||||
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
|
||||
"diff": payload.diffSnippets,
|
||||
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
}
|
||||
clipboard: payload.clipboardSnippets,
|
||||
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
|
||||
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
|
||||
diff: payload.diffSnippets,
|
||||
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
|
||||
base: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
// Define snippets with their priorities
|
||||
const snippetConfigs: {
|
||||
|
|
@ -61,92 +65,133 @@ export const getSnippets = (
|
|||
defaultPriority: number;
|
||||
snippets: AutocompleteSnippet[];
|
||||
}[] = [
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyOpenedFiles",
|
||||
enabledOrPriority: helper.options.useRecentlyOpened,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyOpenedFileSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
if they are visible. We should handle them separately so that we can control their priority
|
||||
and whether they should be included or not. */
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 5,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
),
|
||||
),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
|
||||
// Create a readable order of enabled snippets
|
||||
const snippetOrder = snippetConfigs
|
||||
.filter(({ enabledOrPriority }) => enabledOrPriority)
|
||||
.map(({ key, enabledOrPriority, defaultPriority }) => ({
|
||||
key,
|
||||
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
|
||||
priority:
|
||||
typeof enabledOrPriority === "number"
|
||||
? enabledOrPriority
|
||||
: defaultPriority,
|
||||
}))
|
||||
.sort((a, b) => a.priority - b.priority);
|
||||
|
||||
// Log the snippet order for debugging - uncomment if needed
|
||||
/* console.log(
|
||||
'Snippet processing order:',
|
||||
snippetOrder
|
||||
.map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n")
|
||||
); */
|
||||
|
||||
// Convert configs to prioritized snippets
|
||||
let prioritizedSnippets = snippetOrder
|
||||
.flatMap(({ key, priority }) =>
|
||||
snippets[key].map(snippet => ({ snippet, priority }))
|
||||
)
|
||||
.sort((a, b) => a.priority - b.priority)
|
||||
.map(({ snippet }) => snippet);
|
||||
|
||||
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
|
||||
// while looking at the prompts in the Continue's output
|
||||
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
|
||||
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
|
||||
|
||||
const finalSnippets = [];
|
||||
let remainingTokenCount = getRemainingTokenCount(helper);
|
||||
|
||||
while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) {
|
||||
const snippet = prioritizedSnippets.shift();
|
||||
if (!snippet || !isValidSnippet(snippet)) {
|
||||
continue;
|
||||
// tracks already added filepaths for deduplication
|
||||
const addedFilepaths = new Set<string>();
|
||||
|
||||
// Process snippets in priority order
|
||||
for (const { key } of snippetOrder) {
|
||||
// Special handling for recentlyOpenedFiles
|
||||
if (key === "recentlyOpenedFiles" && helper.options.useRecentlyOpened) {
|
||||
// Custom trimming
|
||||
const processedSnippets = formatOpenedFilesContext(
|
||||
payload.recentlyOpenedFileSnippets,
|
||||
remainingTokenCount,
|
||||
helper,
|
||||
finalSnippets,
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
// Add processed snippets to finalSnippets respecting token limits
|
||||
for (const snippet of processedSnippets) {
|
||||
if (!isValidSnippet(snippet)) continue;
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
addedFilepaths.add(snippet.filepath);
|
||||
remainingTokenCount -= snippetSize;
|
||||
} else {
|
||||
continue; // Not enough tokens, try again with next snippet
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Normal processing for other snippet types
|
||||
const snippetsToProcess = snippets[key].filter(
|
||||
(snippet) =>
|
||||
snippet.type !== AutocompleteSnippetType.Code ||
|
||||
!addedFilepaths.has(snippet.filepath),
|
||||
);
|
||||
|
||||
for (const snippet of snippetsToProcess) {
|
||||
if (!isValidSnippet(snippet)) continue;
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
|
||||
if ((snippet as AutocompleteCodeSnippet).filepath) {
|
||||
addedFilepaths.add((snippet as AutocompleteCodeSnippet).filepath);
|
||||
}
|
||||
|
||||
remainingTokenCount -= snippetSize;
|
||||
} else {
|
||||
continue; // Not enough tokens, try again with next snippet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
remainingTokenCount -= snippetSize;
|
||||
}
|
||||
// If we're out of tokens, no need to process more snippet types
|
||||
if (remainingTokenCount <= 0) break;
|
||||
}
|
||||
|
||||
return finalSnippets;
|
||||
|
|
|
|||
183
core/autocomplete/templating/formatOpenedFilesContext.ts
Normal file
183
core/autocomplete/templating/formatOpenedFilesContext.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { countTokens, pruneStringFromBottom } from "../../llm/countTokens";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
let logMin: number;
|
||||
let logMax: number;
|
||||
|
||||
const numFilesConsidered = 10;
|
||||
const defaultNumFilesUsed = 5;
|
||||
const recencyWeight = 0.6;
|
||||
const sizeWeight = 0.4;
|
||||
const minSize = 10;
|
||||
const minTokensInSnippet = 125;
|
||||
|
||||
// Fits opened-file snippets into the remaining amount of prompt tokens
|
||||
export function formatOpenedFilesContext(
|
||||
recentlyOpenedFilesSnippets: AutocompleteCodeSnippet[],
|
||||
remainingTokenCount: number,
|
||||
helper: HelperVars,
|
||||
alreadyAddedSnippets: AutocompleteSnippet[],
|
||||
TOKEN_BUFFER: number,
|
||||
): AutocompleteCodeSnippet[] {
|
||||
if (recentlyOpenedFilesSnippets.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// deduplication; if a snippet is already added, don't include it here
|
||||
for (const snippet of alreadyAddedSnippets) {
|
||||
if (snippet.type !== AutocompleteSnippetType.Code) {
|
||||
continue;
|
||||
}
|
||||
recentlyOpenedFilesSnippets = recentlyOpenedFilesSnippets.filter(
|
||||
(s) => s.filepath !== snippet.filepath,
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate how many full snippets would fit within the remaining token count
|
||||
let numSnippetsThatFit = 0;
|
||||
let totalTokens = 0;
|
||||
|
||||
const numFilesUsed = Math.min(
|
||||
defaultNumFilesUsed,
|
||||
recentlyOpenedFilesSnippets.length,
|
||||
);
|
||||
|
||||
for (let i = 0; i < recentlyOpenedFilesSnippets.length; i++) {
|
||||
const snippetTokens = countTokens(
|
||||
recentlyOpenedFilesSnippets[i].content,
|
||||
helper.modelName,
|
||||
);
|
||||
if (totalTokens + snippetTokens < remainingTokenCount - TOKEN_BUFFER) {
|
||||
totalTokens += snippetTokens;
|
||||
numSnippetsThatFit++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if all the untrimmed snippets, or more than a default value, fit, return the untrimmed snippets
|
||||
if (numSnippetsThatFit >= numFilesUsed) {
|
||||
return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit);
|
||||
}
|
||||
|
||||
// If they don't fit, adaptively trim them.
|
||||
setLogStats(recentlyOpenedFilesSnippets);
|
||||
const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets);
|
||||
let N = topScoredSnippets.length;
|
||||
while (remainingTokenCount - TOKEN_BUFFER < N * minTokensInSnippet) {
|
||||
topScoredSnippets.pop();
|
||||
N = topScoredSnippets.length;
|
||||
if (N === 0) break;
|
||||
}
|
||||
|
||||
let trimmedSnippets = new Array<AutocompleteCodeSnippet>();
|
||||
|
||||
while (N > 0) {
|
||||
let W = 2 / (N + 1);
|
||||
let snippetTokenLimit = Math.floor(
|
||||
minTokensInSnippet +
|
||||
W * (remainingTokenCount - TOKEN_BUFFER - N * minTokensInSnippet),
|
||||
);
|
||||
|
||||
let trimmedSnippetAndTokenCount = trimSnippetForContext(
|
||||
topScoredSnippets[0],
|
||||
snippetTokenLimit,
|
||||
helper.modelName,
|
||||
);
|
||||
trimmedSnippets.push(trimmedSnippetAndTokenCount.newSnippet);
|
||||
remainingTokenCount -= trimmedSnippetAndTokenCount.newTokens;
|
||||
topScoredSnippets.shift();
|
||||
N = topScoredSnippets.length;
|
||||
}
|
||||
|
||||
return trimmedSnippets;
|
||||
}
|
||||
|
||||
// Rank snippets by recency and size
|
||||
const rankByScore = (
|
||||
snippets: AutocompleteCodeSnippet[],
|
||||
): AutocompleteCodeSnippet[] => {
|
||||
if (snippets.length === 0) return [];
|
||||
|
||||
const topSnippets = snippets.slice(0, numFilesConsidered);
|
||||
|
||||
// Sort by score (using original index for recency calculation)
|
||||
const scoredSnippets = topSnippets.map((snippet, i) => ({
|
||||
snippet,
|
||||
originalIndex: i,
|
||||
score: getRecencyAndSizeScore(i, snippet),
|
||||
}));
|
||||
|
||||
// Uncomment to debug. Logs the table of snippets with their scores (in order of recency).
|
||||
/* console.table(
|
||||
topSnippets.map((snippet, i) => ({
|
||||
filepath: "filepath" in snippet ? snippet.filepath : "unknown",
|
||||
recencyAndSizeScore: getRecencyAndSizeScore(i, snippet),
|
||||
})),
|
||||
); */
|
||||
|
||||
scoredSnippets.sort((a, b) => b.score - a.score);
|
||||
|
||||
return scoredSnippets
|
||||
.slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length))
|
||||
.map((item) => item.snippet);
|
||||
};
|
||||
|
||||
// Returns linear combination of recency and size scores
|
||||
// recency score is exponential decay over recency; log normalized score is used for size
|
||||
const getRecencyAndSizeScore = (
|
||||
index: number,
|
||||
snippet: AutocompleteSnippet,
|
||||
): number => {
|
||||
const recencyScore = Math.pow(1.15, -1 * index);
|
||||
|
||||
const logCurrent = Math.log(Math.max(snippet.content.length, minSize));
|
||||
const sizeScore =
|
||||
logMax === logMin ? 0.5 : 1 - (logCurrent - logMin) / (logMax - logMin);
|
||||
|
||||
return recencyWeight * recencyScore + sizeWeight * sizeScore;
|
||||
};
|
||||
|
||||
const setLogStats = (snippets: AutocompleteSnippet[]): void => {
|
||||
let contentSizes = snippets
|
||||
.slice(0, 10)
|
||||
.map((snippet) => snippet.content.length);
|
||||
logMin = Math.log(Math.max(Math.min(...contentSizes), minSize));
|
||||
logMax = Math.log(Math.max(Math.max(...contentSizes), minSize));
|
||||
return;
|
||||
};
|
||||
|
||||
function trimSnippetForContext(
|
||||
snippet: AutocompleteCodeSnippet,
|
||||
maxTokens: number,
|
||||
modelName: string,
|
||||
): { newSnippet: AutocompleteCodeSnippet; newTokens: number } {
|
||||
let numTokensInSnippet = countTokens(snippet.content, modelName);
|
||||
if (numTokensInSnippet <= maxTokens) {
|
||||
return { newSnippet: snippet, newTokens: numTokensInSnippet };
|
||||
}
|
||||
|
||||
let trimmedCode = pruneStringFromBottom(
|
||||
modelName,
|
||||
maxTokens,
|
||||
snippet.content,
|
||||
);
|
||||
|
||||
return {
|
||||
newSnippet: { ...snippet, content: trimmedCode },
|
||||
newTokens: countTokens(trimmedCode, modelName),
|
||||
};
|
||||
}
|
||||
|
||||
// Uncomment for testing
|
||||
export {
|
||||
getRecencyAndSizeScore,
|
||||
rankByScore,
|
||||
setLogStats,
|
||||
trimSnippetForContext,
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue