diff --git a/.changes/extensions/intellij/0.0.72.md b/.changes/extensions/intellij/0.0.72.md new file mode 100644 index 000000000..2e8962e43 --- /dev/null +++ b/.changes/extensions/intellij/0.0.72.md @@ -0,0 +1,7 @@ +## 0.0.72 - 2024-10-04 +### Added +* Listen for changes to Intellij settings without requiring window reload +### Changed +* Updated tutorial file +### Fixed +* Fix ability to load config.ts in JetBrains IDEs diff --git a/.changes/unreleased/Added-20240927-142940.yaml b/.changes/unreleased/Added-20240927-142940.yaml new file mode 100644 index 000000000..3a2785783 --- /dev/null +++ b/.changes/unreleased/Added-20240927-142940.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved loading/accept/reject UI for apply +time: 2024-09-27T14:29:40.283176-07:00 diff --git a/.changes/unreleased/Added-20240927-143005.yaml b/.changes/unreleased/Added-20240927-143005.yaml new file mode 100644 index 000000000..4dafa06cb --- /dev/null +++ b/.changes/unreleased/Added-20240927-143005.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Polished chat sidebar, especially context dropdown +time: 2024-09-27T14:30:05.576347-07:00 diff --git a/.changes/unreleased/Added-20240929-095627.yaml b/.changes/unreleased/Added-20240929-095627.yaml new file mode 100644 index 000000000..ec21be676 --- /dev/null +++ b/.changes/unreleased/Added-20240929-095627.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Further prompt caching with Anthropic +time: 2024-09-29T09:56:27.946259-07:00 diff --git a/.changes/unreleased/Changed-20240923-160251.yaml b/.changes/unreleased/Changed-20240923-160251.yaml deleted file mode 100644 index 5cef25bab..000000000 --- a/.changes/unreleased/Changed-20240923-160251.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/intellij -kind: Changed -body: Updated tutorial file -time: 2024-09-23T16:02:51.918152-07:00 diff --git a/.changes/unreleased/Changed-20240929-095407.yaml b/.changes/unreleased/Changed-20240929-095407.yaml new file mode 100644 index 000000000..e6f87aac6 --- /dev/null +++ b/.changes/unreleased/Changed-20240929-095407.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved styling on "More" page +time: 2024-09-29T09:54:07.999324-07:00 diff --git a/.changes/unreleased/Fixed-20240927-142924.yaml b/.changes/unreleased/Fixed-20240927-142924.yaml new file mode 100644 index 000000000..9a799ee51 --- /dev/null +++ b/.changes/unreleased/Fixed-20240927-142924.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Fixed a number of apply bugs +time: 2024-09-27T14:29:24.69568-07:00 diff --git a/.changes/unreleased/Fixed-20240929-095525.yaml b/.changes/unreleased/Fixed-20240929-095525.yaml new file mode 100644 index 000000000..2774af39d --- /dev/null +++ b/.changes/unreleased/Fixed-20240929-095525.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Fixed autoscrolling behavior +time: 2024-09-29T09:55:25.835696-07:00 diff --git a/.github/workflows/auto-assign.yaml b/.github/workflows/auto-assign.yaml new file mode 100644 index 000000000..1dd452dae --- /dev/null +++ b/.github/workflows/auto-assign.yaml @@ -0,0 +1,20 @@ +name: Issue assignment + +on: + issues: + types: [opened] + pull_request: + types: [opened] + +jobs: + auto-assign: + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: "Auto-assign issue" + uses: pozil/auto-assign-issue@v2 + with: + repo-token: ${{ secrets.CI_GITHUB_TOKEN }} + assignees: sestinj,Patrick-Erichsen + numOfAssignee: 1 diff --git a/.gitignore b/.gitignore index 5f242c5ef..113c07c43 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,6 @@ Icon? .prompts/ .aider* -notes.md \ No newline at end of file +notes.md + +manual-testing-sandbox/Continue/.idea/vcs.xml \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index fbfae5c57..db326191f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,4 @@ extensions/vscode/continue_rc_schema.json **/.continueignore CHANGELOG.md -**/continue_tutorial.py \ No newline at end of file +**/continue_tutorial.py diff --git a/.prompts/test.prompt b/.prompts/test.prompt new file mode 100644 index 000000000..e2f5d8662 --- /dev/null +++ b/.prompts/test.prompt @@ -0,0 +1,19 @@ +temperature: 0.5 +maxTokens: 4096 +name: jest +description: Write Jest unit tests +--- + +You are an expert programmer + + +{{{ input }}} + +Write unit tests for the above selected code, following each of these instructions: +- Use `jest` +- Properly set up and tear down +- Include important edge cases +- The tests should be complete and sophisticated +- Give the tests just as chat output, don't edit any file +- Don't explain how to set up `jest` +- Write a single code block, making sure to label with the language being used (e.g. "```typscript") \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index f5c81180f..896793040 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,7 +12,7 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/gui", + "${workspaceFolder}/manual-testing-sandbox", "${workspaceFolder}/manual-testing-sandbox/test.js", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], diff --git a/.vscode/settings.json b/.vscode/settings.json index 41b357765..d07234a75 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -17,9 +17,9 @@ "**/binary": true, "binary/": false, "**/core/vendor/**": true, - "**/gui/dist": true + "**/gui/dist": true, + "**/extensions/vscode/gui/**": true, + "**/extensions/vscode/out/**": true }, - "eslint.workingDirectories": [ - "./core" - ] + "eslint.workingDirectories": ["./core"] } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a9ecb709e..c070f0bc1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,12 +68,18 @@ You can run the documentation server locally using either of the following metho #### Method 1: NPM Script -1. Open your terminal and navigate to the root directory of the project. +1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place. -2. Run the following command to start the documentation server: +2. Run the following command to install the necessary dependencies for the documentation server: ```bash - npm run start --prefix docs + npm install + ``` + +3. Run the following command to start the documentation server: + + ```bash + npm run start ``` #### Method 2: VS Code Task diff --git a/README.md b/README.md index 322dd50c4..9751d618d 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ ## Getting Started -Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started) +Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install) ## Contributing diff --git a/binary/package-lock.json b/binary/package-lock.json index 5f1410c1a..010492e82 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -74,6 +74,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/core/autocomplete/ast.ts b/core/autocomplete/ast.ts index 933ae76c0..139b22dbf 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/ast.ts @@ -2,6 +2,8 @@ import Parser from "web-tree-sitter"; import { RangeInFileWithContents } from "../commands/util.js"; import { getParserForFile } from "../util/treeSitter.js"; +export type AstPath = Parser.SyntaxNode[]; + export async function getAst( filepath: string, fileContents: string, @@ -23,7 +25,7 @@ export async function getAst( export async function getTreePathAtCursor( ast: Parser.Tree, cursorIndex: number, -): Promise { +): Promise { const path = [ast.rootNode]; while (path[path.length - 1].childCount > 0) { let foundChild = false; diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/charStream.test.ts index 7ab8923fc..b5504ad63 100644 --- a/core/autocomplete/charStream.test.ts +++ b/core/autocomplete/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "./charStream"; +import { stopAtStopTokens } from "./streamTransforms/charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index e3c887c82..d954c3f31 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -22,20 +22,18 @@ import { } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; -import { BracketMatchingService } from "./brackets.js"; + import AutocompleteLruCache from "./cache.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, - stopAtStopTokens, -} from "./charStream.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; +import { postprocessCompletion } from "./postprocessing.js"; +import { AutocompleteSnippet } from "./ranking.js"; +import { RecentlyEditedRange } from "./recentlyEdited.js"; +import { RootPathContextService } from "./services/RootPathContextService.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, @@ -44,15 +42,19 @@ import { stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, -} from "./lineStream.js"; -import { postprocessCompletion } from "./postprocessing.js"; -import { AutocompleteSnippet } from "./ranking.js"; -import { RecentlyEditedRange } from "./recentlyEdited.js"; +} from "./streamTransforms/lineStream.js"; import { getTemplateForModel } from "./templates.js"; import { GeneratorReuseManager } from "./util.js"; // @prettier-ignore import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; +import { BracketMatchingService } from "./services/BracketMatchingService.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; +import { + noFirstCharNewline, + onlyWhitespaceAfterEndOfLine, + stopAtStopTokens, +} from "./streamTransforms/charStream.js"; export interface AutocompleteInput { completionId: string; @@ -158,9 +160,14 @@ export class CompletionProvider { this.onError.bind(this), ); this.importDefinitionsService = new ImportDefinitionsService(this.ide); + this.rootPathContextService = new RootPathContextService( + this.importDefinitionsService, + this.ide, + ); } private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -542,6 +549,7 @@ export class CompletionProvider { llm.model, extrasSnippets, this.importDefinitionsService, + this.rootPathContextService, ); // If prefix is manually passed diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index cf5b07e44..f3d08ff5c 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,4 +1,3 @@ -import Parser from "web-tree-sitter"; import { RangeInFileWithContents } from "../commands/util.js"; import { TabAutocompleteOptions } from "../index.js"; @@ -7,8 +6,7 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; -import { getAst, getTreePathAtCursor } from "./ast.js"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; import { AutocompleteLanguageInfo, LANGUAGES, @@ -22,6 +20,8 @@ import { type AutocompleteSnippet, } from "./ranking.js"; import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; +import { RootPathContextService } from "./services/RootPathContextService.js"; export function languageForFilepath( filepath: string, @@ -32,7 +32,7 @@ export function languageForFilepath( const BLOCK_TYPES = ["body", "statement_block"]; function shouldCompleteMultilineAst( - treePath: Parser.SyntaxNode[], + treePath: AstPath, cursorLine: number, ): boolean { // If at the base of the file, do multiline @@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean { } async function shouldCompleteMultiline( - filepath: string, + treePath: AstPath | undefined, fullPrefix: string, fullSuffix: string, language: AutocompleteLanguageInfo, @@ -94,18 +94,6 @@ async function shouldCompleteMultiline( } // Use AST to determine whether to complete multiline - let treePath: Parser.SyntaxNode[] | undefined; - try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); - if (!ast) { - return true; - } - - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } catch (e) { - console.error("Failed to parse AST", e); - } - let completeMultiline = false; if (treePath) { const cursorLine = fullPrefix.split("\n").length - 1; @@ -127,6 +115,7 @@ export async function constructAutocompletePrompt( modelName: string, extraSnippets: AutocompleteSnippet[], importDefinitionsService: ImportDefinitionsService, + rootPathContextService: RootPathContextService, ): Promise<{ prefix: string; suffix: string; @@ -145,6 +134,17 @@ export async function constructAutocompletePrompt( ); const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); + // Calculate AST Path + let treePath: AstPath | undefined; + try { + const ast = await getAst(filepath, fullPrefix + fullSuffix); + if (ast) { + treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } + } catch (e) { + console.error("Failed to parse AST", e); + } + // Find external snippets let snippets: AutocompleteSnippet[] = []; @@ -215,6 +215,14 @@ export async function constructAutocompletePrompt( snippets.push(...importSnippets); } + if (options.useRootPathContext && treePath) { + const ctx = await rootPathContextService.getContextForPath( + filepath, + treePath, + ); + snippets.push(...ctx); + } + // Filter out empty snippets and ones that are already in the prefix/suffix snippets = snippets .map((snippet) => ({ ...snippet })) @@ -269,7 +277,7 @@ export async function constructAutocompletePrompt( suffix, useFim: true, completeMultiline: await shouldCompleteMultiline( - filepath, + treePath, fullPrefix, fullSuffix, language, diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index f5b4cffb0..be414098a 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -1,4 +1,4 @@ -import type { LineFilter } from "./lineStream.js"; +import { LineFilter } from "./streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; @@ -26,7 +26,7 @@ export const Python = { name: "Python", // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - topLevelKeywords: ["def", "class", "\"\"\"#"], + topLevelKeywords: ["def", "class", '"""#'], singleLineComment: "#", endOfLine: [], }; diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/lineStream.test.ts index df8cd1263..ace94eaa4 100644 --- a/core/autocomplete/lineStream.test.ts +++ b/core/autocomplete/lineStream.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import * as lineStream from "./lineStream"; +import * as lineStream from "./streamTransforms/lineStream"; describe("lineStream", () => { let mockFullStop: jest.Mock; diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing.ts index bc1961e69..cb3ada459 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing.ts @@ -1,6 +1,6 @@ import type { ILLM } from "../index.js"; import { longestCommonSubsequence } from "../util/lcs.js"; -import { lineIsRepeated } from "./lineStream.js"; +import { lineIsRepeated } from "./streamTransforms/lineStream.js"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index 51791794c..48e01d5ff 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -80,7 +80,7 @@ export function deduplicateSnippets( function mergeSnippetsByRange( snippets: Required[], ): Required[] { - if (snippets.length === 0) { + if (snippets.length <= 1) { return snippets; } diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/services/BracketMatchingService.ts similarity index 100% rename from core/autocomplete/brackets.ts rename to core/autocomplete/services/BracketMatchingService.ts diff --git a/core/autocomplete/ImportDefinitionsService.ts b/core/autocomplete/services/ImportDefinitionsService.ts similarity index 90% rename from core/autocomplete/ImportDefinitionsService.ts rename to core/autocomplete/services/ImportDefinitionsService.ts index a17e3a0c9..0df08f096 100644 --- a/core/autocomplete/ImportDefinitionsService.ts +++ b/core/autocomplete/services/ImportDefinitionsService.ts @@ -1,11 +1,11 @@ -import { IDE } from "../index.js"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { PrecalculatedLruCache } from "../util/LruCache.js"; +import { IDE } from "../.."; +import { RangeInFileWithContents } from "../../commands/util"; +import { PrecalculatedLruCache } from "../../util/LruCache"; import { TSQueryType, getParserForFile, getQueryForFile, -} from "../util/treeSitter.js"; +} from "../../util/treeSitter"; interface FileInfo { imports: { [key: string]: RangeInFileWithContents[] }; diff --git a/core/autocomplete/services/NearbyDefinitionsService.ts b/core/autocomplete/services/NearbyDefinitionsService.ts new file mode 100644 index 000000000..12d6f7947 --- /dev/null +++ b/core/autocomplete/services/NearbyDefinitionsService.ts @@ -0,0 +1,45 @@ +import { IDE, Location } from "../.."; +import { LANGUAGES } from "../languages"; +import { getSymbolsForSnippet } from "../ranking"; + +interface FileInfo { + filepath: string; +} + +export class NearbyDefinitionsService { + static N = 10; + + constructor(private readonly ide: IDE) {} + + async getDefinitionsForLine(filepath: string, line: number) { + const lineContent = await this.ide.readRangeInFile(filepath, { + start: { + line, + character: 0, + }, + end: { + line: line + 1, + character: 0, + }, + }); + + // Remove keywords + const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; + const symbols = Array.from(getSymbolsForSnippet(lineContent)) + .filter((s) => s.length > 0) + .filter((s) => !(lang && lang?.stopWords?.includes(s))); + + return Promise.all( + symbols.map((s) => { + const character = lineContent.indexOf(s); + const pos: Location = { + filepath, + position: { + line, + character, + }, + }; + }), + ); + } +} diff --git a/core/autocomplete/services/RootPathContextService.ts b/core/autocomplete/services/RootPathContextService.ts new file mode 100644 index 000000000..69426aab8 --- /dev/null +++ b/core/autocomplete/services/RootPathContextService.ts @@ -0,0 +1,129 @@ +import { createHash } from "crypto"; +import { LRUCache } from "lru-cache"; +import Parser from "web-tree-sitter"; +import { IDE } from "../.."; +import { getQueryForFile, TSQueryType } from "../../util/treeSitter"; +import { AstPath } from "../ast"; +import { AutocompleteSnippet } from "../ranking"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; + +export class RootPathContextService { + private cache = new LRUCache({ + max: 100, + }); + + constructor( + private readonly importDefinitionsService: ImportDefinitionsService, + private readonly ide: IDE, + ) {} + + private static getNodeId(node: Parser.SyntaxNode): string { + return `${node.startIndex}`; + } + + private static TYPES_TO_USE = new Set([ + "program", + "function_declaration", + "method_definition", + ]); + + /** + * Key comes from hash of parent key and node type and node id. + */ + private static keyFromNode( + parentKey: string, + astNode: Parser.SyntaxNode, + ): string { + return createHash("sha256") + .update(parentKey) + .update(astNode.type) + .update(RootPathContextService.getNodeId(astNode)) + .digest("hex"); + } + + private async getSnippetsForNode( + filepath: string, + node: Parser.SyntaxNode, + ): Promise { + const snippets: AutocompleteSnippet[] = []; + + let query: Parser.Query | undefined; + switch (node.type) { + case "program": + this.importDefinitionsService.get(filepath); + break; + case "function_declaration": + query = await getQueryForFile( + filepath, + TSQueryType.FunctionDeclaration, + ); + break; + case "method_definition": + query = await getQueryForFile(filepath, TSQueryType.MethodDefinition); + break; + case "function_definition": + query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition); + break; + case "method_declaration": + query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration); + break; + default: + break; + } + + if (!query) { + return snippets; + } + + await Promise.all( + query.matches(node).map(async (match) => { + const startPosition = match.captures[0].node.startPosition; + const endPosition = match.captures[0].node.endPosition; + const definitions = await this.ide.gotoDefinition({ + filepath, + position: { + line: endPosition.row, + character: endPosition.column, + }, + }); + const newSnippets = await Promise.all( + definitions.map(async (def) => ({ + ...def, + contents: await this.ide.readRangeInFile(def.filepath, def.range), + })), + ); + snippets.push(...newSnippets); + }), + ); + + return snippets; + } + + async getContextForPath( + filepath: string, + astPath: AstPath, + // cursorIndex: number, + ): Promise { + const snippets: AutocompleteSnippet[] = []; + + let parentKey = filepath; + for (const astNode of astPath.filter((node) => + RootPathContextService.TYPES_TO_USE.has(node.type), + )) { + const key = RootPathContextService.keyFromNode(parentKey, astNode); + + const foundInCache = this.cache.get(key); + const newSnippets = + foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); + snippets.push(...newSnippets); + + if (!foundInCache) { + this.cache.set(key, newSnippets); + } + + parentKey = key; + } + + return snippets; + } +} diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/streamTransforms/charStream.ts similarity index 100% rename from core/autocomplete/charStream.ts rename to core/autocomplete/streamTransforms/charStream.ts diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/streamTransforms/lineStream.ts similarity index 99% rename from core/autocomplete/lineStream.ts rename to core/autocomplete/streamTransforms/lineStream.ts index 4ba14e687..5990bbf3c 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/streamTransforms/lineStream.ts @@ -1,6 +1,6 @@ import { distance } from "fastest-levenshtein"; -import { DiffLine } from "../"; -import { LineStream } from "../diff/util"; +import { DiffLine } from "../.."; +import { LineStream } from "../../diff/util"; export type LineFilter = (args: { lines: LineStream; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index a3c3ed91c..5d26b0408 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -1,3 +1,4 @@ +import { ContextItemWithId, ILLM, SlashCommand } from "../../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, @@ -5,16 +6,15 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/lineStream"; +} from "../../autocomplete/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; -import { ContextItemWithId, ILLM, SlashCommand } from "../../"; import { stripImages } from "../../llm/images"; import { dedentAndGetCommonWhitespace, getMarkdownLanguageTagForFile, } from "../../util/"; import { - contextItemToRangeInFileWithContents, + ctxItemToRifWithContents, type RangeInFileWithContents, } from "../util"; @@ -250,7 +250,7 @@ const EditSlashCommand: SlashCommand = { } const rif: RangeInFileWithContents = - contextItemToRangeInFileWithContents(contextItemToEdit); + ctxItemToRifWithContents(contextItemToEdit); await ide.saveFile(rif.filepath); const fullFileContents = await ide.readFile(rif.filepath); diff --git a/core/commands/util.ts b/core/commands/util.ts index 931564839..a6be440e9 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -9,20 +9,29 @@ export interface RangeInFileWithContents { contents: string; } -export function contextItemToRangeInFileWithContents( +export function ctxItemToRifWithContents( item: ContextItemWithId, ): RangeInFileWithContents { - const lines = item.name.split("(")[1].split(")")[0].split("-"); + let startLine = 0; + let endLine = 0; + + const nameSplit = item.name.split("("); + + if (nameSplit.length > 1) { + const lines = nameSplit[1].split(")")[0].split("-"); + startLine = Number.parseInt(lines[0], 10); + endLine = Number.parseInt(lines[1], 10); + } const rif: RangeInFileWithContents = { filepath: item.uri?.value || "", range: { start: { - line: Number.parseInt(lines[0]), + line: startLine, character: 0, }, end: { - line: Number.parseInt(lines[1]), + line: endLine, character: 0, }, }, diff --git a/core/config/load.ts b/core/config/load.ts index 95fc73053..67982ecad 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -595,7 +595,24 @@ async function loadFullConfigNode( try { // Try config.ts first const configJsPath = getConfigJsPath(); - const module = await import(configJsPath); + let module: any; + + try { + module = await import(configJsPath); + } catch (e) { + console.log(e); + console.log( + "Could not load config.ts as absolute path, retrying as file url ...", + ); + try { + module = await import(`file://${configJsPath}`); + } catch (e) { + throw new Error("Could not load config.ts as file url either", { + cause: e, + }); + } + } + if (typeof require !== "undefined") { delete require.cache[require.resolve(configJsPath)]; } diff --git a/core/config/types.ts b/core/config/types.ts index c571b44df..dafbe588a 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -47,6 +47,7 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; engine?: string; apiVersion?: string; @@ -313,6 +314,7 @@ declare global { apiKey?: string; aiGatewaySlug?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; useLegacyCompletionsEndpoint?: boolean; @@ -341,8 +343,6 @@ declare global { watsonxProjectId?: string; watsonxStopToken?: string; watsonxApiVersion?: string; - - cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -547,7 +547,8 @@ declare global { | "docs" | "gitlab-mr" | "os" - | "currentFile"; + | "currentFile" + | "greptile; type TemplateType = | "llama2" @@ -687,6 +688,11 @@ declare global { clientCertificate?: ClientCertificateOptions; } + export interface CacheBehavior { + cacheSystemMessage?: boolean; + cacheConversation?: boolean; + } + export interface ClientCertificateOptions { cert: string; key: string; @@ -749,6 +755,7 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; capabilities?: ModelCapability; + cacheBehavior?: CacheBehavior; } export type EmbeddingsProviderName = diff --git a/core/config/util.ts b/core/config/util.ts index 69e088a18..0247aa25d 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -29,7 +29,7 @@ export function addContextProvider(provider: ContextProviderWithParams) { }); } -export function addModel(model: ModelDescription) { +export function addModel(model: ModelDescription, role?: keyof ModelRoles) { editConfigJson((config) => { if (config.models?.some((m: any) => stringify(m) === stringify(model))) { return config; @@ -39,6 +39,18 @@ export function addModel(model: ModelDescription) { } config.models.push(model); + + // Set the role for the model + if (role) { + if (!config.experimental) { + config.experimental = {}; + } + if (!config.experimental.modelRoles) { + config.experimental.modelRoles = {}; + } + config.experimental.modelRoles[role] = model.title; + } + return config; }); } diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index be558c651..d1ac2d6e2 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -4,14 +4,14 @@ import { ContextProviderExtras, ContextSubmenuItem, LoadSubmenuItemsArgs, -} from "../../index.js"; -import { walkDir } from "../../indexing/walkDir.js"; +} from "../../"; +import { walkDir } from "../../indexing/walkDir"; import { getBasename, getUniqueFilePath, groupByLastNPathParts, -} from "../../util/index.js"; -import { BaseContextProvider } from "../index.js"; +} from "../../util/"; +import { BaseContextProvider } from "../"; const MAX_SUBMENU_ITEMS = 10_000; diff --git a/core/context/providers/GreptileContextProvider.ts b/core/context/providers/GreptileContextProvider.ts new file mode 100644 index 000000000..c6b7620c4 --- /dev/null +++ b/core/context/providers/GreptileContextProvider.ts @@ -0,0 +1,186 @@ +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + } from "../../index.js"; + import { BaseContextProvider } from "../index.js"; + import { execSync } from "child_process"; + import * as path from "path"; + import * as fs from "fs"; + + class GreptileContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "greptile", + displayTitle: "Greptile", + description: "Insert query to Greptile", + type: "query", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const greptileToken = this.getGreptileToken(); + if (!greptileToken) { + throw new Error("Greptile token not found."); + } + + const githubToken = this.getGithubToken(); + if (!githubToken) { + throw new Error("GitHub token not found."); + } + + let absPath = await this.getWorkspaceDir(extras); + if (!absPath) { + throw new Error("Failed to determine the workspace directory."); + } + + var remoteUrl = getRemoteUrl(absPath) + remoteUrl = getRemoteUrl(absPath); + const repoName = extractRepoName(remoteUrl); + const branch = getCurrentBranch(absPath); + const remoteType = getRemoteType(remoteUrl); + + if (!remoteType) { + throw new Error("Unable to determine remote type."); + } + + const options = { + method: 'POST', + headers: { + Authorization: `Bearer ${greptileToken}`, + 'X-GitHub-Token': githubToken, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [{ id: "", content: query, role: "user" }], + repositories: [{ + remote: remoteType, + branch: branch, + repository: repoName + }], + sessionId: extras.config.userToken || "default-session", + stream: false, + genius: true, + }), + }; + + try { + const response = await extras.fetch('https://api.greptile.com/v2/query', options); + const rawText = await response.text(); + + // Check for HTTP errors + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + // Parse the response as JSON + const json = JSON.parse(rawText); + + return json.sources.map((source: any) => ({ + description: source.filepath, + content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`, + name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "", + })); + } catch (error) { + console.error("Error getting context items from Greptile:", error); + throw new Error(`Error getting context items from Greptile`); + } + } + + private getGreptileToken(): string | undefined { + return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN; + } + + private getGithubToken(): string | undefined { + return this.options.GithubToken || process.env.GITHUB_TOKEN; + } + + private async getWorkspaceDir(extras: ContextProviderExtras): Promise { + try { + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + if (workspaceDirs && workspaceDirs.length > 0) { + return workspaceDirs[0]; + } else { + console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`); + } + } catch (err) { + console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`); + } + + // Fallback to using Git commands + try { + const currentDir = process.cwd(); + if (this.isGitRepository(currentDir)) { + const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim(); + return workspaceDir; + } else { + console.warn(`Current directory is not a Git repository: ${currentDir}`); + return null; + } + } catch (err) { + console.warn(`Failed to get workspace directory using Git commands: `); + return null; + } + } + + private isGitRepository(dir: string): boolean { + try { + const gitDir = path.join(dir, '.git'); + return fs.existsSync(gitDir); + } catch (err) { + console.warn(`Failed to check if directory is a Git repository:`); + return false; + } + } + } + + // Helper functions + function getRemoteUrl(absPath: string): string { + try { + const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim(); + return remote; + } catch (err) { + console.warn(`Failed to get remote URL`); + return ""; + } + } + + function getCurrentBranch(absPath: string): string { + try { + const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim(); + return branch; + } catch (err) { + console.warn(`Failed to get current branch`); + return "master"; // Default to 'master' if the current branch cannot be determined + } + } + + function extractRepoName(remote: string): string { + if (remote.startsWith("http://") || remote.startsWith("https://")) { + const parts = remote.split("/"); + if (parts.length >= 2) { + return parts[parts.length - 2] + "/" + parts[parts.length - 1].replace(".git", ""); + } + } else if (remote.startsWith("git@")) { + const parts = remote.split(":"); + if (parts.length >= 2) { + return parts[1].replace(".git", ""); + } + } + return ""; + } + + function getRemoteType(remote: string): string { + if (remote.includes("github.com")) { + return "github"; + } else if (remote.includes("gitlab.com")) { + return "gitlab"; + } else if (remote.includes("azure.com")) { + return "azure"; + } + return ""; + } + + export default GreptileContextProvider; + \ No newline at end of file diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 9c2ab4303..7ee2881be 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider"; import TerminalContextProvider from "./TerminalContextProvider"; import URLContextProvider from "./URLContextProvider"; import RepoMapContextProvider from "./RepoMapContextProvider"; +import GreptileContextProvider from "./GreptileContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -53,6 +54,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ URLContextProvider, ContinueProxyContextProvider, RepoMapContextProvider, + GreptileContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 9d19a33f7..2652bfa0f 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,12 +1,13 @@ +import path from "path"; import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; -import { getRelativePath } from "../../util/"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; -import path from "path"; + +const DEFAULT_N_FINAL = 25; export async function retrieveContextItemsFromEmbeddings( extras: ContextProviderExtras, @@ -43,7 +44,8 @@ export async function retrieveContextItemsFromEmbeddings( const contextLength = extras.llm.contextLength; const tokensPerSnippet = 512; const nFinal = - options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2); + options?.nFinal ?? + Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2); const useReranking = !!extras.reranker; const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 25ae3e962..acfe82cc9 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -21,7 +21,8 @@ export interface ControlPlaneModelDescription extends ModelDescription {} export const DEFAULT_CONTROL_PLANE_PROXY_URL = process.env.CONTROL_PLANE_ENV === "local" ? "http://localhost:3001/" - : "https://control-plane-proxy.continue.dev/"; + : "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/"; +// : "https://control-plane-proxy.continue.dev/"; export const CONTROL_PLANE_URL = process.env.CONTROL_PLANE_ENV === "local" diff --git a/core/core.ts b/core/core.ts index e9b29b493..ebd08f3bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -226,7 +226,7 @@ export class Core { // Edit config on("config/addModel", (msg) => { const model = msg.data.model; - addModel(model); + addModel(model, msg.data.role); void this.configHandler.reloadConfig(); }); diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index e3db3f280..7194c0083 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -154,4 +154,8 @@ describe("deterministicApplyLazyEdit(", () => { test("no lazy blocks in single top level class", async () => { await expectDiff("no-lazy-single-class.js"); }); + + test("should acknowledge jsx_expression lazy comments", async () => { + await expectDiff("migration-page.tsx"); + }); }); diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index aa03c086b..e9cbdf921 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -135,10 +135,10 @@ export async function deterministicApplyLazyEdit( } } - const acc: AstReplacements = []; - findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, acc); + const replacements: AstReplacements = []; + findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); - const newFullFile = reconstructNewFile(oldFile, newLazyFile, acc); + const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements); const diff = myersDiff(oldFile, newFullFile); // If the diff is too messy and seems likely borked, we fall back to LLM strategy @@ -155,9 +155,27 @@ export function isLazyLine(text: string): boolean { } function isLazyBlock(node: Parser.SyntaxNode): boolean { + // Special case for "{/* ... existing code ... */}" + if ( + node.type === "jsx_expression" && + node.namedChildCount === 1 && + isLazyBlock(node.namedChildren[0]) + ) { + return true; + } + return node.type.includes("comment") && isLazyLine(node.text); } +function stringsWithinLevDistThreshold( + a: string, + b: string, + threshold: number, +) { + const dist = distance(a, b); + return dist / Math.min(a.length, b.length) <= threshold; +} + /** * Determine whether two nodes are similar * @param a @@ -184,11 +202,23 @@ function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { return true; } + // Matching jsx_elements needs to be different because they have such a minimal first line + if ( + a.type === "jsx_element" && + b.type === "jsx_element" && + // Check that the tag names match + a.namedChildren[0]?.children[1]?.text === + b.namedChildren[0]?.children[1]?.text + ) { + if (stringsWithinLevDistThreshold(a.text, b.text, 0.3)) { + return true; + } + } + const lineOneA = a.text.split("\n")[0]; const lineOneB = b.text.split("\n")[0]; - const levDist = distance(lineOneA, lineOneB); - return levDist / Math.min(lineOneA.length, lineOneB.length) <= 0.2; + return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2); } function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { @@ -204,7 +234,7 @@ function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { function findLazyBlockReplacements( oldNode: Parser.SyntaxNode, newNode: Parser.SyntaxNode, - acc: AstReplacements, + replacements: AstReplacements, ): void { // Base case if (nodesAreExact(oldNode, newNode)) { @@ -254,7 +284,7 @@ function findLazyBlockReplacements( } // then recurse at the match - findLazyBlockReplacements(L, rightChildren[0], acc); + findLazyBlockReplacements(L, rightChildren[0], replacements); // then consume L and R leftChildren.shift(); @@ -263,7 +293,7 @@ function findLazyBlockReplacements( // Exit "lazy mode" if (isLazy) { // Record the replacement lines - acc.push({ + replacements.push({ nodeToReplace: currentLazyBlockNode!, replacementNodes: [...currentLazyBlockReplacementNodes], }); @@ -275,7 +305,7 @@ function findLazyBlockReplacements( } if (isLazy) { - acc.push({ + replacements.push({ nodeToReplace: currentLazyBlockNode!, replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren], }); @@ -284,7 +314,7 @@ function findLazyBlockReplacements( // Cut out any extraneous lazy blocks for (const R of rightChildren) { if (isLazyBlock(R)) { - acc.push({ + replacements.push({ nodeToReplace: R, replacementNodes: [], }); diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index ff6701251..b4b6164cc 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -2,7 +2,7 @@ import { ILLM } from "../.."; import { filterLeadingNewline, stopAtLines, -} from "../../autocomplete/lineStream"; +} from "../../autocomplete/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 24a369945..6dd9cef6d 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,7 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, stopAtLines, -} from "../../autocomplete/lineStream.js"; +} from "../../autocomplete/streamTransforms/lineStream"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; diff --git a/core/edit/lazy/test-examples/migration-page.tsx.diff b/core/edit/lazy/test-examples/migration-page.tsx.diff new file mode 100644 index 000000000..3ff1810c5 --- /dev/null +++ b/core/edit/lazy/test-examples/migration-page.tsx.diff @@ -0,0 +1,166 @@ +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ + + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + { + navigate("/"); + }} + disabled={false} + /> +
+ ); +} + +export default MigrationPage; + +--- + +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ + + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + {/* ... existing code ... */} +
+ ); +} + +export default MigrationPage; + +--- + +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +-

