Merge branch 'feature/nextEdit' of github.com:continuedev/continue into jacob/feature/next-edit-mvp
This commit is contained in:
commit
46fd9ebacd
189 changed files with 3420 additions and 1128 deletions
|
|
@ -1,16 +1,111 @@
|
|||
---
|
||||
globs: docs/**/*.{md,mdx}
|
||||
description: Standards for writing and maintaining Continue Docs
|
||||
globs: docs/\*_/_.{md,mdx}
|
||||
description: This style guide should be used as a reference for maintaining consistency across all Continue documentation
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Continue Docs Standards
|
||||
# Continue Documentation Style Guide
|
||||
|
||||
## Overview
|
||||
|
||||
## Writing Tone & Voice
|
||||
|
||||
### Conversational and Direct
|
||||
|
||||
- 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
|
||||
- Use simple, conversational language that gets straight to the point
|
||||
- Avoid overly technical jargon when simpler terms work
|
||||
- Write as if speaking directly to the developer using the tool
|
||||
- Keep paragraphs concise and scannable
|
||||
- Use code blocks with appropriate language tags
|
||||
|
||||
**Example:**
|
||||
✅ "You send it a question, and it replies with an answer"
|
||||
❌ "The system processes user queries and generates corresponding responses"
|
||||
|
||||
### Helpful and Instructional
|
||||
|
||||
- Focus on helping users accomplish their goals
|
||||
- Use active voice and imperative mood for instructions
|
||||
- Assume users want to get things done quickly
|
||||
- Include relevant Admonition components for tips, warnings, and info
|
||||
|
||||
**Example:**
|
||||
✅ "Press cmd/ctrl + L to begin a new session"
|
||||
❌ "A new session can be initiated by pressing cmd/ctrl + L"
|
||||
|
||||
### Practical and Task-Oriented
|
||||
|
||||
- Emphasize what users can accomplish with each feature
|
||||
- Lead with benefits and use cases before diving into mechanics
|
||||
- Keep explanations grounded in real-world scenarios
|
||||
|
||||
## Content Structure
|
||||
|
||||
### Page Organization
|
||||
|
||||
1. **Visual Introduction**: Lead with GIFs or images showing the feature in action
|
||||
2. **Purpose Statement**: Brief explanation of what the feature does and when to use it
|
||||
3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts
|
||||
4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed
|
||||
5. **Additional Tips**: Advanced usage or troubleshooting notes
|
||||
|
||||
### Section Headers
|
||||
|
||||
- Use consistent heading hierarchy starting with h2 (##)
|
||||
- Include YAML frontmatter with title, description, and keywords
|
||||
- Use action-oriented headers that describe what users will do
|
||||
- Format: "Verb + object" (e.g., "Type a request and press enter")
|
||||
- Keep headers concise but descriptive
|
||||
- Use title case
|
||||
|
||||
**Examples:**
|
||||
✅ "Highlight code and activate"
|
||||
✅ "Accept or reject changes"
|
||||
✅ "Switch between different models"
|
||||
|
||||
### Lists and Steps
|
||||
|
||||
- Use numbered lists for sequential steps
|
||||
- Use bullet points for feature lists or options
|
||||
- Keep list items parallel in structure
|
||||
- Start action items with verbs
|
||||
|
||||
## Technical Writing Standards
|
||||
|
||||
### Code and Keyboard Shortcuts
|
||||
|
||||
- Use `backticks` for inline code elements
|
||||
- Format keyboard shortcuts consistently: `cmd/ctrl + L`
|
||||
- Always provide shortcuts for Mac/Windows/Linux
|
||||
- Use code blocks for configuration examples with proper syntax highlighting
|
||||
|
||||
### Cross-References
|
||||
|
||||
- Link to related sections using descriptive anchor text
|
||||
- Use relative links to other documentation pages
|
||||
- Format: `[descriptive text](/path/to/page)`
|
||||
|
||||
### Platform Differences
|
||||
|
||||
- Always address both VS Code and JetBrains when applicable
|
||||
- Use clear subheadings to separate platform-specific instructions
|
||||
- Lead with the more common platform (typically VS Code) when both are covered
|
||||
|
||||
## Language Conventions
|
||||
|
||||
### Terminology
|
||||
|
||||
- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places)
|
||||
- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue)
|
||||
- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete)
|
||||
|
||||
### Abbreviations
|
||||
|
||||
- Spell out acronyms on first use, then use abbreviation consistently
|
||||
- Common abbreviations: LLM, IDE, API, URL
|
||||
|
||||
### Pronouns
|
||||
|
||||
- Use "you" to address the user directly
|
||||
- Use "it" to refer to the tool/model
|
||||
- Avoid "we" unless referring to the Continue team
|
||||
|
|
|
|||
7
.continue/rules/github-pr-documentation-updater.md
Normal file
7
.continue/rules/github-pr-documentation-updater.md
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
---
|
||||
name: Update docs from GitHub PR
|
||||
description: Provide a PR link to update docs based on
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.
|
||||
4
.continue/rules/navigating-responses.md
Normal file
4
.continue/rules/navigating-responses.md
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
If the user's request is vague and you don't have enough information to confidently answer, you can either
|
||||
|
||||
- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
|
||||
- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.
|
||||
6
.continue/rules/programming-principles.md
Normal file
6
.continue/rules/programming-principles.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
name: Programming principles
|
||||
description: Guidelines for coding fundamentals in this project
|
||||
---
|
||||
|
||||
Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.
|
||||
1
.continue/rules/pure-function-unit-tests.md
Normal file
1
.continue/rules/pure-function-unit-tests.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.
|
||||
|
|
@ -6,25 +6,23 @@ rules:
|
|||
rule: >-
|
||||
For unit testing in this project:
|
||||
|
||||
1. The project uses Vitest and Jest for testing. Prefer Vitest
|
||||
|
||||
1. The project uses Jest as the testing framework
|
||||
2. Run tests from within the specific package directory (e.g., `cd core && ..`
|
||||
|
||||
2. Run tests using `npm test` from within the specific package/module
|
||||
directory
|
||||
3. For vitest tests,
|
||||
- Test files follow the pattern `*.vitest.ts`
|
||||
- Run tests using `vitest` from within the specific package/module
|
||||
directory: `cd [directory] && vitest -- [test file path]`
|
||||
|
||||
3. Command structure: `cd [directory] && npm test -- [test file path]`
|
||||
4. For jest tests,
|
||||
- Test files follow the pattern `*.test.ts`
|
||||
- Run tests using `npm test` from within the specific package/module
|
||||
directory: `cd [directory] && npm test -- [test file path]`
|
||||
- The test script uses experimental VM modules via NODE_OPTIONS flag
|
||||
|
||||
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()`
|
||||
5. For both
|
||||
- Write tests as top-level `test()` functions - DO NOT use `describe()`
|
||||
blocks
|
||||
|
||||
9. Include the function name being tested in the test description for
|
||||
- Include the function name being tested in the test description for
|
||||
clarity
|
||||
|
|
|
|||
5
.continue/rules/vs-code-commands-helper-functions.md
Normal file
5
.continue/rules/vs-code-commands-helper-functions.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
globs: "extensions/vscode/src/commands.ts"
|
||||
---
|
||||
|
||||
When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.
|
||||
12
binary/package-lock.json
generated
12
binary/package-lock.json
generated
|
|
@ -20,6 +20,7 @@
|
|||
"posthog-node": "^3.6.3",
|
||||
"system-ca": "^1.0.2",
|
||||
"tar": "^7.4.3",
|
||||
"undici": "^7.10.0",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
"win-ca": "^3.5.1"
|
||||
|
|
@ -105,6 +106,7 @@
|
|||
"sqlite3": "^5.1.7",
|
||||
"system-ca": "^1.0.3",
|
||||
"tar": "^7.4.3",
|
||||
"tree-sitter-structured-text": "^0.0.1",
|
||||
"tree-sitter-wasms": "^0.1.11",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
|
|
@ -143,6 +145,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"tree-sitter-cli": "^0.22.5",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
@ -6774,6 +6777,15 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "7.10.0",
|
||||
"resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz",
|
||||
"integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20.18.1"
|
||||
}
|
||||
},
|
||||
"node_modules/universal-user-agent": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz",
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@
|
|||
"posthog-node": "^3.6.3",
|
||||
"system-ca": "^1.0.2",
|
||||
"tar": "^7.4.3",
|
||||
"undici": "^7.10.0",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
"win-ca": "^3.5.1"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ const { rimrafSync } = require("rimraf");
|
|||
const tar = require("tar");
|
||||
const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets");
|
||||
const AdmZip = require("adm-zip");
|
||||
const { ProxyAgent } = require("undici");
|
||||
|
||||
const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`;
|
||||
|
||||
|
|
@ -16,8 +17,13 @@ const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/downloa
|
|||
*/
|
||||
async function downloadFile(url, destPath) {
|
||||
// Use the built-in fetch API instead of node-fetch
|
||||
// Use proxy if set in environment variables
|
||||
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
|
||||
const agent = proxy ? new ProxyAgent(proxy) : undefined;
|
||||
|
||||
const response = await fetch(url, {
|
||||
redirect: "follow", // Automatically follow redirects
|
||||
dispatcher: agent,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
|
|||
|
|
@ -70,4 +70,20 @@ export class ContextRetrievalService {
|
|||
helper.treePath,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the import definitions cache for a file.
|
||||
* This is normally done automatically when the active text editor changes,
|
||||
* but needs to be called manually when using context fetching outside the normal flow.
|
||||
*/
|
||||
public async initializeForFile(filepath: string): Promise<void> {
|
||||
try {
|
||||
await (this.importDefinitionsService as any).cache.initKey(filepath);
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`Failed to initialize import definitions cache for ${filepath}:`,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ export function slashFromCustomCommand(
|
|||
config,
|
||||
selectedCode,
|
||||
fetch,
|
||||
abortController,
|
||||
}) {
|
||||
// Render prompt template
|
||||
let renderedPrompt: string;
|
||||
|
|
@ -63,7 +64,7 @@ export function slashFromCustomCommand(
|
|||
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { renderChatMessage } from "../../util/messageContent.js";
|
|||
const CommitMessageCommand: SlashCommand = {
|
||||
name: "commit",
|
||||
description: "Generate a commit message for current changes",
|
||||
run: async function* ({ ide, llm, params }) {
|
||||
run: async function* ({ ide, llm, params, abortController }) {
|
||||
const includeUnstaged = params?.includeUnstaged ?? false;
|
||||
const diff = await ide.getDiff(includeUnstaged);
|
||||
|
||||
|
|
@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = {
|
|||
const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ Body:\n\n`;
|
|||
const DraftIssueCommand: SlashCommand = {
|
||||
name: "issue",
|
||||
description: "Draft a GitHub issue",
|
||||
run: async function* ({ input, llm, history, params }) {
|
||||
run: async function* ({ input, llm, history, params, abortController }) {
|
||||
if (params?.repositoryUrl === undefined) {
|
||||
yield "This command requires a repository URL to be set in the config file.";
|
||||
return;
|
||||
|
|
@ -46,7 +46,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
)) {
|
||||
body += chunk.content;
|
||||
yield renderChatMessage(chunk);
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export function constructMcpSlashCommand(
|
|||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
context.abortController.signal,
|
||||
context.completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ const MAX_EXPLORE_DEPTH = 2;
|
|||
const OnboardSlashCommand: SlashCommand = {
|
||||
name: "onboard",
|
||||
description: "Familiarize yourself with the codebase",
|
||||
run: async function* ({ llm, ide }) {
|
||||
run: async function* ({ llm, ide, abortController }) {
|
||||
const [workspaceDir] = await ide.getWorkspaceDirs();
|
||||
|
||||
const context = await gatherProjectContext(workspaceDir, ide);
|
||||
|
|
@ -49,7 +49,7 @@ const OnboardSlashCommand: SlashCommand = {
|
|||
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,14 +38,14 @@ function getLastUserHistory(history: ChatMessage[]): string {
|
|||
const ReviewMessageCommand: SlashCommand = {
|
||||
name: "review",
|
||||
description: "Review code and give feedback",
|
||||
run: async function* ({ llm, history }) {
|
||||
run: async function* ({ llm, history, abortController }) {
|
||||
const reviewText = getLastUserHistory(history).replace("\\review", "");
|
||||
|
||||
const content = `${prompt} \r\n ${reviewText}`;
|
||||
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: content }],
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { ctxItemToRifWithContents } from "./util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ContextItemWithId, RangeInFileWithContents } from "../index";
|
||||
import { ctxItemToRifWithContents } from "./util";
|
||||
|
||||
describe("ctxItemToRifWithContents", () => {
|
||||
it("should parse start and end lines from the item name when format is valid", () => {
|
||||
|
|
@ -19,6 +19,7 @@ export const sharedConfigSchema = z
|
|||
readResponseTTS: z.boolean(),
|
||||
promptPath: z.string(),
|
||||
useCurrentFileAsContext: z.boolean(),
|
||||
logEditingData: z.boolean(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
showSessionTabs: z.boolean(),
|
||||
|
|
@ -171,6 +172,9 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.useCurrentFileAsContext =
|
||||
sharedConfig.useCurrentFileAsContext;
|
||||
}
|
||||
if (sharedConfig.logEditingData !== undefined) {
|
||||
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -719,7 +719,7 @@ declare global {
|
|||
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
getSearchResults(query: string, maxResults?: number): Promise<string>;
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
|
|
|
|||
|
|
@ -56,7 +56,9 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
private insertInputToUriTemplate(uri: string, query: string): string {
|
||||
const TEMPLATE_VAR = "query";
|
||||
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
|
||||
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
|
||||
// Sending an empty string will result in an error, so we instead send "null"
|
||||
const queryOrNull = query.trim() === "" ? "null" : query;
|
||||
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull));
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
import { formatGrepSearchResults } from "../../util/grepSearch.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
const DEFAULT_MAX_SEARCH_CONTEXT_RESULTS = 200;
|
||||
class SearchContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "search",
|
||||
|
|
@ -19,8 +20,12 @@ class SearchContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const results = await extras.ide.getSearchResults(query);
|
||||
const formatted = formatGrepSearchResults(results);
|
||||
const results = await extras.ide.getSearchResults(
|
||||
query,
|
||||
this.options?.maxResults ?? DEFAULT_MAX_SEARCH_CONTEXT_RESULTS,
|
||||
);
|
||||
// Note, search context provider will not truncate result chars, but will limit number of results
|
||||
const { formatted } = formatGrepSearchResults(results);
|
||||
return [
|
||||
{
|
||||
description: "Search results",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Chunk } from "../../../";
|
||||
import { Telemetry } from "../../../util/posthog";
|
||||
import { findUriInDirs } from "../../../util/uri";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
|
@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
try {
|
||||
ftsChunks = await this.retrieveFts(args, ftsNFinal);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving FTS chunks:", error);
|
||||
await Telemetry.captureError("no_reranker_fts_retrieval", error);
|
||||
// console.error("Error retrieving FTS chunks:", error);
|
||||
}
|
||||
|
||||
let embeddingsChunks: Chunk[] = [];
|
||||
|
|
@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
? await this.retrieveEmbeddings(input, embeddingsNFinal)
|
||||
: [];
|
||||
} catch (error) {
|
||||
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
|
||||
console.error("Error retrieving embeddings:", error);
|
||||
}
|
||||
|
||||
|
|
@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
|
||||
} catch (error) {
|
||||
await Telemetry.captureError(
|
||||
"no_reranker_recently_edited_retrieval",
|
||||
error,
|
||||
);
|
||||
console.error("Error retrieving recently edited files:", error);
|
||||
}
|
||||
|
||||
|
|
@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
filterDirectory,
|
||||
);
|
||||
} catch (error) {
|
||||
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
|
||||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
|
||||
import { Telemetry } from "../../../util/posthog";
|
||||
import { findUriInDirs } from "../../../util/uri";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
|
@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
try {
|
||||
ftsChunks = await this.retrieveFts(args, nRetrieve);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving FTS chunks:", error);
|
||||
await Telemetry.captureError("reranker_fts_retrieval", error);
|
||||
// console.error("Error retrieving FTS chunks:", error);
|
||||
}
|
||||
|
||||
let embeddingsChunks: Chunk[] = [];
|
||||
|
|
@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
? await this.retrieveEmbeddings(input, nRetrieve)
|
||||
: [];
|
||||
} catch (error) {
|
||||
await Telemetry.captureError("reranker_embeddings_retrieval", error);
|
||||
console.error("Error retrieving embeddings chunks:", error);
|
||||
}
|
||||
|
||||
|
|
@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
|
||||
} catch (error) {
|
||||
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
|
||||
console.error("Error retrieving recently edited files chunks:", error);
|
||||
}
|
||||
|
||||
|
|
@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
filterDirectory,
|
||||
);
|
||||
} catch (error) {
|
||||
await Telemetry.captureError("reranker_repo_map_retrieval", error);
|
||||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import * as crypto from "crypto";
|
||||
import { expect, test } from "vitest";
|
||||
import { LicenseKeyData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
163
core/core.ts
163
core/core.ts
|
|
@ -42,13 +42,15 @@ import {
|
|||
ContextItemWithId,
|
||||
IdeSettings,
|
||||
ModelDescription,
|
||||
Position,
|
||||
RangeInFile,
|
||||
ToolCall,
|
||||
type ContextItem,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
} from ".";
|
||||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
|
|
@ -59,17 +61,18 @@ import {
|
|||
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
|
||||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
import { ApplyAbortManager } from "./edit/applyAbortManager";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import { NextEditProvider } from "./nextEdit/NextEditProvider";
|
||||
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
|
||||
import { processNextEditData } from "./nextEdit/context/processNextEditData.js";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { OnboardingModes } from "./protocol/core";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
import { StreamAbortManager } from "./util/abortManager";
|
||||
import { getUriPathBasename } from "./util/uri";
|
||||
|
||||
const hasRulesFiles = (uris: string[]): boolean => {
|
||||
|
|
@ -149,6 +152,18 @@ export class Core {
|
|||
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
|
||||
void this.configHandler.reloadConfig();
|
||||
|
||||
// Refresh @mention dropdown submenu items for MCP providers
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
|
||||
(mcpId) => `mcp-${mcpId}`,
|
||||
);
|
||||
|
||||
if (mcpProviderNames.length > 0) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: mcpProviderNames,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
this.codeBaseIndexer = new CodebaseIndexer(
|
||||
|
|
@ -514,6 +529,11 @@ export class Core {
|
|||
throw new Error("No model selected");
|
||||
}
|
||||
|
||||
const abortManager = ApplyAbortManager.getInstance();
|
||||
const abortController = abortManager.get(
|
||||
data.fileUri ?? "current-file-stream",
|
||||
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
|
||||
|
||||
return streamDiffLines({
|
||||
highlighted: data.highlighted,
|
||||
prefix: data.prefix,
|
||||
|
|
@ -527,13 +547,13 @@ export class Core {
|
|||
language: data.language,
|
||||
onlyOneInsertion: false,
|
||||
overridePrompt: undefined,
|
||||
abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
|
||||
abortController,
|
||||
});
|
||||
});
|
||||
|
||||
on("cancelApply", async (msg) => {
|
||||
const abortManager = StreamAbortManager.getInstance();
|
||||
abortManager.clear();
|
||||
const abortManager = ApplyAbortManager.getInstance();
|
||||
abortManager.clear(); // for now abort all streams
|
||||
});
|
||||
|
||||
on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
|
||||
|
|
@ -693,20 +713,54 @@ export class Core {
|
|||
maxEdits: 250,
|
||||
maxDuration: 100.0,
|
||||
contextSize: 5,
|
||||
maxEditSize: 1000,
|
||||
};
|
||||
|
||||
if (!global._editAggregator) {
|
||||
global._editAggregator = new EditAggregator(
|
||||
EDIT_AGGREGATION_OPTIONS,
|
||||
(diff: string) => {
|
||||
// console.log(diff, "\n");
|
||||
// TODO handle devData logging here
|
||||
NextEditProvider.getInstance().addDiffToContext(diff);
|
||||
(
|
||||
beforeAfterdiff: BeforeAfterDiff,
|
||||
cursorPosBeforeEdit: Position,
|
||||
cursorPosAfterPrevEdit: Position,
|
||||
) => {
|
||||
// Get the current context data from the most recent message
|
||||
const currentData = (global._editAggregator as any)
|
||||
.latestContextData || {
|
||||
configHandler: data.configHandler,
|
||||
getDefsFromLspFunction: data.getDefsFromLspFunction,
|
||||
recentlyEditedRanges: [],
|
||||
recentlyVisitedRanges: [],
|
||||
};
|
||||
|
||||
void processNextEditData(
|
||||
beforeAfterdiff.filePath,
|
||||
beforeAfterdiff.beforeContent,
|
||||
beforeAfterdiff.afterContent,
|
||||
cursorPosBeforeEdit,
|
||||
cursorPosAfterPrevEdit,
|
||||
this.ide,
|
||||
currentData.configHandler,
|
||||
currentData.getDefsFromLspFunction,
|
||||
currentData.recentlyEditedRanges,
|
||||
currentData.recentlyVisitedRanges,
|
||||
currentData.workspaceDir,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const workspaceDir =
|
||||
data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
|
||||
|
||||
// Store the latest context data on the aggregator
|
||||
(global._editAggregator as any).latestContextData = {
|
||||
configHandler: data.configHandler,
|
||||
getDefsFromLspFunction: data.getDefsFromLspFunction,
|
||||
recentlyEditedRanges: data.recentlyEditedRanges,
|
||||
recentlyVisitedRanges: data.recentlyVisitedRanges,
|
||||
workspaceDir: workspaceDir,
|
||||
};
|
||||
|
||||
// queueMicrotask prevents blocking the UI thread during typing
|
||||
queueMicrotask(() => {
|
||||
void global._editAggregator.processEdits(data.actions);
|
||||
|
|
@ -767,44 +821,9 @@ export class Core {
|
|||
return { url };
|
||||
});
|
||||
|
||||
on("tools/call", async ({ data: { toolCall } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
if (!config.selectedModelByRole.chat) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Define a callback for streaming output updates
|
||||
const onPartialOutput = (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => {
|
||||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
return await callTool(tool, toolCall, {
|
||||
config,
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
codeBaseIndexer: this.codeBaseIndexer,
|
||||
});
|
||||
});
|
||||
on("tools/call", async ({ data: { toolCall } }) =>
|
||||
this.handleToolCall(toolCall),
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
|
|
@ -829,6 +848,45 @@ export class Core {
|
|||
});
|
||||
}
|
||||
|
||||
private async handleToolCall(toolCall: ToolCall) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
if (!config.selectedModelByRole.chat) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Define a callback for streaming output updates
|
||||
const onPartialOutput = (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => {
|
||||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
return await callTool(tool, toolCall, {
|
||||
config,
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
codeBaseIndexer: this.codeBaseIndexer,
|
||||
});
|
||||
}
|
||||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
@ -916,7 +974,12 @@ export class Core {
|
|||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
|
||||
uri.endsWith(RULES_MARKDOWN_FILENAME)
|
||||
uri.endsWith(RULES_MARKDOWN_FILENAME) ||
|
||||
BLOCK_TYPES.some(
|
||||
(blockType) =>
|
||||
uri.includes(`.continue/${blockType}`) ||
|
||||
uri.includes(`.continue\\${blockType}`),
|
||||
)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
|
|
|
|||
|
|
@ -1,13 +1,22 @@
|
|||
import { DevDataLogEvent } from "@continuedev/config-yaml";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import {
|
||||
afterAll,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { IdeInfo, IdeSettings } from "..";
|
||||
import { Core } from "../core";
|
||||
import { getDevDataFilePath } from "../util/paths";
|
||||
import { DataLogger } from "./log";
|
||||
|
||||
// Only mock fetch, not fs
|
||||
jest.mock("@continuedev/fetch");
|
||||
vi.mock("@continuedev/fetch");
|
||||
|
||||
const TEST_EVENT: DevDataLogEvent = {
|
||||
name: "tokensGenerated",
|
||||
|
|
@ -54,7 +63,7 @@ describe("DataLogger", () => {
|
|||
|
||||
beforeEach(() => {
|
||||
// Reset mocks
|
||||
jest.clearAllMocks();
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Remove test file if it exists
|
||||
if (fs.existsSync(testFilePath)) {
|
||||
|
|
@ -67,7 +76,7 @@ describe("DataLogger", () => {
|
|||
// Mock core and required promises
|
||||
dataLogger.core = {
|
||||
configHandler: {
|
||||
loadConfig: jest.fn().mockResolvedValue({
|
||||
loadConfig: vi.fn().mockResolvedValue({
|
||||
config: {
|
||||
data: [],
|
||||
},
|
||||
|
|
@ -78,7 +87,7 @@ describe("DataLogger", () => {
|
|||
},
|
||||
},
|
||||
controlPlaneClient: {
|
||||
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
|
||||
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
|
||||
},
|
||||
},
|
||||
} as unknown as Core;
|
||||
|
|
@ -184,7 +193,6 @@ describe("DataLogger", () => {
|
|||
|
||||
// Read file contents and verify
|
||||
const fileContent = fs.readFileSync(filepath, "utf8");
|
||||
console.log("debug1 filecontent", fileContent);
|
||||
expect(fileContent).toContain('"eventName":"chatInteraction"');
|
||||
expect(fileContent).toContain('"prompt":"Hello, world!"');
|
||||
expect(fileContent).toContain('"completion":"Hello, world!"');
|
||||
|
|
@ -195,10 +203,10 @@ describe("DataLogger", () => {
|
|||
describe("logDevData", () => {
|
||||
it("should log data locally and to configured destinations", async () => {
|
||||
// Spy on logLocalData and logToOneDestination
|
||||
const logLocalDataSpy = jest
|
||||
const logLocalDataSpy = vi
|
||||
.spyOn(dataLogger, "logLocalData")
|
||||
.mockResolvedValue();
|
||||
const logToOneDestinationSpy = jest
|
||||
const logToOneDestinationSpy = vi
|
||||
.spyOn(dataLogger, "logToOneDestination")
|
||||
.mockResolvedValue();
|
||||
|
||||
|
|
@ -212,7 +220,7 @@ describe("DataLogger", () => {
|
|||
},
|
||||
};
|
||||
|
||||
dataLogger.core!.configHandler.loadConfig = jest
|
||||
dataLogger.core!.configHandler.loadConfig = vi
|
||||
.fn()
|
||||
.mockResolvedValue(mockConfig);
|
||||
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { dedent } from "../util";
|
||||
|
||||
import { myersDiff } from "./myers";
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
// @ts-ignore no typings available
|
||||
import { changed, diff as myersDiff } from "myers-diff";
|
||||
import { streamDiff } from "../diff/streamDiff.js";
|
||||
|
|
@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) {
|
|||
}
|
||||
|
||||
async function expectDiff(file: string) {
|
||||
const testFilePath = path.join(
|
||||
__dirname,
|
||||
"diff",
|
||||
"test-examples",
|
||||
file + ".diff",
|
||||
);
|
||||
const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
|
||||
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
|
||||
const [oldText, newText, expectedDiff] = testFileContents
|
||||
.split("\n---\n")
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
// Generated by continue
|
||||
|
||||
import { matchLine, streamLines, generateLines } from "./util";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ChatMessage } from "../index";
|
||||
import { jest } from "@jest/globals";
|
||||
import { generateLines, matchLine, streamLines } from "./util";
|
||||
|
||||
describe.skip("matchLine", () => {
|
||||
it("should match empty lines if the first old line is also empty", () => {
|
||||
|
|
@ -146,7 +146,7 @@ describe("streamLines", () => {
|
|||
content: "line4",
|
||||
};
|
||||
|
||||
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
|
||||
// const spy = vi.spyOn(messageContentModule, "renderChatMessage");
|
||||
|
||||
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
|
||||
yield messageChunk1;
|
||||
|
|
@ -164,7 +164,7 @@ describe("streamLines", () => {
|
|||
});
|
||||
|
||||
it("should log lines if log parameter is true", async () => {
|
||||
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
async function* streamCompletion(): AsyncGenerator<string> {
|
||||
yield "line1\nline2\n";
|
||||
|
|
@ -1,16 +1,16 @@
|
|||
export class StreamAbortManager {
|
||||
private static instance: StreamAbortManager;
|
||||
export class ApplyAbortManager {
|
||||
private static instance: ApplyAbortManager;
|
||||
private controllers: Map<string, AbortController>;
|
||||
|
||||
private constructor() {
|
||||
this.controllers = new Map();
|
||||
}
|
||||
|
||||
public static getInstance(): StreamAbortManager {
|
||||
if (!StreamAbortManager.instance) {
|
||||
StreamAbortManager.instance = new StreamAbortManager();
|
||||
public static getInstance(): ApplyAbortManager {
|
||||
if (!ApplyAbortManager.instance) {
|
||||
ApplyAbortManager.instance = new ApplyAbortManager();
|
||||
}
|
||||
return StreamAbortManager.instance;
|
||||
return ApplyAbortManager.instance;
|
||||
}
|
||||
|
||||
public get(id: string): AbortController {
|
||||
|
|
@ -16,6 +16,7 @@ export async function applyCodeBlock(
|
|||
newLazyFile: string,
|
||||
filename: string,
|
||||
llm: ILLM,
|
||||
abortController: AbortController,
|
||||
): Promise<{
|
||||
isInstantApply: boolean;
|
||||
diffLinesGenerator: AsyncGenerator<DiffLine>;
|
||||
|
|
@ -51,6 +52,12 @@ export async function applyCodeBlock(
|
|||
|
||||
return {
|
||||
isInstantApply: false,
|
||||
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
|
||||
diffLinesGenerator: streamLazyApply(
|
||||
oldFile,
|
||||
filename,
|
||||
newLazyFile,
|
||||
llm,
|
||||
abortController,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,6 +59,7 @@ export async function* getReplacementWithLlm(
|
|||
linesBefore: string[],
|
||||
linesAfter: string[],
|
||||
llm: ILLM,
|
||||
abortController: AbortController,
|
||||
): AsyncGenerator<string> {
|
||||
const userPrompt = dedent`
|
||||
ORIGINAL CODE:
|
||||
|
|
@ -88,7 +89,7 @@ export async function* getReplacementWithLlm(
|
|||
{ role: "user", content: userPrompt },
|
||||
{ role: "assistant", content: assistantPrompt },
|
||||
],
|
||||
new AbortController().signal,
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ export async function* streamLazyApply(
|
|||
filename: string,
|
||||
newCode: string,
|
||||
llm: ILLM,
|
||||
abortController: AbortController,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
|
||||
if (!promptFactory) {
|
||||
|
|
@ -23,10 +24,7 @@ export async function* streamLazyApply(
|
|||
}
|
||||
|
||||
const promptMessages = promptFactory(oldCode, filename, newCode);
|
||||
const lazyCompletion = llm.streamChat(
|
||||
promptMessages,
|
||||
new AbortController().signal,
|
||||
);
|
||||
const lazyCompletion = llm.streamChat(promptMessages, abortController.signal);
|
||||
|
||||
// Do find and replace over the lazy edit response
|
||||
async function* replacementFunction(
|
||||
|
|
@ -39,6 +37,7 @@ export async function* streamLazyApply(
|
|||
linesBefore,
|
||||
linesAfter,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
yield line;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import { streamDiff } from "../diff/streamDiff";
|
|||
import { streamLines } from "../diff/util";
|
||||
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
|
||||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { StreamAbortManager } from "../util/abortManager";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import { recursiveStream } from "./recursiveStream";
|
||||
|
|
@ -64,7 +63,7 @@ export async function* streamDiffLines({
|
|||
highlighted,
|
||||
suffix,
|
||||
llm,
|
||||
abortControllerId,
|
||||
abortController,
|
||||
input,
|
||||
language,
|
||||
onlyOneInsertion,
|
||||
|
|
@ -75,15 +74,13 @@ export async function* streamDiffLines({
|
|||
highlighted: string;
|
||||
suffix: string;
|
||||
llm: ILLM;
|
||||
abortControllerId: string;
|
||||
abortController: AbortController;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
onlyOneInsertion: boolean;
|
||||
overridePrompt: ChatMessage[] | undefined;
|
||||
rulesToInclude: RuleWithSource[] | undefined;
|
||||
}): AsyncGenerator<DiffLine> {
|
||||
const abortManager = StreamAbortManager.getInstance();
|
||||
const abortController = abortManager.get(abortControllerId);
|
||||
void Telemetry.capture(
|
||||
"inlineEdit",
|
||||
{
|
||||
|
|
|
|||
25
core/index.d.ts
vendored
25
core/index.d.ts
vendored
|
|
@ -783,9 +783,9 @@ export interface IDE {
|
|||
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
getSearchResults(query: string, maxResults?: number): Promise<string>;
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]>;
|
||||
getFileResults(pattern: string, maxResults?: number): Promise<string[]>;
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
|
|
@ -835,6 +835,7 @@ export interface ContinueSDK {
|
|||
config: ContinueConfig;
|
||||
fetch: FetchFunction;
|
||||
completionOptions?: LLMFullCompletionOptions;
|
||||
abortController: AbortController;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -1227,6 +1228,7 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
logEditingData?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMenuConfig {
|
||||
|
|
@ -1282,7 +1284,7 @@ export interface HighlightedCodePayload {
|
|||
}
|
||||
|
||||
export interface AcceptOrRejectDiffPayload {
|
||||
filepath: string;
|
||||
filepath?: string;
|
||||
streamId?: string;
|
||||
}
|
||||
|
||||
|
|
@ -1299,14 +1301,14 @@ export interface RangeInFileWithContents {
|
|||
contents: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContentsAndEdit {
|
||||
export interface RangeInFileWithNextEditInfo {
|
||||
filepath: string;
|
||||
range: {
|
||||
start: { line: number; character: number };
|
||||
end: { line: number; character: number };
|
||||
};
|
||||
range: Range;
|
||||
fileContents: string;
|
||||
editText: string;
|
||||
afterCursorPos: Position;
|
||||
beforeCursorPos: Position;
|
||||
workspaceDir: string;
|
||||
}
|
||||
|
||||
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
|
||||
|
|
@ -1369,6 +1371,11 @@ export interface ExperimentalConfig {
|
|||
* If enabled, will add the current file as context.
|
||||
*/
|
||||
useCurrentFileAsContext?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will save data on the user's editing processes
|
||||
*/
|
||||
logEditingData?: boolean;
|
||||
}
|
||||
|
||||
export interface AnalyticsConfig {
|
||||
|
|
@ -1588,12 +1595,12 @@ export interface RuleWithSource {
|
|||
slug?: string;
|
||||
source: RuleSource;
|
||||
globs?: string | string[];
|
||||
regex?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
provider?: string;
|
||||
|
|
|
|||
|
|
@ -63,13 +63,12 @@ export async function* chunkDocument({
|
|||
resolve({
|
||||
...chunkWithoutId,
|
||||
digest,
|
||||
index,
|
||||
index: index++,
|
||||
filepath,
|
||||
});
|
||||
})();
|
||||
}),
|
||||
);
|
||||
index++;
|
||||
}
|
||||
for await (const chunk of chunkPromises) {
|
||||
if (!chunk) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8192;
|
||||
const DEFAULT_CONTEXT_LENGTH = 32_768;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { findLast } from "../util/findLast";
|
|||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { isUserOrToolMsg } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./rules/types";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
|
@ -108,6 +109,7 @@ export function constructMessages(
|
|||
history: ChatHistoryItem[],
|
||||
baseChatOrAgentSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
rulePolicies?: RulePolicies,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
|
|
@ -164,6 +166,7 @@ export function constructMessages(
|
|||
rules,
|
||||
userMessage: lastUserMsg,
|
||||
contextItems: lastUserContextItems,
|
||||
rulePolicies,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { allModelProviders } from "@continuedev/llm-info";
|
||||
import { LlmInfo } from "@continuedev/llm-info/dist/types";
|
||||
import { BaseLLM } from ".";
|
||||
import { DEFAULT_CONTEXT_LENGTH } from "./constants";
|
||||
import { LLMClasses } from "./llms";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
|
|
@ -140,4 +144,31 @@ describe("BaseLLM", () => {
|
|||
describe("*streamChat", () => {
|
||||
// TODO: Implement tests for *streamChat method
|
||||
});
|
||||
|
||||
describe("default context length", () => {
|
||||
allModelProviders.map((modelProvider) => {
|
||||
const LLMClass = LLMClasses.find(
|
||||
(llm) => llm.providerName === modelProvider.id,
|
||||
);
|
||||
if (!LLMClass) {
|
||||
throw new Error(`did not find LLM provider for ${modelProvider.id}`);
|
||||
}
|
||||
const testContextLength = (llmInfo: LlmInfo) => () => {
|
||||
const llm = new LLMClass({ model: llmInfo.model });
|
||||
if (llmInfo.contextLength) {
|
||||
expect(llm.contextLength).toEqual(llmInfo.contextLength);
|
||||
} else {
|
||||
expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH);
|
||||
}
|
||||
};
|
||||
describe(`${modelProvider.id}`, () => {
|
||||
modelProvider.models.forEach((llmInfo) => {
|
||||
test(
|
||||
`should have correct context length for ${llmInfo.model}`,
|
||||
testContextLength(llmInfo),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ class Anthropic extends BaseLLM {
|
|||
static providerName = "anthropic";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
contextLength: 200_000,
|
||||
completionOptions: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
maxTokens: 8192,
|
||||
|
|
|
|||
|
|
@ -48,7 +48,6 @@ class Bedrock extends BaseLLM {
|
|||
static defaultOptions: Partial<LLMOptions> = {
|
||||
region: "us-east-1",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
contextLength: 200_000,
|
||||
profile: "bedrock",
|
||||
};
|
||||
|
||||
|
|
|
|||
186
core/llm/rules/alwaysApply.vitest.ts
Normal file
186
core/llm/rules/alwaysApply.vitest.ts
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import { getApplicableRules } from "./getSystemMessageWithRules";
|
||||
|
||||
describe("alwaysApply Behavior", () => {
|
||||
// Common test fixtures
|
||||
const testFile = "src/app.ts";
|
||||
const matchingFile = "src/components/Button.tsx";
|
||||
const nonMatchingFile = "src/utils/helper.js"; // Not matching *.tsx glob
|
||||
|
||||
// File context items
|
||||
const matchingFileContext: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "match1" } as ContextItemId,
|
||||
uri: { type: "file", value: matchingFile },
|
||||
content: "export const Button = () => {...}",
|
||||
name: "Button.tsx",
|
||||
description: "Component file",
|
||||
};
|
||||
|
||||
const nonMatchingFileContext: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "nonmatch1" } as ContextItemId,
|
||||
uri: { type: "file", value: nonMatchingFile },
|
||||
content: "export const helper = () => {...}",
|
||||
name: "helper.js",
|
||||
description: "Helper file",
|
||||
};
|
||||
|
||||
// Message with no file references
|
||||
const messageWithoutFile: UserChatMessage = {
|
||||
role: "user",
|
||||
content: "Can you help me understand how this works?",
|
||||
};
|
||||
|
||||
it("alwaysApply: true - Always include the rule, regardless of file context", () => {
|
||||
// Rule with alwaysApply: true
|
||||
const alwaysApplyRule: RuleWithSource = {
|
||||
name: "Always Apply Rule",
|
||||
rule: "This rule should always be applied",
|
||||
alwaysApply: true,
|
||||
globs: "**/*.tsx", // Should be ignored since alwaysApply is true
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Test with no file context
|
||||
let applicableRules = getApplicableRules(
|
||||
messageWithoutFile,
|
||||
[alwaysApplyRule],
|
||||
[],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Always Apply Rule");
|
||||
|
||||
// Test with matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[alwaysApplyRule],
|
||||
[matchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Always Apply Rule");
|
||||
|
||||
// Test with non-matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[alwaysApplyRule],
|
||||
[nonMatchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Always Apply Rule");
|
||||
});
|
||||
|
||||
it("alwaysApply: false - Only include if globs exist AND match file context", () => {
|
||||
// Rule with alwaysApply: false and globs
|
||||
const conditionalRule: RuleWithSource = {
|
||||
name: "Conditional Rule",
|
||||
rule: "Apply only to matching files",
|
||||
alwaysApply: false,
|
||||
globs: "**/*.tsx",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Rule with alwaysApply: false and no globs
|
||||
const neverApplyRule: RuleWithSource = {
|
||||
name: "Never Apply Rule",
|
||||
rule: "This rule should never apply",
|
||||
alwaysApply: false,
|
||||
// No globs
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Test with no file context
|
||||
let applicableRules = getApplicableRules(
|
||||
messageWithoutFile,
|
||||
[conditionalRule, neverApplyRule],
|
||||
[],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(0); // No rules should apply
|
||||
|
||||
// Test with matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[conditionalRule, neverApplyRule],
|
||||
[matchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Conditional Rule");
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"Never Apply Rule",
|
||||
);
|
||||
|
||||
// Test with non-matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[conditionalRule, neverApplyRule],
|
||||
[nonMatchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(0); // No rules should apply
|
||||
});
|
||||
|
||||
it("alwaysApply: undefined - Default behavior: include if no globs exist OR globs exist and match", () => {
|
||||
// Rule with undefined alwaysApply and no globs (should behave like a global rule)
|
||||
const defaultNoGlobsRule: RuleWithSource = {
|
||||
name: "Default No Globs Rule",
|
||||
rule: "Default rule with no globs",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
// No alwaysApply, no globs
|
||||
};
|
||||
|
||||
// Rule with undefined alwaysApply and globs
|
||||
const defaultWithGlobsRule: RuleWithSource = {
|
||||
name: "Default With Globs Rule",
|
||||
rule: "Default rule with globs",
|
||||
globs: "**/*.tsx",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
// No alwaysApply, with globs
|
||||
};
|
||||
|
||||
// Test with no file context
|
||||
let applicableRules = getApplicableRules(
|
||||
messageWithoutFile,
|
||||
[defaultNoGlobsRule, defaultWithGlobsRule],
|
||||
[],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Default No Globs Rule");
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"Default With Globs Rule",
|
||||
);
|
||||
|
||||
// Test with matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[defaultNoGlobsRule, defaultWithGlobsRule],
|
||||
[matchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(2);
|
||||
expect(applicableRules.map((r) => r.name)).toContain(
|
||||
"Default No Globs Rule",
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).toContain(
|
||||
"Default With Globs Rule",
|
||||
);
|
||||
|
||||
// Test with non-matching file
|
||||
applicableRules = getApplicableRules(
|
||||
undefined,
|
||||
[defaultNoGlobsRule, defaultWithGlobsRule],
|
||||
[nonMatchingFileContext],
|
||||
);
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Default No Globs Rule");
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"Default With Globs Rule",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -6,6 +6,7 @@ import {
|
|||
UserChatMessage,
|
||||
} from "../..";
|
||||
import { getApplicableRules } from "./getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
describe("Rule application with alwaysApply", () => {
|
||||
// Create an always-apply rule
|
||||
|
|
@ -136,4 +137,38 @@ describe("Rule application with alwaysApply", () => {
|
|||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
|
||||
});
|
||||
|
||||
it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => {
|
||||
// Rule with alwaysApply: true
|
||||
const globalRule: RuleWithSource = {
|
||||
name: "Global Rule",
|
||||
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/some/path.md",
|
||||
};
|
||||
|
||||
// Message with no code blocks or file references
|
||||
const simpleMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: "Can you help me with something?",
|
||||
};
|
||||
|
||||
// Create a rule policy that blocks the rule
|
||||
const rulePolicies: RulePolicies = {
|
||||
"Global Rule": "off",
|
||||
};
|
||||
|
||||
// The rule should NOT be applied due to the "off" policy,
|
||||
// even though it has alwaysApply: true and there are no file paths
|
||||
const applicableRules = getApplicableRules(
|
||||
simpleMessage,
|
||||
[globalRule],
|
||||
[],
|
||||
rulePolicies,
|
||||
);
|
||||
|
||||
expect(applicableRules).toHaveLength(0);
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@ import {
|
|||
} from "../..";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
|
||||
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
/**
|
||||
* Checks if a path matches any of the provided globs
|
||||
|
|
@ -51,6 +53,47 @@ const matchesGlobs = (
|
|||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if file content matches any of the provided regex regex
|
||||
*
|
||||
* @param fileContent - The content of the file to check
|
||||
* @param regex - A single regex pattern string or array of regex pattern strings
|
||||
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
|
||||
*/
|
||||
const contentMatchesRegex = (
|
||||
fileContent: string,
|
||||
regex: string | string[],
|
||||
): boolean => {
|
||||
// Handle single string pattern
|
||||
if (typeof regex === "string") {
|
||||
try {
|
||||
const expression = new RegExp(regex);
|
||||
return expression.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${regex}`, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle array of regex
|
||||
if (Array.isArray(regex)) {
|
||||
if (regex.length === 0) return true;
|
||||
|
||||
// Content must match at least one pattern
|
||||
return regex.some((pattern) => {
|
||||
try {
|
||||
const regex = new RegExp(pattern);
|
||||
return regex.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${pattern}`, e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a file path is within a specific directory or its subdirectories
|
||||
*
|
||||
|
|
@ -102,31 +145,81 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Root-level rules with no globs are implicitly global
|
||||
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
|
||||
// Root-level rules with no globs or regex are implicitly global
|
||||
if (
|
||||
isRootLevelRule(rule) &&
|
||||
!rule.globs &&
|
||||
!rule.regex &&
|
||||
rule.alwaysApply !== false
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const checkGlobsAndRegex = ({
|
||||
rule,
|
||||
filePaths,
|
||||
fileContents,
|
||||
}: {
|
||||
rule: RuleWithSource;
|
||||
filePaths: string[];
|
||||
fileContents: Record<string, string>;
|
||||
}) => {
|
||||
const matchingFiles = rule.globs
|
||||
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
|
||||
: filePaths;
|
||||
|
||||
// If no files match the globs, don't apply the rule
|
||||
if (matchingFiles.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now check for pattern matches in file contents if regex are specified
|
||||
if (rule.regex) {
|
||||
// Check if any of the matching files also match the content regex
|
||||
return matchingFiles.some((filePath) => {
|
||||
const content = fileContents[filePath];
|
||||
// If we don't have the content, we can't check regex
|
||||
if (!content) return false;
|
||||
return contentMatchesRegex(content, rule.regex!);
|
||||
});
|
||||
}
|
||||
|
||||
// If we have no regex or if we couldn't check regex (no content),
|
||||
// just go with the glob matches
|
||||
return matchingFiles.length > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a rule should be applied based on its alwaysApply property and file path matching
|
||||
* Determines if a rule should be applied based on its properties and file matching
|
||||
*
|
||||
* @param rule - The rule to check
|
||||
* @param filePaths - Array of file paths to check against the rule's globs
|
||||
* @param fileContents - Map of file paths to their contents for pattern matching
|
||||
* @param rulePolicies - Optional policies that can override normal rule behavior
|
||||
* @returns true if the rule should be applied, false otherwise
|
||||
*/
|
||||
export const shouldApplyRule = (
|
||||
rule: RuleWithSource,
|
||||
filePaths: string[],
|
||||
rulePolicies: RulePolicies = {},
|
||||
fileContents: Record<string, string> = {},
|
||||
): boolean => {
|
||||
const policy = rulePolicies[rule.name || ""];
|
||||
|
||||
// Never apply if policy is "off"
|
||||
if (policy === "off") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If it's a global rule, always apply it regardless of file paths
|
||||
if (isGlobalRule(rule)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If there are no file paths to check:
|
||||
// If there are no file paths to check and we've made it here:
|
||||
// - We've already handled global rules above
|
||||
// - Don't apply other rules since we have no files to match against
|
||||
if (filePaths.length === 0) {
|
||||
|
|
@ -148,40 +241,27 @@ export const shouldApplyRule = (
|
|||
isFileInDirectory(filePath, ruleDirPath),
|
||||
);
|
||||
|
||||
// If no files are in this directory, don't apply the rule
|
||||
if (filesInRuleDirectory.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we have globs, check if any files in this directory match them
|
||||
if (rule.globs) {
|
||||
return filesInRuleDirectory.some((filePath) =>
|
||||
matchesGlobs(filePath, rule.globs),
|
||||
);
|
||||
}
|
||||
|
||||
// No globs but files are in this directory, so apply the rule
|
||||
return true;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths: filesInRuleDirectory,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
}
|
||||
|
||||
// For root-level rules:
|
||||
|
||||
// If alwaysApply is explicitly false, only apply if there are globs AND they match
|
||||
if (rule.alwaysApply === false) {
|
||||
if (!rule.globs) {
|
||||
return false;
|
||||
}
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
// If alwaysApply is explicitly false, we need to check globs and/or regex
|
||||
if (
|
||||
rule.alwaysApply === false &&
|
||||
rule.globs === undefined &&
|
||||
rule.regex === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Default behavior for root rules with globs:
|
||||
// - Only apply if they match the globs
|
||||
if (rule.globs) {
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
}
|
||||
|
||||
// This point should not be reached as we've handled all cases above
|
||||
return false;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -196,11 +276,9 @@ export const getApplicableRules = (
|
|||
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
|
||||
rules: RuleWithSource[],
|
||||
contextItems: ContextItemWithId[],
|
||||
rulePolicies: RulePolicies = {},
|
||||
): RuleWithSource[] => {
|
||||
// First, extract any global rules that should always apply
|
||||
const globalRules = rules.filter((rule) => isGlobalRule(rule));
|
||||
|
||||
// Get file paths from message and context for regular rule matching
|
||||
// Get file paths from message and context for rule matching
|
||||
const filePathsFromMessage = userMessage
|
||||
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
|
||||
: [];
|
||||
|
|
@ -213,41 +291,58 @@ export const getApplicableRules = (
|
|||
// Combine file paths from both sources
|
||||
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
|
||||
|
||||
// If we have no file paths, just return the global rules
|
||||
if (allFilePaths.length === 0) {
|
||||
return globalRules;
|
||||
// Create a map of file paths to their contents for pattern matching
|
||||
const fileContents: Record<string, string> = {};
|
||||
|
||||
// Extract contents from context items with file URIs
|
||||
contextItems.forEach((item) => {
|
||||
if (item.uri?.type === "file" && item.uri?.value) {
|
||||
fileContents[item.uri.value] = item.content;
|
||||
}
|
||||
});
|
||||
|
||||
// Extract contents from code blocks in the message for paths that don't have content yet
|
||||
if (userMessage) {
|
||||
const messageContent = renderChatMessage(userMessage);
|
||||
filePathsFromMessage.forEach((path) => {
|
||||
// Only extract content if we don't already have it from context items
|
||||
if (!fileContents[path]) {
|
||||
const blockContent = extractContentFromCodeBlock(messageContent, path);
|
||||
if (blockContent) {
|
||||
fileContents[path] = blockContent;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Get rules that match file paths
|
||||
const matchingRules = rules
|
||||
.filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them
|
||||
.filter((rule) => shouldApplyRule(rule, allFilePaths));
|
||||
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
|
||||
// and path matching in a consistent way
|
||||
const applicableRules = rules.filter((rule) =>
|
||||
shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
|
||||
);
|
||||
|
||||
// Combine global rules with matching rules, ensuring no duplicates
|
||||
return [...globalRules, ...matchingRules];
|
||||
return applicableRules;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a system message string with applicable rules appended
|
||||
*
|
||||
* @param baseSystemMessage - The base system message to start with
|
||||
* @param userMessage - The user message to check for file paths
|
||||
* @param rules - The list of rules to filter
|
||||
* @param contextItems - Context items to check for file paths
|
||||
* @returns System message with applicable rules appended
|
||||
*/
|
||||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules,
|
||||
contextItems,
|
||||
rulePolicies = {},
|
||||
}: {
|
||||
baseSystemMessage?: string;
|
||||
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
contextItems: ContextItemWithId[];
|
||||
rulePolicies?: RulePolicies;
|
||||
}) => {
|
||||
const applicableRules = getApplicableRules(userMessage, rules, contextItems);
|
||||
const applicableRules = getApplicableRules(
|
||||
userMessage,
|
||||
rules,
|
||||
contextItems,
|
||||
rulePolicies,
|
||||
);
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
|
||||
for (const rule of applicableRules) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,15 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { shouldApplyRule } from "./getSystemMessageWithRules";
|
||||
import {
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import {
|
||||
getApplicableRules,
|
||||
shouldApplyRule,
|
||||
} from "./getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
describe("Rule colocation glob matching", () => {
|
||||
// This test file demonstrates the expected behavior after our fix
|
||||
|
|
@ -132,3 +141,339 @@ describe("Rule colocation glob matching", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rule policies", () => {
|
||||
const componentRule: RuleWithSource = {
|
||||
name: "Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
const testFiles = ["src/components/Button.tsx"];
|
||||
const nonMatchingFiles = ["src/utils/helpers.ts"];
|
||||
|
||||
it("should never apply rules with 'off' policy regardless of file paths", () => {
|
||||
const rulePolicies: RulePolicies = {
|
||||
"Components Rule": "off",
|
||||
};
|
||||
|
||||
// Should not apply even to matching files
|
||||
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false);
|
||||
|
||||
// Rule with alwaysApply: true should still be overridden by 'off' policy
|
||||
const alwaysApplyRule: RuleWithSource = {
|
||||
name: "Always Apply Rule",
|
||||
rule: "This rule would normally always apply",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
const offPolicies: RulePolicies = {
|
||||
"Always Apply Rule": "off",
|
||||
};
|
||||
|
||||
expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("should apply 'on' policy rules based on normal matching logic", () => {
|
||||
const rulePolicies: RulePolicies = {
|
||||
"Components Rule": "on",
|
||||
};
|
||||
|
||||
// Should apply to matching files
|
||||
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
|
||||
|
||||
// Should not apply to non-matching files
|
||||
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("should use default behavior when no policy is specified", () => {
|
||||
// Empty policies object should use default behavior
|
||||
const rulePolicies: RulePolicies = {};
|
||||
|
||||
// Should apply to matching files
|
||||
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
|
||||
|
||||
// Should not apply to non-matching files
|
||||
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle policy interaction with global rules", () => {
|
||||
// Root level rule which would normally apply globally
|
||||
const rootRule: RuleWithSource = {
|
||||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Off policy should override even global rules
|
||||
const offPolicies: RulePolicies = {
|
||||
"Root Rule": "off",
|
||||
};
|
||||
|
||||
expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false);
|
||||
|
||||
// On policy should maintain global rule behavior
|
||||
const onPolicies: RulePolicies = {
|
||||
"Root Rule": "on",
|
||||
};
|
||||
|
||||
expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true);
|
||||
});
|
||||
|
||||
it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => {
|
||||
// Create rule with multiple matching criteria
|
||||
const complexRule: RuleWithSource = {
|
||||
name: "Complex Rule",
|
||||
rule: "This rule has complex matching logic",
|
||||
alwaysApply: true,
|
||||
globs: "**/*.ts",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Off policy should win over everything
|
||||
const offPolicies: RulePolicies = {
|
||||
"Complex Rule": "off",
|
||||
};
|
||||
|
||||
// Even with matching files and alwaysApply: true, off policy wins
|
||||
expect(
|
||||
shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Content pattern matching", () => {
|
||||
it("should apply rules when file content matches pattern", () => {
|
||||
// Rule with pattern to match React component files
|
||||
const reactComponentRule: RuleWithSource = {
|
||||
name: "React Component Rule",
|
||||
rule: "Follow React component standards",
|
||||
regex: "export (function|const) \\w+.*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// File that matches the pattern
|
||||
const filePath = "src/components/Button.tsx";
|
||||
const fileContents = {
|
||||
[filePath]:
|
||||
"export function Button() { return <button>Click me</button> }",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
|
||||
).toBe(true);
|
||||
|
||||
// File that doesn't match the pattern
|
||||
const nonMatchingContents = {
|
||||
[filePath]:
|
||||
"import React from 'react'; // Just an import, not a component",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should support multiple regex regex as an array", () => {
|
||||
// Rule with multiple regex
|
||||
const multiPatternRule: RuleWithSource = {
|
||||
name: "Multi-Pattern Rule",
|
||||
rule: "Apply to functions or classes",
|
||||
regex: ["function\\s+\\w+", "class\\s+\\w+"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
|
||||
// Content with function - should match
|
||||
const functionContent = {
|
||||
[filePath]: "function formatDate(date) { return date.toISOString(); }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with class - should match
|
||||
const classContent = {
|
||||
[filePath]:
|
||||
"class DateFormatter { format(date) { return date.toISOString(); } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with neither - should not match
|
||||
const nonMatchingContent = {
|
||||
[filePath]: "const PI = 3.14159;",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should apply rules based on both globs and regex when both are specified", () => {
|
||||
// Rule with both glob and pattern restrictions
|
||||
const typescriptClassRule: RuleWithSource = {
|
||||
name: "TypeScript Class Rule",
|
||||
rule: "Follow class standards in TypeScript",
|
||||
globs: "**/*.ts",
|
||||
regex: "class\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
const tsFilePath = "src/models/User.ts";
|
||||
const jsFilePath = "src/models/Product.js";
|
||||
|
||||
// TypeScript file with class - should match
|
||||
const tsClassContent = {
|
||||
[tsFilePath]: "export class User { constructor(public name: string) {} }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
|
||||
).toBe(true);
|
||||
|
||||
// TypeScript file without class - should not match
|
||||
const tsNonClassContent = {
|
||||
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
|
||||
).toBe(false);
|
||||
|
||||
// JavaScript file with class - should not match due to glob
|
||||
const jsClassContent = {
|
||||
[jsFilePath]:
|
||||
"export class Product { constructor(name) { this.name = name; } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should extract file content from messages for pattern matching", () => {
|
||||
// Rule with pattern
|
||||
const arrowFunctionRule: RuleWithSource = {
|
||||
name: "Arrow Function Rule",
|
||||
rule: "Use arrow functions for better this binding",
|
||||
regex: "const\\s+\\w+\\s*=\\s*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Message with code block containing a matching pattern
|
||||
const messageWithArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
|
||||
};
|
||||
|
||||
// Create context item to match the file in the message
|
||||
const contextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "const format = (date) => {\n return date.toISOString();\n};",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should match the pattern
|
||||
const applicableRules = getApplicableRules(
|
||||
messageWithArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[contextItem],
|
||||
);
|
||||
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Arrow Function Rule");
|
||||
|
||||
// Message with code block that doesn't match the pattern
|
||||
const messageWithoutArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
|
||||
};
|
||||
|
||||
// Context item with non-matching content
|
||||
const nonMatchingContextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "function format(date) {\n return date.toISOString();\n}",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should not match the pattern
|
||||
const nonApplicableRules = getApplicableRules(
|
||||
messageWithoutArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[nonMatchingContextItem],
|
||||
);
|
||||
|
||||
expect(nonApplicableRules).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle invalid regex regex gracefully", () => {
|
||||
// Rule with invalid regex pattern
|
||||
const invalidRegexRule: RuleWithSource = {
|
||||
name: "Invalid Regex Rule",
|
||||
rule: "This rule has an invalid regex pattern",
|
||||
regex: "([unclosed parenthesis",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
const fileContents = {
|
||||
[filePath]: "function helper() { return true; }",
|
||||
};
|
||||
|
||||
// Should not throw an error but gracefully not apply the rule
|
||||
expect(
|
||||
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should respect directory restrictions for pattern rules", () => {
|
||||
// Rule with pattern in a nested directory
|
||||
const nestedPatternRule: RuleWithSource = {
|
||||
name: "Nested Pattern Rule",
|
||||
rule: "Apply only to model files with interfaces",
|
||||
regex: "interface\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
// File in the correct directory with matching content
|
||||
const modelFilePath = "src/models/User.ts";
|
||||
const modelContents = {
|
||||
[modelFilePath]: "export interface User { id: string; name: string; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
|
||||
).toBe(true);
|
||||
|
||||
// File outside the directory with matching content - should not match
|
||||
const utilFilePath = "src/utils/types.ts";
|
||||
const utilContents = {
|
||||
[utilFilePath]:
|
||||
"export interface Config { apiUrl: string; timeout: number; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
2
core/llm/rules/types.ts
Normal file
2
core/llm/rules/types.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export type RulePolicy = "on" | "off";
|
||||
export type RulePolicies = { [ruleName: string]: RulePolicy };
|
||||
|
|
@ -85,6 +85,7 @@ export async function* llmStreamChat(
|
|||
config.requestOptions,
|
||||
),
|
||||
completionOptions,
|
||||
abortController,
|
||||
});
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
|
|
|
|||
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
|
||||
|
||||
describe("extractContentFromCodeBlock", () => {
|
||||
it("should extract content from code block with language and filepath", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with filepath only (no language)", () => {
|
||||
const content = "```test.js\nclass Calculator { }\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with line ranges", () => {
|
||||
const content = "```js test.js (19-25)\nfunction test() {}\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple code blocks and find the right one", () => {
|
||||
const content =
|
||||
"```typescript src/main.ts\nconst x = 1;\n```\n" +
|
||||
"```test.js\nclass Calculator { }\n```\n" +
|
||||
"```js utils.js (19-25)\nfunction test() {}\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle paths with special regex characters", () => {
|
||||
const content =
|
||||
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
|
||||
).toBe("const special = true;");
|
||||
});
|
||||
|
||||
it("should handle multiline content", () => {
|
||||
const content =
|
||||
"```typescript src/multi-line.ts\n" +
|
||||
"function example() {\n" +
|
||||
" const x = 1;\n" +
|
||||
" return x + 2;\n" +
|
||||
"}\n" +
|
||||
"```";
|
||||
|
||||
const expected =
|
||||
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return undefined when path doesn't exist in any code block", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "nonexistent.ts"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should extract content when the path has directory structure", () => {
|
||||
const content =
|
||||
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
|
||||
).toBe("const Button = () => <button>Click me</button>;");
|
||||
});
|
||||
|
||||
it("should match exact paths only", () => {
|
||||
const content =
|
||||
"```typescript src/utils.ts\nconst util = {};\n```\n" +
|
||||
"```typescript src/utils/index.ts\nconst index = {};\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
|
||||
"const util = {};",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
|
||||
"const index = {};",
|
||||
);
|
||||
});
|
||||
});
|
||||
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Extracts content from code blocks with given path
|
||||
* @param content The full message content
|
||||
* @param path The file path to look for
|
||||
* @returns The content of the code block if found, undefined otherwise
|
||||
*/
|
||||
export function extractContentFromCodeBlock(
|
||||
content: string,
|
||||
path: string,
|
||||
): string | undefined {
|
||||
// Escape special characters in the path for regex
|
||||
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
// Match the code block with this path
|
||||
// This regex looks for:
|
||||
// 1. Code block start with the path (```[language] path)
|
||||
// 2. The content until the closing ```
|
||||
// The path can be:
|
||||
// - With language: ```typescript src/main.ts
|
||||
// - Without language: ```src/main.ts
|
||||
// - With line ranges: ```js src/main.ts (1-10)
|
||||
const regex = new RegExp(
|
||||
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
|
||||
"m",
|
||||
);
|
||||
|
||||
const match = content.match(regex);
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -1,14 +1,21 @@
|
|||
import { RangeInFileWithContentsAndEdit } from "../..";
|
||||
import { DiffFormatType, createDiff } from "./diffFormatting";
|
||||
import { Position, RangeInFileWithNextEditInfo } from "../..";
|
||||
import {
|
||||
BeforeAfterDiff,
|
||||
DiffFormatType,
|
||||
createBeforeAfterDiff,
|
||||
createDiff,
|
||||
} from "./diffFormatting";
|
||||
|
||||
interface ClusterState {
|
||||
beforeState: string;
|
||||
startRange: { minLine: number; maxLine: number };
|
||||
currentRange: { minLine: number; maxLine: number };
|
||||
edits: RangeInFileWithContentsAndEdit[];
|
||||
edits: RangeInFileWithNextEditInfo[];
|
||||
firstTimestamp: number;
|
||||
lastTimestamp: number;
|
||||
lastLine: number;
|
||||
firstEditBeforeCursor: { line: number; character: number };
|
||||
lastEditAfterCursor: { line: number; character: number };
|
||||
}
|
||||
|
||||
interface FileState {
|
||||
|
|
@ -25,7 +32,6 @@ export interface EditClusterConfig {
|
|||
maxEdits: number;
|
||||
maxDuration: number;
|
||||
contextSize: number;
|
||||
maxEditSize: number;
|
||||
contextLines: number;
|
||||
verbose: boolean;
|
||||
}
|
||||
|
|
@ -33,31 +39,49 @@ export interface EditClusterConfig {
|
|||
export class EditAggregator {
|
||||
private fileStates: Map<string, FileState> = new Map();
|
||||
private config: EditClusterConfig;
|
||||
private onComparisonFinalized: (diff: string) => void;
|
||||
private previousEditFinalCursorPosition: Position;
|
||||
private lastProcessedFilePath: string | null = null;
|
||||
private onComparisonFinalized: (
|
||||
diff: BeforeAfterDiff,
|
||||
beforeCursorPos: Position,
|
||||
afterPrevEditCursorPos: Position,
|
||||
) => void;
|
||||
|
||||
constructor(
|
||||
config: Partial<EditClusterConfig> = {},
|
||||
onComparisonFinalized: (diff: string) => void = () => {},
|
||||
onComparisonFinalized: (
|
||||
diff: BeforeAfterDiff,
|
||||
beforeCursorPos: Position,
|
||||
afterPrevEditCursorPos: Position,
|
||||
) => void = () => {},
|
||||
) {
|
||||
this.config = {
|
||||
deltaT: config.deltaT ?? 1.0,
|
||||
deltaL: config.deltaL ?? 5,
|
||||
maxEdits: config.maxEdits ?? 500,
|
||||
maxDuration: config.maxDuration ?? 10.0,
|
||||
maxDuration: config.maxDuration ?? 100.0,
|
||||
contextSize: config.contextSize ?? 5,
|
||||
maxEditSize: config.maxEditSize ?? 1000,
|
||||
contextLines: config.contextLines ?? 3,
|
||||
verbose: config.verbose ?? false,
|
||||
};
|
||||
this.onComparisonFinalized = onComparisonFinalized;
|
||||
this.previousEditFinalCursorPosition = { line: 0, character: 0 };
|
||||
}
|
||||
|
||||
async processEdit(
|
||||
edit: RangeInFileWithContentsAndEdit,
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number = Date.now(),
|
||||
): Promise<void> {
|
||||
const filePath = edit.filepath;
|
||||
|
||||
// If we're switching to a different file, finalize all clusters from the previous file
|
||||
if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
|
||||
await this.finalizeClustersForFile(this.lastProcessedFilePath);
|
||||
}
|
||||
|
||||
// Update the last processed file path
|
||||
this.lastProcessedFilePath = filePath;
|
||||
|
||||
if (!this.fileStates.has(filePath)) {
|
||||
this.fileStates.set(filePath, {
|
||||
activeClusters: [],
|
||||
|
|
@ -105,23 +129,18 @@ export class EditAggregator {
|
|||
}
|
||||
|
||||
private async _processEditInternal(
|
||||
edit: RangeInFileWithContentsAndEdit,
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number,
|
||||
fileState: FileState,
|
||||
): Promise<void> {
|
||||
const filePath = edit.filepath;
|
||||
|
||||
const editSize = edit.editText.length;
|
||||
if (editSize > this.config.maxEditSize) {
|
||||
return;
|
||||
}
|
||||
|
||||
const editLine = edit.range.start.line;
|
||||
const currentFileLines = fileState.currentContent.split("\n");
|
||||
|
||||
const clustersToFinalize = this.identifyClustersToFinalize(
|
||||
fileState,
|
||||
editLine,
|
||||
edit,
|
||||
timestamp,
|
||||
false,
|
||||
);
|
||||
|
|
@ -136,6 +155,29 @@ export class EditAggregator {
|
|||
timestamp,
|
||||
);
|
||||
|
||||
// Check if adding this edit would exceed deltaL lines for the cluster
|
||||
if (suitableCluster) {
|
||||
const potentialMinLine = Math.min(
|
||||
suitableCluster.currentRange.minLine,
|
||||
Math.max(0, editLine - this.config.contextLines),
|
||||
);
|
||||
const potentialMaxLine = Math.max(
|
||||
suitableCluster.currentRange.maxLine,
|
||||
Math.min(
|
||||
currentFileLines.length - 1,
|
||||
editLine + this.config.contextLines,
|
||||
),
|
||||
);
|
||||
const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
|
||||
|
||||
if (potentialLineSpan > this.config.deltaL * 2) {
|
||||
// Auto-finalize the current cluster before creating a new one
|
||||
await this.finalizeCluster(filePath, suitableCluster, fileState);
|
||||
suitableCluster = null;
|
||||
}
|
||||
}
|
||||
|
||||
// initialize a cluster
|
||||
if (!suitableCluster) {
|
||||
suitableCluster = {
|
||||
beforeState: fileState.currentContent,
|
||||
|
|
@ -157,6 +199,8 @@ export class EditAggregator {
|
|||
firstTimestamp: timestamp,
|
||||
lastTimestamp: timestamp,
|
||||
lastLine: editLine,
|
||||
firstEditBeforeCursor: edit.beforeCursorPos,
|
||||
lastEditAfterCursor: edit.afterCursorPos,
|
||||
};
|
||||
fileState.activeClusters.push(suitableCluster);
|
||||
}
|
||||
|
|
@ -164,6 +208,7 @@ export class EditAggregator {
|
|||
suitableCluster.edits.push(edit);
|
||||
suitableCluster.lastTimestamp = timestamp;
|
||||
suitableCluster.lastLine = editLine;
|
||||
suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
|
||||
|
||||
const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
|
||||
edit,
|
||||
|
|
@ -203,7 +248,7 @@ export class EditAggregator {
|
|||
}
|
||||
|
||||
private isWhitespaceOnlyEdit(
|
||||
edit: RangeInFileWithContentsAndEdit,
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
currentContent: string,
|
||||
): boolean {
|
||||
const lines = currentContent.split("\n");
|
||||
|
|
@ -236,11 +281,11 @@ export class EditAggregator {
|
|||
);
|
||||
}
|
||||
|
||||
async processEdits(edits: RangeInFileWithContentsAndEdit[]): Promise<void> {
|
||||
async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
|
||||
const timestamp = Date.now();
|
||||
|
||||
// Only process the last edit during rapid typing
|
||||
if (this.getProcessingQueueSize() > 15) {
|
||||
if (this.getProcessingQueueSize() > 50) {
|
||||
if (edits.length > 0) {
|
||||
await this.processEdit(edits[edits.length - 1], timestamp);
|
||||
}
|
||||
|
|
@ -252,17 +297,26 @@ export class EditAggregator {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizes all clusters for a specific file
|
||||
*/
|
||||
private async finalizeClustersForFile(filePath: string): Promise<void> {
|
||||
const fileState = this.fileStates.get(filePath);
|
||||
if (!fileState) return;
|
||||
|
||||
// Create a copy of the clusters to finalize to avoid modifying array during iteration
|
||||
const clustersToFinalize = [...fileState.activeClusters];
|
||||
|
||||
for (const cluster of clustersToFinalize) {
|
||||
await this.finalizeCluster(filePath, cluster, fileState);
|
||||
}
|
||||
}
|
||||
|
||||
async finalizeAllClusters(): Promise<void> {
|
||||
const filePromises: Promise<void>[] = [];
|
||||
|
||||
this.fileStates.forEach((fileState, filePath) => {
|
||||
const filePromise = (async () => {
|
||||
const clustersToFinalize = [...fileState.activeClusters];
|
||||
for (const cluster of clustersToFinalize) {
|
||||
await this.finalizeCluster(filePath, cluster, fileState);
|
||||
}
|
||||
})();
|
||||
|
||||
const filePromise = this.finalizeClustersForFile(filePath);
|
||||
filePromises.push(filePromise);
|
||||
});
|
||||
|
||||
|
|
@ -321,29 +375,39 @@ export class EditAggregator {
|
|||
|
||||
private identifyClustersToFinalize(
|
||||
fileState: FileState,
|
||||
editLine: number,
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number,
|
||||
isStructuralEdit: boolean,
|
||||
): ClusterState[] {
|
||||
const clustersToFinalize: ClusterState[] = [];
|
||||
const editLine = edit.range.start.line;
|
||||
|
||||
fileState.activeClusters.forEach((cluster) => {
|
||||
const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
|
||||
|
||||
// Only consider the line changed if it's a DIFFERENT line
|
||||
const isOnDifferentLine = cluster.lastLine !== editLine;
|
||||
const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
|
||||
|
||||
// Finalize if we moved to a different line AND the time gap exceeds deltaT
|
||||
const isOnDifferentLineByNewline = edit.editText.includes("\n");
|
||||
|
||||
// Use different time thresholds for different types of line change detection
|
||||
const shouldFinalizeByLineNumber =
|
||||
isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
|
||||
|
||||
const shouldFinalizeByNewline =
|
||||
isOnDifferentLineByNewline &&
|
||||
timeSinceLastEdit > this.config.deltaT * 1.5;
|
||||
|
||||
// Finalize if we moved to a different line AND the time gap exceeds the respective threshold
|
||||
const shouldFinalizeByTime =
|
||||
isOnDifferentLine && timeSinceLastEdit > this.config.deltaT;
|
||||
|
||||
shouldFinalizeByLineNumber || shouldFinalizeByNewline;
|
||||
const shouldFinalizeByCount =
|
||||
cluster.edits.length >= this.config.maxEdits;
|
||||
|
||||
const shouldFinalizeByDuration =
|
||||
(timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
|
||||
|
||||
// Structural edits should only finalize other clusters, not their own
|
||||
// For structural edits, use the combined line detection
|
||||
const isOnDifferentLine =
|
||||
isOnDifferentLineByNumber || isOnDifferentLineByNewline;
|
||||
const shouldFinalizeByStructuralEdit =
|
||||
isStructuralEdit && isOnDifferentLine;
|
||||
|
||||
|
|
@ -384,7 +448,7 @@ export class EditAggregator {
|
|||
afterContent,
|
||||
filePath,
|
||||
DiffFormatType.Unified,
|
||||
);
|
||||
); // Used for checks, not for final output
|
||||
|
||||
// Skip diffs with too many changed lines
|
||||
const changedLineCount = this.countChangedLines(diff);
|
||||
|
|
@ -404,7 +468,21 @@ export class EditAggregator {
|
|||
(c) => c !== cluster,
|
||||
);
|
||||
|
||||
this.onComparisonFinalized(diff);
|
||||
// Give format-agnostic diff to the callback
|
||||
const fullFileVersionsDiff = createBeforeAfterDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
);
|
||||
|
||||
// Store this cluster's final cursor position for future reference
|
||||
this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
|
||||
|
||||
this.onComparisonFinalized(
|
||||
fullFileVersionsDiff,
|
||||
cluster.firstEditBeforeCursor,
|
||||
this.previousEditFinalCursorPosition,
|
||||
);
|
||||
}
|
||||
|
||||
private countChangedLines(diff: string): number {
|
||||
|
|
@ -453,5 +531,6 @@ export class EditAggregator {
|
|||
|
||||
resetState(): void {
|
||||
this.fileStates.clear();
|
||||
this.lastProcessedFilePath = null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
140
core/nextEdit/context/autocompleteContextFetching.ts
Normal file
140
core/nextEdit/context/autocompleteContextFetching.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { Position } from "../..";
|
||||
import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
|
||||
import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
|
||||
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
|
||||
import { renderPrompt } from "../../autocomplete/templating";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import {
|
||||
AutocompleteInput,
|
||||
RecentlyEditedRange,
|
||||
} from "../../autocomplete/util/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { IDE, ILLM } from "../../index";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
|
||||
|
||||
/**
|
||||
* Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
|
||||
* This function mimics the context generation pipeline from the autocomplete system without triggering
|
||||
* an actual completion.
|
||||
*
|
||||
* @param filepath - The file path where context is being requested
|
||||
* @param pos - The position in the file where context is being requested
|
||||
* @param ide - The IDE interface for file system operations
|
||||
* @param configHandler - The config handler to load user configuration
|
||||
* @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
|
||||
* @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
|
||||
* @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
|
||||
* @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
|
||||
* @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
|
||||
* @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
|
||||
* @returns Promise that resolves to the formatted context string
|
||||
*/
|
||||
export const getAutocompleteContext = async (
|
||||
filepath: string,
|
||||
pos: Position,
|
||||
ide: IDE,
|
||||
configHandler: ConfigHandler,
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[],
|
||||
maxPromptTokens: number,
|
||||
manuallyPassFileContents: string,
|
||||
autocompleteModel?: ILLM | string,
|
||||
// eslint-disable-next-line max-params
|
||||
): Promise<string> => {
|
||||
if (!recentlyEditedRanges) recentlyEditedRanges = [];
|
||||
if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
|
||||
|
||||
const input: AutocompleteInput = {
|
||||
isUntitledFile: false,
|
||||
completionId: `context-fetch-${Date.now()}`,
|
||||
filepath,
|
||||
pos,
|
||||
recentlyVisitedRanges,
|
||||
recentlyEditedRanges,
|
||||
manuallyPassFileContents,
|
||||
};
|
||||
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("No config available");
|
||||
}
|
||||
|
||||
// Use provided autocomplete model or fall back to configured autocomplete model
|
||||
let finalModel: ILLM;
|
||||
let modelNameForTemplating: string;
|
||||
|
||||
if (autocompleteModel) {
|
||||
if (typeof autocompleteModel === "string") {
|
||||
// Try to find the model in config first
|
||||
const foundModel = config.modelsByRole.autocomplete.find(
|
||||
(m) => m.title === autocompleteModel,
|
||||
);
|
||||
if (foundModel) {
|
||||
finalModel = foundModel;
|
||||
modelNameForTemplating = foundModel.model;
|
||||
} else {
|
||||
// Model not found in config, but we can still use it for template selection
|
||||
const configuredModel = config.selectedModelByRole.autocomplete;
|
||||
if (!configuredModel) {
|
||||
throw new Error(
|
||||
"No autocomplete model configured and provided model not found in config",
|
||||
);
|
||||
}
|
||||
finalModel = configuredModel;
|
||||
modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
|
||||
}
|
||||
} else {
|
||||
finalModel = autocompleteModel;
|
||||
modelNameForTemplating = autocompleteModel.model;
|
||||
}
|
||||
} else {
|
||||
const configuredModel = config.selectedModelByRole.autocomplete;
|
||||
if (!configuredModel) {
|
||||
throw new Error("No autocomplete model configured and no model provided");
|
||||
}
|
||||
finalModel = configuredModel;
|
||||
modelNameForTemplating = configuredModel.model;
|
||||
}
|
||||
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
...finalModel.autocompleteOptions,
|
||||
...(maxPromptTokens && { maxPromptTokens }),
|
||||
};
|
||||
|
||||
if (finalModel.promptTemplates?.autocomplete) {
|
||||
options.template = finalModel.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
modelNameForTemplating,
|
||||
ide,
|
||||
);
|
||||
|
||||
const contextRetrievalService = new ContextRetrievalService(ide);
|
||||
|
||||
await contextRetrievalService.initializeForFile(filepath);
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
ide: ide,
|
||||
getDefinitionsFromLsp: getDefinitionsFromLsp,
|
||||
contextRetrievalService: contextRetrievalService,
|
||||
}),
|
||||
ide.getWorkspaceDirs(),
|
||||
]);
|
||||
|
||||
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
|
||||
snippetPayload,
|
||||
workspaceDirs,
|
||||
helper,
|
||||
});
|
||||
|
||||
return prefix;
|
||||
};
|
||||
|
|
@ -2,10 +2,16 @@ import { createPatch } from "diff";
|
|||
|
||||
export enum DiffFormatType {
|
||||
Unified = "unified",
|
||||
Minimal = "minimal",
|
||||
RawBeforeAfter = "beforeAfter",
|
||||
TokenLineDiff = "linediff",
|
||||
}
|
||||
|
||||
export type BeforeAfterDiff = {
|
||||
filePath: string;
|
||||
beforeContent: string;
|
||||
afterContent: string;
|
||||
};
|
||||
|
||||
export const createDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
|
|
@ -15,11 +21,10 @@ export const createDiff = (
|
|||
switch (diffType) {
|
||||
case DiffFormatType.Unified:
|
||||
return createUnifiedDiff(beforeContent, afterContent, filePath);
|
||||
case DiffFormatType.Minimal:
|
||||
return createMinimalDiff(beforeContent, afterContent, filePath);
|
||||
case DiffFormatType.TokenLineDiff:
|
||||
return createTokenLineDiff(beforeContent, afterContent, filePath);
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
const createUnifiedDiff = (
|
||||
|
|
@ -46,13 +51,25 @@ const createUnifiedDiff = (
|
|||
return patch;
|
||||
};
|
||||
|
||||
const createMinimalDiff = (
|
||||
export const createBeforeAfterDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
) => {
|
||||
// TODO: Implement minimal diff
|
||||
return "";
|
||||
const normalizedBefore = beforeContent.endsWith("\n")
|
||||
? beforeContent
|
||||
: beforeContent + "\n";
|
||||
const normalizedAfter = afterContent.endsWith("\n")
|
||||
? afterContent
|
||||
: afterContent + "\n";
|
||||
|
||||
const result: BeforeAfterDiff = {
|
||||
filePath: filePath,
|
||||
beforeContent: normalizedBefore,
|
||||
afterContent: normalizedAfter,
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const createTokenLineDiff = (
|
||||
|
|
|
|||
69
core/nextEdit/context/processNextEditData.ts
Normal file
69
core/nextEdit/context/processNextEditData.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { IDE, Position } from "../..";
|
||||
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { DataLogger } from "../../data/log";
|
||||
import { RecentlyEditedRange } from "../types";
|
||||
import { getAutocompleteContext } from "./autocompleteContextFetching";
|
||||
|
||||
const randomNumberBetween = (min: number, max: number) => {
|
||||
min = Math.ceil(min); // Ensure min is an integer
|
||||
max = Math.floor(max); // Ensure max is an integer
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
};
|
||||
|
||||
export const processNextEditData = async (
|
||||
filePath: string,
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
cursorPosBeforeEdit: Position,
|
||||
cursorPosAfterPrevEdit: Position,
|
||||
ide: IDE,
|
||||
configHandler: ConfigHandler,
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[],
|
||||
workspaceDir: string,
|
||||
modelNameOrInstance?: string | undefined,
|
||||
// eslint-disable-next-line max-params
|
||||
) => {
|
||||
// To switch to the user's autocomplete model, uncomment the following lines
|
||||
// const { config } = await configHandler.loadConfig();
|
||||
// const autocompleteModel =
|
||||
// (modelNameOrInstance || config?.selectedModelByRole.autocomplete) ??
|
||||
// undefined;
|
||||
|
||||
const modelName = "Codestral";
|
||||
|
||||
const maxPromptTokens = randomNumberBetween(500, 12000);
|
||||
|
||||
const autocompleteContext = await getAutocompleteContext(
|
||||
filePath,
|
||||
cursorPosBeforeEdit,
|
||||
ide,
|
||||
configHandler,
|
||||
getDefinitionsFromLsp,
|
||||
recentlyEditedRanges,
|
||||
recentlyVisitedRanges,
|
||||
maxPromptTokens,
|
||||
beforeContent,
|
||||
modelName,
|
||||
);
|
||||
|
||||
// console.log(
|
||||
// createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
|
||||
// );
|
||||
|
||||
void DataLogger.getInstance().logDevData({
|
||||
name: "nextEdit",
|
||||
data: {
|
||||
fileURI: filePath,
|
||||
workspaceDirURI: workspaceDir,
|
||||
beforeContent,
|
||||
afterContent,
|
||||
beforeCursorPos: cursorPosBeforeEdit,
|
||||
afterCursorPos: cursorPosAfterPrevEdit,
|
||||
context: autocompleteContext,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
|
@ -79,7 +79,7 @@ export function slashCommandFromPromptFileV1(
|
|||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
context.abortController.signal,
|
||||
context.completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,10 @@ import {
|
|||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import {
|
||||
AutocompleteInput,
|
||||
RecentlyEditedRange,
|
||||
} from "../autocomplete/util/types";
|
||||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
|
|
@ -25,7 +28,7 @@ import {
|
|||
ModelDescription,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
RangeInFileWithContentsAndEdit,
|
||||
RangeInFileWithNextEditInfo,
|
||||
SerializedContinueConfig,
|
||||
Session,
|
||||
SessionMetadata,
|
||||
|
|
@ -34,6 +37,9 @@ import {
|
|||
StreamDiffLinesPayload,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types";
|
||||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
|
||||
import { FreeTrialStatus } from "../control-plane/client";
|
||||
|
|
@ -183,7 +189,16 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"files/created": [{ uris?: string[] }, void];
|
||||
"files/deleted": [{ uris?: string[] }, void];
|
||||
"files/closed": [{ uris?: string[] }, void];
|
||||
"files/smallEdit": [{ actions: RangeInFileWithContentsAndEdit[] }, void];
|
||||
"files/smallEdit": [
|
||||
{
|
||||
actions: RangeInFileWithNextEditInfo[];
|
||||
configHandler: ConfigHandler;
|
||||
getDefsFromLspFunction: GetLspDefinitionsFunction;
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[];
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
||||
// Docs etc. Indexing. TODO move codebase to this
|
||||
"indexing/reindex": [{ type: string; id: string }, void];
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
openFile: [{ path: string }, void];
|
||||
openUrl: [string, void];
|
||||
runCommand: [{ command: string; options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
getFileResults: [{ pattern: string }, string[]];
|
||||
getSearchResults: [{ query: string; maxResults?: number }, string];
|
||||
getFileResults: [{ pattern: string; maxResults?: number }, string[]];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
|
|
|
|||
|
|
@ -185,8 +185,8 @@ export class MessageIde implements IDE {
|
|||
return this.request("getPinnedFiles", undefined);
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return this.request("getSearchResults", { query });
|
||||
getSearchResults(query: string, maxResults?: number): Promise<string> {
|
||||
return this.request("getSearchResults", { query, maxResults });
|
||||
}
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]> {
|
||||
|
|
|
|||
|
|
@ -159,11 +159,11 @@ export class ReverseMessageIde {
|
|||
});
|
||||
|
||||
this.on("getSearchResults", (data) => {
|
||||
return this.ide.getSearchResults(data.query);
|
||||
return this.ide.getSearchResults(data.query, data.maxResults);
|
||||
});
|
||||
|
||||
this.on("getFileResults", (data) => {
|
||||
return this.ide.getFileResults(data.pattern);
|
||||
return this.ide.getFileResults(data.pattern, data.maxResults);
|
||||
});
|
||||
|
||||
this.on("getProblems", (data) => {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export const createRuleBlock: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.CreateRuleBlock,
|
||||
description:
|
||||
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
|
||||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "alwaysApply", "description"],
|
||||
|
|
@ -37,6 +37,11 @@ export const createRuleBlock: Tool = {
|
|||
description:
|
||||
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
|
||||
},
|
||||
regex: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ export const globSearchTool: Tool = {
|
|||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.FileGlobSearch,
|
||||
description: "Search for files in the project",
|
||||
description:
|
||||
"Search for files in the project. Output may be truncated; use targeted patterns",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["pattern"],
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ export const grepSearchTool: Tool = {
|
|||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.GrepSearch,
|
||||
description: "Perform a search over the repository using ripgrep.",
|
||||
description:
|
||||
"Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
|
|
|
|||
|
|
@ -7,16 +7,24 @@ export type CreateRuleBlockArgs = Pick<
|
|||
Required<RuleWithSource>,
|
||||
"rule" | "description" | "alwaysApply" | "name"
|
||||
> &
|
||||
Pick<RuleWithSource, "globs">;
|
||||
Pick<RuleWithSource, "globs" | "regex">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
args: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, {
|
||||
// Create options object with the fields that createRuleMarkdown expects
|
||||
const options: any = {
|
||||
description: args.description,
|
||||
globs: args.globs,
|
||||
});
|
||||
};
|
||||
|
||||
// Add regex if provided
|
||||
if (args.regex) {
|
||||
options.regex = args.regex;
|
||||
}
|
||||
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, options);
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,28 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
|
||||
const MAX_AGENT_GLOB_RESULTS = 100;
|
||||
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getFileResults(args.pattern);
|
||||
return [
|
||||
const results = await extras.ide.getFileResults(
|
||||
args.pattern,
|
||||
MAX_AGENT_GLOB_RESULTS,
|
||||
);
|
||||
const contextItems: ContextItem[] = [
|
||||
{
|
||||
name: "File results",
|
||||
description: "Results from file glob search",
|
||||
content: results.join("\n"),
|
||||
},
|
||||
];
|
||||
|
||||
// In case of truncation, add a warning
|
||||
if (results.length === MAX_AGENT_GLOB_RESULTS) {
|
||||
contextItems.push({
|
||||
name: "Truncation warning",
|
||||
description: "Inform the model that results were truncated",
|
||||
content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,13 +1,44 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
|
||||
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
|
||||
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
const results = await extras.ide.getSearchResults(
|
||||
args.query,
|
||||
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
|
||||
);
|
||||
const { formatted, numResults, truncated } = formatGrepSearchResults(
|
||||
results,
|
||||
DEFAULT_GREP_SEARCH_CHAR_LIMIT,
|
||||
);
|
||||
const truncationReasons: string[] = [];
|
||||
if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
|
||||
truncationReasons.push(
|
||||
`the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`,
|
||||
);
|
||||
}
|
||||
if (truncated) {
|
||||
truncationReasons.push(
|
||||
`the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`,
|
||||
);
|
||||
}
|
||||
|
||||
const contextItems: ContextItem[] = [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from grep search",
|
||||
content: formatGrepSearchResults(results),
|
||||
content: formatted,
|
||||
},
|
||||
];
|
||||
if (truncationReasons.length > 0) {
|
||||
contextItems.push({
|
||||
name: "Search truncation warning",
|
||||
description: "Informs the model that search results were truncated",
|
||||
content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
|
||||
});
|
||||
}
|
||||
return contextItems;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -234,11 +234,14 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
async getSearchResults(query: string): Promise<string> {
|
||||
async getSearchResults(query: string, maxResults?: number): Promise<string> {
|
||||
return "";
|
||||
}
|
||||
|
||||
async getFileResults(pattern: string): Promise<string[]> {
|
||||
async getFileResults(
|
||||
pattern: string,
|
||||
maxResults?: number,
|
||||
): Promise<string[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,19 @@
|
|||
export function formatGrepSearchResults(results: string): string {
|
||||
/*
|
||||
Formats the output of a grep search to reduce unnecessary indentation, lines, etc
|
||||
Assumes a command with these params
|
||||
ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
|
||||
|
||||
Also can truncate the output to a specified number of characters
|
||||
*/
|
||||
export function formatGrepSearchResults(
|
||||
results: string,
|
||||
maxChars?: number,
|
||||
): {
|
||||
formatted: string;
|
||||
numResults: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
let numResults = 0;
|
||||
const keepLines: string[] = [];
|
||||
|
||||
function countLeadingSpaces(line: string) {
|
||||
|
|
@ -45,6 +60,7 @@ export function formatGrepSearchResults(results: string): string {
|
|||
if (line.startsWith("./") || line === "--") {
|
||||
processResult(resultLines); // process previous result
|
||||
resultLines = [line];
|
||||
numResults++;
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -57,5 +73,18 @@ export function formatGrepSearchResults(results: string): string {
|
|||
}
|
||||
processResult(resultLines);
|
||||
|
||||
return keepLines.join("\n");
|
||||
const formatted = keepLines.join("\n");
|
||||
if (maxChars && formatted.length > maxChars) {
|
||||
return {
|
||||
formatted: formatted.substring(0, maxChars),
|
||||
numResults,
|
||||
truncated: true,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
formatted,
|
||||
numResults,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
217
core/util/grepSearch.vitest.ts
Normal file
217
core/util/grepSearch.vitest.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { formatGrepSearchResults } from "./grepSearch";
|
||||
|
||||
// Sample grep output mimicking what would come from ripgrep with the params:
|
||||
// ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
|
||||
const sampleGrepOutput = `./program.cs
|
||||
Console.WriteLine("Hello World!");
|
||||
Calculator calc = new Calculator();
|
||||
calc.Add(5).Subtract(3);
|
||||
Console.WriteLine("Result: " + calc.GetResult());
|
||||
}
|
||||
--
|
||||
}
|
||||
|
||||
public Calculator Subtract(double number)
|
||||
{
|
||||
result -= number;
|
||||
|
||||
./test.kt
|
||||
}
|
||||
|
||||
fun subtract(number: Double): Test {
|
||||
result -= number
|
||||
return this
|
||||
|
||||
./test.php
|
||||
}
|
||||
|
||||
public function subtract($number) {
|
||||
$this->result -= $number;
|
||||
return $this;
|
||||
--
|
||||
|
||||
$calc = new Calculator();
|
||||
$calc->add(10)->subtract(5);
|
||||
echo "Result: " . $calc->getResult() . "\n";
|
||||
|
||||
|
||||
./Calculator.java
|
||||
}
|
||||
|
||||
public Calculator subtract(double number) {
|
||||
result -= number;
|
||||
return this;
|
||||
--
|
||||
public static void main(String[] args) {
|
||||
Calculator calc = new Calculator();
|
||||
calc.add(10).subtract(5);
|
||||
System.out.println("Result: " + calc.getResult());
|
||||
}
|
||||
|
||||
./calculator_test/Calculator.java
|
||||
}
|
||||
|
||||
public int subtract(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
|
||||
./test.rb
|
||||
end
|
||||
|
||||
def subtract(number)
|
||||
@result -= number
|
||||
self
|
||||
--
|
||||
|
||||
calc = Calculator.new
|
||||
calc.add(5).subtract(3)
|
||||
puts "Result: #{calc.get_result}"
|
||||
|
||||
./test.js
|
||||
return this;
|
||||
}
|
||||
subtract(number) {
|
||||
return this;
|
||||
}
|
||||
|
||||
./test.py
|
||||
return self
|
||||
|
||||
def subtract(self, number):
|
||||
self.result -= number
|
||||
return self
|
||||
|
||||
./test.ts
|
||||
}
|
||||
|
||||
subtract(number: number): Calculator {
|
||||
this.result -= number;
|
||||
return this;`;
|
||||
|
||||
test("formats grep search results correctly", () => {
|
||||
const result = formatGrepSearchResults(sampleGrepOutput);
|
||||
|
||||
expect(result.numResults).toBe(13); // 4 file paths in the sample
|
||||
expect(result.truncated).toBe(false);
|
||||
|
||||
// Check that all file paths are preserved
|
||||
expect(result.formatted).toContain("./program.cs");
|
||||
expect(result.formatted).toContain("./test.kt");
|
||||
expect(result.formatted).toContain("./test.php");
|
||||
expect(result.formatted).toContain("./Calculator.java");
|
||||
|
||||
// Check that content is preserved and properly indented
|
||||
expect(result.formatted).toContain('Console.WriteLine("Hello World!");');
|
||||
expect(result.formatted).toContain("fun subtract(number: Double): Test {");
|
||||
expect(result.formatted).toContain("public function subtract($number) {");
|
||||
expect(result.formatted).toContain(
|
||||
"public Calculator subtract(double number) {",
|
||||
);
|
||||
});
|
||||
|
||||
test("handles empty input", () => {
|
||||
const result = formatGrepSearchResults("");
|
||||
|
||||
expect(result.numResults).toBe(0);
|
||||
expect(result.truncated).toBe(false);
|
||||
expect(result.formatted).toBe("");
|
||||
});
|
||||
|
||||
test("handles input with only file paths (no content) - lines should be skipped", () => {
|
||||
const input =
|
||||
"./empty-file.ts\n./another-empty.js\n./has-content.ts\n searchMatch";
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
expect(result.numResults).toBe(3);
|
||||
expect(result.formatted).toBe("./has-content.ts\n searchMatch");
|
||||
});
|
||||
|
||||
test("truncates output when exceeding maxChars", () => {
|
||||
const maxChars = 50;
|
||||
const result = formatGrepSearchResults(sampleGrepOutput, maxChars);
|
||||
|
||||
expect(result.truncated).toBe(true);
|
||||
expect(result.formatted.length).toBe(maxChars);
|
||||
});
|
||||
|
||||
test("normalizes indentation to 2 spaces", () => {
|
||||
const input = `./file.ts
|
||||
function test() {
|
||||
const x = 1;
|
||||
console.log(x);
|
||||
}`;
|
||||
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
// The function should normalize the indentation to 2 spaces
|
||||
expect(result.formatted).toContain("./file.ts");
|
||||
expect(result.formatted).toContain(" function test() {");
|
||||
expect(result.formatted).toContain(" const x = 1;");
|
||||
expect(result.formatted).toContain(" console.log(x);");
|
||||
expect(result.formatted).toContain(" }");
|
||||
});
|
||||
|
||||
test("skips leading single-char or empty lines after file paths", () => {
|
||||
const input = `./file.ts
|
||||
|
||||
function test() {
|
||||
console.log("test");
|
||||
}`;
|
||||
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
expect(result.formatted).toContain("./file.ts");
|
||||
expect(result.formatted).not.toContain("\n \n"); // The single space line should be skipped
|
||||
expect(result.formatted).toContain("function test() {");
|
||||
});
|
||||
|
||||
test("processes separator lines correctly", () => {
|
||||
const input = `./file1.ts
|
||||
function one() {
|
||||
return 1;
|
||||
}
|
||||
--
|
||||
function two() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
./file2.ts
|
||||
class Test {
|
||||
method() {}
|
||||
}`;
|
||||
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
expect(result.numResults).toBe(3);
|
||||
expect(result.formatted).toContain("./file1.ts");
|
||||
expect(result.formatted).toContain("--");
|
||||
expect(result.formatted).toContain("function two() {");
|
||||
expect(result.formatted).toContain("./file2.ts");
|
||||
});
|
||||
|
||||
test("increases indentation when original is less than 2 spaces", () => {
|
||||
const input = `./minimal-indent.ts
|
||||
function test() {
|
||||
singleSpaceIndent();
|
||||
}`;
|
||||
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
expect(result.formatted).toContain(" function test() {");
|
||||
expect(result.formatted).toContain(" singleSpaceIndent();");
|
||||
expect(result.formatted).toContain(" }");
|
||||
});
|
||||
|
||||
test("decreases indentation when original is more than 2 spaces", () => {
|
||||
const input = `./excessive-indent.ts
|
||||
function test() {
|
||||
tooMuchIndent();
|
||||
}`;
|
||||
|
||||
const result = formatGrepSearchResults(input);
|
||||
|
||||
expect(result.formatted).toContain(" function test() {");
|
||||
expect(result.formatted).toContain(" tooMuchIndent();");
|
||||
expect(result.formatted).toContain(" }");
|
||||
});
|
||||
|
|
@ -4,6 +4,7 @@ import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
|
|||
import { IdeInfo } from "../index.js";
|
||||
|
||||
import type { PostHog as PostHogType } from "posthog-node";
|
||||
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
|
||||
|
||||
export enum PosthogFeatureFlag {
|
||||
AutocompleteTimeout = "autocomplete-timeout",
|
||||
|
|
@ -37,6 +38,24 @@ export class Telemetry {
|
|||
static os: string | undefined = undefined;
|
||||
static ideInfo: IdeInfo | undefined = undefined;
|
||||
|
||||
/**
|
||||
* Convenience method for capturing errors in a single event
|
||||
*/
|
||||
static async captureError(errorName: string, error: unknown) {
|
||||
if (!(error instanceof Error)) {
|
||||
return;
|
||||
}
|
||||
await Telemetry.capture(
|
||||
"extension_error_caught",
|
||||
{
|
||||
errorName,
|
||||
message: error.message,
|
||||
stack: extractMinimalStackTraceInfo(error.stack),
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
static async capture(
|
||||
event: string,
|
||||
properties: { [key: string]: any },
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ Continue includes several built-in tools which provide the model access to IDE f
|
|||
- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file
|
||||
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
|
||||
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
|
||||
- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
|
||||
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
|
||||
- **Search web** (`builtin_search_web`): Perform a web search to get top results
|
||||
- **View diff** (`builtin_view_diff`): View the current working git diff
|
||||
|
|
|
|||
|
|
@ -288,6 +288,8 @@ Reference the results of codebase search, just like the results you would get fr
|
|||
```yaml title="config.yaml"
|
||||
context:
|
||||
- provider: search
|
||||
params:
|
||||
maxResults: 100 # optional, defaults to 200
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="json" label="JSON">
|
||||
|
|
@ -295,7 +297,10 @@ Reference the results of codebase search, just like the results you would get fr
|
|||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "search"
|
||||
"name": "search",
|
||||
"params": {
|
||||
"maxResults": 100 // optional, defaults to 200
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark
|
|||
|
||||
- `name` (**required** for YAML): A display name/title for the rule
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`).
|
||||
- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context.
|
||||
- `alwaysApply`: true - Always include the rule, regardless of file context
|
||||
- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ We recommend configuring **Claude 4 Sonnet** as your chat model.
|
|||
{
|
||||
"title": "Claude 4 Sonnet",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"model": "claude-sonnet-4-latest",
|
||||
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
|
||||
}
|
||||
]
|
||||
|
|
@ -68,9 +68,6 @@ Prompt caching is generally available for:
|
|||
- Claude 3.7 Sonnet
|
||||
- Claude 3.5 Sonnet
|
||||
- Claude 3.5 Haiku
|
||||
- Claude 3 Opus
|
||||
- Claude 3 Sonnet
|
||||
- Claude 3 Haiku
|
||||
|
||||
To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows:
|
||||
|
||||
|
|
@ -84,9 +81,8 @@ To enable caching of the system message and the turn-by-turn conversation, updat
|
|||
apiKey: <YOUR_ANTHROPIC_API_KEY>
|
||||
roles:
|
||||
- chat
|
||||
cacheBehavior:
|
||||
cacheSystemMessage: true
|
||||
cacheConversation: true
|
||||
defaultCompletionOptions:
|
||||
promptCaching: true
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="json" label="JSON">
|
||||
|
|
@ -100,7 +96,10 @@ To enable caching of the system message and the turn-by-turn conversation, updat
|
|||
},
|
||||
"title": "Anthropic",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"model": "claude-sonnet-4-latest",
|
||||
"defaultCompletionOptions": {
|
||||
"promptCaching": true
|
||||
},
|
||||
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -203,6 +203,14 @@ const config = {
|
|||
},
|
||||
}),
|
||||
plugins: [
|
||||
[
|
||||
"posthog-docusaurus",
|
||||
{
|
||||
apiKey: process.env.POSTHOG_API_KEY || "DEV",
|
||||
appUrl: "https://us.i.posthog.com",
|
||||
enableInDevelopment: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-client-redirects",
|
||||
{
|
||||
|
|
|
|||
10
docs/package-lock.json
generated
10
docs/package-lock.json
generated
|
|
@ -14,6 +14,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
|
|
@ -14990,6 +14991,15 @@
|
|||
"postcss": "^8.4.31"
|
||||
}
|
||||
},
|
||||
"node_modules/posthog-docusaurus": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/posthog-docusaurus/-/posthog-docusaurus-2.0.4.tgz",
|
||||
"integrity": "sha512-xnEVCBovSuvQvYXGny03CDTc0yZCl7O3Mz21sJpXmE1Gvs21gM33WzWaA9Cm6WvWGYZtQy8t8/g8OjCkmTWlXA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.15.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pretty-error": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.24
|
||||
pluginVersion=1.0.25
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
56
extensions/intellij/rules.md
Normal file
56
extensions/intellij/rules.md
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# Continue JetBrains Extension
|
||||
|
||||
## Project Purpose
|
||||
|
||||
JetBrains/IntelliJ extension for Continue AI code assistant. Provides chat, autocomplete, inline edit, and agent features within JetBrains IDEs.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Language**: Kotlin (JDK 17), Gradle build
|
||||
- **Communication**: stdin/stdout message passing with core binary from `../../binary`
|
||||
- **UI**: Embeds React webview from `../../gui`
|
||||
- **Platform**: IntelliJ Platform Plugin (IDEA, PyCharm, WebStorm, etc.)
|
||||
|
||||
## Key Source Structure
|
||||
|
||||
```
|
||||
src/main/kotlin/com/github/continuedev/continueintellijextension/
|
||||
├── continue/ # Core integration (CoreMessenger, IntelliJIde, IdeProtocolClient)
|
||||
├── autocomplete/ # Code completion logic
|
||||
├── editor/ # Diff handling, inline edits
|
||||
├── toolWindow/ # Main UI panel
|
||||
├── services/ # Settings, plugin lifecycle
|
||||
├── actions/ # Keyboard shortcuts, menu actions
|
||||
├── protocol/ # Message type definitions
|
||||
└── constants/ # App constants, paths
|
||||
|
||||
src/main/resources/
|
||||
├── META-INF/plugin.xml # Plugin configuration
|
||||
└── webview/ # Embedded React UI assets
|
||||
```
|
||||
|
||||
## Core Files
|
||||
|
||||
- `IntelliJIde.kt`: Main IDE interface implementation
|
||||
- `CoreMessenger.kt`: Binary communication handler
|
||||
- `plugin.xml`: Plugin manifest and extension points
|
||||
- `build.gradle.kts`: Build configuration
|
||||
- `ContinuePluginService.kt`: Main service orchestrator
|
||||
|
||||
## Message Protocol
|
||||
|
||||
JSON messages between Extension ↔ Core ↔ GUI. Message types in `constants/MessageTypes.kt`. Extension relays messages between core binary and webview.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests: `src/test/kotlin/`
|
||||
- E2E tests: UI automation with intellij-ui-test-robot
|
||||
- Test command: `./gradlew test`
|
||||
- Debug: `runIde` Gradle task
|
||||
|
||||
## Key Integration Points
|
||||
|
||||
- File operations via IntelliJ VFS
|
||||
- Editor integration for diffs/autocomplete
|
||||
- Git operations for repository context
|
||||
- Settings via IntelliJ platform storage
|
||||
|
|
@ -169,7 +169,11 @@ class ApplyToFileHandler(
|
|||
ide: IDE,
|
||||
params: ApplyToFileParams
|
||||
) {
|
||||
val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath)
|
||||
val editorUtils = if (EditorUtils.editorFileExist(params.filepath))
|
||||
EditorUtils.getOrOpenEditor(project, params.filepath)
|
||||
else
|
||||
EditorUtils.getEditorByCreateFile(project, params.filepath)
|
||||
|
||||
val diffStreamService = project.getService(DiffStreamService::class.java)
|
||||
|
||||
val handler = ApplyToFileHandler(
|
||||
|
|
|
|||
|
|
@ -356,7 +356,7 @@ class IdeProtocolClient(
|
|||
dataElement.toString(),
|
||||
GetSearchResultsParams::class.java
|
||||
)
|
||||
val results = ide.getSearchResults(params.query)
|
||||
val results = ide.getSearchResults(params.query, params.maxResults)
|
||||
respond(results)
|
||||
}
|
||||
|
||||
|
|
@ -365,7 +365,7 @@ class IdeProtocolClient(
|
|||
dataElement.toString(),
|
||||
GetFileResultsParams::class.java
|
||||
)
|
||||
val results = ide.getFileResults(params.pattern)
|
||||
val results = ide.getFileResults(params.pattern, params.maxResults)
|
||||
respond(results)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -315,11 +315,11 @@ class IntelliJIDE(
|
|||
return getOpenFiles()
|
||||
}
|
||||
|
||||
override suspend fun getFileResults(pattern: String): List<String> {
|
||||
override suspend fun getFileResults(pattern: String, maxResults: Int?): List<String> {
|
||||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
try {
|
||||
val command = GeneralCommandLine(
|
||||
var commandArgs = mutableListOf<String>(
|
||||
ripgrep,
|
||||
"--files",
|
||||
"--iglob",
|
||||
|
|
@ -327,8 +327,14 @@ class IntelliJIDE(
|
|||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
".gitignore"
|
||||
)
|
||||
if (maxResults != null) {
|
||||
commandArgs.add("--max-count")
|
||||
commandArgs.add(maxResults.toString())
|
||||
}
|
||||
|
||||
val command = GeneralCommandLine(commandArgs)
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
val results = ExecUtil.execAndGetOutput(command).stdout
|
||||
|
|
@ -344,11 +350,11 @@ class IntelliJIDE(
|
|||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
}
|
||||
}
|
||||
override suspend fun getSearchResults(query: String): String {
|
||||
override suspend fun getSearchResults(query: String, maxResults: Int?): String {
|
||||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
try {
|
||||
val command = GeneralCommandLine(
|
||||
val commandArgs = mutableListOf(
|
||||
ripgrep,
|
||||
"-i",
|
||||
"--ignore-file",
|
||||
|
|
@ -357,11 +363,21 @@ class IntelliJIDE(
|
|||
".gitignore",
|
||||
"-C",
|
||||
"2",
|
||||
"--heading",
|
||||
"-e",
|
||||
query,
|
||||
"."
|
||||
"--heading"
|
||||
)
|
||||
|
||||
// Conditionally add maxResults flag
|
||||
if (maxResults != null) {
|
||||
commandArgs.add("-m")
|
||||
commandArgs.add(maxResults.toString())
|
||||
}
|
||||
|
||||
// Add the search query and path
|
||||
commandArgs.add("-e")
|
||||
commandArgs.add(query)
|
||||
commandArgs.add(".")
|
||||
|
||||
val command = GeneralCommandLine(commandArgs)
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
return ExecUtil.execAndGetOutput(command).stdout
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.editor
|
|||
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.runWriteAction
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
|
|
@ -14,6 +15,8 @@ import com.intellij.openapi.util.TextRange
|
|||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.ui.JBColor
|
||||
import com.intellij.openapi.editor.ScrollType
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Utility class for working with Editor instances.
|
||||
|
|
@ -166,5 +169,38 @@ class EditorUtils(val editor: Editor) {
|
|||
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
|
||||
return EditorUtils(editor)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets editor for the filepath is existed
|
||||
*/
|
||||
fun editorFileExist(filepath: String?): Boolean {
|
||||
return !filepath.isNullOrEmpty() && VirtualFileManager.getInstance().findFileByUrl(filepath) != null
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets editor for the no exist filepath and returns an EditorUtils instance
|
||||
*/
|
||||
fun getEditorByCreateFile(project: Project, filepath: String?): EditorUtils? {
|
||||
if (!filepath.isNullOrEmpty()) {
|
||||
// file not exists and create
|
||||
val ioFile = File(filepath.replace("file:///", ""))
|
||||
if (!ioFile.exists()) {
|
||||
ioFile.parentFile?.mkdirs()
|
||||
ioFile.createNewFile()
|
||||
}
|
||||
// IntelliJ refresh VirtualFile
|
||||
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile)
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
runWriteAction {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
|
||||
return EditorUtils(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,9 +21,9 @@ typealias OpenUrlParam = String
|
|||
|
||||
typealias getTagsParams = String
|
||||
|
||||
data class GetSearchResultsParams(val query: String)
|
||||
data class GetSearchResultsParams(val query: String, val maxResults: Int?)
|
||||
|
||||
data class GetFileResultsParams(val pattern: String)
|
||||
data class GetFileResultsParams(val pattern: String, val maxResults: Int?)
|
||||
|
||||
data class SaveFileParams(val filepath: String)
|
||||
|
||||
|
|
|
|||
|
|
@ -157,9 +157,9 @@ interface IDE {
|
|||
|
||||
suspend fun getPinnedFiles(): List<String>
|
||||
|
||||
suspend fun getSearchResults(query: String): String
|
||||
suspend fun getSearchResults(query: String, maxResults: Int?): String
|
||||
|
||||
suspend fun getFileResults(pattern: String): List<String>
|
||||
suspend fun getFileResults(pattern: String, maxResults: Int?): List<String>
|
||||
|
||||
// Note: This should be a `Pair<String, String>` but we use `List<Any>` because the keys of `Pair`
|
||||
// will serialize to `first and `second` rather than `0` and `1` like in JavaScript
|
||||
|
|
@ -239,7 +239,7 @@ data class StreamDiffLinesPayload(
|
|||
)
|
||||
|
||||
data class AcceptOrRejectDiffPayload(
|
||||
val filepath: String,
|
||||
val filepath: String? = null,
|
||||
val streamId: String? = null
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -2144,6 +2144,29 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["search"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"maxResults": {
|
||||
"title": "Max Results",
|
||||
"description": "The maximum number of results to return",
|
||||
"default": 200,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -30,14 +30,14 @@ export class AutocompleteActions {
|
|||
expect(ghostText1).to.equal(messagePair1.llmResponse);
|
||||
}
|
||||
|
||||
public static async forceCompletion(editor: TextEditor): Promise<string> {
|
||||
public static async forceCompletion(editor: TextEditor): Promise<string> {
|
||||
await editor.setText("def main():\n ");
|
||||
await editor.moveCursor(2, 5);
|
||||
|
||||
await new Workbench().executeCommand("Continue: Force Autocomplete");
|
||||
|
||||
const ghostText = await TestUtils.waitForSuccess(() =>
|
||||
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver)
|
||||
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver),
|
||||
);
|
||||
|
||||
return ghostText;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.49",
|
||||
"version": "1.1.50",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
6
extensions/vscode/rules.md
Normal file
6
extensions/vscode/rules.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
The `extensions/vscode` folder contains code for the "Continue" VS Code Extension. Continue is a coding assistant extension which extends IDE functionality with AI.
|
||||
Core IDE functionality, such as reading files, is implemented using the `VSCodeIDE` class. Code to enable editing/diff streaming into the editor, code suggestion autocompletion, and more can also be found in this directory.
|
||||
Shared code that has abstract logic for the extension is in `core/`. Avoid importing code from `core/` directly where possible. Core is designed to be bundalable as a binary. Use `core.invoke` to send messages to the
|
||||
|
||||
- see `core/protocol/core.ts` for a list of commands VS Code can post/request to Core
|
||||
- see `core/portocol/ide.ts` for a list of commands/message types core can post/request to VS Code
|
||||
|
|
@ -433,8 +433,10 @@ class VsCodeIde implements IDE {
|
|||
});
|
||||
}
|
||||
|
||||
async getFileResults(pattern: string): Promise<string[]> {
|
||||
const MAX_FILE_RESULTS = 200;
|
||||
async getFileResults(
|
||||
pattern: string,
|
||||
maxResults?: number,
|
||||
): Promise<string[]> {
|
||||
if (vscode.env.remoteName) {
|
||||
// TODO better tests for this remote search implementation
|
||||
// throw new Error("Ripgrep not supported, this workspace is remote");
|
||||
|
|
@ -501,7 +503,7 @@ class VsCodeIde implements IDE {
|
|||
const results = await vscode.workspace.findFiles(
|
||||
pattern,
|
||||
ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
|
||||
MAX_FILE_RESULTS,
|
||||
maxResults,
|
||||
);
|
||||
return results.map((result) => vscode.workspace.asRelativePath(result));
|
||||
} else {
|
||||
|
|
@ -515,16 +517,24 @@ class VsCodeIde implements IDE {
|
|||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
...(maxResults ? ["--max-count", String(maxResults)] : []),
|
||||
]);
|
||||
|
||||
results.push(dirResults);
|
||||
}
|
||||
|
||||
return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS);
|
||||
const allResults = results.join("\n").split("\n");
|
||||
if (maxResults) {
|
||||
// In the case of multiple workspaces, maxResults will be applied to each workspace
|
||||
// And then the combined results will also be truncated
|
||||
return allResults.slice(0, maxResults);
|
||||
} else {
|
||||
return allResults;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getSearchResults(query: string): Promise<string> {
|
||||
async getSearchResults(query: string, maxResults?: number): Promise<string> {
|
||||
if (vscode.env.remoteName) {
|
||||
throw new Error("Ripgrep not supported, this workspace is remote");
|
||||
}
|
||||
|
|
@ -539,6 +549,7 @@ class VsCodeIde implements IDE {
|
|||
"-C",
|
||||
"2", // Show 2 lines of context
|
||||
"--heading", // Only show filepath once per result
|
||||
...(maxResults ? ["-m", maxResults.toString()] : []),
|
||||
"-e",
|
||||
query, // Pattern to search for
|
||||
".", // Directory to search in
|
||||
|
|
@ -547,7 +558,20 @@ class VsCodeIde implements IDE {
|
|||
results.push(dirResults);
|
||||
}
|
||||
|
||||
return results.join("\n");
|
||||
const allResults = results.join("\n");
|
||||
if (maxResults) {
|
||||
// In case of multiple workspaces, do max results per workspace and then truncate to maxResults
|
||||
// Will prioritize first workspace results, fine for now
|
||||
// Results are separated by either ./ or --
|
||||
const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g));
|
||||
if (matches.length > maxResults) {
|
||||
return allResults.substring(0, matches[maxResults].index);
|
||||
} else {
|
||||
return allResults;
|
||||
}
|
||||
} else {
|
||||
return allResults;
|
||||
}
|
||||
}
|
||||
|
||||
async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
|
|||
import { getUriPathBasename } from "core/util/uri";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { ApplyAbortManager } from "core/edit/applyAbortManager";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
|
@ -116,11 +117,16 @@ export class ApplyManager {
|
|||
return;
|
||||
}
|
||||
|
||||
const fileUri = editor.document.uri.toString();
|
||||
const abortManager = ApplyAbortManager.getInstance();
|
||||
const abortController = abortManager.get(fileUri);
|
||||
|
||||
const { isInstantApply, diffLinesGenerator } = await applyCodeBlock(
|
||||
editor.document.getText(),
|
||||
text,
|
||||
getUriPathBasename(editor.document.uri.toString()),
|
||||
getUriPathBasename(fileUri),
|
||||
llm,
|
||||
abortController,
|
||||
);
|
||||
|
||||
if (isInstantApply) {
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import {
|
|||
type AutocompleteOutcome,
|
||||
} from "core/autocomplete/util/types";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants";
|
||||
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
|
||||
// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants";
|
||||
// import { NextEditProvider } from "core/nextEdit/NextEditProvider";
|
||||
import * as URI from "uri-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
|
|
@ -55,9 +55,9 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
private completionProvider: CompletionProvider;
|
||||
private nextEditProvider: NextEditProvider;
|
||||
private recentlyVisitedRanges: RecentlyVisitedRangesService;
|
||||
private recentlyEditedTracker: RecentlyEditedTracker;
|
||||
// private nextEditProvider: NextEditProvider;
|
||||
public recentlyVisitedRanges: RecentlyVisitedRangesService;
|
||||
public recentlyEditedTracker: RecentlyEditedTracker;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
} from "./autocomplete/statusBar";
|
||||
import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider";
|
||||
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
|
||||
import { processDiff } from "./diff/processDiff";
|
||||
import { VerticalDiffManager } from "./diff/vertical/manager";
|
||||
import EditDecorationManager from "./quickEdit/EditDecorationManager";
|
||||
import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick";
|
||||
|
|
@ -86,56 +87,6 @@ function hideGUI() {
|
|||
}
|
||||
}
|
||||
|
||||
async function processDiff(
|
||||
action: "accept" | "reject",
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
ide: VsCodeIde,
|
||||
core: Core,
|
||||
verticalDiffManager: VerticalDiffManager,
|
||||
newFileUri?: string,
|
||||
streamId?: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
captureCommandTelemetry(`${action}Diff`);
|
||||
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
|
||||
let newOrCurrentUri = newFileUri;
|
||||
if (!newOrCurrentUri) {
|
||||
newOrCurrentUri = currentFile?.path;
|
||||
}
|
||||
if (!newOrCurrentUri) {
|
||||
console.warn(
|
||||
`No file provided or current file open while attempting to resolve diff`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await ide.openFile(newOrCurrentUri);
|
||||
|
||||
// Clear vertical diffs depending on action
|
||||
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
|
||||
if (action === "reject") {
|
||||
core.invoke("cancelApply", undefined);
|
||||
}
|
||||
|
||||
if (streamId) {
|
||||
const fileContent = await ide.readFile(newOrCurrentUri);
|
||||
|
||||
await sidebar.webviewProtocol.request("updateApplyState", {
|
||||
fileContent,
|
||||
filepath: newOrCurrentUri,
|
||||
streamId,
|
||||
status: "closed",
|
||||
numDiffs: 0,
|
||||
toolCallId,
|
||||
});
|
||||
}
|
||||
|
||||
// Save the file
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
}
|
||||
|
||||
function waitForSidebarReady(
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
timeout: number,
|
||||
|
|
@ -226,8 +177,9 @@ const getCommandsMap: (
|
|||
}
|
||||
|
||||
return {
|
||||
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) =>
|
||||
processDiff(
|
||||
"continue.acceptDiff": async (newFileUri?: string, streamId?: string) => {
|
||||
captureCommandTelemetry("acceptDiff");
|
||||
void processDiff(
|
||||
"accept",
|
||||
sidebar,
|
||||
ide,
|
||||
|
|
@ -235,10 +187,12 @@ const getCommandsMap: (
|
|||
verticalDiffManager,
|
||||
newFileUri,
|
||||
streamId,
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
|
||||
processDiff(
|
||||
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) => {
|
||||
captureCommandTelemetry("rejectDiff");
|
||||
void processDiff(
|
||||
"reject",
|
||||
sidebar,
|
||||
ide,
|
||||
|
|
@ -246,7 +200,8 @@ const getCommandsMap: (
|
|||
verticalDiffManager,
|
||||
newFileUri,
|
||||
streamId,
|
||||
),
|
||||
);
|
||||
},
|
||||
"continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
|
||||
captureCommandTelemetry("acceptVerticalDiffBlock");
|
||||
verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index);
|
||||
|
|
|
|||
52
extensions/vscode/src/diff/processDiff.ts
Normal file
52
extensions/vscode/src/diff/processDiff.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { Core } from "core/core";
|
||||
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VerticalDiffManager } from "./vertical/manager";
|
||||
|
||||
export async function processDiff(
|
||||
action: "accept" | "reject",
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
ide: VsCodeIde,
|
||||
core: Core,
|
||||
verticalDiffManager: VerticalDiffManager,
|
||||
newFileUri?: string,
|
||||
streamId?: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
let newOrCurrentUri = newFileUri;
|
||||
if (!newOrCurrentUri) {
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
newOrCurrentUri = currentFile?.path;
|
||||
}
|
||||
if (!newOrCurrentUri) {
|
||||
console.warn(
|
||||
`No file provided or current file open while attempting to resolve diff`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await ide.openFile(newOrCurrentUri);
|
||||
|
||||
// Clear vertical diffs depending on action
|
||||
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
|
||||
if (action === "reject") {
|
||||
// this is so that IDE reject diff command can also cancel apply
|
||||
core.invoke("cancelApply", undefined);
|
||||
}
|
||||
|
||||
if (streamId) {
|
||||
const fileContent = await ide.readFile(newOrCurrentUri);
|
||||
|
||||
await sidebar.webviewProtocol.request("updateApplyState", {
|
||||
fileContent,
|
||||
filepath: newOrCurrentUri,
|
||||
streamId,
|
||||
status: "closed",
|
||||
numDiffs: 0,
|
||||
toolCallId,
|
||||
});
|
||||
}
|
||||
|
||||
// Save the file
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager";
|
|||
import { handleLLMError } from "../../util/errorHandling";
|
||||
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
|
||||
|
||||
import { ApplyAbortManager } from "core/edit/applyAbortManager";
|
||||
import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler";
|
||||
|
||||
export interface VerticalDiffCodeLens {
|
||||
|
|
@ -437,6 +438,9 @@ export class VerticalDiffManager {
|
|||
|
||||
this.editDecorationManager.clear();
|
||||
|
||||
const abortManager = ApplyAbortManager.getInstance();
|
||||
const abortController = abortManager.get(fileUri);
|
||||
|
||||
try {
|
||||
const streamedLines: string[] = [];
|
||||
|
||||
|
|
@ -451,7 +455,7 @@ export class VerticalDiffManager {
|
|||
language: getMarkdownLanguageTagForFile(fileUri),
|
||||
onlyOneInsertion: !!onlyOneInsertion,
|
||||
overridePrompt,
|
||||
abortControllerId: fileUri,
|
||||
abortController,
|
||||
});
|
||||
|
||||
for await (const line of stream) {
|
||||
|
|
@ -467,6 +471,10 @@ export class VerticalDiffManager {
|
|||
// enable a listener for user edits to file while diff is open
|
||||
this.enableDocumentChangeListener();
|
||||
|
||||
if (abortController.signal.aborted) {
|
||||
vscode.commands.executeCommand("continue.rejectDiff");
|
||||
}
|
||||
|
||||
return `${prefix}${streamedLines.join("\n")}${suffix}`;
|
||||
} catch (e) {
|
||||
this.disableDocumentChangeListener();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import fs from "fs";
|
||||
|
||||
import { IContextProvider, RangeInFileWithContentsAndEdit } from "core";
|
||||
import { IContextProvider, Position, RangeInFileWithNextEditInfo } from "core";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
import { EXTENSION_NAME, getControlPlaneEnv } from "core/control-plane/env";
|
||||
import { Core } from "core/core";
|
||||
|
|
@ -41,9 +41,12 @@ import { VsCodeIde } from "../VsCodeIde";
|
|||
import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider";
|
||||
import { VsCodeMessenger } from "./VsCodeMessenger";
|
||||
|
||||
import { AutocompleteCodeSnippet } from "core/autocomplete/snippets/types";
|
||||
import { RecentlyEditedRange } from "core/autocomplete/util/types";
|
||||
import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
|
||||
import { llmFromProviderAndOptions } from "core/llm/llms";
|
||||
import setupNextEditWindowManager from "../activation/NextEditWindowManager";
|
||||
import { getDefinitionsFromLsp } from "../autocomplete/lsp";
|
||||
import { VsCodeIdeUtils } from "../util/ideUtils";
|
||||
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
|
|
@ -65,7 +68,7 @@ export class VsCodeExtension {
|
|||
private workOsAuthProvider: WorkOsAuthProvider;
|
||||
private fileSearch: FileSearch;
|
||||
private uriHandler = new UriEventHandler();
|
||||
private _editDebounceTimer: NodeJS.Timeout | null = null;
|
||||
private completionProvider: ContinueCompletionProvider;
|
||||
|
||||
constructor(context: vscode.ExtensionContext) {
|
||||
// Register auth provider
|
||||
|
|
@ -182,14 +185,15 @@ export class VsCodeExtension {
|
|||
setupStatusBar(
|
||||
enabled ? StatusBarStatus.Enabled : StatusBarStatus.Disabled,
|
||||
);
|
||||
this.completionProvider = new ContinueCompletionProvider(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.sidebar.webviewProtocol,
|
||||
);
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerInlineCompletionItemProvider(
|
||||
[{ pattern: "**" }],
|
||||
new ContinueCompletionProvider(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.sidebar.webviewProtocol,
|
||||
),
|
||||
this.completionProvider,
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -289,34 +293,64 @@ export class VsCodeExtension {
|
|||
|
||||
vscode.workspace.onDidChangeTextDocument(async (event) => {
|
||||
const changes = event.contentChanges;
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
|
||||
if (event.contentChanges.length === 0) {
|
||||
if (!config?.experimental?.logEditingData) return;
|
||||
if (!editor) return;
|
||||
if (event.contentChanges.length === 0) return;
|
||||
|
||||
// Ensure that loggin will only happen in the open-source continue repo
|
||||
const workspaceFolder = vscode.workspace.getWorkspaceFolder(
|
||||
event.document.uri,
|
||||
);
|
||||
if (!workspaceFolder) {
|
||||
return;
|
||||
}
|
||||
|
||||
// OPTIMIZATION: Debounce rapid keystrokes
|
||||
// This prevents sending too many edit events during fast typing
|
||||
if (this._editDebounceTimer) {
|
||||
clearTimeout(this._editDebounceTimer);
|
||||
const workspaceDirUri = workspaceFolder.uri.toString();
|
||||
const repoName = await this.ide.getRepoName(workspaceDirUri);
|
||||
if (repoName !== "continuedev/continue") return;
|
||||
|
||||
const activeCursorPos = editor.selection.active;
|
||||
const editActions: RangeInFileWithNextEditInfo[] = changes.map(
|
||||
(change) => ({
|
||||
filepath: event.document.uri.toString(),
|
||||
range: {
|
||||
start: change.range.start as Position,
|
||||
end: change.range.end as Position,
|
||||
},
|
||||
fileContents: event.document.getText(),
|
||||
editText: change.text,
|
||||
|
||||
// whichever side of the range isn't the active cursor pos is the previous one
|
||||
beforeCursorPos: (change.range.start.line === activeCursorPos.line &&
|
||||
change.range.start.character === activeCursorPos.character
|
||||
? change.range.end
|
||||
: change.range.start) as Position,
|
||||
|
||||
afterCursorPos: activeCursorPos as Position,
|
||||
workspaceDir: workspaceDirUri,
|
||||
}),
|
||||
);
|
||||
|
||||
let recentlyEditedRanges: RecentlyEditedRange[] = [];
|
||||
let recentlyVisitedRanges: AutocompleteCodeSnippet[] = [];
|
||||
|
||||
if (this.completionProvider) {
|
||||
recentlyEditedRanges =
|
||||
await this.completionProvider.recentlyEditedTracker.getRecentlyEditedRanges();
|
||||
recentlyVisitedRanges =
|
||||
this.completionProvider.recentlyVisitedRanges.getSnippets();
|
||||
}
|
||||
|
||||
this._editDebounceTimer = setTimeout(() => {
|
||||
const editActions: RangeInFileWithContentsAndEdit[] = changes.map(
|
||||
(change) => ({
|
||||
filepath: event.document.uri.toString(),
|
||||
range: {
|
||||
start: change.range.start,
|
||||
end: change.range.end,
|
||||
},
|
||||
// OPTIMIZATION: Only get document text once
|
||||
fileContents: event.document.getText(),
|
||||
editText: change.text,
|
||||
}),
|
||||
);
|
||||
|
||||
// Use invoke without awaiting to prevent blocking
|
||||
this.core.invoke("files/smallEdit", { actions: editActions });
|
||||
}, 10); // Small delay to batch rapid edits
|
||||
this.core.invoke("files/smallEdit", {
|
||||
actions: editActions,
|
||||
configHandler: this.configHandler,
|
||||
getDefsFromLspFunction: getDefinitionsFromLsp,
|
||||
recentlyEditedRanges: recentlyEditedRanges,
|
||||
recentlyVisitedRanges: recentlyVisitedRanges,
|
||||
});
|
||||
});
|
||||
|
||||
vscode.workspace.onDidSaveTextDocument(async (event) => {
|
||||
|
|
|
|||
|
|
@ -321,10 +321,10 @@ export class VsCodeMessenger {
|
|||
await ide.runCommand(msg.data.command);
|
||||
});
|
||||
this.onWebviewOrCore("getSearchResults", async (msg) => {
|
||||
return ide.getSearchResults(msg.data.query);
|
||||
return ide.getSearchResults(msg.data.query, msg.data.maxResults);
|
||||
});
|
||||
this.onWebviewOrCore("getFileResults", async (msg) => {
|
||||
return ide.getFileResults(msg.data.pattern);
|
||||
return ide.getFileResults(msg.data.pattern, msg.data.maxResults);
|
||||
});
|
||||
this.onWebviewOrCore("subprocess", async (msg) => {
|
||||
return ide.subprocess(msg.data.command, msg.data.cwd);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"root": true,
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": ["@typescript-eslint", "eslint-plugin-react"],
|
||||
"plugins": ["@typescript-eslint", "eslint-plugin-react", "no-barrel-files"],
|
||||
"parserOptions": {
|
||||
"project": ["tsconfig.json", "tsconfig.node.json"]
|
||||
},
|
||||
|
|
@ -13,7 +13,8 @@
|
|||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn"
|
||||
"@typescript-eslint/no-floating-promises": "warn",
|
||||
"no-barrel-files/no-barrel-files": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
|
|
|
|||
13
gui/package-lock.json
generated
13
gui/package-lock.json
generated
|
|
@ -89,6 +89,7 @@
|
|||
"@vitest/ui": "^2.1.3",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"eslint": "^8",
|
||||
"eslint-plugin-no-barrel-files": "^1.2.1",
|
||||
"eslint-plugin-react": "^7.37.2",
|
||||
"jsdom": "^25.0.1",
|
||||
"postcss": "^8.4.21",
|
||||
|
|
@ -215,7 +216,7 @@
|
|||
},
|
||||
"../packages/config-yaml": {
|
||||
"name": "@continuedev/config-yaml",
|
||||
"version": "1.0.92",
|
||||
"version": "1.0.94",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -5282,6 +5283,16 @@
|
|||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-plugin-no-barrel-files": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/eslint-plugin-no-barrel-files/-/eslint-plugin-no-barrel-files-1.2.1.tgz",
|
||||
"integrity": "sha512-WoZ48JXa99yptWwWWAKmuKNgvgA6tpSol6Cf0GzXs2Lg/JdBqe+CF58Bf8saEpYJRA+6+cTzP90nI7U7zoy5IQ==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/utils": "^8.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-plugin-react": {
|
||||
"version": "7.37.2",
|
||||
"resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.2.tgz",
|
||||
|
|
|
|||
|
|
@ -98,6 +98,7 @@
|
|||
"@vitest/ui": "^2.1.3",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"eslint": "^8",
|
||||
"eslint-plugin-no-barrel-files": "^1.2.1",
|
||||
"eslint-plugin-react": "^7.37.2",
|
||||
"jsdom": "^25.0.1",
|
||||
"postcss": "^8.4.21",
|
||||
|
|
|
|||
51
gui/src/components/AssistantAndOrgListbox/AccountOption.tsx
Normal file
51
gui/src/components/AssistantAndOrgListbox/AccountOption.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import {
|
||||
ArrowRightEndOnRectangleIcon,
|
||||
UserCircleIcon as UserCircleIconOutline,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { ListboxOption, useFontSize } from "../ui";
|
||||
|
||||
interface AccountOptionProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function AccountOption({ onClose }: AccountOptionProps) {
|
||||
const { session, logout, login } = useAuth();
|
||||
const tinyFont = useFontSize(-4);
|
||||
|
||||
// No account option for on-prem deployments
|
||||
if (session && isOnPremSession(session)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleClick() {
|
||||
if (session) {
|
||||
logout();
|
||||
} else {
|
||||
await login(false);
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
|
||||
return (
|
||||
<ListboxOption
|
||||
value={session ? "log-out" : "sign-in"}
|
||||
fontSizeModifier={-2}
|
||||
className="border-border border-b px-2 py-1.5"
|
||||
onClick={handleClick}
|
||||
>
|
||||
<div
|
||||
className="text-description flex flex-row items-center"
|
||||
style={{ fontSize: tinyFont }}
|
||||
>
|
||||
{session ? (
|
||||
<ArrowRightEndOnRectangleIcon className="mr-1 h-3 w-3" />
|
||||
) : (
|
||||
<UserCircleIconOutline className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{session ? "Log out" : "Sign in"}
|
||||
</div>
|
||||
</ListboxOption>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue