From 1755280a6d417a0a35583c0b014d46ce081a32c0 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:03:32 -0700 Subject: [PATCH 001/186] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 122 ++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 57 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 2e0054d5b..4c2954380 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -16,7 +16,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, - MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, } from "./types.js"; @@ -48,6 +47,8 @@ export class LanceDbIndex implements CodebaseIndex { } private async createSqliteCacheTable(db: DatabaseConnection) { + await db.exec("PRAGMA journal_mode=WAL;"); + await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache ( uuid TEXT PRIMARY KEY, cacheKey TEXT NOT NULL, @@ -84,47 +85,6 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async packToRows(item: PathAndCacheKey): Promise { - const content = await this.readFile(item.path); - const chunks: Chunk[] = []; - const chunkParams = { - filepath: item.path, - contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, - digest: item.cacheKey, - }; - for await (const chunk of chunkDocument(chunkParams)) { - if (chunk.content.length === 0) { - // File did not chunk properly, let's skip it. - throw new Error("did not chunk properly"); - } - chunks.push(chunk); - if (chunks.length > 20) { - // Too many chunks to index, probably a larger file than we want to include - throw new Error("too large to index"); - } - } - const embeddings = await this.chunkListToEmbedding(chunks); - if (chunks.length !== embeddings.length) { - throw new Error( - `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, - ); - } - const results = []; - for (let i = 0; i < chunks.length; i++) { - results.push({ - path: item.path, - cachekey: item.cacheKey, - uuid: uuidv4(), - vector: embeddings[i], - startLine: chunks[i].startLine, - endLine: chunks[i].endLine, - contents: chunks[i].content, - }); - } - return results; - } - private async chunkListToEmbedding(chunks: Chunk[]): Promise { let embeddings: number[][]; try { @@ -146,22 +106,74 @@ export class LanceDbIndex implements CodebaseIndex { } private async computeRows(items: PathAndCacheKey[]): Promise { - const rowChunkPromises = items.map(this.packToRows.bind(this)); - const rowChunkLists = []; - for (let i = 0; i < items.length; i++) { + const allChunks: Chunk[] = []; + const chunkMap: Map = + new Map(); + + // First, collect all chunks + for (const item of items) { try { - rowChunkLists.push(await rowChunkPromises[i]); + const content = await this.readFile(item.path); + const chunks: Chunk[] = []; + const chunkParams = { + filepath: item.path, + contents: content, + maxChunkSize: this.embeddingsProvider.maxChunkSize, + digest: item.cacheKey, + }; + + for await (const chunk of chunkDocument(chunkParams)) { + if (chunk.content.length === 0) { + throw new Error("did not chunk properly"); + } + + chunks.push(chunk); + allChunks.push(chunk); + + if (chunks.length > 20) { + throw new Error("too large to index"); + } + } + + chunkMap.set(item.path, { item, chunks }); } catch (err) { - console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`); + console.log(`LanceDBIndex, skipping ${item.path}: ${err}`); } } - return rowChunkLists.flat(); + + // Now, get embeddings for all chunks in a single request + const embeddings = await this.chunkListToEmbedding(allChunks); + + // Associate embeddings back with their chunks and create LanceDbRows + const results: LanceDbRow[] = []; + + let embeddingIndex = 0; + + for (const [path, { item, chunks }] of chunkMap) { + for (const chunk of chunks) { + results.push({ + path, + cachekey: item.cacheKey, + uuid: uuidv4(), + vector: embeddings[embeddingIndex], + startLine: chunk.startLine, + endLine: chunk.endLine, + contents: chunk.content, + }); + embeddingIndex++; + } + } + + return results; } async *update( tag: IndexTag, results: RefreshIndexResults, - markComplete: MarkCompleteCallback, + markComplete: ( + items: PathAndCacheKey[], + resultType: IndexResultType, + ) => void, repoName: string | undefined, ): AsyncGenerator { const lancedb = await import("vectordb"); @@ -197,7 +209,7 @@ export class LanceDbIndex implements CodebaseIndex { } // Mark item complete - await markComplete([pathAndCacheKey], IndexResultType.Compute); + markComplete([pathAndCacheKey], IndexResultType.Compute); }; // Check remote cache @@ -265,12 +277,8 @@ export class LanceDbIndex implements CodebaseIndex { } ${this.formatListPlurality("file", results.compute.length)}`, status: "indexing", }; - - console.log(results.compute); - const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); - await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache @@ -305,7 +313,7 @@ export class LanceDbIndex implements CodebaseIndex { } } - await markComplete([{ path, cacheKey }], IndexResultType.AddTag); + markComplete([{ path, cacheKey }], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 3; yield { progress: accumulatedProgress, @@ -329,7 +337,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } } - await markComplete(results.removeTag, IndexResultType.RemoveTag); + markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { @@ -347,7 +355,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } - await markComplete(results.del, IndexResultType.Delete); + markComplete(results.del, IndexResultType.Delete); yield { progress: 1, desc: "Completed Calculating Embeddings", From 99d3add5f4787430a83510b8fd255a75069ed5de Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:03:45 -0700 Subject: [PATCH 002/186] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 4c2954380..6e6a3cc9e 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -47,8 +47,6 @@ export class LanceDbIndex implements CodebaseIndex { } private async createSqliteCacheTable(db: DatabaseConnection) { - await db.exec("PRAGMA journal_mode=WAL;"); - await db.exec(`CREATE TABLE IF NOT EXISTS lance_db_cache ( uuid TEXT PRIMARY KEY, cacheKey TEXT NOT NULL, From 137bc59a9e4d6a6874c0b7be9a87bb879c737433 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 10:06:48 -0700 Subject: [PATCH 003/186] Update LanceDbIndex.ts --- core/indexing/LanceDbIndex.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 6e6a3cc9e..0dbf6e5fb 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -16,6 +16,7 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, + MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, } from "./types.js"; @@ -168,10 +169,7 @@ export class LanceDbIndex implements CodebaseIndex { async *update( tag: IndexTag, results: RefreshIndexResults, - markComplete: ( - items: PathAndCacheKey[], - resultType: IndexResultType, - ) => void, + markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { const lancedb = await import("vectordb"); @@ -277,6 +275,7 @@ export class LanceDbIndex implements CodebaseIndex { }; const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); + await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache @@ -311,7 +310,7 @@ export class LanceDbIndex implements CodebaseIndex { } } - markComplete([{ path, cacheKey }], IndexResultType.AddTag); + await markComplete([{ path, cacheKey }], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 3; yield { progress: accumulatedProgress, @@ -335,7 +334,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } } - markComplete(results.removeTag, IndexResultType.RemoveTag); + await markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { @@ -353,7 +352,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } - markComplete(results.del, IndexResultType.Delete); + await markComplete(results.del, IndexResultType.Delete); yield { progress: 1, desc: "Completed Calculating Embeddings", From a77f2499e42bd135e4e1808dc719ac3c2ccbb8e7 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 11:13:06 -0700 Subject: [PATCH 004/186] handle undefined embeddings --- core/indexing/LanceDbIndex.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 0dbf6e5fb..17fcc46f7 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -143,6 +143,15 @@ export class LanceDbIndex implements CodebaseIndex { // Now, get embeddings for all chunks in a single request const embeddings = await this.chunkListToEmbedding(allChunks); + // We probably dont want to blow up all embedding here, + // maybe we just filter out the chunks alongside the undefined + // embeddings in `chunkListToEmbedding` + if (allChunks.length !== embeddings.length) { + throw new Error( + `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, + ); + } + // Associate embeddings back with their chunks and create LanceDbRows const results: LanceDbRow[] = []; @@ -205,7 +214,7 @@ export class LanceDbIndex implements CodebaseIndex { } // Mark item complete - markComplete([pathAndCacheKey], IndexResultType.Compute); + await markComplete([pathAndCacheKey], IndexResultType.Compute); }; // Check remote cache @@ -273,6 +282,9 @@ export class LanceDbIndex implements CodebaseIndex { } ${this.formatListPlurality("file", results.compute.length)}`, status: "indexing", }; + + console.log(results.compute); + const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); await markComplete(results.compute, IndexResultType.Compute); From 9f39e12d44b75bca7ff04ed6b38a7dbf2e0c516b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 13:32:31 -0700 Subject: [PATCH 005/186] break down computeRows --- .vscode/launch.json | 3 +- core/indexing/CodebaseIndexer.ts | 18 ++-- core/indexing/LanceDbIndex.ts | 128 +++++++++++++++------------- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- 5 files changed, 82 insertions(+), 73 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 54d282cc8..bde875483 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,8 +12,7 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/manual-testing-sandbox", - "${workspaceFolder}/manual-testing-sandbox/test.js", + "${workspaceFolder}/extensions/vscode", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index efef51c72..9177aa510 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -26,6 +26,8 @@ export class PauseToken { } export class CodebaseIndexer { + batchSize = 100; + constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, @@ -266,11 +268,6 @@ export class CodebaseIndexer { } } - private getBatchSize(workspaceSize: number): number { - // at least 10 and as much as 100 (in a repository with 10000 files) - return Math.min(100, Math.max(10, Math.floor(workspaceSize / 100))); - } - /* * enables the indexing operation to be completed in small batches, this is important in large * repositories where indexing can quickly use up all the memory available @@ -280,7 +277,6 @@ export class CodebaseIndexer { workspaceSize: number, ): Generator { let curPos = 0; - const batchSize = this.getBatchSize(workspaceSize); while ( curPos < results.compute.length || curPos < results.del.length || @@ -288,12 +284,12 @@ export class CodebaseIndexer { curPos < results.removeTag.length ) { yield { - compute: results.compute.slice(curPos, curPos + batchSize), - del: results.del.slice(curPos, curPos + batchSize), - addTag: results.addTag.slice(curPos, curPos + batchSize), - removeTag: results.removeTag.slice(curPos, curPos + batchSize), + compute: results.compute.slice(curPos, curPos + this.batchSize), + del: results.del.slice(curPos, curPos + this.batchSize), + addTag: results.addTag.slice(curPos, curPos + this.batchSize), + removeTag: results.removeTag.slice(curPos, curPos + this.batchSize), }; - curPos += batchSize; + curPos += this.batchSize; } } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 17fcc46f7..7c5aaa26d 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -31,6 +31,10 @@ interface LanceDbRow { [key: string]: any; } +type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] }; + +type ChunkMap = Map; + export class LanceDbIndex implements CodebaseIndex { relativeExpectedTime: number = 13; get artifactId(): string { @@ -84,77 +88,89 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async chunkListToEmbedding(chunks: Chunk[]): Promise { - let embeddings: number[][]; - try { - embeddings = await this.embeddingsProvider.embed( - chunks.map((c) => c.content), - ); - } catch (err) { - throw new Error( - `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`, - { cause: err }, - ); - } - if (embeddings.some((emb) => emb === undefined)) { - throw new Error( - `Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`, - ); - } - return embeddings; - } - private async computeRows(items: PathAndCacheKey[]): Promise { - const allChunks: Chunk[] = []; - const chunkMap: Map = - new Map(); + const chunkMap = await this.collectChunks(items); + const allChunks = Array.from(chunkMap.values()).flatMap( + ({ chunks }) => chunks, + ); + const embeddings = await this.getEmbeddings(allChunks); - // First, collect all chunks - for (const item of items) { - try { - const content = await this.readFile(item.path); - const chunks: Chunk[] = []; - const chunkParams = { - filepath: item.path, - contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, - digest: item.cacheKey, - }; + // Remove undefined embeddings and their corresponding chunks + for (let i = embeddings.length - 1; i >= 0; i--) { + if (embeddings[i] === undefined) { + const chunk = allChunks[i]; + const chunks = chunkMap.get(chunk.filepath)?.chunks; - for await (const chunk of chunkDocument(chunkParams)) { - if (chunk.content.length === 0) { - throw new Error("did not chunk properly"); - } - - chunks.push(chunk); - allChunks.push(chunk); - - if (chunks.length > 20) { - throw new Error("too large to index"); + if (chunks) { + const index = chunks.findIndex((c) => c === chunk); + if (index !== -1) { + chunks.splice(index, 1); } } + embeddings.splice(i, 1); + } + } + + return this.createLanceDbRows(chunkMap, embeddings); + } + + private async collectChunks(items: PathAndCacheKey[]): Promise { + const chunkMap: ChunkMap = new Map(); + + for (const item of items) { + try { + const content = await this.readFile(item.path); + const chunks = await this.getChunks(item, content); chunkMap.set(item.path, { item, chunks }); } catch (err) { console.log(`LanceDBIndex, skipping ${item.path}: ${err}`); } } - // Now, get embeddings for all chunks in a single request - const embeddings = await this.chunkListToEmbedding(allChunks); + return chunkMap; + } - // We probably dont want to blow up all embedding here, - // maybe we just filter out the chunks alongside the undefined - // embeddings in `chunkListToEmbedding` - if (allChunks.length !== embeddings.length) { - throw new Error( - `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, - ); + private async getChunks( + item: PathAndCacheKey, + content: string, + ): Promise { + const chunks: Chunk[] = []; + + const chunkParams = { + filepath: item.path, + contents: content, + maxChunkSize: this.embeddingsProvider.maxChunkSize, + digest: item.cacheKey, + }; + + for await (const chunk of chunkDocument(chunkParams)) { + if (chunk.content.length === 0) { + throw new Error("did not chunk properly"); + } + + chunks.push(chunk); } - // Associate embeddings back with their chunks and create LanceDbRows - const results: LanceDbRow[] = []; + return chunks; + } + private async getEmbeddings(chunks: Chunk[]): Promise { + try { + return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); + } catch (err) { + throw new Error( + `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`, + { cause: err }, + ); + } + } + + private createLanceDbRows( + chunkMap: ChunkMap, + embeddings: number[][], + ): LanceDbRow[] { + const results: LanceDbRow[] = []; let embeddingIndex = 0; for (const [path, { item, chunks }] of chunkMap) { @@ -283,8 +299,6 @@ export class LanceDbIndex implements CodebaseIndex { status: "indexing", }; - console.log(results.compute); - const dbRows = await this.computeRows(results.compute); this.insertRows(sqlite, dbRows); await markComplete(results.compute, IndexResultType.Compute); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8a3b9674..a5fe4405d 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.196", + "version": "0.9.197", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.196", + "version": "0.9.197", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d6006bcc..8cc156935 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.196", + "version": "0.9.197", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 3f62e66d96b65402f885c454f4046fb098d430bc Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 9 Aug 2024 13:43:37 -0700 Subject: [PATCH 006/186] Update launch.json --- .vscode/launch.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index bde875483..54d282cc8 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -12,7 +12,8 @@ "cwd": "${workspaceFolder}/extensions/vscode", "args": [ // Pass a directory to manually test in - "${workspaceFolder}/extensions/vscode", + "${workspaceFolder}/manual-testing-sandbox", + "${workspaceFolder}/manual-testing-sandbox/test.js", "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, From 4c4b211aaee0e4556abc19f82c02e98cc3e74611 Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Fri, 9 Aug 2024 15:04:55 -0700 Subject: [PATCH 007/186] Move the bulk insert resolve into the COMMIT callback db.db.serialize(...) guarantees that each statement runs in order. However, the function itself will terminate execution long before all the statements are executed. Therefore, we should only resolve the promise when the last COMMIT transaction has run. In the other cases, there will have been an error and we'll have call reject(err). This also removed the need for the extra insert that was recently added so it was removed (in fact the extra insert was causing conflict errors). --- core/indexing/LanceDbIndex.ts | 11 ++--------- core/indexing/chunk/ChunkCodebaseIndex.ts | 4 ++-- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 198232a95..f7f1e6ecc 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -268,14 +268,6 @@ export class LanceDbIndex implements CodebaseIndex { const dbRows = await this.computeRows(results.compute); await this.insertRows(sqlite, dbRows); - await Promise.all( - results.compute.map((item) => { - addComputedLanceDbRows( - item, - dbRows.filter((row) => row.path === item.path), - ); - }), - ); await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; @@ -481,9 +473,10 @@ export class LanceDbIndex implements CodebaseIndex { { cause: err }, ), ); + } else { + resolve(); } }); - resolve(); }); }); } diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 008f90c62..0e866b3bf 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -133,7 +133,6 @@ export class ChunkCodebaseIndex implements CodebaseIndex { } } - private async createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -201,9 +200,10 @@ export class ChunkCodebaseIndex implements CodebaseIndex { db.db.exec("COMMIT", (err: Error | null) => { if (err) { reject(new Error("error while committing insert chunks transaction", { cause: err })); + } else { + resolve(); } }); - resolve(); }); }); } From 10e860833aef115f75238dda89b32be162198b46 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 11 Aug 2024 19:01:32 -0700 Subject: [PATCH 008/186] support for all context providers in defaultContext --- core/index.d.ts | 6 +++++- docs/static/schemas/config.json | 14 +++++++++++++- .../src/main/resources/config_schema.json | 14 +++++++++++++- extensions/vscode/config_schema.json | 14 +++++++++++++- extensions/vscode/continue_rc_schema.json | 14 ++++++++++++-- gui/src/components/mainInput/resolveInput.ts | 16 ++++++++++++++++ gui/src/hooks/useChatHandler.ts | 8 ++++++-- 7 files changed, 78 insertions(+), 8 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index d3ff2a4b8..05e0d90a6 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -871,10 +871,14 @@ interface QuickActionConfig { sendToChat: boolean; } +export type DefaultContextProvider = ContextProviderWithParams & { + query?: string; +}; + interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; modelRoles?: ModelRoles; - defaultContext?: "activeFile"[]; + defaultContext?: DefaultContextProvider[]; promptPath?: string; /** diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 180454880..44a908810 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -2374,7 +2374,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 180454880..44a908810 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -2374,7 +2374,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 180454880..44a908810 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2374,7 +2374,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index fcbba3140..d6c797596 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -2669,8 +2669,18 @@ "defaultContext": { "type": "array", "items": { - "enum": [ - "activeFile" + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } ] } }, diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 955ea6f4d..7d26faf25 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -1,6 +1,7 @@ import { JSONContent } from "@tiptap/react"; import { ContextItemWithId, + DefaultContextProvider, InputModifiers, MessageContent, MessagePart, @@ -27,6 +28,7 @@ async function resolveEditorContent( editorState: JSONContent, modifiers: InputModifiers, ideMessenger: IIdeMessenger, + defaultContextProviders: DefaultContextProvider[], ): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> { let parts: MessagePart[] = []; let contextItemAttrs: MentionAttrs[] = []; @@ -131,6 +133,20 @@ async function resolveEditorContent( } } + // Include default context providers + const defaultContextItems = await Promise.all( + defaultContextProviders.map(async (provider) => { + const items = await ideMessenger.request("context/getContextItems", { + name: provider.name, + query: provider.query ?? "", + fullInput: stripImages(parts), + selectedCode, + }); + return items; + }), + ); + contextItems.push(...defaultContextItems.flat()); + if (contextItemsText !== "") { contextItemsText += "\n"; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 94e372d3f..035e8322c 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -37,6 +37,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const posthog = usePostHog(); const defaultModel = useSelector(defaultModelSelector); + const defaultContextProviders = useSelector( + (store: RootState) => store.state.config.experimental?.defaultContext ?? [], + ); const slashCommands = useSelector( (store: RootState) => store.state.config.slashCommands || [], @@ -181,11 +184,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { editorState, modifiers, ideMessenger, + defaultContextProviders, ); - dispatch(addContextItems(contextItems)); // Automatically use currently open file - if (!modifiers.noContext && (history.length === 0 || index === 0)) { + if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; const currentFilePath = await ideMessenger.ide.getCurrentFile(); @@ -212,6 +215,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }); } } + dispatch(addContextItems(contextItems)); const message: ChatMessage = { role: "user", From f27a763e9af7f809c5195c4d5bcdaffeffbedb0b Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Sun, 11 Aug 2024 19:32:05 -0700 Subject: [PATCH 009/186] Limit the index planner to only 10 concurrent readFile(...) which prevents issues related to too many open files in large repositories With this change I am able to run the planner on the linux kernel repository. Previously the planner would error out with exceptions related to "too many file handles" on linux or "file table overflow" on macos --- core/indexing/refreshIndex.ts | 23 +++--- core/package-lock.json | 129 +++++++++++++++++++++++++++++++--- core/package.json | 5 +- 3 files changed, 133 insertions(+), 24 deletions(-) diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 26ca80cb6..10fe55605 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -2,6 +2,7 @@ import crypto from "node:crypto"; import * as fs from "node:fs"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; +import plimit from "p-limit"; import { IndexTag, IndexingProgressUpdate } from "../index.js"; import { getIndexSqlitePath } from "../util/paths.js"; import { @@ -143,7 +144,6 @@ async function getAddRemoveForTag( const saved = await getSavedItemsForTag(tag); - const add: PathAndCacheKey[] = []; const updateNewVersion: PathAndCacheKey[] = []; const updateOldVersion: PathAndCacheKey[] = []; const remove: PathAndCacheKey[] = []; @@ -178,15 +178,16 @@ async function getAddRemoveForTag( } } - // Any leftover in current files need to be added - add.push( - ...(await Promise.all( - Object.keys(files).map(async (path) => { - const fileContents = await readFile(path); - return { path, cacheKey: calculateHash(fileContents) }; - }), - )), - ); + // limit to only 10 concurrent file reads to avoid issues such as + // "too many file handles". A large number here does not improve + // throughput due to the nature of disk or network i/o -- huge + // amounts of readers generally does not improve performance + const limit = plimit(10); + const promises = Object.keys(files).map(async (path) => { + const fileContents = await limit(() => readFile(path)); + return { path, cacheKey: calculateHash(fileContents) }; + }); + const add: PathAndCacheKey[] = await Promise.all(promises); // Create the markComplete callback function const db = await SqliteDb.get(); @@ -408,7 +409,7 @@ export async function getComputeDeleteAddRemove( for await (const _ of globalCacheIndex.update( tag, results, - async () => {}, + async () => { }, repoName, )) { } diff --git a/core/package-lock.json b/core/package-lock.json index 28570648f..827f4f57d 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -44,6 +44,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", @@ -9047,6 +9048,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-changed-files/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-changed-files/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-circus": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", @@ -9078,6 +9106,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-circus/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-circus/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-cli": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", @@ -9645,6 +9700,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-runner/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-runner/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-runtime": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", @@ -11049,6 +11131,34 @@ } }, "node_modules/p-limit": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-6.1.0.tgz", + "integrity": "sha512-H0jc0q1vOzlEk0TqAKXKZxdl7kX3OFUzCnNVUnq5Pc3DGo0kpeaMuPqxQn235HibwBEb0/pm9dgKTjXy66fBkg==", + "dependencies": { + "yocto-queue": "^1.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate/node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", @@ -11062,13 +11172,10 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dependencies": { - "p-limit": "^3.0.2" - }, + "node_modules/p-locate/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "engines": { "node": ">=10" }, @@ -13722,11 +13829,11 @@ } }, "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.1.1.tgz", + "integrity": "sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==", "engines": { - "node": ">=10" + "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" diff --git a/core/package.json b/core/package.json index 82a8157b7..39c8246ef 100644 --- a/core/package.json +++ b/core/package.json @@ -39,8 +39,8 @@ }, "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/credential-providers": "^3.620.1", "@aws-sdk/client-sagemaker-runtime": "^3.621.0", + "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.10", "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", @@ -48,7 +48,6 @@ "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", - "jinja-js": "0.1.8", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", @@ -63,6 +62,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", + "jinja-js": "0.1.8", "js-tiktoken": "^1.0.8", "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", @@ -73,6 +73,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", From bdb967d7b3c18fa2e0237f3cc0e0ea7415102715 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 14:54:51 -0700 Subject: [PATCH 010/186] fix: `REPLACE INTO` code_snippet table --- core/indexing/CodeSnippetsIndex.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 8fc1ccb95..e431dfdf8 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -201,7 +201,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (const snippet of snippets) { const { lastID } = await db.run( - "INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", [ addTag.path, addTag.cacheKey, @@ -212,7 +212,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ], ); await db.run( - "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", + "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", [lastID, tagString], ); } From e45d55d58d3c2788e51b277fe54b91bd74d51eed Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 15:00:45 -0700 Subject: [PATCH 011/186] Update index.ts --- gui/src/redux/selectors/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index f41ad42ff..88f5c99bc 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -26,5 +26,5 @@ export const selectContextProviderDescriptions = createSelector( export const selectUseActiveFile = createSelector( [(store: RootState) => store.state.config.experimental?.defaultContext], - (defaultContext) => defaultContext?.includes("activeFile"), + (defaultContext) => defaultContext?.includes("activeFile" as any), ); From 994c9c4dcf21119050496f197b2bf6b76d7a4bda Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 15:47:17 -0700 Subject: [PATCH 012/186] remove extra arg --- core/indexing/CodebaseIndexer.ts | 5 +---- extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 3db9027e2..dfb53470d 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -334,10 +334,7 @@ export class CodebaseIndexer { results.addTag.length + results.removeTag.length; let completedOps = 0; - for (const subResult of this.batchRefreshIndexResults( - results, - workspaceFiles.length, - )) { + for (const subResult of this.batchRefreshIndexResults(results)) { for await (const { desc } of codebaseIndex.update( tag, subResult, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index a5fe4405d..6af742e21 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -130,6 +130,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/gui/package-lock.json b/gui/package-lock.json index 23ff1c5ac..3e67abbcc 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -123,6 +123,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", From c978d7c871be71cd399d02159be8c1b37a0d36ff Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 18:04:13 -0700 Subject: [PATCH 013/186] feat: create "rebuild index" dialog --- core/core.ts | 9 +- core/index.d.ts | 1 + core/indexing/CodebaseIndexer.ts | 54 +++++++-- core/protocol/core.ts | 5 +- extensions/vscode/package-lock.json | 1 + .../vscode/src/extension/VsCodeExtension.ts | 2 +- gui/package-lock.json | 1 + .../components/dialogs/ConfirmationDialog.tsx | 2 +- .../loaders/IndexingProgressBar.tsx | 110 ++++++++++++------ 9 files changed, 137 insertions(+), 48 deletions(-) diff --git a/core/core.ts b/core/core.ts index 6718cdf7d..340008cdb 100644 --- a/core/core.ts +++ b/core/core.ts @@ -638,8 +638,13 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); - on("index/forceReIndex", async (msg) => { - const dirs = msg.data ? [msg.data] : await this.ide.getWorkspaceDirs(); + on("index/forceReIndex", async ({ data }) => { + if (data?.shouldClearIndexes) { + const codebaseIndexer = await this.codebaseIndexerPromise; + await codebaseIndexer.clearIndexes(); + } + + const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs(); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 05e0d90a6..3fcb08fa1 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -37,6 +37,7 @@ export interface Chunk extends ChunkWithoutID { export interface IndexingProgressUpdate { progress: number; desc: string; + shouldClearIndexes?: boolean; status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled"; } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 984704aa2..fdcab2bfe 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,6 +1,7 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js"; @@ -12,6 +13,7 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; +import * as fs from "fs/promises"; export class PauseToken { constructor(private _paused: boolean) {} @@ -26,6 +28,17 @@ export class PauseToken { } export class CodebaseIndexer { + // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, + // e.g. a `SQLITE_BUSY` error. + errorsRegexesToClearIndexesOn = [ + /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/, + /SQLITE_CONSTRAINT/, + /SQLITE_ERROR/, + /SQLITE_CORRUPT/, + /SQLITE_IOERR/, + /SQLITE_FULL/, + ]; + constructor( private readonly configHandler: ConfigHandler, protected readonly ide: IDE, @@ -33,6 +46,23 @@ export class CodebaseIndexer { private readonly continueServerClient: IContinueServerClient, ) {} + async clearIndexes() { + const sqliteFilepath = getIndexSqlitePath(); + const lanceDbFolder = getLanceDbPath(); + + try { + await fs.unlink(sqliteFilepath); + } catch (error) { + console.error(`Error deleting ${sqliteFilepath} folder: ${error}`); + } + + try { + await fs.rm(lanceDbFolder, { recursive: true, force: true }); + } catch (error) { + console.error(`Error deleting ${lanceDbFolder}: ${error}`); + } + } + protected async getIndexesToBuild(): Promise { const config = await this.configHandler.loadConfig(); const pathSep = await this.ide.pathSep(); @@ -203,7 +233,6 @@ export class CodebaseIndexer { yield this.handleErrorAndGetProgressUpdate(err); return; } - completedDirs += 1; } yield { progress: 100, @@ -227,20 +256,25 @@ export class CodebaseIndexer { } private errorToProgressUpdate(err: Error): IndexingProgressUpdate { - const errorRegex = - /Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/; - const match = err.message.match(errorRegex); - let errMsg: string; - if (match) { - const [_, valuesLength, expectedLength] = match; - errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`; - } else { - errMsg = `${err}`; + let errMsg: string = `${err}`; + let shouldClearIndexes = false; + + // Check if any of the error regexes match + for (const regexStr of this.errorsRegexesToClearIndexesOn) { + const regex = new RegExp(regexStr); + const match = err.message.match(regex); + + if (match !== null) { + shouldClearIndexes = true; + break; + } } + return { progress: 0, desc: errMsg, status: "failed", + shouldClearIndexes, }; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 6d96ec685..fb3f7c684 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -130,7 +130,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: string; promptTokens: number; generatedTokens: number }[], ]; "index/setPaused": [boolean, void]; - "index/forceReIndex": [undefined | string, void]; + "index/forceReIndex": [ + undefined | { dir?: string; shouldClearIndexes?: boolean }, + void, + ]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8a3b9674..48488e486 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -130,6 +130,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index d63b92e1a..563c0d068 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -293,7 +293,7 @@ export class VsCodeExtension { currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] ) { // Trigger refresh of index only in this directory - this.core.invoke("index/forceReIndex", dir); + this.core.invoke("index/forceReIndex", { dir }); } } diff --git a/gui/package-lock.json b/gui/package-lock.json index 23ff1c5ac..3e67abbcc 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -123,6 +123,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx index 6cb4dd18f..cf32d52c2 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.tsx @@ -36,7 +36,7 @@ function ConfirmationDialog(props: ConfirmationDialogProps) { return (

{props.title ?? "Confirmation"}

-

{props.text}

+

{props.text}

{!!props.hideCancelButton || ( diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index 6fcb38e48..530fbaf33 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -2,13 +2,18 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useContext, useEffect, useState } from "react"; import ReactDOM from "react-dom"; -import { useSelector } from "react-redux"; +import { useSelector, useDispatch } from "react-redux"; import styled from "styled-components"; import { StyledTooltip, lightGray, vscForeground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { RootState } from "../../redux/store"; import { getFontSize, isJetBrains } from "../../util"; import StatusDot from "./StatusDot"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; const STATUS_COLORS = { DISABLED: lightGray, // light gray @@ -69,16 +74,35 @@ interface ProgressBarProps { const IndexingProgressBar = ({ indexingState: indexingStateProp, }: ProgressBarProps) => { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const [paused, setPaused] = useState(undefined); + const [hovered, setHovered] = useState(false); + + const embeddingsProvider = useSelector( + (state: RootState) => state.state.config.embeddingsProvider, + ); + // If sidebar is opened before extension initiates, define a default indexingState const defaultIndexingState: IndexingProgressUpdate = { status: "loading", progress: 0, desc: "", }; + const indexingState = indexingStateProp || defaultIndexingState; + const fillPercentage = Math.min( + 100, + Math.max(0, indexingState.progress * 100), + ); + + const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); + // If sidebar is opened after extension initializes, retrieve saved states. let initialized = false; + useEffect(() => { if (!initialized) { // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization @@ -87,58 +111,78 @@ const IndexingProgressBar = ({ } }, []); - const fillPercentage = Math.min( - 100, - Math.max(0, indexingState.progress * 100), - ); - - const ideMessenger = useContext(IdeMessengerContext); - - const embeddingsProvider = useSelector( - (state: RootState) => state.state.config.embeddingsProvider, - ); - - const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); - - const [paused, setPaused] = useState(undefined); - const [hovered, setHovered] = useState(false); - useEffect(() => { if (paused === undefined) return; ideMessenger.post("index/setPaused", paused); }, [paused]); + function onClick() { + switch (indexingState.status) { + case "failed": + if (indexingState.shouldClearIndexes) { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + { + ideMessenger.post("index/forceReIndex", { + shouldClearIndexes: true, + }); + }} + />, + ), + ); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + + break; + case "indexing": + case "paused": + if (indexingState.progress < 1 && indexingState.progress >= 0) { + setPaused((prev) => !prev); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + + break; + default: + ideMessenger.post("index/forceReIndex", undefined); + break; + } + } + function getIndexingErrMsg(msg: string): string { if ( isJetBrains() && embeddingsProvider === TransformersJsEmbeddingsProvider.model ) { - return "The 'transformers.js' embeddingsProvider is currently unsupported in JetBrains. To enable codebase indexing, you can use any of the other providers described in the docs: https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers"; + return ( + "The 'transformers.js' embeddingsProvider is currently unsupported in JetBrains. " + + "To enable codebase indexing, you can use any of the other providers described " + + "in the docs: https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers" + ); } + return msg; } return ( -
{ - if ( - indexingState.status !== "failed" && - indexingState.progress < 1 && - indexingState.progress >= 0 - ) { - setPaused((prev) => !prev); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - }} - className="cursor-pointer" - > +
{indexingState.status === "failed" ? (
Indexing error - click to retry - {/* {getIndexingErrMsg(indexingState.desc)} */}
{tooltipPortalDiv && ReactDOM.createPortal( From e8fa54d757c289bd6032ac0762ab3d51c2649edb Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 18:10:16 -0700 Subject: [PATCH 014/186] update docs --- docs/docs/troubleshooting.md | 8 +++++++- extensions/vscode/package.json | 11 ++++++----- extensions/vscode/src/commands.ts | 6 +++--- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index f330345a7..908b0ee88 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -49,7 +49,7 @@ On JetBrains, the "pre-release" happens through their Early Access Program (EAP) 1. Open JetBrains settings (cmd/ctrl+,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." -4. Add "https://plugins.jetbrains.com/plugins/eap/list" to the list +4. Add "" to the list 5. You'll now always be able to download the latest EAP version from the marketplace ## Download an Older Version @@ -108,6 +108,12 @@ By default the Continue window is on the left side of VS Code, but it can be dra If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. +### Indexing issues + +If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. + +This can be accomplished using the following command: `Continue: Rebuild codebase index`. + ## Still having trouble? Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out. diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d6006bcc..b5c768a5f 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -252,6 +252,12 @@ "title": "Codebase Force Re-Index", "group": "Continue" }, + { + "command": "continue.rebuildCodebaseIndex", + "category": "Continue", + "title": "Rebuild codebase index", + "group": "Continue" + }, { "command": "continue.docsIndex", "category": "Continue", @@ -276,11 +282,6 @@ "mac": "cmd+shift+l", "key": "ctrl+shift+l" }, - { - "command": "continue.toggleAuxiliaryBar", - "mac": "alt+cmd+l", - "key": "alt+ctrl+l" - }, { "command": "continue.acceptDiff", "mac": "shift+cmd+enter", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b2ec0dea7..4226b1328 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -284,12 +284,12 @@ const commandsMap: ( streamInlineEdit("docstring", prompt, false, range); }, - "continue.toggleAuxiliaryBar": () => { - vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); - }, "continue.codebaseForceReIndex": async () => { core.invoke("index/forceReIndex", undefined); }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, "continue.docsIndex": async () => { core.invoke("context/indexDocs", { reIndex: false }); }, From cb41e49a978c43d7f6d353384c560c0e64388e7a Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 12 Aug 2024 18:23:48 -0700 Subject: [PATCH 015/186] chore: add telemetry to index rebuild --- gui/src/components/loaders/IndexingProgressBar.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index 530fbaf33..cfbb63bb3 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -14,6 +14,7 @@ import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiStateSlice"; +import { usePostHog } from "posthog-js/react"; const STATUS_COLORS = { DISABLED: lightGray, // light gray @@ -76,6 +77,7 @@ const IndexingProgressBar = ({ }: ProgressBarProps) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); const [paused, setPaused] = useState(undefined); const [hovered, setHovered] = useState(false); @@ -134,6 +136,7 @@ const IndexingProgressBar = ({ "less reliable for persistent issues." } onConfirm={() => { + posthog.capture("rebuild_index_clicked"); ideMessenger.post("index/forceReIndex", { shouldClearIndexes: true, }); From aca82d2ef36a5bd57119343790875e2acf7819b3 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 13 Aug 2024 12:22:36 +0530 Subject: [PATCH 016/186] fix: MDX compilation issue --- docs/docs/troubleshooting.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 908b0ee88..2ea445f53 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -49,7 +49,7 @@ On JetBrains, the "pre-release" happens through their Early Access Program (EAP) 1. Open JetBrains settings (cmd/ctrl+,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." -4. Add "" to the list +4. Add "[https://plugins.jetbrains.com/plugins/eap/list>](https://plugins.jetbrains.com/plugins/eap/list>)" to the list 5. You'll now always be able to download the latest EAP version from the marketplace ## Download an Older Version From d38e2ef7c94ce614665feedf6a3048ea0c996967 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 13 Aug 2024 13:11:10 +0530 Subject: [PATCH 017/186] build: add nodemon server relaoding for sidebar changes --- docs/package-lock.json | 91 +++++++++++++++++++++++++++++++++++++++++- docs/package.json | 7 ++-- 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/docs/package-lock.json b/docs/package-lock.json index 68e4cd8fa..7387674fb 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -19,7 +19,8 @@ "react-dom": "^18.2.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.2.1" + "@docusaurus/module-type-aliases": "^3.2.1", + "nodemon": "^3.1.4" }, "engines": { "node": ">=20.11.0" @@ -7534,6 +7535,12 @@ "node": ">= 4" } }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true + }, "node_modules/image-size": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.1.1.tgz", @@ -10569,6 +10576,55 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==" }, + "node_modules/nodemon": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", + "dev": true, + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/nodemon/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -11739,6 +11795,12 @@ "node": ">= 0.10" } }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true + }, "node_modules/punycode": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", @@ -13057,6 +13119,18 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/sirv": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.4.tgz", @@ -13628,6 +13702,15 @@ "node": ">=6" } }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -13714,6 +13797,12 @@ "node": ">=14.17" } }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true + }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", diff --git a/docs/package.json b/docs/package.json index d37e79266..09d7b71ea 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "docusaurus start", + "start": "nodemon --watch sidebars.js --exec 'docusaurus start'", "build": "docusaurus build", "build:netlify": "docusaurus build --out-dir build/docs", "swizzle": "docusaurus swizzle", @@ -27,7 +27,8 @@ "react-dom": "^18.2.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.2.1" + "@docusaurus/module-type-aliases": "^3.2.1", + "nodemon": "^3.1.4" }, "browserslist": { "production": [ @@ -45,4 +46,4 @@ "engines": { "node": ">=20.11.0" } -} +} \ No newline at end of file From 88c2c061aad15ac5f52d909d30b5684668ad6c0b Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 13 Aug 2024 13:28:30 +0530 Subject: [PATCH 018/186] docs: merge customization overview into setup overview --- docs/docs/setup/overview.md | 55 ++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/docs/docs/setup/overview.md b/docs/docs/setup/overview.md index d8c1bc8dc..23bae96cd 100644 --- a/docs/docs/setup/overview.md +++ b/docs/docs/setup/overview.md @@ -1,13 +1,54 @@ +--- +title: Overview +description: Get started with Continue and tailor it to your needs +keywords: [setup, customization, models, configuration, LLMs] +--- + # Overview -Continue gives you choice over what [Large Language Models (LLMs)](https://www.youtube.com/watch?v=zjkBMFhNj_g) you use. You can use it with commercial models like Claude 3 Opus via the Anthropic API, open-source models like Llama 3 running on your laptop with Ollama, and everything in between. +Continue is a flexible AI coding assistant that allows you to choose and customize your Large Language Models (LLMs). This guide will help you get started and make Continue work best for you. -When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API keys. Once you're ready to use your own API keys or different models / providers, you can add them to the `config.json`. +## Quick Start -You will need to decide which models and providers you use for [chat](select-model.md#chat), [autocomplete](select-model.md#autocomplete), and [embeddings](select-model.md#embeddings). +1. When you first install Continue, you can use it immediately with our free proxy server. +2. As you get familiar with Continue, you can set up your own API keys and customize your experience. -Learn more: +## Choosing Your Models -- [Configuration](configuration.md) -- [Model Providers](model-providers.md) -- [Select models](select-model.md) +Continue works with a variety of LLMs: + +- Commercial models (e.g., Claude 3 Opus via Anthropic API) +- Open-source models (e.g., Llama 3 running locally with Ollama) +- And many options in between + +You'll need to select models for three main functions: + +- [Chat](select-model.md#chat) +- [Autocomplete](select-model.md#autocomplete) +- [Embeddings](select-model.md#embeddings) + +## Customization Options + +Continue offers deep customization through `config.json` and `config.ts` files. These are located in: + +- MacOS: `~/.continue/` +- Windows: `%userprofile%\.continue` + +You can customize: + +1. [Basic Configuration](configuration.md) +2. [Model Providers](model-providers.md) +3. [Model Selection](select-model.md) +4. [Context Providers](../customization/context-providers.md) +5. [Slash Commands](../customization/slash-commands.md) +6. [Advanced Options](../reference/config.mdx) + +## Sharing Your Configuration + +To share your Continue setup with a team: + +1. Create a `.continuerc.json` file in your project's root directory. +2. Use the same JSON Schema as `config.json`. +3. This file will automatically apply on top of the local `config.json`. + +Get started with Continue today and shape it to fit your coding workflow perfectly! From 9431a0d5eaf6c110f9cda4eef52203f6db15f89a Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 13 Aug 2024 13:28:42 +0530 Subject: [PATCH 019/186] docs: remove duplicate heading --- docs/docs/features/quick-actions.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/docs/features/quick-actions.md b/docs/docs/features/quick-actions.md index 7c6ce8887..a59f8e960 100644 --- a/docs/docs/features/quick-actions.md +++ b/docs/docs/features/quick-actions.md @@ -5,8 +5,6 @@ keywords: [experimental, automate, configuration] toc_max_heading_level: 5 --- -## Quick Actions (experimental, VS Code only) - Quick Actions streamline your development workflow by providing a tool to quickly select an entire class or function to perform a quick edit on. Configure custom actions to execute complex operations with a single click. ![Quick actions example](/img/quick-actions-demo.gif) From eb12a6115e45df07564ea4f6281691153e9a4997 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 13 Aug 2024 13:30:31 +0530 Subject: [PATCH 020/186] docs: merge customization into features --- docs/sidebars.js | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/docs/sidebars.js b/docs/sidebars.js index 84493e2bd..085560a4d 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -31,25 +31,24 @@ const sidebars = { }, { type: "category", - label: "🎨 Customization", - collapsible: true, - collapsed: true, - items: [ - "customization/overview", - "customization/context-providers", - "customization/slash-commands", - ], - }, - { - type: "category", - label: "🪄 Features", + label: "⭐ Features", collapsible: true, collapsed: true, items: [ "features/codebase-embeddings", "features/tab-autocomplete", - "features/prompt-files", - "features/quick-actions", + "customization/context-providers", + "customization/slash-commands", + { + type: "doc", + id: "features/prompt-files", + label: "Prompt Files (experimental)", + }, + { + type: "doc", + id: "features/quick-actions", + label: "Quick Actions (experimental)", + }, ], }, { From 3692aee5335a07472852e385c331530cfaccdf17 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 Aug 2024 09:50:58 -0700 Subject: [PATCH 021/186] chore: remove unnecessary prefixes --- extensions/vscode/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index b5c768a5f..ed3fbfaa2 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -174,7 +174,7 @@ { "command": "continue.debugTerminal", "category": "Continue", - "title": "Continue: Debug Terminal", + "title": "Debug Terminal", "group": "Continue" }, { @@ -199,7 +199,7 @@ { "command": "continue.selectFilesAsContext", "category": "Continue", - "title": "Continue: Select Files as Context", + "title": "Select Files as Context", "group": "Continue" }, { From c92335b3b2269281fe4995c05d95d5e9187b9459 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 10:06:28 -0700 Subject: [PATCH 022/186] mistral apiBase add "/" --- core/llm/llms/Mistral.ts | 4 ++++ extensions/intellij/gradle.properties | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index 95208bb8c..992e650c7 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -20,6 +20,10 @@ class Mistral extends OpenAI { ) { this.apiBase = options.apiBase ?? "https://codestral.mistral.ai/v1/"; } + + if (!this.apiBase?.endsWith("/")) { + this.apiBase += "/"; + } } private static modelConversion: { [key: string]: string } = { diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index cb39f4eee..c61a7c46e 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.59 +pluginVersion = 0.0.60 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From 3844208a3b9b3daaff085daad8ab933f27fcb5f3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 Aug 2024 10:27:28 -0700 Subject: [PATCH 023/186] feat: improve chunking desc on large projects --- core/indexing/chunk/ChunkCodebaseIndex.ts | 67 +++++++++++++++++------ 1 file changed, 49 insertions(+), 18 deletions(-) diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 0e866b3bf..4fbc10266 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -2,7 +2,6 @@ import { RunResult } from "sqlite3"; import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; import { getBasename } from "../../util/index.js"; -import { getLanguageForFile } from "../../util/treeSitter.js"; import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js"; import { IndexResultType, @@ -12,6 +11,7 @@ import { type CodebaseIndex, } from "../types.js"; import { chunkDocument, shouldChunk } from "./chunk.js"; +import * as path from "path"; export class ChunkCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; @@ -61,8 +61,11 @@ export class ChunkCodebaseIndex implements CodebaseIndex { let accumulatedProgress = 0; if (results.compute.length > 0) { + const folderPath = results.compute[0].path; + const folderName = path.basename(path.dirname(folderPath)); + yield { - desc: `Chunking ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`, + desc: `Chunking files in ${folderName}`, status: "indexing", progress: accumulatedProgress, }; @@ -171,11 +174,17 @@ export class ChunkCodebaseIndex implements CodebaseIndex { } private async computeChunks(paths: PathAndCacheKey[]): Promise { - const chunkLists = await Promise.all(paths.map(p => this.packToChunks(p))); + const chunkLists = await Promise.all( + paths.map((p) => this.packToChunks(p)), + ); return chunkLists.flat(); } - private async insertChunks(db: DatabaseConnection, tagString: string, chunks: Chunk[]) { + private async insertChunks( + db: DatabaseConnection, + tagString: string, + chunks: Chunk[], + ) { await new Promise((resolve, reject) => { db.db.serialize(() => { db.db.exec("BEGIN", (err: Error | null) => { @@ -183,23 +192,45 @@ export class ChunkCodebaseIndex implements CodebaseIndex { reject(new Error("error creating transaction", { cause: err })); } }); - const chunksSQL = "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; - chunks.map(c => { - db.db.run(chunksSQL, [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], (result: RunResult, err: Error) => { - if (err) { - reject(new Error("error inserting into chunks table", { cause: err })); - } - }); - const chunkTagsSQL = "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; - db.db.run(chunkTagsSQL, [ tagString ], (result: RunResult, err: Error) => { - if (err) { - reject(new Error("error inserting into chunk_tags table", { cause: err })); - } - }); + const chunksSQL = + "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; + chunks.map((c) => { + db.db.run( + chunksSQL, + [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], + (result: RunResult, err: Error) => { + if (err) { + reject( + new Error("error inserting into chunks table", { + cause: err, + }), + ); + } + }, + ); + const chunkTagsSQL = + "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; + db.db.run( + chunkTagsSQL, + [tagString], + (result: RunResult, err: Error) => { + if (err) { + reject( + new Error("error inserting into chunk_tags table", { + cause: err, + }), + ); + } + }, + ); }); db.db.exec("COMMIT", (err: Error | null) => { if (err) { - reject(new Error("error while committing insert chunks transaction", { cause: err })); + reject( + new Error("error while committing insert chunks transaction", { + cause: err, + }), + ); } else { resolve(); } From 333ba5d6da53576a45a9d5b16163c710aa2ec7cb Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 Aug 2024 10:30:54 -0700 Subject: [PATCH 024/186] Update ChunkCodebaseIndex.ts --- core/indexing/chunk/ChunkCodebaseIndex.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 4fbc10266..498e5144e 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -61,8 +61,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex { let accumulatedProgress = 0; if (results.compute.length > 0) { - const folderPath = results.compute[0].path; - const folderName = path.basename(path.dirname(folderPath)); + const filepath = results.compute[0].path; + const folderName = path.basename(path.dirname(filepath)); yield { desc: `Chunking files in ${folderName}`, From 7c738e887486211d86b2e71b8d47a0e14d863172 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 13 Aug 2024 10:47:10 -0700 Subject: [PATCH 025/186] Update azure.md --- docs/docs/reference/Model Providers/azure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference/Model Providers/azure.md b/docs/docs/reference/Model Providers/azure.md index 1f1518c92..7142b7718 100644 --- a/docs/docs/reference/Model Providers/azure.md +++ b/docs/docs/reference/Model Providers/azure.md @@ -20,7 +20,7 @@ You can configure Azure OpenAI service through the UI, or you can configure it m "apiBase": "", "engine": "", "apiVersion": "", - "apiType": "azure", + "apiType": "openai", "apiKey": "" }] ``` From a9284abdbdfc02d545bb928db804c400c15d3812 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 10:56:07 -0700 Subject: [PATCH 026/186] update package.json version --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index ed3fbfaa2..389c6bac5 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.196", + "version": "0.9.197", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 88b56763a3fe831230d4d172c97ff95a1f3d3ba8 Mon Sep 17 00:00:00 2001 From: mkummer225 <7843299+mkummer225@users.noreply.github.com> Date: Tue, 13 Aug 2024 16:46:37 -0600 Subject: [PATCH 027/186] initial TTS functionality --- core/config/profile/doLoadConfig.ts | 4 ++ core/core.ts | 6 ++ core/index.d.ts | 5 ++ core/util/tts.ts | 108 ++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 core/util/tts.ts diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 16f72d40e..7537fedd6 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,6 +10,7 @@ import { import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js"; import { Telemetry } from "../../util/posthog.js"; +import { TTS } from "../../util/tts.js"; import { loadFullConfigNode } from "../load.js"; export default async function doLoadConfig( @@ -51,6 +52,9 @@ export default async function doLoadConfig( ideInfo.extensionVersion, ); + // TODO: pass config to pre-load non-system TTS models + await TTS.setup(); + if (newConfig.analytics) { await TeamAnalytics.setup( newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all diff --git a/core/core.ts b/core/core.ts index 340008cdb..bba55631f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -26,6 +26,7 @@ import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { TTS } from "./util/tts"; import { streamDiffLines } from "./util/verticalEdit"; export class Core { @@ -383,6 +384,11 @@ export class Core { next = await gen.next(); } + const config = await configHandler.loadConfig(); + if(config.experimental?.readResponseTTS && "completion" in next.value) { + TTS.read(next.value?.completion); + } + return { done: true, content: next.value }; } diff --git a/core/index.d.ts b/core/index.d.ts index 3fcb08fa1..a23068516 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -887,6 +887,11 @@ interface ExperimentalConfig { * function and class declarations. */ quickActions?: QuickActionConfig[]; + + /** + * Automatically read LLM chat responses aloud using system TTS models + */ + readResponseTTS?: boolean; } interface AnalyticsConfig { diff --git a/core/util/tts.ts b/core/util/tts.ts new file mode 100644 index 000000000..77e4b1b12 --- /dev/null +++ b/core/util/tts.ts @@ -0,0 +1,108 @@ +import os from "node:os"; +import { exec, ChildProcess } from "child_process"; + +// The amount of time before a process is declared +// a zombie after executing .kill() +const ttsKillTimeout: number = 5000; + +/** + * Removes code blocks from a message. + * + * Return modified message text. + */ +function removeCodeBlocks(msgText: string): string { + const codeBlockRegex = /```[\s\S]*?```/g; + + // Remove code blocks from the message text + const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); + + return textWithoutCodeBlocks.trim(); +} + +/** + * Cleans a message text to safely be used in 'exec' context on host. + * + * Return modified message text. + */ +function sanitizeMessageForTTS(message: string): string { + message = removeCodeBlocks(message); + + // Remove or replace problematic characters + message = message + .replace(/"/g, "") + .replace(/`/g, "") + .replace(/\$/g, "") + .replace(/\\/g, "") + .replace(/[&|;()<>]/g, ""); + + message = message.trim().replace(/\s+/g, " "); + + return message; +} + +export class TTS { + static os: string | undefined = undefined; + static handle: ChildProcess | undefined = undefined; + + static async read(message: string) { + message = sanitizeMessageForTTS(message); + + try { + // Kill any active TTS processes + await TTS.kill(); + } catch (e) { + console.warn("Error killing TTS process: ", e); + return; + } + + switch (TTS.os) { + case "darwin": + TTS.handle = exec(`say "${message}"`); + break; + case "win32": + // Replace single quotes on windows + TTS.handle = exec( + `powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${message.replace( + /'/g, + "''", + )}')"`, + ); + break; + case "linux": + TTS.handle = exec(`espeak "${message}"`); + break; + default: + console.log( + "Text-to-speech is not supported on this operating system.", + ); + break; + } + } + + static async kill(): Promise { + return new Promise((resolve, reject) => { + // Only kill a TTS process if it's still running + if (TTS.handle && TTS.handle.exitCode === null) { + // Use a timeout in case of zombie processes + let killTimeout: NodeJS.Timeout = setTimeout(() => { + reject(`Unable to kill TTS process: ${TTS.handle?.pid}`); + }, ttsKillTimeout); + + // Resolve our promise once the program has exited + TTS.handle.once("exit", () => { + clearTimeout(killTimeout); + TTS.handle = undefined; + resolve(); + }); + + TTS.handle.kill(); + } else { + resolve(); + } + }); + } + + static async setup() { + TTS.os = os.platform(); + } +} From d8dbfe73c4734f3b26b62c5935233c58e27b633b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 16:16:07 -0700 Subject: [PATCH 028/186] update llamafile docs --- docs/docs/reference/Model Providers/llamafile.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/docs/reference/Model Providers/llamafile.md b/docs/docs/reference/Model Providers/llamafile.md index 04d12aeff..cc969f8d8 100644 --- a/docs/docs/reference/Model Providers/llamafile.md +++ b/docs/docs/reference/Model Providers/llamafile.md @@ -14,6 +14,4 @@ A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contai } ``` -Optionally, you can set the `llamafile_command` property, which will be run to start the llamafile if it isn't already running on port 8080. Be sure to use an absolute path to the llamafile binary. For example: `/Users/yourusername/mistral-7b-instruct-v0.1-Q4_K_M-server.llamafile`. - [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Llamafile.ts) From ae3325d0de9080c75c2cef6cc42d8ff7f76f09b2 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 17:19:27 -0700 Subject: [PATCH 029/186] allow user overriden context length for ollama provider --- core/llm/llms/Ollama.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fe5ab7f55..fcce902c8 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -50,7 +50,8 @@ class Ollama extends BaseLLM { let value = parts[2]; switch (key) { case "num_ctx": - this.contextLength = Number.parseInt(value); + this.contextLength = + options.contextLength ?? Number.parseInt(value); break; case "stop": if (!this.completionOptions.stop) { From a0956e614ed40b44956b394aef20d44d283cd82d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 17:20:42 -0700 Subject: [PATCH 030/186] fix preview ci tests --- .github/workflows/preview.yaml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 6fca2c0ad..aea470286 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -97,6 +97,13 @@ jobs: cd core npm ci + - name: Run core tests + run: | + cd core + npm run test + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + # 2.5. Pre package - name: Set var for environment info shell: pwsh @@ -107,14 +114,6 @@ jobs: cd extensions/vscode npm run prepackage -- --target ${{ env.target }} - # 2.75 Run core tests - - name: Run core tests - run: | - cd core - npm run test - env: - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js) - name: Re-install esbuild run: | From 296ee4f9c53e7dd3e29bfb1af1442a1a56984125 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 17:24:18 -0700 Subject: [PATCH 031/186] update docs for position of log files --- core/autocomplete/README.md | 2 +- docs/docs/features/tab-autocomplete.md | 2 +- docs/docs/troubleshooting.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 4e25c9fef..2c68be1bf 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -131,7 +131,7 @@ Follow these steps to ensure that everything is set up correctly: 3. Run `ollama run starcoder:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. 5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. -6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/core.log in JetBrains). +6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. ### Completions are slow diff --git a/docs/docs/features/tab-autocomplete.md b/docs/docs/features/tab-autocomplete.md index 1aef6cb6b..008358776 100644 --- a/docs/docs/features/tab-autocomplete.md +++ b/docs/docs/features/tab-autocomplete.md @@ -136,7 +136,7 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/core.log in JetBrains). +5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 2ea445f53..ff952ddc0 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -32,7 +32,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c ### JetBrains -Open `~/.continue/core.log`. The most recent logs are found at the bottom of the file. +Open `~/.continue/logs/core.log`. The most recent logs are found at the bottom of the file. ## Download the latest pre-release From 0bce1dc9c2e94e12e484fe8457dde5d6bc1d8f2f Mon Sep 17 00:00:00 2001 From: Maxx Rodriguez Date: Tue, 13 Aug 2024 17:24:52 -0700 Subject: [PATCH 032/186] - added copyTokenizers to util - added workerpools to be copied over from core - import and execute copyTokenizers in prepackage-cross-plat --- .../vscode/scripts/prepackage-cross-platform.js | 4 ++++ extensions/vscode/scripts/utils.js | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 59089dd62..018ea70c2 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -24,6 +24,7 @@ const { copySqliteBinary, installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, + copyTokenizers, } = require("./utils"); // Clear folders that will be packaged to ensure clean slate @@ -104,6 +105,9 @@ async function package(target, os, arch, exe) { // *** onnxruntime-node *** await copyOnnxRuntimeFromNodeModules(target); + // copy llama tokenizers to out + copyTokenizers(); + // *** Install @lancedb binary *** const lancePackageToInstall = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index b0d7def7d..6a129bc61 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -39,6 +39,20 @@ function copyConfigSchema() { fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); } +function copyTokenizers() { + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizerWorkerPool.mjs"), + path.join(__dirname, "../out/llamaTokenizerWorkerPool.mjs"), + ); + console.log("[info] Copied llamaTokenizerWorkerPool"); + + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizer.mjs"), + path.join(__dirname, "../out/llamaTokenizer.mjs"), + ); + console.log("[info] Copied llamaTokenizer"); +} + function installNodeModules() { // Make sure we are in the right directory if (!process.cwd().endsWith("vscode")) { @@ -242,6 +256,7 @@ async function copyNodeModules() { "@esbuild", "@lancedb", "@vscode/ripgrep", + "workerpool" ]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -497,4 +512,5 @@ module.exports = { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, downloadRipgrepBinary, + copyTokenizers }; From 3c4f4dea315ea8831e40185e55840a63ea0f8cec Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 18:13:36 -0700 Subject: [PATCH 033/186] extract functions responsible for errors --- core/core.ts | 1 + core/index.d.ts | 1 + core/indexing/CodebaseIndexer.ts | 5 ++++- core/util/extractMinimalStackTraceInfo.ts | 16 ++++++++++++++++ extensions/vscode/src/webviewProtocol.ts | 2 ++ 5 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 core/util/extractMinimalStackTraceInfo.ts diff --git a/core/core.ts b/core/core.ts index 340008cdb..d3ff7bf36 100644 --- a/core/core.ts +++ b/core/core.ts @@ -695,6 +695,7 @@ export class Core { "indexing_error", { error: update.desc, + stack: update.debugInfo, }, false, ); diff --git a/core/index.d.ts b/core/index.d.ts index 3fcb08fa1..8ce83c6f7 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -39,6 +39,7 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled"; + debugInfo?: string; } export type PromptTemplate = diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 33108c40e..293129627 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,6 +1,8 @@ +import * as fs from "fs/promises"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; @@ -13,7 +15,6 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; -import * as fs from "fs/promises"; export class PauseToken { constructor(private _paused: boolean) {} @@ -259,6 +260,7 @@ export class CodebaseIndexer { progress: 0, desc: `Indexing failed: ${err}`, status: "failed", + debugInfo: extractMinimalStackTraceInfo((err as any)?.stack), }; } @@ -282,6 +284,7 @@ export class CodebaseIndexer { desc: errMsg, status: "failed", shouldClearIndexes, + debugInfo: extractMinimalStackTraceInfo(err.stack), }; } diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts new file mode 100644 index 000000000..a2fa226de --- /dev/null +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -0,0 +1,16 @@ +/** + * It's helpful to know what functions errors occur in, but absolute + * file paths are sensitive information, so we want to remove them. + * @param stack The stack trace to extract minimal information from. + * @returns A string containing the minimal stack trace information. + */ +export function extractMinimalStackTraceInfo(stack: unknown): string { + if (typeof stack !== "string") return ""; + const lines = stack.split("\n"); + const minimalLines = lines.filter((line) => { + return line.trimStart().startsWith("at ") && !line.includes("node_modules"); + }); + return minimalLines + .map((line) => line.trimStart().replace("at ", "").split(" (").slice(0, 1)) + .join(", "); +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index f515995b8..eed3d15a0 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,4 +1,5 @@ import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; +import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Message } from "core/util/messenger"; import { Telemetry } from "core/util/posthog"; import fs from "node:fs"; @@ -159,6 +160,7 @@ export class VsCodeWebviewProtocol { messageType: msg.messageType, errorMsg: message.split("\n\n")[0], + stack: extractMinimalStackTraceInfo(e.stack), }, false, ); From 1e5bddf8087ce579fcd7d66fc61a991c545b914c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 20:49:30 -0700 Subject: [PATCH 034/186] log stack for core_messenger_error --- core/core.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/core.ts b/core/core.ts index d3ff7bf36..a77c7c8bb 100644 --- a/core/core.ts +++ b/core/core.ts @@ -173,6 +173,7 @@ export class Core { console.error(err); Telemetry.capture("core_messenger_error", { message: err.message, + stack: err.stack, }); this.messenger.request("errorPopup", { message: err.message }); }); From fe586f8a7ad717d929c4c3fcc07e183002a09de3 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Aug 2024 21:47:26 -0700 Subject: [PATCH 035/186] crawling tests for common docs sites --- core/test/indexing/crawl.skip.ts | 51 --------------- core/test/indexing/crawl.test.ts | 103 +++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 51 deletions(-) delete mode 100644 core/test/indexing/crawl.skip.ts create mode 100644 core/test/indexing/crawl.test.ts diff --git a/core/test/indexing/crawl.skip.ts b/core/test/indexing/crawl.skip.ts deleted file mode 100644 index 2f4b18817..000000000 --- a/core/test/indexing/crawl.skip.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { crawlPage, PageData } from "../../indexing/docs/crawl"; - -describe("crawlPage - GitHub repository", () => { - const repoUrl = new URL( - "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling", - ); - const maxDepth = 3; - let crawlResults: PageData[]; - - beforeAll(async () => { - crawlResults = []; - for await (const page of crawlPage(repoUrl, maxDepth)) { - crawlResults.push(page); - } - }, 30000); - - test("finds expected markdown files", async () => { - expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( - true, - ); - - expect( - crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), - ).toBe(true); - }); - - test("html includes the correct content", async () => { - const doc = crawlResults.find((page) => - page.path.endsWith("docs-depth-1.md"), - ); - - expect(doc?.html.includes("Test body")).toBe(true); - expect(doc?.html.includes("Test H2 Header")).toBe(true); - }); - - // This test is currently failing, `maxDepth` does not appear to be followed right now - test.todo( - "ignores files past the max depth", - // , () => { - // expect( - // crawlResults.some((page) => page.path.includes("docs-depth-3")), - // ).toBe(false); - // } - ); - - test("ignores non-markdown files, e.g. `test.js` at the root", async () => { - expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( - false, - ); - }); -}); diff --git a/core/test/indexing/crawl.test.ts b/core/test/indexing/crawl.test.ts new file mode 100644 index 000000000..d1a5f233e --- /dev/null +++ b/core/test/indexing/crawl.test.ts @@ -0,0 +1,103 @@ +import { crawlPage, PageData } from "../../indexing/docs/crawl"; + +describe("crawlPage - GitHub repository", () => { + const repoUrl = new URL( + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling", + ); + const maxDepth = 3; + let crawlResults: PageData[]; + + beforeAll(async () => { + crawlResults = []; + for await (const page of crawlPage(repoUrl, maxDepth)) { + crawlResults.push(page); + } + }, 30000); + + test("finds expected markdown files", async () => { + expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( + true, + ); + + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }); + + test("html includes the correct content", async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); + + expect(doc?.html.includes("Test body")).toBe(true); + expect(doc?.html.includes("Test H2 Header")).toBe(true); + }); + + // This test is currently failing, `maxDepth` does not appear to be followed right now + test.todo( + "ignores files past the max depth", + // , () => { + // expect( + // crawlResults.some((page) => page.path.includes("docs-depth-3")), + // ).toBe(false); + // } + ); + + test("ignores non-markdown files, e.g. `test.js` at the root", async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }); +}); + +async function testSite(url: string, expectedPaths: string[]) { + test(`crawlPage - ${url}`, async () => { + const crawlResults: PageData[] = []; + for await (const page of crawlPage(new URL(url))) { + crawlResults.push(page); + } + + console.log(crawlResults.map((page) => page.path)); + + // Check if all expected paths are found + for (const expectedPath of expectedPaths) { + expect( + crawlResults.some((page) => page.path.endsWith(expectedPath)), + ).toBe(true); + } + }); +} + +const SITES: { [rootUrl: string]: string[] } = { + "https://docs.continue.dev": [ + "intro", + "quickstart", + "features/tab-autocomplete", + "reference/Model%20Providers/mistral", + ], + // Failing + // "https://docs.nestjs.com/": ["first-steps"], + // Taking too much time + // "https://go.dev/doc/": ["install", "tutorial/getting-started", "comment"], + // Taking too much time + // "https://clickhouse.com/docs": [ + // "intro", + // "getting-started/quick-start", + // "migrations/bigquery/migrating-to-clickhouse-cloud", + // ], + // Taking too much time + // "https://www.tensorflow.org/api_docs": ["python/tf/Variable"], + // "https://www.rust-lang.org/learn": [] + // Taking too long + // "https://docs.anthropic.com/en/docs": [ + // "welcome", + // "quickstart", + // "build-with-claude/prompt-engineering/prompt-generator", + // ], +}; + +describe.only("crawlPage should return expected subpages for common sites", () => { + for (const [rootUrl, expectedPaths] of Object.entries(SITES)) { + testSite(rootUrl, expectedPaths); + } +}); From cfac639e44ff5ba13960bbed6756047a90ed93f2 Mon Sep 17 00:00:00 2001 From: Vijai Sivakumar Date: Wed, 14 Aug 2024 10:37:50 +0530 Subject: [PATCH 036/186] fix(continue): update context for slash commands Signed-off-by: Vijai Sivakumar --- gui/src/hooks/useChatHandler.ts | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 659438c21..f67cfce65 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -169,12 +169,8 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } // Resolve context providers and construct new history - const [contextItems, selectedCode, content] = await resolveEditorContent( - editorState, - modifiers, - ideMessenger, - ); - dispatch(addContextItems(contextItems)); + const [selectedContextItems, selectedCode, content] = + await resolveEditorContent(editorState, modifiers, ideMessenger); // Automatically use currently open file if (!modifiers.noContext && (history.length === 0 || index === 0)) { @@ -182,15 +178,16 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const currentFilePath = await ideMessenger.ide.getCurrentFile(); if (typeof currentFilePath === "string") { - let currentFileContents = - await ideMessenger.ide.readFile(currentFilePath); + let currentFileContents = await ideMessenger.ide.readFile( + currentFilePath, + ); if (usingFreeTrial) { currentFileContents = currentFileContents .split("\n") .slice(0, 1000) .join("\n"); } - contextItems.unshift({ + 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( currentFilePath, await ideMessenger.ide.getWorkspaceDirs(), @@ -211,7 +208,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }; const historyItem: ChatHistoryItem = { message, - contextItems, + contextItems: selectedContextItems, // : typeof index === "number" // ? history[index].contextItems // : contextItems, @@ -224,7 +221,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { setMessageAtIndex({ message, index: historyIndex, - contextItems, + contextItems: selectedContextItems, }), ); @@ -246,17 +243,26 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { await _streamNormalInput(messages); } else { const [slashCommand, commandInput] = commandAndInput; + let updatedContextItems = []; posthog.capture("step run", { step_name: slashCommand.name, params: {}, }); + + // For edit and comment slash commands, including the selected code in the context from store and for other commands, including the selected context alone + if (slashCommand.name === "edit" || slashCommand.name === "comment") { + updatedContextItems = [...contextItems]; + } else { + updatedContextItems = [...selectedContextItems]; + } + await _streamSlashCommand( messages, slashCommand, commandInput, historyIndex, selectedCode, - contextItems, + updatedContextItems, ); } } catch (e) { From 873a42d461a12220f3408dff701308748541a744 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Wed, 14 Aug 2024 14:54:50 +0530 Subject: [PATCH 037/186] docs: add install section in docs sidebar --- docs/docs/how-to-use-continue.md | 76 +++++++++++++-------- docs/docs/install/jetbrains.md | 110 +++++++++++++++++++++++++++++++ docs/docs/install/vscode.md | 77 ++++++++++++++++++++++ docs/docs/intro.md | 44 ++++++++----- docs/docs/troubleshooting.md | 12 ++-- docs/sidebars.js | 37 +++++++++-- 6 files changed, 303 insertions(+), 53 deletions(-) create mode 100644 docs/docs/install/jetbrains.md create mode 100644 docs/docs/install/vscode.md diff --git a/docs/docs/how-to-use-continue.md b/docs/docs/how-to-use-continue.md index eb6a51fb0..8cbd23216 100644 --- a/docs/docs/how-to-use-continue.md +++ b/docs/docs/how-to-use-continue.md @@ -1,67 +1,85 @@ --- -title: 🧑‍🎓 How to use Continue -description: Using LLMs as you code with Continue +title: How to Use Continue +description: Utilizing LLMs (Large Language Models) as you code with Continue keywords: [how to, edit, refactor, boilerplate, context] --- -# 🧑‍🎓 How to use Continue +Continue is an advanced tool designed to help you integrate the power of Large Language Models (LLMs) seamlessly into your coding environment, providing assistance with understanding code, generating boilerplate, refactoring, and much more. Below are detailed instructions on how you can make the most out of Continue across different integrated development environments (IDEs) like VS Code and JetBrains. -## Easily understand code sections +## Easily Understand Code Sections + +If you ever find yourself puzzled by a piece of code, Continue can help break it down for you. This feature gives you a clear and concise explanation which can significantly speed up the debugging and understanding process. + +- **VS Code**: Press `cmd+L` (MacOS) or `ctrl+L` (Windows) to get insights into the current code section you are working on. +- **JetBrains**: Utilize the same feature with `cmd+J` (MacOS) or `ctrl+J` (Windows). ![understand](/img/understand.gif) -- VS Code: `cmd+L` (MacOS) / `ctrl+L` (Windows) -- JetBrains: `cmd+J` (MacOS) / `ctrl+J` (Windows) +## Tab to Autocomplete Code Suggestions -## Tab to autocomplete code suggestions +Autocomplete can save you time by predicting and inserting code snippets. Continue enhances this feature by using AI to offer smarter autocomplete suggestions tailored to your context. + +- **VS Code**: Simply press `tab` (MacOS) or `tab` (Windows) to autocomplete code suggestions. +- **JetBrains**: Similar functionality is available with the `tab` key on both MacOS and Windows. ![autocomplete](/img/autocomplete.gif) -- VS Code: `tab` (MacOS) / `tab` (Windows) -- JetBrains: `tab` (MacOS) / `tab` (Windows) +## Refactor Functions Where You are Coding -## Refactor functions where you are coding +Refactoring is a crucial part of maintaining and improving your code. With Continue, you can refactor functions right where you are coding, ensuring seamless transitions and minimal interruptions. + +- **VS Code**: Press `cmd+I` (MacOS) or `ctrl+I` (Windows) to refactor in place. +- **JetBrains**: Trigger the same action using `cmd+I` (MacOS) or `ctrl+I` (Windows). ![inline](/img/inline.gif) -- VS Code: `cmd+I` (MacOS) / `ctrl+I` (Windows) -- JetBrains: `cmd+I` (MacOS) / `ctrl+I` (Windows) +## Ask Questions About Your Codebase -## Ask questions about your codebase +Continue allows you to ask questions about your entire codebase, which can be extremely useful for getting quick answers and making informed decisions. + +- **VS Code**: Type `@codebase` followed by your query (works on both MacOS and Windows). +- **JetBrains**: This feature will be available soon. ![codebase](/img/codebase.gif) -- VS Code: `@codebase` (MacOS) / `@codebase` (Windows) -- JetBrains: Support coming soon +## Quickly Use Documentation as Context -## Quickly use documentation as context +Documentation can often be complex and time-consuming to scroll through. Continue can fetch the relevant sections for you, allowing you to use documentation as context efficiently. + +- **VS Code**: Use the `@docs` command (available on both MacOS and Windows). +- **JetBrains**: The same functionality is available using `@docs` on both MacOS and Windows. ![docs](/img/docs.gif) -- VS Code: `@docs` (MacOS) / `@docs` (Windows) -- JetBrains: `@docs` (MacOS) / `@docs` (Windows) +## Kick Off Actions with Slash Commands -## Kick off actions with slash commands +Slash commands in Continue enable you to perform various actions quickly and efficiently without having to leave your coding environment. + +- **VS Code**: Start commands with a `/` (works on both MacOS and Windows) like `/edit`. +- **JetBrains**: Support the use of slash commands by typing `/edit` on MacOS or Windows. ![slash](/img/slash.gif) -- VS Code: `/edit` (MacOS) / `/edit` (Windows) -- JetBrains: `/edit` (MacOS) / `/edit` (Windows) +Learn more about slash commands [here](./customization/slash-commands.md). -Learn more about slash commands [here](./customization/slash-commands.md) +## Add Classes, Files, and More to Context -## Add classes, files, and more to context +Context switching can disrupt your workflow. Continue allows you to add classes, files, and more to your current context, allowing you to see everything you need in one place. + +- **VS Code**: Use the `@files` command (available on both MacOS and Windows) for this purpose. +- **JetBrains**: This feature can also be utilized using `@files` on MacOS and Windows. ![classes](/img/classes.gif) -- VS Code: `@files` (MacOS) / `@files` (Windows) -- JetBrains: `@files` (MacOS) / `@files` (Windows) - Learn more about context providers [here](./customization/context-providers.md). -## Understand terminal errors immediately +## Understand Terminal Errors Immediately + +One of the most frustrating parts of coding is deciphering terminal errors. Continue can help you understand these errors instantly, reducing downtime and confusion. + +- **VS Code**: Press `cmd+shift+R` (MacOS) or `ctrl+shift+R` (Windows) for instant error explanations. +- **JetBrains**: This feature will be supported soon. ![error](/img/error.gif) -- VS Code: `cmd+shift+R` (MacOS) / `ctrl+shift+R` (Windows) -- JetBrains: Support coming soon \ No newline at end of file +By following these extended and detailed instructions, you can significantly improve your coding efficiency and debug processes using Continue. Happy coding! diff --git a/docs/docs/install/jetbrains.md b/docs/docs/install/jetbrains.md new file mode 100644 index 000000000..3ff9ac1fc --- /dev/null +++ b/docs/docs/install/jetbrains.md @@ -0,0 +1,110 @@ +--- +title: Installing Continue in JetBrains IDEs +description: Instructions for installing the Continue extension in JetBrains IDEs +keywords: [install, setup, jetbrains, plugin, continue, intellij, pycharm, webstorm] +--- + +## Prerequisites + +Ensure you have a compatible [JetBrains IDE](https://www.jetbrains.com/products/) installed. Continue is compatible with: + +- IntelliJ IDEA (Ultimate, Community) +- Android Studio +- AppCode +- Aqua +- CLion +- DataGrip +- DataSpell +- GoLand +- PhpStorm +- PyCharm (Professional, Community) +- Rider +- RubyMine +- RustRover +- WebStorm +- Writerside + +## Installation Options + +There are three ways to install the Continue extension in JetBrains IDEs: + +1. Install from JetBrains Marketplace within the IDE +2. Manual Installation from JetBrains Marketplace website +3. Manual Installation using ZIP from GitHub Releases + +Choose the method that best suits your preference and setup. Each option is detailed below. + +### Option 1: Install from JetBrains Marketplace within the IDE + +1. Open your JetBrains IDE. +2. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +3. Navigate to "Plugins" in the left sidebar. +4. Click on the "Marketplace" tab. +5. Search for "Continue" in the search bar. +6. Click the "Install" button next to the Continue plugin. +7. Restart your IDE when prompted to complete the installation. + +### Option 2: Manual Installation from JetBrains Marketplace website + +1. Visit the [Continue plugin page on the JetBrains Marketplace](https://plugins.jetbrains.com/plugin/22707-continue). +2. Click the "Get" button on the page. +3. Select your IDE from the list and click "Download". +4. Open your JetBrains IDE. +5. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +6. Navigate to "Plugins" in the left sidebar. +7. Click the gear icon and select "Install Plugin from Disk...". +8. Navigate to the downloaded plugin file and select it. +9. Restart your IDE when prompted to complete the installation. + +### Option 3: Manual Installation using ZIP from GitHub Releases + +1. Visit the [Continue GitHub releases page](https://github.com/continuedev/continue/releases). +2. Find the latest release and download the JetBrains ZIP file (e.g., `continue-jetbrains-[version].zip`). +3. Open your JetBrains IDE. +4. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +5. Navigate to "Plugins" in the left sidebar. +6. Click the gear icon and select "Install Plugin from Disk...". +7. Navigate to the downloaded ZIP file and select it. +8. Restart your IDE when prompted to complete the installation. + +## Post-Installation Setup + +1. After installation and IDE restart, you'll see the Continue icon in the right toolbar. +2. Click it to open the Continue tool window. + +![jetbrains-quickstart](/img/jetbrains-quickstart.png) + +## Getting Started with Continue + +Now that you've successfully installed Continue, you're ready to enhance your coding experience. Here's a quick summary of what you can do: + +1. **Open the Continue tool window**: Click the Continue icon in the right toolbar to access the extension's features. +2. **Start a conversation**: Use the chat interface to ask questions, get code suggestions, or request explanations. +3. **Explore features**: Familiarize yourself with Continue's features to streamline your workflow. +4. **Customize settings**: Adjust the plugin's settings to suit your preferences and coding style. + +For more detailed information on using Continue, check out our [user guide](../how-to-use-continue.md). + +## Pre-release Version (Optional) + +The Continue plugin for JetBrains IDEs offers a pre-release version through their Early Access Program (EAP) channel. To access the latest EAP version: + +1. Open your JetBrains IDE. +2. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +3. Navigate to "Plugins" in the left sidebar. +4. Click the gear icon at the top of the Plugins page. +5. Select "Manage Plugin Repositories...". +6. In the dialog that opens, add the URL to the list: `https://plugins.jetbrains.com/plugins/eap/list` +7. Click "OK" to save the changes. + +After adding the EAP channel, you'll be able to download the latest pre-release version of Continue from the marketplace. To install or update to the EAP version: + +1. Go back to the Plugins page in Settings/Preferences. +2. Search for "Continue" in the marketplace. +3. You should see the EAP version available. Click "Install" or "Update" to get the latest pre-release version. + +Remember that EAP versions may contain experimental features and could be less stable than the regular releases. + +## Troubleshooting + +If you encounter any issues, please refer to our [troubleshooting guide](../troubleshooting.md) or ask for help in [our Discord community](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/install/vscode.md b/docs/docs/install/vscode.md new file mode 100644 index 000000000..10114d9f1 --- /dev/null +++ b/docs/docs/install/vscode.md @@ -0,0 +1,77 @@ +--- +title: Installing Continue in VS Code +description: Instructions for installing the Continue extension in Visual Studio Code +keywords: [install, setup, vscode, extension, continue, vsix] +--- + +## Prerequisites + +Ensure you have Visual Studio Code installed. If not, download and install it from the [Visual Studio Code download page](https://code.visualstudio.com/download). + +## Installation Options + +There are three ways to install the Continue extension in Visual Studio Code: + +1. Install from VS Code Marketplace (Web) +2. Install from VS Code Extensions Marketplace +3. Manual Installation using VSIX + +Choose the method that best suits your preference and setup. Each option is detailed below. + +### Option 1: Install from VS Code Marketplace (Web) + +1. Visit the [Continue extension page on the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue). +2. Click the `Install` button on the page. +3. This will open VS Code (if it's not already open) and take you to the extension page within VS Code. +4. Click `Install` in VS Code to complete the installation. + +### Option 2: Install from VS Code Extensions Marketplace + +1. Open Visual Studio Code. +2. Navigate to the Extensions view (Ctrl+Shift+X or Cmd+Shift+X). +3. Search for "Continue" in the marketplace. +4. Click `Install` next to the Continue extension. + +### Option 3: Manual Installation using VSIX + +1. Download the latest VSIX package from the [Continue GitHub repository](https://github.com/continuedev/continue/releases). +2. In VS Code, go to Extensions view. +3. Click on the "..." menu at the top of the Extensions sidebar. +4. Select `Install from VSIX...`. +5. Navigate to the downloaded VSIX file and select it. + +## Post-Installation Setup + +1. After installation, you'll see the Continue logo in the left sidebar. +2. Click it to open the Continue extension. +3. We recommend moving Continue to VS Code's right sidebar: + +![move-to-right-sidebar](/img/move-to-right-sidebar.png) + +This keeps the file explorer accessible while using Continue. + +## Getting Started with Continue + +Now that you've successfully installed Continue, you're ready to enhance your coding experience. Here's a quick summary of what you can do: + +1. **Open the Continue sidebar**: Click the Continue logo in the sidebar to access the extension's features. +2. **Start a conversation**: Use the chat interface to ask questions, get code suggestions, or request explanations. +3. **Explore commands**: Familiarize yourself with Continue's commands to streamline your workflow. +4. **Customize settings**: Adjust the extension's settings to suit your preferences and coding style. + +For more detailed information on using Continue, check out our [user guide](../how-to-use-continue.md). + +## Pre-release Version (Optional) + +The VS Code Continue extension is currently in beta. A pre-release version is available with the latest fixes and features. To install the pre-release version: + +1. Open Visual Studio Code. +2. Navigate to the Extensions view (Ctrl+Shift+X or Cmd+Shift+X). +3. Search for "Continue" in the installed extensions. +4. Select `Switch to Pre-release Version` from the menu. + +![Pre-Release](../../static/img/prerelease.png) + +## Troubleshooting + +If you encounter any issues, please refer to our [troubleshooting guide](.././troubleshooting.md) or ask for help in [our Discord community](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/intro.md b/docs/docs/intro.md index e21f85be8..4fed466be 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -1,24 +1,36 @@ --- -title: 💻 Introduction -description: Continue is the open-source autopilot for software development -keywords: [introduction, intro, continue, autopilot, chatgpt] +title: Introduction +description: The open-source AI code assistant for developers +keywords: [continue, AI, code assistant, autocomplete, chat, VS Code, JetBrains] --- -# 💻 Introduction +![Continue Logo](/img/intro.png) -![continue-cover-logo](/img/intro.png) +## The Open-Source AI Code Assistant -**Continue is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** +Continue is the leading open-source AI code assistant, designed to enhance your development workflow. It seamlessly integrates with popular IDEs like [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), providing custom autocomplete and chat experiences. -Some examples of what you can achieve are: +### Key Features -- [Easily understand code sections](how-to-use-continue.md#easily-understand-code-sections) -- [Tab to autocomplete code suggestions](how-to-use-continue.md#tab-to-autocomplete-code-suggestions) -- [Refactor functions where you are coding](how-to-use-continue.md#refactor-functions-where-you-are-coding) -- [Ask questions about your codebase](how-to-use-continue.md#ask-questions-about-your-codebase) -- [Quickly use documentation as context](how-to-use-continue.md#quickly-use-documentation-as-context) -- [Kick off actions with slash commands](how-to-use-continue.md#kick-off-actions-with-slash-commands) -- [Add classes, files, and more to context](how-to-use-continue.md#add-classes-files-and-more-to-context) -- [Understand terminal errors immediately](how-to-use-continue.md#understand-terminal-errors-immediately) +- **Flexible Model Integration**: Use any AI model, whether open-source or commercial, local or remote. +- **Versatile Applications**: Ideal for chat, autocomplete, and embeddings. +- **Highly Customizable**: Configure to fit your existing workflows. -Continue enables you to use the right model for the job, whether it's open-source or commercial, running local or remote, and used for chat, autocomplete, or embeddings. And we provide numerous points of configuration, so that you can customize the extension to fit into your existing workflows. +### What You Can Do with Continue + +1. [Understand code sections easily](how-to-use-continue.md#easily-understand-code-sections) +2. [Autocomplete code with tab](how-to-use-continue.md#tab-to-autocomplete-code-suggestions) +3. [Refactor functions in-place](how-to-use-continue.md#refactor-functions-where-you-are-coding) +4. [Query your codebase](how-to-use-continue.md#ask-questions-about-your-codebase) +5. [Leverage documentation as context](how-to-use-continue.md#quickly-use-documentation-as-context) +6. [Use slash commands for quick actions](how-to-use-continue.md#kick-off-actions-with-slash-commands) +7. [Add various elements to context](how-to-use-continue.md#add-classes-files-and-more-to-context) +8. [Instantly understand terminal errors](how-to-use-continue.md#understand-terminal-errors-immediately) + +Explore these features to supercharge your development process with Continue! + +## See Continue in Action + +
+ +
diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index ff952ddc0..459271d47 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -1,13 +1,17 @@ --- -title: ❓ Troubleshooting +title: Troubleshooting description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- -# ❓ Troubleshooting - The Continue VS Code extension is currently in beta, and the Intellij extension is in Alpha. If you are having trouble, please follow the steps below. +1. [Check the logs](#check-the-logs) +2. [Try the latest pre-release](#download-the-latest-pre-release) +3. [Download an older version](#download-an-older-version) +4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving) +5. [Check FAQs for common issues](#faqs) + ## Check the logs To solve many problems, the first step is reading the logs to find the relevant error message. To do this, follow these steps: @@ -116,4 +120,4 @@ This can be accomplished using the following command: `Continue: Rebuild codebas ## Still having trouble? -Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out. +You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. diff --git a/docs/sidebars.js b/docs/sidebars.js index 085560a4d..0841adbdb 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -14,9 +14,39 @@ /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { docsSidebar: [ - "intro", - "quickstart", - "how-to-use-continue", + { + type: "category", + label: "🚀 Install", + collapsible: true, + collapsed: true, + items: [ + { + type: "doc", + id: "intro", + label: "Introduction", + }, + { + type: "doc", + id: "install/vscode", + label: "VS Code", + }, + { + type: "doc", + id: "install/jetbrains", + label: "JetBrains", + }, + { + type: "doc", + id: "how-to-use-continue", + label: "How to use Continue", + }, + { + type: "doc", + id: "troubleshooting", + label: "Troubleshooting", + }, + ], + }, { type: "category", label: "🌉 Setup", @@ -73,7 +103,6 @@ const sidebars = { }, ], }, - "troubleshooting", { type: "category", label: "📖 Reference", From e72923032d2b3a0ce796e7e8c948843cb40d35ab Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Wed, 14 Aug 2024 15:06:07 +0530 Subject: [PATCH 038/186] build: add watching docusaurus.config.js --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index 09d7b71ea..3e212827e 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "nodemon --watch sidebars.js --exec 'docusaurus start'", + "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'", "build": "docusaurus build", "build:netlify": "docusaurus build --out-dir build/docs", "swizzle": "docusaurus swizzle", From e3e244e96133dd99e9d4598c784bb8210b820256 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Wed, 14 Aug 2024 15:22:09 +0530 Subject: [PATCH 039/186] docs: move reference docs to its own sidebar --- docs/docusaurus.config.js | 6 ++++++ docs/sidebars.js | 11 +++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index e6ec86dcd..006981beb 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -82,6 +82,12 @@ const config = { position: "left", label: "Docs", }, + { + type: "docSidebar", + sidebarId: "referenceSidebar", + position: "left", + label: "Reference", + }, { to: "https://github.com/continuedev/continue", label: "GitHub", diff --git a/docs/sidebars.js b/docs/sidebars.js index 0841adbdb..f03b7402b 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -103,19 +103,22 @@ const sidebars = { }, ], }, + "changelog", + ], + referenceSidebar: [ + "reference/config", { type: "category", - label: "📖 Reference", + label: "LLM Providers", collapsible: true, collapsed: true, items: [ { - type: "autogenerated", - dirName: "reference", + type: 'autogenerated', + dirName: 'reference/Model Providers', }, ], }, - "changelog", ], }; From 058784f84a484f6c13873a55e49924442a9df92f Mon Sep 17 00:00:00 2001 From: mkummer225 <7843299+mkummer225@users.noreply.github.com> Date: Wed, 14 Aug 2024 10:52:57 -0600 Subject: [PATCH 040/186] add GUI stop TTS button functionality & stop TTS on new chat --- core/core.ts | 15 ++++++++++++++- core/protocol/core.ts | 1 + core/protocol/ideWebview.ts | 2 ++ core/protocol/passThrough.ts | 3 +++ core/protocol/webview.ts | 2 ++ core/util/tts.ts | 11 ++++++++++- gui/src/hooks/useSetup.ts | 10 ++++++++++ gui/src/pages/gui.tsx | 11 +++++++++++ gui/src/redux/slices/stateSlice.ts | 10 ++++++++++ 9 files changed, 63 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index bba55631f..16dbd0f06 100644 --- a/core/core.ts +++ b/core/core.ts @@ -360,6 +360,13 @@ export class Core { abortedMessageIds: Set, msg: Message, ) { + const config = await configHandler.loadConfig(); + + // Stop TTS on new StreamChat + if(config.experimental?.readResponseTTS) { + TTS.kill(); + } + const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, @@ -384,7 +391,6 @@ export class Core { next = await gen.next(); } - const config = await configHandler.loadConfig(); if(config.experimental?.readResponseTTS && "completion" in next.value) { TTS.read(next.value?.completion); } @@ -463,6 +469,13 @@ export class Core { } }); + // Provide messenger to TTS so it can set GUI active / inactive state + TTS.messenger = this.messenger; + + on("tts/kill", async () => { + TTS.kill(); + }); + async function* runNodeJsSlashCommand( configHandler: ConfigHandler, abortedMessageIds: Set, diff --git a/core/protocol/core.ts b/core/protocol/core.ts index fb3f7c684..1476fe67e 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -129,6 +129,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined, { model: string; promptTokens: number; generatedTokens: number }[], ]; + "tts/kill": [undefined, void]; "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dir?: string; shouldClearIndexes?: boolean }, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 2fa70bf73..d8701a035 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -31,6 +31,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; + setTTSActive: [undefined, void]; + setTTSInactive: [undefined, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 5fe14573a..3cfaa7628 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -30,6 +30,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/cancel", "autocomplete/accept", "command/run", + "tts/kill", "llm/complete", "llm/streamComplete", "llm/streamChat", @@ -57,4 +58,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", + "setTTSActive", + "setTTSInactive", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 061f2819d..5ee751dec 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -13,4 +13,6 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + setTTSInactive: [undefined, void]; + setTTSActive: [undefined, void]; }; diff --git a/core/util/tts.ts b/core/util/tts.ts index 77e4b1b12..62f69f600 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -1,5 +1,7 @@ import os from "node:os"; import { exec, ChildProcess } from "child_process"; +import type { IMessenger } from "./messenger"; +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; // The amount of time before a process is declared // a zombie after executing .kill() @@ -43,6 +45,7 @@ function sanitizeMessageForTTS(message: string): string { export class TTS { static os: string | undefined = undefined; static handle: ChildProcess | undefined = undefined; + static messenger: IMessenger; static async read(message: string) { message = sanitizeMessageForTTS(message); @@ -75,8 +78,14 @@ export class TTS { console.log( "Text-to-speech is not supported on this operating system.", ); - break; + return; } + + TTS.messenger.request("setTTSActive", undefined); + + TTS.handle?.once("exit", () => { + TTS.messenger.request("setTTSInactive", undefined); + }); } static async kill(): Promise { diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 28cd4019b..e6d05771b 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -7,6 +7,8 @@ import { setVscMachineId } from "../redux/slices/configSlice"; import { addContextItemsAtIndex, setConfig, + setTTSActive, + setTTSInactive, setInactive, setSelectedProfileId, } from "../redux/slices/stateSlice"; @@ -81,6 +83,14 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); }); + useWebviewListener("setTTSActive", async () => { + dispatch(setTTSActive()); + }); + + useWebviewListener("setTTSInactive", async () => { + dispatch(setTTSInactive()); + }); + useWebviewListener("setColors", async (colors) => { Object.keys(colors).forEach((key) => { document.body.style.setProperty(key, colors[key]); diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index caaff7ea6..faeeccd83 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -195,6 +195,7 @@ function GUI() { const defaultModel = useSelector(defaultModelSelector); + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); const active = useSelector((state: RootState) => state.state.active); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); @@ -549,6 +550,16 @@ function GUI() { trackVisibility={active} /> + {ttsActive && ( + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + )} {active && ( (values: &mut[T]) { type State = { history: ChatHistory; contextItems: ContextItemWithId[]; + ttsActive: boolean; active: boolean; config: BrowserSerializedContinueConfig; title: string; @@ -110,6 +111,7 @@ type State = { const initialState: State = { history: [], contextItems: [], + ttsActive: false, active: false, config: { slashCommands: [ @@ -168,6 +170,9 @@ export const stateSlice = createSlice({ ? lastHistory.promptLogs.concat(payload) : payload; }, + setTTSActive: (state) => { + state.ttsActive = true; + }, setActive: (state) => { state.active = true; }, @@ -329,6 +334,9 @@ export const stateSlice = createSlice({ } historyItem.contextItems.push(...payload.contextItems); }, + setTTSInactive: (state) => { + state.ttsActive = false; + }, setInactive: (state) => { state.active = false; }, @@ -500,6 +508,7 @@ export const { setContextItemsAtIndex, addContextItems, addContextItemsAtIndex, + setTTSInactive, setInactive, streamUpdate, newSession, @@ -510,6 +519,7 @@ export const { setDefaultModel, setConfig, addPromptCompletionPair, + setTTSActive, setActive, setEditingContextItemAtIndex, initNewActiveMessage, From 50bca94eee117e603005841b9a8e51ed9c6d9d1f Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 14 Aug 2024 10:30:32 -0700 Subject: [PATCH 041/186] Update ignore.ts --- core/indexing/ignore.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 643b61c32..16526e7fb 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -65,6 +65,8 @@ export const DEFAULT_IGNORE_FILETYPES = [ "*.continueignore", "config.json", "*.csv", + "*.uasset", + "*.pdb", // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; From 978f387922b20e73c1090bd809eb55c4d0830ec6 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 14 Aug 2024 11:30:36 -0700 Subject: [PATCH 042/186] testing: add indexing update tests --- core/indexing/CodeSnippetsIndex.ts | 34 ++++-- core/indexing/FullTextSearch.ts | 3 +- core/indexing/chunk/ChunkCodebaseIndex.ts | 4 - core/indexing/refreshIndex.ts | 8 +- core/test/fixtures.ts | 8 +- core/test/indexing/ChunkCodebaseIndex.test.ts | 96 +++++++++++++++ core/test/indexing/CodeSnippetsIndex.test.ts | 115 ++++++++++++++++++ .../FullTextSearchCodebaseIndex.test.ts | 82 +++++++++++++ core/test/indexing/LanceDbIndex.test.ts | 94 ++++++++++++++ core/test/indexing/utils.ts | 82 +++++++++++++ core/test/testUtils/testDir.ts | 3 +- 11 files changed, 503 insertions(+), 26 deletions(-) create mode 100644 core/test/indexing/ChunkCodebaseIndex.test.ts create mode 100644 core/test/indexing/CodeSnippetsIndex.test.ts create mode 100644 core/test/indexing/FullTextSearchCodebaseIndex.test.ts create mode 100644 core/test/indexing/LanceDbIndex.test.ts create mode 100644 core/test/indexing/utils.ts diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index e431dfdf8..f16c5137a 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -100,26 +100,30 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { contents: string, ): Promise<(ChunkWithoutID & { title: string })[]> { const parser = await getParserForFile(filepath); + if (!parser) { return []; } + const ast = parser.parse(contents); const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets); const matches = query?.matches(ast.rootNode); - return ( - matches?.flatMap((match) => { - const node = match.captures[0].node; - const title = match.captures[1].node.text; - const results = { - title, - content: node.text, - startLine: node.startPosition.row, - endLine: node.endPosition.row, - }; - return results; - }) ?? [] - ); + if (!matches) { + return []; + } + + return matches.flatMap((match) => { + const node = match.captures[0].node; + const title = match.captures[1].node.text; + const results = { + title, + content: node.text, + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + return results; + }); } async *update( @@ -132,6 +136,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { await CodeSnippetsCodebaseIndex._createTables(db); const tagString = tagToString(tag); + // Compute for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; @@ -174,6 +179,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([compute], IndexResultType.Compute); } + // Delete for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; const deleted = await db.run( @@ -186,6 +192,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([del], IndexResultType.Delete); } + // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; let snippets: (ChunkWithoutID & { title: string })[] = []; @@ -220,6 +227,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([results.addTag[i]], IndexResultType.AddTag); } + // Remove tag for (let i = 0; i < results.removeTag.length; i++) { const item = results.removeTag[i]; await db.run( diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts index c640eae20..982886d45 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearch.ts @@ -17,7 +17,8 @@ import { export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; - artifactId = "sqliteFts"; + static artifactId = "sqliteFts"; + artifactId: string = ChunkCodebaseIndex.artifactId; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 498e5144e..671ce31e6 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -238,8 +238,4 @@ export class ChunkCodebaseIndex implements CodebaseIndex { }); }); } - - private formatListPlurality(word: string, length: number): string { - return length <= 1 ? word : `${word}s`; - } } diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 10fe55605..7cfeae0f9 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import crypto from "node:crypto"; import * as fs from "node:fs"; import { open, type Database } from "sqlite"; @@ -113,11 +114,6 @@ async function getSavedItemsForTag( return rows; } -interface PathAndOptionalCacheKey { - path: string; - cacheKey?: string; -} - enum AddRemoveResultType { Add = "add", Remove = "remove", @@ -409,7 +405,7 @@ export async function getComputeDeleteAddRemove( for await (const _ of globalCacheIndex.update( tag, results, - async () => { }, + async () => {}, repoName, )) { } diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index 97c1815b0..51f974fea 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -4,10 +4,16 @@ import FileSystemIde from "../util/filesystem"; import { TEST_DIR } from "./testUtils/testDir"; export const testIde = new FileSystemIde(TEST_DIR); + export const ideSettingsPromise = testIde.getIdeSettings(); + +export const testControlPlaneClient = new ControlPlaneClient( + Promise.resolve(undefined), +); + export const testConfigHandler = new ConfigHandler( testIde, ideSettingsPromise, async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined)), + testControlPlaneClient, ); diff --git a/core/test/indexing/ChunkCodebaseIndex.test.ts b/core/test/indexing/ChunkCodebaseIndex.test.ts new file mode 100644 index 000000000..3c8693beb --- /dev/null +++ b/core/test/indexing/ChunkCodebaseIndex.test.ts @@ -0,0 +1,96 @@ +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; +import { IndexResultType } from "../../indexing/types"; +import { testIde } from "../fixtures"; +import { addToTestDir } from "../testUtils/testDir"; +import { jest } from "@jest/globals"; +import { + mockFileContents, + mockFilename, + mockPathAndCacheKey, + testContinueServerClient, + updateIndexAndAwaitGenerator, +} from "./utils"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: ChunkCodebaseIndex; + let db: DatabaseConnection; + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + + index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + db = await SqliteDb.get(); + }); + + it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + + const computeResult = await db.get( + "SELECT * FROM chunks WHERE cacheKey = ?", + [mockPathAndCacheKey.cacheKey], + ); + + expect(computeResult).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + + const addTagResult = await db.get( + "SELECT * FROM chunk_tags WHERE chunkId = ?", + [computeResult.id], + ); + + expect(addTagResult).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + + const removeTagResult = await db.get( + "SELECT * FROM chunk_tags WHERE id = ?", + [addTagResult.id], + ); + + expect(removeTagResult).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + + const delResult = await db.get("SELECT * FROM chunks WHERE id = ?", [ + computeResult.id, + ]); + + expect(delResult).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/test/indexing/CodeSnippetsIndex.test.ts b/core/test/indexing/CodeSnippetsIndex.test.ts new file mode 100644 index 000000000..2eabaa93f --- /dev/null +++ b/core/test/indexing/CodeSnippetsIndex.test.ts @@ -0,0 +1,115 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex"; +import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; +import { IndexResultType } from "../../indexing/types"; +import { testIde } from "../fixtures"; +import { + insertMockChunks, + mockPathAndCacheKey, + updateIndexAndAwaitGenerator, +} from "./utils"; +import { jest } from "@jest/globals"; + +describe("CodeSnippetsCodebaseIndex", () => { + let index: CodeSnippetsCodebaseIndex; + let db: DatabaseConnection; + + beforeEach(async () => { + db = await SqliteDb.get(); + index = new CodeSnippetsCodebaseIndex(testIde); + }); + + it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + const mockSnippet = { + title: "", + content: "", + startLine: 0, + endLine: 1, + }; + + // We mock this fn since currently in testing the directory structure to access the tree-sitter + // binaries does not match what is in the release environment. + jest + .spyOn(CodeSnippetsCodebaseIndex.prototype, "getSnippetsInFile") + .mockResolvedValue([mockSnippet]); + + await insertMockChunks(); + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + + const computeResult = await db.get( + "SELECT * FROM code_snippets WHERE path = ?", + [mockPathAndCacheKey.path], + ); + + const computeResultTags = await db.get( + "SELECT * FROM code_snippets_tags WHERE snippetId = ?", + [computeResult.id], + ); + + expect(computeResult).toBeTruthy(); + expect(computeResultTags).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + + const delResult = await db.get("SELECT * FROM code_snippets WHERE id = ?", [ + computeResult.id, + ]); + + const delResultTags = await db.get( + "SELECT * FROM code_snippets_tags WHERE id = ?", + [computeResultTags.id], + ); + + expect(delResult).toBeFalsy(); + expect(delResultTags).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + + const addTagResult = await db.get( + "SELECT * FROM code_snippets WHERE path = ?", + [mockPathAndCacheKey.path], + ); + + const addTagResultTags = await db.get( + "SELECT * FROM code_snippets_tags WHERE snippetId = ?", + [addTagResult.id], + ); + + expect(addTagResult).toBeTruthy(); + expect(addTagResultTags).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + + const removeTagResultTag = await db.get( + "SELECT * FROM code_snippets_tags WHERE id = ?", + [addTagResultTags.id], + ); + + expect(removeTagResultTag).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + }); +}); diff --git a/core/test/indexing/FullTextSearchCodebaseIndex.test.ts b/core/test/indexing/FullTextSearchCodebaseIndex.test.ts new file mode 100644 index 000000000..cb27ee920 --- /dev/null +++ b/core/test/indexing/FullTextSearchCodebaseIndex.test.ts @@ -0,0 +1,82 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch"; +import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; +import { IndexResultType } from "../../indexing/types"; +import { + insertMockChunks, + mockPathAndCacheKey, + updateIndexAndAwaitGenerator, +} from "./utils"; +import { jest } from "@jest/globals"; + +describe("FullTextSearchCodebaseIndex", () => { + let index: FullTextSearchCodebaseIndex; + let db: DatabaseConnection; + + beforeEach(async () => { + db = await SqliteDb.get(); + index = new FullTextSearchCodebaseIndex(); + }); + + it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + await insertMockChunks(); + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + + const computeResult = await db.get("SELECT * FROM fts WHERE path = ?", [ + mockPathAndCacheKey.path, + ]); + + const computeResultMetadata = await db.get( + "SELECT * FROM fts_metadata WHERE path = ?", + [mockPathAndCacheKey.path], + ); + + expect(computeResult).toBeTruthy(); + expect(computeResultMetadata).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // AddTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + + const delResult = await db.get("SELECT * FROM fts WHERE path = ?", [ + mockPathAndCacheKey.cacheKey, + ]); + + const delResultMetadata = await db.get( + "SELECT * FROM fts_metadata WHERE path = ?", + [mockPathAndCacheKey.path], + ); + + expect(delResult).toBeFalsy(); + expect(delResultMetadata).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/test/indexing/LanceDbIndex.test.ts b/core/test/indexing/LanceDbIndex.test.ts new file mode 100644 index 000000000..1cf1ec800 --- /dev/null +++ b/core/test/indexing/LanceDbIndex.test.ts @@ -0,0 +1,94 @@ +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; +import { IndexResultType } from "../../indexing/types"; +import { testIde } from "../fixtures"; +import { addToTestDir } from "../testUtils/testDir"; +import { jest } from "@jest/globals"; +import { + testContinueServerClient, + updateIndexAndAwaitGenerator, +} from "./utils"; +import { LanceDbIndex } from "../../indexing/LanceDbIndex"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: ChunkCodebaseIndex; + let db: DatabaseConnection; + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + + index = new LanceDbIndex( + undefined, + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + db = await SqliteDb.get(); + }); + + it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + + const computeResult = await db.get( + "SELECT * FROM chunks WHERE cacheKey = ?", + [mockPathAndCacheKey.cacheKey], + ); + + expect(computeResult).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + + const addTagResult = await db.get( + "SELECT * FROM chunk_tags WHERE chunkId = ?", + [computeResult.id], + ); + + expect(addTagResult).toBeTruthy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + + const removeTagResult = await db.get( + "SELECT * FROM chunk_tags WHERE id = ?", + [addTagResult.id], + ); + + expect(removeTagResult).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + + const delResult = await db.get("SELECT * FROM chunks WHERE id = ?", [ + computeResult.id, + ]); + + expect(delResult).toBeFalsy(); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/test/indexing/utils.ts b/core/test/indexing/utils.ts new file mode 100644 index 000000000..e79a79b27 --- /dev/null +++ b/core/test/indexing/utils.ts @@ -0,0 +1,82 @@ +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { IContinueServerClient } from "../../continueServer/interface"; +import { testIde } from "../fixtures"; +import { addToTestDir, TEST_DIR } from "../testUtils/testDir"; +import { IndexTag } from "../.."; +import { CodebaseIndex, RefreshIndexResults } from "../../indexing/types"; +import { jest } from "@jest/globals"; +import { tagToString } from "../../indexing/refreshIndex"; + +export const mockFilename = "test.py"; +export const mockPathAndCacheKey = { + path: `${TEST_DIR}/${mockFilename}`, + cacheKey: "abc123", +}; +export const mockFileContents = `\ +def main(): + print("Hello, world!") + +class Foo: + def __init__(self, bar: str): + self.bar = bar +`; + +export const mockTag: IndexTag = { + branch: "main", + directory: "/", + artifactId: "artifactId", +}; + +export const mockTagString = tagToString(mockTag); + +export const testContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockResults: RefreshIndexResults = { + compute: [], + addTag: [], + removeTag: [], + del: [], +}; + +const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + +export async function insertMockChunks() { + const pathSep = await testIde.pathSep(); + + const index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + mockContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); +} + +export async function updateIndexAndAwaitGenerator( + index: CodebaseIndex, + resultType: keyof RefreshIndexResults, + mockMarkComplete: any, +) { + const computeGenerator = index.update( + mockTag, + { ...mockResults, [resultType]: [mockPathAndCacheKey] }, + mockMarkComplete, + "test-repo", + ); + + while (!(await computeGenerator.next()).done) {} +} diff --git a/core/test/testUtils/testDir.ts b/core/test/testUtils/testDir.ts index 557906cef..d6bc462dc 100644 --- a/core/test/testUtils/testDir.ts +++ b/core/test/testUtils/testDir.ts @@ -1,8 +1,9 @@ import fs from "fs"; import path from "path"; +import os from "os"; // Want this outside of the git repository so we can change branches in tests -export const TEST_DIR = path.join(__dirname, "..", "..", "testDir"); +export const TEST_DIR = path.join(os.tmpdir(), "testDir"); export function setUpTestDir() { if (fs.existsSync(TEST_DIR)) { From 3f2e5b02291133f7a0905d320c6cc4d16f87474f Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 14 Aug 2024 12:08:49 -0700 Subject: [PATCH 043/186] docs: add 'talk to your docs' --- docs/docs/customization/context-providers.md | 26 +----- docs/docs/features/talk-to-your-docs.md | 84 ++++++++++++++++++++ docs/sidebars.js | 11 +-- 3 files changed, 92 insertions(+), 29 deletions(-) create mode 100644 docs/docs/features/talk-to-your-docs.md diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 77d03b683..250db4158 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -50,35 +50,13 @@ Type '@terminal' to reference the contents of your IDE's terminal. ### Documentation -Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question. +Type `@docs` to index and retrieve snippets from any documentation site. ```json { "name": "docs" } ``` -Continue also pre-indexes a number of common sites, listed [here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). The embeddings for these sites are hosted by us, but downloaded for local use after the first time. All other indexing occurs entirely locally. - -#### Adding a Documentation Site via Configuration - -To add a documentation site via configuration, update the `config.json` file as follows: - -```json -{ - "name": "docs", - "params": { - "sites": [ - { - "title": "ExampleDocs", - "startUrl": "https://exampledocs.com/docs", - "rootUrl": "https://exampledocs.com", - "maxDepth": 3 // Default - } - ] - } -} -``` - -The docs are indexed when you modify the configuration file, unless indexing is disabled. If you want to manually trigger the indexing, you can use the command `Continue: Docs Index`. For force indexing, you can use the command `Continue: Docs Force Re-Index`. Note that these commands will work even if automatic indexing is disabled. +To learn more, visit [Talk to your docs](../features/talk-to-your-docs.md). ### Open Files diff --git a/docs/docs/features/talk-to-your-docs.md b/docs/docs/features/talk-to-your-docs.md new file mode 100644 index 000000000..f18ac08e1 --- /dev/null +++ b/docs/docs/features/talk-to-your-docs.md @@ -0,0 +1,84 @@ +--- +title: Talk to your docs +description: Use the @docs context provider to index documentation sites for querying +keywords: [documentation, indexing, context provider, embeddings] +toc_max_heading_level: 5 +--- + +The [`@docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. + +## Enabling the `@docs` context provider + +To enable the `@docs` context provider, you need to add it to the list of context providers in your `config.json` file. + +```json +{ + "contextProviders": [ + { "name": "docs" } + ... + ] +} +``` + +## How It Works + +The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. + +1. We crawl the specified documentation site +2. Generate embeddings for the content +3. Store the embeddings locally on your machine +4. Provide access to the indexed content through the `@docs` context provider + +## Pre-indexed Documentation Sites + +We offer a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). + +## Indexing Your Own Documentation + +### Through the `@docs` Context Provider + +To add a single documentation site, we recommend going through the `@docs` context provider. + +1. Type `@docs` in the chat panel, hit enter +2. Type "add" and select the "Add Docs" option +3. Enter the required information into the dialog + +Indexing will begin upon submission. + +### Through `config.json` + +To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save. + +The configuration schema is as follows: + +```json +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + "maxDepth": 3 + } +] +``` + +- `title`: The name of the documentation site, used for identification in the UI. +- `startUrl`: The URL where the indexing process should begin. +- `rootUrl`: The base URL of the documentation site, used to determine which pages to index. +- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +- `maxDepth`: The maximum number of levels deep the indexer should crawl from the start URL. + +## FAQ + +### Why did my documentation site fail to index? + +Our current crawler is designed to work with static websites and may encounter issues with dynamic or JavaScript-heavy sites. If your documentation site failed to index, it's possible that it contains non-static elements that our crawler couldn't process. + +If you're experiencing issues with indexing a documentation site, please let us know. We're continuously improving our indexing capabilities and would appreciate your feedback to help us enhance the feature. + +Report Indexing Issues on Discord + +### How often is the indexed content updated? + +Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`. diff --git a/docs/sidebars.js b/docs/sidebars.js index f03b7402b..b569b31d8 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -66,6 +66,7 @@ const sidebars = { collapsed: true, items: [ "features/codebase-embeddings", + "features/talk-to-your-docs", "features/tab-autocomplete", "customization/context-providers", "customization/slash-commands", @@ -97,9 +98,9 @@ const sidebars = { "development-data", "telemetry", { - type: 'link', - label: 'Privacy Policy', - href: 'https://www.continue.dev/privacy', + type: "link", + label: "Privacy Policy", + href: "https://www.continue.dev/privacy", }, ], }, @@ -114,8 +115,8 @@ const sidebars = { collapsed: true, items: [ { - type: 'autogenerated', - dirName: 'reference/Model Providers', + type: "autogenerated", + dirName: "reference/Model Providers", }, ], }, From bba8f564894730dd372cdf6a88c46f73e0b464dd Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 14 Aug 2024 12:09:47 -0700 Subject: [PATCH 044/186] update title --- docs/docs/customization/context-providers.md | 2 +- docs/docs/features/talk-to-your-docs.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 250db4158..610e272a9 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -56,7 +56,7 @@ Type `@docs` to index and retrieve snippets from any documentation site. { "name": "docs" } ``` -To learn more, visit [Talk to your docs](../features/talk-to-your-docs.md). +To learn more, visit [Talk To Your Docs](../features/talk-to-your-docs.md). ### Open Files diff --git a/docs/docs/features/talk-to-your-docs.md b/docs/docs/features/talk-to-your-docs.md index f18ac08e1..569fea3c2 100644 --- a/docs/docs/features/talk-to-your-docs.md +++ b/docs/docs/features/talk-to-your-docs.md @@ -1,5 +1,5 @@ --- -title: Talk to your docs +title: Talk To Your Docs description: Use the @docs context provider to index documentation sites for querying keywords: [documentation, indexing, context provider, embeddings] toc_max_heading_level: 5 From d9d001ea1d50d8da684c600e5140632f98d99773 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 14 Aug 2024 12:10:50 -0700 Subject: [PATCH 045/186] improve description --- docs/docs/features/talk-to-your-docs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/features/talk-to-your-docs.md b/docs/docs/features/talk-to-your-docs.md index 569fea3c2..d1088b4ea 100644 --- a/docs/docs/features/talk-to-your-docs.md +++ b/docs/docs/features/talk-to-your-docs.md @@ -1,6 +1,6 @@ --- title: Talk To Your Docs -description: Use the @docs context provider to index documentation sites for querying +description: Learn how to access and search your project's documentation directly within Continue keywords: [documentation, indexing, context provider, embeddings] toc_max_heading_level: 5 --- From 37269db91caaa77a3789a34ed44687b5c4c4f4c0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Aug 2024 16:47:33 -0700 Subject: [PATCH 046/186] add computed rows to lancedb --- core/indexing/LanceDbIndex.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 3f0b3a3bc..12f8b1668 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -307,6 +307,17 @@ export class LanceDbIndex implements CodebaseIndex { const dbRows = await this.computeRows(results.compute); await this.insertRows(sqlite, dbRows); + await Promise.all( + results.compute.map((result) => { + addComputedLanceDbRows( + result, + dbRows.filter( + (row) => + row.path === result.path && row.cachekey === result.cacheKey, + ), + ); + }), + ); await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; From b5fbb9827890af4d03133baeb63fa3730683099f Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 14 Aug 2024 17:48:30 -0700 Subject: [PATCH 047/186] add(llm)-bedrock-imported-models --- binary/package-lock.json | 1 + core/index.d.ts | 9 +- core/llm/llms/Bedrock.ts | 11 ++- core/llm/llms/BedrockImport.ts | 94 +++++++++++++++++++ core/llm/llms/index.ts | 2 + docs/static/schemas/config.json | 2 + .../src/main/resources/config_schema.json | 2 + extensions/vscode/config_schema.json | 2 + extensions/vscode/continue_rc_schema.json | 2 + extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- 11 files changed, 123 insertions(+), 8 deletions(-) create mode 100644 core/llm/llms/BedrockImport.ts diff --git a/binary/package-lock.json b/binary/package-lock.json index 9378d2eef..b57800a29 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -79,6 +79,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/core/index.d.ts b/core/index.d.ts index 3fcb08fa1..42bc389ed 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -341,8 +341,14 @@ export interface LLMOptions { apiVersion?: string; apiType?: string; - // GCP Options + // AWS options + profile?: string; + modelArn?: string; + + // AWS and GCP Options region?: string; + + // GCP Options projectId?: string; capabilities?: ModelCapability; @@ -595,6 +601,7 @@ type ModelProvider = | "gemini" | "mistral" | "bedrock" + | "bedrockimport" | "sagemaker" | "deepinfra" | "flowise" diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 226671c52..0cdebc309 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,19 +14,22 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { - private static PROFILE_NAME: string = "bedrock"; static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", - contextLength: 200_000, + contextLength: 200_000 }; + profile?: string | undefined; constructor(options: LLMOptions) { super(options); if (!options.apiBase) { this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } + if (options.profile) { + this.profile = options.profile; + } } protected async *_streamComplete( @@ -124,11 +127,11 @@ class Bedrock extends BaseLLM { private async _getCredentials() { try { return await fromIni({ - profile: Bedrock.PROFILE_NAME, + profile: this.profile, })(); } catch (e) { console.warn( - `AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`, + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); return await fromIni()(); } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts new file mode 100644 index 000000000..504f472f2 --- /dev/null +++ b/core/llm/llms/BedrockImport.ts @@ -0,0 +1,94 @@ +import { + BedrockRuntimeClient, + InvokeModelWithResponseStreamCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class BedrockImport extends BaseLLM { + static providerName: ModelProvider = "bedrockimport"; + static defaultOptions: Partial = { + region: "us-east-1" + }; + // the BedRock imported custom model ARN + modelArn?: string | undefined; + profile?: string | undefined; + + constructor(options: LLMOptions) { + super(options); + if (!options.apiBase) { + this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + } + if (options.modelArn) { + this.modelArn = options.modelArn; + } + if (options.profile) { + this.profile = options.profile; + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const input = this._generateInvokeModelCommandInput(prompt, options); + const command = new InvokeModelWithResponseStreamCommand(input); + const response = await client.send(command); + + if (response.body) { + for await (const item of response.body) { + const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes)); + if (chunk.outputs[0].text) { + yield chunk.outputs[0].text; + } + } + } + } + + private _generateInvokeModelCommandInput( + prompt: string, + options: CompletionOptions, + ): any { + const payload = { + prompt: prompt + }; + + return { + body: JSON.stringify(payload), + modelId: this.modelArn, + accept: "application/json", + contentType: "application/json" + }; + } + + private async _getCredentials() { + try { + return await + fromIni({ + profile: this.profile + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default BedrockImport; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cd084207e..7cc6f701f 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -11,6 +11,7 @@ import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; +import BedrockImport from "./BedrockImport"; import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; @@ -53,6 +54,7 @@ const LLMs = [ LMStudio, Mistral, Bedrock, + BedrockImport, SageMaker, DeepInfra, Flowise, diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 44a908810..4e85e91a4 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 44a908810..4e85e91a4 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 44a908810..4e85e91a4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index d6c797596..35fc4906f 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -174,6 +174,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -200,6 +201,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 6af742e21..7c2cad527 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.197", + "version": "0.9.199", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.197", + "version": "0.9.199", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 389c6bac5..a87c6ac3c 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.197", + "version": "0.9.199", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 48353e651de2a7a8df9cce77473f25e2b79807b1 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 14 Aug 2024 17:58:38 -0700 Subject: [PATCH 048/186] update docs --- .../docs/reference/Model Providers/bedrock.md | 11 ++++---- .../Model Providers/bedrockimport.md | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 docs/docs/reference/Model Providers/bedrockimport.md diff --git a/docs/docs/reference/Model Providers/bedrock.md b/docs/docs/reference/Model Providers/bedrock.md index daac562af..d720de66f 100644 --- a/docs/docs/reference/Model Providers/bedrock.md +++ b/docs/docs/reference/Model Providers/bedrock.md @@ -1,4 +1,4 @@ -# AWS Bedrock +# AWS Bedrock To setup Bedrock, add the following to your `config.json` file: @@ -9,18 +9,19 @@ To setup Bedrock, add the following to your `config.json` file: "title": "Bedrock: Claude 3 Sonnet", "provider": "bedrock", "model": "anthropic.claude-3-sonnet-20240229-v1:0", - "region": "us-east-1" + "region": "us-east-1", + "profile": "bedrock", } ] } ``` -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a profile called "bedrock". +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). ```title="~/.aws/credentials [bedrock] aws_access_key_id = abcdefg aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. +aws_session_token = pqrstuvwxyz # Optional: means short term creds. ``` diff --git a/docs/docs/reference/Model Providers/bedrockimport.md b/docs/docs/reference/Model Providers/bedrockimport.md new file mode 100644 index 000000000..6a8c50d68 --- /dev/null +++ b/docs/docs/reference/Model Providers/bedrockimport.md @@ -0,0 +1,28 @@ +# AWS Bedrock Custom Imported Models + +To setup Bedrock using custom imported models, add the following to your `config.json` file: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] +} +``` + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` From c20b0b42204afbcc74c1ba779a06f551db885156 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Thu, 15 Aug 2024 08:15:18 -0700 Subject: [PATCH 049/186] default to bedrock profile for backwards compatibility --- core/llm/llms/Bedrock.ts | 2 ++ core/llm/llms/BedrockImport.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 0cdebc309..415ec0f10 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -29,6 +29,8 @@ class Bedrock extends BaseLLM { } if (options.profile) { this.profile = options.profile; + } else { + this.profile = "bedrock"; } } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 504f472f2..f53d4b15e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -29,6 +29,8 @@ class BedrockImport extends BaseLLM { } if (options.profile) { this.profile = options.profile; + } else { + this.profile = "bedrock"; } } From 81487d2d5ab82f0dbaca78bd14bcea964e4ef005 Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Thu, 15 Aug 2024 10:59:45 -0700 Subject: [PATCH 050/186] Correct the behavior for ignore files in sub-directories The ignore library expects for a subdirectory that the caller pass in the relative path of files, i.e. remove the sub-directory prefix from the filepath. --- core/indexing/walkDir.ts | 73 ++++++++++++++++++++++++++++----------- core/test/walkDir.test.ts | 19 +++++++++- 2 files changed, 70 insertions(+), 22 deletions(-) diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 014753daf..eeeb064d0 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -29,7 +29,12 @@ type WalkableEntry = { // helper struct used for the DFS walk type WalkContext = { walkableEntry: WalkableEntry; + ignoreContexts: IgnoreContext[]; +}; + +type IgnoreContext = { ignore: Ignore; + dirname: string; }; class DFSWalker { @@ -51,30 +56,22 @@ class DFSWalker { this.options.returnRelativePaths ? "" : this.path, this.ide, ); - const root: WalkContext = { - walkableEntry: { - relPath: "", - absPath: this.path, - type: 2 as FileType.Directory, - entry: ["", 2 as FileType.Directory], - }, - ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), - }; + const root = this.newRootWalkContext(); const stack = [root]; for (let cur = stack.pop(); cur; cur = stack.pop()) { const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignore = await this.getIgnoreToApplyInDir( - cur.ignore, + const ignoreContexts = await this.getIgnoreToApplyInDir( + cur, walkableEntries, ); for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignore)) { + if (!this.shouldInclude(w, ignoreContexts)) { continue; } if (this.entryIsDirectory(w.entry)) { stack.push({ walkableEntry: w, - ignore: ignore, + ignoreContexts: ignoreContexts, }); if (this.options.onlyDirs) { // when onlyDirs is enabled the walker will only return directory names @@ -87,6 +84,23 @@ class DFSWalker { } } + private newRootWalkContext(): WalkContext { + return { + walkableEntry: { + relPath: "", + absPath: this.path, + type: 2 as FileType.Directory, + entry: ["", 2 as FileType.Directory], + }, + ignoreContexts: [ + { + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), + dirname: "", + }, + ], + }; + } + private async listDirForWalking( walkableEntry: WalkableEntry, ): Promise { @@ -102,15 +116,22 @@ class DFSWalker { } private async getIgnoreToApplyInDir( - parentIgnore: Ignore, - walkableEntries: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries); + curDir: WalkContext, + entriesInDir: WalkableEntry[], + ): Promise { + const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); if (ignoreFilesInDir.length === 0) { - return parentIgnore; + return curDir.ignoreContexts; } const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - return ignore().add(parentIgnore).add(patterns); + const newIgnoreContext = { + ignore: ignore().add(patterns), + dirname: curDir.walkableEntry.relPath, + }; + return [ + ...curDir.ignoreContexts, + newIgnoreContext + ]; } private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { @@ -126,7 +147,7 @@ class DFSWalker { return this.ignoreFileNames.has(p); } - private shouldInclude(walkableEntry: WalkableEntry, ignore: Ignore) { + private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, // and therefore will be walked OR it linksto something outside of the repository and @@ -141,7 +162,17 @@ class DFSWalker { return false; } } - return !ignore.ignores(relPath); + for (const ig of ignoreContexts) { + // remove the directory name and path seperator from the match path, unless this an ignore file + // in the root directory + const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + return false; + } + } + return true; } private entryIsDirectory(entry: Entry) { diff --git a/core/test/walkDir.test.ts b/core/test/walkDir.test.ts index 87f643f4e..5ae033337 100644 --- a/core/test/walkDir.test.ts +++ b/core/test/walkDir.test.ts @@ -1,5 +1,6 @@ import path from "path"; -import { walkDir, WalkerOptions } from "../indexing/walkDir.js"; +import ignore, { Ignore } from "ignore"; +import { walkDir, walkDirAsync, WalkerOptions } from "../indexing/walkDir.js"; import FileSystemIde from "../util/filesystem.js"; import { addToTestDir, @@ -191,6 +192,22 @@ describe("walkDir", () => { await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]); }); + test("gitignore in sub directory should only apply to subdirectory", async () => { + const files = [ + [".gitignore", "abc"], + "a.txt", + "abc", + "xyz/", + ["xyz/.gitignore", "xyz"], + "xyz/b.txt", + "xyz/c/", + "xyz/c/d.py", + "xyz/xyz", + ]; + addToTestDir(files); + await expectPaths(["a.txt", "xyz/b.txt", "xyz/c/d.py"], ["abc", "xyz/xyz"]); + }); + test("should handle complex patterns in .gitignore", async () => { const files = [ [".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"], From b5eed347da8c83bc572c122c036c6d96816acb81 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 15 Aug 2024 11:27:40 -0700 Subject: [PATCH 051/186] Update pull_request_template.md --- .github/pull_request_template.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index bad9f55f0..f9a4b0151 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -9,8 +9,8 @@ ## Screenshots -[ "For visual changes, include screenshots." ] +[ For visual changes, include screenshots. ] ## Testing -[ For new or modified features, provide testing instructions. ] +[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change. ] From 5008f1d71a4ae2abcf9ae8d2b8e56d5f65a3ea8e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 11:59:00 -0700 Subject: [PATCH 052/186] draft update jetbrains-release --- .github/workflows/jetbrains-build.yaml | 2 +- .github/workflows/jetbrains-release.yaml | 401 ++++++++++++++++++++--- 2 files changed, 352 insertions(+), 51 deletions(-) diff --git a/.github/workflows/jetbrains-build.yaml b/.github/workflows/jetbrains-build.yaml index 16d07163c..b23094106 100644 --- a/.github/workflows/jetbrains-build.yaml +++ b/.github/workflows/jetbrains-build.yaml @@ -110,7 +110,7 @@ jobs: npm ci # npm install binary - - name: Install core node_modules + - name: Install binary node_modules run: | cd ../../binary npm ci diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 3df1ae29f..85fdece4d 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -3,14 +3,22 @@ # See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information. name: Release -# on: -# release: -# types: [prereleased, released] + +on: + create: + tags: + - "v0.0.*-jetbrains" + branches: + - dev defaults: run: working-directory: ./extensions/intellij +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: check_release_name: runs-on: ubuntu-latest @@ -41,6 +49,10 @@ jobs: with: ref: ${{ github.event.release.tag_name }} + # Validate wrapper + - name: Gradle Wrapper Validation + uses: gradle/actions/wrapper-validation@v3 + # Set up Java environment for the next steps - name: Setup Java uses: actions/setup-java@v4 @@ -59,15 +71,20 @@ jobs: id: properties shell: bash run: | - CHANGELOG="$(cat << 'EOM' | sed -e 's/^[[:space:]]*$//g' -e '/./,$!d' - ${{ github.event.release.body }} - EOM - )" + PROPERTIES="$(./gradlew properties --console=plain -q)" + VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" + # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" + CHANGELOG="" + + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT echo "changelog<> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT + ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier + # Setup Node.js - name: Use Node.js from .nvmrc uses: actions/setup-node@v4 @@ -100,7 +117,7 @@ jobs: npm ci # npm install binary - - name: Install core node_modules + - name: Install binary node_modules run: | cd ../../binary npm ci @@ -123,60 +140,344 @@ jobs: cd ../../extensions/vscode npm ci npm run prepackage + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} # Build binaries - - name: Install core node_modules + - name: Build the binaries run: | cd ../../binary npm run build - # Update Unreleased section with the current release note - - name: Patch Changelog - if: ${{ steps.properties.outputs.changelog != '' }} - env: - CHANGELOG: ${{ steps.properties.outputs.changelog }} + # Build plugin + - name: Build plugin + run: ./gradlew buildPlugin + + # Prepare plugin archive content for creating artifact + - name: Prepare Plugin Artifact + id: artifact + shell: bash run: | - ./gradlew patchChangelog --release-note="$CHANGELOG" + cd ../../extensions/intellij/build/distributions + FILENAME=`ls *.zip` + unzip "$FILENAME" -d content - # Upload artifact as a release asset - - name: Upload Release Asset - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT - # Publish the plugin to JetBrains Marketplace - - name: Publish Plugin - env: - PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} - CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} - PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} - PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} - run: ./gradlew publishPlugin + # Store already-built plugin as an artifact for downloading + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./extensions/intellij/build/distributions/content/*/* - # Create a pull request - - name: Create Pull Request - if: ${{ steps.properties.outputs.changelog != '' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Upload binaries as artifacts + - name: Upload artifact (darwin-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-arm64 + path: ./binary/bin/darwin-arm64/ + + - name: Upload artifact (darwin-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-x64 + path: ./binary/bin/darwin-x64/ + + - name: Upload artifact (win32-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-win32-x64 + path: ./binary/bin/win32-x64/ + + - name: Upload artifact (linux-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-linux-arm64 + path: ./binary/bin/linux-arm64/ + + - name: Upload artifact (linux-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-linux-x64 + path: ./binary/bin/linux-x64/ + + test-binaries: + needs: build + strategy: + matrix: + include: + - os: windows-latest + platform: win32 + arch: x64 + npm_config_arch: x64 + - os: ubuntu-latest + platform: linux + arch: x64 + npm_config_arch: x64 + # arm64 not actually supported by GitHub + # - os: ubuntu-latest + # platform: linux + # arch: arm64 + # npm_config_arch: arm64 + - os: macos-12 + platform: darwin + arch: x64 + npm_config_arch: x64 + - os: macos-latest + platform: darwin + arch: arm64 + npm_config_arch: arm64 + runs-on: ${{ matrix.os }} + steps: + # 1. Check-out repository + - name: Check-out repository + uses: actions/checkout@v4 + + # 2. Install npm dependencies + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Cache core node_modules + uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} + + - name: Cache binary node_modules + uses: actions/cache@v3 + with: + path: binary/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + + - name: Install Core Dependencies run: | - VERSION="${{ github.event.release.tag_name }}" - BRANCH="changelog-update-$VERSION" - LABEL="release changelog" + cd ../../core + npm ci - git config user.email "action@github.com" - git config user.name "GitHub Action" + - name: Install Binary Dependencies + run: | + cd ../../binary + npm ci - git checkout -b $BRANCH - git commit -am "Changelog update - $VERSION" - git push --set-upstream origin $BRANCH + # Download the binary artifact + - name: Download binary artifact + uses: actions/download-artifact@v4 + with: + name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} + path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ - gh label create "$LABEL" \ - --description "Pull requests with release changelog update" \ - --force \ - || true + # Set execute permissions for the binary (non-Windows) + - name: Set execute permissions + run: | + cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }} + chmod +x continue-binary + chmod +x node_sqlite3.node + chmod +x index.node + chmod +x esbuild + if: ${{ matrix.platform }} != 'win32' - gh pr create \ - --title "Changelog update - \`$VERSION\`" \ - --body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \ - --label "$LABEL" \ - --head $BRANCH + - name: Copy node_sqlite3.node to necessary location + run: | + cd ../../binary + mkdir build + cp ./bin/${{ matrix.platform }}-${{ matrix.arch }}/node_sqlite3.node ./build/node_sqlite3.node + + # Run tests for binary + - name: Run binary tests + run: | + cd ../../binary + npm run test + + - name: Upload logs + if: ${{ always() }} + uses: actions/upload-artifact@v2 + with: + name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} + path: binary/.continue/logs/core.log + + # Run tests and upload a code coverage report + test: + name: Test + needs: [build] + runs-on: ubuntu-latest + steps: + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Setup Gradle + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true + + # Run tests + - name: Run Tests + run: ./gradlew check + + # Collect Tests Result of failed tests + - name: Collect Tests Result + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: tests-result + path: ${{ github.workspace }}/extensions/intellij/build/reports/tests + + # Upload the Kover report to CodeCov + # - name: Upload Code Coverage Report + # uses: codecov/codecov-action@v4 + # with: + # files: ${{ github.workspace }}/build/reports/kover/report.xml + + # Run Qodana inspections and provide report + inspectCode: + if: false + name: Inspect code + needs: [build] + runs-on: ubuntu-latest + permissions: + contents: write + checks: write + pull-requests: write + steps: + # Free GitHub Actions Environment Disk Space + - name: Maximize Build Space + uses: jlumbroso/free-disk-space@main + with: + tool-cache: false + large-packages: false + + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Run Qodana inspections + - name: Qodana - Code Inspection + uses: JetBrains/qodana-action@v2024.1.5 + with: + cache-default-branch-only: true + + # Run plugin structure verification along with IntelliJ Plugin Verifier + verify: + name: Verify plugin + needs: [build] + runs-on: ubuntu-latest + steps: + # Free GitHub Actions Environment Disk Space + - name: Maximize Build Space + uses: jlumbroso/free-disk-space@main + with: + tool-cache: false + large-packages: false + + # Check out current repository + - name: Fetch Sources + uses: actions/checkout@v4 + + # Set up Java environment for the next steps + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 + + # Setup Gradle + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true + + # Cache Plugin Verifier IDEs + - name: Setup Plugin Verifier IDEs Cache + uses: actions/cache@v4 + with: + path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides + key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }} + + # Run Verify Plugin task and IntelliJ Plugin Verifier tool + - name: Run Plugin Verification tasks + run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }} + + # Collect Plugin Verifier Result + - name: Collect Plugin Verifier Result + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: pluginVerifier-result + path: ${{ github.workspace }}/build/reports/pluginVerifier + + upload-release: + # # Update Unreleased section with the current release note + # - name: Patch Changelog + # if: ${{ steps.properties.outputs.changelog != '' }} + # env: + # CHANGELOG: ${{ steps.properties.outputs.changelog }} + # run: | + # ./gradlew patchChangelog --release-note="$CHANGELOG" + + - name: Download the plugin + uses: actions/download-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./build/distributions/ + + # Upload artifact as a release asset + - name: Upload Release Asset + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + + # Publish the plugin to JetBrains Marketplace + - name: Publish Plugin + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + run: ./gradlew publishPlugin + + # Create a pull request + - name: Create Pull Request + if: ${{ steps.properties.outputs.changelog != '' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + VERSION="${{ github.event.release.tag_name }}" + BRANCH="changelog-update-$VERSION" + LABEL="release changelog" + + git config user.email "action@github.com" + git config user.name "GitHub Action" + + git checkout -b $BRANCH + git commit -am "Changelog update - $VERSION" + git push --set-upstream origin $BRANCH + + gh label create "$LABEL" \ + --description "Pull requests with release changelog update" \ + --force \ + || true + + gh pr create \ + --title "Changelog update - \`$VERSION\`" \ + --body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \ + --label "$LABEL" \ + --head $BRANCH From 1c437a74de7558c2e645e3d5b3139166056163b0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 11:59:19 -0700 Subject: [PATCH 053/186] update branch name --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 85fdece4d..285d0bae8 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -9,7 +9,7 @@ on: tags: - "v0.0.*-jetbrains" branches: - - dev + - nate/apple-developer-finally defaults: run: From 111c03f1da039b5741763a95f1f7ddcae4ddaca9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:02:54 -0700 Subject: [PATCH 054/186] fix syntax --- .github/workflows/jetbrains-release.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 285d0bae8..577b266b2 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -435,9 +435,9 @@ jobs: - name: Download the plugin uses: actions/download-artifact@v4 - with: - name: ${{ steps.artifact.outputs.filename }} - path: ./build/distributions/ + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./build/distributions/ # Upload artifact as a release asset - name: Upload Release Asset From dc11b1e9987573f31c33360cb7ac9afd348fa5e9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:03:11 -0700 Subject: [PATCH 055/186] trigger on push for testing --- .github/workflows/jetbrains-release.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 577b266b2..4c5454a7f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -5,9 +5,10 @@ name: Release on: - create: - tags: - - "v0.0.*-jetbrains" + push: + # create: + # tags: + # - "v0.0.*-jetbrains" branches: - nate/apple-developer-finally From a273fe804c0a1b1539a9253990f31db1008718ea Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:03:58 -0700 Subject: [PATCH 056/186] syntax --- .github/workflows/jetbrains-release.yaml | 97 ++++++++++++------------ 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 4c5454a7f..d7228bf9d 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -426,59 +426,60 @@ jobs: path: ${{ github.workspace }}/build/reports/pluginVerifier upload-release: - # # Update Unreleased section with the current release note - # - name: Patch Changelog - # if: ${{ steps.properties.outputs.changelog != '' }} - # env: - # CHANGELOG: ${{ steps.properties.outputs.changelog }} - # run: | - # ./gradlew patchChangelog --release-note="$CHANGELOG" + steps: + # # Update Unreleased section with the current release note + # - name: Patch Changelog + # if: ${{ steps.properties.outputs.changelog != '' }} + # env: + # CHANGELOG: ${{ steps.properties.outputs.changelog }} + # run: | + # ./gradlew patchChangelog --release-note="$CHANGELOG" - - name: Download the plugin - uses: actions/download-artifact@v4 - with: - name: ${{ steps.artifact.outputs.filename }} - path: ./build/distributions/ + - name: Download the plugin + uses: actions/download-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./build/distributions/ - # Upload artifact as a release asset - - name: Upload Release Asset - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + # Upload artifact as a release asset + - name: Upload Release Asset + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* - # Publish the plugin to JetBrains Marketplace - - name: Publish Plugin - env: - PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} - CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} - PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} - PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} - run: ./gradlew publishPlugin + # Publish the plugin to JetBrains Marketplace + - name: Publish Plugin + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + run: ./gradlew publishPlugin - # Create a pull request - - name: Create Pull Request - if: ${{ steps.properties.outputs.changelog != '' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - VERSION="${{ github.event.release.tag_name }}" - BRANCH="changelog-update-$VERSION" - LABEL="release changelog" + # Create a pull request + - name: Create Pull Request + if: ${{ steps.properties.outputs.changelog != '' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + VERSION="${{ github.event.release.tag_name }}" + BRANCH="changelog-update-$VERSION" + LABEL="release changelog" - git config user.email "action@github.com" - git config user.name "GitHub Action" + git config user.email "action@github.com" + git config user.name "GitHub Action" - git checkout -b $BRANCH - git commit -am "Changelog update - $VERSION" - git push --set-upstream origin $BRANCH + git checkout -b $BRANCH + git commit -am "Changelog update - $VERSION" + git push --set-upstream origin $BRANCH - gh label create "$LABEL" \ - --description "Pull requests with release changelog update" \ - --force \ - || true + gh label create "$LABEL" \ + --description "Pull requests with release changelog update" \ + --force \ + || true - gh pr create \ - --title "Changelog update - \`$VERSION\`" \ - --body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \ - --label "$LABEL" \ - --head $BRANCH + gh pr create \ + --title "Changelog update - \`$VERSION\`" \ + --body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \ + --label "$LABEL" \ + --head $BRANCH From c9f21c88e47036ca297ba1a257e4aa3f6068fbbd Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:04:17 -0700 Subject: [PATCH 057/186] on tag --- .github/workflows/jetbrains-release.yaml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index d7228bf9d..32e45d3be 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -5,10 +5,9 @@ name: Release on: - push: - # create: - # tags: - # - "v0.0.*-jetbrains" + create: + tags: + - "v0.0.*-jetbrains" branches: - nate/apple-developer-finally From 4ea218d854dd73809fa77cf6b161def11587efa0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:04:57 -0700 Subject: [PATCH 058/186] delete jetbrains-build --- .github/workflows/jetbrains-build.yaml | 476 ------------------------- 1 file changed, 476 deletions(-) delete mode 100644 .github/workflows/jetbrains-build.yaml diff --git a/.github/workflows/jetbrains-build.yaml b/.github/workflows/jetbrains-build.yaml deleted file mode 100644 index b23094106..000000000 --- a/.github/workflows/jetbrains-build.yaml +++ /dev/null @@ -1,476 +0,0 @@ -# GitHub Actions Workflow is created for testing and preparing the plugin release in the following steps: -# - Validate Gradle Wrapper. -# - Run 'test' and 'verifyPlugin' tasks. -# - Run Qodana inspections. -# - Run the 'buildPlugin' task and prepare artifact for further tests. -# - Run the 'runPluginVerifier' task. -# - Create a draft release. -# -# The workflow is triggered on push and pull_request events. -# -# GitHub Actions reference: https://help.github.com/en/actions -# -## JBIJPPTPL - -name: Build -# on: -# # Trigger the workflow on pushes to only the 'main' branch (this avoids duplicate checks being run e.g., for dependabot pull requests) -# push: -# branches: [main, preview] -# Trigger the workflow on any pull request -# pull_request: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -defaults: - run: - working-directory: ./extensions/intellij - -jobs: - # Prepare environment and build the plugin - build: - name: Build - runs-on: macos-latest - outputs: - version: ${{ steps.properties.outputs.version }} - changelog: ${{ steps.properties.outputs.changelog }} - pluginVerifierHomeDir: ${{ steps.properties.outputs.pluginVerifierHomeDir }} - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Validate wrapper - - name: Gradle Wrapper Validation - uses: gradle/actions/wrapper-validation@v3 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Set environment variables - - name: Export Properties - id: properties - shell: bash - run: | - PROPERTIES="$(./gradlew properties --console=plain -q)" - VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" - # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" - CHANGELOG="" - - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT - - echo "changelog<> $GITHUB_OUTPUT - echo "$CHANGELOG" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT - - ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier - - # Setup Node.js - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - # Cache node_modules - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - # npm install core - - name: Install core node_modules - run: | - cd ../../core - npm ci - - # npm install binary - - name: Install binary node_modules - run: | - cd ../../binary - npm ci - - # npm install gui - - name: Install gui node_modules - run: | - cd ../../gui - npm ci - - # build gui - - name: Build gui - run: | - cd ../../gui - npm run build - - # Run prepackage.js script - - name: Run prepackage script - run: | - cd ../../extensions/vscode - npm ci - npm run prepackage - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - # Build binaries - - name: Build the binaries - run: | - cd ../../binary - npm run build - - # Build plugin - - name: Build plugin - run: ./gradlew buildPlugin - - # Prepare plugin archive content for creating artifact - - name: Prepare Plugin Artifact - id: artifact - shell: bash - run: | - cd ../../extensions/intellij/build/distributions - FILENAME=`ls *.zip` - unzip "$FILENAME" -d content - - echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT - - # Store already-built plugin as an artifact for downloading - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: ${{ steps.artifact.outputs.filename }} - path: ./extensions/intellij/build/distributions/content/*/* - - # Upload binaries as artifacts - - name: Upload artifact (darwin-arm64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-arm64 - path: ./binary/bin/darwin-arm64/ - - - name: Upload artifact (darwin-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-x64 - path: ./binary/bin/darwin-x64/ - - - name: Upload artifact (win32-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-win32-x64 - path: ./binary/bin/win32-x64/ - - - name: Upload artifact (linux-arm64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-linux-arm64 - path: ./binary/bin/linux-arm64/ - - - name: Upload artifact (linux-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-linux-x64 - path: ./binary/bin/linux-x64/ - - test-binaries: - needs: build - strategy: - matrix: - include: - - os: windows-latest - platform: win32 - arch: x64 - npm_config_arch: x64 - - os: ubuntu-latest - platform: linux - arch: x64 - npm_config_arch: x64 - # arm64 not actually supported by GitHub - # - os: ubuntu-latest - # platform: linux - # arch: arm64 - # npm_config_arch: arm64 - - os: macos-12 - platform: darwin - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: arm64 - npm_config_arch: arm64 - runs-on: ${{ matrix.os }} - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - # 2. Install npm dependencies - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache binary node_modules - uses: actions/cache@v3 - with: - path: binary/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - - name: Install Core Dependencies - run: | - cd ../../core - npm ci - - - name: Install Binary Dependencies - run: | - cd ../../binary - npm ci - - # Download the binary artifact - - name: Download binary artifact - uses: actions/download-artifact@v4 - with: - name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }} - path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/ - - # Set execute permissions for the binary (non-Windows) - - name: Set execute permissions - run: | - cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }} - chmod +x continue-binary - chmod +x node_sqlite3.node - chmod +x index.node - chmod +x esbuild - if: ${{ matrix.platform }} != 'win32' - - - name: Copy node_sqlite3.node to necessary location - run: | - cd ../../binary - mkdir build - cp ./bin/${{ matrix.platform }}-${{ matrix.arch }}/node_sqlite3.node ./build/node_sqlite3.node - - # Run tests for binary - - name: Run binary tests - run: | - cd ../../binary - npm run test - - - name: Upload logs - if: ${{ always() }} - uses: actions/upload-artifact@v2 - with: - name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} - path: binary/.continue/logs/core.log - - # Run tests and upload a code coverage report - test: - name: Test - needs: [build] - runs-on: ubuntu-latest - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Run tests - - name: Run Tests - run: ./gradlew check - - # Collect Tests Result of failed tests - - name: Collect Tests Result - if: ${{ failure() }} - uses: actions/upload-artifact@v4 - with: - name: tests-result - path: ${{ github.workspace }}/extensions/intellij/build/reports/tests - - # Upload the Kover report to CodeCov - # - name: Upload Code Coverage Report - # uses: codecov/codecov-action@v4 - # with: - # files: ${{ github.workspace }}/build/reports/kover/report.xml - - # Run Qodana inspections and provide report - inspectCode: - if: false - name: Inspect code - needs: [build] - runs-on: ubuntu-latest - permissions: - contents: write - checks: write - pull-requests: write - steps: - # Free GitHub Actions Environment Disk Space - - name: Maximize Build Space - uses: jlumbroso/free-disk-space@main - with: - tool-cache: false - large-packages: false - - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Run Qodana inspections - - name: Qodana - Code Inspection - uses: JetBrains/qodana-action@v2024.1.5 - with: - cache-default-branch-only: true - - # Run plugin structure verification along with IntelliJ Plugin Verifier - verify: - name: Verify plugin - needs: [build] - runs-on: ubuntu-latest - steps: - # Free GitHub Actions Environment Disk Space - - name: Maximize Build Space - uses: jlumbroso/free-disk-space@main - with: - tool-cache: false - large-packages: false - - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 - - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true - - # Cache Plugin Verifier IDEs - - name: Setup Plugin Verifier IDEs Cache - uses: actions/cache@v4 - with: - path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides - key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }} - - # Run Verify Plugin task and IntelliJ Plugin Verifier tool - - name: Run Plugin Verification tasks - run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }} - - # Collect Plugin Verifier Result - - name: Collect Plugin Verifier Result - if: ${{ always() }} - uses: actions/upload-artifact@v4 - with: - name: pluginVerifier-result - path: ${{ github.workspace }}/build/reports/pluginVerifier - - # Prepare a draft release for GitHub Releases page for the manual verification - # If accepted and published, release workflow would be triggered - releaseDraft: - name: Release draft - if: github.event_name != 'pull_request' - needs: [build, test, test-binaries, verify] - runs-on: ubuntu-latest - permissions: - contents: write - steps: - # Check out current repository - - name: Fetch Sources - uses: actions/checkout@v4 - - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - - - name: Tag the repository - id: tag - run: | - # See https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names - TAG=v${{ needs.build.outputs.version }}-jetbrains - echo "$TAG" - echo "tag=$TAG" >> $GITHUB_OUTPUT - git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA} - git push origin $TAG - - # Remove old release drafts by using the curl request for the available releases with a draft flag - - name: Remove Old Release Drafts - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh api repos/{owner}/{repo}/releases \ - --jq '.[] | select(.draft == true) | .id' \ - | xargs -I '{}' gh api -X DELETE repos/{owner}/{repo}/releases/{} - - # Create a new release draft which is not publicly visible and requires manual acceptance - - name: Create Release Draft - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh release create "${{ steps.tag.outputs.tag }}" \ - --draft \ - --title "v${{ needs.build.outputs.version }}-jetbrains" \ - --notes "$(cat << 'EOM' - ${{ needs.build.outputs.changelog }} - EOM - )" - - # Download the Gradle build artifact - - name: Download Gradle build artifact - uses: actions/download-artifact@v4 - with: - name: ${{ needs.build.outputs.filename }} - path: ./artifacts From 11f6c9b18d4908c026153db15b93597827a797f5 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:07:07 -0700 Subject: [PATCH 059/186] set runs-on --- .github/workflows/jetbrains-release.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 32e45d3be..578de0786 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -425,6 +425,7 @@ jobs: path: ${{ github.workspace }}/build/reports/pluginVerifier upload-release: + runs-on: ubuntu-latest steps: # # Update Unreleased section with the current release note # - name: Patch Changelog From 26cc5342301933c39608b0128c5bd38cfb4c31e9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:09:01 -0700 Subject: [PATCH 060/186] release -> build --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 578de0786..439c624fd 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -34,7 +34,7 @@ jobs: fi # Prepare and publish the plugin to JetBrains Marketplace repository - release: + build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' name: Publish Plugin From 6e966488b270a19c0a28f2f485c1ac0363492b26 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:23:13 -0700 Subject: [PATCH 061/186] update triggers --- .github/workflows/jetbrains-release.yaml | 9 ++++----- .github/workflows/main.yaml | 2 +- .github/workflows/preview.yaml | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 439c624fd..955de0d44 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -5,16 +5,15 @@ name: Release on: - create: - tags: - - "v0.0.*-jetbrains" - branches: - - nate/apple-developer-finally + release: + types: [prereleased] defaults: run: working-directory: ./extensions/intellij +if: ${{ startsWith(github.event.release.tag_name, 'v') }} + concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 3591d3e23..74e2cdc25 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -1,7 +1,7 @@ name: Publish Extension on: - create: + push: tags: - "v0.8.*-vscode" branches: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index aea470286..40f61c3e3 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,7 +1,7 @@ name: Publish Preview Extension on: - create: + push: tags: - "v0.9.*-vscode" branches: From 778e6df85fb889f856624acd06433c179e42dcb5 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 12:30:04 -0700 Subject: [PATCH 062/186] correct if statement --- .github/workflows/jetbrains-release.yaml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 955de0d44..606f328ed 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -12,8 +12,6 @@ defaults: run: working-directory: ./extensions/intellij -if: ${{ startsWith(github.event.release.tag_name, 'v') }} - concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true @@ -26,7 +24,7 @@ jobs: steps: - id: check run: | - if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then + if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT From 8cdb68c6d646893902dace76a158cb1157e79b3c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 15 Aug 2024 13:38:15 -0700 Subject: [PATCH 063/186] update tests --- core/indexing/CodeSnippetsIndex.ts | 54 ++++++------- core/indexing/FullTextSearch.ts | 11 +-- core/indexing/LanceDbIndex.ts | 66 ++++++++-------- core/indexing/chunk/ChunkCodebaseIndex.ts | 11 ++- core/jest.config.js | 1 + core/jest.global-setup.ts | 3 - core/jest.setup-after-env.ts | 15 ++++ core/package.json | 2 +- core/test/indexing/ChunkCodebaseIndex.test.ts | 55 ++++++-------- core/test/indexing/CodeSnippetsIndex.test.ts | 75 ++++++------------- .../FullTextSearchCodebaseIndex.test.ts | 54 +++++-------- core/test/indexing/LanceDbIndex.test.ts | 72 +++++++++--------- core/util/paths.ts | 4 + 13 files changed, 189 insertions(+), 234 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index f16c5137a..4dd56e4c2 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -17,6 +17,7 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { IndexResultType, MarkCompleteCallback, + PathAndCacheKey, RefreshIndexResults, type CodebaseIndex, } from "./types.js"; @@ -182,47 +183,38 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Delete for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; - const deleted = await db.run( - "DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?", + + const snippetToDelete = await db.get( + "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ - deleted.lastID, + + await db.run("DELETE FROM code_snippets WHERE id = ?", [ + snippetToDelete.id, ]); + + await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ + snippetToDelete.id, + ]); + markComplete([del], IndexResultType.Delete); } // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; - let snippets: (ChunkWithoutID & { title: string })[] = []; - try { - snippets = await this.getSnippetsInFile( - addTag.path, - await this.ide.readFile(addTag.path), - ); - } catch (e) { - // If can't parse, assume malformatted code - console.error(`Error parsing ${addTag.path}:`, e); - } - for (const snippet of snippets) { - const { lastID } = await db.run( - "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", - [ - addTag.path, - addTag.cacheKey, - snippet.content, - snippet.title, - snippet.startLine, - snippet.endLine, - ], - ); - await db.run( - "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", - [lastID, tagString], - ); - } + await db.run( + ` + REPLACE INTO code_snippets_tags (tag, snippetId) + SELECT ?, ( + SELECT id + FROM code_snippets + WHERE cacheKey = ? AND path = ? + ) + `, + [tagString, addTag.cacheKey, addTag.path], + ); markComplete([results.addTag[i]], IndexResultType.AddTag); } diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts index 982886d45..9ece3ff6e 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearch.ts @@ -91,11 +91,12 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const { lastID } = await db.run( - "DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", - [item.path, item.cacheKey], - ); - await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]); + await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ + item.path, + item.cacheKey, + ]); + + await db.run("DELETE FROM fts WHERE path = ?", [item.path]); markComplete([item], IndexResultType.Delete); } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 3f0b3a3bc..df8acb53c 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -21,6 +21,7 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; +import lance from "vectordb"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { @@ -48,7 +49,7 @@ export class LanceDbIndex implements CodebaseIndex { private readonly continueServerClient?: IContinueServerClient, ) {} - private tableNameForTag(tag: IndexTag) { + tableNameForTag(tag: IndexTag) { return tagToString(tag).replace(/[^\w-_.]/g, ""); } @@ -203,36 +204,35 @@ export class LanceDbIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { - const lancedb = await import("vectordb"); - const tableName = this.tableNameForTag(tag); - const db = await lancedb.connect(getLanceDbPath()); + const sqliteDb = await SqliteDb.get(); + await this.createSqliteCacheTable(sqliteDb); - const sqlite = await SqliteDb.get(); - await this.createSqliteCacheTable(sqlite); + const lanceTableName = this.tableNameForTag(tag); + const lanceDb = await lance.connect(getLanceDbPath()); + const existingLanceTables = await lanceDb.tableNames(); + + let lanceTable: Table | undefined = undefined; + let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName); // Compute - let table: Table | undefined = undefined; - const existingTables = await db.tableNames(); - let needToCreateTable = !existingTables.includes(tableName); - const addComputedLanceDbRows = async ( pathAndCacheKey: PathAndCacheKey, computedRows: LanceDbRow[], ) => { // Create table if needed, add computed rows - if (table) { + if (lanceTable) { if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } - } else if (existingTables.includes(tableName)) { - table = await db.openTable(tableName); - needToCreateTable = false; + } else if (existingLanceTables.includes(lanceTableName)) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } } else if (computedRows.length > 0) { - table = await db.createTable(tableName, computedRows); - needToCreateTable = false; + lanceTable = await lanceDb.createTable(lanceTableName, computedRows); + needToCreateLanceTable = false; } // Mark item complete @@ -272,7 +272,7 @@ export class LanceDbIndex implements CodebaseIndex { }; rows.push(row); - await sqlite.run( + await sqliteDb.run( "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row.uuid, row.cachekey, @@ -306,13 +306,13 @@ export class LanceDbIndex implements CodebaseIndex { }; const dbRows = await this.computeRows(results.compute); - await this.insertRows(sqlite, dbRows); + await this.insertRows(sqliteDb, dbRows); await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { - const stmt = await sqlite.prepare( + const stmt = await sqliteDb.prepare( "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, @@ -330,15 +330,15 @@ export class LanceDbIndex implements CodebaseIndex { }); if (lanceRows.length > 0) { - if (needToCreateTable) { - table = await db.createTable(tableName, lanceRows); - needToCreateTable = false; - } else if (!table) { - table = await db.openTable(tableName); - needToCreateTable = false; - await table.add(lanceRows); + if (needToCreateLanceTable) { + lanceTable = await lanceDb.createTable(lanceTableName, lanceRows); + needToCreateLanceTable = false; + } else if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; + await lanceTable.add(lanceRows); } else { - await table?.add(lanceRows); + await lanceTable?.add(lanceRows); } } @@ -352,11 +352,13 @@ export class LanceDbIndex implements CodebaseIndex { } // Delete or remove tag - remove from lance table) - if (!needToCreateTable) { + if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; for (const { path, cacheKey } of toDel) { // This is where the aforementioned lowercase conversion problem shows - await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); + await lanceTable?.delete( + `cachekey = '${cacheKey}' AND path = '${path}'`, + ); accumulatedProgress += 1 / toDel.length / 3; yield { @@ -370,7 +372,7 @@ export class LanceDbIndex implements CodebaseIndex { // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { - await sqlite.run( + await sqliteDb.run( "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 671ce31e6..b7e239eea 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -117,13 +117,16 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [ - item.cacheKey, - ]); + const chunkToDelete = await db.get( + "SELECT id FROM chunks WHERE cacheKey = ?", + [item.cacheKey], + ); + + await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); // Delete from chunk_tags await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ - deleted.lastID, + chunkToDelete.id, ]); await markComplete([item], IndexResultType.Delete); diff --git a/core/jest.config.js b/core/jest.config.js index 2567c5891..5fa08c29a 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import path from "path"; import { fileURLToPath } from "url"; diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index cf374a702..1f548c57b 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -3,7 +3,4 @@ import path from "path"; export default async function () { process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); - if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { - fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); - } } diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index d4b86824a..200b7a98c 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -2,6 +2,7 @@ import { TextEncoder, TextDecoder } from "util"; import fetch, { Request, Response } from "node-fetch"; import { jest } from "@jest/globals"; +import fs from "fs"; if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); @@ -14,3 +15,17 @@ globalThis.Request = Request; globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; + +global.beforeAll(() => { + // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { + fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); + } +}); + +global.afterAll(() => { + // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { + fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); + } +}); diff --git a/core/package.json b/core/package.json index 39c8246ef..66c228cba 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", "lint:fix": "eslint . --ext ts --fix" diff --git a/core/test/indexing/ChunkCodebaseIndex.test.ts b/core/test/indexing/ChunkCodebaseIndex.test.ts index 3c8693beb..bb3208345 100644 --- a/core/test/indexing/ChunkCodebaseIndex.test.ts +++ b/core/test/indexing/ChunkCodebaseIndex.test.ts @@ -18,6 +18,14 @@ describe("ChunkCodebaseIndex", () => { let index: ChunkCodebaseIndex; let db: DatabaseConnection; + async function getAllChunks() { + return await db.all("SELECT * FROM chunks"); + } + + async function getAllChunkTags() { + return await db.all("SELECT * FROM chunk_tags"); + } + beforeAll(async () => { const pathSep = await testIde.pathSep(); @@ -40,54 +48,33 @@ describe("ChunkCodebaseIndex", () => { // Compute test await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); - - const computeResult = await db.get( - "SELECT * FROM chunks WHERE cacheKey = ?", - [mockPathAndCacheKey.cacheKey], - ); - - expect(computeResult).toBeTruthy(); + expect((await getAllChunks()).length).toBe(1); + expect((await getAllChunkTags()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Compute, ); - // AddTag test - await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); - - const addTagResult = await db.get( - "SELECT * FROM chunk_tags WHERE chunkId = ?", - [computeResult.id], - ); - - expect(addTagResult).toBeTruthy(); - expect(mockMarkComplete).toHaveBeenCalledWith( - [mockPathAndCacheKey], - IndexResultType.AddTag, - ); - // RemoveTag test await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); - - const removeTagResult = await db.get( - "SELECT * FROM chunk_tags WHERE id = ?", - [addTagResult.id], - ); - - expect(removeTagResult).toBeFalsy(); + expect((await getAllChunkTags()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.RemoveTag, ); + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect((await getAllChunkTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + // Delete test await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); - - const delResult = await db.get("SELECT * FROM chunks WHERE id = ?", [ - computeResult.id, - ]); - - expect(delResult).toBeFalsy(); + expect((await getAllChunks()).length).toBe(0); + expect((await getAllChunkTags()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Delete, diff --git a/core/test/indexing/CodeSnippetsIndex.test.ts b/core/test/indexing/CodeSnippetsIndex.test.ts index 2eabaa93f..919f5d294 100644 --- a/core/test/indexing/CodeSnippetsIndex.test.ts +++ b/core/test/indexing/CodeSnippetsIndex.test.ts @@ -14,12 +14,20 @@ describe("CodeSnippetsCodebaseIndex", () => { let index: CodeSnippetsCodebaseIndex; let db: DatabaseConnection; - beforeEach(async () => { + async function getAllSnippets() { + return await db.all("SELECT * FROM code_snippets"); + } + + async function getAllSnippetTags() { + return await db.all("SELECT * FROM code_snippets_tags"); + } + + beforeAll(async () => { db = await SqliteDb.get(); index = new CodeSnippetsCodebaseIndex(testIde); }); - it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + it("should update the index and maintain expected database state", async () => { const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; @@ -41,75 +49,36 @@ describe("CodeSnippetsCodebaseIndex", () => { // Compute test await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); - - const computeResult = await db.get( - "SELECT * FROM code_snippets WHERE path = ?", - [mockPathAndCacheKey.path], - ); - - const computeResultTags = await db.get( - "SELECT * FROM code_snippets_tags WHERE snippetId = ?", - [computeResult.id], - ); - - expect(computeResult).toBeTruthy(); - expect(computeResultTags).toBeTruthy(); + expect((await getAllSnippetTags()).length).toBe(1); + expect((await getAllSnippets()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Compute, ); - // Delete test - await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); - - const delResult = await db.get("SELECT * FROM code_snippets WHERE id = ?", [ - computeResult.id, - ]); - - const delResultTags = await db.get( - "SELECT * FROM code_snippets_tags WHERE id = ?", - [computeResultTags.id], - ); - - expect(delResult).toBeFalsy(); - expect(delResultTags).toBeFalsy(); + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], - IndexResultType.Delete, + IndexResultType.RemoveTag, ); // AddTag test await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); - - const addTagResult = await db.get( - "SELECT * FROM code_snippets WHERE path = ?", - [mockPathAndCacheKey.path], - ); - - const addTagResultTags = await db.get( - "SELECT * FROM code_snippets_tags WHERE snippetId = ?", - [addTagResult.id], - ); - - expect(addTagResult).toBeTruthy(); - expect(addTagResultTags).toBeTruthy(); + expect((await getAllSnippetTags()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.AddTag, ); - // RemoveTag test - await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); - - const removeTagResultTag = await db.get( - "SELECT * FROM code_snippets_tags WHERE id = ?", - [addTagResultTags.id], - ); - - expect(removeTagResultTag).toBeFalsy(); + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(0); + expect((await getAllSnippets()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], - IndexResultType.RemoveTag, + IndexResultType.Delete, ); }); }); diff --git a/core/test/indexing/FullTextSearchCodebaseIndex.test.ts b/core/test/indexing/FullTextSearchCodebaseIndex.test.ts index cb27ee920..4822626e8 100644 --- a/core/test/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/test/indexing/FullTextSearchCodebaseIndex.test.ts @@ -13,12 +13,20 @@ describe("FullTextSearchCodebaseIndex", () => { let index: FullTextSearchCodebaseIndex; let db: DatabaseConnection; + async function getFts() { + return await db.all("SELECT * FROM fts"); + } + + async function getFtsMetadata() { + return await db.all("SELECT * FROM fts_metadata"); + } + beforeEach(async () => { db = await SqliteDb.get(); index = new FullTextSearchCodebaseIndex(); }); - it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + it("should update the index and maintain expected database state", async () => { const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; @@ -27,53 +35,31 @@ describe("FullTextSearchCodebaseIndex", () => { // Compute test await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); - - const computeResult = await db.get("SELECT * FROM fts WHERE path = ?", [ - mockPathAndCacheKey.path, - ]); - - const computeResultMetadata = await db.get( - "SELECT * FROM fts_metadata WHERE path = ?", - [mockPathAndCacheKey.path], - ); - - expect(computeResult).toBeTruthy(); - expect(computeResultMetadata).toBeTruthy(); + expect((await getFts()).length).toBe(1); + expect((await getFtsMetadata()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Compute, ); - // AddTag test - currently, we don't do anything other than mark complete - await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); - - expect(mockMarkComplete).toHaveBeenCalledWith( - [mockPathAndCacheKey], - IndexResultType.AddTag, - ); - // RemoveTag test - currently, we don't do anything other than mark complete await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); - expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.RemoveTag, ); - // Delete test - await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); - - const delResult = await db.get("SELECT * FROM fts WHERE path = ?", [ - mockPathAndCacheKey.cacheKey, - ]); - - const delResultMetadata = await db.get( - "SELECT * FROM fts_metadata WHERE path = ?", - [mockPathAndCacheKey.path], + // AddTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, ); - expect(delResult).toBeFalsy(); - expect(delResultMetadata).toBeFalsy(); + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getFts()).length).toBe(0); + expect((await getFtsMetadata()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Delete, diff --git a/core/test/indexing/LanceDbIndex.test.ts b/core/test/indexing/LanceDbIndex.test.ts index 1cf1ec800..e6ebd3eb6 100644 --- a/core/test/indexing/LanceDbIndex.test.ts +++ b/core/test/indexing/LanceDbIndex.test.ts @@ -1,91 +1,89 @@ -import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; import { IndexResultType } from "../../indexing/types"; import { testIde } from "../fixtures"; -import { addToTestDir } from "../testUtils/testDir"; import { jest } from "@jest/globals"; import { + insertMockChunks, + mockPathAndCacheKey, + mockTag, testContinueServerClient, updateIndexAndAwaitGenerator, } from "./utils"; import { LanceDbIndex } from "../../indexing/LanceDbIndex"; +import { testConfigHandler } from "../fixtures"; +import lance from "vectordb"; +import { getLanceDbPath } from "../../util/paths"; jest.useFakeTimers(); describe("ChunkCodebaseIndex", () => { - let index: ChunkCodebaseIndex; - let db: DatabaseConnection; + let index: LanceDbIndex; + let sqliteDb: DatabaseConnection; + let lanceDb: lance.Connection; + let lanceTableName: string; + + async function getAllSqliteLanceDbCache() { + return await sqliteDb.all("SELECT * FROM lance_db_cache"); + } beforeAll(async () => { const pathSep = await testIde.pathSep(); + const mockConfig = await testConfigHandler.loadConfig(); index = new LanceDbIndex( - undefined, + mockConfig.embeddingsProvider, testIde.readFile.bind(testIde), pathSep, testContinueServerClient, ); - addToTestDir([[mockFilename, mockFileContents]]); - - db = await SqliteDb.get(); + sqliteDb = await SqliteDb.get(); + lanceDb = await lance.connect(getLanceDbPath()); + lanceTableName = index.tableNameForTag(mockTag); }); - it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + it("should update the index and maintain expected database state", async () => { const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; - // Compute test + await insertMockChunks(); + + // Compute test - only inserts into Sqlite await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); - const computeResult = await db.get( - "SELECT * FROM chunks WHERE cacheKey = ?", - [mockPathAndCacheKey.cacheKey], - ); - - expect(computeResult).toBeTruthy(); + expect((await getAllSqliteLanceDbCache()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Compute, ); - // AddTag test + // AddTag test - only inserts into Lance DB await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); - const addTagResult = await db.get( - "SELECT * FROM chunk_tags WHERE chunkId = ?", - [computeResult.id], - ); + // Note that we must wait until the first call 'addTag' result has been processed. + // The current functionality of the `update` function doesn't insert into the Lance DB + // table until this point. We need to wait for this event to avoid needing to create a + // mock embedding to instantiate the table with. + const table = await lanceDb.openTable(lanceTableName); - expect(addTagResult).toBeTruthy(); + expect(await table.countRows()).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.AddTag, ); - // RemoveTag test + // // RemoveTag test - only removes from Lance DB await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); - - const removeTagResult = await db.get( - "SELECT * FROM chunk_tags WHERE id = ?", - [addTagResult.id], - ); - - expect(removeTagResult).toBeFalsy(); + expect(await table.countRows()).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.RemoveTag, ); - // Delete test + // Delete test - only removes from Sqlite await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); - - const delResult = await db.get("SELECT * FROM chunks WHERE id = ?", [ - computeResult.id, - ]); - - expect(delResult).toBeFalsy(); + expect((await getAllSqliteLanceDbCache()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.Delete, diff --git a/core/util/paths.ts b/core/util/paths.ts index 7c208f92c..7a6ed8831 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -200,6 +200,10 @@ export async function migrate( callback: () => void | Promise, onAlreadyComplete?: () => void, ) { + if (process.env.NODE_ENV === "test") { + return await Promise.resolve(callback()); + } + const migrationsPath = getMigrationsFolderPath(); const migrationPath = path.join(migrationsPath, id); From b67fbe1749ccbf79c6a086fa8593680a406054f0 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 15 Aug 2024 17:08:54 -0700 Subject: [PATCH 064/186] update tests --- core/indexing/LanceDbIndex.ts | 37 ++++++++------ core/indexing/README.md | 4 +- core/test/indexing/LanceDbIndex.test.ts | 67 +++++++++++++++++-------- core/test/indexing/utils.ts | 14 ++++-- 4 files changed, 78 insertions(+), 44 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 615769bd6..3890e7db8 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -310,8 +310,8 @@ export class LanceDbIndex implements CodebaseIndex { await this.insertRows(sqliteDb, dbRows); await Promise.all( - results.compute.map((result) => { - addComputedLanceDbRows( + results.compute.map(async (result) => { + await addComputedLanceDbRows( result, dbRows.filter( (row) => @@ -335,14 +335,17 @@ export class LanceDbIndex implements CodebaseIndex { ); const cachedItems = await stmt.all(); - const lanceRows: LanceDbRow[] = cachedItems.map((item) => { - return { + const lanceRows: LanceDbRow[] = cachedItems.map( + ({ uuid, vector, startLine, endLine, contents }) => ({ path, + uuid, + startLine, + endLine, + contents, cachekey: cacheKey, - uuid: item.uuid, - vector: JSON.parse(item.vector), - }; - }); + vector: JSON.parse(vector), + }), + ); if (lanceRows.length > 0) { if (needToCreateLanceTable) { @@ -369,9 +372,14 @@ export class LanceDbIndex implements CodebaseIndex { // Delete or remove tag - remove from lance table) if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; + + if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + } + for (const { path, cacheKey } of toDel) { // This is where the aforementioned lowercase conversion problem shows - await lanceTable?.delete( + await lanceTable.delete( `cachekey = '${cacheKey}' AND path = '${path}'`, ); @@ -383,6 +391,7 @@ export class LanceDbIndex implements CodebaseIndex { }; } } + await markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache @@ -402,6 +411,7 @@ export class LanceDbIndex implements CodebaseIndex { } await markComplete(results.del, IndexResultType.Delete); + yield { progress: 1, desc: "Completed Calculating Embeddings", @@ -423,8 +433,7 @@ export class LanceDbIndex implements CodebaseIndex { return []; } - const table = await db.openTable(tableName); - let query = table.search(vector); + let query = db.search(vector); if (directory) { // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after query = query.where(`path LIKE '${directory}%'`).limit(300); @@ -441,12 +450,8 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { - const lancedb = await import("vectordb"); - if (!lancedb.connect) { - throw new Error("LanceDB failed to load a native module"); - } const [vector] = await this.embeddingsProvider.embed([query]); - const db = await lancedb.connect(getLanceDbPath()); + const db = await lance.connect(getLanceDbPath()); let allResults = []; for (const tag of tags) { diff --git a/core/indexing/README.md b/core/indexing/README.md index b0f8d408a..2a7375f00 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -23,8 +23,8 @@ All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./ `CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 `ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` -`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite +`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. -## Known problems: +## Known problems - `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table diff --git a/core/test/indexing/LanceDbIndex.test.ts b/core/test/indexing/LanceDbIndex.test.ts index a4bff4de8..89baf737b 100644 --- a/core/test/indexing/LanceDbIndex.test.ts +++ b/core/test/indexing/LanceDbIndex.test.ts @@ -3,7 +3,6 @@ import { IndexResultType } from "../../indexing/types"; import { testIde } from "../fixtures"; import { jest } from "@jest/globals"; import { - insertMockChunks, mockPathAndCacheKey, mockTag, testContinueServerClient, @@ -20,7 +19,6 @@ describe("ChunkCodebaseIndex", () => { let index: LanceDbIndex; let sqliteDb: DatabaseConnection; let lanceDb: lance.Connection; - let lanceTableName: string; async function getAllSqliteLanceDbCache() { return await sqliteDb.all("SELECT * FROM lance_db_cache"); @@ -39,26 +37,38 @@ describe("ChunkCodebaseIndex", () => { sqliteDb = await SqliteDb.get(); lanceDb = await lance.connect(getLanceDbPath()); - lanceTableName = index.tableNameForTag(mockTag); }); + /** + * Some notes on quirks of this test: + * - Currently, it appears that there is a race condition in LanceDB that + * requires us to re-open the table connection each time we want to read + * from it. Attempting to follow these docs did not resolve the issue: + * https://lancedb.github.io/lancedb/guides/tables/#consistency + * + * - We cannot open either the 'dev' or 'main' tag tables ubtil after we + * can assume they've been created through `updateIndexAndAwaitGenerator` + */ it("should update the index and maintain expected database state", async () => { + const mainTag = mockTag; + const mainTagTableName = index.tableNameForTag(mainTag); + + const devTag = { ...mockTag, branch: "dev" }; + const devTagTableName = index.tableNameForTag(devTag); + const mockMarkComplete = jest .fn() .mockImplementation(() => Promise.resolve()) as any; - await insertMockChunks(); - // Compute test - inserts into both LanceDB and Sqlite - await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); - - // Note that we must wait until the first call 'compute' result has been processed. - // The current functionality of the `update` function doesn't insert into the Lance DB - // table until this point. We need to wait for this event to avoid needing to create a - // mock embedding to instantiate the table with. - const table = await lanceDb.openTable(lanceTableName); - - expect(await table.countRows()).toBe(1); + await updateIndexAndAwaitGenerator( + index, + "compute", + mockMarkComplete, + mainTag, + ); + let mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(1); expect((await getAllSqliteLanceDbCache()).length).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], @@ -66,24 +76,37 @@ describe("ChunkCodebaseIndex", () => { ); // AddTag test - only inserts into Lance DB - await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); - - expect(await table.countRows()).toBe(1); + await updateIndexAndAwaitGenerator( + index, + "addTag", + mockMarkComplete, + devTag, + ); + let devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(1); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.AddTag, ); - // // RemoveTag test - only removes from Lance DB - await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); - expect(await table.countRows()).toBe(1); + // RemoveTag - only removes from Lance DB + await updateIndexAndAwaitGenerator( + index, + "removeTag", + mockMarkComplete, + devTag, + ); + devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], IndexResultType.RemoveTag, ); - // Delete test - only removes from Sqlite - await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + // Delete test - removes from LanceDB and Sqlite + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete, mainTag); + mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(0); expect((await getAllSqliteLanceDbCache()).length).toBe(0); expect(mockMarkComplete).toHaveBeenCalledWith( [mockPathAndCacheKey], diff --git a/core/test/indexing/utils.ts b/core/test/indexing/utils.ts index e79a79b27..670617c74 100644 --- a/core/test/indexing/utils.ts +++ b/core/test/indexing/utils.ts @@ -3,7 +3,11 @@ import { IContinueServerClient } from "../../continueServer/interface"; import { testIde } from "../fixtures"; import { addToTestDir, TEST_DIR } from "../testUtils/testDir"; import { IndexTag } from "../.."; -import { CodebaseIndex, RefreshIndexResults } from "../../indexing/types"; +import { + CodebaseIndex, + PathAndCacheKey, + RefreshIndexResults, +} from "../../indexing/types"; import { jest } from "@jest/globals"; import { tagToString } from "../../indexing/refreshIndex"; @@ -12,6 +16,7 @@ export const mockPathAndCacheKey = { path: `${TEST_DIR}/${mockFilename}`, cacheKey: "abc123", }; + export const mockFileContents = `\ def main(): print("Hello, world!") @@ -69,12 +74,13 @@ export async function insertMockChunks() { export async function updateIndexAndAwaitGenerator( index: CodebaseIndex, resultType: keyof RefreshIndexResults, - mockMarkComplete: any, + markComplete: any, + tag: IndexTag = mockTag, ) { const computeGenerator = index.update( - mockTag, + tag, { ...mockResults, [resultType]: [mockPathAndCacheKey] }, - mockMarkComplete, + markComplete, "test-repo", ); From 0b6522f13499ef8dace93be50e205fc6b45a1763 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Aug 2024 17:39:22 -0700 Subject: [PATCH 065/186] fix lancedb indexing bug --- core/indexing/LanceDbIndex.ts | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 12f8b1668..13a07c54d 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -216,7 +216,7 @@ export class LanceDbIndex implements CodebaseIndex { let needToCreateTable = !existingTables.includes(tableName); const addComputedLanceDbRows = async ( - pathAndCacheKey: PathAndCacheKey, + pathAndCacheKeys: PathAndCacheKey[], computedRows: LanceDbRow[], ) => { // Create table if needed, add computed rows @@ -236,7 +236,7 @@ export class LanceDbIndex implements CodebaseIndex { } // Mark item complete - await markComplete([pathAndCacheKey], IndexResultType.Compute); + await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; // Check remote cache @@ -285,7 +285,7 @@ export class LanceDbIndex implements CodebaseIndex { ); } - await addComputedLanceDbRows({ cacheKey, path }, rows); + await addComputedLanceDbRows([{ cacheKey, path }], rows); } // Remove items that don't need to be recomputed @@ -307,18 +307,7 @@ export class LanceDbIndex implements CodebaseIndex { const dbRows = await this.computeRows(results.compute); await this.insertRows(sqlite, dbRows); - await Promise.all( - results.compute.map((result) => { - addComputedLanceDbRows( - result, - dbRows.filter( - (row) => - row.path === result.path && row.cachekey === result.cacheKey, - ), - ); - }), - ); - await markComplete(results.compute, IndexResultType.Compute); + await addComputedLanceDbRows(results.compute, dbRows); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache From 76e7059c9289e56b020c8131a5544db6c5c9b627 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 15 Aug 2024 17:43:44 -0700 Subject: [PATCH 066/186] update jest config --- core/jest.global-setup.ts | 1 - core/jest.setup-after-env.ts | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index 1f548c57b..ee9cddde4 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -1,4 +1,3 @@ -import fs from "fs"; import path from "path"; export default async function () { diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index 200b7a98c..a89c28ff0 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -16,14 +16,14 @@ globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; -global.beforeAll(() => { +globalThis.beforeAll(() => { // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); } }); -global.afterAll(() => { +globalThis.afterAll(() => { // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); From e701ceacfa77a8c75f1878770fbdfb428cdf9524 Mon Sep 17 00:00:00 2001 From: mkummer225 <7843299+mkummer225@users.noreply.github.com> Date: Thu, 15 Aug 2024 18:48:18 -0600 Subject: [PATCH 067/186] cleanup --- core/protocol/ideWebview.ts | 3 +-- core/protocol/passThrough.ts | 1 - core/protocol/webview.ts | 3 +-- core/util/tts.ts | 4 ++-- gui/src/hooks/useSetup.ts | 9 ++------- gui/src/redux/slices/stateSlice.ts | 8 ++------ 6 files changed, 8 insertions(+), 20 deletions(-) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index d8701a035..5e1e74589 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -31,8 +31,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; - setTTSActive: [undefined, void]; - setTTSInactive: [undefined, void]; + setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 3cfaa7628..1e2499ca7 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -59,5 +59,4 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", - "setTTSInactive", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 5ee751dec..d3b127fdc 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -13,6 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; - setTTSInactive: [undefined, void]; - setTTSActive: [undefined, void]; + setTTSActive: [boolean, void]; }; diff --git a/core/util/tts.ts b/core/util/tts.ts index 62f69f600..248c38518 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -81,10 +81,10 @@ export class TTS { return; } - TTS.messenger.request("setTTSActive", undefined); + TTS.messenger.request("setTTSActive", true); TTS.handle?.once("exit", () => { - TTS.messenger.request("setTTSInactive", undefined); + TTS.messenger.request("setTTSActive", false); }); } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e6d05771b..a3a4dcfc4 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -8,7 +8,6 @@ import { addContextItemsAtIndex, setConfig, setTTSActive, - setTTSInactive, setInactive, setSelectedProfileId, } from "../redux/slices/stateSlice"; @@ -83,12 +82,8 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); }); - useWebviewListener("setTTSActive", async () => { - dispatch(setTTSActive()); - }); - - useWebviewListener("setTTSInactive", async () => { - dispatch(setTTSInactive()); + useWebviewListener("setTTSActive", async (status) => { + dispatch(setTTSActive(status)); }); useWebviewListener("setColors", async (colors) => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index de11a237c..7534d9b85 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -170,8 +170,8 @@ export const stateSlice = createSlice({ ? lastHistory.promptLogs.concat(payload) : payload; }, - setTTSActive: (state) => { - state.ttsActive = true; + setTTSActive: (state, { payload }: PayloadAction) => { + state.ttsActive = payload; }, setActive: (state) => { state.active = true; @@ -334,9 +334,6 @@ export const stateSlice = createSlice({ } historyItem.contextItems.push(...payload.contextItems); }, - setTTSInactive: (state) => { - state.ttsActive = false; - }, setInactive: (state) => { state.active = false; }, @@ -508,7 +505,6 @@ export const { setContextItemsAtIndex, addContextItems, addContextItemsAtIndex, - setTTSInactive, setInactive, streamUpdate, newSession, From ac68becf2acff2198ea50842fef0fc5db06aa031 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 10:12:39 -0700 Subject: [PATCH 068/186] maxStopWords option --- core/index.d.ts | 3 +++ core/llm/index.ts | 2 ++ core/llm/llms/Deepseek.ts | 2 +- core/llm/llms/Groq.ts | 2 +- core/llm/llms/OpenAI.ts | 16 ++++++++-------- core/llm/llms/WatsonX.ts | 6 ++++-- docs/static/schemas/config.json | 5 +++++ .../src/main/resources/config_schema.json | 5 +++++ extensions/vscode/config_schema.json | 5 +++++ extensions/vscode/continue_rc_schema.json | 5 +++++ 10 files changed, 39 insertions(+), 12 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 8ce83c6f7..b0505e1ae 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -58,6 +58,7 @@ export interface ILLM extends LLMOptions { title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number; completionOptions: CompletionOptions; requestOptions?: RequestOptions; promptTemplates?: Record; @@ -321,6 +322,7 @@ export interface LLMOptions { uniqueId?: string; systemMessage?: string; contextLength?: number; + maxStopWords?: number; completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -747,6 +749,7 @@ export interface ModelDescription { apiKey?: string; apiBase?: string; contextLength?: number; + maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; diff --git a/core/llm/index.ts b/core/llm/index.ts index ca3c032a6..73a0151e9 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -91,6 +91,7 @@ export abstract class BaseLLM implements ILLM { title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number | undefined; completionOptions: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -143,6 +144,7 @@ export abstract class BaseLLM implements ILLM { this.systemMessage = options.systemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; + this.maxStopWords = options.maxStopWords ?? this.maxStopWords; this.completionOptions = { ...options.completionOptions, model: options.model || "gpt-4", diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index e8342b546..105a2e20c 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -13,7 +13,7 @@ class Deepseek extends OpenAI { }, useLegacyCompletionsEndpoint: false, }; - protected maxStopWords: number | undefined = 16; + maxStopWords: number | undefined = 16; supportsFim(): boolean { return true; diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index 27c51e1e3..7115bcc32 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -6,7 +6,7 @@ class Groq extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.groq.com/openai/v1/", }; - protected maxStopWords: number | undefined = 4; + maxStopWords: number | undefined = 4; private static modelConversion: { [key: string]: string } = { "llama2-70b": "llama2-70b-4096", diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index cea8ec524..4a7477102 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -42,7 +42,7 @@ const CHAT_ONLY_MODELS = [ class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); @@ -104,13 +104,13 @@ class OpenAI extends BaseLLM { this.maxStopWords !== undefined ? options.stop?.slice(0, this.maxStopWords) : url.host === "api.deepseek.com" - ? options.stop?.slice(0, 16) - : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" - ? options.stop?.slice(0, 4) - : options.stop, + ? options.stop?.slice(0, 16) + : url.port === "1337" || + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" + ? options.stop?.slice(0, 4) + : options.stop, }; return finalOptions; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 747a10c6a..02e7c0799 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -13,7 +13,7 @@ const watsonxConfig = { }, }; class WatsonX extends BaseLLM { - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); @@ -176,7 +176,9 @@ class WatsonX extends BaseLLM { throw new Error(`Something went wrong. Check your credentials, please.`); } - const stopToken = this.watsonxStopToken ?? (options.model.includes("granite") ? "<|im_end|>" : undefined); + const stopToken = + this.watsonxStopToken ?? + (options.model.includes("granite") ? "<|im_end|>" : undefined); var streamResponse = await fetch( `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, { diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 44a908810..faac345c2 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -239,6 +239,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 44a908810..faac345c2 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -239,6 +239,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 44a908810..faac345c2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -239,6 +239,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index d6c797596..815ed50c5 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -242,6 +242,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", From 5406d0e1a29936966af7852ee4d7fbe09a8340d3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 10:35:40 -0700 Subject: [PATCH 069/186] test: colocate tests in `core` --- .github/workflows/dev_pr.yaml | 90 +++++ .github/workflows/ts-check.yaml | 1 - core/.eslintrc.json | 2 +- .../charStream.test.ts} | 2 +- core/autocomplete/retrieval.ts | 2 +- .../ConfigHandler.test.ts} | 10 +- core/context/retrieval/fullTextSearch.ts | 2 +- core/{test => diff}/streamDiff.test.ts | 0 .../indexing/CodeSnippetsIndex.test.ts | 15 +- .../CodebaseIndexer.test.ts} | 20 +- core/indexing/CodebaseIndexer.ts | 2 +- .../FullTextSearchCodebaseIndex.test.ts | 13 +- ...arch.ts => FullTextSearchCodebaseIndex.ts} | 17 +- core/{test => }/indexing/LanceDbIndex.test.ts | 23 +- .../chunk}/ChunkCodebaseIndex.test.ts | 12 +- core/{test => }/indexing/chunk/chunk.test.ts | 2 +- core/{test => }/indexing/chunk/code.test.ts | 10 +- .../docs/DocsService.test.ts} | 23 +- .../indexing => indexing/docs}/crawl.test.ts | 0 core/{test => indexing}/walkDir.test.ts | 11 +- core/llm/asyncEncoder.test.ts | 45 +++ core/llm/asyncEncoder.ts | 13 +- .../baseLLM.test.ts => llm/index.test.ts} | 4 +- core/package.json | 2 +- core/test/context/providers/index.skip.ts | 2 +- .../retrieval/RetrievalPipeline.test.ts | 24 -- core/test/llm.test.ts | 6 +- core/test/llm/asyncEncoder.test.ts | 41 -- .../util/dedentAndGetCommonWhitespace.test.ts | 76 ---- core/test/util/deduplicateArray.test.ts | 82 ---- core/test/{ => util}/fixtures.ts | 8 +- core/test/util/getLastNPathParts.test.ts | 51 --- .../{indexing/utils.ts => util/indexing.ts} | 4 +- core/test/util/lcs.test.ts | 40 -- .../test/util/ranges/getRangeInString.test.ts | 105 ----- core/test/util/ranges/intersection.test.ts | 123 ------ core/test/util/ranges/maxMinPosition.test.ts | 70 ---- core/test/util/ranges/union.test.ts | 92 ----- core/test/{testUtils => util}/testDir.ts | 0 core/util/index.test.ts | 200 ++++++++++ core/util/lcs.test.ts | 31 ++ core/{test => }/util/merge.test.ts | 5 +- core/util/ranges.test.ts | 374 ++++++++++++++++++ 43 files changed, 836 insertions(+), 819 deletions(-) create mode 100644 .github/workflows/dev_pr.yaml rename core/{test/streamTransforms/stopAtStopTokens.test.ts => autocomplete/charStream.test.ts} (98%) rename core/{test/config/ConfigHandler.skip.ts => config/ConfigHandler.test.ts} (83%) rename core/{test => diff}/streamDiff.test.ts (100%) rename core/{test => }/indexing/CodeSnippetsIndex.test.ts (87%) rename core/{test/indexing/CodebaseIndexer.skip.ts => indexing/CodebaseIndexer.test.ts} (89%) rename core/{test => }/indexing/FullTextSearchCodebaseIndex.test.ts (89%) rename core/indexing/{FullTextSearch.ts => FullTextSearchCodebaseIndex.ts} (93%) rename core/{test => }/indexing/LanceDbIndex.test.ts (90%) rename core/{test/indexing => indexing/chunk}/ChunkCodebaseIndex.test.ts (87%) rename core/{test => }/indexing/chunk/chunk.test.ts (94%) rename core/{test => }/indexing/chunk/code.test.ts (85%) rename core/{test/indexing/DocsService.skip.ts => indexing/docs/DocsService.test.ts} (87%) rename core/{test/indexing => indexing/docs}/crawl.test.ts (100%) rename core/{test => indexing}/walkDir.test.ts (97%) create mode 100644 core/llm/asyncEncoder.test.ts rename core/{test/baseLLM.test.ts => llm/index.test.ts} (97%) delete mode 100644 core/test/context/retrieval/RetrievalPipeline.test.ts delete mode 100644 core/test/llm/asyncEncoder.test.ts delete mode 100644 core/test/util/dedentAndGetCommonWhitespace.test.ts delete mode 100644 core/test/util/deduplicateArray.test.ts rename core/test/{ => util}/fixtures.ts (61%) delete mode 100644 core/test/util/getLastNPathParts.test.ts rename core/test/{indexing/utils.ts => util/indexing.ts} (95%) delete mode 100644 core/test/util/lcs.test.ts delete mode 100644 core/test/util/ranges/getRangeInString.test.ts delete mode 100644 core/test/util/ranges/intersection.test.ts delete mode 100644 core/test/util/ranges/maxMinPosition.test.ts delete mode 100644 core/test/util/ranges/union.test.ts rename core/test/{testUtils => util}/testDir.ts (100%) create mode 100644 core/util/index.test.ts create mode 100644 core/util/lcs.test.ts rename core/{test => }/util/merge.test.ts (96%) create mode 100644 core/util/ranges.test.ts diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml new file mode 100644 index 000000000..c7fe2deb7 --- /dev/null +++ b/.github/workflows/dev_pr.yaml @@ -0,0 +1,90 @@ +name: Dev PR checks + +on: + pull_request: + branches: + - dev + +jobs: + tsc-check: + runs-on: ubuntu-latest + + steps: + # 1. Check-out repository + - name: Check-out repository + uses: actions/checkout@v4 + + # 2. Install npm dependencies + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Cache extension node_modules + uses: actions/cache@v3 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Cache core node_modules + uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} + + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + + - name: Cache binary node_modules + uses: actions/cache@v3 + with: + path: binary/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + + - name: Install extension Dependencies + run: | + cd extensions/vscode + npm ci + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: Install gui Dependencies + run: | + cd gui + npm ci + + - name: Install Core Dependencies + run: | + cd core + npm ci + + - name: Install Binary Dependencies + run: | + cd binary + npm ci + + - name: core checks + run: | + cd core + npx tsc --noEmit + npm run lint + npm run test + + - name: tsc extensions/vscode + run: | + cd extensions/vscode + npx tsc --noEmit + + - name: tsc binary + run: | + cd binary + npx tsc --noEmit + + - name: tsc gui + run: | + cd gui + npx tsc --noEmit diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml index 193988990..f73016fa5 100644 --- a/.github/workflows/ts-check.yaml +++ b/.github/workflows/ts-check.yaml @@ -5,7 +5,6 @@ on: branches: - main - preview - - dev jobs: tsc-check: diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 1c67b146c..8ba241323 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -8,7 +8,7 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], - "@typescript-eslint/naming-convention": "warn", + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/core/test/streamTransforms/stopAtStopTokens.test.ts b/core/autocomplete/charStream.test.ts similarity index 98% rename from core/test/streamTransforms/stopAtStopTokens.test.ts rename to core/autocomplete/charStream.test.ts index cdb507dd7..7ab8923fc 100644 --- a/core/test/streamTransforms/stopAtStopTokens.test.ts +++ b/core/autocomplete/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "../../autocomplete/charStream.js"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 635f52012..422b377bd 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -1,5 +1,5 @@ import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; export async function fullTextRetrieve( prefix: string, diff --git a/core/test/config/ConfigHandler.skip.ts b/core/config/ConfigHandler.test.ts similarity index 83% rename from core/test/config/ConfigHandler.skip.ts rename to core/config/ConfigHandler.test.ts index ef35789cb..ef4e1814d 100644 --- a/core/test/config/ConfigHandler.skip.ts +++ b/core/config/ConfigHandler.test.ts @@ -1,11 +1,11 @@ import fs from "node:fs"; import path from "node:path"; -import { defaultConfig } from "../../config/default"; -import { getConfigTsPath } from "../../util/paths"; -import { testConfigHandler } from "../fixtures"; -import { TEST_DIR } from "../testUtils/testDir"; +import { defaultConfig } from "./default"; +import { getConfigTsPath } from "../util/paths"; +import { testConfigHandler } from "../test/util/fixtures"; +import { TEST_DIR } from "../test/util/testDir"; -describe("Test the ConfigHandler and E2E config loading", () => { +describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { const profiles = testConfigHandler.listProfiles(); expect(profiles.length).toBe(1); diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts index 3e22db302..9c52bd6b6 100644 --- a/core/context/retrieval/fullTextSearch.ts +++ b/core/context/retrieval/fullTextSearch.ts @@ -1,5 +1,5 @@ import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; export async function retrieveFts( query: string, diff --git a/core/test/streamDiff.test.ts b/core/diff/streamDiff.test.ts similarity index 100% rename from core/test/streamDiff.test.ts rename to core/diff/streamDiff.test.ts diff --git a/core/test/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts similarity index 87% rename from core/test/indexing/CodeSnippetsIndex.test.ts rename to core/indexing/CodeSnippetsIndex.test.ts index 919f5d294..a80ffe7bd 100644 --- a/core/test/indexing/CodeSnippetsIndex.test.ts +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -1,14 +1,13 @@ -/* eslint-disable @typescript-eslint/naming-convention */ -import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex"; -import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; -import { IndexResultType } from "../../indexing/types"; -import { testIde } from "../fixtures"; +import { jest } from "@jest/globals"; +import { testIde } from "../test/util/fixtures"; import { insertMockChunks, - mockPathAndCacheKey, updateIndexAndAwaitGenerator, -} from "./utils"; -import { jest } from "@jest/globals"; + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; describe("CodeSnippetsCodebaseIndex", () => { let index: CodeSnippetsCodebaseIndex; diff --git a/core/test/indexing/CodebaseIndexer.skip.ts b/core/indexing/CodebaseIndexer.test.ts similarity index 89% rename from core/test/indexing/CodebaseIndexer.skip.ts rename to core/indexing/CodebaseIndexer.test.ts index 6d7d73c8d..221035737 100644 --- a/core/test/indexing/CodebaseIndexer.skip.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -2,20 +2,20 @@ import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { ContinueServerClient } from "../../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js"; -import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js"; -import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js"; -import { CodebaseIndex } from "../../indexing/types.js"; -import { walkDir } from "../../indexing/walkDir.js"; -import { getIndexSqlitePath } from "../../util/paths.js"; -import { testConfigHandler, testIde } from "../fixtures.js"; +import { ContinueServerClient } from "../continueServer/stubs/client.js"; +import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "./refreshIndex.js"; +import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; +import { CodebaseIndex } from "./types.js"; +import { walkDir } from "./walkDir.js"; +import { getIndexSqlitePath } from "../util/paths.js"; +import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { addToTestDir, setUpTestDir, tearDownTestDir, TEST_DIR, -} from "../testUtils/testDir.js"; +} from "../test/util/testDir.js"; jest.useFakeTimers(); @@ -57,7 +57,7 @@ class TestCodebaseIndexer extends CodebaseIndexer { // These are more like integration tests, whereas we should separately test // the individual CodebaseIndex classes -describe("CodebaseIndexer", () => { +describe.skip("CodebaseIndexer", () => { const pauseToken = new PauseToken(false); const continueServerClient = new ContinueServerClient(undefined, undefined); const codebaseIndexer = new TestCodebaseIndexer( diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 293129627..da06bb0d9 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -6,7 +6,7 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; -import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; import { LanceDbIndex } from "./LanceDbIndex.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { diff --git a/core/test/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts similarity index 89% rename from core/test/indexing/FullTextSearchCodebaseIndex.test.ts rename to core/indexing/FullTextSearchCodebaseIndex.test.ts index 4822626e8..ccd0e8687 100644 --- a/core/test/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -1,13 +1,14 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch"; -import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; -import { IndexResultType } from "../../indexing/types"; + +import { jest } from "@jest/globals"; import { insertMockChunks, - mockPathAndCacheKey, updateIndexAndAwaitGenerator, -} from "./utils"; -import { jest } from "@jest/globals"; + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; describe("FullTextSearchCodebaseIndex", () => { let index: FullTextSearchCodebaseIndex; diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearchCodebaseIndex.ts similarity index 93% rename from core/indexing/FullTextSearch.ts rename to core/indexing/FullTextSearchCodebaseIndex.ts index 9ece3ff6e..7a571bc13 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,19 +1,14 @@ -import { - BranchAndDir, - Chunk, - IndexTag, - IndexingProgressUpdate, -} from "../index.js"; -import { getBasename } from "../util/index.js"; -import { RETRIEVAL_PARAMS } from "../util/parameters.js"; -import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; +import { getBasename } from "../util/index"; +import { RETRIEVAL_PARAMS } from "../util/parameters"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, RefreshIndexResults, type CodebaseIndex, -} from "./types.js"; +} from "./types"; export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; diff --git a/core/test/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts similarity index 90% rename from core/test/indexing/LanceDbIndex.test.ts rename to core/indexing/LanceDbIndex.test.ts index 89baf737b..a8ba2173a 100644 --- a/core/test/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -1,17 +1,16 @@ -import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; -import { IndexResultType } from "../../indexing/types"; -import { testIde } from "../fixtures"; import { jest } from "@jest/globals"; -import { - mockPathAndCacheKey, - mockTag, - testContinueServerClient, - updateIndexAndAwaitGenerator, -} from "./utils"; -import { LanceDbIndex } from "../../indexing/LanceDbIndex"; -import { testConfigHandler } from "../fixtures"; import lance from "vectordb"; -import { getLanceDbPath } from "../../util/paths"; +import { testIde, testConfigHandler } from "../test/util/fixtures"; +import { + testContinueServerClient, + mockTag, + updateIndexAndAwaitGenerator, + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { getLanceDbPath } from "../util/paths"; +import { LanceDbIndex } from "./LanceDbIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; jest.useFakeTimers(); diff --git a/core/test/indexing/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts similarity index 87% rename from core/test/indexing/ChunkCodebaseIndex.test.ts rename to core/indexing/chunk/ChunkCodebaseIndex.test.ts index bb3208345..ac98d0094 100644 --- a/core/test/indexing/ChunkCodebaseIndex.test.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -1,8 +1,8 @@ -import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; -import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex"; -import { IndexResultType } from "../../indexing/types"; -import { testIde } from "../fixtures"; -import { addToTestDir } from "../testUtils/testDir"; +import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "../refreshIndex"; +import { IndexResultType } from "../types"; +import { testIde } from "../../test/util/fixtures"; +import { addToTestDir } from "../../test/util/testDir"; import { jest } from "@jest/globals"; import { mockFileContents, @@ -10,7 +10,7 @@ import { mockPathAndCacheKey, testContinueServerClient, updateIndexAndAwaitGenerator, -} from "./utils"; +} from "../../test/util/indexing"; jest.useFakeTimers(); diff --git a/core/test/indexing/chunk/chunk.test.ts b/core/indexing/chunk/chunk.test.ts similarity index 94% rename from core/test/indexing/chunk/chunk.test.ts rename to core/indexing/chunk/chunk.test.ts index e45c11c79..a9559ca27 100644 --- a/core/test/indexing/chunk/chunk.test.ts +++ b/core/indexing/chunk/chunk.test.ts @@ -1,5 +1,5 @@ import path from "path"; -import { shouldChunk } from "../../../indexing/chunk/chunk"; +import { shouldChunk } from "./chunk"; describe("shouldChunk", () => { test("should chunk a typescript file", () => { diff --git a/core/test/indexing/chunk/code.test.ts b/core/indexing/chunk/code.test.ts similarity index 85% rename from core/test/indexing/chunk/code.test.ts rename to core/indexing/chunk/code.test.ts index 00615d124..c852ecafd 100644 --- a/core/test/indexing/chunk/code.test.ts +++ b/core/indexing/chunk/code.test.ts @@ -1,5 +1,5 @@ -import { ChunkWithoutID } from "../../../index.js"; -import { codeChunker } from "../../../indexing/chunk/code.js"; +import { ChunkWithoutID } from "../.."; +import { codeChunker } from "./code"; async function genToArr(generator: AsyncGenerator): Promise { const result: T[] = []; @@ -29,7 +29,7 @@ describe.skip("codeChunker", () => { test("should capture small class and function from large python file", async () => { const extraLine = "# This is a comment"; const myClass = "class MyClass:\n def __init__(self):\n pass"; - const myFunction = 'def my_function():\n return "Hello, World!"'; + const myFunction = "def my_function():\n return \"Hello, World!\""; const file = Array(100).fill(extraLine).join("\n") + @@ -66,7 +66,7 @@ describe.skip("codeChunker", () => { chunks[0].startsWith("class MyClass:\n def method1():\n ..."), ).toBe(true); // The extra spaces seem to be a bug with tree-sitter-python - expect(chunks).toContain('def method1():\n return "Hello, 1!"'); - expect(chunks).toContain('def method20():\n return "Hello, 20!"'); + expect(chunks).toContain("def method1():\n return \"Hello, 1!\""); + expect(chunks).toContain("def method20():\n return \"Hello, 20!\""); }); }); diff --git a/core/test/indexing/DocsService.skip.ts b/core/indexing/docs/DocsService.test.ts similarity index 87% rename from core/test/indexing/DocsService.skip.ts rename to core/indexing/docs/DocsService.test.ts index da688dbe1..f1fb6295b 100644 --- a/core/test/indexing/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -1,16 +1,14 @@ /** * @jest-environment jsdom */ -import * as fs from "fs"; -import * as path from "path"; import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; -import DocsService from "../../indexing/docs/DocsService.js"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js"; -import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js"; +import DocsService from "./DocsService.js"; +import preIndexedDocs from "./preIndexedDocs.js"; +import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js"; import FileSystemIde from "../../util/filesystem.js"; -import { editConfigJson, getConfigJsonPath } from "../../util/paths.js"; +import { editConfigJson } from "../../util/paths.js"; describe.skip("DocsService Integration Tests", () => { let ide: FileSystemIde; @@ -23,13 +21,6 @@ describe.skip("DocsService Integration Tests", () => { faviconUrl: "https://github.com/favicon.ico", }; - async function clearConfigDir() { - const configFolder = path.dirname(getConfigJsonPath()); - if (fs.existsSync(configFolder)) { - fs.rmSync(configFolder, { recursive: true, force: true }); - } - } - /** * We need to reload config explicitly to handle the scenario where the * config file update listeners are not called before we attempt to @@ -43,8 +34,6 @@ describe.skip("DocsService Integration Tests", () => { } beforeEach(async () => { - await clearConfigDir(); - ide = new FileSystemIde(process.cwd()); configHandler = new ConfigHandler( @@ -75,10 +64,6 @@ describe.skip("DocsService Integration Tests", () => { await docsService.isInitialized; }); - afterAll(async () => { - await clearConfigDir(); - }); - test("Indexing, retrieval, and deletion of a new documentation site", async () => { const generator = docsService.indexAndAdd(mockSiteConfig); while (!(await generator.next()).done) {} diff --git a/core/test/indexing/crawl.test.ts b/core/indexing/docs/crawl.test.ts similarity index 100% rename from core/test/indexing/crawl.test.ts rename to core/indexing/docs/crawl.test.ts diff --git a/core/test/walkDir.test.ts b/core/indexing/walkDir.test.ts similarity index 97% rename from core/test/walkDir.test.ts rename to core/indexing/walkDir.test.ts index 5ae033337..7fa5ed00c 100644 --- a/core/test/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,13 +1,12 @@ import path from "path"; -import ignore, { Ignore } from "ignore"; -import { walkDir, walkDirAsync, WalkerOptions } from "../indexing/walkDir.js"; -import FileSystemIde from "../util/filesystem.js"; +import { walkDir, WalkerOptions } from "../indexing/walkDir"; +import FileSystemIde from "../util/filesystem"; import { - addToTestDir, + TEST_DIR, setUpTestDir, tearDownTestDir, - TEST_DIR, -} from "./testUtils/testDir.js"; + addToTestDir, +} from "../test/util/testDir"; const ide = new FileSystemIde(TEST_DIR); diff --git a/core/llm/asyncEncoder.test.ts b/core/llm/asyncEncoder.test.ts new file mode 100644 index 000000000..9ed5eb80a --- /dev/null +++ b/core/llm/asyncEncoder.test.ts @@ -0,0 +1,45 @@ +import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder"; + +describe("llama encoder", () => { + var tokenizer: LlamaAsyncEncoder; + + beforeAll(() => { + tokenizer = new LlamaAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); + +describe("tiktoken encoder", () => { + var tokenizer: GPTAsyncEncoder; + + beforeAll(() => { + tokenizer = new GPTAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index ed6425df2..0af5f10cb 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -1,5 +1,4 @@ -import llamaTokenizer from "./llamaTokenizer.js"; -import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; +import { encodingForModel as _encodingForModel } from "js-tiktoken"; import workerpool from "workerpool"; import * as path from "path"; @@ -13,7 +12,9 @@ export class LlamaAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("llamaTokenizerWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -35,7 +36,9 @@ export class GPTAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("tiktokenWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -58,4 +61,4 @@ function workerCodeFilePath(workerFileName: string): string { return path.join(__dirname, "llm", workerFileName); } return path.join(__dirname, workerFileName); -} \ No newline at end of file +} diff --git a/core/test/baseLLM.test.ts b/core/llm/index.test.ts similarity index 97% rename from core/test/baseLLM.test.ts rename to core/llm/index.test.ts index b49c9ac39..926b61209 100644 --- a/core/test/baseLLM.test.ts +++ b/core/llm/index.test.ts @@ -1,5 +1,5 @@ -import { ChatMessage, LLMOptions, ModelProvider } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; +import { ChatMessage, LLMOptions, ModelProvider } from ".."; +import { BaseLLM } from "."; class DummyLLM extends BaseLLM { static providerName: ModelProvider = "openai"; diff --git a/core/package.json b/core/package.json index 66c228cba..5e4e2652d 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", "lint:fix": "eslint . --ext ts --fix" diff --git a/core/test/context/providers/index.skip.ts b/core/test/context/providers/index.skip.ts index a31d10e46..f5da28fab 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/test/context/providers/index.skip.ts @@ -8,7 +8,7 @@ import { ConfigHandler } from "../../../config/ConfigHandler"; import { contextProviderClassFromName } from "../../../context/providers"; import { ControlPlaneClient } from "../../../control-plane/client"; import FileSystemIde from "../../../util/filesystem"; -import { TEST_DIR } from "../../testUtils/testDir"; +import { TEST_DIR } from "../../util/testDir"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ { name: "diff", params: {} }, diff --git a/core/test/context/retrieval/RetrievalPipeline.test.ts b/core/test/context/retrieval/RetrievalPipeline.test.ts deleted file mode 100644 index d6bfdbb3d..000000000 --- a/core/test/context/retrieval/RetrievalPipeline.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline.js"; - -function testRetrievalPipeline(pipeline: IRetrievalPipeline) { - test("should successfully run"); -} - -describe.skip("RetrievalPipeline", () => { - test.todo("should successfully run"); -}); - -// describe("Retrieval Pipelines", () => { -// const ide = new FileSystemIde(); -// const options: RetrievalPipelineOptions; - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); -// }); diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index e3f427731..7b9b861b8 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -1,8 +1,8 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; -import OpenAI from "../llm/llms/OpenAI.js"; +import { CompletionOptions } from "../"; +import { BaseLLM } from "../llm/"; +import OpenAI from "../llm/llms/OpenAI"; // jest.setTimeout(100_000); diff --git a/core/test/llm/asyncEncoder.test.ts b/core/test/llm/asyncEncoder.test.ts deleted file mode 100644 index f181a05ca..000000000 --- a/core/test/llm/asyncEncoder.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder"; - -describe("llama encoder", () => { - var tokenizer: LlamaAsyncEncoder; - - beforeAll(() => { - tokenizer = new LlamaAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); - -describe("tiktoken encoder", () => { - var tokenizer: GPTAsyncEncoder; - - beforeAll(() => { - tokenizer = new GPTAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); \ No newline at end of file diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts deleted file mode 100644 index d96ccbe8f..000000000 --- a/core/test/util/dedentAndGetCommonWhitespace.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated by Continue -import { dedentAndGetCommonWhitespace } from "../../util/index.js"; - -describe("dedentAndGetCommonWhitespace", () => { - let originalString: string; - - beforeEach(() => { - // Setup any global variables or states if needed - originalString = " line1\n line2\n line3"; - }); - - afterEach(() => { - // Tear down any changes to global variables or states if needed - originalString = ""; - }); - - test("should dedent and return common whitespace for a simple case", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", " "]); - }); - - test("should handle empty string", () => { - const input = ""; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with only whitespace", () => { - const input = " "; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with mixed whitespace and content", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); - - test("should handle string with no common leading whitespace", () => { - const input = "line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([input, ""]); - }); - - test("should handle string with empty lines", () => { - const input = " line1\n\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\n\nline3", " "]); - }); - - test("should handle string with only empty lines", () => { - const input = "\n\n"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["\n\n", ""]); - }); - - test("should handle string with tabs as whitespace", () => { - const input = "\tline1\n\tline2\n\tline3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t"]); - }); - - test("should handle string with mixed tabs and spaces", () => { - const input = "\t line1\n\t line2\n\t line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t "]); - }); - - test("should handle string with different leading whitespace lengths", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); -}); diff --git a/core/test/util/deduplicateArray.test.ts b/core/test/util/deduplicateArray.test.ts deleted file mode 100644 index f4277916b..000000000 --- a/core/test/util/deduplicateArray.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { deduplicateArray } from "../../util/index.js"; - -describe("deduplicateArray", () => { - it("should return an empty array when given an empty array", () => { - const result = deduplicateArray([], (a, b) => a === b); - expect(result).toEqual([]); - }); - - it("should return the same array when there are no duplicates", () => { - const input = [1, 2, 3, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(input); - }); - - it("should remove duplicates based on the equality function", () => { - const input = [1, 2, 2, 3, 4, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1, 2, 3, 4, 5]); - }); - - it("should work with objects using custom equality function", () => { - const input = [ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 1, name: "Alice" }, - { id: 3, name: "Charlie" }, - ]; - const result = deduplicateArray(input, (a, b) => a.id === b.id); - expect(result).toEqual([ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 3, name: "Charlie" }, - ]); - }); - - it("should preserve the order of items", () => { - const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); - }); - - it("should work with strings", () => { - const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(["apple", "banana", "cherry", "date"]); - }); - - it("should handle arrays with all duplicate elements", () => { - const input = [1, 1, 1, 1, 1]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1]); - }); - - it("should work with custom equality function for complex objects", () => { - const input = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, - { x: 3, y: 4 }, - ]; - const result = deduplicateArray( - input, - (a, b) => a.x === b.x && a.y === b.y, - ); - expect(result).toEqual([ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 3, y: 4 }, - ]); - }); - - it("should handle large arrays efficiently", () => { - const input = Array(10000) - .fill(0) - .map((_, i) => i % 100); - const start = performance.now(); - const result = deduplicateArray(input, (a, b) => a === b); - const end = performance.now(); - expect(result).toHaveLength(100); - expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second - }); -}); diff --git a/core/test/fixtures.ts b/core/test/util/fixtures.ts similarity index 61% rename from core/test/fixtures.ts rename to core/test/util/fixtures.ts index 51f974fea..89c1c0b3b 100644 --- a/core/test/fixtures.ts +++ b/core/test/util/fixtures.ts @@ -1,7 +1,7 @@ -import { ConfigHandler } from "../config/ConfigHandler"; -import { ControlPlaneClient } from "../control-plane/client"; -import FileSystemIde from "../util/filesystem"; -import { TEST_DIR } from "./testUtils/testDir"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { ControlPlaneClient } from "../../control-plane/client"; +import FileSystemIde from "../../util/filesystem"; +import { TEST_DIR } from "./testDir"; export const testIde = new FileSystemIde(TEST_DIR); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts deleted file mode 100644 index 926218fe2..000000000 --- a/core/test/util/getLastNPathParts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// File generated by Continue -import { getLastNPathParts } from "../../util/index.js"; - -describe("getLastNPathParts", () => { - const SEP_REGEX = /[\\/]+/; - - beforeAll(() => { - // Setup code if needed - }); - - afterAll(() => { - // Teardown code if needed - }); - - test("returns the last N parts of a filepath with forward slashes", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); - }); - - test("returns the last N parts of a filepath with backward slashes", () => { - const filepath = "C:\\home\\user\\documents\\project\\file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("returns the last part if N is 1", () => { - const filepath = "/home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); - }); - - test("returns the entire path if N is greater than the number of parts", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 10)).toBe( - "home/user/documents/project/file.txt", - ); - }); - - test("returns an empty string if N is 0", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 0)).toBe(""); - }); - - test("handles paths with mixed forward and backward slashes", () => { - const filepath = "home\\user/documents\\project/file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("handles edge case with empty filepath", () => { - const filepath = ""; - expect(getLastNPathParts(filepath, 2)).toBe(""); - }); -}); diff --git a/core/test/indexing/utils.ts b/core/test/util/indexing.ts similarity index 95% rename from core/test/indexing/utils.ts rename to core/test/util/indexing.ts index 670617c74..650cc5b56 100644 --- a/core/test/indexing/utils.ts +++ b/core/test/util/indexing.ts @@ -1,7 +1,7 @@ import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; import { IContinueServerClient } from "../../continueServer/interface"; -import { testIde } from "../fixtures"; -import { addToTestDir, TEST_DIR } from "../testUtils/testDir"; +import { testIde } from "./fixtures"; +import { addToTestDir, TEST_DIR } from "./testDir"; import { IndexTag } from "../.."; import { CodebaseIndex, diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts deleted file mode 100644 index c7116fd8b..000000000 --- a/core/test/util/lcs.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// This file is generated by Continue -import { longestCommonSubsequence } from "../../util/lcs.js"; - -describe("longestCommonSubsequence", () => { - beforeAll(() => { - // Setup if needed - }); - - afterAll(() => { - // Teardown if needed - }); - - test("should return the longest common subsequence for non-empty strings", () => { - expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); - expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); - expect(longestCommonSubsequence("abc", "def")).toBe(""); - }); - - test("should handle cases where one or both strings are empty", () => { - expect(longestCommonSubsequence("", "abc")).toBe(""); - expect(longestCommonSubsequence("abc", "")).toBe(""); - expect(longestCommonSubsequence("", "")).toBe(""); - }); - - test("should handle cases with no common subsequence", () => { - expect(longestCommonSubsequence("abc", "def")).toBe(""); - expect(longestCommonSubsequence("xyz", "abc")).toBe(""); - }); - - test("should handle cases with special characters", () => { - expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); - expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); - }); - - test("should handle long strings efficiently", () => { - const str1 = "a".repeat(1000) + "b".repeat(1000); - const str2 = "a".repeat(1000) + "c".repeat(1000); - expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); - }); -}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts deleted file mode 100644 index 95d9f25af..000000000 --- a/core/test/util/ranges/getRangeInString.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// This file is generated by Continue - -import { getRangeInString } from "../../../util/ranges.js"; - -describe.skip("getRangeInString", () => { - let content: string; - - beforeEach(() => { - content = `Line 1 -Line 2 -Line 3 -Line 4 -Line 5`; - }); - - afterEach(() => { - content = ""; - }); - - test("should return substring within the same line", () => { - const range = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 4 }, - }; - expect(getRangeInString(content, range)).toBe("Line"); - }); - - test("should return substring spanning multiple lines", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 3, character: 3 }, - }; - const expected = `ne 2 -Line 3 -Line 4`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle range that starts and ends at the same character", () => { - const range = { - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe("L"); - }); - - test("should handle range that spans entire content", () => { - const range = { - start: { line: 0, character: 0 }, - end: { line: 4, character: 5 }, - }; - expect(getRangeInString(content, range)).toBe(content); - }); - - test("should handle range that spans to the end of the last line", () => { - const range = { - start: { line: 3, character: 2 }, - end: { line: 4, character: 5 }, - }; - const expected = `ne 4 -Line 5`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle empty content", () => { - content = ""; - const range = { - start: { line: 0, character: 0 }, - end: { line: 0, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start line > end line)", () => { - const range = { - start: { line: 3, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start character > end character on same line)", () => { - const range = { - start: { line: 1, character: 5 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle range that starts and ends at the same line but different characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 6 }, - }; - expect(getRangeInString(content, range)).toBe("ne 2"); - }); - - test("should handle range that starts and ends at the same line and same characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe("n"); - }); -}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts deleted file mode 100644 index e1b0a3d52..000000000 --- a/core/test/util/ranges/intersection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -// This file is generated by Continue - -import { intersection } from "../../../util/ranges.js"; - -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("intersection", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 4, character: 0 }, - }; - }); - - test("returns correct intersection for overlapping ranges", () => { - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 5 }, - }); - }); - - test("returns null for non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 3, character: 0 }, - end: { line: 4, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - // TODO - test.skip("returns correct intersection for single line overlap", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 2, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }); - }); - - test("returns null for single line non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 2 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - test("returns correct intersection when one range is fully within another", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 4, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }); - }); - - test("returns correct intersection when ranges touch at the edge", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 2, character: 0 }, - end: { line: 3, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }); - }); -}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts deleted file mode 100644 index 684dced31..000000000 --- a/core/test/util/ranges/maxMinPosition.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { maxPosition, minPosition } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -describe("Position comparison functions", () => { - let pos1: Position; - let pos2: Position; - let pos3: Position; - let pos4: Position; - - beforeAll(() => { - // Setup: Initializing positions - pos1 = { line: 1, character: 5 }; - pos2 = { line: 2, character: 3 }; - pos3 = { line: 1, character: 7 }; - pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality - }); - - describe("maxPosition", () => { - it("should return the position with the greater line number", () => { - expect(maxPosition(pos1, pos2)).toEqual(pos2); - }); - - it("should return the position with the greater character number when lines are equal", () => { - expect(maxPosition(pos1, pos3)).toEqual(pos3); - }); - - it("should return the first position when both positions are equal", () => { - expect(maxPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(maxPosition(posNegative, pos1)).toEqual(pos1); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); - }); - }); - - describe("minPosition", () => { - it("should return the position with the lesser line number", () => { - expect(minPosition(pos1, pos2)).toEqual(pos1); - }); - - it("should return the position with the lesser character number when lines are equal", () => { - expect(minPosition(pos1, pos3)).toEqual(pos1); - }); - - it("should return the first position when both positions are equal", () => { - expect(minPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(minPosition(posNegative, pos1)).toEqual(posNegative); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); - }); - }); -}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts deleted file mode 100644 index 0ee62cb4f..000000000 --- a/core/test/util/ranges/union.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { union } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("union", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 3 }, - end: { line: 4, character: 2 }, - }; - }); - - test("should return the union of two overlapping ranges", () => { - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when ranges are identical", () => { - const result = union(rangeA, rangeA); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap but are adjacent", () => { - rangeB = { - start: { line: 3, character: 5 }, - end: { line: 4, character: 2 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when one range is completely within the other", () => { - rangeB = { - start: { line: 2, character: 1 }, - end: { line: 2, character: 4 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap and are not adjacent", () => { - rangeB = { - start: { line: 4, character: 3 }, - end: { line: 5, character: 1 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 5, character: 1 }, - }); - }); - - // TODO - test.skip("should handle edge case where start and end lines are the same", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 7 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 1, character: 7 }, - }); - }); -}); diff --git a/core/test/testUtils/testDir.ts b/core/test/util/testDir.ts similarity index 100% rename from core/test/testUtils/testDir.ts rename to core/test/util/testDir.ts diff --git a/core/util/index.test.ts b/core/util/index.test.ts new file mode 100644 index 000000000..0d618069c --- /dev/null +++ b/core/util/index.test.ts @@ -0,0 +1,200 @@ +// File generated by Continue +import { + dedentAndGetCommonWhitespace, + deduplicateArray, + getLastNPathParts, +} from "./"; + +describe("getLastNPathParts", () => { + test("returns the last N parts of a filepath with forward slashes", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); + }); + + test("returns the last N parts of a filepath with backward slashes", () => { + const filepath = "C:\\home\\user\\documents\\project\\file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("returns the last part if N is 1", () => { + const filepath = "/home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); + }); + + test("returns the entire path if N is greater than the number of parts", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 10)).toBe( + "home/user/documents/project/file.txt", + ); + }); + + test("returns an empty string if N is 0", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 0)).toBe(""); + }); + + test("handles paths with mixed forward and backward slashes", () => { + const filepath = "home\\user/documents\\project/file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("handles edge case with empty filepath", () => { + const filepath = ""; + expect(getLastNPathParts(filepath, 2)).toBe(""); + }); +}); + +describe("deduplicateArray", () => { + it("should return an empty array when given an empty array", () => { + const result = deduplicateArray([], (a, b) => a === b); + expect(result).toEqual([]); + }); + + it("should return the same array when there are no duplicates", () => { + const input = [1, 2, 3, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(input); + }); + + it("should remove duplicates based on the equality function", () => { + const input = [1, 2, 2, 3, 4, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1, 2, 3, 4, 5]); + }); + + it("should work with objects using custom equality function", () => { + const input = [ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 1, name: "Alice" }, + { id: 3, name: "Charlie" }, + ]; + const result = deduplicateArray(input, (a, b) => a.id === b.id); + expect(result).toEqual([ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 3, name: "Charlie" }, + ]); + }); + + it("should preserve the order of items", () => { + const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); + }); + + it("should work with strings", () => { + const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(["apple", "banana", "cherry", "date"]); + }); + + it("should handle arrays with all duplicate elements", () => { + const input = [1, 1, 1, 1, 1]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1]); + }); + + it("should work with custom equality function for complex objects", () => { + const input = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, + { x: 3, y: 4 }, + ]; + const result = deduplicateArray( + input, + (a, b) => a.x === b.x && a.y === b.y, + ); + expect(result).toEqual([ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 3, y: 4 }, + ]); + }); + + it("should handle large arrays efficiently", () => { + const input = Array(10000) + .fill(0) + .map((_, i) => i % 100); + const start = performance.now(); + const result = deduplicateArray(input, (a, b) => a === b); + const end = performance.now(); + expect(result).toHaveLength(100); + expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second + }); +}); + +describe("dedentAndGetCommonWhitespace", () => { + let originalString: string; + + beforeEach(() => { + // Setup any global variables or states if needed + originalString = " line1\n line2\n line3"; + }); + + afterEach(() => { + // Tear down any changes to global variables or states if needed + originalString = ""; + }); + + test("should dedent and return common whitespace for a simple case", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", " "]); + }); + + test("should handle empty string", () => { + const input = ""; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with only whitespace", () => { + const input = " "; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with mixed whitespace and content", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); + + test("should handle string with no common leading whitespace", () => { + const input = "line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([input, ""]); + }); + + test("should handle string with empty lines", () => { + const input = " line1\n\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\n\nline3", " "]); + }); + + test("should handle string with only empty lines", () => { + const input = "\n\n"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["\n\n", ""]); + }); + + test("should handle string with tabs as whitespace", () => { + const input = "\tline1\n\tline2\n\tline3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t"]); + }); + + test("should handle string with mixed tabs and spaces", () => { + const input = "\t line1\n\t line2\n\t line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t "]); + }); + + test("should handle string with different leading whitespace lengths", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); +}); diff --git a/core/util/lcs.test.ts b/core/util/lcs.test.ts new file mode 100644 index 000000000..2f8e1f92f --- /dev/null +++ b/core/util/lcs.test.ts @@ -0,0 +1,31 @@ +import { longestCommonSubsequence as lcs } from "./lcs"; + +describe("longestCommonSubsequence", () => { + test("should return the longest common subsequence for non-empty strings", () => { + expect(lcs("abcde", "ace")).toBe("ace"); + expect(lcs("abc", "abc")).toBe("abc"); + expect(lcs("abc", "def")).toBe(""); + }); + + test("should handle cases where one or both strings are empty", () => { + expect(lcs("", "abc")).toBe(""); + expect(lcs("abc", "")).toBe(""); + expect(lcs("", "")).toBe(""); + }); + + test("should handle cases with no common subsequence", () => { + expect(lcs("abc", "def")).toBe(""); + expect(lcs("xyz", "abc")).toBe(""); + }); + + test("should handle cases with special characters", () => { + expect(lcs("a!@#b$c", "!@#$")).toBe("!@#$"); + expect(lcs("a!@#b$c", "xyz")).toBe(""); + }); + + test("should handle long strings efficiently", () => { + const str1 = "a".repeat(1000) + "b".repeat(1000); + const str2 = "a".repeat(1000) + "c".repeat(1000); + expect(lcs(str1, str2)).toBe("a".repeat(1000)); + }); +}); diff --git a/core/test/util/merge.test.ts b/core/util/merge.test.ts similarity index 96% rename from core/test/util/merge.test.ts rename to core/util/merge.test.ts index 3bd8309a8..237f362c4 100644 --- a/core/test/util/merge.test.ts +++ b/core/util/merge.test.ts @@ -1,5 +1,6 @@ // File generated by Continue -import { mergeJson } from "../../util/merge.js"; + +import mergeJson from "./merge"; describe("mergeJson", () => { it("should merge two simple JSON objects", () => { @@ -9,7 +10,7 @@ describe("mergeJson", () => { expect(result).toEqual({ a: 1, b: 3, c: 4 }); }); - it('should overwrite values when mergeBehavior is "overwrite"', () => { + it("should overwrite values when mergeBehavior is \"overwrite\"", () => { const first = { a: 1, b: 2 }; const second = { b: 3, c: 4 }; const result = mergeJson(first, second, "overwrite"); diff --git a/core/util/ranges.test.ts b/core/util/ranges.test.ts new file mode 100644 index 000000000..d9d12c07a --- /dev/null +++ b/core/util/ranges.test.ts @@ -0,0 +1,374 @@ +// This file is generated by Continue + +import { + intersection, + getRangeInString, + maxPosition, + minPosition, + union, +} from "./ranges"; + +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("union", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 3 }, + end: { line: 4, character: 2 }, + }; + }); + + test("should return the union of two overlapping ranges", () => { + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when ranges are identical", () => { + const result = union(rangeA, rangeA); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap but are adjacent", () => { + rangeB = { + start: { line: 3, character: 5 }, + end: { line: 4, character: 2 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when one range is completely within the other", () => { + rangeB = { + start: { line: 2, character: 1 }, + end: { line: 2, character: 4 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap and are not adjacent", () => { + rangeB = { + start: { line: 4, character: 3 }, + end: { line: 5, character: 1 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 5, character: 1 }, + }); + }); + + // TODO + test.skip("should handle edge case where start and end lines are the same", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 7 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 1, character: 7 }, + }); + }); +}); + +describe("Position comparison functions", () => { + let pos1: Position; + let pos2: Position; + let pos3: Position; + let pos4: Position; + + beforeAll(() => { + // Setup: Initializing positions + pos1 = { line: 1, character: 5 }; + pos2 = { line: 2, character: 3 }; + pos3 = { line: 1, character: 7 }; + pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality + }); + + describe("maxPosition", () => { + it("should return the position with the greater line number", () => { + expect(maxPosition(pos1, pos2)).toEqual(pos2); + }); + + it("should return the position with the greater character number when lines are equal", () => { + expect(maxPosition(pos1, pos3)).toEqual(pos3); + }); + + it("should return the first position when both positions are equal", () => { + expect(maxPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(maxPosition(posNegative, pos1)).toEqual(pos1); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); + }); + }); + + describe("minPosition", () => { + it("should return the position with the lesser line number", () => { + expect(minPosition(pos1, pos2)).toEqual(pos1); + }); + + it("should return the position with the lesser character number when lines are equal", () => { + expect(minPosition(pos1, pos3)).toEqual(pos1); + }); + + it("should return the first position when both positions are equal", () => { + expect(minPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(minPosition(posNegative, pos1)).toEqual(posNegative); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); + }); + }); +}); + +describe.skip("getRangeInString", () => { + let content: string; + + beforeEach(() => { + content = `Line 1 +Line 2 +Line 3 +Line 4 +Line 5`; + }); + + afterEach(() => { + content = ""; + }); + + test("should return substring within the same line", () => { + const range = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 4 }, + }; + expect(getRangeInString(content, range)).toBe("Line"); + }); + + test("should return substring spanning multiple lines", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 3, character: 3 }, + }; + const expected = `ne 2 +Line 3 +Line 4`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle range that starts and ends at the same character", () => { + const range = { + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe("L"); + }); + + test("should handle range that spans entire content", () => { + const range = { + start: { line: 0, character: 0 }, + end: { line: 4, character: 5 }, + }; + expect(getRangeInString(content, range)).toBe(content); + }); + + test("should handle range that spans to the end of the last line", () => { + const range = { + start: { line: 3, character: 2 }, + end: { line: 4, character: 5 }, + }; + const expected = `ne 4 +Line 5`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle empty content", () => { + content = ""; + const range = { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start line > end line)", () => { + const range = { + start: { line: 3, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start character > end character on same line)", () => { + const range = { + start: { line: 1, character: 5 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle range that starts and ends at the same line but different characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 6 }, + }; + expect(getRangeInString(content, range)).toBe("ne 2"); + }); + + test("should handle range that starts and ends at the same line and same characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe("n"); + }); +}); + +describe("intersection", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 4, character: 0 }, + }; + }); + + test("returns correct intersection for overlapping ranges", () => { + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 5 }, + }); + }); + + test("returns null for non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 3, character: 0 }, + end: { line: 4, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + // TODO + test.skip("returns correct intersection for single line overlap", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 2, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }); + }); + + test("returns null for single line non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 2 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + test("returns correct intersection when one range is fully within another", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 4, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }); + }); + + test("returns correct intersection when ranges touch at the edge", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 2, character: 0 }, + end: { line: 3, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }); + }); +}); From e94c399034ba5aefa6ec14fc82406be1f7d2bd27 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 10:36:57 -0700 Subject: [PATCH 070/186] chore: turn off `naming-convention` --- core/.eslintrc.json | 2 +- core/autocomplete/brackets.ts | 4 ++-- core/autocomplete/languages.ts | 2 +- core/autocomplete/templates.ts | 10 +++++++--- .../context/providers/PostgresContextProvider.ts | 2 +- core/context/rerankers/tei.ts | 2 +- core/control-plane/client.ts | 2 +- core/indexing/TestCodebaseIndex.ts | 4 ++-- core/llm/autodetect.ts | 2 +- core/llm/llms/FreeTrial.ts | 2 +- core/llm/llms/Ollama.ts | 2 +- core/llm/llms/SageMaker.ts | 6 +++--- core/llm/llms/WatsonX.ts | 16 +++++++++++----- core/llm/templates/edit.ts | 2 +- core/test/indexing/chunk/code.test.ts | 6 +++--- core/test/util/merge.test.ts | 2 +- core/util/devdataSqlite.ts | 6 +++--- core/util/extractMinimalStackTraceInfo.ts | 2 +- core/util/filesystem.ts | 4 ++-- core/util/index.ts | 12 ++++++------ core/util/messenger.ts | 2 +- 21 files changed, 51 insertions(+), 41 deletions(-) diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 1c67b146c..8ba241323 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -8,7 +8,7 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], - "@typescript-eslint/naming-convention": "warn", + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/brackets.ts index 63afdfd10..3734df2be 100644 --- a/core/autocomplete/brackets.ts +++ b/core/autocomplete/brackets.ts @@ -84,9 +84,9 @@ export class BracketMatchingService { // Add corresponding open brackets from suffix to stack // because we overwrite them and the diff is displayed, and this allows something to be edited after that for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") continue; + if (suffix[i] === " ") {continue;} const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) break; + if (!openBracket) {break;} stack.unshift(openBracket); } diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 19ab65f71..f5b4cffb0 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -26,7 +26,7 @@ export const Python = { name: "Python", // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - topLevelKeywords: ["def", "class", '"""#'], + topLevelKeywords: ["def", "class", "\"\"\"#"], singleLineComment: "#", endOfLine: [], }; diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 53aa034a9..c0e5c132a 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -70,7 +70,9 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) .join("\n\n"); return [ - `${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`, + `${otherFiles}\n\n+++++ ${ + relativePaths[relativePaths.length - 1] + }\n${prefix}`, suffix, ]; }, @@ -172,8 +174,10 @@ const codegeexFimTemplate: AutocompleteTemplate = { ...snippets.map((snippet) => snippet.filepath), filepath, ]); - const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; - if (snippets.length == 0) { + const baseTemplate = `###PATH:${ + relativePaths[relativePaths.length - 1] + }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; + if (snippets.length === 0) { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets diff --git a/core/context/providers/PostgresContextProvider.ts b/core/context/providers/PostgresContextProvider.ts index 494a3bc33..55c00ae3c 100644 --- a/core/context/providers/PostgresContextProvider.ts +++ b/core/context/providers/PostgresContextProvider.ts @@ -37,7 +37,7 @@ class PostgresContextProvider extends BaseContextProvider { let tablesInfoQuery = ` SELECT table_schema, table_name FROM information_schema.tables`; - if (schema != null) { + if (schema !== null) { tablesInfoQuery += ` WHERE table_schema = '${schema}'`; } const { rows: tablesInfo } = await pool.query(tablesInfoQuery); diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 667181ae3..61f38b98b 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -26,7 +26,7 @@ export class HuggingFaceTEIReranker implements Reranker { const resp = await fetch(new URL("rerank", apiBase), { method: "POST", - headers: { 'Content-Type': 'application/json' }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: query, return_text: false, diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 53e62d247..bee6061b2 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -74,7 +74,7 @@ export class ControlPlaneClient { } try { - const resp = await this.request(`/workspaces`, { + const resp = await this.request("/workspaces", { method: "GET", }); return (await resp.json()) as any; diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts index 234bcbc3e..7031fd992 100644 --- a/core/indexing/TestCodebaseIndex.ts +++ b/core/indexing/TestCodebaseIndex.ts @@ -35,14 +35,14 @@ export class TestCodebaseIndex implements CodebaseIndex { for (const item of [...results.compute, ...results.addTag]) { await db.run( - `INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`, + "INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)", [item.path, tag.branch, tag.directory], ); } for (const item of [...results.del, ...results.removeTag]) { await db.run( - `DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`, + "DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?", [item.path, tag.branch, tag.directory], ); } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index e1d184b80..1696bd674 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -80,7 +80,7 @@ function modelSupportsImages( title: string | undefined, capabilities: ModelCapability | undefined ): boolean { - if (capabilities?.uploadImage !== undefined) return capabilities.uploadImage + if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;} if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { return false; } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index e4c1674e6..9fc59313b 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -31,7 +31,7 @@ class FreeTrial extends BaseLLM { private async _countTokens(prompt: string, model: string, isPrompt: boolean) { if (!Telemetry.client) { throw new Error( - 'In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set "allowAnonymousTelemetry": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.', + "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", ); } const event = isPrompt diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fcce902c8..f830b7f0f 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -61,7 +61,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - 'Error parsing stop parameter value "{value}: ${e}', + "Error parsing stop parameter value \"{value}: ${e}", ); } break; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 6a5890e67..a59de352c 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -55,7 +55,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield data.choices[0].delta.content; } @@ -94,7 +94,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield { role: "assistant", content: data.choices[0].delta.content }; } @@ -143,7 +143,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit { let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render( { messages: messages, add_generation_prompt: true }, { autoEscape: false } - ) + ); const payload = { inputs: prompt, parameters: this.sagemaker.completionOptions, diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 02e7c0799..edf1bd9fb 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -19,7 +19,7 @@ class WatsonX extends BaseLLM { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if (this.watsonxUrl != null && this.watsonxUrl.includes("cloud.ibm.com")) { + if (this.watsonxUrl !== null && this.watsonxUrl.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( await fetch( @@ -125,7 +125,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }; } @@ -169,11 +171,13 @@ class WatsonX extends BaseLLM { watsonxConfig.accessToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60} mins)`, + `Reusing token (expires in ${ + (watsonxConfig.accessToken.expiration - now) / 60 + } mins)`, ); } if (watsonxConfig.accessToken.token === undefined) { - throw new Error(`Something went wrong. Check your credentials, please.`); + throw new Error("Something went wrong. Check your credentials, please."); } const stopToken = @@ -185,7 +189,9 @@ class WatsonX extends BaseLLM { method: "POST", headers: { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }, body: JSON.stringify({ input: messages[messages.length - 1].content, diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index fd288a48e..00a05ac72 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -74,7 +74,7 @@ const osModelsEditPrompt: PromptTemplate = (history, otherData) => { !firstCharOfFirstLine; const suffixTag = isSuffix ? "" : ""; const suffixExplanation = isSuffix - ? ' When you get to "", end your response.' + ? " When you get to \"\", end your response." : ""; // If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth diff --git a/core/test/indexing/chunk/code.test.ts b/core/test/indexing/chunk/code.test.ts index 00615d124..92332dc28 100644 --- a/core/test/indexing/chunk/code.test.ts +++ b/core/test/indexing/chunk/code.test.ts @@ -29,7 +29,7 @@ describe.skip("codeChunker", () => { test("should capture small class and function from large python file", async () => { const extraLine = "# This is a comment"; const myClass = "class MyClass:\n def __init__(self):\n pass"; - const myFunction = 'def my_function():\n return "Hello, World!"'; + const myFunction = "def my_function():\n return \"Hello, World!\""; const file = Array(100).fill(extraLine).join("\n") + @@ -66,7 +66,7 @@ describe.skip("codeChunker", () => { chunks[0].startsWith("class MyClass:\n def method1():\n ..."), ).toBe(true); // The extra spaces seem to be a bug with tree-sitter-python - expect(chunks).toContain('def method1():\n return "Hello, 1!"'); - expect(chunks).toContain('def method20():\n return "Hello, 20!"'); + expect(chunks).toContain("def method1():\n return \"Hello, 1!\""); + expect(chunks).toContain("def method20():\n return \"Hello, 20!\""); }); }); diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts index 3bd8309a8..8eb0546bd 100644 --- a/core/test/util/merge.test.ts +++ b/core/test/util/merge.test.ts @@ -9,7 +9,7 @@ describe("mergeJson", () => { expect(result).toEqual({ a: 1, b: 3, c: 4 }); }); - it('should overwrite values when mergeBehavior is "overwrite"', () => { + it("should overwrite values when mergeBehavior is \"overwrite\"", () => { const first = { a: 1, b: 2 }; const second = { b: 3, c: 4 }; const result = mergeJson(first, second, "overwrite"); diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts index 9724e9f21..4f86cb1a1 100644 --- a/core/util/devdataSqlite.ts +++ b/core/util/devdataSqlite.ts @@ -21,14 +21,14 @@ export class DevDataSqliteDb { // Add tokens_prompt column if it doesn't exist const columnCheckResult = await db.all( - `PRAGMA table_info(tokens_generated);`, + "PRAGMA table_info(tokens_generated);", ); const columnExists = columnCheckResult.some( (col: any) => col.name === "tokens_prompt", ); if (!columnExists) { await db.exec( - `ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;`, + "ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;", ); } } @@ -41,7 +41,7 @@ export class DevDataSqliteDb { ) { const db = await DevDataSqliteDb.get(); await db?.run( - `INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)`, + "INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)", [model, provider, promptTokens, generatedTokens], ); } diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts index a2fa226de..51fcde91a 100644 --- a/core/util/extractMinimalStackTraceInfo.ts +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -5,7 +5,7 @@ * @returns A string containing the minimal stack trace information. */ export function extractMinimalStackTraceInfo(stack: unknown): string { - if (typeof stack !== "string") return ""; + if (typeof stack !== "string") {return "";} const lines = stack.split("\n"); const minimalLines = lines.filter((line) => { return line.trimStart().startsWith("at ") && !line.includes("node_modules"); diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 330776518..06209a474 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -84,12 +84,12 @@ class FileSystemIde implements IDE { } async getTags(artifactId: string): Promise { - const directory =(await this.getWorkspaceDirs())[0] + const directory =(await this.getWorkspaceDirs())[0]; return [{ artifactId, branch: await this.getBranch(directory), directory - }] + }]; } getIdeInfo(): Promise { diff --git a/core/util/index.ts b/core/util/index.ts index 0c7a06317..a628948c7 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string { output = output.trim(); // Replace smart quotes - output = output.replace("“", '"'); - output = output.replace("”", '"'); + output = output.replace("“", "\""); + output = output.replace("”", "\""); output = output.replace("‘", "'"); output = output.replace("’", "'"); // Remove escapes - output = output.replace('\\"', '"'); + output = output.replace("\\\"", "\""); output = output.replace("\\'", "'"); output = output.replace("\\n", "\n"); output = output.replace("\\t", "\t"); output = output.replace("\\\\", "\\"); while ( - (output.startsWith('"') && output.endsWith('"')) || + (output.startsWith("\"") && output.endsWith("\"")) || (output.startsWith("'") && output.endsWith("'")) ) { output = output.slice(1, -1); @@ -120,7 +120,7 @@ export function getUniqueFilePath( } export function shortestRelativePaths(paths: string[]): string[] { - if (paths.length === 0) return []; + if (paths.length === 0) {return [];} const partsLengths = paths.map((x) => x.split(SEP_REGEX).length); const currentRelativePaths = paths.map(getBasename); @@ -135,7 +135,7 @@ export function shortestRelativePaths(paths: string[]): string[] { const firstDuplicatedPath = currentRelativePaths.find( (x, i) => isDuplicated[i], ); - if (!firstDuplicatedPath) break; + if (!firstDuplicatedPath) {break;} currentRelativePaths.forEach((x, i) => { if (x === firstDuplicatedPath) { diff --git a/core/util/messenger.ts b/core/util/messenger.ts index 416e4e8da..2b0593ef3 100644 --- a/core/util/messenger.ts +++ b/core/util/messenger.ts @@ -75,7 +75,7 @@ export class InProcessMessenger< messageId?: string, ): ToProtocol[T][1] { const listener = this.myTypeListeners.get(messageType); - if (!listener) return; + if (!listener) {return;} const msg: Message = { messageType: messageType as string, From c818e2d44b236223fbb2134379585bc729050749 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 10:42:12 -0700 Subject: [PATCH 071/186] remove unneeded eslint ignores --- core/commands/slash/onboard.ts | 1 - core/indexing/FullTextSearchCodebaseIndex.test.ts | 2 -- core/indexing/docs/preIndexedDocs.ts | 1 - core/indexing/embeddings/GeminiEmbeddingsProvider.ts | 2 -- core/indexing/embeddings/index.ts | 3 --- core/indexing/refreshIndex.ts | 1 - core/jest.config.js | 1 - core/llm/llms/WatsonX.ts | 5 ++++- core/protocol/core.ts | 7 +++---- 9 files changed, 7 insertions(+), 16 deletions(-) diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index ed5fa4dec..a7738a041 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import { IDE, SlashCommand } from "../.."; import * as fs from "fs/promises"; import * as path from "path"; diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts index ccd0e8687..eaa614aff 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ - import { jest } from "@jest/globals"; import { insertMockChunks, diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 1cb34ba6f..877002322 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import { SiteIndexingConfig } from "../../index.js"; const preIndexedDocs: Record< diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts index 1bb7af75a..d3c22f3f0 100644 --- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts +++ b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts @@ -37,9 +37,7 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider { requests, }), headers: { - // eslint-disable-next-line @typescript-eslint/naming-convention "x-goog-api-key": this.options.apiKey, - // eslint-disable-next-line @typescript-eslint/naming-convention "Content-Type": "application/json", }, }), diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index f39dee4fa..acf3d81e8 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -19,13 +19,10 @@ export const allEmbeddingsProviders: Record< EmbeddingsProviderConstructor > = { ollama: OllamaEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "transformers.js": TransformersJsEmbeddingsProvider, openai: OpenAIEmbeddingsProvider, cohere: CohereEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "free-trial": FreeTrialEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 7cfeae0f9..c60a1a4d3 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import crypto from "node:crypto"; import * as fs from "node:fs"; import { open, type Database } from "sqlite"; diff --git a/core/jest.config.js b/core/jest.config.js index 5fa08c29a..2567c5891 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import path from "path"; import { fileURLToPath } from "url"; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index edf1bd9fb..5a18ab932 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -19,7 +19,10 @@ class WatsonX extends BaseLLM { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if (this.watsonxUrl !== null && this.watsonxUrl.includes("cloud.ibm.com")) { + if ( + this.watsonxUrl !== null && + this.watsonxUrl!.includes("cloud.ibm.com") + ) { // watsonx SaaS const wxToken = await ( await fetch( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index fb3f7c684..918ba6e66 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,6 +1,5 @@ -/* eslint-disable @typescript-eslint/naming-convention */ -import type { AutocompleteInput } from "../autocomplete/completionProvider.js"; -import { ProfileDescription } from "../config/ConfigHandler.js"; +import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -16,7 +15,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, -} from "../index.js"; +} from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; From 4e2289459d8e3fd6e15a0a5b1bc974055b920586 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 10:58:36 -0700 Subject: [PATCH 072/186] Update dev_pr.yaml --- .github/workflows/dev_pr.yaml | 41 ++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index c7fe2deb7..b74a03137 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -44,47 +44,48 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - name: Install extension Dependencies + - name: extensions/vscode install run: | - cd extensions/vscode + cd npm ci env: # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - name: Install gui Dependencies + - name: extensions/vscode checks run: | - cd gui - npm ci + cd extensions/vscode + npx tsc --noEmit - - name: Install Core Dependencies + - name: core install run: | cd core npm ci - - name: Install Binary Dependencies - run: | - cd binary - npm ci - - name: core checks run: | cd core + npm ci npx tsc --noEmit npm run lint npm run test - - name: tsc extensions/vscode + - name: gui install run: | - cd extensions/vscode - npx tsc --noEmit + cd + npm ci - - name: tsc binary - run: | - cd binary - npx tsc --noEmit - - - name: tsc gui + - name: gui checks run: | cd gui npx tsc --noEmit + + - name: binary install + run: | + cd + npm ci + + - name: binary checks + run: | + cd binary + npx tsc --noEmit From f6d100df524873e44e9da5da00c4b6e192a83ffe Mon Sep 17 00:00:00 2001 From: hbernie Date: Thu, 15 Aug 2024 14:06:07 -0700 Subject: [PATCH 073/186] Add Kindo provider --- core/index.d.ts | 1 + core/llm/llms/Kindo.ts | 16 ++++++++ core/llm/llms/index.ts | 2 + docs/docs/reference/Model Providers/kindo.md | 42 ++++++++++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 core/llm/llms/Kindo.ts create mode 100644 docs/docs/reference/Model Providers/kindo.md diff --git a/core/index.d.ts b/core/index.d.ts index 8ce83c6f7..51ea0ecb7 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -588,6 +588,7 @@ type ModelProvider = | "ollama" | "huggingface-tgi" | "huggingface-inference-api" + | "kindo" | "llama.cpp" | "replicate" | "text-gen-webui" diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts new file mode 100644 index 000000000..855e386de --- /dev/null +++ b/core/llm/llms/Kindo.ts @@ -0,0 +1,16 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class Kindo extends OpenAI { + static providerName: ModelProvider = "kindo"; + static defaultOptions: Partial = { + apiBase: "https://llm.kindo.ai/v1", + requestOptions: { + headers: { + "kindo-token-transaction-type": "CONTINUE" + } + } + }; +} + +export default Kindo; \ No newline at end of file diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cd084207e..33c7d0406 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -22,6 +22,7 @@ import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; +import Kindo from "./Kindo"; import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; @@ -48,6 +49,7 @@ const LLMs = [ Together, HuggingFaceTGI, HuggingFaceInferenceAPI, + Kindo, LlamaCpp, OpenAI, LMStudio, diff --git a/docs/docs/reference/Model Providers/kindo.md b/docs/docs/reference/Model Providers/kindo.md new file mode 100644 index 000000000..442e30b10 --- /dev/null +++ b/docs/docs/reference/Model Providers/kindo.md @@ -0,0 +1,42 @@ +# Kindo +Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins). + +## Config Example + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "" + } + ] +} +``` + +## Tab Autocomplete Config Example + +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "" + }, + { + "title": "DeepSeek", + "provider": "kindo", + "model": "deepseek-ai/deepseek-coder-33b-instruct", + "apiKey": "" + } + ] +} +``` + +## Security + +To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). \ No newline at end of file From 872915b643bbe289adf743899f8c046dbca2a9f1 Mon Sep 17 00:00:00 2001 From: hbernie Date: Fri, 16 Aug 2024 15:25:08 -0700 Subject: [PATCH 074/186] Add to model-providers --- docs/docs/setup/model-providers.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index ab774d242..db79d5e33 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -63,6 +63,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co You can access both open-source and commercial LLMs via: - [OpenRouter](../reference/Model%20Providers/openrouter.md) +- [Kindo](../reference/Model%20Providers/kindo.md) ### Open-source models From 4d01ed7a72b0e6b1a4d3b74483c3190b8aae9b6d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 16:49:36 -0700 Subject: [PATCH 075/186] test: lineStream.ts --- core/.gitignore | 3 +- core/autocomplete/completionProvider.ts | 18 +- core/autocomplete/lineStream.test.ts | 421 ++++++++++++++++++++++++ core/autocomplete/lineStream.ts | 344 +++++++++++++------ 4 files changed, 674 insertions(+), 112 deletions(-) create mode 100644 core/autocomplete/lineStream.test.ts diff --git a/core/.gitignore b/core/.gitignore index ad1c54334..7d8f1fa53 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -4,4 +4,5 @@ target npm-debug.log* .env .continue-test -testDir \ No newline at end of file +testDir +coverage \ No newline at end of file diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index c67ce1f0a..39d2d1e73 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -37,7 +37,7 @@ import { import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; import { - avoidPathLine, + avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, skipPrefixes, stopAtLines, @@ -478,9 +478,9 @@ export class CompletionProvider { const lines = fullPrefix.split("\n"); fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ lang.singleLineComment - } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ - lines[lines.length - 1] - }`; + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -581,7 +581,10 @@ export class CompletionProvider { prefix = `${formattedSnippets}\n\n${prefix}`; } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`; + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; } prompt = compiledTemplate({ @@ -689,7 +692,10 @@ export class CompletionProvider { let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); lineGenerator = skipPrefixes(lineGenerator); lineGenerator = noTopLevelKeywordsMidline( lineGenerator, diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/lineStream.test.ts new file mode 100644 index 000000000..df8cd1263 --- /dev/null +++ b/core/autocomplete/lineStream.test.ts @@ -0,0 +1,421 @@ +import { jest } from "@jest/globals"; +import * as lineStream from "./lineStream"; + +describe("lineStream", () => { + let mockFullStop: jest.Mock; + + async function getLineGenerator(lines: any) { + return (async function* () { + for (const line of lines) { + yield line; + } + })(); + } + + async function getFilteredLines(results: any) { + const output = []; + + for await (const line of results) { + output.push(line); + } + + return output; + } + + beforeEach(() => { + mockFullStop = jest.fn(); + }); + + describe("noTopLevelKeywordsMidline", () => { + it.todo("Need some sample inputs to properly test this"); + }); + + describe("avoidPathLine", () => { + it("should filter out path lines and empty comments", async () => { + const linesGenerator = await getLineGenerator([ + "// Path: src/index.ts", + "const x = 5;", + "//", + "console.log(x);", + ]); + + const result = lineStream.avoidPathLineAndEmptyComments( + linesGenerator, + "//", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]); + }); + }); + + describe("streamWithNewLines", () => { + it("should add newlines between lines", async () => { + const linesGenerator = await getLineGenerator([ + "line1", + "line2", + "line3", + ]); + + const result = lineStream.streamWithNewLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); + }); + }); + + describe("lineIsRepeated", () => { + it("should return true for similar lines", () => { + expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( + true, + ); + }); + + it("should return false for different lines", () => { + expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( + false, + ); + }); + + it("should return false for short lines", () => { + expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); + }); + }); + + describe("stopAtSimilarLine", () => { + it("should stop at the exact same line", async () => { + const lineToTest = "const x = 6;"; + const linesGenerator = await getLineGenerator([ + "console.log();", + "const y = () => {};", + lineToTest, + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + lineToTest, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should stop at a similar line", async () => { + const lineToTest = "const x = 6;"; + const linesGenerator = await getLineGenerator([ + "console.log();", + "const y = () => {};", + lineToTest, + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + "a" + lineToTest, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should continue on bracket ending lines", async () => { + const linesGenerator = await getLineGenerator([ + " if (x > 0) {", + " console.log(x);", + " }", + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + "}", + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + " if (x > 0) {", + " console.log(x);", + " }", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + }); + + describe("stopAtLines", () => { + it("should stop at specified lines", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + lineStream.LINES_TO_STOP_AT[0], + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + }); + + describe("skipPrefixes", () => { + it("should skip specified prefixes", async () => { + const linesGenerator = await getLineGenerator([ + `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, + "let y = 10;", + ]); + + const result = lineStream.skipPrefixes(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + }); + + describe("skipLines", () => { + it("should skip specified lines", async () => { + const linesGenerator = await getLineGenerator([ + `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, + "let y = 10;", + ]); + + const result = lineStream.skipLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["let y = 10;"]); + }); + }); + + describe("filterCodeBlockLines", () => { + it("should remove lines before the first valid line", async () => { + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it.todo("Need some sample inputs to properly test this"); + }); + + describe("filterEnglishLinesAtStart", () => { + it("should skip initial empty line", async () => { + const linesGenerator = await getLineGenerator([ + "", + "const x = 5;", + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + + it("should filter out English first line", async () => { + const linesGenerator = await getLineGenerator([ + lineStream.ENGLISH_START_PHRASES[0], + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["let y = 10;"]); + }); + + it("should not filter out non-English first line", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + + it("should filter out empty newline after first line english word", async () => { + const linesGenerator = await getLineGenerator([ + lineStream.ENGLISH_START_PHRASES[0], + "", + "const x = 5;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { + const linesGenerator = await getLineGenerator([ + "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", + "const x = 5;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { + const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; + + const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([keyword, "const x = 5;"]); + }); + }); + + describe("filterEnglishLinesAtEnd", () => { + it("should stop at English explanation after code block", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```", + lineStream.ENGLISH_POST_PHRASES[0], + ]); + + const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```"]); + }); + }); + + describe("fixCodeLlamaFirstLineIndentation", () => { + it("should fix indentation of the first line", async () => { + const linesGenerator = await getLineGenerator([ + " const x = 5;", + "let y = 10;", + ]); + + const result = + lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + }); + + describe("filterLeadingAndTrailingNewLineInsertion", () => { + it("should ignore 'useless' new first lines", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: lineStream.USELESS_LINES[0] }, + { type: "new", line: "const x = 5;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); + }); + + it("should handle preserve newlines chars in old lines", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + { type: "old", line: "" }, + { type: "new", line: "const z = 15;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + { type: "old", line: "" }, + { type: "new", line: "const z = 15;" }, + ]); + }); + + it("should filter leading and trailing new line insertions", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "" }, + { type: "new", line: "const x = 5;" }, + { type: "new", line: "let y = 10;" }, + { type: "new", line: "" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "let y = 10;" }, + ]); + }); + + it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "" }, + { type: "new", line: "let y = 10;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "" }, + { type: "new", line: "let y = 10;" }, + ]); + }); + }); + + describe("stopAtRepeatingLines", () => { + it("should handle non-repeating lines correctly", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtRepeatingLines( + linesGenerator, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "let y = 10;", + "const z = 15;", + ]); + }); + + it("should stop at repeating lines", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "let y = 10;", + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtRepeatingLines( + linesGenerator, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 674f0d46e..6c8b9fd3a 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -1,12 +1,106 @@ import { distance } from "fastest-levenshtein"; -import { LineStream } from "../diff/util.js"; -import { DiffLine } from "../index.js"; +import { LineStream } from "../diff/util"; +import { DiffLine } from "../"; export type LineFilter = (args: { lines: LineStream; fullStop: () => void; }) => LineStream; +function isBracketEnding(line: string): boolean { + return line + .trim() + .split("") + .some((char) => BRACKET_ENDING_CHARS.includes(char)); +} + +function commonPrefixLength(a: string, b: string): number { + let i = 0; + while (i < a.length && i < b.length && a[i] === b[i]) { + i++; + } + return i; +} + +function isEnglishFirstLine(line: string) { + line = line.trim().toLowerCase(); + + if ( + line.endsWith(":") && + !CODE_KEYWORDS_ENDING_IN_SEMICOLON.some((keyword) => + line.startsWith(keyword), + ) + ) { + return true; + } + + return ENGLISH_START_PHRASES.some((phrase) => line.startsWith(phrase)); +} + +function isEnglishPostExplanation(line: string): boolean { + const lower = line.toLowerCase(); + return ENGLISH_POST_PHRASES.some((phrase) => lower.startsWith(phrase)); +} + +function shouldRemoveLineBeforeStart(line: string): boolean { + return ( + line.trimStart().startsWith("```") || + LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l) + ); +} + +function shouldChangeLineAndStop(line: string): string | undefined { + if (line.trimStart() === "```") { + return line; + } + + if (line.includes(CODE_START_BLOCK)) { + return line.split(CODE_START_BLOCK)[0].trimEnd(); + } + + return undefined; +} + +function isUselessLine(line: string): boolean { + const trimmed = line.trim().toLowerCase(); + const hasUselessLine = USELESS_LINES.some( + (uselessLine) => trimmed === uselessLine, + ); + + return hasUselessLine || trimmed.startsWith("// end"); +} + +export const USELESS_LINES = ["", "```"]; +export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; +export const CODE_START_BLOCK = "[/CODE]"; +export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; +export const PREFIXES_TO_SKIP = [""]; +export const LINES_TO_STOP_AT = ["# End of file.", ""]; +export const LINES_TO_REMOVE_BEFORE_START = [ + "", + "[CODE]", + "", +]; +export const ENGLISH_START_PHRASES = [ + "here is", + "here's", + "sure, here", + "sure thing", + "sure!", + "to fill", + "certainly", + "of course", + "the code should", +]; + +export const ENGLISH_POST_PHRASES = [ + "explanation:", + "here is", + "here's how", + "the above", +]; + export async function* noTopLevelKeywordsMidline( lines: LineStream, topLevelKeywords: string[], @@ -15,6 +109,7 @@ export async function* noTopLevelKeywordsMidline( for await (const line of lines) { for (const keyword of topLevelKeywords) { const indexOf = line.indexOf(`${keyword} `); + // TODO: What is this second clause for? if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") { yield line.slice(0, indexOf); fullStop(); @@ -25,7 +120,14 @@ export async function* noTopLevelKeywordsMidline( } } -export async function* avoidPathLine( +/** + * Filters out unwanted lines from a LineStream, specifically those starting with '// Path: ' or empty comments. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). + * @yields {string} The filtered lines, excluding unwanted path lines and empty comments. + */ +export async function* avoidPathLineAndEmptyComments( stream: LineStream, comment: string, ): LineStream { @@ -40,6 +142,12 @@ export async function* avoidPathLine( } } +/** + * Transforms a LineStream by adding newline characters between lines. + * + * @param {LineStream} stream - The input stream of lines. + * @yields {string} The lines from the input stream with newline characters added between them. + */ export async function* streamWithNewLines(stream: LineStream): LineStream { let firstLine = true; for await (const nextLine of stream) { @@ -51,22 +159,19 @@ export async function* streamWithNewLines(stream: LineStream): LineStream { } } -const bracketEnding = [")", "]", "}", ";"]; -function isBracketEnding(line: string): boolean { - return line - .trim() - .split("") - .some((char) => bracketEnding.includes(char)); -} - -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - +/** + * Determines if two lines of text are considered repeated or very similar. + * + * @param {string} a - The first line of text to compare. + * @param {string} b - The second line of text to compare. + * @returns {boolean} True if the lines are considered repeated, false otherwise. + * + * @description + * This function checks if two lines are repeated or very similar based on two criteria: + * 1. They have a common prefix longer than 12 characters. + * 2. The Levenshtein distance between them is less than 10% of the length of the second line. + * Lines shorter than 5 characters are never considered repeated. + */ export function lineIsRepeated(a: string, b: string): boolean { if (a.length <= 4 || b.length <= 4) { return false; @@ -80,6 +185,21 @@ export function lineIsRepeated(a: string, b: string): boolean { ); } +/** + * Filters a LineStream, stopping when a line similar to the provided one is encountered. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} line - The line to compare against for similarity. + * @param {() => void} fullStop - Function to call when stopping the stream. + * @yields {string} Filtered lines until a similar line is encountered. + * + * @description + * This generator function processes the input stream, yielding lines until it encounters: + * 1. An exact match to the provided line. + * 2. A line that is considered repeated or very similar to the provided line. + * 3. For lines ending with brackets, it allows exact matches of trimmed content. + * When any of these conditions are met, it calls the fullStop function and stops yielding. + */ export async function* stopAtSimilarLine( stream: LineStream, line: string, @@ -87,6 +207,7 @@ export async function* stopAtSimilarLine( ): AsyncGenerator { const trimmedLine = line.trim(); const lineIsBracketEnding = isBracketEnding(trimmedLine); + for await (const nextLine of stream) { if (nextLine === line) { fullStop(); @@ -102,12 +223,17 @@ export async function* stopAtSimilarLine( fullStop(); break; } + yield nextLine; } } -const LINES_TO_STOP_AT = ["# End of file.", " void} fullStop - Function to call when stopping. + * @yields {string} Filtered lines until a stop phrase is encountered. + */ export async function* stopAtLines( stream: LineStream, fullStop: () => void, @@ -121,7 +247,11 @@ export async function* stopAtLines( } } -const PREFIXES_TO_SKIP = [""]; +/** + * Filters a LineStream, skipping specified prefixes on the first line. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Filtered lines with prefixes removed from the first line if applicable. + */ export async function* skipPrefixes(lines: LineStream): LineStream { let isFirstLine = true; for await (const line of lines) { @@ -137,8 +267,11 @@ export async function* skipPrefixes(lines: LineStream): LineStream { } } -const LINES_TO_SKIP = [""]; - +/** + * Filters out lines starting with specified prefixes from a LineStream. + * @param {LineStream} stream - The input stream of lines. + * @yields {string} Filtered lines that don't start with any of the LINES_TO_SKIP prefixes. + */ export async function* skipLines(stream: LineStream): LineStream { for await (const line of stream) { if (!LINES_TO_SKIP.some((skipAt) => line.startsWith(skipAt))) { @@ -147,34 +280,21 @@ export async function* skipLines(stream: LineStream): LineStream { } } -const LINES_TO_REMOVE_BEFORE_START = [ - "", - "[CODE]", - "", -]; - -function shouldRemoveLineBeforeStart(line: string): boolean { - return ( - line.trimStart().startsWith("```") || - LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l) - ); -} - -function shouldChangeLineAndStop(line: string): string | undefined { - if (line.trimStart() === "```") { - return line; - } - - if (line.includes("[/CODE]")) { - return line.split("[/CODE]")[0].trimEnd(); - } - - return undefined; -} - +/** + * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * + * @param {LineStream} rawLines - The input stream of lines to filter. + * @yields {string} Filtered and processed lines from the code block. + * + * @description + * This generator function performs the following tasks: + * 1. Removes initial lines that should be removed before the actual code starts. + * 2. Filters out ending code block markers (```) unless they are the last line. + * 3. Handles special cases where lines should be changed and the stream should stop. + * 4. Yields processed lines that are part of the actual code block content. + */ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { let seenValidLine = false; - let waitingToSeeIfLineIsLast = undefined; for await (const line of rawLines) { @@ -206,28 +326,19 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { } } -function isEnglishFirstLine(line: string) { - line = line.trim().toLowerCase(); - if (line.endsWith(":") && !line.trimStart().startsWith("def")) { - return true; - } - if ( - line.startsWith("here is") || - line.startsWith("here's") || - line.startsWith("sure, here") || - line.startsWith("sure thing") || - line.startsWith("sure!") || - line.startsWith("to fill") || - line.startsWith("certainly") || - line.startsWith("of course") || - line.startsWith("the code should") - ) { - return true; - } - - return false; -} - +/** + * Filters out English explanations at the start of a code block. + * + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Filtered lines with English explanations removed from the start. + * + * @description + * This generator function performs the following tasks: + * 1. Skips initial blank lines. + * 2. Removes the first line if it's identified as an English explanation. + * 3. Removes a subsequent blank line if the first line was an English explanation. + * 4. Yields all remaining lines. + */ export async function* filterEnglishLinesAtStart(lines: LineStream) { let i = 0; let wasEnglishFirstLine = false; @@ -235,6 +346,7 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) { if (i === 0 && line.trim() === "") { continue; } + if (i === 0) { if (isEnglishFirstLine(line)) { wasEnglishFirstLine = true; @@ -250,18 +362,14 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) { } } -function isEnglishPostExplanation(line: string): boolean { - const lower = line.toLowerCase(); - return ( - lower.startsWith("explanation:") || - lower.startsWith("here is") || - lower.startsWith("here's how") || - lower.startsWith("the above") - ); -} - +/** + * Filters out English explanations at the end of a code block. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Lines up to the end of the code block or start of English explanation. + */ export async function* filterEnglishLinesAtEnd(lines: LineStream) { let finishedCodeBlock = false; + for await (const line of lines) { if (line.trim() === "```") { finishedCodeBlock = true; @@ -273,8 +381,14 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) { } } +/** + * Removes leading indentation from the first line of a CodeLlama output. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Lines with the first line's indentation fixed if necessary. + */ export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) { let isFirstLine = true; + for await (const line of lines) { if (isFirstLine && line.startsWith(" ")) { yield line.slice(2); @@ -285,23 +399,36 @@ export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) { } } -function isUselessLine(line: string): boolean { - const trimmed = line.trim().toLowerCase(); - return trimmed === "" || trimmed === "```" || trimmed.startsWith("// end"); -} - +/** + * Filters leading and trailing blank line insertions from a stream of diff lines. + * + * @param {AsyncGenerator} diffLines - An async generator that yields DiffLine objects. + * @yields {DiffLine} Filtered DiffLine objects, with leading and trailing blank line insertions removed. + * + * @description + * This generator function processes a stream of diff lines, removing leading and trailing + * blank line insertions. It performs the following tasks: + * 1. Skips the first blank line insertion if it occurs at the beginning. + * 2. Buffers subsequent blank line insertions. + * 3. Yields buffered blank lines when a non-blank insertion is encountered. + * 4. Clears the buffer when an old line is encountered. + * 5. Yields all non-blank insertions and old lines. + */ export async function* filterLeadingAndTrailingNewLineInsertion( diffLines: AsyncGenerator, ): AsyncGenerator { let isFirst = true; let buffer: DiffLine[] = []; + for await (const diffLine of diffLines) { const isBlankLineInsertion = diffLine.type === "new" && isUselessLine(diffLine.line); + if (isFirst && isBlankLineInsertion) { isFirst = false; continue; } + isFirst = false; if (isBlankLineInsertion) { @@ -319,31 +446,38 @@ export async function* filterLeadingAndTrailingNewLineInsertion( } } +/** + * Filters a LineStream, stopping when a line repeats more than a specified number of times. + * + * @param {LineStream} lines - The input stream of lines to filter. + * @param {() => void} fullStop - Function to call when stopping the stream. + * @yields {string} Filtered lines until excessive repetition is detected. + * + * @description + * This function yields lines from the input stream until a line is repeated + * for a maximum of 3 consecutive times. When this limit is reached, it calls + * the fullStop function and stops yielding. Only the first of the repeating + * lines is yieled. + */ export async function* stopAtRepeatingLines( lines: LineStream, fullStop: () => void, ): LineStream { - const repeatedLines: string[] = []; + let previousLine: string | undefined; + let repeatCount = 0; + const MAX_REPEATS = 3; + for await (const line of lines) { - if (repeatedLines.length === 0) { - repeatedLines.push(line); - } else if (repeatedLines.length < 3) { - if (repeatedLines[repeatedLines.length - 1] === line) { - repeatedLines.push(line); - } else { - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; - } - yield line; + if (line === previousLine) { + repeatCount++; + if (repeatCount === MAX_REPEATS) { + fullStop(); + return; } } else { - yield repeatedLines[0]; - fullStop(); - return; + yield line; + repeatCount = 1; } - } - - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; + previousLine = line; } } From 6002dcea55e7cccdf20adef1c73b4e01f8910e91 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 16:51:29 -0700 Subject: [PATCH 076/186] update ci --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 606f328ed..fb4cad979 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -10,7 +10,7 @@ on: defaults: run: - working-directory: ./extensions/intellij + working-directory: extensions/intellij concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} From ac99735d6da71a028e9416edd32eaa9328a4037a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 16:53:18 -0700 Subject: [PATCH 077/186] change working directory --- .github/workflows/jetbrains-release.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index fb4cad979..dc06f7b85 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -21,6 +21,7 @@ jobs: runs-on: ubuntu-latest outputs: should_run: ${{ steps.check.outputs.should_run }} + working-directory: . steps: - id: check run: | From 80bde596271b0283773538a3ab5097b1ec3a0e23 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 16:54:34 -0700 Subject: [PATCH 078/186] fix --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index dc06f7b85..1d3d96b83 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -21,9 +21,9 @@ jobs: runs-on: ubuntu-latest outputs: should_run: ${{ steps.check.outputs.should_run }} - working-directory: . steps: - id: check + working-directory: . run: | if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then echo "should_run=true" >> $GITHUB_OUTPUT From f389e0079327cb35f424696e868d92415cc7bd4e Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 16:57:22 -0700 Subject: [PATCH 079/186] Update lineStream.ts --- core/autocomplete/lineStream.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 6c8b9fd3a..e7d3493bd 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -82,6 +82,7 @@ export const LINES_TO_REMOVE_BEFORE_START = [ "[CODE]", "", ]; + export const ENGLISH_START_PHRASES = [ "here is", "here's", From 379939d3fc8fc64ca40bc02ca0030a9962ad0f4d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 16:58:41 -0700 Subject: [PATCH 080/186] Update dev_pr.yaml --- .github/workflows/dev_pr.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index b74a03137..de45e9523 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -68,7 +68,6 @@ jobs: npm ci npx tsc --noEmit npm run lint - npm run test - name: gui install run: | From d05d056b1fcce904de1528ce5de7690a628b7541 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 17:16:33 -0700 Subject: [PATCH 081/186] tests: charStream --- core/autocomplete/charStream.test.ts | 138 +++++++++++++++++++++++++++ core/autocomplete/charStream.ts | 32 +++++++ 2 files changed, 170 insertions(+) create mode 100644 core/autocomplete/charStream.test.ts diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/charStream.test.ts new file mode 100644 index 000000000..bc5136d1c --- /dev/null +++ b/core/autocomplete/charStream.test.ts @@ -0,0 +1,138 @@ +import { jest } from "@jest/globals"; +import * as charStream from "./charStream"; +import { Typescript } from "./languages"; + +describe("charStream", () => { + let mockFullStop: jest.Mock; + + async function getCharGenerator(chars: string[]) { + return (async function* () { + for (const char of chars) { + yield char; + } + })(); + } + + async function getFilteredChars(results: AsyncGenerator) { + const output = []; + for await (const char of results) { + output.push(char); + } + return output; + } + + beforeEach(() => { + mockFullStop = jest.fn(); + }); + + describe("onlyWhitespaceAfterEndOfLine", () => { + const endOfLineChar = Typescript.endOfLine[0]; + + it("should stop at end of line if non-whitespace follows", async () => { + const charGenerator = await getCharGenerator([ + `Hello${endOfLineChar}World`, + ]); + + const result = charStream.onlyWhitespaceAfterEndOfLine( + charGenerator, + [endOfLineChar], + mockFullStop, + ); + const filteredChars = await getFilteredChars(result); + + expect(filteredChars.join("")).toBe(`Hello${endOfLineChar}`); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should continue past end of line if only whitespace follows", async () => { + const charGenerator = await getCharGenerator([ + `Hello${endOfLineChar} World`, + ]); + const result = charStream.onlyWhitespaceAfterEndOfLine( + charGenerator, + [endOfLineChar], + mockFullStop, + ); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe(`Hello${endOfLineChar} World`); + expect(mockFullStop).not.toHaveBeenCalled(); + }); + + it("should handle end of line at the end of chunk", async () => { + const charGenerator = await getCharGenerator([ + `Hello${endOfLineChar}`, + "World", + ]); + const result = charStream.onlyWhitespaceAfterEndOfLine( + charGenerator, + [endOfLineChar], + mockFullStop, + ); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe(`Hello${endOfLineChar}`); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + }); + + describe("noFirstCharNewline", () => { + it("should remove leading newline", async () => { + const charGenerator = await getCharGenerator(["\nHello"]); + const result = charStream.noFirstCharNewline(charGenerator); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe(""); + }); + + it("should keep content if no leading newline", async () => { + const charGenerator = await getCharGenerator(["Hello\nWorld"]); + const result = charStream.noFirstCharNewline(charGenerator); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe("Hello\nWorld"); + }); + + it("should remove leading carriage return", async () => { + const charGenerator = await getCharGenerator(["\rHello"]); + const result = charStream.noFirstCharNewline(charGenerator); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe(""); + }); + }); + + describe("stopAtStopTokens", () => { + it("should stop at the first occurrence of a stop token", async () => { + const charGenerator = await getCharGenerator(["Hello<|endoftext|>World"]); + const result = charStream.stopAtStopTokens(charGenerator, [ + "<|endoftext|>", + ]); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe("Hello"); + }); + + it("should return all content if no stop tokens are provided", async () => { + const charGenerator = await getCharGenerator(["Hello<|endoftext|>World"]); + const result = charStream.stopAtStopTokens(charGenerator, []); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe("Hello<|endoftext|>World"); + }); + + it("should handle stop tokens that span multiple chunks", async () => { + const charGenerator = await getCharGenerator([ + "Hello<|", + "endoftext|>World", + ]); + const result = charStream.stopAtStopTokens(charGenerator, [ + "<|endoftext|>", + ]); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe("Hello"); + }); + + it("should yield remaining characters in buffer if no stop token is found", async () => { + const charGenerator = await getCharGenerator(["Hello", "World"]); + const result = charStream.stopAtStopTokens(charGenerator, [ + "<|endoftext|>", + ]); + const filteredChars = await getFilteredChars(result); + expect(filteredChars.join("")).toBe("HelloWorld"); + }); + }); +}); diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/charStream.ts index 0ce49e418..79fc33a0d 100644 --- a/core/autocomplete/charStream.ts +++ b/core/autocomplete/charStream.ts @@ -1,12 +1,24 @@ +/** + * Asynchronous generator that yields characters from the input stream until it encounters + * an end-of-line character followed by a non-whitespace character. + * + * @param {AsyncGenerator} stream - The input stream of characters. + * @param {string[]} endOfLine - An array of characters considered as end-of-line markers. + * @param {() => void} fullStop - A function to be called when the generator stops. + * @yields {string} Characters from the input stream. + * @returns {AsyncGenerator} An async generator that yields characters. + */ export async function* onlyWhitespaceAfterEndOfLine( stream: AsyncGenerator, endOfLine: string[], fullStop: () => void, ): AsyncGenerator { let pending = ""; + for await (let chunk of stream) { chunk = pending + chunk; pending = ""; + for (let i = 0; i < chunk.length - 1; i++) { if ( endOfLine.includes(chunk[i]) && @@ -17,6 +29,7 @@ export async function* onlyWhitespaceAfterEndOfLine( return; } } + if (endOfLine.includes(chunk[chunk.length - 1])) { pending = chunk[chunk.length - 1]; yield chunk.slice(0, chunk.length - 1); @@ -27,6 +40,11 @@ export async function* onlyWhitespaceAfterEndOfLine( yield pending; } +/** + * Yields characters from the stream, stopping if the first character is a newline. + * @param {AsyncGenerator} stream - The input character stream. + * @yields {string} Characters from the stream. + */ export async function* noFirstCharNewline(stream: AsyncGenerator) { let first = true; for await (const char of stream) { @@ -40,6 +58,20 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { } } +/** + * Asynchronously yields characters from the input stream, stopping if a stop token is encountered. + * + * @param {AsyncGenerator} stream - The input stream of characters. + * @param {string[]} stopTokens - Array of tokens that signal when to stop yielding. + * @yields {string} Characters from the input stream. + * @returns {AsyncGenerator} An async generator that yields characters until a stop condition is met. + * @description + * 1. If no stop tokens are provided, yields all characters from the stream. + * 2. Otherwise, buffers incoming chunks and checks for stop tokens. + * 3. Yields characters one by one if no stop token is found at the start of the buffer. + * 4. Stops yielding and returns if a stop token is encountered. + * 5. After the stream ends, yields any remaining buffered characters. + */ export async function* stopAtStopTokens( stream: AsyncGenerator, stopTokens: string[], From d3e31412b08377fd3d04291227ff0ce54c509ded Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 17:21:36 -0700 Subject: [PATCH 082/186] update build to include worker files --- .github/workflows/jetbrains-release.yaml | 4 +++- binary/build.js | 8 ++++++++ binary/pkgJson/darwin-arm64/package.json | 5 ++++- binary/pkgJson/darwin-x64/package.json | 5 ++++- binary/pkgJson/linux-arm64/package.json | 5 ++++- binary/pkgJson/linux-x64/package.json | 5 ++++- binary/pkgJson/win32-arm64/package.json | 5 ++++- binary/pkgJson/win32-x64/package.json | 5 ++++- 8 files changed, 35 insertions(+), 7 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 1d3d96b83..03b2255f9 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -35,7 +35,7 @@ jobs: build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' - name: Publish Plugin + name: Build Plugin runs-on: ubuntu-latest permissions: contents: write @@ -423,6 +423,8 @@ jobs: path: ${{ github.workspace }}/build/reports/pluginVerifier upload-release: + name: Upload Release + needs: build, test-binaries, test, inspectCode, verify runs-on: ubuntu-latest steps: # # Update Unreleased section with the current release note diff --git a/binary/build.js b/binary/build.js index d2f01ee35..4d5861295 100644 --- a/binary/build.js +++ b/binary/build.js @@ -302,6 +302,14 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `${targetDir}/node_sqlite3.node`, ); } + + // Note that this doesn't verify they actually made it into the binary, just that they were in the expected folder before it was built + pathsToVerify.push("out/index.js"); + pathsToVerify.push("out/llamaTokenizerWorkerPool.mjs"); + pathsToVerify.push("out/tiktokenWorkerPool.mjs"); + pathsToVerify.push("out/xhr-sync-worker.js"); + pathsToVerify.push("out/tree-sitter.wasm"); + validateFilesPresent(pathsToVerify); console.log("[info] Done!"); diff --git a/binary/pkgJson/darwin-arm64/package.json b/binary/pkgJson/darwin-arm64/package.json index cc41ae801..ce6f2cace 100644 --- a/binary/pkgJson/darwin-arm64/package.json +++ b/binary/pkgJson/darwin-arm64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-macos-arm64" diff --git a/binary/pkgJson/darwin-x64/package.json b/binary/pkgJson/darwin-x64/package.json index 8ccb256e1..178ef6471 100644 --- a/binary/pkgJson/darwin-x64/package.json +++ b/binary/pkgJson/darwin-x64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-macos-x64" diff --git a/binary/pkgJson/linux-arm64/package.json b/binary/pkgJson/linux-arm64/package.json index 9fe88da50..4a3b2a42f 100644 --- a/binary/pkgJson/linux-arm64/package.json +++ b/binary/pkgJson/linux-arm64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-linux-arm64" diff --git a/binary/pkgJson/linux-x64/package.json b/binary/pkgJson/linux-x64/package.json index 1c875baa0..f62ecede7 100644 --- a/binary/pkgJson/linux-x64/package.json +++ b/binary/pkgJson/linux-x64/package.json @@ -10,7 +10,10 @@ "assets": [ "../../../core/node_modules/sqlite3/**/*", "../../out/tree-sitter.wasm", - "../../out/tree-sitter-wasms/*" + "../../out/tree-sitter-wasms/*", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-linux-x64" diff --git a/binary/pkgJson/win32-arm64/package.json b/binary/pkgJson/win32-arm64/package.json index 3eeb12234..478cf7eb9 100644 --- a/binary/pkgJson/win32-arm64/package.json +++ b/binary/pkgJson/win32-arm64/package.json @@ -13,7 +13,10 @@ "../../out/tree-sitter-wasms/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", - "../../node_modules/win-ca/lib/roots.exe" + "../../node_modules/win-ca/lib/roots.exe", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-win-arm64" diff --git a/binary/pkgJson/win32-x64/package.json b/binary/pkgJson/win32-x64/package.json index 2e495524b..c466fc942 100644 --- a/binary/pkgJson/win32-x64/package.json +++ b/binary/pkgJson/win32-x64/package.json @@ -13,7 +13,10 @@ "../../out/tree-sitter-wasms/*", "../../node_modules/win-ca/lib/crypt32-ia32.node", "../../node_modules/win-ca/lib/crypt32-x64.node", - "../../node_modules/win-ca/lib/roots.exe" + "../../node_modules/win-ca/lib/roots.exe", + "../../out/llamaTokenizer.mjs", + "../../out/llamaTokenizerWorkerPool.mjs", + "../../out/tiktokenWorkerPool.mjs" ], "targets": [ "node18-win-x64" From 3a443b81b79eb3bf526216eb05aa065024581484 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 17:22:13 -0700 Subject: [PATCH 083/186] Update dev_pr.yaml --- .github/workflows/dev_pr.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index de45e9523..3ccf09c18 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -46,7 +46,7 @@ jobs: - name: extensions/vscode install run: | - cd + cd extensions/vscode npm ci env: # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 @@ -68,10 +68,12 @@ jobs: npm ci npx tsc --noEmit npm run lint + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - name: gui install run: | - cd + cd gui npm ci - name: gui checks @@ -81,7 +83,7 @@ jobs: - name: binary install run: | - cd + cd binary npm ci - name: binary checks From 48d30307b824938a28facc3da5c010333bf804e4 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 17:25:06 -0700 Subject: [PATCH 084/186] update ci --- .github/workflows/jetbrains-release.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 03b2255f9..798f0c1e3 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -424,7 +424,12 @@ jobs: upload-release: name: Upload Release - needs: build, test-binaries, test, inspectCode, verify + needs: + - build + - test-binaries + - test + - inspectCode + - verify runs-on: ubuntu-latest steps: # # Update Unreleased section with the current release note From d3ec41e4086f4ae2e91adadaa65b08d3ea83ef5d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 17:26:00 -0700 Subject: [PATCH 085/186] ci changes --- .github/workflows/jetbrains-release.yaml | 39 +++++++++++++----------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 798f0c1e3..086a2e379 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -5,8 +5,11 @@ name: Release on: - release: - types: [prereleased] + push: + branches: + - nate/apple-developer-finally + # release: + # types: [prereleased] defaults: run: @@ -17,23 +20,23 @@ concurrency: cancel-in-progress: true jobs: - check_release_name: - runs-on: ubuntu-latest - outputs: - should_run: ${{ steps.check.outputs.should_run }} - steps: - - id: check - working-directory: . - run: | - if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then - echo "should_run=true" >> $GITHUB_OUTPUT - else - echo "should_run=false" >> $GITHUB_OUTPUT - fi + # check_release_name: + # runs-on: ubuntu-latest + # outputs: + # should_run: ${{ steps.check.outputs.should_run }} + # steps: + # - id: check + # working-directory: . + # run: | + # if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then + # echo "should_run=true" >> $GITHUB_OUTPUT + # else + # echo "should_run=false" >> $GITHUB_OUTPUT + # fi # Prepare and publish the plugin to JetBrains Marketplace repository build: - needs: check_release_name + # needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin runs-on: ubuntu-latest @@ -44,8 +47,8 @@ jobs: # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 - with: - ref: ${{ github.event.release.tag_name }} + # with: + # ref: ${{ github.event.release.tag_name }} # Validate wrapper - name: Gradle Wrapper Validation From cca2af87b597a3fbd8f5ac7addf25fa9ea25cd64 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 17:28:41 -0700 Subject: [PATCH 086/186] update --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 086a2e379..85b444b97 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -37,7 +37,7 @@ jobs: # Prepare and publish the plugin to JetBrains Marketplace repository build: # needs: check_release_name - if: needs.check_release_name.outputs.should_run == 'true' + # if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin runs-on: ubuntu-latest permissions: From eded88edd7ad8f6ea9eda12c0039928db60b7d18 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 17:29:33 -0700 Subject: [PATCH 087/186] Update dev_pr.yaml --- .github/workflows/dev_pr.yaml | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index 3ccf09c18..d909a279a 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -52,16 +52,26 @@ jobs: # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - name: extensions/vscode checks - run: | - cd extensions/vscode - npx tsc --noEmit - - name: core install run: | cd core npm ci + - name: gui install + run: | + cd gui + npm ci + + - name: binary install + run: | + cd binary + npm ci + + - name: extensions/vscode checks + run: | + cd extensions/vscode + npx tsc --noEmit + - name: core checks run: | cd core @@ -71,21 +81,11 @@ jobs: env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - - name: gui install - run: | - cd gui - npm ci - - name: gui checks run: | cd gui npx tsc --noEmit - - name: binary install - run: | - cd binary - npm ci - - name: binary checks run: | cd binary From ed416d0bfe918edfbac3617631838c49f594a7bb Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 16 Aug 2024 17:36:45 -0700 Subject: [PATCH 088/186] update tsconfig --- .../providers/{index.skip.ts => index.test.ts} | 2 +- extensions/vscode/tsconfig.json | 12 ++++-------- 2 files changed, 5 insertions(+), 9 deletions(-) rename core/test/context/providers/{index.skip.ts => index.test.ts} (96%) diff --git a/core/test/context/providers/index.skip.ts b/core/test/context/providers/index.test.ts similarity index 96% rename from core/test/context/providers/index.skip.ts rename to core/test/context/providers/index.test.ts index f5da28fab..ae16ccb87 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/test/context/providers/index.test.ts @@ -46,7 +46,7 @@ async function getContextProviderExtras( }; } -describe("Should successfully run all context providers", () => { +describe.skip("Should successfully run all context providers", () => { const extrasPromise = getContextProviderExtras("Test"); CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => { diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index 639fc167c..d2f8575e0 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -6,16 +6,12 @@ "outDir": "out/tsc/src", "sourceMap": true, "rootDir": "../../", - "strict": true /* enable all strict type-checking options */, - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, - "resolveJsonModule": true /* Enable importing .json files */, + "strict": true, + "esModuleInterop": true, + "resolveJsonModule": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], // core/test uses @types/jest, which conflicts with @types/mocha - "exclude": ["../../core/dist/**/*", "../../core/test/**/*"] + "exclude": ["../../core/dist/**/*", "../../core/**/*.test.ts"] } From 567fbb38991ac1173ed4fb859bd528ae6aaec0cc Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Aug 2024 21:58:32 -0700 Subject: [PATCH 089/186] code sign --- .github/workflows/jetbrains-release.yaml | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 85b444b97..50ebbc2e2 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -151,6 +151,32 @@ jobs: cd ../../binary npm run build + - name: Sign darwin-arm64 binary + uses: lando/code-sign-action@v2 + with: + file: ./binary/bin/darwin-arm64/continue-binary + certificate-data: ${{ secrets.APPLE_CERT_DATA }} + certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} + apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} + apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} + apple-notary-tool: altool + apple-team-id: 43XFLY66ZD + apple-product-id: dev.continue.continue-binary + options: --options runtime --entitlements entitlements.xml + + - name: Sign darwin-x64 binary + uses: lando/code-sign-action@v2 + with: + file: ./binary/bin/darwin-x64/continue-binary + certificate-data: ${{ secrets.APPLE_CERT_DATA }} + certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} + apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} + apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} + apple-notary-tool: altool + apple-team-id: 43XFLY66ZD + apple-product-id: dev.continue.continue-binary + options: --options runtime --entitlements entitlements.xml + # Build plugin - name: Build plugin run: ./gradlew buildPlugin From 1546aed5c96f11e504b333608aa51207d6bd40f0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Aug 2024 09:05:36 -0700 Subject: [PATCH 090/186] run on mac --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 50ebbc2e2..14c496083 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -39,7 +39,7 @@ jobs: # needs: check_release_name # if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin - runs-on: ubuntu-latest + runs-on: macos-latest permissions: contents: write pull-requests: write From 455534263a9aac29064fdd87cde6d1808e60103c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Aug 2024 09:57:07 -0700 Subject: [PATCH 091/186] macos-11 --- .github/workflows/jetbrains-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 14c496083..d64f14a87 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -39,7 +39,7 @@ jobs: # needs: check_release_name # if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin - runs-on: macos-latest + runs-on: macos-11 permissions: contents: write pull-requests: write From 8551ea1f41d25b4815ce4420dfd5e151d3befe54 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Aug 2024 10:09:34 -0700 Subject: [PATCH 092/186] OpenRouter LLM Provider --- core/index.d.ts | 3 ++- core/llm/llms/OpenRouter.ts | 17 +++++++++++++++++ core/llm/llms/index.ts | 2 ++ docs/static/schemas/config.json | 6 ++++-- .../src/main/resources/config_schema.json | 6 ++++-- extensions/vscode/config_schema.json | 7 +++++-- extensions/vscode/continue_rc_schema.json | 6 ++++-- 7 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 core/llm/llms/OpenRouter.ts diff --git a/core/index.d.ts b/core/index.d.ts index b0505e1ae..1dc806f88 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -610,7 +610,8 @@ type ModelProvider = | "azure" | "openai-aiohttp" | "msty" - | "watsonx"; + | "watsonx" + | "openrouter"; export type ModelName = | "AUTODETECT" diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts new file mode 100644 index 000000000..d01a19ec5 --- /dev/null +++ b/core/llm/llms/OpenRouter.ts @@ -0,0 +1,17 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; +import OpenAI from "./OpenAI.js"; + +class OpenRouter extends OpenAI { + static providerName: ModelProvider = "openrouter"; + static defaultOptions: Partial = { + apiBase: "https://openrouter.ai/api/v1/", + model: "gpt-4o-mini", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; +} + +export default OpenRouter; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cd084207e..56ff2dff4 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -29,6 +29,7 @@ import Mistral from "./Mistral"; import Msty from "./Msty"; import Ollama from "./Ollama"; import OpenAI from "./OpenAI"; +import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import TextGenWebUI from "./TextGenWebUI"; @@ -64,6 +65,7 @@ const LLMs = [ Msty, Azure, WatsonX, + OpenRouter, ]; export async function llmFromDescription( diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index faac345c2..2b8f5a9e3 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -214,7 +215,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index faac345c2..2b8f5a9e3 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -214,7 +215,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index faac345c2..f6611bea0 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +216,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 815ed50c5..06d9cdd50 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -192,7 +192,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -217,7 +218,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, From f34b06fb83e700a6407374b6017d0a98378f47f3 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Aug 2024 12:31:15 -0700 Subject: [PATCH 093/186] temporary fix for encoding packaging issues --- binary/README.md | 12 ++++++++++++ binary/build.js | 1 + core/llm/asyncEncoder.ts | 14 ++++++++------ core/llm/countTokens.ts | 23 +++++++++++++++++++++-- 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/binary/README.md b/binary/README.md index beff54b4b..741cc425f 100644 --- a/binary/README.md +++ b/binary/README.md @@ -30,3 +30,15 @@ The build process is otherwise defined entirely in `build.js`. ## Debugging To debug the binary with IntelliJ, set `useTcp` to `true` in `CoreMessenger.kt`, and then in VS Code run the "Core Binary" debug script. Instead of starting a subprocess for the binary and communicating over stdin/stdout, the IntelliJ extension will connect over TCP to the server started from the VS Code window. You can place breakpoints anywhere in the `core` or `binary` folders. + +## Building + +```bash +npm run build +``` + +## Testing + +```bash +npm run test +``` diff --git a/binary/build.js b/binary/build.js index 4d5861295..1ebc4b196 100644 --- a/binary/build.js +++ b/binary/build.js @@ -162,6 +162,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { "../core/vendor/tree-sitter.wasm", "../core/llm/llamaTokenizerWorkerPool.mjs", "../core/llm/llamaTokenizer.mjs", + "../core/llm/tiktokenWorkerPool.mjs", ]; for (const f of filesToCopy) { fs.copyFileSync( diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index ed6425df2..5fd39eed6 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -1,7 +1,5 @@ -import llamaTokenizer from "./llamaTokenizer.js"; -import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; +import path from "path"; import workerpool from "workerpool"; -import * as path from "path"; export interface AsyncEncoder { encode(text: string): Promise; @@ -13,7 +11,9 @@ export class LlamaAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("llamaTokenizerWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -35,7 +35,9 @@ export class GPTAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("tiktokenWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -58,4 +60,4 @@ function workerCodeFilePath(workerFileName: string): string { return path.join(__dirname, "llm", workerFileName); } return path.join(__dirname, workerFileName); -} \ No newline at end of file +} diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 5d042e3ca..06cd4a3bb 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -24,18 +24,37 @@ class LlamaEncoding implements Encoding { } } +class NonWorkerAsyncEncoder implements AsyncEncoder { + constructor(private readonly encoding: Encoding) {} + + async close(): Promise {} + + async encode(text: string): Promise { + return this.encoding.encode(text); + } + + async decode(tokens: number[]): Promise { + return this.encoding.decode(tokens); + } +} + let gptEncoding: Encoding | null = null; const gptAsyncEncoder = new GPTAsyncEncoder(); const llamaEncoding = new LlamaEncoding(); const llamaAsyncEncoder = new LlamaAsyncEncoder(); function asyncEncoderForModel(modelName: string): AsyncEncoder { + // Temporary due to issues packaging the worker files + if (process.env.IS_BINARY) { + const encoding = encodingForModel(modelName); + return new NonWorkerAsyncEncoder(encoding); + } + const modelType = autodetectTemplateType(modelName); if (!modelType || modelType === "none") { return gptAsyncEncoder; } - // Temporary due to issues packaging the worker files - return process.env.IS_BINARY ? gptAsyncEncoder : llamaAsyncEncoder; + return llamaAsyncEncoder; } function encodingForModel(modelName: string): Encoding { From d28d32c5046f8915da1866cbf1d61153be29bd0a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Aug 2024 19:35:42 -0700 Subject: [PATCH 094/186] try to sign only darwin-x64 --- .github/workflows/jetbrains-release.yaml | 26 ++++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index d64f14a87..26d014dce 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -39,7 +39,7 @@ jobs: # needs: check_release_name # if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin - runs-on: macos-11 + runs-on: macos-latest permissions: contents: write pull-requests: write @@ -151,18 +151,18 @@ jobs: cd ../../binary npm run build - - name: Sign darwin-arm64 binary - uses: lando/code-sign-action@v2 - with: - file: ./binary/bin/darwin-arm64/continue-binary - certificate-data: ${{ secrets.APPLE_CERT_DATA }} - certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} - apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} - apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} - apple-notary-tool: altool - apple-team-id: 43XFLY66ZD - apple-product-id: dev.continue.continue-binary - options: --options runtime --entitlements entitlements.xml + # - name: Sign darwin-arm64 binary + # uses: lando/code-sign-action@v2 + # with: + # file: ./binary/bin/darwin-arm64/continue-binary + # certificate-data: ${{ secrets.APPLE_CERT_DATA }} + # certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} + # apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} + # apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} + # apple-notary-tool: altool + # apple-team-id: 43XFLY66ZD + # apple-product-id: dev.continue.continue-binary + # options: --options runtime --entitlements entitlements.xml - name: Sign darwin-x64 binary uses: lando/code-sign-action@v2 From 2c0c591f3fb978074c2c047227d5b6202c2778fa Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 09:36:06 -0700 Subject: [PATCH 095/186] codesign --- .github/workflows/jetbrains-release.yaml | 61 +++++++++++++++++++----- 1 file changed, 49 insertions(+), 12 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 26d014dce..3bc5ba875 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -50,6 +50,29 @@ jobs: # with: # ref: ${{ github.event.release.tag_name }} + - name: Import Apple certificate + uses: apple-actions/import-codesign-certs@v3 + with: + keychain: ${{ github.run_id }} + keychain-password: ${{ github.run_id }} + p12-file-base64: ${{ secrets.APPLE_CERT_DATA }} + p12-password: ${{ secrets.APPLE_CERT_PASSWORD }} + + # - name: Download artifact + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # OWNER: continuedev + # REPO: continue + # ARTIFACT_ID: 1822461754 + # run: | + # curl -L \ + # -H "Authorization: token $GITHUB_TOKEN" \ + # -H "Accept: application/vnd.github+json" \ + # -o artifact.zip \ + # "https://api.github.com/repos/continuedev/continue/actions/artifacts/1822461754/zip" + # unzip artifact.zip + # shell: bash + # Validate wrapper - name: Gradle Wrapper Validation uses: gradle/actions/wrapper-validation@v3 @@ -151,6 +174,20 @@ jobs: cd ../../binary npm run build + - name: Code sign darwin-arm64 binary + run: | + echo "Signing executable with keychain: ${{ github.run_id }}" + codesign --sign - ../../binary/bin/darwin-x64/continue-binary + codesign --sign - ../../binary/bin/darwin-arm64/continue-binary + + - name: Validate codesigning + run: | + echo "Validating codesigning for darwin-x64 binary" + codesign -dv --verbose=4 ../../binary/bin/darwin-x64/continue-binary + + echo "Validating codesigning for darwin-arm64 binary" + codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary + # - name: Sign darwin-arm64 binary # uses: lando/code-sign-action@v2 # with: @@ -164,18 +201,18 @@ jobs: # apple-product-id: dev.continue.continue-binary # options: --options runtime --entitlements entitlements.xml - - name: Sign darwin-x64 binary - uses: lando/code-sign-action@v2 - with: - file: ./binary/bin/darwin-x64/continue-binary - certificate-data: ${{ secrets.APPLE_CERT_DATA }} - certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} - apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} - apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} - apple-notary-tool: altool - apple-team-id: 43XFLY66ZD - apple-product-id: dev.continue.continue-binary - options: --options runtime --entitlements entitlements.xml + # - name: Sign darwin-x64 binary + # uses: lando/code-sign-action@v2 + # with: + # file: ./binary/bin/darwin-x64/continue-binary + # certificate-data: ${{ secrets.APPLE_CERT_DATA }} + # certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} + # apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} + # apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} + # apple-notary-tool: altool + # apple-team-id: 43XFLY66ZD + # apple-product-id: dev.continue.continue-binary + # options: --options runtime --entitlements entitlements.xml # Build plugin - name: Build plugin From 942cd50583521f418c393120cd4bad71135df35c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 12:55:00 -0700 Subject: [PATCH 096/186] already codesigned --- .github/workflows/jetbrains-release.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 3bc5ba875..5d1cbb918 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -174,11 +174,11 @@ jobs: cd ../../binary npm run build - - name: Code sign darwin-arm64 binary - run: | - echo "Signing executable with keychain: ${{ github.run_id }}" - codesign --sign - ../../binary/bin/darwin-x64/continue-binary - codesign --sign - ../../binary/bin/darwin-arm64/continue-binary + # - name: Code sign darwin binaries + # run: | + # echo "Signing executable with keychain: ${{ github.run_id }}" + # codesign --sign - ../../binary/bin/darwin-x64/continue-binary + # codesign --sign - ../../binary/bin/darwin-arm64/continue-binary - name: Validate codesigning run: | From 1f2a58e24ec9557e69f717c1bbf205b0485cc39e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 13:07:35 -0700 Subject: [PATCH 097/186] fix logstash loading bug --- core/control-plane/analytics/LogStashAnalyticsProvider.ts | 3 ++- docs/static/schemas/config.json | 1 + extensions/intellij/src/main/resources/config_schema.json | 1 + extensions/vscode/continue_rc_schema.json | 1 + 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index 59d72432a..aa35af43e 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -30,7 +30,8 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider { async setup(config: Analytics, uniqueId: string): Promise { if (!config.url) { - throw new Error("Missing url in analytics config"); + console.warn("LogStashAnalyticsProvider is missing a URL"); + return; } const url = new URL(config.url); this.host = url.hostname; diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 2b8f5a9e3..f6611bea0 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -198,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 2b8f5a9e3..f6611bea0 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -198,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 06d9cdd50..5bcfaa05c 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -201,6 +201,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", From d5522a989f1636bcacc18087836b452be9f788d1 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 15:03:39 -0700 Subject: [PATCH 098/186] publish to eap and stable --- binary/package-lock.json | 1 + extensions/intellij/build.gradle.kts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index 9378d2eef..b57800a29 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -79,6 +79,7 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index e3eba0461..27f108b4a 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -142,6 +142,6 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = properties("pluginVersion").map { listOf(it.split('-').getOrElse(1) { "default" }.split('.').first()) } + channels = ['eap', 'default'] } } From 5b38fc96dcb17e9dd25d09e93f625ff1bbb3d292 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 15:29:40 -0700 Subject: [PATCH 099/186] change ordering --- .github/workflows/jetbrains-release.yaml | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 5d1cbb918..1baa12202 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -140,22 +140,11 @@ jobs: cd ../../core npm ci - # npm install binary - - name: Install binary node_modules - run: | - cd ../../binary - npm ci - # npm install gui - - name: Install gui node_modules + - name: Install gui node_modules and build run: | cd ../../gui npm ci - - # build gui - - name: Build gui - run: | - cd ../../gui npm run build # Run prepackage.js script @@ -168,6 +157,12 @@ jobs: # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + # npm install binary + - name: Install binary node_modules + run: | + cd ../../binary + npm ci + # Build binaries - name: Build the binaries run: | @@ -224,6 +219,9 @@ jobs: shell: bash run: | cd ../../extensions/intellij/build/distributions + echo "Builds:" + ls + echo "---" FILENAME=`ls *.zip` unzip "$FILENAME" -d content From fd69ed69289009842aa002a15aab16f89860b4b6 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 15:33:45 -0700 Subject: [PATCH 100/186] fix build file --- extensions/intellij/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 27f108b4a..956a3e73e 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -142,6 +142,6 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = ['eap', 'default'] + channels = ["eap", "default"] } } From b675a70eb0d686a20624ba8c0a43e10330cf4d4f Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 15:35:00 -0700 Subject: [PATCH 101/186] again --- extensions/intellij/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 956a3e73e..766cf3ebd 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -142,6 +142,6 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = ["eap", "default"] + channels.set(listOf("eap", "default")) } } From fd9fa36e27aa436a39ee2baf6e6a1b839978f73a Mon Sep 17 00:00:00 2001 From: Cheng Zhu Date: Sun, 18 Aug 2024 17:53:39 -0700 Subject: [PATCH 102/186] added @ open files context provider "pinned" option. --- .../continue/IdeProtocolClient.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) 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 e8aa27b6c..cead14fbf 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 @@ -31,6 +31,7 @@ import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor +import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware @@ -44,6 +45,8 @@ import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint +import com.intellij.ui.content.ContentManagerUtil +import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.* import java.awt.Toolkit import java.awt.datatransfer.StringSelection @@ -605,8 +608,10 @@ class IdeProtocolClient ( respond(currentFile) } "getPinnedFiles" -> { - val openFiles = visibleFiles() - respond(openFiles) + ApplicationManager.getApplication().invokeLater { + val pinnedFiles = pinnedFiles() + respond(pinnedFiles) + } } "insertAtCursor" -> { val msg = data as Map; @@ -964,6 +969,14 @@ class IdeProtocolClient ( return fileEditorManager.openFiles.toList().map { it.path } } + @RequiresEdt + private fun pinnedFiles(): List { + val fileEditorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return listOf() + val openFiles = fileEditorManager.openFiles.map { it.path }.toList() + val pinnedFiles = fileEditorManager.windows.flatMap { window -> window.files.filter { window.isFilePinned(it) } }.map { it.path }.toSet() + return openFiles.intersect(pinnedFiles).toList() + } + private fun currentFile(): String? { val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor From 1821e1ebb5a2018e556d22dea6ea04a31270772c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:30:58 -0700 Subject: [PATCH 103/186] test --- .github/workflows/jetbrains-release.yaml | 167 +++++++++++------------ 1 file changed, 78 insertions(+), 89 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 1baa12202..9520c4823 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -11,9 +11,9 @@ on: # release: # types: [prereleased] -defaults: - run: - working-directory: extensions/intellij +# defaults: +# run: +# working-directory: extensions/intellij concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -58,62 +58,47 @@ jobs: p12-file-base64: ${{ secrets.APPLE_CERT_DATA }} p12-password: ${{ secrets.APPLE_CERT_PASSWORD }} - # - name: Download artifact - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # OWNER: continuedev - # REPO: continue - # ARTIFACT_ID: 1822461754 - # run: | - # curl -L \ - # -H "Authorization: token $GITHUB_TOKEN" \ - # -H "Accept: application/vnd.github+json" \ - # -o artifact.zip \ - # "https://api.github.com/repos/continuedev/continue/actions/artifacts/1822461754/zip" - # unzip artifact.zip - # shell: bash - # Validate wrapper - - name: Gradle Wrapper Validation - uses: gradle/actions/wrapper-validation@v3 + # - name: Gradle Wrapper Validation + # uses: gradle/actions/wrapper-validation@v3 - # Set up Java environment for the next steps - - name: Setup Java - uses: actions/setup-java@v4 - with: - distribution: zulu - java-version: 17 + # # Set up Java environment for the next steps + # - name: Setup Java + # uses: actions/setup-java@v4 + # with: + # distribution: zulu + # java-version: 17 - # Setup Gradle - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - with: - gradle-home-cache-cleanup: true + # # Setup Gradle + # - name: Setup Gradle + # uses: gradle/actions/setup-gradle@v3 + # with: + # gradle-home-cache-cleanup: true - # Set environment variables - - name: Export Properties - id: properties - shell: bash - run: | - PROPERTIES="$(./gradlew properties --console=plain -q)" - VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" - # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" - CHANGELOG="" + # # Set environment variables + # - name: Export Properties + # id: properties + # shell: bash + # run: | + # PROPERTIES="$(./gradlew properties --console=plain -q)" + # VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" + # # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" + # CHANGELOG="" - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT + # echo "version=$VERSION" >> $GITHUB_OUTPUT + # echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT - echo "changelog<> $GITHUB_OUTPUT - echo "$CHANGELOG" >> $GITHUB_OUTPUT - echo "EOF" >> $GITHUB_OUTPUT + # echo "changelog<> $GITHUB_OUTPUT + # echo "$CHANGELOG" >> $GITHUB_OUTPUT + # echo "EOF" >> $GITHUB_OUTPUT - ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier + # ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier - # Setup Node.js - - name: Use Node.js from .nvmrc - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" + # # Setup Node.js + # - name: Use Node.js from .nvmrc + # uses: actions/setup-node@v4 + # with: + # node-version-file: ".nvmrc" # Cache node_modules - name: Cache core node_modules @@ -128,11 +113,11 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + # - name: Cache gui node_modules + # uses: actions/cache@v3 + # with: + # path: gui/node_modules + # key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} # npm install core - name: Install core node_modules @@ -141,21 +126,21 @@ jobs: npm ci # npm install gui - - name: Install gui node_modules and build - run: | - cd ../../gui - npm ci - npm run build + # - name: Install gui node_modules and build + # run: | + # cd ../../gui + # npm ci + # npm run build # Run prepackage.js script - - name: Run prepackage script - run: | - cd ../../extensions/vscode - npm ci - npm run prepackage - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + # - name: Run prepackage script + # run: | + # cd ../../extensions/vscode + # npm ci + # npm run prepackage + # env: + # # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + # GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} # npm install binary - name: Install binary node_modules @@ -183,6 +168,10 @@ jobs: echo "Validating codesigning for darwin-arm64 binary" codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary + - name: Try to run the darwin-arm64 binary + run: | + ../../binary/bin/darwin-arm64/continue-binary + # - name: Sign darwin-arm64 binary # uses: lando/code-sign-action@v2 # with: @@ -210,29 +199,29 @@ jobs: # options: --options runtime --entitlements entitlements.xml # Build plugin - - name: Build plugin - run: ./gradlew buildPlugin + # - name: Build plugin + # run: ./gradlew buildPlugin - # Prepare plugin archive content for creating artifact - - name: Prepare Plugin Artifact - id: artifact - shell: bash - run: | - cd ../../extensions/intellij/build/distributions - echo "Builds:" - ls - echo "---" - FILENAME=`ls *.zip` - unzip "$FILENAME" -d content + # # Prepare plugin archive content for creating artifact + # - name: Prepare Plugin Artifact + # id: artifact + # shell: bash + # run: | + # cd ../../extensions/intellij/build/distributions + # echo "Builds:" + # ls + # echo "---" + # FILENAME=`ls *.zip` + # unzip "$FILENAME" -d content - echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT + # echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT - # Store already-built plugin as an artifact for downloading - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: ${{ steps.artifact.outputs.filename }} - path: ./extensions/intellij/build/distributions/content/*/* + # # Store already-built plugin as an artifact for downloading + # - name: Upload artifact + # uses: actions/upload-artifact@v4 + # with: + # name: ${{ steps.artifact.outputs.filename }} + # path: ./extensions/intellij/build/distributions/content/*/* # Upload binaries as artifacts - name: Upload artifact (darwin-arm64) From 83b7fed21eaa0767291ce6fb14c4f6b5e7b4c5e3 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:31:16 -0700 Subject: [PATCH 104/186] test again --- .github/workflows/jetbrains-release.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 9520c4823..f19c09d4c 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -11,9 +11,9 @@ on: # release: # types: [prereleased] -# defaults: -# run: -# working-directory: extensions/intellij +defaults: + run: + working-directory: extensions/intellij concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} From 05d4e0f314ead25d1225055c23e2f07042288d4b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:31:50 -0700 Subject: [PATCH 105/186] change default path --- .github/workflows/jetbrains-release.yaml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index f19c09d4c..ee6db0646 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -11,9 +11,9 @@ on: # release: # types: [prereleased] -defaults: - run: - working-directory: extensions/intellij +# defaults: +# run: +# working-directory: extensions/intellij concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -122,7 +122,7 @@ jobs: # npm install core - name: Install core node_modules run: | - cd ../../core + cd core npm ci # npm install gui @@ -145,13 +145,13 @@ jobs: # npm install binary - name: Install binary node_modules run: | - cd ../../binary + cd binary npm ci # Build binaries - name: Build the binaries run: | - cd ../../binary + cd binary npm run build # - name: Code sign darwin binaries @@ -170,7 +170,7 @@ jobs: - name: Try to run the darwin-arm64 binary run: | - ../../binary/bin/darwin-arm64/continue-binary + ./binary/bin/darwin-arm64/continue-binary # - name: Sign darwin-arm64 binary # uses: lando/code-sign-action@v2 From c1ae7edcfb2fb71eceecb0cf190227b674007e15 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:37:55 -0700 Subject: [PATCH 106/186] test --- .github/workflows/jetbrains-release.yaml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index ee6db0646..33dcf6a9f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -133,14 +133,14 @@ jobs: # npm run build # Run prepackage.js script - # - name: Run prepackage script - # run: | - # cd ../../extensions/vscode - # npm ci - # npm run prepackage - # env: - # # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - # GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + - name: Run prepackage script + run: | + cd extensions/vscode + npm ci + npm run prepackage + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} # npm install binary - name: Install binary node_modules From 0aadbaca308f5d7b59b3c2fab97e837a2c755b7f Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:42:07 -0700 Subject: [PATCH 107/186] fix test --- .github/workflows/jetbrains-release.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 33dcf6a9f..58a725cc1 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -160,13 +160,13 @@ jobs: # codesign --sign - ../../binary/bin/darwin-x64/continue-binary # codesign --sign - ../../binary/bin/darwin-arm64/continue-binary - - name: Validate codesigning - run: | - echo "Validating codesigning for darwin-x64 binary" - codesign -dv --verbose=4 ../../binary/bin/darwin-x64/continue-binary + # - name: Validate codesigning + # run: | + # echo "Validating codesigning for darwin-x64 binary" + # codesign -dv --verbose=4 ../../binary/bin/darwin-x64/continue-binary - echo "Validating codesigning for darwin-arm64 binary" - codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary + # echo "Validating codesigning for darwin-arm64 binary" + # codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary - name: Try to run the darwin-arm64 binary run: | From a25d56b5430e941e562296e764e2ba4f1e8b0dec Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 18:49:22 -0700 Subject: [PATCH 108/186] test 2 --- .github/workflows/jetbrains-release.yaml | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 58a725cc1..53673d144 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -95,10 +95,10 @@ jobs: # ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier # # Setup Node.js - # - name: Use Node.js from .nvmrc - # uses: actions/setup-node@v4 - # with: - # node-version-file: ".nvmrc" + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" # Cache node_modules - name: Cache core node_modules @@ -168,6 +168,18 @@ jobs: # echo "Validating codesigning for darwin-arm64 binary" # codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary + - name: Upload artifact (darwin-arm64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-arm64 + path: ./binary/bin/darwin-arm64/ + + - name: Upload artifact (darwin-x64) + uses: actions/upload-artifact@v4 + with: + name: continue-binary-darwin-x64 + path: ./binary/bin/darwin-x64/ + - name: Try to run the darwin-arm64 binary run: | ./binary/bin/darwin-arm64/continue-binary From 0f24577bd103f7b2742ac992ee0da174be93c043 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 20:49:48 -0700 Subject: [PATCH 109/186] fix build to include package.json --- binary/build.js | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/binary/build.js b/binary/build.js index 1ebc4b196..cf8a2420b 100644 --- a/binary/build.js +++ b/binary/build.js @@ -238,17 +238,16 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { }.tar.gz`; execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); - fs.copyFileSync( - `${targetDir}/build/Release/node_sqlite3.node`, - `${targetDir}/node_sqlite3.node`, - ); + + // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + fs.writeFileSync(`${targetDir}/package.json`, ""); // Copy to build directory for testing try { const [platform, arch] = target.split("-"); if (platform === currentPlatform && arch === currentArch) { fs.copyFileSync( - `${targetDir}/node_sqlite3.node`, + `${targetDir}/build/Release/node_sqlite3.node`, `build/node_sqlite3.node`, ); } @@ -258,10 +257,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } fs.unlinkSync(`${targetDir}/build.tar.gz`); - fs.rmSync(`${targetDir}/build`, { - recursive: true, - force: true, - }); // Download and unzip prebuilt esbuild binary for the target console.log(`[info] Downloading esbuild for ${target}...`); @@ -300,7 +295,8 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `${targetDir}/continue-binary${exe}`, `${targetDir}/esbuild${exe}`, `${targetDir}/index.node`, // @lancedb - `${targetDir}/node_sqlite3.node`, + "package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + `${targetDir}/build/Release/node_sqlite3.node`, ); } From d895d6471991d88d5b389576e4e2f172e10c62fd Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 21:00:55 -0700 Subject: [PATCH 110/186] revert CI --- .github/workflows/jetbrains-release.yaml | 142 ++++++++++------------- 1 file changed, 63 insertions(+), 79 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 53673d144..6ade07b71 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -11,9 +11,9 @@ on: # release: # types: [prereleased] -# defaults: -# run: -# working-directory: extensions/intellij +defaults: + run: + working-directory: extensions/intellij concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -59,40 +59,40 @@ jobs: p12-password: ${{ secrets.APPLE_CERT_PASSWORD }} # Validate wrapper - # - name: Gradle Wrapper Validation - # uses: gradle/actions/wrapper-validation@v3 + - name: Gradle Wrapper Validation + uses: gradle/actions/wrapper-validation@v3 # # Set up Java environment for the next steps - # - name: Setup Java - # uses: actions/setup-java@v4 - # with: - # distribution: zulu - # java-version: 17 + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 17 # # Setup Gradle - # - name: Setup Gradle - # uses: gradle/actions/setup-gradle@v3 - # with: - # gradle-home-cache-cleanup: true + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true - # # Set environment variables - # - name: Export Properties - # id: properties - # shell: bash - # run: | - # PROPERTIES="$(./gradlew properties --console=plain -q)" - # VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" - # # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" - # CHANGELOG="" + # Set environment variables + - name: Export Properties + id: properties + shell: bash + run: | + PROPERTIES="$(./gradlew properties --console=plain -q)" + VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" + # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" + CHANGELOG="" - # echo "version=$VERSION" >> $GITHUB_OUTPUT - # echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT - # echo "changelog<> $GITHUB_OUTPUT - # echo "$CHANGELOG" >> $GITHUB_OUTPUT - # echo "EOF" >> $GITHUB_OUTPUT + echo "changelog<> $GITHUB_OUTPUT + echo "$CHANGELOG" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT - # ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier + ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier # # Setup Node.js - name: Use Node.js from .nvmrc @@ -113,29 +113,29 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} - # - name: Cache gui node_modules - # uses: actions/cache@v3 - # with: - # path: gui/node_modules - # key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} # npm install core - name: Install core node_modules run: | - cd core + cd ../../core npm ci # npm install gui - # - name: Install gui node_modules and build - # run: | - # cd ../../gui - # npm ci - # npm run build + - name: Install gui node_modules and build + run: | + cd ../../gui + npm ci + npm run build # Run prepackage.js script - name: Run prepackage script run: | - cd extensions/vscode + cd ../../extensions/vscode npm ci npm run prepackage env: @@ -145,13 +145,13 @@ jobs: # npm install binary - name: Install binary node_modules run: | - cd binary + cd ../../binary npm ci # Build binaries - name: Build the binaries run: | - cd binary + cd ../../binary npm run build # - name: Code sign darwin binaries @@ -168,22 +168,6 @@ jobs: # echo "Validating codesigning for darwin-arm64 binary" # codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary - - name: Upload artifact (darwin-arm64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-arm64 - path: ./binary/bin/darwin-arm64/ - - - name: Upload artifact (darwin-x64) - uses: actions/upload-artifact@v4 - with: - name: continue-binary-darwin-x64 - path: ./binary/bin/darwin-x64/ - - - name: Try to run the darwin-arm64 binary - run: | - ./binary/bin/darwin-arm64/continue-binary - # - name: Sign darwin-arm64 binary # uses: lando/code-sign-action@v2 # with: @@ -211,29 +195,29 @@ jobs: # options: --options runtime --entitlements entitlements.xml # Build plugin - # - name: Build plugin - # run: ./gradlew buildPlugin + - name: Build plugin + run: ./gradlew buildPlugin - # # Prepare plugin archive content for creating artifact - # - name: Prepare Plugin Artifact - # id: artifact - # shell: bash - # run: | - # cd ../../extensions/intellij/build/distributions - # echo "Builds:" - # ls - # echo "---" - # FILENAME=`ls *.zip` - # unzip "$FILENAME" -d content + # Prepare plugin archive content for creating artifact + - name: Prepare Plugin Artifact + id: artifact + shell: bash + run: | + cd ../../extensions/intellij/build/distributions + echo "Builds:" + ls + echo "---" + FILENAME=`ls *.zip` + unzip "$FILENAME" -d content - # echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT + echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT - # # Store already-built plugin as an artifact for downloading - # - name: Upload artifact - # uses: actions/upload-artifact@v4 - # with: - # name: ${{ steps.artifact.outputs.filename }} - # path: ./extensions/intellij/build/distributions/content/*/* + # Store already-built plugin as an artifact for downloading + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.artifact.outputs.filename }} + path: ./extensions/intellij/build/distributions/content/*/* # Upload binaries as artifacts - name: Upload artifact (darwin-arm64) From 27fe97f216bbf0daf787252fc88ca34028fca80c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 21:21:52 -0700 Subject: [PATCH 111/186] remove to test --- .github/workflows/jetbrains-release.yaml | 32 ++++++++++-------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 6ade07b71..efb5228d3 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -322,29 +322,23 @@ jobs: run: | cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }} chmod +x continue-binary - chmod +x node_sqlite3.node + chmod +x build/Release/node_sqlite3.node chmod +x index.node chmod +x esbuild if: ${{ matrix.platform }} != 'win32' - - name: Copy node_sqlite3.node to necessary location - run: | - cd ../../binary - mkdir build - cp ./bin/${{ matrix.platform }}-${{ matrix.arch }}/node_sqlite3.node ./build/node_sqlite3.node + # # Run tests for binary + # - name: Run binary tests + # run: | + # cd ../../binary + # npm run test - # Run tests for binary - - name: Run binary tests - run: | - cd ../../binary - npm run test - - - name: Upload logs - if: ${{ always() }} - uses: actions/upload-artifact@v2 - with: - name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} - path: binary/.continue/logs/core.log + # - name: Upload logs + # if: ${{ always() }} + # uses: actions/upload-artifact@v2 + # with: + # name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} + # path: binary/.continue/logs/core.log # Run tests and upload a code coverage report test: @@ -424,6 +418,7 @@ jobs: # Run plugin structure verification along with IntelliJ Plugin Verifier verify: + if: false name: Verify plugin needs: [build] runs-on: ubuntu-latest @@ -478,7 +473,6 @@ jobs: - test-binaries - test - inspectCode - - verify runs-on: ubuntu-latest steps: # # Update Unreleased section with the current release note From f39326bdc41481567faca9313a125457efc025ff Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 21:36:46 -0700 Subject: [PATCH 112/186] remove unecessary move of node_sqlite3.node in intellij --- .../activities/ContinuePluginStartupActivity.kt | 11 ----------- 1 file changed, 11 deletions(-) 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 444a4d397..e1a427040 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 @@ -206,17 +206,6 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val targetPath = Paths.get(corePath, target).toString() val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() - // Copy targetPath / node_sqlite3.node to core / node_sqlite3.node - val nodeSqlite3Path = Paths.get(targetPath, "node_sqlite3.node") - - // Create the build/Release path first - File(Paths.get(corePath, "build", "Release").toString()).mkdirs() - - val coreNodeSqlite3Path = Paths.get(corePath, "build", "Release", "node_sqlite3.node") - if (!File(coreNodeSqlite3Path.toString()).exists()) { - Files.copy(nodeSqlite3Path, coreNodeSqlite3Path) - } - // esbuild needs permissions val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString() From ea772dad2aa5fb1d8255cb07cf9e131379605448 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 21:37:38 -0700 Subject: [PATCH 113/186] don't upload release asset --- .github/workflows/jetbrains-release.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index efb5228d3..30489d7db 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -490,10 +490,10 @@ jobs: path: ./build/distributions/ # Upload artifact as a release asset - - name: Upload Release Asset - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* + # - name: Upload Release Asset + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* # Publish the plugin to JetBrains Marketplace - name: Publish Plugin From 4cf31b85fe9c12381f34c1dabb1c9d4f13787fd9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 22:08:45 -0700 Subject: [PATCH 114/186] remove dep --- .github/workflows/jetbrains-release.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 30489d7db..944dfac2f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -472,7 +472,6 @@ jobs: - build - test-binaries - test - - inspectCode runs-on: ubuntu-latest steps: # # Update Unreleased section with the current release note From cffc9a803d52180e90335a70610d867751a26524 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 22:20:26 -0700 Subject: [PATCH 115/186] test tests --- .github/workflows/preview.yaml | 57 ++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index aea470286..7d3e6f23f 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,11 +1,14 @@ name: Publish Preview Extension on: - create: - tags: - - "v0.9.*-vscode" + push: branches: - - dev + - nate/fix-ci-tests + # create: + # tags: + # - "v0.9.*-vscode" + # branches: + # - dev jobs: build: @@ -52,8 +55,8 @@ jobs: with: fetch-depth: 0 # This ensures all tags are fetched - - name: Checkout tag - run: git checkout ${GITHUB_REF#refs/tags/} + # - name: Checkout tag + # run: git checkout ${GITHUB_REF#refs/tags/} # 2. Install npm dependencies - name: Use Node.js from .nvmrc @@ -61,11 +64,11 @@ jobs: with: node-version-file: ".nvmrc" - - name: Cache extension node_modules - uses: actions/cache@v3 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + # - name: Cache extension node_modules + # uses: actions/cache@v3 + # with: + # path: extensions/vscode/node_modules + # key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - name: Cache core node_modules uses: actions/cache@v3 @@ -73,24 +76,24 @@ jobs: path: core/node_modules key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + # - name: Cache gui node_modules + # uses: actions/cache@v3 + # with: + # path: gui/node_modules + # key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + # - name: Install extension Dependencies + # run: | + # cd extensions/vscode + # npm ci + # env: + # # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + # GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - name: Install gui Dependencies - run: | - cd gui - npm ci + # - name: Install gui Dependencies + # run: | + # cd gui + # npm ci - name: Install Core Dependencies run: | From e1c28e5d65aa1cf2e0a452158b8f168404bbb0f0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 23:01:59 -0700 Subject: [PATCH 116/186] releasePlugin right after build --- .github/workflows/jetbrains-release.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 944dfac2f..14371345f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -198,6 +198,15 @@ jobs: - name: Build plugin run: ./gradlew buildPlugin + # Publish the plugin to JetBrains Marketplace + - name: Publish Plugin + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + run: ./gradlew publishPlugin + # Prepare plugin archive content for creating artifact - name: Prepare Plugin Artifact id: artifact @@ -251,6 +260,7 @@ jobs: path: ./binary/bin/linux-x64/ test-binaries: + if: false needs: build strategy: matrix: @@ -467,6 +477,7 @@ jobs: path: ${{ github.workspace }}/build/reports/pluginVerifier upload-release: + if: false name: Upload Release needs: - build From 69215a76271d63441f0f8646e09e5ff2ff149fd4 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Aug 2024 23:13:04 -0700 Subject: [PATCH 117/186] version update --- .github/workflows/jetbrains-release.yaml | 23 +++++++++++------------ extensions/intellij/gradle.properties | 2 +- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 14371345f..8f7c18b3f 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -260,7 +260,6 @@ jobs: path: ./binary/bin/linux-x64/ test-binaries: - if: false needs: build strategy: matrix: @@ -337,18 +336,18 @@ jobs: chmod +x esbuild if: ${{ matrix.platform }} != 'win32' - # # Run tests for binary - # - name: Run binary tests - # run: | - # cd ../../binary - # npm run test + # Run tests for binary + - name: Run binary tests + run: | + cd ../../binary + npm run test - # - name: Upload logs - # if: ${{ always() }} - # uses: actions/upload-artifact@v2 - # with: - # name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} - # path: binary/.continue/logs/core.log + - name: Upload logs + if: ${{ always() }} + uses: actions/upload-artifact@v2 + with: + name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} + path: binary/.continue/logs/core.log # Run tests and upload a code coverage report test: diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index c61a7c46e..f5e4edb49 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.60 +pluginVersion = 0.0.61 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From 9db4ad886a9d9febe79b930406bc2e4eb87cbe7a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 07:46:38 -0700 Subject: [PATCH 118/186] test --- .github/workflows/preview.yaml | 9 ++++++++- core/indexing/CodebaseIndexer.test.ts | 14 +++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 7d3e6f23f..6263c6bbd 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -99,11 +99,18 @@ jobs: run: | cd core npm ci + npm install @lancedb/vectordb-linux-x64-gnu + + - name: Install lance + run: | + cd core + npm install @lancedb/vectordb-linux-x64-gnu + if: matrix.os == 'ubuntu-latest' - name: Run core tests run: | cd core - npm run test + npm run test -- ./indexing/CodebaseIndexer.test.ts env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 221035737..cce5d61d8 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -3,12 +3,6 @@ import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { ContinueServerClient } from "../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; -import { getComputeDeleteAddRemove } from "./refreshIndex.js"; -import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; -import { CodebaseIndex } from "./types.js"; -import { walkDir } from "./walkDir.js"; -import { getIndexSqlitePath } from "../util/paths.js"; import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { addToTestDir, @@ -16,6 +10,12 @@ import { tearDownTestDir, TEST_DIR, } from "../test/util/testDir.js"; +import { getIndexSqlitePath } from "../util/paths.js"; +import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "./refreshIndex.js"; +import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; +import { CodebaseIndex } from "./types.js"; +import { walkDir } from "./walkDir.js"; jest.useFakeTimers(); @@ -57,7 +57,7 @@ class TestCodebaseIndexer extends CodebaseIndexer { // These are more like integration tests, whereas we should separately test // the individual CodebaseIndex classes -describe.skip("CodebaseIndexer", () => { +describe("CodebaseIndexer", () => { const pauseToken = new PauseToken(false); const continueServerClient = new ContinueServerClient(undefined, undefined); const codebaseIndexer = new TestCodebaseIndexer( From e852c965e22fb6f1ed06a7d55b9f174441f5ef44 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 07:49:47 -0700 Subject: [PATCH 119/186] fix git error --- core/indexing/CodebaseIndexer.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index cce5d61d8..f05acfc16 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -71,6 +71,9 @@ describe("CodebaseIndexer", () => { beforeAll(async () => { tearDownTestDir(); setUpTestDir(); + + execSync('git config --global user.email "test@example.com"'); + execSync('git config --global user.name "Test"'); }); afterAll(async () => { From f618f9d64639995054260cc90e722f5190c2681e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 07:52:43 -0700 Subject: [PATCH 120/186] try something else --- .github/workflows/preview.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 6263c6bbd..5f3fa5ec9 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -95,11 +95,12 @@ jobs: # cd gui # npm ci + # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - name: Install Core Dependencies run: | cd core npm ci - npm install @lancedb/vectordb-linux-x64-gnu + npm i vectordb - name: Install lance run: | From d4e7372cc8c788b18717e36e6ce21ad24647a65a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 09:44:24 -0700 Subject: [PATCH 121/186] rename intellij to jetbrains --- .github/workflows/README.md | 4 +-- CHANGELOG.md | 2 +- CONTRIBUTING.md | 2 +- docs/docs/changelog.mdx | 4 +-- docs/docs/troubleshooting.md | 2 +- extensions/vscode/scripts/prepackage.js | 11 ++++++--- extensions/vscode/scripts/utils.js | 33 +++++++++++-------------- 7 files changed, 29 insertions(+), 29 deletions(-) diff --git a/.github/workflows/README.md b/.github/workflows/README.md index f22d06955..ff1b7bd22 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -7,7 +7,7 @@ When merging to `preview`: - the VS Code extension along with Rust extension is built and uploaded as an artifact - all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases. - the version is bumped and this change is commited to preview -- in the future, the Intellij extension will be built and uploaded to the marketplace here +- in the future, the JetBrains extension will be built and uploaded to the marketplace here ## main @@ -16,4 +16,4 @@ When merging to `main`: - the VS Code extension along with Rust extension is built and uploaded as an artifact - all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases. - the version is bumped and this change is commited to main -- in the future, the Intellij extension will be built and uploaded to the marketplace here +- in the future, the JetBrains extension will be built and uploaded to the marketplace here diff --git a/CHANGELOG.md b/CHANGELOG.md index 010e9d1e3..268bbe613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,4 +3,4 @@ Separate changelogs are kept for each extension: - [VS Code Extension](./extensions/vscode/CHANGELOG.md) -- [Intellij Extension](./extensions/intellij/CHANGELOG.md) +- [JetBrains Extension](./extensions/intellij/CHANGELOG.md) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2192b2b8d..0a998802a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -152,7 +152,7 @@ Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](h ##### Debugging -Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. +Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The JetBrains extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. For the sake of rapid development, it is also possible to configure this communication to happen over local TCP sockets: diff --git a/docs/docs/changelog.mdx b/docs/docs/changelog.mdx index 990953abe..3b703ce52 100644 --- a/docs/docs/changelog.mdx +++ b/docs/docs/changelog.mdx @@ -1,6 +1,6 @@ --- title: 📝 Changelog -description: Changelogs for the latest releases of the VSCode and IntelliJ extensions +description: Changelogs for the latest releases of the VSCode and JetBrains extensions keywords: [changelog] hide_table_of_contents: true --- @@ -8,7 +8,7 @@ hide_table_of_contents: true import VSCodeChangelog from "../../extensions/vscode/CHANGELOG.md"; import IntelliJChangelog from "../../extensions/intellij/CHANGELOG.md"; -Below are the changelogs for the latest releases of the VSCode and IntelliJ extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. +Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. import TOCInline from "@theme/TOCInline"; diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 459271d47..44742c0de 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -4,7 +4,7 @@ description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- -The Continue VS Code extension is currently in beta, and the Intellij extension is in Alpha. If you are having trouble, please follow the steps below. +The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below. 1. [Check the logs](#check-the-logs) 2. [Try the latest pre-release](#download-the-latest-pre-release) diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index f7ca0e5d7..ad2ba5773 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -94,7 +94,7 @@ const exe = os === "win32" ? ".exe" : ""; execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -114,7 +114,7 @@ const exe = os === "win32" ? ".exe" : ""; ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -136,7 +136,7 @@ const exe = os === "win32" ? ".exe" : ""; path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); @@ -248,7 +248,10 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/llm/tiktokenWorkerPool.mjs", ]; for (const f of filesToCopy) { - fs.copyFileSync(path.join(__dirname, f), path.join(__dirname, "..", "out", path.basename(f))); + fs.copyFileSync( + path.join(__dirname, f), + path.join(__dirname, "..", "out", path.basename(f)), + ); console.log(`[info] Copied ${path.basename(f)}`); } diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 6a129bc61..93c1928ce 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -78,7 +78,7 @@ async function buildGui(isGhAction) { execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -98,7 +98,7 @@ async function buildGui(isGhAction) { ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -120,7 +120,7 @@ async function buildGui(isGhAction) { path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); @@ -256,7 +256,7 @@ async function copyNodeModules() { "@esbuild", "@lancedb", "@vscode/ripgrep", - "workerpool" + "workerpool", ]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -328,15 +328,13 @@ async function downloadEsbuildBinary(target) { "win32-x64": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", }[target]; - execCmdSync( - `curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`, - ); + execCmdSync(`curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`); execCmdSync("cd out/tmp && tar -xvzf esbuild.tgz"); // Copy the installed package back to the current directory let tmpPath = "out/tmp/package/bin"; let outPath = `out/node_modules/@esbuild/${target}/bin`; if (target.startsWith("win")) { - tmpPath = 'out/tmp/package'; + tmpPath = "out/tmp/package"; outPath = `out/node_modules/@esbuild/${target}`; } @@ -347,10 +345,7 @@ async function downloadEsbuildBinary(target) { { dereference: true }, (error) => { if (error) { - console.error( - `[error] Error copying esbuild package`, - error, - ); + console.error(`[error] Error copying esbuild package`, error); reject(error); } else { resolve(); @@ -358,7 +353,7 @@ async function downloadEsbuildBinary(target) { }, ); }); - rimrafSync("out/tmp") + rimrafSync("out/tmp"); } async function downloadSqliteBinary(target) { @@ -408,7 +403,8 @@ async function copySqliteBinary() { async function downloadRipgrepBinary(target) { console.log("[info] Downloading pre-built ripgrep binary"); rimrafSync("node_modules/@vscode/ripgrep/bin"); - fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true });4 + fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true }); + 4; const downloadUrl = { "darwin-arm64": "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-apple-darwin.tar.gz", @@ -424,8 +420,7 @@ async function downloadRipgrepBinary(target) { "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-pc-windows-msvc.zip", }[target]; - - if(target.startsWith("win")) { + if (target.startsWith("win")) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.zip ${downloadUrl}`, ); @@ -435,7 +430,9 @@ async function downloadRipgrepBinary(target) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.tar.gz ${downloadUrl}`, ); - execCmdSync("cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz"); + execCmdSync( + "cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz", + ); fs.unlinkSync("node_modules/@vscode/ripgrep/bin/build.tar.gz"); } } @@ -512,5 +509,5 @@ module.exports = { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, downloadRipgrepBinary, - copyTokenizers + copyTokenizers, }; From e703e8094208a7bc8503f3131a974530cc7aa7c0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 09:44:41 -0700 Subject: [PATCH 122/186] include vscode/jetbrains in telemetry --- core/config/profile/doLoadConfig.ts | 2 +- core/util/posthog.ts | 15 +++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 16f72d40e..b4556f826 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -48,7 +48,7 @@ export default async function doLoadConfig( await Telemetry.setup( newConfig.allowAnonymousTelemetry ?? true, await ide.getUniqueId(), - ideInfo.extensionVersion, + ideInfo, ); if (newConfig.analytics) { diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 3a79814d0..be62977fc 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -1,12 +1,13 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; +import { IdeInfo } from "../index.js"; export class Telemetry { // Set to undefined whenever telemetry is disabled static client: any = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; - static extensionVersion: string | undefined = undefined; + static ideInfo: IdeInfo | undefined = undefined; static async capture( event: string, @@ -19,7 +20,9 @@ export class Telemetry { properties: { ...properties, os: Telemetry.os, - extensionVersion: Telemetry.extensionVersion, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, }, }); @@ -32,14 +35,10 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async setup( - allow: boolean, - uniqueId: string, - extensionVersion: string, - ) { + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); - Telemetry.extensionVersion = extensionVersion; + Telemetry.ideInfo = ideInfo; if (!allow) { Telemetry.client = undefined; From 5db3a581c3565730df5ce561ed1b5cbc6b278949 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 12:12:08 -0700 Subject: [PATCH 123/186] reduce posthog costs, report core exits --- extensions/intellij/build.gradle.kts | 1 + .../ContinuePluginStartupActivity.kt | 11 ++++++++ .../continue/CoreMessenger.kt | 15 ++++++---- .../services/TelemetryService.kt | 28 +++++++++++++++++++ gui/src/hooks/CustomPostHogProvider.tsx | 2 ++ 5 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 766cf3ebd..8146cb32c 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -37,6 +37,7 @@ dependencies { implementation("io.ktor:ktor-server-cors:2.3.7"){ exclude(group = "org.slf4j", module = "slf4j-api") } + implementation("com.posthog.java:posthog:1.+") } 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 e1a427040..caf9b4720 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 @@ -9,6 +9,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.SettingsListener +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager @@ -211,6 +212,16 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient) continuePluginService.coreMessenger = coreMessenger + + coreMessenger.request("config/getSerializedProfileInfo", null, null) { resp -> + val data = resp as? Map + val profileInfo = data?.get("config") as? Map + val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean + val telemetryService = service() + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { + telemetryService.setup(getMachineUniqueID()) + } + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index ded887c76..4d4e9f9ba 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,15 +1,12 @@ package com.github.continuedev.continueintellijextension.`continue` + import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import java.io.BufferedReader -import java.io.InputStreamReader -import java.io.OutputStreamWriter - -import java.io.* - +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +import java.io.* import java.net.Socket import java.nio.charset.StandardCharsets import java.nio.file.Files @@ -241,6 +238,12 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC val err = process?.errorStream?.bufferedReader()?.readText()?.trim() println("Core process exited with output: $err") ideProtocolClient.showMessage("Core process exited with output: $err") + + // Log the cause of the failure + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf( + "error" to err + )) } Thread { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt new file mode 100644 index 000000000..5b7f00678 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt @@ -0,0 +1,28 @@ +package com.github.continuedev.continueintellijextension.services + +import com.intellij.openapi.components.Service +import com.posthog.java.PostHog +import com.posthog.java.PostHog.Builder + +@Service +class TelemetryService { + private val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" + private var posthog: PostHog? = null; + private var distinctId: String? = null; + + fun setup(distinctId: String) { + this.posthog = Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() + this.distinctId = distinctId + } + + fun capture(eventName: String, properties: Map) { + if (this.posthog == null || this.distinctId == null) { + return; + } + this.posthog?.capture(this.distinctId, eventName, properties) + } + + fun shutdown() { + this.posthog?.shutdown() + } +} \ No newline at end of file diff --git a/gui/src/hooks/CustomPostHogProvider.tsx b/gui/src/hooks/CustomPostHogProvider.tsx index 1d93889df..592288bb8 100644 --- a/gui/src/hooks/CustomPostHogProvider.tsx +++ b/gui/src/hooks/CustomPostHogProvider.tsx @@ -16,7 +16,9 @@ const CustomPostHogProvider = ({ children }: PropsWithChildren) => { posthog.init("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { api_host: "https://app.posthog.com", disable_session_recording: true, + autocapture: false, // // We need to manually track pageviews since we're a SPA + capture_pageleave: false, capture_pageview: false, }); posthog.identify(window.vscMachineId); From a841e55b44dc7278d4762405fc691866c2584651 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 13:10:45 -0700 Subject: [PATCH 124/186] remove unnecessary telemetry --- core/indexing/LanceDbIndex.ts | 3 +-- core/indexing/docs/DocsService.ts | 13 +++++++------ core/llm/llms/FreeTrial.ts | 26 +++++++++++++------------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 69e138ddc..7c4787529 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,7 +1,7 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; -import { Table } from "vectordb"; +import lance, { Table } from "vectordb"; import { IContinueServerClient } from "../continueServer/interface.js"; import { BranchAndDir, @@ -21,7 +21,6 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; -import lance from "vectordb"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1e8a8245c..dbf1910dc 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -722,12 +722,13 @@ export default class DocsService { await this.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - this.ide.errorPopup( - "The 'transformers.js' embeddings provider currently cannot be used to index " + - "documentation in JetBrains. To enable documentation indexing, you can use " + - "any of the other providers described in the docs: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - ); + // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider + // this.ide.errorPopup( + // "The 'transformers.js' embeddings provider currently cannot be used to index " + + // "documentation in JetBrains. To enable documentation indexing, you can use " + + // "any of the other providers described in the docs: " + + // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + // ); this.globalContext.update( "curEmbeddingsProviderId", diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9fc59313b..10632b90f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -2,7 +2,6 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { constants } from "../../deploy/constants.js"; import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { Telemetry } from "../../util/posthog.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -29,18 +28,19 @@ class FreeTrial extends BaseLLM { } private async _countTokens(prompt: string, model: string, isPrompt: boolean) { - if (!Telemetry.client) { - throw new Error( - "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", - ); - } - const event = isPrompt - ? "free_trial_prompt_tokens" - : "free_trial_completion_tokens"; - Telemetry.capture(event, { - tokens: this.countTokens(prompt), - model, - }); + // Removed to reduce PostHog bill + // if (!Telemetry.client) { + // throw new Error( + // "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", + // ); + // } + // const event = isPrompt + // ? "free_trial_prompt_tokens" + // : "free_trial_completion_tokens"; + // Telemetry.capture(event, { + // tokens: this.countTokens(prompt), + // model, + // }); } private _convertArgs(options: CompletionOptions): any { From 77b4b67282f1dcfdeaf2d74d60b074509467f030 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 13:31:18 -0700 Subject: [PATCH 125/186] improved indexing error handling --- binary/build.js | 14 +++++++- core/indexing/CodeSnippetsIndex.ts | 1 - core/indexing/CodebaseIndexer.ts | 53 ++++++++++++++++++------------ core/indexing/refreshIndex.ts | 4 +-- 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/binary/build.js b/binary/build.js index cf8a2420b..016afe9bd 100644 --- a/binary/build.js +++ b/binary/build.js @@ -240,7 +240,19 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found - fs.writeFileSync(`${targetDir}/package.json`, ""); + fs.writeFileSync( + `${targetDir}/package.json`, + JSON.stringify( + { + name: "binary", + version: "1.0.0", + author: "Continue Dev, Inc", + license: "Apache-2.0", + }, + undefined, + 2, + ), + ); // Copy to build directory for testing try { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 4dd56e4c2..0b97696bf 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -17,7 +17,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { IndexResultType, MarkCompleteCallback, - PathAndCacheKey, RefreshIndexResults, type CodebaseIndex, } from "./types.js"; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index da06bb0d9..b377d5a2f 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,7 +1,7 @@ import * as fs from "fs/promises"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; -import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; @@ -126,6 +126,12 @@ export class CodebaseIndexer { results.removeTag = []; results.addTag = []; results.del = []; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (results.compute.length === 0) { + continue; + } + for await (const _ of index.update( tag, results, @@ -371,28 +377,33 @@ export class CodebaseIndexer { results.addTag.length + results.removeTag.length; let completedOps = 0; - for (const subResult of this.batchRefreshIndexResults(results)) { - for await (const { desc } of codebaseIndex.update( - tag, - subResult, - markComplete, - repoName, - )) { - yield { - progress: progress, - desc, - status: "indexing", - }; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (totalOps > 0) { + for (const subResult of this.batchRefreshIndexResults(results)) { + for await (const { desc } of codebaseIndex.update( + tag, + subResult, + markComplete, + repoName, + )) { + yield { + progress: progress, + desc, + status: "indexing", + }; + } + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); } - completedOps += - subResult.compute.length + - subResult.del.length + - subResult.addTag.length + - subResult.removeTag.length; - progress = - (completedIndexCount + completedOps / totalOps) * - (1 / indexesToBuild.length); } + await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); completedIndexCount += 1; } diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index c60a1a4d3..3404a22d5 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,8 +1,8 @@ import crypto from "node:crypto"; import * as fs from "node:fs"; +import plimit from "p-limit"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; -import plimit from "p-limit"; import { IndexTag, IndexingProgressUpdate } from "../index.js"; import { getIndexSqlitePath } from "../util/paths.js"; import { @@ -391,7 +391,7 @@ export async function getComputeDeleteAddRemove( lastUpdated, async (items, resultType) => { // Update tag catalog - markComplete(items, resultType); + await markComplete(items, resultType); // Update the global cache const results: any = { From 647656cd3d007c016bea372bdfcb5d69f9d1d52a Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:11:39 -0700 Subject: [PATCH 126/186] fix: scaffolding for future language syntax highlighting --- .vscode/launch.json | 5 +- core/commands/slash/comment.ts | 4 +- core/commands/slash/edit.ts | 19 +-- .../components/markdown/CodeBlockToolbar.tsx | 6 +- .../components/markdown/PreWithToolbar.tsx | 5 +- gui/src/components/markdown/StyledCode.tsx | 19 --- .../markdown/StyledMarkdownPreview.tsx | 116 ++++++------------ gui/src/hooks/useChatHandler.ts | 1 - gui/src/pages/gui.tsx | 32 ----- 9 files changed, 48 insertions(+), 159 deletions(-) delete mode 100644 gui/src/components/markdown/StyledCode.tsx diff --git a/.vscode/launch.json b/.vscode/launch.json index 54d282cc8..896793040 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -17,10 +17,7 @@ "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, - "outFiles": [ - "${workspaceFolder}/extensions/vscode/out/extension.js", - "/Users/natesesti/.continue/config.ts" - ], + "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { // "CONTROL_PLANE_ENV": "local" diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts index 929763bf3..e3b601c04 100644 --- a/core/commands/slash/comment.ts +++ b/core/commands/slash/comment.ts @@ -1,5 +1,5 @@ -import { SlashCommand } from "../../index.js"; -import EditSlashCommand from "./edit.js"; +import { SlashCommand } from "../../"; +import EditSlashCommand from "./edit"; const CommentSlashCommand: SlashCommand = { name: "comment", diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index a0fbfdd26..a3c3ed91c 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -5,18 +5,18 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/lineStream.js"; -import { streamLines } from "../../diff/util.js"; -import { ContextItemWithId, ILLM, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +} from "../../autocomplete/lineStream"; +import { streamLines } from "../../diff/util"; +import { ContextItemWithId, ILLM, SlashCommand } from "../../"; +import { stripImages } from "../../llm/images"; import { dedentAndGetCommonWhitespace, getMarkdownLanguageTagForFile, -} from "../../util/index.js"; +} from "../../util/"; import { contextItemToRangeInFileWithContents, type RangeInFileWithContents, -} from "../util.js"; +} from "../util"; const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. @@ -62,13 +62,6 @@ export async function getPromptParts( ) { const maxTokens = Math.floor(model.contextLength / 2); - const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit ?? 1200; - // if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) { - // throw new Error( - // "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**" - // ); - // } - const BUFFER_FOR_FUNCTIONS = 400; let totalTokens = model.countTokens(fullFileContents + PROMPT + input) + diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index 84e521192..c7f695f00 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -72,8 +72,6 @@ function isTerminalCodeBlock(language: string | undefined, text: string) { function CodeBlockToolBar(props: CodeBlockToolBarProps) { const ideMessenger = useContext(IdeMessengerContext); - - const [copied, setCopied] = useState(false); const [applying, setApplying] = useState(false); return ( @@ -85,8 +83,8 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { isTerminalCodeBlock(props.language, props.text) ? "Run in terminal" : applying - ? "Applying..." - : "Apply to current file" + ? "Applying..." + : "Apply to current file" } disabled={applying} style={{ backgroundColor: vscEditorBackground }} diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index a5df415f1..3731109f5 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -19,10 +19,7 @@ function childrenToText(children: any) { return children.map((child: any) => childToText(child)).join(""); } -function PreWithToolbar(props: { - children: any; - language: string | undefined; -}) { +function PreWithToolbar(props: { children: any; language: string | null }) { const uiConfig = useUIConfig(); const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom"; diff --git a/gui/src/components/markdown/StyledCode.tsx b/gui/src/components/markdown/StyledCode.tsx deleted file mode 100644 index c5ed01014..000000000 --- a/gui/src/components/markdown/StyledCode.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; -import { vscDarkPlus as highlightStyle } from "react-syntax-highlighter/dist/esm/styles/prism"; - -interface StyledCodeProps { - children: string; - language?: string; -} - -const StyledCode = (props: StyledCodeProps) => ( - - {props.children} - -); - -export default StyledCode; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 7ae3c9a61..afdc88ec5 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,7 +1,6 @@ -import React, { memo, useEffect, useState } from "react"; -import { useSelector } from "react-redux"; +import { memo, useEffect } from "react"; import { useRemark } from "react-remark"; -import rehypeHighlight from "rehype-highlight"; +import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; import remarkMath from "remark-math"; import styled from "styled-components"; @@ -12,11 +11,11 @@ import { vscEditorBackground, vscForeground, } from ".."; -import { RootState } from "../../redux/store"; import { getFontSize } from "../../util"; import LinkableCode from "./LinkableCode"; import PreWithToolbar from "./PreWithToolbar"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; +import { common } from "lowlight"; import "./katex.css"; import "./markdown.css"; @@ -59,19 +58,9 @@ const StyledMarkdown = styled.div<{ } background-color: ${vscBackground}; - font-family: - var(--vscode-font-family), - system-ui, - -apple-system, - BlinkMacSystemFont, - "Segoe UI", - Roboto, - Oxygen, - Ubuntu, - Cantarell, - "Open Sans", - "Helvetica Neue", - sans-serif; + font-family: var(--vscode-font-family), system-ui, -apple-system, + BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, + "Open Sans", "Helvetica Neue", sans-serif; font-size: ${(props) => props.fontSize || getFontSize()}px; padding-left: 8px; padding-right: 8px; @@ -92,41 +81,19 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; } -const FadeInWords: React.FC = (props: any) => { - const { children, ...otherProps } = props; +const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; - const active = useSelector((store: RootState) => store.state.active); +const getLanuageFromClassName = (className: any): string | null => { + if (!className || typeof className !== "string") { + return null; + } - const [textWhenActiveStarted, setTextWhenActiveStarted] = useState( - props.children, - ); + const language = className + .split(" ") + .find((word) => word.startsWith(HLJS_LANGUAGE_CLASSNAME_PREFIX)) + ?.split("-")[1]; - useEffect(() => { - if (active) { - setTextWhenActiveStarted(children); - } - }, [active]); - - // Split the text into words - const words = children - .map((child) => { - if (typeof child === "string") { - return child.split(" ").map((word, index) => ( - - {word}{" "} - - )); - } else { - return {child}; - } - }) - .flat(); - - return active && children !== textWhenActiveStarted ? ( -

{words}

- ) : ( -

{children}

- ); + return language; }; const StyledMarkdownPreview = memo(function StyledMarkdownPreview( @@ -147,7 +114,21 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }; }, ], - rehypePlugins: [rehypeHighlight as any, {}, rehypeKatex as any, {}], + rehypePlugins: [ + rehypeKatex as any, + {}, + [ + rehypeHighlight as any, + { + // Note: This is the default behavior, but leaving this here for scaffolding to + // add unsupported languages in the future. + // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md + languages: { ...common }, + } as Options, + + , + ], + ], rehypeReactOptions: { components: { a: ({ node, ...props }) => { @@ -158,12 +139,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); }, pre: ({ node, ...preProps }) => { - const language = preProps?.children?.[0]?.props?.className - ?.split(" ") - .find((word) => word.startsWith("language-")) - ?.split("-")[1]; + const childrenClassName = preProps?.children?.[0]?.props?.className; + return props.showCodeBorder ? ( - + ) : ( @@ -181,31 +162,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( {codeProps.children} ); }, - // pre: ({ node, ...preProps }) => { - // const codeString = - // preProps.children?.[0]?.props?.children?.[0].trim() || ""; - // const monacoEditor = ( - // - // ); - // return props.showCodeBorder ? ( - // - // - // - // ) : ( - // - // ); - // }, - // p: ({ node, ...props }) => { - // return ; - // }, }, }, }); diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index a61f13196..fa7e01945 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -1,5 +1,4 @@ import { Dispatch } from "@reduxjs/toolkit"; - import { JSONContent } from "@tiptap/react"; import { ChatHistory, diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index caaff7ea6..2de4e5f6b 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -134,38 +134,6 @@ const NewSessionButton = styled.div` cursor: pointer; `; -const ThreadHead = styled.div` - display: flex; - align-items: center; - gap: 6px; - margin: 18px 6px 0 6px; -`; - -const THREAD_AVATAR_SIZE = 15; - -const ThreadAvatar = styled.div` - width: 24px; - height: 24px; - border-radius: 50%; - background-color: rgba(248, 248, 248, 0.75); - color: #000; - display: flex; - align-items: center; - justify-content: center; - border: 1px solid rgba(136, 136, 136, 0.3); -`; - -const ThreadUserTitle = styled.div` - text-transform: capitalize; - font-weight: 500; - margin-bottom: 2px; -`; - -const ThreadUserName = styled.div` - font-size: ${getFontSize() - 3}px; - color: ${lightGray}; -`; - function fallbackRender({ error, resetErrorBoundary }: any) { // Call resetErrorBoundary() to reset the error boundary and retry the render. From 850f662b9ec597e8067ac5cd30fc154c4e1511d3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:17:56 -0700 Subject: [PATCH 127/186] Update StyledMarkdownPreview.tsx --- gui/src/components/markdown/StyledMarkdownPreview.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index afdc88ec5..fde4cd043 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -120,10 +120,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( [ rehypeHighlight as any, { - // Note: This is the default behavior, but leaving this here for scaffolding to - // add unsupported languages in the future. + // Note: An empty obj is the default behavior, but leaving this here for scaffolding to + // add unsupported languages in the future. We will need to install the `lowlight` package + // to use the `common` language set in addition to unsupported languages. // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md - languages: { ...common }, + // languages: {}, } as Options, , From 0cf02066ec444f99dc266814856e9d26f4a2ee1b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:18:52 -0700 Subject: [PATCH 128/186] Update StyledMarkdownPreview.tsx --- .../markdown/StyledMarkdownPreview.tsx | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index fde4cd043..3959b70e3 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -117,18 +117,14 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( rehypePlugins: [ rehypeKatex as any, {}, - [ - rehypeHighlight as any, - { - // Note: An empty obj is the default behavior, but leaving this here for scaffolding to - // add unsupported languages in the future. We will need to install the `lowlight` package - // to use the `common` language set in addition to unsupported languages. - // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md - // languages: {}, - } as Options, - - , - ], + rehypeHighlight as any, + { + // Note: An empty obj is the default behavior, but leaving this here for scaffolding to + // add unsupported languages in the future. We will need to install the `lowlight` package + // to use the `common` language set in addition to unsupported languages. + // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md + // languages: {}, + } as Options, ], rehypeReactOptions: { components: { From ff8fab7a407b600849afbe4c7cc6247bfd7523f3 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:31:28 -0700 Subject: [PATCH 129/186] docs: update `openai` provider names --- docs/docs/reference/Model Providers/azure.md | 15 ++++++++------- docs/docs/reference/Model Providers/openrouter.md | 4 ++-- .../reference/Model Providers/textgenwebui.md | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/docs/reference/Model Providers/azure.md b/docs/docs/reference/Model Providers/azure.md index 7142b7718..0b61884c2 100644 --- a/docs/docs/reference/Model Providers/azure.md +++ b/docs/docs/reference/Model Providers/azure.md @@ -15,7 +15,7 @@ You can configure Azure OpenAI service through the UI, or you can configure it m ```json title="~/.continue/config.json" "models": [{ "title": "Azure OpenAI", - "provider": "openai", + "provider": "azure", "model": "", "apiBase": "", "engine": "", @@ -25,10 +25,11 @@ You can configure Azure OpenAI service through the UI, or you can configure it m }] ``` -To find out the information from *Azure AI Studio*, select the model that you would like to connect. Under the *Endpoint* section and capture the Target URI. -For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview +To find out the information from _Azure AI Studio_, select the model that you would like to connect. Under the _Endpoint_ section and capture the Target URI. +For example, Target URI of Maps to: -* model = gpt-4o -* engine = gpt-4o -* apiVersion = 2023-13-15-preview -* apiBase = just-an-example.openai.azure.com + +- model = gpt-4o +- engine = gpt-4o +- apiVersion = 2023-13-15-preview +- apiBase = just-an-example.openai.azure.com diff --git a/docs/docs/reference/Model Providers/openrouter.md b/docs/docs/reference/Model Providers/openrouter.md index 5f2558399..eabc291bb 100644 --- a/docs/docs/reference/Model Providers/openrouter.md +++ b/docs/docs/reference/Model Providers/openrouter.md @@ -2,14 +2,14 @@ OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). -Change `~/.continue/config.json` to look like the following. Since OpenRouter is fully API compatible with OpenAI, it is recommended to stick with `"provider": "openai"`, even if they aren't necessarily the upstream provider. +Change `~/.continue/config.json` to look like the following. ```json title="~/.continue/config.json" { "models": [ { "title": "OpenRouter LLaMA 70 8B", - "provider": "openai", + "provider": "openrouter", "model": "meta-llama/llama-3-70b-instruct", "apiBase": "https://openrouter.ai/api/v1", "apiKey": "..." diff --git a/docs/docs/reference/Model Providers/textgenwebui.md b/docs/docs/reference/Model Providers/textgenwebui.md index f52e44219..1aee87049 100644 --- a/docs/docs/reference/Model Providers/textgenwebui.md +++ b/docs/docs/reference/Model Providers/textgenwebui.md @@ -7,7 +7,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. "models": [ { "title": "Text Generation WebUI", - "provider": "openai", + "provider": "text-gen-webui", "apiBase": "http://localhost:5000", "model": "MODEL_NAME" } From fcc20efe0667912761a4b7076ce735ffa7a2e203 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:32:54 -0700 Subject: [PATCH 130/186] docs: update provider name docs --- docs/docs/reference/Model Providers/azure.md | 15 ++++++++------- docs/docs/reference/Model Providers/openrouter.md | 4 ++-- .../reference/Model Providers/textgenwebui.md | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/docs/reference/Model Providers/azure.md b/docs/docs/reference/Model Providers/azure.md index 7142b7718..0b61884c2 100644 --- a/docs/docs/reference/Model Providers/azure.md +++ b/docs/docs/reference/Model Providers/azure.md @@ -15,7 +15,7 @@ You can configure Azure OpenAI service through the UI, or you can configure it m ```json title="~/.continue/config.json" "models": [{ "title": "Azure OpenAI", - "provider": "openai", + "provider": "azure", "model": "", "apiBase": "", "engine": "", @@ -25,10 +25,11 @@ You can configure Azure OpenAI service through the UI, or you can configure it m }] ``` -To find out the information from *Azure AI Studio*, select the model that you would like to connect. Under the *Endpoint* section and capture the Target URI. -For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview +To find out the information from _Azure AI Studio_, select the model that you would like to connect. Under the _Endpoint_ section and capture the Target URI. +For example, Target URI of Maps to: -* model = gpt-4o -* engine = gpt-4o -* apiVersion = 2023-13-15-preview -* apiBase = just-an-example.openai.azure.com + +- model = gpt-4o +- engine = gpt-4o +- apiVersion = 2023-13-15-preview +- apiBase = just-an-example.openai.azure.com diff --git a/docs/docs/reference/Model Providers/openrouter.md b/docs/docs/reference/Model Providers/openrouter.md index 5f2558399..eabc291bb 100644 --- a/docs/docs/reference/Model Providers/openrouter.md +++ b/docs/docs/reference/Model Providers/openrouter.md @@ -2,14 +2,14 @@ OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). -Change `~/.continue/config.json` to look like the following. Since OpenRouter is fully API compatible with OpenAI, it is recommended to stick with `"provider": "openai"`, even if they aren't necessarily the upstream provider. +Change `~/.continue/config.json` to look like the following. ```json title="~/.continue/config.json" { "models": [ { "title": "OpenRouter LLaMA 70 8B", - "provider": "openai", + "provider": "openrouter", "model": "meta-llama/llama-3-70b-instruct", "apiBase": "https://openrouter.ai/api/v1", "apiKey": "..." diff --git a/docs/docs/reference/Model Providers/textgenwebui.md b/docs/docs/reference/Model Providers/textgenwebui.md index f52e44219..1aee87049 100644 --- a/docs/docs/reference/Model Providers/textgenwebui.md +++ b/docs/docs/reference/Model Providers/textgenwebui.md @@ -7,7 +7,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. "models": [ { "title": "Text Generation WebUI", - "provider": "openai", + "provider": "text-gen-webui", "apiBase": "http://localhost:5000", "model": "MODEL_NAME" } From c5c78279c32bf5a67651b7d2aefffb8afa34f611 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 14:34:22 -0700 Subject: [PATCH 131/186] Update StyledMarkdownPreview.tsx --- gui/src/components/markdown/StyledMarkdownPreview.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 3959b70e3..311d8c84a 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -118,11 +118,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( rehypeKatex as any, {}, rehypeHighlight as any, + // Note: An empty obj is the default behavior, but leaving this here for scaffolding to + // add unsupported languages in the future. We will need to install the `lowlight` package + // to use the `common` language set in addition to unsupported languages. + // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md { - // Note: An empty obj is the default behavior, but leaving this here for scaffolding to - // add unsupported languages in the future. We will need to install the `lowlight` package - // to use the `common` language set in addition to unsupported languages. - // https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md // languages: {}, } as Options, ], From f19c89148e0d7ea79c74bfcb5a98f8bcd0450d8f Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 15:09:19 -0700 Subject: [PATCH 132/186] cleaning --- .github/workflows/jetbrains-release.yaml | 21 --------------------- .vscode/settings.json | 1 + 2 files changed, 1 insertion(+), 21 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 8f7c18b3f..3897662be 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -160,14 +160,6 @@ jobs: # codesign --sign - ../../binary/bin/darwin-x64/continue-binary # codesign --sign - ../../binary/bin/darwin-arm64/continue-binary - # - name: Validate codesigning - # run: | - # echo "Validating codesigning for darwin-x64 binary" - # codesign -dv --verbose=4 ../../binary/bin/darwin-x64/continue-binary - - # echo "Validating codesigning for darwin-arm64 binary" - # codesign -dv --verbose=4 ../../binary/bin/darwin-arm64/continue-binary - # - name: Sign darwin-arm64 binary # uses: lando/code-sign-action@v2 # with: @@ -181,19 +173,6 @@ jobs: # apple-product-id: dev.continue.continue-binary # options: --options runtime --entitlements entitlements.xml - # - name: Sign darwin-x64 binary - # uses: lando/code-sign-action@v2 - # with: - # file: ./binary/bin/darwin-x64/continue-binary - # certificate-data: ${{ secrets.APPLE_CERT_DATA }} - # certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }} - # apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }} - # apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }} - # apple-notary-tool: altool - # apple-team-id: 43XFLY66ZD - # apple-product-id: dev.continue.continue-binary - # options: --options runtime --entitlements entitlements.xml - # Build plugin - name: Build plugin run: ./gradlew buildPlugin diff --git a/.vscode/settings.json b/.vscode/settings.json index 060bc5e6c..f56d10f61 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,6 +15,7 @@ }, "search.exclude": { "**/binary": true, + "binary/": false, "**/core/vendor/**": true, "**/gui/dist": true } From 67cbfb12ee4d2cdebe5058788efbb69f37d5d070 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 15:09:30 -0700 Subject: [PATCH 133/186] add debug logs to core.log --- binary/src/logging.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/binary/src/logging.ts b/binary/src/logging.ts index cba34855c..b6dbfba2c 100644 --- a/binary/src/logging.ts +++ b/binary/src/logging.ts @@ -11,5 +11,6 @@ export function setupCoreLogging() { console.log = logger; console.error = logger; console.warn = logger; + console.debug = logger; console.log("[info] Starting Continue core..."); } From 998303b2e61f962e70d79e6b8cf9a8e3ad571fd6 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 15:30:35 -0700 Subject: [PATCH 134/186] fix binary tests --- binary/src/IpcMessenger.ts | 2 +- core/config/promptFile.ts | 2 +- core/util/reverseMessageIde.ts | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index 66acb1448..341372d8e 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -38,7 +38,7 @@ class IPCMessengerBase< } this.send(msg.messageType, { done: true }, msg.messageId); } else { - this.send(msg.messageType, response || {}, msg.messageId); + this.send(msg.messageType, response, msg.messageId); } } catch (e: any) { console.warn(`Error running handler for "${msg.messageType}": `, e); diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 92d558aaf..f1bfc898d 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,8 +4,8 @@ import * as YAML from "yaml"; import type { IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; -import { getBasename } from "../util/index"; import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import { getBasename } from "../util/index"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts index 1e5a2d1ca..a65f1f1f2 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/util/reverseMessageIde.ts @@ -124,6 +124,11 @@ export class ReverseMessageIde { return this.ide.listFolders(); }); + this.on("getControlPlaneSessionInfo", async (msg) => { + // Not supported in testing + return undefined; + }); + this.on("getContinueDir", () => { return this.ide.getContinueDir(); }); From ca3e0d58952e86f38c2ed3044d84deee41b90b03 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 19 Aug 2024 15:30:43 -0700 Subject: [PATCH 135/186] chore: updated dialog for index rebuilds --- gui/src/components/loaders/IndexingProgressBar.tsx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index cfbb63bb3..7446f8df9 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -121,7 +121,9 @@ const IndexingProgressBar = ({ function onClick() { switch (indexingState.status) { case "failed": - if (indexingState.shouldClearIndexes) { + // For now, we don't show in JetBrains since the reindex command + // is not yet implemented + if (indexingState.shouldClearIndexes && !isJetBrains()) { dispatch(setShowDialog(true)); dispatch( setDialogMessage( @@ -131,9 +133,8 @@ const IndexingProgressBar = ({ text={ "Your index appears corrupted. We recommend clearing and rebuilding it, " + "which may take time for large codebases.\n\n" + - "Alternatively, you can close this and use the 'Continue: Force Codebase Re-Indexing' " + - "command to attempt a faster rebuild without clearing data, though it may be " + - "less reliable for persistent issues." + "For a faster rebuild without clearing data, press 'Shift + Command + P' to open " + + "the Command Palette, and type out 'Continue: Force Codebase Re-Indexing'" } onConfirm={() => { posthog.capture("rebuild_index_clicked"); From 37f444d87675cc3b349f3809b5a2e1491888672f Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 15:35:59 -0700 Subject: [PATCH 136/186] release from tags --- .github/workflows/jetbrains-release.yaml | 41 +++++++++++------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 3897662be..56cd88b16 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -5,11 +5,8 @@ name: Release on: - push: - branches: - - nate/apple-developer-finally - # release: - # types: [prereleased] + release: + types: [prereleased] defaults: run: @@ -20,24 +17,24 @@ concurrency: cancel-in-progress: true jobs: - # check_release_name: - # runs-on: ubuntu-latest - # outputs: - # should_run: ${{ steps.check.outputs.should_run }} - # steps: - # - id: check - # working-directory: . - # run: | - # if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then - # echo "should_run=true" >> $GITHUB_OUTPUT - # else - # echo "should_run=false" >> $GITHUB_OUTPUT - # fi + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + working-directory: . + run: | + if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi # Prepare and publish the plugin to JetBrains Marketplace repository build: - # needs: check_release_name - # if: needs.check_release_name.outputs.should_run == 'true' + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' name: Build Plugin runs-on: macos-latest permissions: @@ -47,8 +44,8 @@ jobs: # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 - # with: - # ref: ${{ github.event.release.tag_name }} + with: + ref: ${{ github.event.release.tag_name }} - name: Import Apple certificate uses: apple-actions/import-codesign-certs@v3 From f3a74705b86aa550af15eaac7f07cdab55e2fb23 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 15:57:15 -0700 Subject: [PATCH 137/186] publish to both eap and stable --- .github/workflows/jetbrains-release.yaml | 12 +++++++++++- extensions/intellij/build.gradle.kts | 2 +- extensions/intellij/gradle.properties | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 56cd88b16..714796bad 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -175,12 +175,22 @@ jobs: run: ./gradlew buildPlugin # Publish the plugin to JetBrains Marketplace - - name: Publish Plugin + - name: Publish EAP Plugin env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: eap + run: ./gradlew publishPlugin + + - name: Publish Stable Plugin + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: default run: ./gradlew publishPlugin # Prepare plugin archive content for creating artifact diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 8146cb32c..8a0b2363c 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -143,6 +143,6 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels.set(listOf("eap", "default")) + channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index f5e4edb49..723551552 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.61 +pluginVersion = 0.0.62 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From 12d910d877cf834c46e65411b8675a894923eb99 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 16:25:20 -0700 Subject: [PATCH 138/186] automatically hide stable versions on release --- .github/workflows/jetbrains-release.yaml | 4 ++-- extensions/intellij/build.gradle.kts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 714796bad..a9cd2e092 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -199,10 +199,10 @@ jobs: shell: bash run: | cd ../../extensions/intellij/build/distributions - echo "Builds:" + echo "Contents of distributions folder:" ls echo "---" - FILENAME=`ls *.zip` + FILENAME=`ls continue-intellij-extension-*.zip` unzip "$FILENAME" -d content echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 8a0b2363c..ac38ac9fc 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -144,5 +144,8 @@ tasks { // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) + + // We always hide the stable releases until a few days of EAP have proven them stable + hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) } } From 746afb23d9d5972828ae402a1f87b1e314b7527f Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 16:34:37 -0700 Subject: [PATCH 139/186] cleaner core exit messages --- .../continue/CoreMessenger.kt | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 4d4e9f9ba..80ec73b70 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -235,7 +235,16 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) process!!.onExit().thenRun { - val err = process?.errorStream?.bufferedReader()?.readText()?.trim() + var err = process?.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡️Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } + } + println("Core process exited with output: $err") ideProtocolClient.showMessage("Core process exited with output: $err") From b90953eaff28deb571984f041b63a5da8f38a204 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 16:40:23 -0700 Subject: [PATCH 140/186] await --- core/config/ConfigHandler.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index dff0b065b..a95da2db1 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -51,12 +51,12 @@ class ProfileLifecycleManager { } // Clear saved config and reload - reloadConfig(): Promise { + async reloadConfig(): Promise { this.savedConfig = undefined; this.savedBrowserConfig = undefined; this.pendingConfigPromise = undefined; - return this.profileLoader.doLoadConfig(); + return await this.profileLoader.doLoadConfig(); } async loadConfig( From d56cf555e819a4e96656c1b14b8afa6526484d0e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 16:47:14 -0700 Subject: [PATCH 141/186] remove testing changes --- .github/workflows/main.yaml | 2 ++ .github/workflows/preview.yaml | 65 +++++++++++++++------------------- 2 files changed, 30 insertions(+), 37 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 3591d3e23..dc5f1019f 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -97,10 +97,12 @@ jobs: cd gui npm ci + # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - name: Install Core Dependencies run: | cd core npm ci + npm i vectordb - name: Run core tests run: | diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 5f3fa5ec9..c2abeb9cb 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,14 +1,11 @@ name: Publish Preview Extension on: - push: + create: + tags: + - "v0.9.*-vscode" branches: - - nate/fix-ci-tests - # create: - # tags: - # - "v0.9.*-vscode" - # branches: - # - dev + - dev jobs: build: @@ -55,8 +52,8 @@ jobs: with: fetch-depth: 0 # This ensures all tags are fetched - # - name: Checkout tag - # run: git checkout ${GITHUB_REF#refs/tags/} + - name: Checkout tag + run: git checkout ${GITHUB_REF#refs/tags/} # 2. Install npm dependencies - name: Use Node.js from .nvmrc @@ -64,11 +61,11 @@ jobs: with: node-version-file: ".nvmrc" - # - name: Cache extension node_modules - # uses: actions/cache@v3 - # with: - # path: extensions/vscode/node_modules - # key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + - name: Cache extension node_modules + uses: actions/cache@v3 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - name: Cache core node_modules uses: actions/cache@v3 @@ -76,24 +73,24 @@ jobs: path: core/node_modules key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - # - name: Cache gui node_modules - # uses: actions/cache@v3 - # with: - # path: gui/node_modules - # key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - # - name: Install extension Dependencies - # run: | - # cd extensions/vscode - # npm ci - # env: - # # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - # GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + - name: Install extension Dependencies + run: | + cd extensions/vscode + npm ci + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - # - name: Install gui Dependencies - # run: | - # cd gui - # npm ci + - name: Install gui Dependencies + run: | + cd gui + npm ci # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - name: Install Core Dependencies @@ -102,16 +99,10 @@ jobs: npm ci npm i vectordb - - name: Install lance - run: | - cd core - npm install @lancedb/vectordb-linux-x64-gnu - if: matrix.os == 'ubuntu-latest' - - name: Run core tests run: | cd core - npm run test -- ./indexing/CodebaseIndexer.test.ts + npm run test env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} From 4da47907f00e08f5de87c2ea940c81c567e865a9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Aug 2024 16:49:39 -0700 Subject: [PATCH 142/186] fix type error --- core/continueServer/stubs/headers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/continueServer/stubs/headers.ts b/core/continueServer/stubs/headers.ts index e6a864230..ca1e0df9d 100644 --- a/core/continueServer/stubs/headers.ts +++ b/core/continueServer/stubs/headers.ts @@ -6,7 +6,7 @@ export async function getHeaders() { key: constants.c, timestamp: getTimestamp(), v: "1", - extensionVersion: Telemetry.extensionVersion ?? "0.0.0", + extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0", os: Telemetry.os ?? "Unknown", uniqueId: Telemetry.uniqueId ?? "None", }; From 41e1eb582bec8676fc973c3a2b76259344fbb317 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 20 Aug 2024 18:51:03 +0530 Subject: [PATCH 143/186] fix(gui): passing style props on StyledTooltip --- gui/src/components/index.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/gui/src/components/index.tsx b/gui/src/components/index.tsx index a186d0e6b..eac6bf022 100644 --- a/gui/src/components/index.tsx +++ b/gui/src/components/index.tsx @@ -192,7 +192,12 @@ const TooltipStyles = { }; export function StyledTooltip(props: any) { - return ; + const combinedStyles = { + ...TooltipStyles, + ...props.style, // Merge any additional styles passed via props + }; + + return ; } export const TextArea = styled.textarea` From acea620043d2c48826266d4f1f73eaf42819f0c6 Mon Sep 17 00:00:00 2001 From: Priyash Patil <38959321+priyashpatil@users.noreply.github.com> Date: Tue, 20 Aug 2024 18:57:44 +0530 Subject: [PATCH 144/186] fix(core): delete indexed docs if re-indexing --- core/indexing/docs/DocsService.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index dbf1910dc..efd679290 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -291,8 +291,8 @@ export default class DocsService { status: "indexing", }; - // Clear old index if re-indexing. - if (reIndex) { + // Delete indexed docs if re-indexing + if (reIndex && await this.has(startUrl.toString())) { console.log("Deleting old embeddings"); await this.delete(startUrl); } From e8add8253a0368bdb63172eafcc2da82df698a27 Mon Sep 17 00:00:00 2001 From: anrgct Date: Tue, 20 Aug 2024 22:20:54 +0800 Subject: [PATCH 145/186] Fix passing codebaseContext parameter and InputToolbar flickering --- core/config/load.ts | 4 ++- gui/src/components/mainInput/TipTapEditor.tsx | 28 ++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index a9b2ba94f..2bb836d73 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -355,9 +355,11 @@ async function intermediateToFinalConfig( // These context providers are always included, regardless of what, if anything, // the user has configured in config.json + + const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {}; const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), - new CodebaseContextProvider({}), + new CodebaseContextProvider(codebaseContextParams), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 8ab8f190e..83752c95f 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -56,6 +56,7 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; +import { debounce } from "lodash"; const InputBoxDiv = styled.div` resize: none; @@ -473,6 +474,31 @@ function TipTapEditor(props: TipTapEditorProps) { }, }); + const [shouldHideToolbar, setShouldHideToolbar] = useState(false); + const debouncedShouldHideToolbar = debounce((value) => { + setShouldHideToolbar(value); + }, 200); + + useEffect(() => { + if (editor) { + const handleFocus = () => { + debouncedShouldHideToolbar(false); + } + + const handleBlur = () => { + debouncedShouldHideToolbar(true); + }; + + editor.on('focus', handleFocus); + editor.on('blur', handleBlur); + + return () => { + editor.off('focus', handleFocus); + editor.off('blur', handleBlur); + }; + } + }, [editor]); + const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); useEffect(() => { @@ -831,7 +857,7 @@ function TipTapEditor(props: TipTapEditorProps) { />