++

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +-

++

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +-

++

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ +- ++ + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + { + navigate("/"); + }} + disabled={false} + /> +
+ ); +} + +export default MigrationPage; \ No newline at end of file diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 8448262e1..cad33b3a2 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -5,7 +5,7 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/lineStream.js"; +} from "../autocomplete/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; import { diff --git a/core/index.d.ts b/core/index.d.ts index 659f9f80c..c1c8ddc04 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -70,6 +70,7 @@ export interface ILLM extends LLMOptions { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; engine?: string; apiVersion?: string; @@ -342,6 +343,7 @@ export interface LLMOptions { apiKey?: string; aiGatewaySlug?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; useLegacyCompletionsEndpoint?: boolean; @@ -371,8 +373,6 @@ export interface LLMOptions { watsonxStopToken?: string; watsonxApiVersion?: string; watsonxFullUrl?: string; - - cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -580,6 +580,7 @@ type ContextProviderName = | "gitlab-mr" | "os" | "currentFile" + | "greptile" | "outline" | "continue-proxy" | "highlights" @@ -729,6 +730,11 @@ export interface RequestOptions { clientCertificate?: ClientCertificateOptions; } +export interface CacheBehavior { + cacheSystemMessage?: boolean; + cacheConversation?: boolean; +} + export interface ClientCertificateOptions { cert: string; key: string; @@ -791,6 +797,7 @@ export interface ModelDescription { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; capabilities?: ModelCapability; + cacheBehavior?: CacheBehavior; } export type EmbeddingsProviderName = @@ -875,6 +882,7 @@ export interface TabAutocompleteOptions { recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; + useRootPathContext?: boolean; } export interface ContinueUIConfig { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 30e205c3b..9cba2d841 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -534,8 +534,12 @@ export default class DocsService { await table.delete(`title = '${mockRowTitle}'`); } - private removeInvalidLanceTableNameChars(tableName: string) { - return tableName.replace(/:/g, ""); + /** + * From Lance: Table names can only contain alphanumeric characters, + * underscores, hyphens, and periods + */ + private sanitizeLanceTableName(name: string) { + return name.replace(/[^a-zA-Z0-9_.-]/g, "_"); } private async getLanceTableNameFromEmbeddingsProvider( @@ -544,10 +548,10 @@ export default class DocsService { const embeddingsProvider = await this.getEmbeddingsProvider( isPreIndexedDoc, ); - const embeddingsProviderId = this.removeInvalidLanceTableNameChars( - embeddingsProvider.id, + + const tableName = this.sanitizeLanceTableName( + `${DocsService.lanceTableName}${embeddingsProvider.id}`, ); - const tableName = `${DocsService.lanceTableName}${embeddingsProviderId}`; return tableName; } diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index fd111e56b..93ad7b43d 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -68,6 +68,8 @@ export const DEFAULT_IGNORE_FILETYPES = [ "*.uasset", "*.pdb", "*.bin", + "*.pag", + "*.swp", // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index d339134e3..13d538be8 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -5,9 +5,10 @@ const SYSTEM_MESSAGE = `When generating new code: 1. Always produce a single code block. 2. Never separate the code into multiple code blocks. 3. Only include the code that is being added. -4. Replace existing code with a "lazy" block like this: "// ... existing code ..." -5. You must always provide 1-2 lines of context above and below a "lazy" block -6. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. +4. Replace existing code with a "lazy" comment like this: "// ... existing code ..." +5. The "lazy" comment must always be a valid comment in the current context (e.g. "" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.) +6. You must always provide 1-2 lines of context above and below a "lazy" comment +7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. Example 1: Input: diff --git a/core/llm/index.ts b/core/llm/index.ts index 336ded890..53c984b43 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,6 +1,7 @@ import { findLlmInfo } from "@continuedev/llm-info"; import Handlebars from "handlebars"; import { + CacheBehavior, ChatMessage, ChatMessageRole, CompletionOptions, @@ -102,6 +103,7 @@ export abstract class BaseLLM implements ILLM { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; engine?: string; @@ -120,8 +122,6 @@ export abstract class BaseLLM implements ILLM { watsonxApiVersion?: string; watsonxFullUrl?: string; - cacheSystemMessage?: boolean; - private _llmOptions: LLMOptions; constructor(_options: LLMOptions) { @@ -184,6 +184,7 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + this.cacheBehavior = options.cacheBehavior; // for watsonx only this.watsonxUrl = options.watsonxUrl; @@ -193,8 +194,6 @@ export abstract class BaseLLM implements ILLM { this.watsonxApiVersion = options.watsonxApiVersion; this.watsonxFullUrl = options.watsonxFullUrl; - this.cacheSystemMessage = options.cacheSystemMessage; - if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 654d50805..f2182d851 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -35,17 +35,40 @@ class Anthropic extends BaseLLM { } private _convertMessages(msgs: ChatMessage[]): any[] { - const messages = msgs - .filter((m) => m.role !== "system") - .map((message) => { + const filteredmessages = msgs.filter((m) => m.role !== "system") + const lastTwoUserMsgIndices = filteredmessages + .map((msg, index) => (msg.role === "user" ? index : -1)) + .filter((index) => index !== -1).slice(-2); + + const messages = filteredmessages.map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); + if (typeof message.content === "string") { - return message; + var chatMessage = { + ...message, + content: [{ + type: "text", + text: message.content, + ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) + }] + }; + return chatMessage; } + return { ...message, - content: message.content.map((part) => { + content: message.content.map((part, contentIdx) => { if (part.type === "text") { - return part; + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) + }; + return newpart; } return { type: "image", @@ -75,9 +98,7 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = - !!this.systemMessage && !!this.cacheSystemMessage; - + const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; const systemMessage: string = stripImages( messages.filter((m) => m.role === "system")[0]?.content, ); @@ -89,7 +110,7 @@ class Anthropic extends BaseLLM { Accept: "application/json", "anthropic-version": "2023-06-01", "x-api-key": this.apiKey as string, - ...(shouldCacheSystemMessage + ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation ? { "anthropic-beta": "prompt-caching-2024-07-31" } : {}), }, @@ -115,6 +136,7 @@ class Anthropic extends BaseLLM { } for await (const value of streamSse(response)) { + if (value.type == "message_start") console.log(value); if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index ce20b4ecc..be7d1c18c 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -1,8 +1,18 @@ -import { ModelProvider } from "../../index.js"; +import { LLMOptions, ModelProvider } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + + static defaultOptions: Partial = { + apiVersion: "2024-02-15-preview", + apiType: "azure", + }; + + constructor(options: LLMOptions) { + super(options); + this.engine = options.model; + } } export default Azure; diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 947e15e6f..9636dbc63 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -3,6 +3,7 @@ import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class HuggingFaceTGI extends BaseLLM { + private static MAX_STOP_TOKENS = 4; static providerName: ModelProvider = "huggingface-tgi"; static defaultOptions: Partial = { apiBase: "http://localhost:8080/", @@ -36,7 +37,10 @@ class HuggingFaceTGI extends BaseLLM { top_k: options.topK, presence_penalty: options.presencePenalty, frequency_penalty: options.frequencyPenalty, - stop: options.stop, + stop: options.stop?.slice( + 0, + this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS, + ), }; return finalOptions; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 3b16d0456..75e973219 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -15,6 +15,8 @@ class Ollama extends BaseLLM { model: "codellama-7b", }; + private fimSupported: boolean = false; + constructor(options: LLMOptions) { super(options); @@ -31,7 +33,7 @@ class Ollama extends BaseLLM { body: JSON.stringify({ name: this._getModel() }), }) .then(async (response) => { - if (response.status !== 200) { + if (response?.status !== 200) { // console.warn( // "Error calling Ollama /api/show endpoint: ", // await response.text(), @@ -70,6 +72,13 @@ class Ollama extends BaseLLM { } } } + + /** + * There is no API to get the model's FIM capabilities, so we have to + * make an educated guess. If a ".Suffix" variable appears in the template + * it's a good indication the model supports FIM. + */ + this.fimSupported = !!body?.template?.includes(".Suffix"); }) .catch((e) => { // console.warn("Error calling the Ollama /api/show endpoint: ", e); @@ -251,7 +260,7 @@ class Ollama extends BaseLLM { } supportsFim(): boolean { - return true; + return this.fimSupported; } protected async *_streamFim( diff --git a/core/package-lock.json b/core/package-lock.json index e00d854cf..fe1e4c48d 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -39,6 +39,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", @@ -1342,6 +1343,15 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, "node_modules/@babel/helper-compilation-targets/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -10481,12 +10491,11 @@ "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" }, "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "dependencies": { - "yallist": "^3.0.2" + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz", + "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==", + "engines": { + "node": "14 || >=16.14" } }, "node_modules/mac-ca": { diff --git a/core/package.json b/core/package.json index 0456836f6..b04da182b 100644 --- a/core/package.json +++ b/core/package.json @@ -69,6 +69,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 73f55946c..d5920ca81 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,5 +1,3 @@ -import type { AutocompleteInput } from "../autocomplete/completionProvider"; -import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -10,12 +8,15 @@ import type { LLMFullCompletionOptions, MessageContent, ModelDescription, + ModelRoles, PersistedSessionInfo, RangeInFile, SerializedContinueConfig, SessionInfo, SiteIndexingConfig, } from "../"; +import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; @@ -50,7 +51,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { "devdata/log": [{ tableName: string; data: any }, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ - { model: SerializedContinueConfig["models"][number] }, + { + model: SerializedContinueConfig["models"][number]; + role?: keyof ModelRoles; + }, void, ]; "config/newPromptFile": [undefined, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 393797f5d..43cacb733 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -97,4 +97,5 @@ export type ToWebviewOrCoreFromIdeProtocol = { { sessionInfo: ControlPlaneSessionInfo | undefined }, void, ]; + didChangeIdeSettings: [{ settings: IdeSettings }, void]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 8ccc6d007..774da7ee5 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -15,7 +15,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, ]; openUrl: [string, void]; - applyToCurrentFile: [{ text: string }, void]; + applyToCurrentFile: [{ text: string; streamId: string }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -32,6 +32,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { rejectDiff: [{ filepath: string }, void]; }; +export interface ApplyState { + streamId: string; + status: "streaming" | "done" | "closed"; +} + export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; setTTSActive: [boolean, void]; @@ -65,4 +70,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { incrementFtc: [undefined, void]; openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; + updateApplyState: [ApplyState, void]; }; diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts new file mode 100644 index 000000000..5f3c6a4be --- /dev/null +++ b/core/test/util/dedentAndGetCommonWhitespace.test.ts @@ -0,0 +1,76 @@ +// File generated by Continue +import { dedentAndGetCommonWhitespace } from "../../util"; + +describe("dedentAndGetCommonWhitespace", () => { + let originalString: string; + + beforeEach(() => { + // Setup any global variables or states if needed + originalString = " line1\n line2\n line3"; + }); + + afterEach(() => { + // Tear down any changes to global variables or states if needed + originalString = ""; + }); + + test("should dedent and return common whitespace for a simple case", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", " "]); + }); + + test("should handle empty string", () => { + const input = ""; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with only whitespace", () => { + const input = " "; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with mixed whitespace and content", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); + + test("should handle string with no common leading whitespace", () => { + const input = "line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([input, ""]); + }); + + test("should handle string with empty lines", () => { + const input = " line1\n\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\n\nline3", " "]); + }); + + test("should handle string with only empty lines", () => { + const input = "\n\n"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["\n\n", ""]); + }); + + test("should handle string with tabs as whitespace", () => { + const input = "\tline1\n\tline2\n\tline3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t"]); + }); + + test("should handle string with mixed tabs and spaces", () => { + const input = "\t line1\n\t line2\n\t line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t "]); + }); + + test("should handle string with different leading whitespace lengths", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); +}); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts new file mode 100644 index 000000000..ba72b4520 --- /dev/null +++ b/core/test/util/getLastNPathParts.test.ts @@ -0,0 +1,51 @@ +// File generated by Continue +import { getLastNPathParts } from "../../util"; + +describe("getLastNPathParts", () => { + const SEP_REGEX = /[\\/]+/; + + beforeAll(() => { + // Setup code if needed + }); + + afterAll(() => { + // Teardown code if needed + }); + + test("returns the last N parts of a filepath with forward slashes", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); + }); + + test("returns the last N parts of a filepath with backward slashes", () => { + const filepath = "C:\\home\\user\\documents\\project\\file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("returns the last part if N is 1", () => { + const filepath = "/home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); + }); + + test("returns the entire path if N is greater than the number of parts", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 10)).toBe( + "home/user/documents/project/file.txt", + ); + }); + + test("returns an empty string if N is 0", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 0)).toBe(""); + }); + + test("handles paths with mixed forward and backward slashes", () => { + const filepath = "home\\user/documents\\project/file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("handles edge case with empty filepath", () => { + const filepath = ""; + expect(getLastNPathParts(filepath, 2)).toBe(""); + }); +}); diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts new file mode 100644 index 000000000..da10cdf90 --- /dev/null +++ b/core/test/util/lcs.test.ts @@ -0,0 +1,40 @@ +// This file is generated by Continue +import { longestCommonSubsequence } from "../../util/lcs"; + +describe("longestCommonSubsequence", () => { + beforeAll(() => { + // Setup if needed + }); + + afterAll(() => { + // Teardown if needed + }); + + test("should return the longest common subsequence for non-empty strings", () => { + expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); + expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); + expect(longestCommonSubsequence("abc", "def")).toBe(""); + }); + + test("should handle cases where one or both strings are empty", () => { + expect(longestCommonSubsequence("", "abc")).toBe(""); + expect(longestCommonSubsequence("abc", "")).toBe(""); + expect(longestCommonSubsequence("", "")).toBe(""); + }); + + test("should handle cases with no common subsequence", () => { + expect(longestCommonSubsequence("abc", "def")).toBe(""); + expect(longestCommonSubsequence("xyz", "abc")).toBe(""); + }); + + test("should handle cases with special characters", () => { + expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); + expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); + }); + + test("should handle long strings efficiently", () => { + const str1 = "a".repeat(1000) + "b".repeat(1000); + const str2 = "a".repeat(1000) + "c".repeat(1000); + expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); + }); +}); diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts new file mode 100644 index 000000000..a39a5bc30 --- /dev/null +++ b/core/test/util/merge.test.ts @@ -0,0 +1,100 @@ +// File generated by Continue +import { mergeJson } from "../../util/merge"; + +describe("mergeJson", () => { + it("should merge two simple JSON objects", () => { + const first = { a: 1, b: 2 }; + const second = { b: 3, c: 4 }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: 3, c: 4 }); + }); + + it('should overwrite values when mergeBehavior is "overwrite"', () => { + const first = { a: 1, b: 2 }; + const second = { b: 3, c: 4 }; + const result = mergeJson(first, second, "overwrite"); + expect(result).toEqual({ a: 1, b: 3, c: 4 }); + }); + + it("should merge nested objects", () => { + const first = { a: { b: 1 } }; + const second = { a: { c: 2 } }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: { b: 1, c: 2 } }); + }); + + it("should merge arrays without mergeKeys", () => { + const first = { a: [1, 2] }; + const second = { a: [3, 4] }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: [1, 2, 3, 4] }); + }); + + it("should merge arrays with mergeKeys", () => { + const first = { + a: [ + { id: 1, value: "first" }, + { id: 2, value: "second" }, + ], + }; + const second = { + a: [ + { id: 2, value: "updated" }, + { id: 3, value: "third" }, + ], + }; + const mergeKeys = { + a: (item1: any, item2: any) => item1.id === item2.id, + }; + const result = mergeJson(first, second, undefined, mergeKeys); + expect(result).toEqual({ + a: [ + { id: 1, value: "first" }, + { id: 2, value: "updated" }, + { id: 3, value: "third" }, + ], + }); + }); + + it("should handle non-object values correctly", () => { + const first = { a: 1, b: "string", c: true }; + const second = { a: 2, b: "new string", c: false }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 2, b: "new string", c: false }); + }); + + it("should handle null and undefined values correctly", () => { + const first = { a: 1, b: null }; + const second = { b: 2, c: undefined }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: 2, c: undefined }); + }); + + it("should handle empty objects", () => { + const first = {}; + const second = { a: 1 }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1 }); + }); + + it("should handle empty second object", () => { + const first = { a: 1 }; + const second = {}; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1 }); + }); + + it("should handle errors gracefully", () => { + const first = { a: 1 }; + const second = { b: () => {} }; // Functions are not serializable in JSON + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: expect.any(Function) }); + }); + + it("should merge deeply nested objects", () => { + const first = { a: { b: { c: 1 } } }; + const second = { a: { b: { d: 2 } } }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: { b: { c: 1, d: 2 } } }); + }); +}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts new file mode 100644 index 000000000..e0a4df67a --- /dev/null +++ b/core/test/util/ranges/getRangeInString.test.ts @@ -0,0 +1,105 @@ +// This file is generated by Continue + +import { getRangeInString } from "../../../util/ranges"; + +describe.skip("getRangeInString", () => { + let content: string; + + beforeEach(() => { + content = `Line 1 +Line 2 +Line 3 +Line 4 +Line 5`; + }); + + afterEach(() => { + content = ""; + }); + + test("should return substring within the same line", () => { + const range = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 4 }, + }; + expect(getRangeInString(content, range)).toBe("Line"); + }); + + test("should return substring spanning multiple lines", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 3, character: 3 }, + }; + const expected = `ne 2 +Line 3 +Line 4`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle range that starts and ends at the same character", () => { + const range = { + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe("L"); + }); + + test("should handle range that spans entire content", () => { + const range = { + start: { line: 0, character: 0 }, + end: { line: 4, character: 5 }, + }; + expect(getRangeInString(content, range)).toBe(content); + }); + + test("should handle range that spans to the end of the last line", () => { + const range = { + start: { line: 3, character: 2 }, + end: { line: 4, character: 5 }, + }; + const expected = `ne 4 +Line 5`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle empty content", () => { + content = ""; + const range = { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start line > end line)", () => { + const range = { + start: { line: 3, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start character > end character on same line)", () => { + const range = { + start: { line: 1, character: 5 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle range that starts and ends at the same line but different characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 6 }, + }; + expect(getRangeInString(content, range)).toBe("ne 2"); + }); + + test("should handle range that starts and ends at the same line and same characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe("n"); + }); +}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts new file mode 100644 index 000000000..397dbc1a8 --- /dev/null +++ b/core/test/util/ranges/intersection.test.ts @@ -0,0 +1,123 @@ +// This file is generated by Continue + +import { intersection } from "../../../util/ranges"; + +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("intersection", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 4, character: 0 }, + }; + }); + + test("returns correct intersection for overlapping ranges", () => { + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 5 }, + }); + }); + + test("returns null for non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 3, character: 0 }, + end: { line: 4, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + // TODO + test.skip("returns correct intersection for single line overlap", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 2, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }); + }); + + test("returns null for single line non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 2 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + test("returns correct intersection when one range is fully within another", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 4, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }); + }); + + test("returns correct intersection when ranges touch at the edge", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 2, character: 0 }, + end: { line: 3, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }); + }); +}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts new file mode 100644 index 000000000..0468df1cd --- /dev/null +++ b/core/test/util/ranges/maxMinPosition.test.ts @@ -0,0 +1,70 @@ +import { maxPosition, minPosition } from "../../../util/ranges"; + +// This file is generated by Continue +interface Position { + line: number; + character: number; +} + +describe("Position comparison functions", () => { + let pos1: Position; + let pos2: Position; + let pos3: Position; + let pos4: Position; + + beforeAll(() => { + // Setup: Initializing positions + pos1 = { line: 1, character: 5 }; + pos2 = { line: 2, character: 3 }; + pos3 = { line: 1, character: 7 }; + pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality + }); + + describe("maxPosition", () => { + it("should return the position with the greater line number", () => { + expect(maxPosition(pos1, pos2)).toEqual(pos2); + }); + + it("should return the position with the greater character number when lines are equal", () => { + expect(maxPosition(pos1, pos3)).toEqual(pos3); + }); + + it("should return the first position when both positions are equal", () => { + expect(maxPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(maxPosition(posNegative, pos1)).toEqual(pos1); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); + }); + }); + + describe("minPosition", () => { + it("should return the position with the lesser line number", () => { + expect(minPosition(pos1, pos2)).toEqual(pos1); + }); + + it("should return the position with the lesser character number when lines are equal", () => { + expect(minPosition(pos1, pos3)).toEqual(pos1); + }); + + it("should return the first position when both positions are equal", () => { + expect(minPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(minPosition(posNegative, pos1)).toEqual(posNegative); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); + }); + }); +}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts new file mode 100644 index 000000000..9d06a97b4 --- /dev/null +++ b/core/test/util/ranges/union.test.ts @@ -0,0 +1,92 @@ +import { union } from "../../../util/ranges"; + +// This file is generated by Continue +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("union", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 3 }, + end: { line: 4, character: 2 }, + }; + }); + + test("should return the union of two overlapping ranges", () => { + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when ranges are identical", () => { + const result = union(rangeA, rangeA); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap but are adjacent", () => { + rangeB = { + start: { line: 3, character: 5 }, + end: { line: 4, character: 2 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when one range is completely within the other", () => { + rangeB = { + start: { line: 2, character: 1 }, + end: { line: 2, character: 4 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap and are not adjacent", () => { + rangeB = { + start: { line: 4, character: 3 }, + end: { line: 5, character: 1 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 5, character: 1 }, + }); + }); + + // TODO + test.skip("should handle edge case where start and end lines are the same", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 7 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 1, character: 7 }, + }); + }); +}); diff --git a/core/util/parameters.ts b/core/util/parameters.ts index b413a869e..88c7d38a6 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, + useRootPathContext: true, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index a6fd0f2db..08cfe64d1 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -129,6 +129,11 @@ export async function getLanguageForFile( export enum TSQueryType { CodeSnippets = "code-snippet-queries", Imports = "import-queries", + // Used in RootPathContextService.ts + FunctionDeclaration = "root-path-context-queries/function_declaration", + MethodDefinition = "root-path-context-queries/method_definition", + FunctionDefinition = "root-path-context-queries/function_definition", + MethodDeclaration = "root-path-context-queries/method_declaration", } export async function getQueryForFile( diff --git a/core/vendor/modules/@xenova/transformers/types/utils/generation.d.ts b/core/vendor/modules/@xenova/transformers/types/utils/generation.d.ts index 1688d6a6d..49ea01a51 100644 --- a/core/vendor/modules/@xenova/transformers/types/utils/generation.d.ts +++ b/core/vendor/modules/@xenova/transformers/types/utils/generation.d.ts @@ -320,7 +320,7 @@ export class NoBadWordsLogitsProcessor extends LogitsProcessor { * @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. * @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled. * @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. - * @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. + * @property {number} [encoder_repetition_penalty=1.0] The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. * @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. * @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once. * @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`. @@ -488,7 +488,7 @@ export type GenerationConfigType = { */ repetition_penalty?: number; /** - * The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. + * The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty. */ encoder_repetition_penalty?: number; /** @@ -590,4 +590,4 @@ export type GenerationConfigType = { }; import { Tensor } from './tensor.js'; export {}; -//# sourceMappingURL=generation.d.ts.map \ No newline at end of file +//# sourceMappingURL=generation.d.ts.map diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 53cd85d17..509702b4f 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -28,7 +28,7 @@ If there is information from the codebase, documentation, IDE, or other tools th ## Apply generated code to your file -When the LLM replies with code, you can hover over the top right of the code block and select “Apply to current file” to update the existing code in the editor to this new version. +When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes. ## Start a fresh session for a new task diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index f302ec44e..bc8968528 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -51,7 +51,7 @@ Indexing will begin upon submission. To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save. -The configuration schema is as follows: +The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows: ```json "docs": [ diff --git a/docs/docs/customize/model-providers/top-level/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md index ebc156413..c4bb24a4c 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.md +++ b/docs/docs/customize/model-providers/top-level/anthropic.md @@ -48,14 +48,17 @@ Anthropic currently does not offer any reranking models. Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). -Currently, we only allow caching of the system message. To enable this feature, update your your model configuration with `"cacheSystemMessage": true`: +To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: ```json { "models": [ { // Enable prompt caching - "cacheSystemMessage": true, + "cacheBehavior": { + "cacheSystemMessage": true, + "cacheConversation": true + }, "title": "Anthropic", "provider": "anthropic", "model": "claude-3-5-sonnet-20240620", diff --git a/docs/docs/customize/model-providers/top-level/azure.md b/docs/docs/customize/model-providers/top-level/azure.md index 295b7cdc8..f6e54137f 100644 --- a/docs/docs/customize/model-providers/top-level/azure.md +++ b/docs/docs/customize/model-providers/top-level/azure.md @@ -42,7 +42,7 @@ We recommend configuring **Codestral** as your autocomplete model. We recommend configuring **text-embedding-3-large** as your embeddings model. ```json title="config.json" -"embeddingsProvider": [{ +"embeddingsProvider": { "provider": "azure", "model": "text-embedding-3-large", "apiBase": "", @@ -50,7 +50,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. "apiVersion": "", "apiType": "azure", "apiKey": "" -}] +} ``` ## Reranking model diff --git a/docs/docs/customize/model-providers/top-level/gemini.md b/docs/docs/customize/model-providers/top-level/gemini.md index e8b55c2e8..eff3e91ac 100644 --- a/docs/docs/customize/model-providers/top-level/gemini.md +++ b/docs/docs/customize/model-providers/top-level/gemini.md @@ -38,13 +38,11 @@ We recommend configuring **text-embedding-004** as your embeddings model. ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "gemini", - "model": "models/text-embedding-004", - "apiKey": "[API_KEY]" - } - ] + "embeddingsProvider": { + "provider": "gemini", + "model": "models/text-embedding-004", + "apiKey": "[API_KEY]" + } } ``` diff --git a/docs/docs/customize/model-providers/top-level/mistral.md b/docs/docs/customize/model-providers/top-level/mistral.md index 7da0fd6e2..ba9427c9f 100644 --- a/docs/docs/customize/model-providers/top-level/mistral.md +++ b/docs/docs/customize/model-providers/top-level/mistral.md @@ -46,14 +46,12 @@ We recommend configuring **Mistral Embed** as your embeddings model. ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "mistral", - "model": "mistral-embed", - "apiKey": "[API_KEY]", - "apiBase": "https://api.mistral.ai/v1" - } - ] + "embeddingsProvider": { + "provider": "mistral", + "model": "mistral-embed", + "apiKey": "[API_KEY]", + "apiBase": "https://api.mistral.ai/v1" + } } ``` diff --git a/docs/docs/customize/model-providers/top-level/openai.md b/docs/docs/customize/model-providers/top-level/openai.md index 600ec08cd..d594f4f39 100644 --- a/docs/docs/customize/model-providers/top-level/openai.md +++ b/docs/docs/customize/model-providers/top-level/openai.md @@ -38,13 +38,11 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "openai", - "model": "text-embedding-3-large", - "apiKey": "[API_KEY]" - } - ] + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-3-large", + "apiKey": "[API_KEY]" + } } ``` diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.md index 1ab4aecbb..208180a58 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.md +++ b/docs/docs/customize/tutorials/custom-code-rag.md @@ -48,7 +48,8 @@ func = get_registry().get("openai").create( class CodeChunks(LanceModel): filename: str text: str = func.SourceField() - vector: Vector(func.ndims()) = func.VectorField() + # 1536 is the embedding dimension of the `voyage-code-2` model. + vector: Vector(1536) = func.VectorField() table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") table.add([ diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index 9f5bbe9be..b3f6d87d6 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -20,6 +20,6 @@ keywords: **Continue is the leading open-source AI code assistant inside of [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** - [Chat](chat/how-to-use-it.md) to understand and iterate on code in the sidebar -- [Autocomplete](autocomplete/how-to-use-it.md) to recieve inline code suggestions as you type +- [Autocomplete](autocomplete/how-to-use-it.md) to receive inline code suggestions as you type - [Edit](edit/how-to-use-it.md) to modify code without leaving your current file - [Actions](actions/how-to-use-it.md) to establish shortcuts for common use cases diff --git a/docs/package.json b/docs/package.json index 644b1d7f4..423c60bde 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'", + "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec \"docusaurus start\"", "build": "docusaurus build", "build:netlify": "docusaurus build --out-dir build/docs", "swizzle": "docusaurus swizzle", diff --git a/docs/sidebars.js b/docs/sidebars.js index 196a6c832..755d7f720 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -8,10 +8,6 @@ const sidebars = { type: "category", label: "Getting started", collapsed: false, - link: { - type: "doc", - id: "getting-started/install", - }, items: [ { type: "autogenerated", @@ -22,10 +18,6 @@ const sidebars = { { type: "category", label: "Chat", - link: { - type: "doc", - id: "chat/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -36,10 +28,6 @@ const sidebars = { { type: "category", label: "Autocomplete", - link: { - type: "doc", - id: "autocomplete/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -50,10 +38,6 @@ const sidebars = { { type: "category", label: "Edit", - link: { - type: "doc", - id: "edit/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -64,10 +48,6 @@ const sidebars = { { type: "category", label: "Actions", - link: { - type: "doc", - id: "actions/how-to-use-it", - }, items: [ { type: "autogenerated", diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 6692f2de7..3f340f6ce 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -699,8 +699,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "anyOf": [ @@ -796,8 +805,14 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1017,8 +1032,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] @@ -1528,7 +1552,8 @@ "url", "database", "os", - "repo-map" + "repo-map", + "greptile" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1552,7 +1577,8 @@ "Reference the contents of a page at a URL", "Reference table schemas", "Operating system and CPU Information", - "Map of files in the repository with important code highlights" + "Map of files in the repository with important code highlights", + "Query your greptile index of the current repo" ], "type": "string" }, @@ -1930,6 +1956,36 @@ }, "required": ["host", "port", "user", "password", "database"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["greptile"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "GithubToken": { + "title": "GithubToken", + "description": "Your github access token", + "default": "", + "type": "string" + }, + "GreptileToken": { + "title": "GreptileToken", + "description": "Your greptile access token", + "default": "", + "type": "string" + } + } + } + }, + "required": ["GreptileToken", "GithubToken"] + } } ], "required": ["name"] diff --git a/extensions/intellij/CHANGELOG.md b/extensions/intellij/CHANGELOG.md index 3483adeb9..63feb8335 100644 --- a/extensions/intellij/CHANGELOG.md +++ b/extensions/intellij/CHANGELOG.md @@ -5,9 +5,13 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). -Pre-release Changes +## 0.0.72 - 2024-10-04 +### Added +* Listen for changes to Intellij settings without requiring window reload ### Changed * Updated tutorial file +### Fixed +* Fix ability to load config.ts in JetBrains IDEs ## 0.0.69 - 2024-09-22 ### Added diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 34fbfa779..05a5c1c5f 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,35 +1,26 @@ # IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html - -pluginGroup = com.github.continuedev.continueintellijextension -pluginName = continue-intellij-extension -pluginRepositoryUrl = https://github.com/continuedev/continue +pluginGroup=com.github.continuedev.continueintellijextension +pluginName=continue-intellij-extension +pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.69 - +pluginVersion=0.0.73 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html -pluginSinceBuild = 223 +pluginSinceBuild=223 #pluginUntilBuild = 232.* - # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension -platformType = IC -platformVersion = 2022.3.3 +platformType=IC +platformVersion=2022.3.3 #platformVersion = LATEST-EAP-SNAPSHOT - # Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html # Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22 -platformPlugins = org.jetbrains.plugins.terminal - +platformPlugins=org.jetbrains.plugins.terminal # Gradle Releases -> https://github.com/gradle/gradle/releases -gradleVersion = 8.3 - +gradleVersion=8.3 # Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib -kotlin.stdlib.default.dependency = false - +kotlin.stdlib.default.dependency=false # Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html -org.gradle.configuration-cache = true - +org.gradle.configuration-cache=true # Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html -org.gradle.caching = true - +org.gradle.caching=true # Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment -systemProp.org.gradle.unsafe.kotlin.assignment = true +systemProp.org.gradle.unsafe.kotlin.assignment=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 71c7435b3..37bf5e613 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -141,6 +141,9 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { connection.subscribe(SettingsListener.TOPIC, object : SettingsListener { override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) { continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> } + continuePluginService.sendToWebview("didChangeIdeSettings", mapOf( + "settings" to settings + )) } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 877308fa4..9a1ef1ab3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -5,10 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinueExtensi import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson import com.intellij.injected.editor.VirtualFileWindow -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.application.WriteAction -import com.intellij.openapi.application.invokeLater -import com.intellij.openapi.application.runReadAction +import com.intellij.openapi.application.* import com.intellij.openapi.components.Service import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service @@ -93,11 +90,11 @@ class AutocompleteService(private val project: Project) { val completions = response as List<*> if (completions.isNotEmpty()) { val completion = completions[0].toString() + val finalTextToInsert = deduplicateCompletion(editor, offset, completion) - if (completion.isNotEmpty() && (completion.lines().size === 1 || column >= lineLength)) { - // Do not render if completion is multi-line and caret is in middle of line - renderCompletion(editor, offset, completion) - pendingCompletion = pendingCompletion?.copy(text = completion) + if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) { + renderCompletion(editor, offset, finalTextToInsert) + pendingCompletion = pendingCompletion?.copy(text = finalTextToInsert) // Hide auto-popup // AutoPopupController.getInstance(project).cancelAllRequests() @@ -106,17 +103,48 @@ class AutocompleteService(private val project: Project) { })) } - private fun renderCompletion(editor: Editor, offset: Int, text: String) { - if (text.isEmpty()) { - return + private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean { + if (completion.isEmpty()) { + return false } - if (isInjectedFile(editor)) return + // Do not render if completion is multi-line and caret is in middle of line + return !(completion.lines().size > 1 && column < lineLength) + } + private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { + // Check if completion matches the first 10 characters after the cursor + return ApplicationManager.getApplication().runReadAction { + val document = editor.document + val caretOffset = editor.caretModel.offset + val N = 10 + var textAfterCursor = if (caretOffset + N <= document.textLength) { + document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N)) + } else { + document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength)) + } + + val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) + if (indexOfTextAfterCursorInCompletion > 0) { + return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) + } else if (indexOfTextAfterCursorInCompletion == 0) { + return@runReadAction "" + } + + return@runReadAction completion + } + } + + private fun renderCompletion(editor: Editor, offset: Int, completion: String) { + if (completion.isEmpty()) { + return + } + if (isInjectedFile(editor)) return // Don't render completions when code completion dropdown is visible if (!autocompleteLookupListener.isLookupEmpty()) { return } + ApplicationManager.getApplication().invokeLater { WriteAction.run { // Clear existing completions @@ -126,10 +154,10 @@ class AutocompleteService(private val project: Project) { properties.relatesToPrecedingText(true) properties.disableSoftWrapping(true) - if (text.lines().size > 1) { - editor.inlayModel.addBlockElement(offset, properties, ContinueMultilineCustomElementRenderer(editor, text)) + if (completion.lines().size > 1) { + editor.inlayModel.addBlockElement(offset, properties, ContinueMultilineCustomElementRenderer(editor, completion)) } else { - editor.inlayModel.addInlineElement(offset, properties, ContinueCustomElementRenderer(editor, text)) + editor.inlayModel.addInlineElement(offset, properties, ContinueCustomElementRenderer(editor, completion)) } // val attributes = TextAttributes().apply { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt similarity index 92% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index ccd76b570..dc02892c0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -1,4 +1,4 @@ -package com.github.continuedev.continueintellijextension.toolWindow +package com.github.continuedev.continueintellijextension.constants class MessageTypes { companion object { @@ -38,7 +38,6 @@ class MessageTypes { "getTags", "getIdeInfo", "getIdeSettings", - "errorPopup", "getRepoName", "listDir", "getGitRootPath", @@ -50,7 +49,8 @@ class MessageTypes { "pathSep", "getControlPlaneSessionInfo", "logoutOfControlPlane", - "getTerminalContents" + "getTerminalContents", + "showToast", ) val PASS_THROUGH_TO_WEBVIEW = listOf( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index f47f6f138..d04f8d028 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -3,7 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.TelemetryService -import com.github.continuedev.continueintellijextension.toolWindow.MessageTypes +import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project @@ -15,7 +15,13 @@ import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.PosixFilePermission -class CoreMessenger(private val project: Project, esbuildPath: String, continueCorePath: String, ideProtocolClient: IdeProtocolClient, private val coroutineScope: CoroutineScope) { +class CoreMessenger( + private val project: Project, + esbuildPath: String, + continueCorePath: String, + ideProtocolClient: IdeProtocolClient, + private val coroutineScope: CoroutineScope +) { private var writer: Writer? = null private var reader: BufferedReader? = null private var process: Process? = null @@ -42,11 +48,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { val id = messageId ?: uuid() - val message = gson.toJson(mapOf( + val message = gson.toJson( + mapOf( "messageId" to id, "messageType" to messageType, "data" to data - )) + ) + ) responseListeners[id] = onResponse write(message) } @@ -60,11 +68,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC // IDE listeners if (MessageTypes.ideMessageTypes.contains(messageType)) { ideProtocolClient.handleMessage(json) { data -> - val message = gson.toJson(mapOf( + val message = gson.toJson( + mapOf( "messageId" to messageId, "messageType" to messageType, "data" to data - )) + ) + ) write(message) }; } @@ -76,11 +86,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC if (messageType == "getDefaultModelTitle") { val continueSettingsService = service() val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel; - val message = gson.toJson(mapOf( + val message = gson.toJson( + mapOf( "messageId" to messageId, "messageType" to messageType, "data" to defaultModelTitle - )) + ) + ) write(message) } val continuePluginService = project.service() @@ -94,7 +106,8 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC val done = (data as Map)["done"] if (done == true) { responseListeners.remove(messageId) - } else {} + } else { + } } else { responseListeners.remove(messageId) } @@ -106,10 +119,10 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC val osName = System.getProperty("os.name").toLowerCase() if (osName.contains("mac") || osName.contains("darwin")) { ProcessBuilder( - "xattr", - "-dr", - "com.apple.quarantine", - destination + "xattr", + "-dr", + "com.apple.quarantine", + destination ).start() setFilePermissions(destination, "rwxr-xr-x") } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { @@ -177,7 +190,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC // Start the subprocess val processBuilder = ProcessBuilder(continueCorePath) - .directory(File(continueCorePath).parentFile) + .directory(File(continueCorePath).parentFile) process = processBuilder.start() val outputStream = process!!.outputStream @@ -200,14 +213,16 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC println("Core process exited with output: $err") CoroutineScope(Dispatchers.Main).launch { - ideProtocolClient.showMessage("Core process exited with output: $err") + ideProtocolClient.showToast("error", "Core process exited with output: $err") } // Log the cause of the failure val telemetryService = service() - telemetryService.capture("jetbrains_core_exit", mapOf( - "error" to err - )) + telemetryService.capture( + "jetbrains_core_exit", mapOf( + "error" to err + ) + ) // Clean up all resources writer?.close() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 3b11fbe78..aa1988504 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -14,6 +14,9 @@ import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore +import com.intellij.notification.NotificationDisplayType +import com.intellij.notification.NotificationGroup +import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager @@ -154,8 +157,8 @@ private fun readConfigJson(): Map { val configJsonPath = getConfigJsonPath() val reader = FileReader(configJsonPath) val config: Map = gson.fromJson( - reader, - object : TypeToken>() {}.type + reader, + object : TypeToken>() {}.type ) reader.close() return config @@ -167,9 +170,13 @@ class AsyncFileSaveListener : AsyncFileListener { constructor(ideProtocolClient: IdeProtocolClient) { this.ideProtocolClient = ideProtocolClient } + override fun prepareChange(events: MutableList): AsyncFileListener.ChangeApplier? { for (event in events) { - if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) { + if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith( + ".continue\\config.json" + ) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") + ) { return object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { val config = readConfigJson() @@ -183,14 +190,15 @@ class AsyncFileSaveListener : AsyncFileListener { } -class IdeProtocolClient ( +class IdeProtocolClient( private val continuePluginService: ContinuePluginService, private val textSelectionStrategy: TextSelectionStrategy, private val coroutineScope: CoroutineScope, private val workspacePath: String?, private val project: Project -): DumbAware { +) : DumbAware { val diffManager = DiffManager(project) + private val CONTINUE_NOTIFICATION_GROUP = NotificationGroup("Continue", NotificationDisplayType.BALLOON, true) private val ripgrep: String init { @@ -202,7 +210,8 @@ class IdeProtocolClient ( }) val myPluginId = "com.github.continuedev.continueintellijextension" - val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found") + val pluginDescriptor = + PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found") val pluginPath = pluginDescriptor.pluginPath val osName = System.getProperty("os.name").toLowerCase() @@ -213,7 +222,8 @@ class IdeProtocolClient ( else -> "linux" } - ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString() + ripgrep = + Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString() } private fun send(messageType: String, data: Any?, messageId: String? = null) { @@ -224,8 +234,8 @@ class IdeProtocolClient ( fun handleMessage(text: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val parsedMessage: Map = Gson().fromJson( - text, - object : TypeToken>() {}.type + text, + object : TypeToken>() {}.type ) val messageType = parsedMessage["messageType"] as? String if (messageType == null) { @@ -239,16 +249,20 @@ class IdeProtocolClient ( "uniqueId" -> respond( mapOf("uniqueId" to uniqueId()) ) + "getIdeSettings" -> { val settings = - ServiceManager.getService(ContinueExtensionSettings::class.java) - respond(mapOf( - "remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl, - "remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod, - "userToken" to settings.continueState.userToken, - "enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta - )) + ServiceManager.getService(ContinueExtensionSettings::class.java) + respond( + mapOf( + "remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl, + "remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod, + "userToken" to settings.continueState.userToken, + "enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta + ) + ) } + "getControlPlaneSessionInfo" -> { val silent = (data as? Map)?.get("silent") as? Boolean ?: false @@ -261,12 +275,15 @@ class IdeProtocolClient ( respond(null) } } + "logoutOfControlPlane" -> { val authService = service() authService.signOut() - ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC).handleUpdatedSessionInfo(null) + ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) + .handleUpdatedSessionInfo(null) respond(null) } + "getIdeInfo" -> { val applicationInfo = ApplicationInfo.getInstance() val ideName: String = applicationInfo.fullApplicationName @@ -283,13 +300,15 @@ class IdeProtocolClient ( val plugin = PluginManagerCore.getPlugin(PluginId.getId(pluginId)) val extensionVersion = plugin?.version ?: "Unknown" - respond(mapOf( - "ideType" to "jetbrains", - "name" to ideName, - "version" to ideVersion, - "remoteName" to remoteName, - "extensionVersion" to extensionVersion - )) + respond( + mapOf( + "ideType" to "jetbrains", + "name" to ideName, + "version" to ideVersion, + "remoteName" to remoteName, + "extensionVersion" to extensionVersion + ) + ) } "getUniqueId" -> { @@ -307,9 +326,9 @@ class IdeProtocolClient ( "showDiff" -> { val data = data as Map diffManager.showDiff( - data["filepath"] as String, - data["newContents"] as String, - (data["stepIndex"] as Double).toInt() + data["filepath"] as String, + data["newContents"] as String, + (data["stepIndex"] as Double).toInt() ) respond(null) } @@ -333,7 +352,8 @@ class IdeProtocolClient ( val endLine = end["line"] as Int val endCharacter = end["character"] as Int - val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length) + val firstLine = + fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length) val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter) val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n") @@ -391,6 +411,7 @@ class IdeProtocolClient ( saveFile((data as Map)["filepath"] ?: throw Exception("No filepath provided")) respond(null) } + "showVirtualFile" -> { val data = data as Map showVirtualFile( @@ -401,15 +422,11 @@ class IdeProtocolClient ( } "connected" -> {} - "showMessage" -> { - showMessage(data as String) - respond(null) - } "setFileOpen" -> { val data = data as Map setFileOpen( - data["filepath"] as String, - data["open"] as Boolean + data["filepath"] as String, + data["open"] as Boolean ) respond(null) } @@ -420,14 +437,14 @@ class IdeProtocolClient ( val startLine = (data["startLine"] as Double).toInt() val endLine = (data["endLine"] as Double).toInt() highlightCode( - RangeInFile( - filepath, - Range( - Position(startLine, 0), - Position(endLine, 0) - ) - ), - data["color"] as String? + RangeInFile( + filepath, + Range( + Position(startLine, 0), + Position(endLine, 0) + ) + ), + data["color"] as String? ) respond(null) } @@ -438,7 +455,7 @@ class IdeProtocolClient ( val json = gson.toJson(data["rangeInFile"]) val type = object : TypeToken() {}.type val rangeInFile = - gson.fromJson(json, type) + gson.fromJson(json, type) highlightCode(rangeInFile, data["color"] as String) respond(null) } @@ -456,6 +473,7 @@ class IdeProtocolClient ( }.toMap() respond(pathToLastModified) } + "listDir" -> { val data = data as Map val dir = data["dir"] as String @@ -465,6 +483,7 @@ class IdeProtocolClient ( } ?: emptyList() respond(files) } + "getGitRootPath" -> { val data = data as Map val directory = data["dir"] as String @@ -478,12 +497,14 @@ class IdeProtocolClient ( respond(output) } + "getBranch" -> { // Get the current branch name val dir = (data as Map)["dir"] as String val branch = getBranch(dir) respond(branch) } + "getRepoName" -> { // Get the current repository name val dir = (data as Map)["dir"] as String @@ -522,6 +543,7 @@ class IdeProtocolClient ( respond(output.toString()); } + "getProblems" -> { // Get currently active editor var editor: Editor? = null @@ -570,46 +592,58 @@ class IdeProtocolClient ( // } // respond(problems) } + "getConfigJsUrl" -> { // Calculate a data URL for the config.js file val configJsPath = getConfigJsPath() val configJsContents = File(configJsPath).readText() - val configJsDataUrl = "data:text/javascript;base64,${Base64.getEncoder().encodeToString(configJsContents.toByteArray())}" + val configJsDataUrl = "data:text/javascript;base64,${ + Base64.getEncoder().encodeToString(configJsContents.toByteArray()) + }" respond(configJsDataUrl) } + "writeFile" -> { val msg = data as Map; val file = File(msg["path"]) file.writeText(msg["contents"] as String) respond(null); } + "fileExists" -> { val msg = data as Map; val file = File(msg["filepath"]) respond(file.exists()) } + "getContinueDir" -> { respond(getContinueGlobalPath()) } + "openFile" -> { setFileOpen((data as Map)["path"] as String) respond(null) } + "runCommand" -> { respond(null) // Running commands not yet supported in JetBrains } - "errorPopup" -> { - val data = data as Map - val message = data["message"] as String - showMessage(message) + + "showToast" -> { + val data = data as ArrayList + val toast_type = data[0] + val message = data[1] + showToast(toast_type, message) respond(null) } "listFolders" -> { val workspacePath = workspacePath ?: return@launch val workspaceDir = File(workspacePath) - val folders = workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } ?: emptyList() + val folders = + workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } + ?: emptyList() respond(folders) } @@ -623,16 +657,19 @@ class IdeProtocolClient ( val openFiles = visibleFiles() respond(openFiles) } + "getCurrentFile" -> { val currentFile = currentFile() respond(currentFile) } + "getPinnedFiles" -> { ApplicationManager.getApplication().invokeLater { val pinnedFiles = pinnedFiles() respond(pinnedFiles) } } + "insertAtCursor" -> { val msg = data as Map; val text = msg["text"] as String @@ -649,8 +686,10 @@ class IdeProtocolClient ( } } } + "applyToFile" -> { } + "getGitHubAuthToken" -> { val continueSettingsService = service() val ghAuthToken = continueSettingsService.continueState.ghAuthToken; @@ -663,26 +702,30 @@ class IdeProtocolClient ( respond(ghAuthToken) } } + "setGitHubAuthToken" -> { val continueSettingsService = service() val data = data as Map continueSettingsService.continueState.ghAuthToken = data["token"] respond(null) } + "openUrl" -> { val url = data as String java.awt.Desktop.getDesktop().browse(java.net.URI(url)) respond(null) } + "pathSep" -> { respond(File.separator) } + else -> { println("Unknown messageType: $messageType") } } } catch (error: Exception) { - showMessage("Error handling message of type $messageType: $error") + showToast("error", "Error handling message of type $messageType: $error") } } } @@ -696,8 +739,8 @@ class IdeProtocolClient ( val configJsonPath = getConfigJsonPath() val reader = FileReader(configJsonPath) val config: MutableMap = gson.fromJson( - reader, - object : TypeToken>() {}.type + reader, + object : TypeToken>() {}.type ) reader.close() @@ -818,7 +861,8 @@ class IdeProtocolClient ( val result = ApplicationManager.getApplication().runReadAction { // Get the editor instance for the currently active editor window val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null - val virtualFile = editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null + val virtualFile = + editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null // Get the selection range and content val selectionModel: SelectionModel = editor.selectionModel @@ -838,10 +882,12 @@ class IdeProtocolClient ( val startChar = startOffset - document.getLineStartOffset(startLine) val endChar = endOffset - document.getLineStartOffset(endLine) - return@runReadAction RangeInFileWithContents(virtualFile.path, Range( + return@runReadAction RangeInFileWithContents( + virtualFile.path, Range( Position(startLine, startChar), Position(endLine, endChar) - ), selectedText) + ), selectedText + ) } return result @@ -856,8 +902,8 @@ class IdeProtocolClient ( // )) continuePluginService.sendToWebview( -"highlightedCode", - mapOf( + "highlightedCode", + mapOf( "rangeInFileWithContents" to rif, "edit" to edit ) @@ -877,29 +923,30 @@ class IdeProtocolClient ( } private val DEFAULT_IGNORE_DIRS = listOf( - ".git", - ".vscode", - ".idea", - ".vs", - "venv", - ".venv", - "env", - ".env", - "node_modules", - "dist", - "build", - "target", - "out", - "bin", - ".pytest_cache", - ".vscode-test", - ".continue", - "__pycache__", - "site-packages", - ".gradle", - ".cache", - "gems", + ".git", + ".vscode", + ".idea", + ".vs", + "venv", + ".venv", + "env", + ".env", + "node_modules", + "dist", + "build", + "target", + "out", + "bin", + ".pytest_cache", + ".vscode-test", + ".continue", + "__pycache__", + "site-packages", + ".gradle", + ".cache", + "gems", ) + private fun shouldIgnoreDirectory(name: String): Boolean { val components = File(name).path.split(File.separator) return DEFAULT_IGNORE_DIRS.any { dir -> @@ -976,21 +1023,16 @@ class IdeProtocolClient ( return virtualFile?.path } -suspend fun showMessage(msg: String) { - withContext(Dispatchers.Main) { - val statusBar = WindowManager.getInstance().getStatusBar(project) + fun showToast(type: String, content: String) { + val notificationType = when (type.uppercase()) { + "ERROR" -> NotificationType.ERROR + "WARNING" -> NotificationType.WARNING + else -> NotificationType.INFORMATION + } - JBPopupFactory.getInstance() - .createHtmlTextBalloonBuilder(msg, MessageType.INFO, null) - .setFadeoutTime(10000) - .setHideOnAction(false) - .createBalloon() - .show( - RelativePoint.getSouthEastOf(statusBar.component), - Balloon.Position.atRight - ) + CONTINUE_NOTIFICATION_GROUP.createNotification(content, notificationType) + .notify(project); } -} fun highlightCode(rangeInFile: RangeInFile, color: String?) { val file = diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index 318afda59..21b1ce240 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -24,46 +24,65 @@ import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXTextArea -import org.jdesktop.swingx.border.DropShadowBorder import java.awt.* import java.awt.event.* -import java.awt.geom.RoundRectangle2D +import java.awt.geom.Path2D import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.plaf.basic.BasicComboBoxUI import kotlin.math.max +import java.awt.geom.RoundRectangle2D +import java.awt.geom.AffineTransform +import javax.swing.event.ListDataListener - -const val SHADOW_SIZE = 7 const val MAIN_FONT_SIZE = 13 fun makeTextArea(): JTextArea { - val textArea = CustomTextArea( 2, 40).apply { + val textArea = CustomTextArea(1, 40).apply { lineWrap = true wrapStyleWord = true isOpaque = false background = GetTheme().getSecondaryDark() maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) - margin = JBUI.insets(8) + margin = JBUI.insets(6, 4, 6, 4) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) + preferredSize = Dimension(400, 75) } textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - return textArea } -fun makePanel(project: Project, customPanelRef: Ref, textArea: JTextArea, inlayRef: Ref, comboBoxRef: Ref>, leftInset: Int, modelTitles: List, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel { - val topPanel = ShadowPanel(MigLayout("wrap 1, insets 4 $leftInset 2 2, gap 0!")).apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground -// background = defaultBackground - background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) +fun makePanel( + project: Project, + customPanelRef: Ref, + textArea: JTextArea, + inlayRef: Ref, + comboBoxRef: Ref>, + leftInset: Int, + modelTitles: List, + onEnter: () -> Unit, + onCancel: () -> Unit, + onAccept: () -> Unit, + onReject: () -> Unit +): JPanel { + val topPanel = ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply { + background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) isOpaque = false } - val panel = CustomPanel(MigLayout("wrap 1, insets 0, gap 0!, fillx"), project, modelTitles, comboBoxRef, onEnter, onCancel, onAccept, onReject).apply { + val panel = CustomPanel( + MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), + project, + modelTitles, + comboBoxRef, + onEnter, + onCancel, + onAccept, + onReject, + textArea + ).apply { val globalScheme = EditorColorsManager.getInstance().globalScheme val defaultBackground = globalScheme.defaultBackground background = defaultBackground @@ -71,16 +90,9 @@ fun makePanel(project: Project, customPanelRef: Ref, textArea: JTex putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) preferredSize = textArea.preferredSize - isOpaque = false setup() - - val shadow = DropShadowBorder() - shadow.shadowColor = JBColor(0xb0b0b0, 0x505050) - shadow.isShowRightShadow = true - shadow.isShowBottomShadow = true - shadow.shadowSize = SHADOW_SIZE - border = shadow } + customPanelRef.set(panel) textArea.addComponentListener(object : ComponentAdapter() { @@ -99,9 +111,9 @@ fun openInlineEdit(project: Project?, editor: Editor) { if (project == null) return // Don't open in terminal - if (EditorUtils().isTerminal(editor)) { - return - } + if (EditorUtils().isTerminal(editor)) { + return + } val manager = EditorComponentInlaysManager.from(editor, true) @@ -142,7 +154,8 @@ fun openInlineEdit(project: Project?, editor: Editor) { val lineEnd = editor.document.getLineEndOffset(indentationLineNum) val text = editor.document.getText(TextRange(lineStart, lineEnd)) val indentation = text.takeWhile { it == ' ' }.length - val charWidth = editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ') + val charWidth = + editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ') val leftInset = indentation * charWidth * 2 / 3 val inlayRef = Ref() @@ -165,8 +178,9 @@ fun openInlineEdit(project: Project?, editor: Editor) { val comboBoxRef = Ref>() fun onEnter() { + val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾") customPanelRef.get().enter() - diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, comboBoxRef.get().selectedItem as String) + diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret) } val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, { @@ -180,6 +194,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { inlayRef.get().dispose() }) val inlay = manager.insert(startLineNum, panel, true) + panel.revalidate() inlayRef.set(inlay) val viewport = (editor as? EditorImpl)?.scrollPane?.viewport @@ -187,20 +202,40 @@ fun openInlineEdit(project: Project?, editor: Editor) { // Add key listener to text area textArea.addKeyListener(object : KeyAdapter() { - override fun keyPressed(e: KeyEvent) { - if (e.keyCode == KeyEvent.VK_ESCAPE) { - diffStreamService.reject(editor) + override fun keyTyped(e: KeyEvent) { + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() + } + } - // Re-highlight the selected text - val documentLength = editor.document.textLength - val safeEnd = minOf(end, documentLength) - selectionModel.setSelection(start, safeEnd) - } else if (e.keyCode == KeyEvent.VK_ENTER) { - if (e.modifiersEx == KeyEvent.SHIFT_DOWN_MASK) { - textArea.document.insertString(textArea.caretPosition, "\n", null) - } else if (e.modifiersEx == 0) { - onEnter() - e.consume() + + override fun keyPressed(e: KeyEvent) { + when (e.keyCode) { + KeyEvent.VK_ESCAPE -> { + diffStreamService.reject(editor) + selectionModel.setSelection(start, end) + } + + KeyEvent.VK_ENTER -> { + when (e.modifiersEx) { + KeyEvent.SHIFT_DOWN_MASK -> { + textArea.document.insertString(textArea.caretPosition, "\n", null) + } + + 0 -> { + onEnter() + e.consume() + } + } + } + } + } + + // We need this because backspace/delete is not registering properly on keyPressed for an unknown reason + override fun keyReleased(e: KeyEvent) { + if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() } } } @@ -216,6 +251,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) } } + override fun insertUpdate(e: DocumentEvent?) { updateSize() } @@ -253,19 +289,67 @@ class InlineEditAction : AnAction(), DumbAware { } } -class CustomPanel(layout: MigLayout, project: Project, modelTitles: List, comboBoxRef: Ref>, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel(layout) { +class CustomPanel( + layout: MigLayout, + project: Project, + modelTitles: List, + comboBoxRef: Ref>, + private val onEnter: () -> Unit, + private val onCancel: () -> Unit, + private val onAccept: () -> Unit, + private val onReject: () -> Unit, + private val textArea: JTextArea +) : JPanel(layout) { + private val shadowSize = 5 + private val cornerRadius = 8 + private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow + private val borderColor = Color(128, 128, 128, 128) + private val borderThickness = 1 + private val triangleSize = 6 + private val rightMargin = 3.0 + private val closeButton: JComponent = createCloseButton() + private val originalTextColor: Color = textArea.foreground + private val greyTextColor: Color = Color(128, 128, 128, 200) + public var isFinished = false + + init { + isOpaque = false + add(closeButton, "pos 100%-25 0 -3 3, w 20!, h 20!") + } + + private fun createCloseButton(): JComponent { + return JLabel("X").apply { + foreground = Color(128, 128, 128, 128) + background = Color(0, 0, 0, 0) + font = UIUtil.getFontWithFallback("Arial", Font.BOLD, 10) + border = EmptyBorder(2, 6, 2, 6) + toolTipText = "`esc` to cancel" + isOpaque = false + + addMouseListener(object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent) { + foreground = Color(128, 128, 128, 255) + cursor = Cursor(Cursor.HAND_CURSOR) + } + + override fun mouseExited(e: MouseEvent) { + foreground = Color(128, 128, 128, 128) + cursor = Cursor.getDefaultCursor() + } + + override fun mouseClicked(e: MouseEvent) { + onCancel() + } + }) + } + } + private val subPanelA: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { val globalScheme = EditorColorsManager.getInstance().globalScheme val defaultBackground = globalScheme.defaultBackground - - val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply { - foreground = Color(128, 128, 128, 200) - background = defaultBackground - } - val continueSettingsService = service() - val dropdown = JComboBox(modelTitles.toTypedArray()).apply { + setUI(TransparentArrowButtonUI()) isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) @@ -275,7 +359,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) renderer = DefaultListCellRenderer().apply { - horizontalAlignment = SwingConstants.RIGHT + horizontalAlignment = SwingConstants.LEFT } selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let { if (modelTitles.isEmpty()) -1 else { @@ -287,16 +371,14 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List addActionListener { continueSettingsService.continueState.lastSelectedInlineEditModel = selectedItem as String } - -// setUI(TransparentArrowButtonUI()) } comboBoxRef.set(dropdown) - val rightButton = CustomButton("Submit") { onEnter() }.apply { -// background = GetTheme().getHighlight() - background = JBColor(0xe04573e8.toInt(), 0xe04573e8.toInt()) - foreground = JBColor(0xffffffff.toInt(), 0xffffffff.toInt()) + val rightButton = CustomButton("⏎ Enter") { onEnter() }.apply { + background = JBColor(0x999998.toInt(), 0x999998.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + border = EmptyBorder(2, 6, 2, 6) } val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { @@ -306,75 +388,43 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List add(rightButton, "align right") } - border = EmptyBorder(4, 8, 4, 8) + border = EmptyBorder(0, 0, 20, 16) - add(leftButton, "align left") - add(rightPanel, "align right") + add(dropdown, "align left") + add(rightPanel, "align right, split 2") isOpaque = false cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) } - private val subPanelB: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { - // Get the global color scheme and default background color - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - - val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply { - foreground = Color(128, 128, 128, 200) - background = defaultBackground - } - - val dropdown = JComboBox(modelTitles.toTypedArray()).apply { - isEditable = true - background = defaultBackground - foreground = Color(128, 128, 128, 200) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 4, 2, 4) - isOpaque = false - isEditable = false - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - renderer = DefaultListCellRenderer().apply { - horizontalAlignment = SwingConstants.RIGHT - } - - isVisible = false - -// setUI(TransparentArrowButtonUI()) - } - - val progressBar = JProgressBar() - progressBar.isIndeterminate = true - - val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - border = EmptyBorder(0, 0, 0, 0) - add(dropdown, "align right") - add(progressBar, "align right") - } - - - - border = EmptyBorder(4, 8, 4, 8) - add(leftButton, "align left") - add(rightPanel, "align right") + private val subPanelB: JPanel = JPanel(BorderLayout()).apply { isOpaque = false - cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) + val progressBar = JProgressBar().apply { + isIndeterminate = true + } + + add(progressBar, BorderLayout.CENTER) + border = BorderFactory.createEmptyBorder(0, 0, 20, 16) } private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { - val leftLabel = JLabel("Enter follow-up instructions").apply { - foreground = Color(128, 128, 128, 200) + val leftLabel = JLabel("Type to re-prompt").apply { + foreground = Color(156, 163, 175) // text-gray-400 font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = EmptyBorder(0, 4, 0, 0) } - val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply { - background = Color(255, 0, 0, 64) + val leftButton = CustomButton("Reject (${getAltKeyLabel()}⇧N)") { onReject() }.apply { + background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + } - val rightButton = CustomButton("${getAltKeyLabel()}⇧Y") { onAccept() }.apply { - background = Color(0, 255, 0, 64) + val rightButton = CustomButton("Accept (${getAltKeyLabel()}⇧Y)") { onAccept() }.apply { + background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + } val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { @@ -386,7 +436,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List add(leftLabel, "align left") add(rightPanel, "align right") - border = EmptyBorder(4, 8, 4, 8) + border = BorderFactory.createEmptyBorder(0, 0, 20, 16) isOpaque = false } @@ -394,6 +444,10 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List remove(subPanelB) remove(subPanelC) add(subPanelA, "grow, gap 0!") + isFinished = false + revalidate() + repaint() + textArea.foreground = originalTextColor } fun enter() { @@ -409,33 +463,63 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List add(subPanelC, "grow, gap 0!") revalidate() repaint() + isFinished = true + textArea.foreground = greyTextColor } override fun paintComponent(g: Graphics) { + super.paintComponent(g) + val g2 = g as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - // Draw the rounded border - val borderColor = Color(128, 128, 128, 128) - val borderThickness = 1 - val borderRadius = 8 + val w = width - shadowSize + val h = height - shadowSize - g2.color = borderColor - g2.stroke = BasicStroke(borderThickness.toFloat()) - g2.drawRoundRect( - borderThickness / 2, - borderThickness / 2, - width - borderThickness - SHADOW_SIZE + 1, - height - borderThickness - SHADOW_SIZE + 1, - borderRadius, - borderRadius + // Create the shape for the tooltip/triangle + val shape = Path2D.Double() + shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) + shape.quadTo(borderThickness / 2.0, borderThickness / 2.0, cornerRadius.toDouble(), borderThickness / 2.0) + shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + borderThickness / 2.0, + w - borderThickness / 2.0 - rightMargin, + cornerRadius.toDouble() + ) + shape.lineTo(w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + h - triangleSize.toDouble(), + w - cornerRadius.toDouble() - rightMargin, + h - triangleSize.toDouble() + ) + shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) + shape.lineTo(borderThickness / 2.0, h.toDouble()) + shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) + + // Draw shadow + g2.color = shadowColor + g2.fill( + shape.createTransformedShape( + AffineTransform.getTranslateInstance( + shadowSize.toDouble(), + shadowSize.toDouble() + ) + ) ) - super.paintComponent(g) + // Draw main shape + g2.color = background + g2.fill(shape) + + // Draw border + g2.color = borderColor + g2.stroke = BasicStroke(borderThickness.toFloat()) + g2.draw(shape) } } - class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { private var isHovered = false @@ -458,26 +542,41 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { } }) -// verticalAlignment = CENTER font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 4, 2, 4) + border = EmptyBorder(2, 6, 2, 6) } + override fun paintComponent(g: Graphics) { val g2 = g as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val cornerRadius = 8 val rect = Rectangle(0, 0, width, height) - val roundRect = RoundRectangle2D.Float(rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat(), cornerRadius.toFloat(), cornerRadius.toFloat()) + val roundRect = RoundRectangle2D.Float( + rect.x.toFloat(), + rect.y.toFloat(), + rect.width.toFloat(), + rect.height.toFloat(), + cornerRadius.toFloat(), + cornerRadius.toFloat() + ) if (isHovered) { - g2.color = background.brighter() + val brightenFactor = 1.1f + val brighterColor = Color( + (background.red * brightenFactor).toInt(), + (background.green * brightenFactor).toInt(), + (background.blue * brightenFactor).toInt() + ) + g2.color = brighterColor } else { g2.color = background } g2.fill(roundRect) g2.color = foreground - g2.drawString(text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), - (height / 2 + g.fontMetrics.ascent / 2).toFloat()) + g2.drawString( + text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), + (height / 2 + g.fontMetrics.ascent / 2).toFloat() + ) } } @@ -492,7 +591,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { if (text.isEmpty()) { g.color = Color(128, 128, 128, 255) g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) - g.drawString("Enter instructions to edit highlighted code", 8, 20) + g.drawString("Enter instructions...", 3, 20) } super.paintComponent(g) @@ -514,37 +613,69 @@ class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { } class TransparentArrowButtonUI : BasicComboBoxUI() { - override fun createArrowButton() = object : JButton() { - override fun paintComponent(g: Graphics) { - val g2 = g as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - val size = 6 - val x = (width - size) / 2 - val y = (height - size / 2) / 2 - val triangle = Polygon( - intArrayOf(x, x + size, x + size / 2), - intArrayOf(y, y, (y + size / 1.16).toInt()), - 3 - ) - g2.color = Color.GRAY - g2.fill(triangle) - } - }.apply { - border = EmptyBorder(0, 0, 0, 0) -// background = Color(0, 0, 0, 0) - isOpaque = false + override fun createArrowButton() = JButton().apply { + isVisible = false + preferredSize = Dimension(0, 0) } override fun getInsets(): Insets { - return JBUI.insets(0, 0, 0, 0) + return JBUI.insets(0, 6, 0, 0) } override fun installUI(c: JComponent?) { super.installUI(c) - comboBox.border = EmptyBorder(0, 0, 0, 0) comboBox.isOpaque = false val globalScheme = EditorColorsManager.getInstance().globalScheme val defaultBackground = globalScheme.defaultBackground comboBox.background = defaultBackground + + // Modify the ComboBoxModel to include the down symbol + val originalModel = comboBox.model + comboBox.model = object : ComboBoxModel { + override fun getSize(): Int = originalModel.size + override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) + override fun setSelectedItem(anItem: Any?) { + originalModel.selectedItem = anItem + } + + override fun getSelectedItem(): Any? { + val item = originalModel.selectedItem + return "$item ▾" + } + + override fun addListDataListener(l: ListDataListener?) { + originalModel.addListDataListener(l) + } + + override fun removeListDataListener(l: ListDataListener?) { + originalModel.removeListDataListener(l) + } + } } -} \ No newline at end of file + + + override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + // Do nothing to prevent painting the background + } + + + override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + val renderer = comboBox.renderer + val item = comboBox.selectedItem + + if (item != null) { + val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) + c.font = comboBox.font + c.foreground = Color(156, 163, 175) // text-gray-400 + c.background = comboBox.background + + if (c is JComponent) { + c.isOpaque = false + } + + val currentValuePane = currentValuePane + currentValuePane.paintComponent(g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true) + } + } +} + diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt index 7d5ba7c08..5651a033d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt @@ -2,71 +2,96 @@ import com.github.continuedev.continueintellijextension.actions.focusContinueInp import com.github.continuedev.continueintellijextension.editor.openInlineEdit import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.ui.components.JBPanel import java.awt.* import java.awt.event.ActionEvent +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent import java.util.* import javax.swing.JButton import java.awt.geom.RoundRectangle2D -class StyledButton(text: String, foregroundColor: Color) : JButton(text) { +class StyledButton(text: String) : JButton(text) { + private var isHovered = false + private val editorBackground: Color + init { - cursor = Cursor(Cursor.HAND_CURSOR) - isOpaque = false + border = null isContentAreaFilled = false isFocusPainted = false - border = null // Remove the border - foreground = foregroundColor + cursor = Cursor(Cursor.HAND_CURSOR) + + val scheme = EditorColorsManager.getInstance().globalScheme + val editorFont = scheme.getFont(EditorFontType.PLAIN) + val editorFontSize = editorFont.size + + font = font.deriveFont(editorFontSize.toFloat() * 0.75f) + + editorBackground = scheme.defaultBackground + + addMouseListener(object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent) { + isHovered = true + repaint() + } + + override fun mouseExited(e: MouseEvent) { + isHovered = false + repaint() + } + }) } + override fun paintComponent(g: Graphics) { val g2 = g.create() as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - val arc = 24f // Corner radius - val padding = 0f - val x = padding - val y = padding - val w = (width - 2 * padding) - val h = (height - 2 * padding) + val width = width.toFloat() + val height = height.toFloat() + val arc = 6f - // Draw flat background -// g2.color = if (model.isPressed) Color(70, 70, 70) else Color(100, 100, 100) -// g2.fill(RoundRectangle2D.Float(x, y, w, h, arc, arc)) + // Draw semi-transparent background + g2.color = editorBackground + g2.fill(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc)) // Draw border -// g2.color = Color(120, 120, 120) -// g2.draw(RoundRectangle2D.Float(x, y, w - 1, h - 1, arc, arc)) - - g2.dispose() + g2.color = if (isHovered) foreground else foreground.darker() + g2.stroke = BasicStroke(1f) + g2.draw(RoundRectangle2D.Float(0.5f, 0.5f, width - 1f, height - 1f, arc, arc)) super.paintComponent(g) + g2.dispose() } } + class ToolTipComponent(editor: Editor, x: Int, y: Int) : JBPanel() { private var addToChatButton: StyledButton private var editButton: StyledButton - private var backgroundColor: Color - private var foregroundColor: Color init { layout = null // Remove the FlowLayout - val globalScheme = EditorColorsManager.getInstance().globalScheme - backgroundColor = globalScheme.defaultBackground - foregroundColor = Color( - globalScheme.defaultForeground.red, - globalScheme.defaultForeground.green, - globalScheme.defaultForeground.blue, - 200 - ) + // Make the background transparent + isOpaque = false + background = Color(0, 0, 0, 0) - val cmdCtrlChar = if (System.getProperty("os.name").lowercase(Locale.getDefault()).contains("mac")) "⌘" else "Ctrl" - addToChatButton = StyledButton("${cmdCtrlChar}J Chat", foregroundColor) - editButton = StyledButton("${cmdCtrlChar}I Edit", foregroundColor) + val cmdCtrlChar = + if (System.getProperty("os.name").lowercase(Locale.getDefault()).contains("mac")) "⌘" else "Ctrl" + + val buttonHeight = 16 + val buttonHorizontalPadding = 2 + val buttonVerticalPadding = 2 + val componentHorizontalPadding = 4 + val buttonMargin = 4 + + addToChatButton = StyledButton("Chat (${cmdCtrlChar}J)") + editButton = StyledButton("Edit (${cmdCtrlChar}I)") addToChatButton.addActionListener { e: ActionEvent? -> focusContinueInput(editor.project) @@ -77,45 +102,28 @@ class ToolTipComponent(editor: Editor, x: Int, y: Int) : editor.contentComponent.remove(this) } - // Set bounds for buttons to remove spacing - addToChatButton.setBounds(0, 0, addToChatButton.preferredSize.width, addToChatButton.preferredSize.height) - editButton.setBounds(addToChatButton.preferredSize.width, 0, editButton.preferredSize.width, editButton.preferredSize.height) + + // Calculate button widths + val addToChatWidth = addToChatButton.preferredSize.width + (2 * buttonHorizontalPadding) + val editWidth = editButton.preferredSize.width + (2 * buttonHorizontalPadding) + + // Set bounds for buttons + addToChatButton.setBounds(componentHorizontalPadding, buttonVerticalPadding, addToChatWidth, buttonHeight) + editButton.setBounds( + componentHorizontalPadding + addToChatWidth + buttonMargin, + buttonVerticalPadding, + editWidth, + buttonHeight + ) add(addToChatButton) add(editButton) - val totalWidth = addToChatButton.preferredSize.width + editButton.preferredSize.width - val totalHeight = addToChatButton.preferredSize.height - setBounds(x, y, totalWidth, totalHeight) + val totalWidth = addToChatWidth + editWidth + buttonMargin + (2 * componentHorizontalPadding) + val totalHeight = buttonHeight + (2 * buttonVerticalPadding) - // Make the background transparent - isOpaque = false - background = Color(0, 0, 0, 0) - } - - override fun paintComponent(g: Graphics) { - val arc = 12f - - val g2 = g.create() as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - - // Draw rounded rectangle background - g2.color = backgroundColor - g2.fill(RoundRectangle2D.Float(0f, 0f, width.toFloat(), height.toFloat(), arc, arc)) - - // Draw rounded rectangle border - g2.color = Color(120, 120, 120) - val strokeWidth = 1.0f - g2.stroke = BasicStroke(1.0f) - g2.draw(RoundRectangle2D.Float(0f, 0f, width.toFloat() - strokeWidth, height.toFloat() - strokeWidth, arc, arc)) - - // Draw border between buttons - g2.color = Color(120, 120, 120) - g2.stroke = BasicStroke(1.0f) - val middleX = addToChatButton.width.toFloat() - g2.drawLine(middleX.toInt(), 0, middleX.toInt(), height) - - g2.dispose() - super.paintComponent(g) + // Center the component on the provided y coordinate + val yPosition = y - (totalHeight / 2) + setBounds(x, yPosition, totalWidth, totalHeight) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt index 8c4b2f8b7..fcc9c1d2f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt @@ -12,25 +12,44 @@ import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.event.SelectionListener -import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware -import com.intellij.openapi.vfs.VirtualFile +import com.intellij.openapi.util.TextRange import kotlinx.coroutines.CoroutineScope -import kotlin.math.max -import kotlin.math.min +import com.intellij.openapi.editor.Document class ContinuePluginSelectionListener( private val ideProtocolClient: IdeProtocolClient, private val coroutineScope: CoroutineScope ) : SelectionListener, DumbAware { - private val debouncer = Debouncer(100L, coroutineScope) + private val debouncer = Debouncer(100, coroutineScope) + private var toolTipComponents: ArrayList = ArrayList() + override fun selectionChanged(e: SelectionEvent) { debouncer.debounce { handleSelection(e) } } - private var toolTipComponents: ArrayList = ArrayList() + private fun handleSelection(e: SelectionEvent) { + ApplicationManager.getApplication().runReadAction { + val editor = e.editor + val model: SelectionModel = editor.selectionModel + val selectedText = model.selectedText - private fun removeExistingTooltips(editor: Editor, onComplete : () -> Unit = {}) { + if (shouldRemoveTooltip(selectedText, editor)) { + removeExistingTooltips(editor) + return@runReadAction + } + + updateTooltip(editor, model) + } + } + + private fun shouldRemoveTooltip(selectedText: String?, editor: Editor): Boolean { + return selectedText.isNullOrEmpty() || + !service().continueState.displayEditorTooltip || + EditorUtils().isTerminal(editor) + } + + private fun removeExistingTooltips(editor: Editor, onComplete: () -> Unit = {}) { ApplicationManager.getApplication().invokeLater { toolTipComponents.forEach { editor.contentComponent.remove(it) @@ -42,76 +61,114 @@ class ContinuePluginSelectionListener( } } - private fun handleSelection(e: SelectionEvent) { - ApplicationManager.getApplication().runReadAction { - val editor = e.editor - val model: SelectionModel = editor.selectionModel - val selectedText = model.selectedText + private fun updateTooltip(editor: Editor, model: SelectionModel) { + removeExistingTooltips(editor) { + ApplicationManager.getApplication().invokeLater { + val document = editor.document + val (startLine, endLine, isFullLineSelection) = getSelectionInfo(model, document) + val selectionTopY = calculateSelectionTopY(editor, startLine, endLine, isFullLineSelection) + val tooltipX = calculateTooltipX(editor, document, startLine, endLine, isFullLineSelection) - // If selected text is empty, remove the tooltip - if (selectedText.isNullOrEmpty()) { - removeExistingTooltips(editor) - return@runReadAction - } - - // Allow user to disable editor tooltip - // Note that we still check for empty selected text before this - val extensionSettingsService = service() - if (extensionSettingsService.continueState.displayEditorTooltip == false) { - return@runReadAction - } - - // Don't display in the terminal - if (EditorUtils().isTerminal(editor)) { - return@runReadAction - } - - val document = editor.document - val startOffset = model.selectionStart - val endOffset = model.selectionEnd - val startLine = document.getLineNumber(startOffset) - val endLine = document.getLineNumber(endOffset) - val startCharacter = - startOffset - document.getLineStartOffset(startLine) - val endCharacter = endOffset - document.getLineStartOffset(endLine) - - val virtualFile: VirtualFile? = - FileDocumentManager.getInstance().getFile(document) - val filepath = virtualFile?.path ?: "Unknown path" - - - removeExistingTooltips(editor) { - ApplicationManager.getApplication().invokeLater { - editor.contentComponent.layout = null - - val line = startLine - 2 - if (line > 0 && startLine < endLine) { - // Get the text on line number "line" -// val text = document.getText(document.getLineStartOffset(line), document.getLineEndOffset(line)) - - val pos = LogicalPosition(line, selectedText.split("\n")[0].length + 1) - val y: Int = editor.logicalPositionToXY(pos).y + editor.lineHeight - var x: Int = editor.logicalPositionToXY(pos).x - - // Check if x is out of bounds - val maxEditorWidth = editor.contentComponent.width - val maxToolTipWidth = 600 - x = max(0, min(x, maxEditorWidth - maxToolTipWidth)) - - val toolTipComponent = ToolTipComponent(editor, x, y) - toolTipComponents.add(toolTipComponent) - editor.contentComponent.add(toolTipComponent) - } - - editor.contentComponent.revalidate() - editor.contentComponent.repaint() + if (tooltipX != null) { + addToolTipComponent(editor, tooltipX, selectionTopY) } } } } + + private fun getSelectionInfo(model: SelectionModel, document: Document): Triple { + val startOffset = model.selectionStart + val endOffset = model.selectionEnd + val startLine = document.getLineNumber(startOffset) + val endLine = document.getLineNumber(endOffset) + + val isFullLineSelection = startOffset == document.getLineStartOffset(startLine) && + (endOffset == document.getLineEndOffset(endLine - 1) || endOffset == document.getLineStartOffset(endLine)) + + val adjustedEndLine = if (isFullLineSelection && endLine > startLine) endLine - 1 else endLine + + return Triple(startLine, adjustedEndLine, isFullLineSelection) + } + + private fun calculateSelectionTopY( + editor: Editor, + startLine: Int, + endLine: Int, + isFullLineSelection: Boolean + ): Int { + return if (startLine == endLine || isFullLineSelection) { + val lineTopY = editor.logicalPositionToXY(LogicalPosition(startLine, 0)).y + lineTopY + (editor.lineHeight / 2) + } else { + editor.logicalPositionToXY(LogicalPosition(startLine, 0)).y + } + } + + private fun calculateTooltipX( + editor: Editor, + document: Document, + startLine: Int, + endLine: Int, + isFullLineSelection: Boolean + ): Int? { + fun isLineEmpty(lineNumber: Int): Boolean { + val lineStartOffset = document.getLineStartOffset(lineNumber) + val lineEndOffset = document.getLineEndOffset(lineNumber) + return document.getText(TextRange(lineStartOffset, lineEndOffset)).trim().isEmpty() + } + + fun getLineEndX(lineNumber: Int): Int { + val lineStartOffset = document.getLineStartOffset(lineNumber) + val lineEndOffset = document.getLineEndOffset(lineNumber) + val lineText = document.getText(TextRange(lineStartOffset, lineEndOffset)).trimEnd() + val endOfLinePos = LogicalPosition(lineNumber, lineText.length) + return editor.logicalPositionToXY(endOfLinePos).x + } + + val offset = 40 + + // If only one line is selected and it's empty, return null + if (startLine == endLine && isLineEmpty(startLine) && !isFullLineSelection) { + return null + } + + // Find the topmost non-empty line within the selection + var topNonEmptyLine = startLine + while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) { + topNonEmptyLine++ + } + + // If all lines in the selection are empty, return null + if (topNonEmptyLine > endLine) { + return null + } + + // Always display inline if the selection is a single line + if (isFullLineSelection || startLine == endLine) { + return getLineEndX(topNonEmptyLine) + offset + } + + // Check the line above the start of the selection (if it exists) + val lineAboveSelection = maxOf(0, startLine - 1) + + // Get x-coordinates + val xCoordTopNonEmpty = getLineEndX(topNonEmptyLine) + val xCoordLineAbove = getLineEndX(lineAboveSelection) + + // Use the maximum of the two x-coordinates + val baseXCoord = maxOf(xCoordTopNonEmpty, xCoordLineAbove) + + // Calculate the final x-coordinate + return baseXCoord + offset + } + + private fun addToolTipComponent(editor: Editor, tooltipX: Int, selectionTopY: Int) { + val toolTipComponent = ToolTipComponent(editor, tooltipX, selectionTopY) + toolTipComponents.add(toolTipComponent) + editor.contentComponent.add(toolTipComponent) + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } } - - - diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 30eb27204..71a019af4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -27,7 +27,7 @@ class ContinueSettingsComponent: DumbAware { val remoteConfigSyncPeriod: JTextField = JTextField() val userToken: JTextField = JTextField() val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete") - val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta (requires restart)") + val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta") val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") init { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 0d1f7f169..6321e0c44 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.activities.showTutorial +import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory @@ -8,7 +9,6 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser -import com.intellij.openapi.Disposable import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index ada642dac..52111bc83 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -5,7 +5,8 @@ continue-dev com.intellij.modules.platform com.intellij.modules.json - + + diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 6692f2de7..3f340f6ce 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -699,8 +699,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "anyOf": [ @@ -796,8 +805,14 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1017,8 +1032,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] @@ -1528,7 +1552,8 @@ "url", "database", "os", - "repo-map" + "repo-map", + "greptile" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1552,7 +1577,8 @@ "Reference the contents of a page at a URL", "Reference table schemas", "Operating system and CPU Information", - "Map of files in the repository with important code highlights" + "Map of files in the repository with important code highlights", + "Query your greptile index of the current repo" ], "type": "string" }, @@ -1930,6 +1956,36 @@ }, "required": ["host", "port", "user", "password", "database"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["greptile"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "GithubToken": { + "title": "GithubToken", + "description": "Your github access token", + "default": "", + "type": "string" + }, + "GreptileToken": { + "title": "GreptileToken", + "description": "Your greptile access token", + "default": "", + "type": "string" + } + } + } + }, + "required": ["GreptileToken", "GithubToken"] + } } ], "required": ["name"] diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index ffa85e2d1..7ea557b25 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -6,10 +6,17 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes +### Added +* Improved loading/accept/reject UI for apply +* Polished chat sidebar, especially context dropdown +* Further prompt caching with Anthropic ### Changed * Updated tutorial file +* Improved styling on "More" page ### Fixed * Continue for teams auth bug fix +* Fixed a number of apply bugs +* Fixed autoscrolling behavior ## 0.9.210 - 2024-09-15 diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 6692f2de7..3f340f6ce 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -699,8 +699,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "anyOf": [ @@ -796,8 +805,14 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1017,8 +1032,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] @@ -1528,7 +1552,8 @@ "url", "database", "os", - "repo-map" + "repo-map", + "greptile" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1552,7 +1577,8 @@ "Reference the contents of a page at a URL", "Reference table schemas", "Operating system and CPU Information", - "Map of files in the repository with important code highlights" + "Map of files in the repository with important code highlights", + "Query your greptile index of the current repo" ], "type": "string" }, @@ -1930,6 +1956,36 @@ }, "required": ["host", "port", "user", "password", "database"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["greptile"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "GithubToken": { + "title": "GithubToken", + "description": "Your github access token", + "default": "", + "type": "string" + }, + "GreptileToken": { + "title": "GreptileToken", + "description": "Your greptile access token", + "default": "", + "type": "string" + } + } + } + }, + "required": ["GreptileToken", "GithubToken"] + } } ], "required": ["name"] diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 4095e0fa0..26877d8a3 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -756,8 +756,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "anyOf": [ @@ -872,8 +881,14 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1115,8 +1130,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1699,7 +1723,8 @@ "url", "database", "os", - "repo-map" + "repo-map", + "greptile" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1723,7 +1748,8 @@ "Reference the contents of a page at a URL", "Reference table schemas", "Operating system and CPU Information", - "Map of files in the repository with important code highlights" + "Map of files in the repository with important code highlights", + "Query your greptile index of the current repo" ], "type": "string" }, @@ -2166,6 +2192,41 @@ "database" ] } + }, + { + "if": { + "properties": { + "name": { + "enum": [ + "greptile" + ] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "GithubToken": { + "title": "GithubToken", + "description": "Your github access token", + "default": "", + "type": "string" + }, + "GreptileToken": { + "title": "GreptileToken", + "description": "Your greptile access token", + "default": "", + "type": "string" + } + } + } + }, + "required": [ + "GreptileToken", + "GithubToken" + ] + } } ], "required": [ diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 0eb4461d9..5bfd16377 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.212", + "version": "0.9.214", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.212", + "version": "0.9.214", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -125,6 +125,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 653922315..193546288 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.212", + "version": "0.9.214", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -77,7 +77,7 @@ "continue.enableContinueForTeams": { "type": "boolean", "default": false, - "markdownDescription": "_(Requires window reload)_ Enable Continue for teams beta features. To sign in, click the person icon in the bottom right of the sidebar." + "markdownDescription": "Enable Continue for teams beta features. To sign in, click the person icon in the bottom right of the sidebar." }, "continue.showInlineTip": { "type": "boolean", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index ed7139636..e2fa97c9d 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -87,6 +87,7 @@ class VsCodeIde implements IDE { const session = await vscode.authentication.getSession("github", [], { silent: true, }); + if (session) { this.authToken = session.accessToken; return this.authToken; diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 220b259d5..f24b23bf3 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,4 +1,4 @@ -import type { IDE, RangeInFile } from "core"; +import type { IDE, Range, RangeInFile } from "core"; import { getAst, getTreePathAtCursor } from "core/autocomplete/ast"; import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/languages"; @@ -303,6 +303,19 @@ export async function getDefinitionsForNode( } return await Promise.all( ranges.map(async (rif) => { + // Convert the VS Code Range type to ours + const range: Range = { + start: { + line: rif.range.start.line, + character: rif.range.start.character, + }, + end: { + line: rif.range.end.line, + character: rif.range.end.character, + }, + }; + rif.range = range; + if (!isRifWithContents(rif)) { return { ...rif, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6bec8b754..0edf63227 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -223,6 +223,7 @@ const commandsMap: ( await verticalDiffManager.streamEdit( config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, modelTitle, + undefined, onlyOneInsertion, undefined, range, @@ -640,6 +641,12 @@ const commandsMap: ( : StatusBarStatus.Disabled; } quickPick.items = [ + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, { label: quickPickStatusText(targetStatus), }, @@ -684,6 +691,13 @@ const commandsMap: ( configHandler.reloadConfig(); } else if (selectedOption === "$(feedback) Give feedback") { vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); } quickPick.dispose(); }); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 9259cb38e..5aa5b070b 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -1,4 +1,5 @@ import type { DiffLine } from "core"; +import { ApplyState } from "core/protocol/ideWebview"; import * as vscode from "vscode"; import { DecorationTypeRangeManager, @@ -12,6 +13,7 @@ import type { VerticalDiffCodeLens } from "./manager"; export interface VerticalDiffHandlerOptions { input?: string; instant?: boolean; + onStatusUpdate: (status: ApplyState["status"]) => void; } export class VerticalDiffHandler implements vscode.Disposable { @@ -268,6 +270,8 @@ export class VerticalDiffHandler implements vscode.Disposable { }, ); + this.options.onStatusUpdate("closed"); + this.cancelled = true; this.refreshCodeLens(); this.dispose(); @@ -352,6 +356,8 @@ export class VerticalDiffHandler implements vscode.Disposable { this.refreshCodeLens(); + this.options.onStatusUpdate("done"); + // Reject on user typing // const listener = vscode.workspace.onDidChangeTextDocument((e) => { // if (e.document.uri.fsPath === this.filepath) { diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index c84fa4397..2ecf6d596 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -5,6 +5,7 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { DiffLine } from "core"; import { streamDiffLines } from "core/edit/streamDiffLines"; import * as vscode from "vscode"; +import { VsCodeWebviewProtocol } from "../../webviewProtocol"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -22,7 +23,10 @@ export class VerticalDiffManager { private userChangeListener: vscode.Disposable | undefined; - constructor(private readonly configHandler: ConfigHandler) { + constructor( + private readonly configHandler: ConfigHandler, + private readonly webviewProtocol: VsCodeWebviewProtocol, + ) { this.userChangeListener = undefined; } @@ -176,6 +180,7 @@ export class VerticalDiffManager { async streamDiffLines( diffStream: AsyncGenerator, instant: boolean, + streamId: string, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -205,6 +210,11 @@ export class VerticalDiffManager { endLine, { instant, + onStatusUpdate: (status) => + this.webviewProtocol.request("updateApplyState", { + streamId, + status, + }), }, ); @@ -271,6 +281,7 @@ export class VerticalDiffManager { async streamEdit( input: string, modelTitle: string | undefined, + streamId?: string, onlyOneInsertion?: boolean, quickEdit?: string, range?: vscode.Range, @@ -339,7 +350,15 @@ export class VerticalDiffManager { filepath, startLine, endLine, - { input }, + { + input, + onStatusUpdate: (status) => + streamId && + this.webviewProtocol.request("updateApplyState", { + streamId, + status, + }), + }, ); if (!diffHandler) { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 68714b106..674a80d1f 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -24,6 +24,7 @@ import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; +import { arePathsEqual } from "../util/arePathsEqual"; import { Battery } from "../util/battery"; import { AUTH_TYPE, EXTENSION_NAME } from "../util/constants"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; @@ -124,7 +125,10 @@ export class VsCodeExtension { resolveConfigHandler?.(this.configHandler); this.configHandler.reloadConfig(); - this.verticalDiffManager = new VerticalDiffManager(this.configHandler); + this.verticalDiffManager = new VerticalDiffManager( + this.configHandler, + this.sidebar.webviewProtocol, + ); resolveVerticalDiffManager?.(this.verticalDiffManager); this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); @@ -225,7 +229,7 @@ export class VsCodeExtension { // Listen for file changes in the workspace const filepath = event.uri.fsPath; - if (filepath === getConfigJsonPath()) { + if (arePathsEqual(filepath, getConfigJsonPath())) { // Trigger a toast notification to provide UI feedback that config // has been updated const showToast = context.globalState.get( @@ -327,6 +331,16 @@ export class VsCodeExtension { this.ide.onDidChangeActiveTextEditor((filepath) => { this.core.invoke("didChangeActiveTextEditor", { filepath }); }); + + vscode.workspace.onDidChangeConfiguration(async (event) => { + if (event.affectsConfiguration(EXTENSION_NAME)) { + const settings = this.ide.getIdeSettingsSync(); + const webviewProtocol = await this.webviewProtocolPromise; + webviewProtocol.request("didChangeIdeSettings", { + settings, + }); + } + }); } static continueVirtualDocumentScheme = EXTENSION_NAME; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 0e5b91b88..c0b62fdbc 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -191,10 +191,30 @@ export class VsCodeMessenger { ); const verticalDiffManager = await this.verticalDiffManagerPromise; if (instant) { - verticalDiffManager.streamDiffLines(diffLines, instant); + verticalDiffManager.streamDiffLines( + diffLines, + instant, + msg.data.streamId, + ); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`; - verticalDiffManager.streamEdit(prompt, llm.title); + const fullEditorRange = new vscode.Range( + 0, + 0, + editor.document.lineCount - 1, + editor.document.lineAt(editor.document.lineCount - 1).text.length, + ); + const rangeToApplyTo = editor.selection.isEmpty + ? fullEditorRange + : editor.selection; + verticalDiffManager.streamEdit( + prompt, + llm.title, + msg.data.streamId, + undefined, + undefined, + rangeToApplyTo, + ); } }); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts index 94a68bac7..a96cf5660 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts @@ -1,6 +1,6 @@ import * as vscode from "vscode"; import { VerticalDiffCodeLens } from "../../../diff/vertical/manager"; -import { getAltOrOption, getMetaKeyLabel } from "../../../util/util"; +import { getMetaKeyLabel } from "../../../util/util"; export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider { private _eventEmitter: vscode.EventEmitter = @@ -33,9 +33,6 @@ export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider { const codeLenses: vscode.CodeLens[] = []; for (let i = 0; i < blocks.length; i++) { - const isFirstBlockInMultiBlockDocument = - codeLenses.length === 0 && blocks.length > 1; - const block = blocks[i]; const start = new vscode.Position(block.start, 0); const range = new vscode.Range( @@ -43,43 +40,20 @@ export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider { start.translate(block.numGreen + block.numRed), ); - if (isFirstBlockInMultiBlockDocument) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `Accept All (${getMetaKeyLabel()}⇧↩)`, - command: "continue.acceptDiff", - arguments: [filepath, i], - }), - new vscode.CodeLens(range, { - title: `Reject All (${getMetaKeyLabel()}⇧⌫)`, - command: "continue.rejectDiff", - arguments: [filepath, i], - }), - ); - } - codeLenses.push( new vscode.CodeLens(range, { - title: `Accept${ - codeLenses.length === 2 - ? ` (${getAltOrOption()}${getMetaKeyLabel()}Y)` - : "" - }`, + title: `Accept`, command: "continue.acceptVerticalDiffBlock", arguments: [filepath, i], }), new vscode.CodeLens(range, { - title: `Reject${ - codeLenses.length === 2 - ? ` (${getAltOrOption()}${getMetaKeyLabel()}N)` - : "" - }`, + title: `Reject`, command: "continue.rejectVerticalDiffBlock", arguments: [filepath, i], }), ); - if (codeLenses.length === 4) { + if (codeLenses.length === 2) { codeLenses.push( new vscode.CodeLens(range, { title: `${getMetaKeyLabel()}I to add instructions`, diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 59b7ad41f..0c0b276a8 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -13,6 +13,7 @@ import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; import { ConfigHandler } from "core/config/ConfigHandler"; // @ts-ignore import { getModelByRole } from "core/config/util"; +// @ts-ignore import MiniSearch from "minisearch"; /** @@ -295,6 +296,7 @@ export class QuickEdit { prompt, modelTitle, undefined, + undefined, this.previousInput, this.range, ); diff --git a/extensions/vscode/src/util/arePathsEqual.ts b/extensions/vscode/src/util/arePathsEqual.ts new file mode 100644 index 000000000..cd10e5399 --- /dev/null +++ b/extensions/vscode/src/util/arePathsEqual.ts @@ -0,0 +1,11 @@ +import * as os from "os"; + +export function arePathsEqual(path1: string, path2: string): boolean { + if (os.platform() === "win32") { + // On Windows, compare paths case-insensitively + return path1.toLowerCase() === path2.toLowerCase(); + } else { + // On other platforms, compare paths case-sensitively + return path1 === path2; + } +} diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index a2f2e3f9f..635f65182 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -136,10 +136,30 @@ export class VsCodeIdeUtils { ); } - openFile(filepath: string, range?: vscode.Range) { + private async resolveAbsFilepathInWorkspace( + filepath: string, + ): Promise { + // If the filepath is already absolute, return it as is + if (this.path.isAbsolute(filepath)) { + return filepath; + } + + // Try to resolve for each workspace directory + const workspaceDirectories = this.getWorkspaceDirectories(); + for (const dir of workspaceDirectories) { + const resolvedPath = this.path.resolve(dir, filepath); + if (await this.fileExists(resolvedPath)) { + return resolvedPath; + } + } + + return filepath; + } + + async openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files return openEditorAndRevealRange( - filepath, + await this.resolveAbsFilepathInWorkspace(filepath), range, vscode.ViewColumn.One, false, @@ -226,7 +246,7 @@ export class VsCodeIdeUtils { .flat() .filter(Boolean) // filter out undefined values .filter((uri) => this.documentIsCode(uri)) // Filter out undesired documents - .map((uri) => uri.fsPath); + .map((uri) => uriFromFilePath(uri.fsPath).fsPath); } getVisibleFiles(): string[] { diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm index 0aeccc319..8b8b90a19 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm @@ -12,4 +12,4 @@ (interface_declaration name: (_) @name.definition.interface -) @definition.interface \ No newline at end of file +) @definition.interface diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm index 3b6153c90..a99e33ced 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm @@ -19,4 +19,4 @@ name: (_) @name parameters: (_) @parameters ) @definition -) \ No newline at end of file +) diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm index 124de18ea..4240ecef5 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm @@ -5,4 +5,4 @@ name: (name) @name) @definition (method_declaration - name: (name) @name) @definition \ No newline at end of file + name: (name) @name) @definition diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm index 586d738c7..235a953df 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm @@ -4,4 +4,4 @@ (function_definition name: (_) @name parameters: (_) @parameters -) @definition \ No newline at end of file +) @definition diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm index 4b10e7c34..4eda6b166 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm @@ -8,4 +8,4 @@ name: (_) @name) @definition (impl_item - type: (_) @name) @definition \ No newline at end of file + type: (_) @name) @definition diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm index d564f406a..2316d733f 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm @@ -25,4 +25,4 @@ (comment)? @comment (interface_declaration name: (_) @name) @definition -) \ No newline at end of file +) diff --git a/extensions/vscode/tree-sitter/import-queries/cpp.scm b/extensions/vscode/tree-sitter/import-queries/cpp.scm new file mode 100644 index 000000000..c740cf762 --- /dev/null +++ b/extensions/vscode/tree-sitter/import-queries/cpp.scm @@ -0,0 +1,9 @@ +(using_declaration + (qualified_identifier + (identifier) @a)) + +(namespace_alias_definition + (nested_namespace_specifier) @b) + +(preproc_include + (system_lib_string) @c) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/import-queries/java.scm b/extensions/vscode/tree-sitter/import-queries/java.scm new file mode 100644 index 000000000..51920eda7 --- /dev/null +++ b/extensions/vscode/tree-sitter/import-queries/java.scm @@ -0,0 +1,3 @@ +(import_declaration + (scoped_identifier + (identifier) @import)) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/import-queries/python.scm b/extensions/vscode/tree-sitter/import-queries/python.scm new file mode 100644 index 000000000..dedaf23aa --- /dev/null +++ b/extensions/vscode/tree-sitter/import-queries/python.scm @@ -0,0 +1,8 @@ +(import_from_statement + (dotted_name) ; skip the first (this is the module) + (dotted_name + (identifier) @importa)) + +(import_statement + (dotted_name + (identifier) @importb )) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm new file mode 100644 index 000000000..c0d936f5e --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm @@ -0,0 +1,9 @@ +( + (function_declaration + (formal_parameters + (_ + (type_annotation) @type + ) + ) + ) +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/cpp.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/cpp.scm new file mode 100644 index 000000000..2610f5393 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/cpp.scm @@ -0,0 +1,13 @@ +(function_definition + (function_declarator + (parameter_list + (parameter_declaration + (type_identifier) @a + ) + ) + ) +) + +(function_definition + (type_identifier) @b +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/python.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/python.scm new file mode 100644 index 000000000..864666a4a --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/python.scm @@ -0,0 +1,17 @@ +( + (function_definition + (parameters + (_ + (type) @a + (#not-match? @a "^(str|int|float|bool|list|dict|tuple)$") + ) + ) + ) +) + +( + (function_definition + (type) @b + (#not-match? @b "^(str|int|float|bool|list|dict|tuple)$") + ) +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/java.scm b/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/java.scm new file mode 100644 index 000000000..ff77555c7 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/java.scm @@ -0,0 +1,13 @@ +; Method parameters +(method_declaration + (formal_parameters + (formal_parameter + (type_identifier) @a + ) + ) +) + +; Return type +(method_declaration + (type_identifier) @b +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm new file mode 100644 index 000000000..10ee28346 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm @@ -0,0 +1,9 @@ +( + (method_definition + (formal_parameters + (_ + (type_annotation) @type + ) + ) + ) +) \ No newline at end of file diff --git a/gui/package-lock.json b/gui/package-lock.json index 490db589c..9c10b7f68 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -118,6 +118,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 9cf442727..f5ef97e67 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -12,7 +12,7 @@ import GUI from "./pages/gui"; import History from "./pages/history"; import MigrationPage from "./pages/migration"; import MonacoPage from "./pages/monaco"; -import { default as More, default as MorePage } from "./pages/more"; +import MorePage from "./pages/More"; import SettingsPage from "./pages/settings"; import Stats from "./pages/stats"; @@ -38,10 +38,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: "/help", - element: , - }, { path: "/settings", element: , diff --git a/gui/src/components/ButtonWithTooltip.tsx b/gui/src/components/ButtonWithTooltip.tsx index 005b82001..f692133a1 100644 --- a/gui/src/components/ButtonWithTooltip.tsx +++ b/gui/src/components/ButtonWithTooltip.tsx @@ -1,4 +1,4 @@ -import React, { useState } from "react"; +import React from "react"; import ReactDOM from "react-dom"; import { type PlacesType } from "react-tooltip"; import { HeaderButton } from "."; @@ -25,7 +25,6 @@ const ButtonWithTooltip = React.forwardRef< HTMLButtonElement, HeaderButtonWithTextProps >((props: HeaderButtonWithTextProps, ref) => { - const [hover, setHover] = useState(false); const id = uuidv4(); const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); @@ -39,14 +38,6 @@ const ButtonWithTooltip = React.forwardRef< data-tooltip-id={tooltipId} inverted={props.inverted} disabled={props.disabled} - onMouseEnter={() => { - if (!props.disabled) { - setHover(true); - } - }} - onMouseLeave={() => { - setHover(false); - }} onClick={props.onClick} onKeyDown={props.onKeyDown} className={props.className} diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx new file mode 100644 index 000000000..671b000fb --- /dev/null +++ b/gui/src/components/Footer.tsx @@ -0,0 +1,76 @@ +import { + Cog6ToothIcon, + EllipsisHorizontalCircleIcon, +} from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { useSelector } from "react-redux"; +import { useNavigate } from "react-router-dom"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { RootState } from "../redux/store"; +import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; +import ButtonWithTooltip from "./ButtonWithTooltip"; +import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; +import ProfileSwitcher from "./ProfileSwitcher"; + +function Footer() { + const navigate = useNavigate(); + const defaultModel = useSelector(defaultModelSelector); + const ideMessenger = useContext(IdeMessengerContext); + const selectedProfileId = useSelector( + (store: RootState) => store.state.selectedProfileId, + ); + + function onClickMore() { + if (location.pathname === "/more") { + navigate("/"); + } else { + navigate("/more"); + } + } + + function onClickSettings() { + if (selectedProfileId === "local") { + ideMessenger.post("openConfigJson", undefined); + } else { + ideMessenger.post( + "openUrl", + `http://app.continue.dev/workspaces/${selectedProfileId}/config`, + ); + } + } + + return ( +
+
+ + {defaultModel?.provider === "free-trial" && ( + + )} +
+ +
+ + + + + + + +
+
+ ); +} + +export default Footer; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index d012194a3..f0213197b 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -1,35 +1,18 @@ -import { EllipsisHorizontalCircleIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { - CustomScrollbarDiv, - defaultBorderRadius, - vscForeground, - vscInputBackground, -} from "."; +import { CustomScrollbarDiv, defaultBorderRadius, vscInputBackground } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { RootState } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; -import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import TextDialog from "./dialogs"; -import ProgressBar from "./loaders/ProgressBar"; import PostHogPageView from "./PosthogPageView"; -import ProfileSwitcher from "./ProfileSwitcher"; -import { isNewUserOnboarding } from "./OnboardingCard/utils"; -import { useOnboardingCard } from "./OnboardingCard"; -import { - setBottomMessage, - setBottomMessageCloseTimeout, - setShowDialog, -} from "../redux/slices/uiStateSlice"; -import ButtonWithTooltip from "./ButtonWithTooltip"; - -const FOOTER_HEIGHT = "1.8em"; +import Footer from "./Footer"; +import { updateApplyState, setShowDialog } from "../redux/slices/uiStateSlice"; +import TextDialog from "./dialogs"; +import { useOnboardingCard, isNewUserOnboarding } from "./OnboardingCard"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -48,39 +31,6 @@ const LayoutTopDiv = styled(CustomScrollbarDiv)` } `; -const BottomMessageDiv = styled.div<{ displayOnBottom: boolean }>` - position: fixed; - bottom: ${(props) => (props.displayOnBottom ? "50px" : undefined)}; - top: ${(props) => (props.displayOnBottom ? undefined : "50px")}; - left: 0; - right: 0; - margin: 8px; - margin-top: 0; - background-color: ${vscInputBackground}; - color: ${vscForeground}; - border-radius: ${defaultBorderRadius}; - padding: 12px; - z-index: 100; - box-shadow: 0px 0px 2px 0px ${vscForeground}; - max-height: 35vh; -`; - -const Footer = styled.footer` - display: flex; - flex-direction: row; - gap: 8px; - justify-content: right; - padding: 8px; - align-items: center; - width: calc(100% - 16px); - height: ${FOOTER_HEIGHT}; - background-color: transparent; - backdrop-filter: blur(12px); - border-top: 1px solid rgba(136, 136, 136, 0.3); - border-bottom: 1px solid rgba(136, 136, 136, 0.3); - overflow: hidden; -`; - const GridDiv = styled.div` display: grid; grid-template-rows: 1fr auto; @@ -99,7 +49,7 @@ const ModelDropdownPortalDiv = styled.div` const ProfileDropdownPortalDiv = styled.div` background-color: ${vscInputBackground}; position: relative; - margin-left: calc(100% - 190px); + margin-left: 8px; z-index: 200; font-size: ${getFontSize() - 2}; `; @@ -118,15 +68,6 @@ const Layout = () => { (state: RootState) => state.uiState.showDialog, ); - const defaultModel = useSelector(defaultModelSelector); - - const bottomMessage = useSelector( - (state: RootState) => state.uiState.bottomMessage, - ); - const displayBottomMessageOnBottom = useSelector( - (state: RootState) => state.uiState.displayBottomMessageOnBottom, - ); - const timeline = useSelector((state: RootState) => state.state.history); useEffect(() => { @@ -187,6 +128,14 @@ const Layout = () => { [], ); + useWebviewListener( + "updateApplyState", + async (state) => { + dispatch(updateApplyState(state)); + }, + [], + ); + useWebviewListener( "openOnboardingCard", async () => { @@ -238,47 +187,8 @@ const Layout = () => { -
-
- {defaultModel?.provider === "free-trial" && ( - - )} -
- - - { - if (location.pathname === "/help") { - navigate("/"); - } else { - navigate("/help"); - } - }} - > - - -
+