diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 31b64bae1..b73cdb3ad 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -213,8 +213,8 @@ jobs: git config --local user.email "action@github.com" git config --local user.name "GitHub Action" - - name: Pull latest changes - run: git pull origin main + - name: Pull latest changes from release + run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }} # 1. Download the artifacts - uses: actions/download-artifact@v4 @@ -237,21 +237,3 @@ jobs: run: | cd extensions/vscode npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix - - # 4. Update the package.json version and push changes - # - name: Update version in package.json - # run: | - # cd extensions/vscode - # npm version patch - - # - name: Commit changes - # run: | - # git config --local user.email "action@github.com" - # git config --local user.name "GitHub Action" - # git commit -am "💚 Update package.json version [skip ci]" - - # - name: Push changes - # uses: ad-m/github-push-action@master - # with: - # github_token: ${{ secrets.GITHUB_TOKEN }} - # branch: ${{ github.ref }} diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 0df08f096..525834a95 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -2,7 +2,7 @@ import { IDE } from "../.."; import { RangeInFileWithContents } from "../../commands/util"; import { PrecalculatedLruCache } from "../../util/LruCache"; import { - TSQueryType, + getFullLanguageName, getParserForFile, getQueryForFile, } from "../../util/treeSitter"; @@ -47,7 +47,11 @@ export class ImportDefinitionsService { }, ], }); - const query = await getQueryForFile(filepath, TSQueryType.Imports); + const language = getFullLanguageName(filepath); + const query = await getQueryForFile( + filepath, + `import-queries/${language}.scm`, + ); if (!query) { return { imports: {}, diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index b4b742911..0147df151 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -4,7 +4,12 @@ import { LRUCache } from "lru-cache"; import Parser from "web-tree-sitter"; import { IDE } from "../../.."; -import { getQueryForFile } from "../../../util/treeSitter"; +import { + getFullLanguageName, + getQueryForFile, + IGNORE_PATH_PATTERNS, + LanguageName, +} from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; import { AutocompleteSnippet } from "../ranking"; @@ -40,6 +45,7 @@ export class RootPathContextService { private static TYPES_TO_USE = new Set([ "arrow_function", + "generator_function_declaration", "program", "function_declaration", "function_definition", @@ -68,6 +74,7 @@ export class RootPathContextService { node: Parser.SyntaxNode, ): Promise { const snippets: AutocompleteSnippet[] = []; + const language = getFullLanguageName(filepath); let query: Parser.Query | undefined; switch (node.type) { @@ -76,16 +83,15 @@ export class RootPathContextService { break; default: // const type = node.type; - // debugger; // console.log(getSyntaxTreeString(node)); + // debugger; query = await getQueryForFile( filepath, - `root-path-context-queries/${node.type}`, + `root-path-context-queries/${language}/${node.type}.scm`, ); break; } - const type = node.type; if (!query) { return snippets; @@ -93,9 +99,18 @@ export class RootPathContextService { const queries = query.matches(node).map(async (match) => { for (const item of match.captures) { - const endPosition = item.node.endPosition; - const newSnippets = await this.getSnippets(filepath, endPosition); - snippets.push(...newSnippets); + try { + const endPosition = item.node.endPosition; + const newSnippets = await this.getSnippets( + filepath, + endPosition, + language, + ); + snippets.push(...newSnippets); + } catch (e) { + debugger; + throw e; + } } }); @@ -107,6 +122,7 @@ export class RootPathContextService { private async getSnippets( filepath: string, endPosition: Parser.Point, + language: LanguageName, ): Promise { const definitions = await this.ide.gotoDefinition({ filepath, @@ -116,10 +132,18 @@ export class RootPathContextService { }, }); const newSnippets = await Promise.all( - definitions.map(async (def) => ({ - ...def, - contents: await this.ide.readRangeInFile(def.filepath, def.range), - })), + definitions + .filter((definition) => { + const isIgnoredPath = IGNORE_PATH_PATTERNS[language]?.some( + (pattern) => pattern.test(definition.filepath), + ); + + return !isIgnoredPath; + }) + .map(async (def) => ({ + ...def, + contents: await this.ide.readRangeInFile(def.filepath, def.range), + })), ); return newSnippets; diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index fe81a0edd..78aed69a7 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -61,15 +61,17 @@ const TEST_CASES = [ ]; describe("RootPathContextService", () => { - test.each(TEST_CASES)( - "Should look for correct type definitions when editing inside a $nodeType in $language", - async ({ fileName, cursorPosition, definitionPositions }) => { - await testRootPathContext( - "files", - fileName, - cursorPosition, - definitionPositions, - ); - }, - ); + describe("should look for correct type definitions", () => { + test.each(TEST_CASES)( + "$language: $nodeType", + async ({ fileName, cursorPosition, definitionPositions }) => { + await testRootPathContext( + "files", + fileName, + cursorPosition, + definitionPositions, + ); + }, + ); + }); }); diff --git a/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts b/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts index 42ef247b0..aadffe065 100644 --- a/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts +++ b/core/autocomplete/context/root-path-context/test/files/arrowFunctions.ts @@ -23,3 +23,7 @@ const logPersonWithAddres = (person: Person
): Person
=> { const logPersonOrAddress = (person: Person | Address): Person | Address => { // TODO }; + +const logPersonAndAddress = (person: Person, address: Address) => { + // TODO +}; diff --git a/core/autocomplete/context/root-path-context/test/files/classMethods.ts b/core/autocomplete/context/root-path-context/test/files/classMethods.ts index 36224029b..08f7506a7 100644 --- a/core/autocomplete/context/root-path-context/test/files/classMethods.ts +++ b/core/autocomplete/context/root-path-context/test/files/classMethods.ts @@ -28,4 +28,8 @@ class Group { logPersonOrAddress(person: Person | Address): Person | Address { // TODO } + + logPersonAndAddress(person: Person, address: Address) { + // TODO + } } diff --git a/core/autocomplete/context/root-path-context/test/files/classes.ts b/core/autocomplete/context/root-path-context/test/files/classes.ts index 2f6b76cda..8bb829986 100644 --- a/core/autocomplete/context/root-path-context/test/files/classes.ts +++ b/core/autocomplete/context/root-path-context/test/files/classes.ts @@ -1,3 +1,9 @@ // @ts-nocheck +class Group extends BaseClass {} + +class Group implements FirstInterface {} + class Group extends BaseClass implements FirstInterface, SecondInterface {} + +class Group extends BaseClass implements FirstInterface {} diff --git a/core/autocomplete/context/root-path-context/test/files/functions.ts b/core/autocomplete/context/root-path-context/test/files/functions.ts index 4189f4e20..bb9d39c85 100644 --- a/core/autocomplete/context/root-path-context/test/files/functions.ts +++ b/core/autocomplete/context/root-path-context/test/files/functions.ts @@ -27,3 +27,7 @@ function logPersonWithAddress(person: Person
): Person
{ function logPersonOrAddress(person: Person | Address): Person | Address { // TODO } + +function logPersonAndAddress(person: Person, address: Address) { + // TODO +} diff --git a/core/autocomplete/context/root-path-context/test/files/generators.ts b/core/autocomplete/context/root-path-context/test/files/generators.ts new file mode 100644 index 000000000..79811b478 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/generators.ts @@ -0,0 +1,33 @@ +// @ts-nocheck + +function* getAddress(person: Person): Address { + // TODO +} + +function* getFirstAddress(people: Person[]): Address { + // TODO +} + +function* logPerson(person: Person) { + // TODO +} + +function* getHardcodedAddress(): Address { + // TODO +} + +function* getAddresses(people: Person[]): Address[] { + // TODO +} + +function* logPersonWithAddress(person: Person
): Person
{ + // TODO +} + +function* logPersonOrAddress(person: Person | Address): Person | Address { + // TODO +} + +function* logPersonAndAddress(person: Person, address: Address) { + // TODO +} diff --git a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts index 9c490ae23..f945a02a9 100644 --- a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts +++ b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts @@ -73,6 +73,103 @@ const FUNCTIONS = [ { row: 26, column: 71 }, // Address ], }, + { + nodeType: "function_declaration with two arguments", + fileName: "functions.ts", + language: "TypeScript", + cursorPosition: { line: 31, character: 9 }, + definitionPositions: [ + { row: 30, column: 43 }, // Person + { row: 30, column: 61 }, // Address + ], + }, +]; + +const GENERATORS = [ + { + nodeType: "function_declaration with a param and a return type", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 3, character: 9 }, + definitionPositions: [ + { row: 2, column: 35 }, // Person + { row: 2, column: 45 }, // Address + ], + }, + { + nodeType: "function_declaration with array param", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 7, character: 9 }, + definitionPositions: [ + { row: 6, column: 40 }, // Person + { row: 6, column: 52 }, // Address + ], + }, + { + nodeType: "function_declaration without return type", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 11, character: 9 }, + definitionPositions: [ + { row: 10, column: 34 }, // Person + ], + }, + { + nodeType: "function_declaration without params", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 15, character: 9 }, + definitionPositions: [ + { row: 14, column: 40 }, // Person + ], + }, + { + nodeType: "function_declaration with array params and array return type", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 19, character: 9 }, + definitionPositions: [ + { row: 18, column: 37 }, // Person + { row: 18, column: 49 }, // Address + ], + }, + { + nodeType: + "function_declaration with generic params and generic return type", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 23, character: 9 }, + definitionPositions: [ + { row: 22, column: 45 }, // Person + { row: 22, column: 53 }, // Address + { row: 22, column: 63 }, // Person + { row: 22, column: 71 }, // Address + ], + }, + { + nodeType: + "function_declaration with union type params and union return type", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 27, character: 9 }, + definitionPositions: [ + { row: 26, column: 43 }, // Person + { row: 26, column: 53 }, // Address + { row: 26, column: 62 }, // Person + { row: 26, column: 72 }, // Address + ], + }, + { + nodeType: "function_declaration with two arguments", + fileName: "generators.ts", + language: "TypeScript", + cursorPosition: { line: 31, character: 9 }, + definitionPositions: [ + { row: 30, column: 44 }, // Person + { row: 30, column: 62 }, // Address + ], + }, ]; const ARROW_FUNCTIONS = [ @@ -138,6 +235,16 @@ const ARROW_FUNCTIONS = [ { row: 22, column: 71 }, // Address ], }, + { + nodeType: "arrow_function with two arguments", + fileName: "arrowFunctions.ts", + language: "TypeScript", + cursorPosition: { line: 27, character: 11 }, + definitionPositions: [ + { row: 26, column: 43 }, // Person + { row: 26, column: 61 }, // Address + ], + }, ]; const CLASS_METHODS = [ @@ -214,10 +321,77 @@ const CLASS_METHODS = [ { row: 27, column: 64 }, // Address ], }, + { + nodeType: "method_declaration with two arguments", + fileName: "classMethods.ts", + language: "TypeScript", + cursorPosition: { line: 32, character: 11 }, + definitionPositions: [ + { row: 31, column: 36 }, // Person + { row: 31, column: 54 }, // Address + ], + }, +]; + +const CLASS_DEFINITIONS = [ + { + nodeType: "class_declaration with base class", + fileName: "classes.ts", + language: "TypeScript", + cursorPosition: { line: 2, character: 31 }, + definitionPositions: [ + { row: 2, column: 29 }, // BaseClass + ], + }, + { + nodeType: "class_declaration with interface", + fileName: "classes.ts", + language: "TypeScript", + cursorPosition: { line: 4, character: 39 }, + definitionPositions: [ + { row: 4, column: 37 }, // FirstInterface + ], + }, + { + nodeType: "class_declaration with base class and multiple interfaces", + fileName: "classes.ts", + language: "TypeScript", + cursorPosition: { line: 6, character: 74 }, + definitionPositions: [ + { row: 6, column: 29 }, // BaseClass + { row: 6, column: 55 }, // FirstInterface + { row: 6, column: 72 }, // SecondInterface + ], + }, + { + nodeType: "class_declaration with base class and multiple interfaces", + fileName: "classes.ts", + language: "TypeScript", + cursorPosition: { line: 6, character: 74 }, + definitionPositions: [ + { row: 6, column: 29 }, // BaseClass + { row: 6, column: 55 }, // FirstInterface + { row: 6, column: 72 }, // SecondInterface + ], + }, + { + nodeType: "class_declaration with generic base class and generic interface", + fileName: "classes.ts", + language: "TypeScript", + cursorPosition: { line: 8, character: 69 }, + definitionPositions: [ + { row: 8, column: 29 }, // BaseClass + { row: 8, column: 61 }, // FirstInterface + { row: 8, column: 34 }, // User + { row: 8, column: 66 }, // User + ], + }, ]; export const TYPESCRIPT_TEST_CASES = [ ...FUNCTIONS, + ...GENERATORS, ...ARROW_FUNCTIONS, ...CLASS_METHODS, + ...CLASS_DEFINITIONS, ]; diff --git a/core/autocomplete/context/root-path-context/test/testUtils.ts b/core/autocomplete/context/root-path-context/test/testUtils.ts index 9526cacdb..7a5c22aba 100644 --- a/core/autocomplete/context/root-path-context/test/testUtils.ts +++ b/core/autocomplete/context/root-path-context/test/testUtils.ts @@ -84,6 +84,7 @@ export async function testRootPathContext( index + 1, expect.any(String), // filepath argument position, + expect.any(String), // language argument ); }); } diff --git a/core/config/validation.ts b/core/config/validation.ts index ebcbb623d..062c0eaed 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -34,6 +34,18 @@ export function validateConfig(config: SerializedContinueConfig) { message: `Model at index ${index} has an invalid 'provider'.`, }); } + + if (model.contextLength && model.completionOptions?.maxTokens) { + const difference = + model.contextLength - model.completionOptions.maxTokens; + + if (difference < 1000) { + errors.push({ + fatal: false, + message: `Model "${model.title}" has a contextLength of ${model.contextLength} and a maxTokens of ${model.completionOptions.maxTokens}. This leaves only ${difference} tokens for input context and will likely result in your inputs being truncated.`, + }); + } + } }); } diff --git a/core/core.ts b/core/core.ts index 8a27fedc3..ab71ab4d7 100644 --- a/core/core.ts +++ b/core/core.ts @@ -161,7 +161,7 @@ export class Core { // Respect pauseCodebaseIndexOnStart user settings this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { - await this.messenger.request("indexProgress", { + void this.messenger.request("indexProgress", { progress: 1, desc: "Initial Indexing Skipped", status: "paused", @@ -680,6 +680,11 @@ export class Core { const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); await this.refreshCodebaseIndex(dirs); }); + on("index/forceReIndexFiles", async ({ data }) => { + if (data?.files?.length) { + await this.refreshCodebaseIndexFiles(data.files); + } + }); on("index/setPaused", (msg) => { this.globalContext.update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; @@ -731,14 +736,29 @@ export class Core { } private indexingCancellationController: AbortController | undefined; + private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) { + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); + void Telemetry.capture( + "indexing_error", + { + error: update.desc, + stack: update.debugInfo, + }, + false, + ); + } - private async refreshCodebaseIndex(dirs: string[]) { + private async refreshCodebaseIndex(paths: string[]) { if (this.indexingCancellationController) { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refresh( - dirs, + for await (const update of (await this.codebaseIndexerPromise).refreshDirs( + paths, this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; @@ -752,19 +772,41 @@ export class Core { this.codebaseIndexingState = updateToSend; if (update.status === "failed") { - console.debug( - "Indexing failed with error: ", - update.desc, - update.debugInfo, - ); - void Telemetry.capture( - "indexing_error", - { - error: update.desc, - stack: update.debugInfo, - }, - false, - ); + void this.sendIndexingErrorTelemetry(update); + } + } + + this.messenger.send("refreshSubmenuItems", undefined); + this.indexingCancellationController = undefined; + } + + private async refreshCodebaseIndexFiles(files: string[]) { + // Can be cancelled by codebase index but not vice versa + if ( + this.indexingCancellationController && + !this.indexingCancellationController.signal.aborted + ) { + return console.debug( + "Codebase indexing already in progress, skipping indexing of files\n" + + files.join("\n"), + ); + } + this.indexingCancellationController = new AbortController(); + for await (const update of (await this.codebaseIndexerPromise).refreshFiles( + files, + )) { + let updateToSend = { ...update }; + if (update.status === "failed") { + updateToSend.status = "done"; + updateToSend.desc = "Indexing complete"; + updateToSend.progress = 1.0; + } + + void this.messenger.request("indexProgress", updateToSend); + this.indexingState = updateToSend; + + if (update.status === "failed") { + void this.sendIndexingErrorTelemetry(update); } } diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 8e1edcc7b..0138817f6 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -3,12 +3,17 @@ import Parser from "web-tree-sitter"; import { getBasename, getLastNPathParts } from "../util/"; import { migrate } from "../util/paths"; import { - TSQueryType, + getFullLanguageName, getParserForFile, getQueryForFile, } from "../util/treeSitter"; -import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex"; +import { + DatabaseConnection, + SqliteDb, + tagToString, + truncateSqliteLikePattern, +} from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, @@ -31,7 +36,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; artifactId = "codeSnippets"; - constructor(private readonly ide: IDE) { } + constructor(private readonly ide: IDE) {} private static async _createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( @@ -183,7 +188,12 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } const ast = parser.parse(contents); - const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets); + + const language = getFullLanguageName(filepath); + const query = await getQueryForFile( + filepath, + `code-snippet-queries/${language}.scm`, + ); const matches = query?.matches(ast.rootNode); if (!matches) { @@ -386,7 +396,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); - const likePatterns = workspaceDirs.map((dir) => truncateSqliteLikePattern(`${dir}%`)); + const likePatterns = workspaceDirs.map((dir) => + truncateSqliteLikePattern(`${dir}%`), + ); const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 5b59c39fa..ee2f108f7 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -89,7 +89,7 @@ describe("CodebaseIndexer", () => { const abortSignal = abortController.signal; const updates = []; - for await (const update of codebaseIndexer.refresh( + for await (const update of codebaseIndexer.refreshDirs( [TEST_DIR], abortSignal, )) { @@ -98,6 +98,16 @@ describe("CodebaseIndexer", () => { return updates; } + async function refreshIndexFiles(files: string[]) { + const updates = []; + for await (const update of codebaseIndexer.refreshFiles( + files, + )) { + updates.push(update); + } + return updates; + } + async function getAllIndexedFiles() { const files = await testIndex.getIndexedFilesForTags( await testIde.getTags(testIndex.artifactId), @@ -158,6 +168,15 @@ describe("CodebaseIndexer", () => { expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true); }); + test("should successfuly re-index specific files", async () => { + // Could add more specific tests for this but uses similar logic + const before = await getAllIndexedFiles(); + await refreshIndexFiles(before); + + const after = await getAllIndexedFiles(); + expect(after.length).toBe(before.length); + }); + test("should successfully re-index after adding a file", async () => { addToTestDir([["main.rs", TEST_RS]]); diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b4962d182..5c70f8bad 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -17,6 +17,7 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; +import { getBasename } from "../util/index.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -144,13 +145,52 @@ export class CodebaseIndexer { } } - async *refresh( - workspaceDirs: string[], + async *refreshFiles( + files: string[], + ): AsyncGenerator { + let progress = 0; + if (files.length === 0) { + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } + + const progressPer = 1 / files.length; + try { + for (const file of files) { + yield { + progress, + desc: `Indexing file ${file}...`, + status: "indexing", + }; + await this.refreshFile(file); + + progress += progressPer; + + if (this.pauseToken.paused) { + yield* this.yieldUpdateAndPause(); + } + } + + yield { + progress: 1, + desc: "Indexing Complete", + status: "done", + }; + } catch (err) { + yield this.handleErrorAndGetProgressUpdate(err); + } + } + + async *refreshDirs( + dirs: string[], abortSignal: AbortSignal, ): AsyncGenerator { let progress = 0; - if (workspaceDirs.length === 0) { + if (dirs.length === 0) { yield { progress, desc: "Nothing to index", @@ -175,11 +215,9 @@ export class CodebaseIndexer { }; } - let completedDirs = 0; - // Wait until Git Extension has loaded to report progress // so we don't appear stuck at 0% while waiting - await this.ide.getRepoName(workspaceDirs[0]); + await this.ide.getRepoName(dirs[0]); yield { progress, @@ -188,16 +226,16 @@ export class CodebaseIndexer { }; const beginTime = Date.now(); - for (const directory of workspaceDirs) { + for (const directory of dirs) { const dirBasename = await this.basename(directory); yield { progress, desc: `Discovering files in ${dirBasename}...`, status: "indexing", }; - const workspaceFiles = []; + const directoryFiles = []; for await (const p of walkDirAsync(directory, this.ide)) { - workspaceFiles.push(p); + directoryFiles.push(p); if (abortSignal.aborted) { yield { progress: 1, @@ -218,7 +256,7 @@ export class CodebaseIndexer { try { for await (const updateDesc of this.indexFiles( directory, - workspaceFiles, + directoryFiles, branch, repoName, )) { @@ -240,7 +278,7 @@ export class CodebaseIndexer { nextLogThreshold += 0.025; this.logProgress( beginTime, - Math.floor(workspaceFiles.length * updateDesc.progress), + Math.floor(directoryFiles.length * updateDesc.progress), updateDesc.progress, ); } @@ -347,18 +385,18 @@ export class CodebaseIndexer { } private async *indexFiles( - workspaceDir: string, - workspaceFiles: string[], + directory: string, + files: string[], branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(workspaceFiles); + const stats = await this.ide.getLastModified(files); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { - directory: workspaceDir, + directory, branch, artifactId: codebaseIndex.artifactId, }; diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 01f0efab1..8854d8e87 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -79,7 +79,7 @@ class DocsCrawler { ); if (didInstall) { - await this.ide.showToast( + void this.ide.showToast( "info", `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`, ); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 801796363..25f465be4 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -258,7 +258,7 @@ export default class DocsService { params: {}, }); - await this.ide.showToast( + void this.ide.showToast( "info", "Successfuly added docs context provider", ); diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index ee49270a8..e2feb4c59 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -242,7 +242,7 @@ export class ChromiumInstaller { ChromiumCrawler.setUseChromiumForDocsCrawling(false); - await this.ide.showToast("error", "Failed to install Chromium"); + void this.ide.showToast("error", "Failed to install Chromium"); return false; } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 17f104a52..bebb8ead1 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -49,7 +49,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "mistral", "sambanova", "vertexai", - "watsonx" + "watsonx", ]; const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ @@ -63,7 +63,8 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ "sagemaker", "continue-proxy", "openrouter", - "vertexai" + "vertexai", + "azure", ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -121,7 +122,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "together", "sambanova", "nebius", - "vertexai" + "vertexai", ]; function llmCanGenerateInParallel( diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 7ae3da1b7..9b30ad4bc 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -323,6 +323,27 @@ function pruneChatHistory( return chatHistory; } +function messageIsEmpty(message: ChatMessage): boolean { + if (typeof message.content === "string") { + return message.content.trim() === ""; + } + if (Array.isArray(message.content)) { + return message.content.every( + (item) => !item.imageUrl && item.text?.trim() === "", + ); + } + return false; +} + +function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] { + return messages.map((message) => { + if (messageIsEmpty(message)) { + message.content = " "; + } + return message; + }); +} + function compileChatMessages( modelName: string, msgs: ChatMessage[] | undefined, @@ -333,12 +354,14 @@ function compileChatMessages( functions: any[] | undefined = undefined, systemMessage: string | undefined = undefined, ): ChatMessage[] { - const msgsCopy = msgs + let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) .filter((msg) => msg.content !== "" && msg.role !== "system") : []; + msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); + if (prompt) { const promptMsg: ChatMessage = { role: "user", diff --git a/core/package-lock.json b/core/package-lock.json index fd3173f28..e817a7c6f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -5846,9 +5846,9 @@ "integrity": "sha512-3AungXC4I8kKsS9PuS4JH2nc+0bVY/mjgrephHTIi8fpEeGsTHBUJeosp0Wc1myYMElmD0B3Oc4XL/HVJ4PV2g==" }, "node_modules/axios": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.1.tgz", - "integrity": "sha512-+LV37nQcd1EpFalkXksWNBiA17NZ5m5/WspmHGmZmdx1qBOg/VNq/c4eRJiA9VQQHBOs+N0ZhhdU10h2TyNK7Q==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz", + "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts index 21ff3c7c1..0a8adc25d 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -26,9 +26,6 @@ const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file # To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files name: Example - -# For example, here is how you would write a .prompt -name: Example description: Example prompt file --- diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2e5a660d4..65a798c55 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -151,6 +151,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; + "index/forceReIndexFiles": [undefined | { files?: string[] }, void]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index b2d18c533..1997b8700 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -42,6 +42,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = // Codebase "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", // Docs, etc. "indexing/getStatuses", diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index b877a251b..9118b80ee 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -3,81 +3,116 @@ import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; -export const supportedLanguages: { [key: string]: string } = { - cpp: "cpp", - hpp: "cpp", - cc: "cpp", - cxx: "cpp", - hxx: "cpp", - cp: "cpp", - hh: "cpp", - inc: "cpp", - // Depended on this PR: https://github.com/tree-sitter/tree-sitter-cpp/pull/173 - // ccm: "cpp", - // c++m: "cpp", - // cppm: "cpp", - // cxxm: "cpp", - cs: "c_sharp", - c: "c", - h: "c", - css: "css", - php: "php", - phtml: "php", - php3: "php", - php4: "php", - php5: "php", - php7: "php", - phps: "php", - "php-s": "php", - bash: "bash", - sh: "bash", - json: "json", - ts: "typescript", - mts: "typescript", - cts: "typescript", - tsx: "tsx", - // vue: "vue", // tree-sitter-vue parser is broken - // The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part - // yaml: "yaml", - // yml: "yaml", - elm: "elm", - js: "javascript", - jsx: "javascript", - mjs: "javascript", - cjs: "javascript", - py: "python", - ipynb: "python", - pyw: "python", - pyi: "python", - el: "elisp", - emacs: "elisp", - ex: "elixir", - exs: "elixir", - go: "go", - eex: "embedded_template", - heex: "embedded_template", - leex: "embedded_template", - html: "html", - htm: "html", - java: "java", - lua: "lua", - ocaml: "ocaml", - ml: "ocaml", - mli: "ocaml", - ql: "ql", - res: "rescript", - resi: "rescript", - rb: "ruby", - erb: "ruby", - rs: "rust", - rdl: "systemrdl", - toml: "toml", - sol: "solidity", +export enum LanguageName { + CPP = "cpp", + C_SHARP = "c_sharp", + C = "c", + CSS = "css", + PHP = "php", + BASH = "bash", + JSON = "json", + TYPESCRIPT = "typescript", + TSX = "tsx", + ELM = "elm", + JAVASCRIPT = "javascript", + PYTHON = "python", + ELISP = "elisp", + ELIXIR = "elixir", + GO = "go", + EMBEDDED_TEMPLATE = "embedded_template", + HTML = "html", + JAVA = "java", + LUA = "lua", + OCAML = "ocaml", + QL = "ql", + RESCRIPT = "rescript", + RUBY = "ruby", + RUST = "rust", + SYSTEMRDL = "systemrdl", + TOML = "toml", + SOLIDITY = "solidity", +} - // jl: "julia", - // swift: "swift", - // kt: "kotlin", - // scala: "scala", +export const supportedLanguages: { [key: string]: LanguageName } = { + cpp: LanguageName.CPP, + hpp: LanguageName.CPP, + cc: LanguageName.CPP, + cxx: LanguageName.CPP, + hxx: LanguageName.CPP, + cp: LanguageName.CPP, + hh: LanguageName.CPP, + inc: LanguageName.CPP, + // Depended on this PR: https://github.com/tree-sitter/tree-sitter-cpp/pull/173 + // ccm: LanguageName.CPP, + // c++m: LanguageName.CPP, + // cppm: LanguageName.CPP, + // cxxm: LanguageName.CPP, + cs: LanguageName.C_SHARP, + c: LanguageName.C, + h: LanguageName.C, + css: LanguageName.CSS, + php: LanguageName.PHP, + phtml: LanguageName.PHP, + php3: LanguageName.PHP, + php4: LanguageName.PHP, + php5: LanguageName.PHP, + php7: LanguageName.PHP, + phps: LanguageName.PHP, + "php-s": LanguageName.PHP, + bash: LanguageName.BASH, + sh: LanguageName.BASH, + json: LanguageName.JSON, + ts: LanguageName.TYPESCRIPT, + mts: LanguageName.TYPESCRIPT, + cts: LanguageName.TYPESCRIPT, + tsx: LanguageName.TSX, + // vue: LanguageName.VUE, // tree-sitter-vue parser is broken + // The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part + // yaml: LanguageName.YAML, + // yml: LanguageName.YAML, + elm: LanguageName.ELM, + js: LanguageName.JAVASCRIPT, + jsx: LanguageName.JAVASCRIPT, + mjs: LanguageName.JAVASCRIPT, + cjs: LanguageName.JAVASCRIPT, + py: LanguageName.PYTHON, + ipynb: LanguageName.PYTHON, + pyw: LanguageName.PYTHON, + pyi: LanguageName.PYTHON, + el: LanguageName.ELISP, + emacs: LanguageName.ELISP, + ex: LanguageName.ELIXIR, + exs: LanguageName.ELIXIR, + go: LanguageName.GO, + eex: LanguageName.EMBEDDED_TEMPLATE, + heex: LanguageName.EMBEDDED_TEMPLATE, + leex: LanguageName.EMBEDDED_TEMPLATE, + html: LanguageName.HTML, + htm: LanguageName.HTML, + java: LanguageName.JAVA, + lua: LanguageName.LUA, + ocaml: LanguageName.OCAML, + ml: LanguageName.OCAML, + mli: LanguageName.OCAML, + ql: LanguageName.QL, + res: LanguageName.RESCRIPT, + resi: LanguageName.RESCRIPT, + rb: LanguageName.RUBY, + erb: LanguageName.RUBY, + rs: LanguageName.RUST, + rdl: LanguageName.SYSTEMRDL, + toml: LanguageName.TOML, + sol: LanguageName.SOLIDITY, + + // jl: LanguageName.JULIA, + // swift: LanguageName.SWIFT, + // kt: LanguageName.KOTLIN, + // scala: LanguageName.SCALA, +}; + +export const IGNORE_PATH_PATTERNS: Partial> = { + [LanguageName.TYPESCRIPT]: [/.*node_modules/], + [LanguageName.JAVASCRIPT]: [/.*node_modules/], }; export async function getParserForFile(filepath: string) { @@ -128,15 +163,9 @@ 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 const getFullLanguageName = (filepath: string) => { + return supportedLanguages[filepath.split(".").pop() ?? ""]; +}; export async function getQueryForFile( filepath: string, @@ -147,7 +176,6 @@ export async function getQueryForFile( return undefined; } - const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""]; const sourcePath = path.join( __dirname, "..", @@ -155,7 +183,6 @@ export async function getQueryForFile( ? ["extensions", "vscode", "tree-sitter"] : ["tree-sitter"]), queryPath, - `${fullLangName}.scm`, ); if (!fs.existsSync(sourcePath)) { return undefined; diff --git a/core/util/tts.ts b/core/util/tts.ts index 9bde6e57c..efae302c2 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -82,10 +82,10 @@ export class TTS { return; } - TTS.messenger.request("setTTSActive", true); + void TTS.messenger.request("setTTSActive", true); TTS.handle?.once("exit", () => { - TTS.messenger.request("setTTSActive", false); + void TTS.messenger.request("setTTSActive", false); }); } diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index 943d5e7ac..9df6ec020 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -7,6 +7,7 @@ sidebar_position: 5 There are a number of different ways to customize Chat +- You can add a [`.continuerules`](../customize/deep-dives/rules.md) file to the root of your project to customize the system prompt - You can configure [`@Codebase`](../customize/deep-dives/codebase.md) - You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md) - You can configure [`@Docs`](../customize/deep-dives/docs.md) diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 928e01543..e69902a42 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -6,42 +6,30 @@ Prompt files provide a convenient way to standardize common patterns and share a ## Quick start -:::tip[Prompt library] + -Below is a quick example of setting up a prompt file to write unit tests using Jest. +Below is a quick example of setting up a prompt file to de -1. Create a folder called `.prompts/` at the top level of your workspace. -2. Add a file called `test.prompt` to this folder. The name of this file will be the name of the slash command you will use to generate your prompt. -3. Write the following contents to `test.prompt` and save. +1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File"). +2. Add a file called `rails.prompt` to this folder. +3. Write the following contents to `rails.prompt` and save. ``` -temperature: 0.5 -maxTokens: 4096 +name: Rails Project +description: Information about this project --- - -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` +Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb ``` Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. -Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. +Then, type "@", select "Prompt files", and choose the one called "Rails Project". You can now ask any question as usual and the LLM will have the information from your .prompt file. ## Format -The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to use context providers and built-in variables using [Handlebars syntax](https://handlebarsjs.com/guide/). +The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. :::info The current state of this format is experimental and subject to change @@ -51,38 +39,19 @@ The current state of this format is experimental and subject to change The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: -- `name` -- `temperature` -- `topP` -- `topK` -- `minP` -- `presencePenalty` -- `frequencyPenalty` -- `mirostat` -- `stop` -- `maxTokens` -- `description` +- `name` - The display title +- `description` - The description you will see in the dropdown +- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. -### System message +### Context -To add a system message, start the body with `` tags like in the example above and place your system message inside. +Many [context provider](../context-providers.md) can be referenced by typing "@" followed by the name of the context provider. -### Built-in variables - -The following built-in variables are currently available: - -- `{{{ input }}}` - The full text from the input box in the sidebar that is sent along with the slash command -- `{{{ currentFile }}}` - The currently open file in your IDE -- `{{{ ./path/to/file.js }}}` - Any file can be directly referenced - -### Context providers - -Any [context provider](../context-providers.md) that you have added to your config can be referenced using the name of the context provider. Context providers that receive an input are also supported. - -- `{{{ terminal }}}` - The contents of the terminal -- `{{{ url "https://github.com/continuedev/continue" }}}` - The contents of a URL +- `@terminal` - The contents of the terminal +- `@https://github.com/continuedev/continue` - The contents of a URL +- `@src/index.ts` - The contents of a file ## Feedback diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md new file mode 100644 index 000000000..30100aaeb --- /dev/null +++ b/docs/docs/customize/deep-dives/rules.md @@ -0,0 +1,27 @@ +--- +description: Learn how to customize the system prompt with a `.continuerules` file +keywords: [rules, .continuerules, system, prompt, message] +--- + +# `.continuerules` + +You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its contents will be inserted into the system message for all LLM requests. + +## Simple Examples + +- If you want concise answers: + +```title=.continuerules +Please provide concise answers. Do explain obvious concepts. You can assume that I am knowledgable about most programming topics. +``` + +- If you want to ensure certain practices are followed, for example in React: + +```title=.continuerules +Whenever you are writing React code, make sure to +- use functional components instead of class components +- use hooks for state management +- define an interface for your component props +- use Tailwind CSS for styling +- modularize components into smaller, reusable pieces +``` diff --git a/docs/package-lock.json b/docs/package-lock.json index 756266105..c2485bdf7 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -5229,9 +5229,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.5.tgz", + "integrity": "sha512-ZVJrKKYunU38/76t0RMOulHOnUcbU9GbpWKAOZ0mhjr7CX6FVrH+4FrAapSOekrgFQ3f/8gwMEuIft0aKq6Hug==", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt new file mode 100644 index 000000000..e8d3d0788 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginDisposable.kt @@ -0,0 +1,32 @@ +package com.github.continuedev.continueintellijextension.activities + +import com.intellij.openapi.Disposable +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project + +/** + * The service is a parent disposable that represents the entire plugin lifecycle + * and is intended to be used instead of the project/application as a parent disposable, + * ensures that disposables registered using it as parents will be processed when the plugin is unloaded to avoid memory leaks. + * + * @author lk + */ +@Service(Service.Level.APP, Service.Level.PROJECT) +class ContinuePluginDisposable : Disposable { + + override fun dispose() { + } + + companion object { + + fun getInstance(): ContinuePluginDisposable { + return ApplicationManager.getApplication().getService(ContinuePluginDisposable::class.java) + } + + fun getInstance(project: Project): ContinuePluginDisposable { + return project.getService(ContinuePluginDisposable::class.java) + } + + } +} \ No newline at end of file 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 fa39729fa..eecbc958c 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 @@ -70,7 +70,7 @@ private fun getTutorialFileName(): String { } } -class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { +class ContinuePluginStartupActivity : StartupActivity, DumbAware { override fun runActivity(project: Project) { removeShortcutFromAction(getPlatformSpecificKeyStroke("J")) @@ -169,8 +169,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // Create a data map if there are any paths to re-index if (allPaths.isNotEmpty()) { - val data = mapOf("dirs" to allPaths) - continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + val data = mapOf("files" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndexFiles", data, null) { _ -> } } } }) @@ -225,14 +225,11 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { EditorFactory.getInstance().eventMulticaster.addSelectionListener( listener, - this@ContinuePluginStartupActivity + ContinuePluginDisposable.getInstance(project) ) val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope) continuePluginService.coreMessengerManager = coreMessengerManager } } - - override fun dispose() { - } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt index 299614665..98be79f74 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.autocomplete +import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.intellij.openapi.Disposable import com.intellij.openapi.components.service @@ -35,7 +36,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), ) init { - Disposer.register(project, this) + Disposer.register(ContinuePluginDisposable.getInstance(project), this) updateIcon() } 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 c2a35a918..c48c8e58b 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 @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue` +import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.constants.getConfigJsPath @@ -132,9 +133,9 @@ class IdeProtocolClient( initIdeProtocol() // Setup config.json / config.ts save listeners - VirtualFileManager.getInstance().addAsyncFileListener(AsyncFileSaveListener(this), object : Disposable { - override fun dispose() {} - }) + VirtualFileManager.getInstance().addAsyncFileListener( + AsyncFileSaveListener(this), ContinuePluginDisposable.getInstance(project) + ) val myPluginId = "com.github.continuedev.continueintellijextension" val pluginDescriptor = diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 0a6b33496..3f25b87cb 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -109,14 +109,14 @@ class DiffStreamHandler( } updateProgressHighlighters(type) - - // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where - // we reach EOF while in a diff block, since we won't encounter a "same" line. - if (curLine.index >= editor.document.lineCount - 1) { - curLine.diffBlock?.onLastDiffLine() - } } catch (e: Exception) { - println("Error handling diff line: ${curLine.index}, $type, $text, ${e.message}") + println( + "Error handling diff line - " + + "Line index: ${curLine.index}, " + + "Line type: $type, " + + "Line text: $text, " + + "Error message: ${e.message}" + ) } } @@ -139,7 +139,7 @@ class DiffStreamHandler( val diffBlock = VerticalDiffBlock( editor, project, curLine.index, ::handleDiffBlockAcceptOrReject ) - + diffBlocks.add(diffBlock) return diffBlock @@ -251,9 +251,12 @@ class DiffStreamHandler( } private fun handleFinishedResponse() { - onFinish() - ApplicationManager.getApplication().invokeLater { + // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where + // the last line in the diff stream is in the middle of a diff block. + curLine.diffBlock?.onLastDiffLine() + + onFinish() cleanupProgressHighlighters() } } @@ -267,9 +270,12 @@ class DiffStreamHandler( private fun handleDiffLineResponse(parsed: Map<*, *>) { val data = parsed["content"] as Map<*, *> val diffLineType = getDiffLineType(data["type"] as String) + val lineText = data["line"] as String - WriteCommandAction.runWriteCommandAction(project) { - handleDiffLine(diffLineType, data["line"] as String) + ApplicationManager.getApplication().invokeLater { + WriteCommandAction.runWriteCommandAction(project) { + handleDiffLine(diffLineType, lineText) + } } } 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 bd1ac8072..714cd6417 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 @@ -40,6 +40,8 @@ import org.jdesktop.swingx.JXTextArea const val MAIN_FONT_SIZE = 13 +const val DOWN_ARROW = " â–¾" + fun makeTextArea(): JTextArea { val textArea = CustomTextArea(1, 40).apply { @@ -48,7 +50,7 @@ fun makeTextArea(): JTextArea { isOpaque = false background = GetTheme().getSecondaryDark() maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) - margin = JBUI.insets(6, 8, 6, 4) + margin = JBUI.insets(6, 8, 2, 4) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) preferredSize = Dimension(400, 75) } @@ -206,7 +208,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { val comboBoxRef = Ref>() fun onEnter() { - val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" â–¾") + val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW) customPanelRef.get().enter() diffStreamHandler.streamDiffLinesToEditor( textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret @@ -425,7 +427,7 @@ class CustomPanel( } selectedIndex = - continueSettingsService.continueState.lastSelectedInlineEditModel?.let { + if(itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let { if (modelTitles.isEmpty()) -1 else { val index = modelTitles.indexOf(it) @@ -435,7 +437,7 @@ class CustomPanel( addActionListener { continueSettingsService.continueState.lastSelectedInlineEditModel = - selectedItem as String + (selectedItem as String).removeSuffix(DOWN_ARROW) } } @@ -711,7 +713,7 @@ class TransparentArrowButtonUI : BasicComboBoxUI() { override fun getSelectedItem(): Any? { val item = originalModel.selectedItem - return "$item â–¾" + return "$item$DOWN_ARROW" } override fun addListDataListener(l: ListDataListener?) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index 2990b72e8..a84bf7f9b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -29,6 +29,7 @@ class VerticalDiffBlock( private val rejectButton: JButton private var deletionInlay: Disposable? = null private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons + private var hasRenderedDiffBlock: Boolean = false private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false) private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor) @@ -81,11 +82,19 @@ class VerticalDiffBlock( } fun onLastDiffLine() { + // Handles the case where we are invoking one last time on last line of diff stream, but the block has + // already been rendered + if (hasRenderedDiffBlock) { + return + } + if (deletedLines.size > 0) { renderDeletedLinesInlay() } renderButtons() + + hasRenderedDiffBlock = true } fun handleReject() { 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 26896906b..fc51a392e 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,5 +1,6 @@ package com.github.continuedev.continueintellijextension.toolWindow +import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.activities.showTutorial import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath @@ -58,6 +59,7 @@ class ContinueBrowser(val project: Project, url: String) { "stats/getTokensPerModel", "index/setPaused", "index/forceReIndex", + "index/forceReIndexFiles", "index/indexingProgressBarInitialized", "completeOnboarding", "addAutocompleteModel", @@ -88,7 +90,7 @@ class ContinueBrowser(val project: Project, url: String) { registerAppSchemeHandler() browser.loadURL(url); - Disposer.register(project, browser) + Disposer.register(ContinuePluginDisposable.getInstance(project), browser) // Listen for events sent from browser val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 29ac4731f..3dc6757e7 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.230", + "version": "0.9.231", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.230", + "version": "0.9.231", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e7b6c8271..186d18219 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.230", + "version": "0.9.231", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b6b04297f..0df8e58b1 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -41,7 +41,9 @@ export class ContinueCompletionProvider showFreeTrialLoginMessage( e.message, this.configHandler.reloadConfig.bind(this.configHandler), - () => this.webviewProtocol.request("openOnboardingCard", undefined), + () => { + void this.webviewProtocol.request("openOnboardingCard", undefined) + }, ); return; } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 4733dee6f..42c10c3c9 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -258,7 +258,7 @@ const commandsMap: ( const modelTitle = getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - sidebar.webviewProtocol.request("incrementFtc", undefined); + void sidebar.webviewProtocol.request("incrementFtc", undefined); await verticalDiffManager.streamEdit( config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, @@ -287,7 +287,7 @@ const commandsMap: ( verticalDiffManager.clearForFilepath(fullPath, true); await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { + void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); }, @@ -306,7 +306,7 @@ const commandsMap: ( verticalDiffManager.clearForFilepath(fullPath, false); await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { + void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); }, @@ -387,12 +387,12 @@ const commandsMap: ( if (historyLength === 0) { hideGUI(); } else { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); + void sidebar.webviewProtocol?.request("focusContinueInput", undefined); } } else { focusGUI(); sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); + void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, "continue.focusContinueInputWithoutClear": async () => { @@ -419,7 +419,7 @@ const commandsMap: ( undefined, ); - await addHighlightedCodeToContext(sidebar.webviewProtocol); + void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, "continue.edit": async () => { @@ -596,10 +596,10 @@ const commandsMap: ( prompt: "Enter the Session ID", }); } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + void sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); }, "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + void sidebar.webviewProtocol.request("applyCodeFromChat", undefined); }, "continue.toggleFullScreen": () => { focusGUI(); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 1ec5a60b6..f2bf20ef6 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -25,9 +25,12 @@ export class VerticalDiffHandler implements vscode.Disposable { private currentLineIndex: number; private cancelled = false; private newLinesAdded = 0; - private get diffBlocks() { - return this.editorToVerticalDiffCodeLens.get(this.filepath) || []; + private deletionBuffer: string[] = []; + private redDecorationManager: DecorationTypeRangeManager; + private get filepath() { + return this.editor.document.uri.fsPath; } + public insertedInCurrentBlock = 0; public get range(): vscode.Range { const startLine = Math.min(this.startLine, this.endLine); const endLine = Math.max(this.startLine, this.endLine); @@ -77,14 +80,6 @@ export class VerticalDiffHandler implements vscode.Disposable { this.disposables.push(disposable); } - private get filepath() { - return this.editor.document.uri.fsPath; - } - - private deletionBuffer: string[] = []; - private redDecorationManager: DecorationTypeRangeManager; - insertedInCurrentBlock = 0; - private async insertDeletionBuffer() { // Don't remove trailing whitespace line const totalDeletedContent = this.deletionBuffer.join("\n"); @@ -98,13 +93,15 @@ export class VerticalDiffHandler implements vscode.Disposable { } if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { - this.diffBlocks.push({ + const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || []; + + blocks.push({ start: this.currentLineIndex - this.insertedInCurrentBlock, numRed: this.deletionBuffer.length, numGreen: this.insertedInCurrentBlock, }); - this.editorToVerticalDiffCodeLens.set(this.filepath, this.diffBlocks); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } if (this.deletionBuffer.length === 0) { @@ -271,7 +268,10 @@ export class VerticalDiffHandler implements vscode.Disposable { }, ); - this.options.onStatusUpdate("closed", this.diffBlocks.length); + this.options.onStatusUpdate( + "closed", + this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + ); this.cancelled = true; this.refreshCodeLens(); @@ -359,7 +359,10 @@ export class VerticalDiffHandler implements vscode.Disposable { this.refreshCodeLens(); - this.options.onStatusUpdate("done", this.diffBlocks.length); + this.options.onStatusUpdate( + "done", + this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + ); // Reject on user typing // const listener = vscode.workspace.onDidChangeTextDocument((e) => { @@ -409,8 +412,11 @@ export class VerticalDiffHandler implements vscode.Disposable { // Shift the codelens objects this.shiftCodeLensObjects(startLine, offset); - const status = this.diffBlocks.length === 0 ? "closed" : undefined; - this.options.onStatusUpdate(status, this.diffBlocks.length); + const numDiffs = + this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0; + + const status = numDiffs === 0 ? "closed" : undefined; + this.options.onStatusUpdate(status, numDiffs); } private shiftCodeLensObjects(startLine: number, offset: number) { @@ -450,6 +456,7 @@ export class VerticalDiffHandler implements vscode.Disposable { } public hasDiffForCurrentFile(): boolean { - return this.diffBlocks.length > 0; + const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.filepath); + return diffBlocks !== undefined && diffBlocks.length > 0; } } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 5c6ca0884..4595ca013 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -218,7 +218,7 @@ export class VerticalDiffManager { { instant, onStatusUpdate: (status, numDiffs) => - this.webviewProtocol.request("updateApplyState", { + void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, @@ -338,7 +338,7 @@ export class VerticalDiffManager { input, onStatusUpdate: (status, numDiffs) => streamId && - this.webviewProtocol.request("updateApplyState", { + void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 06263e356..1eb619aa8 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -297,17 +297,21 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - this.core.invoke("index/forceReIndex", { - dirs: [filepath], + this.core.invoke("index/forceReIndexFiles", { + files: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { - this.core.invoke("index/forceReIndex", { - dirs: event.files.map((file) => - file.fsPath.split("/").slice(0, -1).join("/"), - ), + this.core.invoke("index/forceReIndexFiles", { + files: event.files.map((file) => file.fsPath), + }); + }); + + vscode.workspace.onDidCreateFiles(async (event) => { + this.core.invoke("index/forceReIndexFiles", { + files: event.files.map((file) => file.fsPath), }); }); @@ -318,14 +322,14 @@ export class VsCodeExtension { } else if (e.provider.id === controlPlaneEnv.AUTH_TYPE) { const sessionInfo = await getControlPlaneSessionInfo(true); this.webviewProtocolPromise.then(async (webviewProtocol) => { - webviewProtocol.request("didChangeControlPlaneSessionInfo", { + void webviewProtocol.request("didChangeControlPlaneSessionInfo", { sessionInfo, }); // To make sure continue-proxy models and anything else requiring it get updated access token this.configHandler.reloadConfig(); }); - this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo }); + void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo }); } }); @@ -374,14 +378,14 @@ export class VsCodeExtension { ); this.ide.onDidChangeActiveTextEditor((filepath) => { - this.core.invoke("didChangeActiveTextEditor", { filepath }); + void 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", { + void webviewProtocol.request("didChangeIdeSettings", { settings, }); } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b4e9749da..e71bd2bfd 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -48,7 +48,7 @@ export class VsCodeMessenger { message: Message, ) => Promise | FromWebviewProtocol[T][1], ): void { - this.webviewProtocol.on(messageType, handler); + void this.webviewProtocol.on(messageType, handler); } onCore( @@ -153,11 +153,11 @@ export class VsCodeMessenger { }); webviewProtocol.on("acceptDiff", async ({ data: { filepath } }) => { - await vscode.commands.executeCommand("continue.acceptDiff", filepath); + void vscode.commands.executeCommand("continue.acceptDiff", filepath); }); webviewProtocol.on("rejectDiff", async ({ data: { filepath } }) => { - await vscode.commands.executeCommand("continue.rejectDiff", filepath); + void vscode.commands.executeCommand("continue.rejectDiff", filepath); }); this.onWebview("applyToFile", async ({ data }) => { @@ -178,7 +178,7 @@ export class VsCodeMessenger { await this.ide.writeFile(fullPath, data.text); await this.ide.openFile(fullPath); - await webviewProtocol.request("updateApplyState", { + void webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "done", numDiffs: 0, @@ -203,7 +203,7 @@ export class VsCodeMessenger { editor.edit((builder) => builder.insert(new vscode.Position(0, 0), data.text), ); - await webviewProtocol.request("updateApplyState", { + void webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "done", numDiffs: 0, @@ -328,7 +328,7 @@ export class VsCodeMessenger { ), ); - this.webviewProtocol.request("setEditStatus", { + void this.webviewProtocol.request("setEditStatus", { status: "accepting", fileAfterEdit, }); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 355c02de6..4b59dcbda 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -329,7 +329,7 @@ export class QuickEdit { prompt = this.contextProviderStr + prompt; } - this.webviewProtocol.request("incrementFtc", undefined); + void this.webviewProtocol.request("incrementFtc", undefined); await this.verticalDiffManager.streamEdit( prompt, diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm deleted file mode 100644 index bf38152b7..000000000 --- a/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm +++ /dev/null @@ -1,19 +0,0 @@ -( - (class_declaration - (class_heritage - (extends_clause - (identifier) @base-class - ) - ) - ) -) - -( - (class_declaration - (class_heritage - (implements_clause - (type_identifier) @interface - ) - ) - ) -) \ 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/cpp/function_definition.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/function_definition/cpp.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/cpp/function_definition.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm b/extensions/vscode/tree-sitter/root-path-context-queries/go/function_declaration.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/go/function_declaration.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/java.scm b/extensions/vscode/tree-sitter/root-path-context-queries/java/method_declaration.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/java.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/java/method_declaration.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/php/class_declaration.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/php/class_declaration.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/php/function_definition.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/php/function_definition.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/php/method_declaration.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/php/method_declaration.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_definition/python.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/class_definition/python.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/python/class_definition.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/python.scm b/extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/function_definition/python.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/python/function_definition.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/arrow_function/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/typescript/arrow_function.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/arrow_function/typescript.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/typescript/arrow_function.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/typescript/class_declaration.scm b/extensions/vscode/tree-sitter/root-path-context-queries/typescript/class_declaration.scm new file mode 100644 index 000000000..d164b05a8 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/typescript/class_declaration.scm @@ -0,0 +1,45 @@ +; Match a class declaration that extends a base class +; Returns: +; @base-class: The identifier of the base class being extended +; @generic_argument: The type identifier of the generic argument, if present +(class_declaration + (class_heritage + (extends_clause + (identifier) @base-class + (type_arguments + (type_identifier) @generic_argument + )? + ) + ) +) + +; Match a class declaration that implements an interface +; Returns: +; @interface: The type identifier of the interface being implemented +( + (class_declaration + (class_heritage + (implements_clause + (type_identifier) @interface + ) + ) + ) +) + +; Match a class declaration that implements a generic interface +; Returns: +; @interface: The type identifier of the generic interface being implemented +; @generic_argument: The type identifier of the generic argument +( + class_declaration + (class_heritage + (implements_clause + (generic_type + (type_identifier) @interface + (type_arguments + (type_identifier) @generic_argument + ) + ) + ) + ) +) \ 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/typescript/function_declaration.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/typescript/function_declaration.scm diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/typescript/generator_function_declaration.scm b/extensions/vscode/tree-sitter/root-path-context-queries/typescript/generator_function_declaration.scm new file mode 100644 index 000000000..b6417f45c --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/typescript/generator_function_declaration.scm @@ -0,0 +1,77 @@ +; Pattern for return type with direct type_identifier +( + (generator_function_declaration + (type_annotation + (type_identifier) @return_type + ) + ) +) + +; Pattern for return type with one level of nesting +( + (generator_function_declaration + (type_annotation + (_ + (type_identifier) @return_type + ) + ) + ) +) + +; Pattern for return type with two levels of nesting +( + (generator_function_declaration + (type_annotation + (_ + (_ + (type_identifier) @return_type + ) + ) + ) + ) +) + +; Pattern for parameters with direct type_identifier +( + (generator_function_declaration + (formal_parameters + (_ + (type_annotation + (type_identifier) @param_type + ) + ) + ) + ) +) + +; Pattern for parameters with one level of nesting +( + (generator_function_declaration + (formal_parameters + (_ + (type_annotation + (_ + (type_identifier) @param_type + ) + ) + ) + ) + ) +) + +; Pattern for parameters with two levels of nesting +( + (generator_function_declaration + (formal_parameters + (_ + (type_annotation + (_ + (_ + (type_identifier) @param_type + ) + ) + ) + ) + ) + ) +) \ 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/typescript/method_definition.scm similarity index 100% rename from extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm rename to extensions/vscode/tree-sitter/root-path-context-queries/typescript/method_definition.scm diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 7ed525626..4aee636bd 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -46,13 +46,20 @@ export function History() { const fetchSessions = async () => { const sessions = await getHistory(); setSessions(sessions); - minisearch.addAll( - sessions.map((session) => ({ - title: session.title, - sessionId: session.sessionId, - id: session.sessionId, - })), - ); + + try { + // Consider adding just last session to existing instead of clearing/adding all + minisearch.removeAll(); + minisearch.addAll( + sessions.map((session) => ({ + title: session.title, + sessionId: session.sessionId, + id: session.sessionId, + })), + ); + } catch (e) { + console.log("error adding sessions to minisearch", e); + } }; fetchSessions(); }, [lastSessionId]); diff --git a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx index e798bf18a..2113be710 100644 --- a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx +++ b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx @@ -41,7 +41,7 @@ function QuickstartSubmitButton() { force: true, }); - if (result.status === "success" && typeof result.content === "string") { + if (result.status === "success") { onComplete(); } else { ideMessenger.post("showToast", [ diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index 2e4175083..d16587427 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -57,11 +57,11 @@ function OnboardingLocalTab() { useEffect(() => { const fetchDownloadedModels = async () => { try { - const result = (await ideMessenger.request("llm/listModels", { + const result = await ideMessenger.request("llm/listModels", { title: ONBOARDING_LOCAL_MODEL_TITLE, - })) as any; + }) - if (result.status === "success" && Array.isArray(result.content)) { + if (result.status === "success") { setDownloadedOllamaModels(result.content); setIsOllamaConnected(true); } else { diff --git a/gui/src/components/ProfileSwitcher.tsx b/gui/src/components/ProfileSwitcher.tsx index 4fe8bd72d..601de6782 100644 --- a/gui/src/components/ProfileSwitcher.tsx +++ b/gui/src/components/ProfileSwitcher.tsx @@ -193,7 +193,7 @@ function ProfileSwitcher() { { - ideMessenger.request("didChangeSelectedProfile", { id }); + ideMessenger.post("didChangeSelectedProfile", { id }); }} >
diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 1eba7ee91..22523cfb2 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -105,6 +105,7 @@ function StepContainer(props: StepContainerProps) { )} diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 217fcc293..20d700c63 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -1,28 +1,25 @@ import { NodeViewWrapper } from "@tiptap/react"; import { ContextItemWithId } from "core"; -import { useDispatch, useSelector } from "react-redux"; import { vscBadgeBackground } from ".."; -import { RootState } from "../../redux/store"; import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; -export const CodeBlockComponent = ({ - node, - deleteNode, - selected, - editor, - updateAttributes, -}: any) => { - const dispatch = useDispatch(); +export const CodeBlockComponent = (props: any) => { + const { node, deleteNode, selected, editor, updateAttributes } = props; const item: ContextItemWithId = node.attrs.item; + // const contextItems = useSelector( + // (store: RootState) => + // store.state.history[store.state.history.length - 1].contextItems, + // ); + // const isFirstContextItem = item.id === contextItems[0]?.id; + const isFirstContextItem = false; - const contextItems = useSelector( - (state: RootState) => state.state.contextItems, - ); return ( { title: "New .prompt file", type: "action", action: () => { - ideMessenger.request("config/newPromptFile", undefined); + ideMessenger.post("config/newPromptFile", undefined); const { tr } = props.editor.view.state; const text = tr.doc.textBetween(0, tr.selection.from); const start = text.lastIndexOf("@"); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 98f1b79cc..6da867b40 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -225,10 +225,6 @@ function TipTapEditor(props: TipTapEditorProps) { inDropdownRef.current = true; }; - const contextItems = useSelector( - (store: RootState) => store.state.contextItems, - ); - const defaultModel = useSelector(defaultModelSelector); const defaultModelRef = useUpdatingRef(defaultModel); @@ -498,19 +494,7 @@ function TipTapEditor(props: TipTapEditorProps) { content: props.editorState || mainEditorContent || "", onFocus: () => setIsEditorFocused(true), onBlur: () => setIsEditorFocused(false), - onUpdate: ({ editor, transaction }) => { - // If /edit is typed and no context items are selected, select the first - - if (contextItems.length > 0) { - return; - } - - const json = editor.getJSON(); - let codeBlock = json.content?.find((el) => el.type === "codeBlock"); - if (!codeBlock) { - return; - } - }, + // onUpdate editable: !active || props.isMainInput, }); diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx index 3a424e257..4e07ead6d 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/TutorialCard.tsx @@ -57,7 +57,7 @@ export function TutorialCard({ onClose }: TutorialCardProps) { - ideMessenger.request( + ideMessenger.post( "vscode/openMoveRightMarkdown", undefined, ) diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 7711562ae..b52328148 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -89,7 +89,7 @@ function getSubActionsForSubmenuItem( label: "Open in new tab", icon: "trash", action: () => { - ideMessenger.request("context/removeDocs", { startUrl: item.id }); + ideMessenger.post("context/removeDocs", { startUrl: item.id }); }, }, ]; @@ -166,7 +166,7 @@ export function getContextProviderDropdownOptions( title: "Add more context providers", type: "action", action: () => { - ideMessenger.request( + ideMessenger.post( "openUrl", "https://docs.continue.dev/customization/context-providers#built-in-context-providers", ); @@ -196,7 +196,7 @@ export function getSlashCommandDropdownOptions( // id: "createPromptFile", // label: "Create Prompt File", // action: () => { - // ideMessenger.request("config/newPromptFile", undefined); + // ideMessenger.post("config/newPromptFile", undefined); // }, // name: "Create Prompt File", // }, diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 639e14cc8..39c09cfb6 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -124,6 +124,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { source={`${fence}${getMarkdownLanguageTagForFile( props.item.description.split(" ")[0], )} ${props.item.description}\n${content}\n${fence}`} + contextItems={[props.item]} />
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index ac13c6d54..0fa57fd08 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -2,7 +2,7 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; -import styled, { keyframes } from "styled-components"; +import styled, { css, keyframes } from "styled-components"; import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, lightGray, vscEditorBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; @@ -26,13 +26,18 @@ const fadeInAnimation = keyframes` } `; -const TopDiv = styled.div` +const TopDiv = styled.div<{ active?: boolean }>` outline: 1px solid rgba(153, 153, 152); outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; - animation: ${fadeInAnimation} 300ms ease-out forwards; + ${(props) => + props.active + ? "animation: none;" + : css` + animation: ${fadeInAnimation} 300ms ease-out forwards; + `} `; const ToolbarDiv = styled.div<{ isExpanded: boolean }>` @@ -67,6 +72,7 @@ export default function StepContainerPreToolbar( const isMultifileEdit = useSelector( (state: RootState) => state.state.isInMultifileEdit, ); + const active = useSelector((state: RootState) => state.state.active); const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); @@ -168,7 +174,7 @@ export default function StepContainerPreToolbar( } return ( - +
processCodeBlocks], rehypePlugins: [ @@ -236,13 +234,14 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( code: ({ node, ...codeProps }) => { const content = getCodeChildrenContent(codeProps.children); - const ctxItem = contextItems.find((ctxItem) => - ctxItem.uri?.value.includes(content), - ); - - if (ctxItem) { - const rif = ctxItemToRifWithContents(ctxItem); - return ; + if (props.contextItems) { + const ctxItem = props.contextItems.find((ctxItem) => + ctxItem.uri?.value.includes(content), + ); + if (ctxItem) { + const rif = ctxItemToRifWithContents(ctxItem); + return ; + } } return {codeProps.children}; diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index 4b7b55ab8..7e8e5fde1 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -35,7 +35,7 @@ function EditorInset() { if (!elementRef.current) return; console.log("Height: ", elementRef.current.clientHeight); - ideMessenger.request("jetbrains/editorInsetHeight", { + ideMessenger.post("jetbrains/editorInsetHeight", { height: elementRef.current.clientHeight, }); }); diff --git a/gui/src/hooks/useAuth.tsx b/gui/src/hooks/useAuth.tsx index 49961df8b..994c8c1e7 100644 --- a/gui/src/hooks/useAuth.tsx +++ b/gui/src/hooks/useAuth.tsx @@ -68,7 +68,7 @@ export function useAuth(): { confirmText="Yes, log out" text={"Are you sure you want to log out of Continue?"} onConfirm={() => { - ideMessenger.request("logoutOfControlPlane", undefined); + ideMessenger.post("logoutOfControlPlane", undefined); }} />, ), diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 2e35acc53..229c03ebc 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -23,7 +23,6 @@ import resolveEditorContent, { import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { - addContextItems, addPromptCompletionPair, clearLastResponse, initNewActiveMessage, @@ -50,10 +49,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { (store: RootState) => store.state.config.slashCommands || [], ); - const contextItems = useSelector( - (state: RootState) => state.state.contextItems, - ); - const history = useSelector((store: RootState) => store.state.history); const active = useSelector((store: RootState) => store.state.active); const activeRef = useRef(active); @@ -226,26 +221,33 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { .slice(0, 1000) .join("\n"); } - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( - currentFile.path, - await ideMessenger.ide.getWorkspaceDirs(), - )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, - providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); + if ( + !selectedContextItems.find( + (item) => item.uri?.value === currentFile.path, + ) + ) { + // don't add the file if it's already in the context items + selectedContextItems.unshift({ + content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( + currentFile.path, + await ideMessenger.ide.getWorkspaceDirs(), + )}\n${currentFileContents}\n\`\`\``, + name: `Active file: ${getBasename(currentFile.path)}`, + description: currentFile.path, + id: { + itemId: currentFile.path, + providerTitle: "file", + }, + uri: { + type: "file", + value: currentFile.path, + }, + }); + } } } - dispatch(addContextItems(contextItems)); + // dispatch(addContextItems(contextItems)); const message: ChatMessage = { role: "user", diff --git a/gui/src/hooks/useCopy.tsx b/gui/src/hooks/useCopy.tsx index e8d880828..4daa0b933 100644 --- a/gui/src/hooks/useCopy.tsx +++ b/gui/src/hooks/useCopy.tsx @@ -9,7 +9,7 @@ export default function useCopy(text: string | (() => string)) { const copyText = useCallback(() => { const textVal = typeof text === "string" ? text : text(); if (isJetBrains()) { - ideMessenger.request("copyText", { text: textVal }); + ideMessenger.post("copyText", { text: textVal }); } else { navigator.clipboard.writeText(textVal); } diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 1d8963b5e..911a2a014 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -121,9 +121,9 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } - const json = result.content; - dispatch(newSession(json)); - return json; + const persistedSessionInfo = result.content; + dispatch(newSession(persistedSessionInfo)); + return persistedSessionInfo; } async function loadLastSession(): Promise { diff --git a/gui/src/hooks/useIsOSREnabled.ts b/gui/src/hooks/useIsOSREnabled.ts index f1e71770a..10ad04756 100644 --- a/gui/src/hooks/useIsOSREnabled.ts +++ b/gui/src/hooks/useIsOSREnabled.ts @@ -13,7 +13,7 @@ export default function useIsOSREnabled() { useEffect(() => { if (isJetBrains()) { - ideMessenger.request("jetbrains/isOSREnabled", undefined); + ideMessenger.post("jetbrains/isOSREnabled", undefined); } }, []); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 07bcec0eb..49a6d429f 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,5 +1,5 @@ import { Dispatch } from "@reduxjs/toolkit"; -import { useContext, useEffect, useState } from "react"; +import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -21,11 +21,10 @@ import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; function useSetup(dispatch: Dispatch) { - const [configLoaded, setConfigLoaded] = useState(false); - const ideMessenger = useContext(IdeMessengerContext); - const loadConfig = async () => { + const initialConfigLoad = useRef(false); + const loadConfig = useCallback(async () => { const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, @@ -36,20 +35,21 @@ function useSetup(dispatch: Dispatch) { const { config, profileId } = result.content; dispatch(setConfig(config)); dispatch(setSelectedProfileId(profileId)); - setConfigLoaded(true); + initialConfigLoad.current = true; + setLocalStorage("disableIndexing", config.disableIndexing || false); // Perform any actions needed with the config if (config.ui?.fontSize) { setLocalStorage("fontSize", config.ui.fontSize); document.body.style.fontSize = `${config.ui.fontSize}px`; } - }; + }, [dispatch, ideMessenger, initialConfigLoad]); // Load config from the IDE useEffect(() => { loadConfig(); const interval = setInterval(() => { - if (configLoaded) { + if (initialConfigLoad.current) { clearInterval(interval); return; } @@ -57,7 +57,7 @@ function useSetup(dispatch: Dispatch) { }, 2_000); return () => clearInterval(interval); - }, [configLoaded]); + }, [initialConfigLoad, loadConfig]); useEffect(() => { // Override persisted state diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index 7f9e65f73..67abeb632 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -234,12 +234,12 @@ function useSubmenuContextProviders() { storeFields: ["id", "title", "description"], }); - const result = (await ideMessenger.request( + const result = await ideMessenger.request( "context/loadSubmenuItems", { title: description.title, }, - )) as WebviewMessengerResult<"context/loadSubmenuItems">; + ) if (result.status === "error") { console.error( diff --git a/gui/src/pages/edit/EditInputHeader.tsx b/gui/src/pages/edit/EditInputHeader.tsx index b7b66de8c..8248bbfa6 100644 --- a/gui/src/pages/edit/EditInputHeader.tsx +++ b/gui/src/pages/edit/EditInputHeader.tsx @@ -82,7 +82,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { className="h-4 w-4 cursor-pointer px-2" color="red" onClick={() => { - ideMessenger.request("edit/acceptReject", { + ideMessenger.post("edit/acceptReject", { accept: false, onlyFirst: false, filepath: editModeState.highlightedCode.filepath, @@ -95,7 +95,7 @@ export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { { - ideMessenger.request("edit/acceptReject", { + ideMessenger.post("edit/acceptReject", { accept: true, onlyFirst: false, filepath: editModeState.highlightedCode.filepath, diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index 5b1b71e66..3b708e980 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -98,7 +98,7 @@ function Edit() { // Reusing the applyState logic which was just the fastest way to get this working useEffect(() => { if (editModeState.editStatus === "done") { - ideMessenger.request("edit/escape", undefined); + ideMessenger.post("edit/escape", undefined); navigate("/"); } }, [editModeState.editStatus]); @@ -180,7 +180,7 @@ function Edit() { ...contextItems.map((item) => item.content), stripImages(userInstructions), ].join("\n\n"); - ideMessenger.request("edit/sendPrompt", { + ideMessenger.post("edit/sendPrompt", { prompt, range: editModeState.highlightedCode, }); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 78bbcd262..1cb6d66d6 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -159,11 +159,11 @@ export function Chat() { if (active) snapToBottom(); }, [active, snapToBottom]); - useEffect(() => { - setTimeout(() => { - smoothScrollToBottom(); - }, 400); - }, [smoothScrollToBottom, state.sessionId]); + // useEffect(() => { + // setTimeout(() => { + // smoothScrollToBottom(); + // }, 400); + // }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { // Cmd + Backspace to delete current step @@ -290,7 +290,7 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [state.history, state.contextItems, defaultModel, state, streamResponse], + [state.history, defaultModel, state, streamResponse], ); useWebviewListener( diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index e3ce22eb6..4222b4693 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -15,16 +15,6 @@ import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; import { RootState } from "../store"; -export const memoizedContextItemsSelector = createSelector( - [(state: RootState) => state.state.history], - (history) => { - return history.reduce((acc, item) => { - acc.push(...item.contextItems); - return acc; - }, []); - }, -); - // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. type ChatHistoryItemWithMessageId = ChatHistoryItem & { @@ -33,7 +23,6 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { type State = { history: ChatHistoryItemWithMessageId[]; - contextItems: ContextItemWithId[]; ttsActive: boolean; active: boolean; isGatheringContext: boolean; @@ -49,7 +38,6 @@ type State = { const initialState: State = { history: [], - contextItems: [], ttsActive: false, active: false, isGatheringContext: false, @@ -143,9 +131,6 @@ export const stateSlice = createSlice({ state.history[index].contextItems = contextItems; } }, - addContextItems: (state, action: PayloadAction) => { - state.contextItems = state.contextItems.concat(action.payload); - }, resubmitAtIndex: ( state, { @@ -173,7 +158,6 @@ export const stateSlice = createSlice({ }); // https://github.com/continuedev/continue/pull/1021 - // state.contextItems = []; state.active = true; }, deleteMessage: (state, action: PayloadAction) => { @@ -190,7 +174,7 @@ export const stateSlice = createSlice({ ) => { state.history.push({ message: { role: "user", content: "", id: uuidv4() }, - contextItems: state.contextItems, + contextItems: [], editorState: payload.editorState, }); state.history.push({ @@ -201,8 +185,7 @@ export const stateSlice = createSlice({ }, contextItems: [], }); - // https://github.com/continuedev/continue/pull/1021 - // state.contextItems = []; + state.active = true; }, setMessageAtIndex: ( @@ -272,78 +255,27 @@ export const stateSlice = createSlice({ state.sessionId = payload.sessionId; } else { state.history = []; - state.contextItems = []; state.active = false; state.title = "New Session"; state.sessionId = v4(); state.isInMultifileEdit = false; } }, - deleteContextWithIds: ( - state, - { - payload, - }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }>, - ) => { - const getKey = (id: ContextItemId) => `${id.providerTitle}-${id.itemId}`; - const ids = new Set(payload.ids.map(getKey)); - - if (payload.index === undefined) { - state.contextItems = state.contextItems.filter( - (item) => !ids.has(getKey(item.id)), - ); - } else { - state.history[payload.index].contextItems = state.history[ - payload.index - ].contextItems.filter((item) => !ids.has(getKey(item.id))); - } - }, addHighlightedCode: ( state, { payload, }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>, ) => { - let contextItems = [...state.contextItems].map((item) => { + let contextItems = + state.history[state.history.length - 1].contextItems ?? []; + contextItems = contextItems.map((item) => { return { ...item, editing: false }; }); const base = payload.rangeInFileWithContents.filepath .split(/[\\/]/) .pop(); - // Merge if there is overlap - for (let i = 0; i < contextItems.length; i++) { - const item = contextItems[i]; - if (item.description === payload.rangeInFileWithContents.filepath) { - let newStart = payload.rangeInFileWithContents.range.start.line; - let newEnd = payload.rangeInFileWithContents.range.end.line; - let [oldStart, oldEnd] = item.name - .split("(")[1] - .split(")")[0] - .split("-") - .map((x: string) => parseInt(x) - 1); - if (newStart > oldEnd || newEnd < oldStart) { - continue; - } - const startLine = Math.min(newStart, oldStart); - const endLine = Math.max(newEnd, oldEnd); - - // const oldContents = item.content.split("\n"); - // const newContents = - // payload.rangeInFileWithContents.contents.split("\n"); - // const finalContents = []; - - contextItems[i] = { - ...item, - name: `${base} (${startLine + 1}-${endLine + 1})`, - content: payload.rangeInFileWithContents.contents, - editing: true, - editable: true, - }; - return { ...state, contextItems }; - } - } - const lineNums = `(${ payload.rangeInFileWithContents.range.start.line + 1 }-${payload.rangeInFileWithContents.range.end.line + 1})`; @@ -358,46 +290,7 @@ export const stateSlice = createSlice({ editing: true, editable: true, }); - - return { ...state, contextItems }; - }, - setEditingAtIds: ( - state, - { - payload, - }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }>, - ) => { - const ids = payload.ids.map((id) => id.itemId); - - if (typeof payload.index === "undefined") { - return { - ...state, - contextItems: state.contextItems.map((item) => { - return { - ...item, - editing: ids.includes(item.id.itemId), - }; - }), - }; - } else { - return { - ...state, - history: state.history.map((step, i) => { - if (i === payload.index) { - return { - ...step, - contextItems: step.contextItems.map((item) => { - return { - ...item, - editing: ids.includes(item.id.itemId), - }; - }), - }; - } - return step; - }), - }; - } + state.history[state.history.length - 1].contextItems = contextItems; }, setDefaultModel: ( state, @@ -426,15 +319,12 @@ export const stateSlice = createSlice({ export const { setContextItemsAtIndex, - addContextItems, addContextItemsAtIndex, setInactive, streamUpdate, newSession, - deleteContextWithIds, resubmitAtIndex, addHighlightedCode, - setEditingAtIds, setDefaultModel, setConfig, setConfigError, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index a5d0313f4..221d275c9 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -40,12 +40,7 @@ const windowIDTransform = (windowID: string) => ); const saveSubsetFilters = [ - createFilter("state", [ - "history", - "contextItems", - "sessionId", - "defaultModelTitle", - ]), + createFilter("state", ["history", "sessionId", "defaultModelTitle"]), ]; const persistConfig = {