diff --git a/.vscode/settings.json b/.vscode/settings.json index 37b52608c..2224a7a16 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,5 +5,12 @@ "python.autoComplete.extraPaths": [], "python.testing.pytestArgs": ["server"], "python.testing.unittestEnabled": false, - "python.testing.pytestEnabled": true + "python.testing.pytestEnabled": true, + "terminal.integrated.defaultProfile.linux": "bash", + "terminal.integrated.profiles.linux": { + "bash": { + "path": "bash", + "args": ["-l"] + } + } } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 2a2944567..ac279cdba 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -121,7 +121,7 @@ "type": "shell", "command": "npm", "options": { - "cwd": "gui" + "cwd": "${workspaceFolder}/gui" }, "args": ["run", "dev"], "isBackground": true, @@ -142,7 +142,7 @@ } } ] - }, + }, // // esbuild for the core binary { diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 47f510040..391d81cfb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,8 +58,6 @@ Continue is continuously improving, but a feature isn't complete until it is ref #### VS Code - - Pre-requisite: You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project: ```bash diff --git a/core/.npmignore b/core/.npmignore new file mode 100644 index 000000000..899fde2a6 --- /dev/null +++ b/core/.npmignore @@ -0,0 +1,3 @@ +.env +.vscode +test \ No newline at end of file diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 66d29a17f..8e0664136 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -53,7 +53,7 @@ const autocompleteCache = AutocompleteLruCache.get(); function formatExternalSnippet( filepath: string, snippet: string, - language: AutocompleteLanguageInfo, + language: AutocompleteLanguageInfo ) { const comment = language.comment; const lines = [ @@ -78,8 +78,8 @@ export async function getTabCompletion( filepath: string, contents: string, cursorIndex: number, - ide: IDE, - ) => Promise, + ide: IDE + ) => Promise ): Promise { const startTime = Date.now(); @@ -105,6 +105,10 @@ export async function getTabCompletion( // Model if (llm instanceof OpenAI) { llm.useLegacyCompletionsEndpoint = true; + } else if (llm.providerName === "free-trial") { + throw new Error( + "Free trial is not supported for tab-autocomplete. We recommend using starcoder with Ollama, LM Studio, or another provider.", + ); } if (!llm) return; @@ -125,7 +129,7 @@ export async function getTabCompletion( filepath, fullPrefix + fullSuffix, fullPrefix.length, - ide, + ide ), new Promise((resolve) => { setTimeout(() => resolve([]), 100); @@ -151,7 +155,7 @@ export async function getTabCompletion( recentlyEditedRanges, recentlyEditedFiles, llm.model, - extrasSnippets, + extrasSnippets ); // Template prompt @@ -168,7 +172,7 @@ export async function getTabCompletion( // Format snippets as comments and prepend to prefix const formattedSnippets = snippets .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), + formatExternalSnippet(snippet.filepath, snippet.contents, lang) ) .join("\n"); if (formattedSnippets.length > 0) { @@ -220,7 +224,7 @@ export async function getTabCompletion( raw: true, stop, }), - multiline, + multiline ); // LLM @@ -237,13 +241,13 @@ export async function getTabCompletion( let chars = generatorWithCancellation(); const gen2 = onlyWhitespaceAfterEndOfLine( noFirstCharNewline(chars), - lang.endOfLine, + lang.endOfLine ); const lineGenerator = streamWithNewLines( avoidPathLine( stopAtRepeatingLines(stopAtLines(streamLines(gen2))), - lang.comment, - ), + lang.comment + ) ); const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); for await (const update of finalGenerator) { @@ -289,11 +293,11 @@ export class CompletionProvider { filepath: string, contents: string, cursorIndex: number, - ide: IDE, - ) => Promise, + ide: IDE + ) => Promise ) { this.generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), + this.onError.bind(this) ); } @@ -343,7 +347,7 @@ export class CompletionProvider { public async provideInlineCompletionItems( input: AutocompleteInput, - token: AbortSignal | undefined, + token: AbortSignal | undefined ): Promise { // Create abort signal if not given if (!token) { @@ -368,7 +372,7 @@ export class CompletionProvider { const lastUUID = await new Promise((resolve) => setTimeout(() => { resolve(CompletionProvider.lastUUID); - }, options.debounceDelay), + }, options.debounceDelay) ); if (uuid !== lastUUID) { return undefined; @@ -398,7 +402,7 @@ export class CompletionProvider { this.ide, this.generatorReuseManager, input, - this.getDefinitionsFromLsp, + this.getDefinitionsFromLsp ); const completion = outcome?.completion; @@ -430,6 +434,8 @@ export class CompletionProvider { this._logRejectionTimeouts.set(input.completionId, logRejectionTimeout); return outcome; + } catch (e: any) { + this.onError(e); } finally { this._abortControllers.delete(input.completionId); } diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 98f39b326..b24cb1458 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -127,6 +127,7 @@ function isEnglishFirstLine(line: string) { } if ( line.startsWith("here is") || + line.startsWith("here's") || line.startsWith("sure, here") || line.startsWith("sure thing") || line.startsWith("sure!") diff --git a/core/autocomplete/parameters.ts b/core/autocomplete/parameters.ts index 2bde04cf5..4940a6710 100644 --- a/core/autocomplete/parameters.ts +++ b/core/autocomplete/parameters.ts @@ -14,5 +14,5 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { recentlyEditedSimilarityThreshold: 0.3, useCache: true, onlyMyCode: true, - useOtherFiles: true, + useOtherFiles: false, }; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 00a29459c..8cb85e442 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -225,7 +225,7 @@ const EditSlashCommand: SlashCommand = { } if (!contextItemToEdit) { - yield "Select (highlight and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first"; + yield "Select (highlight and press `cmd+shift+L` (MacOS) / `ctrl+shift+L` (Windows)) the code that you want to edit first"; return; } diff --git a/core/config/default.ts b/core/config/default.ts index 60d74f7ec..da0f9aa91 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -137,4 +137,7 @@ export const defaultConfigJetBrains: SerializedContinueConfig = { params: {}, }, ], + ui: { + codeBlockToolbarPosition: "top", + } }; diff --git a/core/config/handler.ts b/core/config/handler.ts index 33712ed60..221a3ae37 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -16,15 +16,11 @@ export class ConfigHandler { private savedConfig: ContinueConfig | undefined; private savedBrowserConfig?: BrowserSerializedContinueConfig; - private readonly ide: IDE; - private ideSettingsPromise: Promise; - private readonly writeLog: (text: string) => void; - private readonly onConfigUpdate: () => void; constructor( - ide: IDE, - ideSettingsPromise: Promise, - writeLog: (text: string) => void, - onConfigUpdate: () => void, + private readonly ide: IDE, + private ideSettingsPromise: Promise, + private readonly writeLog: (text: string) => void, + private readonly onConfigUpdate: () => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -58,50 +54,45 @@ export class ConfigHandler { } async loadConfig(): Promise { - try { - if (this.savedConfig) { - return this.savedConfig; - } - - let workspaceConfigs: ContinueRcJson[] = []; - try { - workspaceConfigs = await this.ide.getWorkspaceConfigs(); - } catch (e) { - console.warn("Failed to load workspace configs"); - } - - const ideInfo = await this.ide.getIdeInfo(); - const ideSettings = await this.ideSettingsPromise; - let remoteConfigServerUrl = undefined; - try { - remoteConfigServerUrl = - typeof ideSettings.remoteConfigServerUrl !== "string" || - ideSettings.remoteConfigServerUrl === "" - ? undefined - : new URL(ideSettings.remoteConfigServerUrl); - } catch (e) {} - - this.savedConfig = await loadFullConfigNode( - this.ide.readFile, - workspaceConfigs, - remoteConfigServerUrl, - ideInfo.ideType, - ); - this.savedConfig.allowAnonymousTelemetry = - this.savedConfig.allowAnonymousTelemetry && - (await this.ide.isTelemetryEnabled()); - - // Setup telemetry only after (and if) we know it is enabled - await Telemetry.setup( - this.savedConfig.allowAnonymousTelemetry ?? true, - await this.ide.getUniqueId(), - ); - + if (this.savedConfig) { return this.savedConfig; - } catch (e: any) { - console.error("Failed to loadConfig: ", e.message); - throw new Error("Failed to loadConfig: " + e.message); } + + let workspaceConfigs: ContinueRcJson[] = []; + try { + workspaceConfigs = await this.ide.getWorkspaceConfigs(); + } catch (e) { + console.warn("Failed to load workspace configs"); + } + + const ideInfo = await this.ide.getIdeInfo(); + const ideSettings = await this.ideSettingsPromise; + let remoteConfigServerUrl = undefined; + try { + remoteConfigServerUrl = + typeof ideSettings.remoteConfigServerUrl !== "string" || + ideSettings.remoteConfigServerUrl === "" + ? undefined + : new URL(ideSettings.remoteConfigServerUrl); + } catch (e) {} + + this.savedConfig = await loadFullConfigNode( + this.ide.readFile, + workspaceConfigs, + remoteConfigServerUrl, + ideInfo.ideType, + ); + this.savedConfig.allowAnonymousTelemetry = + this.savedConfig.allowAnonymousTelemetry && + (await this.ide.isTelemetryEnabled()); + + // Setup telemetry only after (and if) we know it is enabled + await Telemetry.setup( + this.savedConfig.allowAnonymousTelemetry ?? true, + await this.ide.getUniqueId(), + ); + + return this.savedConfig; } setupLlm(llm: ILLM): ILLM { diff --git a/core/config/load.ts b/core/config/load.ts index e30980b4b..c52ab61cc 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -38,7 +38,6 @@ import { getContinueDotEnv, migrate, } from "../util/paths"; -import { defaultConfig } from "./default"; const { execSync } = require("child_process"); function resolveSerializedConfig(filepath: string): SerializedContinueConfig { @@ -80,8 +79,7 @@ function loadSerializedConfig( try { config = resolveSerializedConfig(configPath); } catch (e) { - console.log("config.json is invalid. Falling back to default."); - config = defaultConfig; + throw new Error(`Failed to parse config.json: ${e}`); } if (config.allowAnonymousTelemetry === undefined) { @@ -321,6 +319,7 @@ function finalToBrowserConfig( disableSessionTitles: final.disableSessionTitles, userToken: final.userToken, embeddingsProvider: final.embeddingsProvider?.id, + ui: final.ui, }; } diff --git a/core/index.d.ts b/core/index.d.ts index 5485a1d49..f1c2ab35a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -624,6 +624,10 @@ export interface TabAutocompleteOptions { useOtherFiles: boolean; } +export interface ContinueUIConfig { + codeBlockToolbarPosition?: "top" | "bottom"; +} + export interface SerializedContinueConfig { env?: string[]; allowAnonymousTelemetry?: boolean; @@ -639,6 +643,7 @@ export interface SerializedContinueConfig { embeddingsProvider?: EmbeddingsProviderDescription; tabAutocompleteModel?: ModelDescription; tabAutocompleteOptions?: Partial; + ui?: ContinueUIConfig; } export type ConfigMergeType = "merge" | "overwrite"; @@ -677,6 +682,8 @@ export interface Config { tabAutocompleteModel?: CustomLLM | ModelDescription; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; + /** UI styles customization */ + ui?: ContinueUIConfig; } export interface ContinueConfig { @@ -692,6 +699,7 @@ export interface ContinueConfig { embeddingsProvider: EmbeddingsProvider; tabAutocompleteModel?: ILLM; tabAutocompleteOptions?: Partial; + ui?: ContinueUIConfig; } export interface BrowserSerializedContinueConfig { @@ -705,4 +713,5 @@ export interface BrowserSerializedContinueConfig { disableSessionTitles?: boolean; userToken?: string; embeddingsProvider?: string; + ui?: ContinueUIConfig; } diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index c1ab1c68d..f8f92443f 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -27,7 +27,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { constructor(private readonly ide: IDE) {} - private async _createTables(db: DatabaseConnection) { + private static async _createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( id INTEGER PRIMARY KEY, path TEXT NOT NULL, @@ -98,7 +98,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, ): AsyncGenerator { const db = await SqliteDb.get(); - await this._createTables(db); + await CodeSnippetsCodebaseIndex._createTables(db); const tagString = tagToString(tag); for (let i = 0; i < results.compute.length; i++) { @@ -193,6 +193,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async getAll(tag: IndexTag): Promise { const db = await SqliteDb.get(); + await CodeSnippetsCodebaseIndex._createTables(db); try { const rows = await db.all( `SELECT cs.id, cs.path, cs.title diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index ec9a0c98b..e97bd3aec 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -1,8 +1,9 @@ import { Readability } from "@mozilla/readability"; +import { JSDOM } from "jsdom"; import { Chunk } from "../.."; import { MAX_CHUNK_SIZE } from "../../llm/constants"; import { cleanFragment, cleanHeader } from "../chunk/markdown"; -import { PageData } from "./crawl" +import { PageData } from "./crawl"; export type ArticleComponent = { title: string; @@ -93,10 +94,7 @@ export function chunkArticle(articleResult: Article): Chunk[] { return chunks; } -async function extractTitlesAndBodies( - html: string, -): Promise { - const { JSDOM } = await import("jsdom"); +function extractTitlesAndBodies(html: string): ArticleComponent[] { const dom = new JSDOM(html); const document = dom.window.document; @@ -117,14 +115,13 @@ async function extractTitlesAndBodies( return result; } -export async function stringToArticle( +export function stringToArticle( url: string, - htmlContent: string, + html: string, subpath: string, -): Promise
{ +): Article | undefined { try { - const { JSDOM } = await import("jsdom"); - const dom = new JSDOM(htmlContent); + const dom = new JSDOM(html); let reader = new Readability(dom.window.document); let article = reader.parse(); @@ -132,8 +129,8 @@ export async function stringToArticle( return undefined; } - let article_components = await extractTitlesAndBodies(article.content); - + let article_components = extractTitlesAndBodies(article.content); + return { url, subpath, @@ -146,9 +143,7 @@ export async function stringToArticle( } } -export async function pageToArticle( - page: PageData -): Promise
{ +export function pageToArticle(page: PageData): Article | undefined { try { return stringToArticle(page.url, page.html, page.path); } catch (err) { diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index 151b220fb..2e94aba91 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -8,19 +8,20 @@ import { default as configs } from "./preIndexedDocs"; const DOCS_TABLE_NAME = "docs"; +// Purposefully lowercase because lancedb converts interface LanceDbDocsRow { title: string; - baseUrl: string; + baseurl: string; // Chunk content: string; path: string; - startLine: number; - endLine: number; + startline: number; + endline: number; vector: number[]; [key: string]: any; } -let dbDocs:Database; +let dbDocs: Database; async function getDBDocs() { if (!dbDocs) { @@ -28,7 +29,7 @@ async function getDBDocs() { filename: getDocsSqlitePath(), driver: sqlite3.Database, }); - + dbDocs.exec(`CREATE TABLE IF NOT EXISTS docs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, @@ -75,10 +76,10 @@ export async function retrieveDocs( let docs: LanceDbDocsRow[] = await table .search(vector) .limit(nRetrieve) - .where(`baseUrl = '${baseUrl}'`) + .where(`baseurl = '${baseUrl}'`) .execute(); - docs = docs.filter((doc) => doc.baseUrl === baseUrl); + docs = docs.filter((doc) => doc.baseurl === baseUrl); if ((!docs || docs.length === 0) && !nested) { const downloaded = await downloadDocs(); @@ -88,8 +89,8 @@ export async function retrieveDocs( return docs.map((doc) => ({ digest: doc.path, filepath: doc.path, - startLine: doc.startLine, - endLine: doc.endLine, + startLine: doc.startline, + endLine: doc.endline, index: 0, content: doc.content, otherMetadata: { @@ -106,11 +107,11 @@ export async function addDocs( ) { const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ title: chunk.otherMetadata?.title || title, - baseUrl: baseUrl.toString(), + baseurl: baseUrl.toString(), content: chunk.content, path: chunk.filepath, - startLine: chunk.startLine, - endLine: chunk.endLine, + startline: chunk.startLine, + endline: chunk.endLine, vector: embeddings[i], })); @@ -144,5 +145,5 @@ export async function listDocs(): Promise< export async function hasDoc(baseUrl: string) { const db = await getDBDocs(); const doc = await db.get(`SELECT title FROM docs WHERE baseUrl =?`, baseUrl); - return!!doc; + return !!doc; } diff --git a/core/indexing/docs/index.ts b/core/indexing/docs/index.ts index 89906f0f1..79d96371c 100644 --- a/core/indexing/docs/index.ts +++ b/core/indexing/docs/index.ts @@ -29,7 +29,7 @@ export async function* indexDocs( const articles: Article[] = []; for await (const page of crawlPage(baseUrl)) { - const article = await pageToArticle(page); + const article = pageToArticle(page); if (!article) continue; articles.push(article); diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 6680e3c45..2fe2fe415 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -211,6 +211,11 @@ const configs: SiteIndexingConfig[] = [ startUrl: "https://www.w3schools.com/css/default.asp", rootUrl: "https://www.w3schools.com/css", }, + { + title: "Langchain", + startUrl: "https://python.langchain.com/docs/get_started/introduction", + rootUrl: "https://python.langchain.com/docs", + }, ]; export default configs; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 03bf7f7fa..6f6ec1406 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -147,7 +147,12 @@ async function getAddRemoveForTag( } = {}; async function markComplete(items: PathAndCacheKey[], _: IndexResultType) { - const actions = items.map((item) => itemToAction[JSON.stringify(item)]); + const actions = items.map( + (item) => + itemToAction[ + JSON.stringify({ path: item.path, cacheKey: item.cacheKey }) + ], + ); for (const [{ path, cacheKey }, resultType] of actions) { switch (resultType) { case AddRemoveResultType.Add: diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 4274c3a55..a82104afd 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -281,7 +281,9 @@ function compileChatMessages( functions: any[] | undefined = undefined, systemMessage: string | undefined = undefined, ): ChatMessage[] { - const msgsCopy = msgs ? msgs.map((msg) => ({ ...msg })) : []; + const msgsCopy = msgs + ? msgs.map((msg) => ({ ...msg })).filter((msg) => msg.content !== "") + : []; if (prompt) { const promptMsg: ChatMessage = { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 4bafdccba..d59d114b9 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -98,6 +98,9 @@ class FreeTrial extends BaseLLM { "gemini-pro", "gpt-4-vision-preview", "codellama-70b", + "claude-3-opus-20240229", + "claude-3-sonnet-20240229", + "claude-3-haiku-20240307", ]; } } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 1ea5deab4..b7209e94c 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -164,6 +164,7 @@ class Ollama extends BaseLLM { buffer += value; // Split the buffer into individual JSON chunks const chunks = buffer.split("\n"); + buffer = chunks.pop() ?? ""; for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; @@ -180,8 +181,6 @@ class Ollama extends BaseLLM { } } } - // Assign the last chunk to the buffer - buffer = chunks[chunks.length - 1]; } } diff --git a/core/package-lock.json b/core/package-lock.json index 545983547..9c82cd3d2 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -1,12 +1,12 @@ { - "name": "core", - "version": "1.0.0", + "name": "@continuedev/core", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "core", - "version": "1.0.0", + "name": "@continuedev/core", + "version": "1.0.4", "license": "Apache-2.0", "dependencies": { "@mozilla/readability": "^0.5.0", @@ -56,6 +56,9 @@ "esbuild": "^0.19.11", "jest": "^29.7.0", "ts-jest": "^29.1.1" + }, + "engines": { + "node": ">=20.11.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/core/package.json b/core/package.json index 184dd7a56..3cd4ea5f0 100644 --- a/core/package.json +++ b/core/package.json @@ -1,9 +1,10 @@ { "name": "@continuedev/core", - "version": "1.0.1", + "version": "1.0.4", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.", "scripts": { - "test": "jest ./test/diff.test.ts" + "test": "jest ./test/diff.test.ts", + "build:npm": "tsc -p ./tsconfig.npm.json" }, "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", diff --git a/core/tsconfig.npm.json b/core/tsconfig.npm.json new file mode 100644 index 000000000..3e6d85576 --- /dev/null +++ b/core/tsconfig.npm.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "lib": ["DOM", "DOM.Iterable", "ESNext", "ES2021"], + "allowJs": false, + "skipLibCheck": true, + "esModuleInterop": false, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "ESNext", + "moduleResolution": "Node", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "noEmitOnError": false, + "types": ["jest", "node"], + "outDir": "dist", + "declaration": true, + "declarationMap": true + }, + "include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"] +} diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 4a54f2044..64a7d66d3 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -36,8 +36,9 @@ export const supportedLanguages: { [key: string]: string } = { cts: "typescript", tsx: "tsx", vue: "vue", - yaml: "yaml", - yml: "yaml", + // The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part + // yaml: "yaml", + // yml: "yaml", elm: "elm", js: "javascript", jsx: "javascript", diff --git a/core/yarn.lock b/core/yarn.lock index e3d3fc3d9..795d82637 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -326,6 +326,11 @@ resolved "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== +"@esbuild/darwin-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.12.tgz" + integrity sha512-B6IeSgZgtEzGC42jsI+YYu9Z3HKRxp8ZT3cqhvliEHovq8HSX2YX8lNocDn79gCKJXOSaEot9MVYky7AKjCs8g== + "@eslint-community/eslint-utils@^4.2.0": version "4.4.0" resolved "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz" @@ -2662,6 +2667,11 @@ fs.realpath@^1.0.0: resolved "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz" integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== +fsevents@^2.3.2: + version "2.3.3" + resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz" + integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== + function-bind@^1.1.2: version "1.1.2" resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz" diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 6445a7577..65089e0f9 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.38 +pluginVersion = 0.0.39 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index f272a0aac..2c9a5c874 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -4,6 +4,11 @@ import com.github.continuedev.continueintellijextension.`continue`.uuid import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson +import com.intellij.codeInsight.AutoPopupController +import com.intellij.codeInsight.lookup.LookupManager +import com.intellij.codeInsight.lookup.impl.LookupImpl +import com.intellij.openapi.actionSystem.ActionManager +import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.invokeLater @@ -44,23 +49,36 @@ class AutocompleteService(private val project: Project) { // Request a completion from the core val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) + val column = editor.caretModel.primaryCaret.logicalPosition.column val input = mapOf( "completionId" to completionId, "filepath" to virtualFile?.path, "pos" to mapOf( "line" to editor.caretModel.primaryCaret.logicalPosition.line, - "character" to editor.caretModel.primaryCaret.logicalPosition.column + "character" to column ), "recentlyEditedFiles" to emptyList(), "recentlyEditedRanges" to emptyList(), "clipboardText" to "" ) + + val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line) + val lineEnd = editor.document.getLineEndOffset(editor.caretModel.primaryCaret.logicalPosition.line) + val lineLength = lineEnd - lineStart + project.service().coreMessenger?.request("autocomplete/complete", input, null, ({ response -> val completions = Gson().fromJson(response, List::class.java) if (completions.isNotEmpty()) { val completion = completions[0].toString() - renderCompletion(editor, offset, completion) - pendingCompletion = pendingCompletion?.copy(text = completion) + + if (completion.lines().size === 1 || column >= lineLength) { + // Do not render if completion is multi-line and caret is in middle of line + renderCompletion(editor, offset, completion) + pendingCompletion = pendingCompletion?.copy(text = completion) + + // Hide auto-popup +// AutoPopupController.getInstance(project).cancelAllRequests() + } } })) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt new file mode 100644 index 000000000..1cd223df9 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt @@ -0,0 +1,26 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.intellij.openapi.actionSystem.DataContext +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Caret +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.actionSystem.EditorAction +import com.intellij.openapi.editor.actionSystem.EditorActionHandler + +class PartialAcceptAutocompleteAction: EditorAction(object : EditorActionHandler() { + override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { + ApplicationManager.getApplication().runWriteAction { + // TODO +// editor.project?.service()?.accept() + } + } + + override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { + val autocompleteService = editor.project?.service(); + val enabled = editor == autocompleteService?.pendingCompletion?.editor + && caret.offset == autocompleteService.pendingCompletion?.offset + && autocompleteService.pendingCompletion?.text != null + return enabled + } +}) {} \ No newline at end of file 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 ae74a89e1..bd9f2f676 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 @@ -6,6 +6,7 @@ import java.io.OutputStreamWriter import java.io.* import com.google.gson.Gson +import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.PosixFilePermission @@ -147,7 +148,7 @@ class CoreMessenger(esbuildPath: String, continueCorePath: String, ideProtocolCl val inputStream = process.inputStream writer = OutputStreamWriter(outputStream) - reader = BufferedReader(InputStreamReader(inputStream)) + reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) process.onExit().thenRun { val err = process.errorStream.bufferedReader().readText().trim() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index c3ae201ef..873ccb911 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -76,19 +76,31 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { init { System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) - System.setProperty("ide.browser.jcef.osr.enabled", "false") System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") } val webView: JBCefBrowser by lazy { - val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build() + val osName = System.getProperty("os.name").toLowerCase() + val os = when { + osName.contains("mac") || osName.contains("darwin") -> "darwin" + osName.contains("win") -> "win32" + osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" + else -> "linux" + } + + val browser = JBCefBrowser.createBuilder().setOffScreenRendering(os == "linux").build() browser.jbCefClient.setProperty( JBCefClient.Properties.JS_QUERY_POOL_SIZE, JS_QUERY_POOL_SIZE ) registerAppSchemeHandler() - browser.loadURL("http://continue/index.html") + // Use to get hot-reloading in local development + if (false) { + browser.loadURL("http://localhost:5173/jetbrains_index.html"); + } else { + browser.loadURL("http://continue/index.html") + } // browser.loadHTML("") // browser.loadURL("http://localhost:5173/index.html") Disposer.register(project, browser) diff --git a/extensions/intellij/src/main/resources/continue_tutorial.py b/extensions/intellij/src/main/resources/continue_tutorial.py index 5bdc1ab85..7c8d6b0c8 100644 --- a/extensions/intellij/src/main/resources/continue_tutorial.py +++ b/extensions/intellij/src/main/resources/continue_tutorial.py @@ -65,3 +65,5 @@ select the code""" accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit""" # endregion + +# Ready to learn more? Check out the Continue documentation: https://continue.dev/docs \ No newline at end of file diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index 2583d5621..e332e22af 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -12,7 +12,7 @@ You can either - follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section" """ -# region —————————————————————————— Part 1: Ask a question about code [⌘ L] —————————————————————————— +# region —————————————————————————— Part 1: Ask a question about code [Cmd+L] —————————————————————————— """Step 1: Highlight the function below""" @@ -27,14 +27,14 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ L] to +"""Step 2: Use the keyboard shortcut [Cmd+L] to select the code and toggle the Continue input box""" """Step 3: Ask a question and press Enter""" # endregion -# region ————————————————————————————————— Part 2: Edit code [⌘ I] ————————————————————————————————— +# region ————————————————————————————————— Part 2: Edit code [Cmd+I] ————————————————————————————————— """Step 1: Highlight this code""" @@ -53,16 +53,16 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ I] to edit""" +"""Step 2: Use the keyboard shortcut [Cmd+I] to edit""" """Step 3: Type "" and press Enter""" """Step 4: Use keyboard shortcuts to -accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit""" +accept [Cmd+Shift+Enter] or reject [Cmd+Shift+Backspace] the edit""" # endregion -# region ———————————————————————————— Part 3: Debug automatically [⌘ ⇧ R] ———————————————————————————— +# region ———————————————————————————— Part 3: Debug automatically [Cmd+Shift+R] ———————————————————————————— """Step 1: Run this Python file (it should error!)""" @@ -72,8 +72,10 @@ def print_sum(list_to_print): print(sum(list_to_print)) -"""Step 2: Use the keyboard shortcut [⌘ ⇧ R] +"""Step 2: Use the keyboard shortcut [Cmd+Shift+R] to automatically debug the error""" print_sum(["a", "b", "c"]) # endregion + +# Ready to learn more? Check out the Continue documentation: https://continue.dev/docs \ No newline at end of file diff --git a/extensions/vscode/esbuild.js b/extensions/vscode/esbuild.js index 67c307d05..fed18197a 100644 --- a/extensions/vscode/esbuild.js +++ b/extensions/vscode/esbuild.js @@ -6,7 +6,7 @@ const esbuildConfig = { entryPoints: ["src/extension.ts"], bundle: true, outfile: "out/extension.js", - external: ["vscode", "esbuild", "jsdom"], + external: ["vscode", "esbuild"], format: "cjs", platform: "node", sourcemap: true, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index d2afbe815..6ab6ac9f7 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.88", + "version": "0.9.92", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.88", + "version": "0.9.92", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -86,7 +86,7 @@ }, "../../core": { "name": "@continuedev/core", - "version": "1.0.1", + "version": "1.0.4", "license": "Apache-2.0", "dependencies": { "@mozilla/readability": "^0.5.0", @@ -123,7 +123,7 @@ "sqlite3": "^5.1.7", "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", - "vectordb": "^0.4.3", + "vectordb": "^0.4.12", "web-tree-sitter": "^0.21.0" }, "devDependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9a290cb08..50d9a7872 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,7 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.8.21", + "version": "0.9.92", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -62,7 +62,7 @@ "continue.showInlineTip": { "type": "boolean", "default": true, - "description": "Show inline suggestion to use the Continue keyboard shortcuts." + "description": "Show inline suggestion to use the Continue keyboard shortcuts (e.g. \"Cmd/Ctrl L to select code, Cmd/Ctrl I to edit\")." }, "continue.enableTabAutocomplete": { "type": "boolean", diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 3da971d49..208ef0019 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -9,8 +9,8 @@ if (!fs.existsSync("build")) { } const command = isPreRelease - ? "vsce package --out ./build patch --pre-release --yarn" - : "vsce package --out ./build patch --yarn"; + ? "vsce package --out ./build patch --pre-release" // --yarn" + : "vsce package --out ./build patch"; // --yarn"; exec(command, (error) => { if (error) throw error; diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index cdcf4c2b1..3b3e06a0e 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -241,7 +241,7 @@ if (args[2] === "--target") { }); function ghAction() { - return target !== undefined; + return !!process.env.GITHUB_ACTIONS; } function isArm() { @@ -317,13 +317,7 @@ if (args[2] === "--target") { }); // Copy node_modules for pre-built binaries - const NODE_MODULES_TO_COPY = [ - "esbuild", - "@esbuild", - "@lancedb", - "@vscode", - "jsdom", - ]; + const NODE_MODULES_TO_COPY = ["esbuild", "@esbuild", "@lancedb", "@vscode"]; fs.mkdirSync("out/node_modules", { recursive: true }); await Promise.all( @@ -346,5 +340,12 @@ if (args[2] === "--target") { }), ), ); + console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`); + + // Copy over any worker files + fs.cpSync( + "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js", + "out/xhr-sync-worker.js", + ); })(); diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 3de6b77be..3b999b4b9 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -17,7 +17,7 @@ export async function showTutorial() { // Ensure keyboard shortcuts match OS if (process.platform !== "darwin") { let tutorialContent = fs.readFileSync(tutorialPath, "utf8"); - tutorialContent = tutorialContent.replace("⌘", "^"); + tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl"); fs.writeFileSync(tutorialPath, tutorialContent); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 30866ca74..24140cde9 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -20,8 +20,8 @@ export class ContinueCompletionProvider if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete", - ), + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) ); } }); @@ -32,14 +32,14 @@ export class ContinueCompletionProvider constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, - private readonly tabAutocompleteModel: TabAutocompleteModel, + private readonly tabAutocompleteModel: TabAutocompleteModel ) { this.completionProvider = new CompletionProvider( this.configHandler, this.ide, this.tabAutocompleteModel.get.bind(this.tabAutocompleteModel), this.onError.bind(this), - getDefinitionsFromLsp, + getDefinitionsFromLsp ); } @@ -47,7 +47,7 @@ export class ContinueCompletionProvider document: vscode.TextDocument, position: vscode.Position, context: vscode.InlineCompletionContext, - token: vscode.CancellationToken, + token: vscode.CancellationToken //@ts-ignore ): ProviderResult { const enableTabAutocomplete = @@ -75,7 +75,7 @@ export class ContinueCompletionProvider const outcome = await this.completionProvider.provideInlineCompletionItems( input, - signal, + signal ); if (!outcome || !outcome.completion) { @@ -100,17 +100,15 @@ export class ContinueCompletionProvider outcome.completion, new vscode.Range( position, - position.translate(0, outcome.completion.length), + position.translate(0, outcome.completion.length) ), { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", arguments: [outcome, logRejectionTimeout], - }, + } ), ]; - } catch (e: any) { - this.onError(e); } finally { stopStatusBarLoading(); } diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 4aed9174c..7d10ff8f1 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,5 +1,6 @@ import { ConfigHandler } from "core/config/handler"; import { getMarkdownLanguageTagForFile } from "core/util"; +import { Telemetry } from "core/util/posthog"; import { streamDiffLines } from "core/util/verticalEdit"; import * as vscode from "vscode"; import { VerticalPerLineDiffHandler } from "./handler"; @@ -182,6 +183,10 @@ export class VerticalPerLineDiffManager { input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; } try { + Telemetry.capture("inlineEdit", { + model: llm.model, + provider: llm.providerName, + }); await diffHandler.run( streamDiffLines( rangeContent, diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index 9c57b884e..4d41632e9 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -6,6 +6,7 @@ import * as vscode from "vscode"; import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; import { setupStatusBar } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; +import { registerDebugTracker } from "../debug/debug"; import { ContinueGUIWebviewViewProvider } from "../debugPanel"; import { DiffManager } from "../diff/horizontal"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; @@ -14,7 +15,6 @@ import { registerAllCodeLensProviders } from "../lang-server/codeLens"; import { setupRemoteConfigSync } from "../stubs/activation"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { registerDebugTracker } from "../debug/debug"; export class VsCodeExtension { private configHandler: ConfigHandler; @@ -48,26 +48,28 @@ export class VsCodeExtension { // Config Handler with output channel const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion" + "Continue - LLM Prompt/Completion", ); this.configHandler = new ConfigHandler( this.ide, Promise.resolve(ideSettings), async (log: string) => { outputChannel.appendLine( - "==========================================================================" + "==========================================================================", ); outputChannel.appendLine( - "==========================================================================" + "==========================================================================", ); outputChannel.append(log); }, - () => this.webviewProtocol?.request("configUpdate", undefined) + (() => this.webviewProtocol?.request("configUpdate", undefined)).bind( + this, + ), ); this.configHandler.reloadConfig(); this.verticalDiffManager = new VerticalPerLineDiffManager( - this.configHandler + this.configHandler, ); this.extensionContext = context; this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); @@ -77,7 +79,7 @@ export class VsCodeExtension { this.ide, this.windowId, this.extensionContext, - this.verticalDiffManager + this.verticalDiffManager, ); setupRemoteConfigSync( @@ -91,14 +93,14 @@ export class VsCodeExtension { this.sidebar, { webviewOptions: { retainContextWhenHidden: true }, - } - ) + }, + ), ); this.webviewProtocol = this.sidebar.webviewProtocol; // Indexing + pause token const indexingPauseToken = new PauseToken( - context.globalState.get("continue.indexingPaused") === true + context.globalState.get("continue.indexingPaused") === true, ); this.webviewProtocol.on("index/setPaused", (msg) => { context.globalState.update("continue.indexingPaused", msg.data); @@ -109,14 +111,14 @@ export class VsCodeExtension { this.indexer = new CodebaseIndexer( this.configHandler, this.ide, - indexingPauseToken + indexingPauseToken, ); // CodeLens registerAllCodeLensProviders( context, this.diffManager, - this.verticalDiffManager.editorToVerticalDiffCodeLens + this.verticalDiffManager.editorToVerticalDiffCodeLens, ); // Tab autocomplete @@ -131,9 +133,9 @@ export class VsCodeExtension { new ContinueCompletionProvider( this.configHandler, this.ide, - this.tabAutocompleteModel - ) - ) + this.tabAutocompleteModel, + ), + ), ); // Commands @@ -144,7 +146,7 @@ export class VsCodeExtension { this.sidebar, this.configHandler, this.diffManager, - this.verticalDiffManager + this.verticalDiffManager, ); registerDebugTracker(this.webviewProtocol, this.ide); @@ -195,7 +197,7 @@ export class VsCodeExtension { } }); } - }) + }), ); // Register a content provider for the readonly virtual documents @@ -213,8 +215,8 @@ export class VsCodeExtension { context.subscriptions.push( vscode.workspace.registerTextDocumentContentProvider( VsCodeExtension.continueVirtualDocumentScheme, - documentContentProvider - ) + documentContentProvider, + ), ); } diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 3004e9b4c..0f1557d40 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,6 +1,7 @@ import { FileEdit, RangeInFile, Thread } from "core"; import path from "path"; import * as vscode from "vscode"; +import { threadStopped } from "../debug/debug"; import { VsCodeExtension } from "../extension/vscodeExtension"; import { SuggestionRanges, @@ -15,7 +16,6 @@ import { openEditorAndRevealRange, uriFromFilePath, } from "./vscode"; -import { threadStopped } from "../debug/debug"; const util = require("util"); const asyncExec = util.promisify(require("child_process").exec); @@ -298,7 +298,7 @@ export class VsCodeIdeUtils { // Check first whether it's an open document const openTextDocument = vscode.workspace.textDocuments.find( - (doc) => doc.uri.toString() === uri.toString(), + (doc) => doc.uri.fsPath === uri.fsPath, ); if (openTextDocument !== undefined) { return openTextDocument.getText(); diff --git a/extensions/vscode/src/util/traverseDirectory.ts b/extensions/vscode/src/util/traverseDirectory.ts index e1af01848..cd4095da4 100644 --- a/extensions/vscode/src/util/traverseDirectory.ts +++ b/extensions/vscode/src/util/traverseDirectory.ts @@ -51,6 +51,8 @@ const DEFAULT_IGNORE_FILETYPES = [ "*.onnx", "*.parquet", "*.pqt", + "*.wav", + "*.webp", ]; export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); const DEFAULT_IGNORE_DIRS = [ diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 381b543e5..3b21730ca 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -8,6 +8,7 @@ import { DevDataSqliteDb } from "core/util/devdataSqlite"; import historyManager from "core/util/history"; import { Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; +import { Telemetry } from "core/util/posthog"; import { ReverseWebviewProtocol, WebviewProtocol, @@ -83,7 +84,7 @@ export class VsCodeWebviewProtocol { JSON.stringify({ msg }, null, 2), ); - let message = `Continue error: ${e.message}`; + let message = e.message; if (e.cause) { if (e.cause.name === "ConnectTimeoutError") { message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; @@ -387,6 +388,10 @@ export class VsCodeWebviewProtocol { throw new Error(`Unknown slash command ${slashCommandName}`); } + Telemetry.capture("useSlashCommand", { + name: slashCommandName, + }); + for await (const content of slashCommand.run({ input, history, @@ -465,6 +470,11 @@ export class VsCodeWebviewProtocol { ide, selectedCode, }); + + Telemetry.capture("useContextProvider", { + name: provider.description.title, + }); + return items.map((item) => ({ ...item, id })); } catch (e) { vscode.window.showErrorMessage( diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index a46bb2042..9d1481221 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -14,5 +14,6 @@ "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 */ }, - "include": ["src/**/*", "../../core/**/*.ts"] + "include": ["src/**/*", "../../core/**/*.ts"], + "exclude": ["../../core/dist/**/*"] } diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index b47e18677..9268fc252 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -2353,7 +2353,7 @@ core-util-is@1.0.2: integrity sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ== "core@file:../../core": - version "1.0.1" + version "1.0.4" resolved "file:../../core" dependencies: "@mozilla/readability" "^0.5.0" @@ -2390,7 +2390,7 @@ core-util-is@1.0.2: sqlite3 "^5.1.7" tree-sitter-wasms "^0.1.6" uuid "^9.0.1" - vectordb "^0.4.3" + vectordb "^0.4.12" web-tree-sitter "^0.21.0" cors@^2.8.5: diff --git a/gui/package-lock.json b/gui/package-lock.json index 92bc8e738..6f308aca7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -48,6 +48,7 @@ "seti-file-icons": "^0.0.8", "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", + "table": "^6.8.1", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", @@ -74,7 +75,7 @@ }, "../core": { "name": "@continuedev/core", - "version": "1.0.1", + "version": "1.0.4", "license": "Apache-2.0", "dependencies": { "@mozilla/readability": "^0.5.0", @@ -111,7 +112,7 @@ "sqlite3": "^5.1.7", "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", - "vectordb": "^0.4.3", + "vectordb": "^0.4.12", "web-tree-sitter": "^0.21.0" }, "devDependencies": { @@ -1960,6 +1961,21 @@ "vite": "^4 || ^5" } }, + "node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/ansi-regex": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", @@ -2013,6 +2029,14 @@ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "engines": { + "node": ">=8" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -3531,7 +3555,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "engines": { "node": ">=8" } @@ -3645,6 +3668,11 @@ "node": ">=4" } }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -3711,6 +3739,11 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "node_modules/lodash.truncate": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", + "integrity": "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw==" + }, "node_modules/longest-streak": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", @@ -5120,6 +5153,14 @@ "prosemirror-transform": "^1.1.0" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, "node_modules/punycode.js": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", @@ -6010,6 +6051,14 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/reselect": { "version": "4.1.8", "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.8.tgz", @@ -6146,6 +6195,52 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/slice-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, "node_modules/socket.io-client": { "version": "4.7.4", "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.7.4.tgz", @@ -6395,6 +6490,58 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/table": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", + "integrity": "sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA==", + "dependencies": { + "ajv": "^8.0.1", + "lodash.truncate": "^4.4.2", + "slice-ansi": "^4.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/table/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/table/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/table/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/table/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tailwindcss": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.1.tgz", @@ -6715,6 +6862,14 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dependencies": { + "punycode": "^2.1.0" + } + }, "node_modules/use-sync-external-store": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", diff --git a/gui/package.json b/gui/package.json index e37a80785..3fbbea92b 100644 --- a/gui/package.json +++ b/gui/package.json @@ -50,6 +50,7 @@ "seti-file-icons": "^0.0.8", "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", + "table": "^6.8.1", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", diff --git a/gui/public/jetbrains_index.html b/gui/public/jetbrains_index.html new file mode 100644 index 000000000..590109a35 --- /dev/null +++ b/gui/public/jetbrains_index.html @@ -0,0 +1,26 @@ + + + + + + + + Continue + + +
+ + + + + + + diff --git a/gui/src/components/dialogs/KeyboardShortcuts.tsx b/gui/src/components/dialogs/KeyboardShortcuts.tsx index 574ee48ff..d4a55d030 100644 --- a/gui/src/components/dialogs/KeyboardShortcuts.tsx +++ b/gui/src/components/dialogs/KeyboardShortcuts.tsx @@ -114,8 +114,8 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ description: "Reject Diff", }, { - mac: "⌥ ⌘ M", - windows: "⌥ ⌃ M", + mac: "⌥ ⌘ L", + windows: "⌥ ⌃ L", description: "Toggle Auxiliary Bar", }, { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c29f063e5..80c8142ff 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -582,6 +582,7 @@ function TipTapEditor(props: TipTapEditorProps) { }} > { setInputFocused(true); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 0460c719e..ac039d694 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -34,8 +34,9 @@ async function resolveEditorContent( for (const p of editorState?.content) { if (p.type === "paragraph") { const [text, ctxItems, foundSlashCommand] = resolveParagraph(p); - + // Only take the first slash command + if (foundSlashCommand && typeof slashCommand === "undefined") { slashCommand = foundSlashCommand; } @@ -89,14 +90,14 @@ async function resolveEditorContent( let contextItemsText = ""; let contextItems: ContextItemWithId[] = []; - const ide = new WebviewIde(); for (const item of contextItemAttrs) { if (item.itemType === "file") { + const ide = new WebviewIde(); // This is a quick way to resolve @file references const basename = getBasename(item.id); const rawContent = await ide.readFile(item.id); const content = `\`\`\`title="${basename}"\n${rawContent}\n\`\`\`\n`; - contextItemsText += content + contextItemsText += content; contextItems.push({ name: basename, description: item.id, diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index 6bb735afb..b23c5ff61 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -1,13 +1,10 @@ -import { - CheckIcon, - ClipboardIcon, - PlayIcon, -} from "@heroicons/react/24/outline"; +import { CheckIcon, PlayIcon } from "@heroicons/react/24/outline"; import { useState } from "react"; import styled from "styled-components"; import { vscEditorBackground } from ".."; import { isJetBrains, postToIde } from "../../util/ide"; import HeaderButtonWithText from "../HeaderButtonWithText"; +import { CopyButton } from "./CopyButton"; const TopDiv = styled.div` position: sticky; @@ -19,9 +16,9 @@ const TopDiv = styled.div` z-index: 100; `; -const SecondDiv = styled.div` +const SecondDiv = styled.div<{ bottom: boolean }>` position: absolute; - top: 4px; + ${(props) => (props.bottom ? "bottom: 1.2rem;" : "top: 4px;")} right: 4px; display: flex; gap: 4px; @@ -30,6 +27,7 @@ const SecondDiv = styled.div` interface CodeBlockToolBarProps { text: string; + bottom: boolean; } function CodeBlockToolBar(props: CodeBlockToolBarProps) { @@ -38,7 +36,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { return ( - + {isJetBrains() || ( )} - { - navigator.clipboard.writeText(props.text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }} - > - {copied ? ( - - ) : ( - - )} - + ); diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index d5c80e08c..2ce8d138a 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -71,9 +71,16 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { }, [props.item.content]); const codeBlockRef = React.useRef(null); + const codeBlockHeight = `${Math.min( + MAX_PREVIEW_HEIGHT, + codeBlockRef.current?.scrollHeight + ? codeBlockRef.current?.scrollHeight + : Number.MAX_SAFE_INTEGER + )}px`; return ( setHovered(true)} onMouseLeave={() => setHovered(false)} borderColor={props.borderColor} @@ -93,7 +100,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { new WebviewIde().showLines( props.item.description, parseInt(lines[0]) - 1, - parseInt(lines[1]) - 1, + parseInt(lines[1]) - 1 ); } else { postToIde("showVirtualFile", { @@ -141,18 +148,13 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { className="m-0" ref={codeBlockRef} style={{ - height: collapsed - ? `${Math.min( - MAX_PREVIEW_HEIGHT, - codeBlockRef.current?.scrollHeight, - )}px` - : undefined, + height: collapsed ? codeBlockHeight : undefined, overflow: collapsed ? "hidden" : "auto", }} > diff --git a/gui/src/components/markdown/CopyButton.tsx b/gui/src/components/markdown/CopyButton.tsx new file mode 100644 index 000000000..a284745d6 --- /dev/null +++ b/gui/src/components/markdown/CopyButton.tsx @@ -0,0 +1,34 @@ +import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline"; +import { useState } from "react"; +import { vscEditorBackground } from ".."; +import HeaderButtonWithText from "../HeaderButtonWithText"; + +interface CopyButtonProps { + text: string | (() => string); +} + +export function CopyButton(props: CopyButtonProps) { + const [copied, setCopied] = useState(false); + + return ( + <> + { + navigator.clipboard.writeText( + typeof props.text === "string" ? props.text : props.text(), + ); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }} + > + {copied ? ( + + ) : ( + + )} + + + ); +} diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index 19f5f8857..08be4c643 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -1,5 +1,6 @@ import { debounce } from "lodash"; import { useEffect, useState } from "react"; +import useUIConfig from "../../hooks/useUIConfig"; import CodeBlockToolBar from "./CodeBlockToolbar"; function childToText(child: any) { @@ -19,6 +20,9 @@ function childrenToText(children: any) { } function PreWithToolbar(props: { children: any }) { + const uiConfig = useUIConfig() + const toolbarBottom = uiConfig?.codeBlockToolbarPosition == 'bottom'; + const [hovering, setHovering] = useState(false); const [copyValue, setCopyValue] = useState(""); @@ -42,8 +46,9 @@ function PreWithToolbar(props: { children: any }) { onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)} > - {hovering && } + {!toolbarBottom && hovering && } {props.children} + {toolbarBottom && hovering && } ); } diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 75220b843..d1c793fe2 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -158,8 +158,8 @@ function ListBoxOption({ onConfirm={() => { postToIde("config/deleteModel", { title: option.title }); }} - /> - ) + />, + ), ); e.stopPropagation(); e.preventDefault(); @@ -195,7 +195,7 @@ function ModelSelect(props: {}) { const dispatch = useDispatch(); const defaultModel = useSelector(defaultModelSelector); const allModels = useSelector( - (state: RootState) => state.state.config.models + (state: RootState) => state.state.config.models, ); const navigate = useNavigate(); @@ -209,7 +209,7 @@ function ModelSelect(props: {}) { value: model.title, title: modelSelectTitle(model), }; - }) + }), ); }, [allModels]); @@ -220,7 +220,7 @@ function ModelSelect(props: {}) { if (event.key === "'" && isMetaEquivalentKeyPressed(event)) { const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === defaultModel?.title + (option) => option.value === defaultModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; @@ -274,12 +274,13 @@ function ModelSelect(props: {}) { showDelete={options.length > 1} /> ))} + {options.length === 0 && No models found} {getMetaKeyLabel()}' to toggle , - topDiv + topDiv, )} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 04e69af95..419e23b91 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,5 +1,5 @@ import { Dispatch } from "@reduxjs/toolkit"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { setVscMachineId } from "../redux/slices/configSlice"; @@ -14,15 +14,27 @@ import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; function useSetup(dispatch: Dispatch) { + const [configLoaded, setConfigLoaded] = useState(false); + const loadConfig = async () => { const config = await ideRequest("config/getBrowserSerialized", undefined); dispatch(setConfig(config)); + setConfigLoaded(true); }; // Load config from the IDE useEffect(() => { loadConfig(); - }, []); + const interval = setInterval(() => { + if (configLoaded) { + clearInterval(interval); + return; + } + loadConfig(); + }, 2_000); + + return () => clearInterval(interval); + }, [configLoaded]); useEffect(() => { // Override persisted state diff --git a/gui/src/hooks/useUIConfig.ts b/gui/src/hooks/useUIConfig.ts new file mode 100644 index 000000000..07cce9598 --- /dev/null +++ b/gui/src/hooks/useUIConfig.ts @@ -0,0 +1,8 @@ +import { useSelector } from 'react-redux'; +import { RootState } from '../redux/store'; + +function useUIConfig() { + return useSelector((store: RootState) => store.state.config.ui); +} + +export default useUIConfig; diff --git a/gui/src/main.tsx b/gui/src/main.tsx index f217f1dd8..f13e5fbbe 100644 --- a/gui/src/main.tsx +++ b/gui/src/main.tsx @@ -1,4 +1,3 @@ -import { loadWASM } from "onigasm"; import React from "react"; import ReactDOM from "react-dom/client"; import { Provider } from "react-redux"; @@ -9,12 +8,6 @@ import "./index.css"; import { persistor, store } from "./redux/store"; (async () => { - // "" lets it pass through to the correct path for JetBrains - const onigPath = (window.vscMediaUrl ?? "") + "/onigasm.wasm"; - const resp = await fetch(onigPath); - const onigWasm = await resp.arrayBuffer(); - await loadWASM(onigWasm); - ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( @@ -24,6 +17,6 @@ import { persistor, store } from "./redux/store"; - + , ); })(); diff --git a/gui/src/pages/stats.tsx b/gui/src/pages/stats.tsx index 7c9d8f09c..74942795f 100644 --- a/gui/src/pages/stats.tsx +++ b/gui/src/pages/stats.tsx @@ -2,7 +2,9 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; +import { table } from "table"; import { lightGray, vscBackground, vscInputBackground } from "../components"; +import { CopyButton } from "../components/markdown/CopyButton"; import { useNavigationListener } from "../hooks/useNavigationListener"; import { ideRequest } from "../util/ide"; @@ -27,6 +29,10 @@ const Td = styled.td` border: 1px solid ${vscInputBackground}; `; +function generateTable(data: unknown[][]) { + return table(data); +} + function Stats() { useNavigationListener(); const navigate = useNavigate(); @@ -65,7 +71,16 @@ function Stats() {

My Usage

-

Tokens per Day

+
+

Tokens per Day

+ [day.day, day.tokens]), + ), + )} + /> +
@@ -83,7 +98,16 @@ function Stats() {
-

Tokens per Model

+
+

Tokens per Model

+ [model.model, model.tokens]), + ), + )} + /> +
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index a51c85965..f151df3bc 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -97,18 +97,6 @@ const initialState: State = { contextItems: [], active: false, config: { - models: [ - { - title: "GPT-4 (Free Trial)", - model: "gpt-4", - provider: "free-trial", - }, - { - title: "GPT-3.5-Turbo (Free Trial)", - model: "gpt-3.5-turbo", - provider: "free-trial", - }, - ], slashCommands: [ { name: "edit", @@ -128,6 +116,38 @@ const initialState: State = { }, ], contextProviders: [], + models: [ + { + title: "GPT-4 Vision (Free Trial)", + provider: "free-trial", + model: "gpt-4-vision-preview", + }, + { + title: "GPT-3.5-Turbo (Free Trial)", + provider: "free-trial", + model: "gpt-3.5-turbo", + }, + { + title: "Gemini Pro (Free Trial)", + provider: "free-trial", + model: "gemini-pro", + }, + { + title: "Codellama 70b (Free Trial)", + provider: "free-trial", + model: "codellama-70b", + }, + { + title: "Mixtral (Free Trial)", + provider: "free-trial", + model: "mistral-8x7b", + }, + { + title: "Claude 3 Sonnet (Free Trial)", + provider: "free-trial", + model: "claude-3-sonnet-20240229", + }, + ], }, title: "New Session", sessionId: v4(), @@ -140,7 +160,7 @@ export const stateSlice = createSlice({ reducers: { setConfig: ( state, - { payload: config }: PayloadAction + { payload: config }: PayloadAction, ) => { const defaultModelTitle = config.models.find((model) => model.title === state.defaultModelTitle) @@ -168,7 +188,7 @@ export const stateSlice = createSlice({ }: PayloadAction<{ index: number; contextItems: ChatHistoryItem["contextItems"]; - }> + }>, ) => { if (state.history[index]) { state.history[index].contextItems = contextItems; @@ -178,7 +198,7 @@ export const stateSlice = createSlice({ state, { payload: { index, item }, - }: PayloadAction<{ index?: number; item: ContextItemWithId }> + }: PayloadAction<{ index?: number; item: ContextItemWithId }>, ) => { if (index === undefined) { const isFirstContextItem = @@ -201,7 +221,7 @@ export const stateSlice = createSlice({ }: PayloadAction<{ index: number; editorState: JSONContent; - }> + }>, ) => { const historyItem = state.history[payload.index]; if (!historyItem) { @@ -228,7 +248,7 @@ export const stateSlice = createSlice({ payload, }: PayloadAction<{ editorState: JSONContent; - }> + }>, ) => { state.history.push({ message: { role: "user", content: "" }, @@ -253,7 +273,7 @@ export const stateSlice = createSlice({ message: ChatMessage; index: number; contextItems?: ContextItemWithId[]; - }> + }>, ) => { if (payload.index >= state.history.length) { state.history.push({ @@ -281,7 +301,7 @@ export const stateSlice = createSlice({ }: PayloadAction<{ index: number; contextItems: ContextItemWithId[]; - }> + }>, ) => { const historyItem = state.history[payload.index]; if (!historyItem) { @@ -300,7 +320,7 @@ export const stateSlice = createSlice({ }, newSession: ( state, - { payload }: PayloadAction + { payload }: PayloadAction, ) => { if (payload) { state.history = payload.history; @@ -318,14 +338,14 @@ export const stateSlice = createSlice({ state, { payload, - }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }> + }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }>, ) => { const getKey = (id: ContextItemId) => `${id.providerTitle}-${id.itemId}`; const ids = new Set(payload.ids.map(getKey)); if (payload.index === undefined) { state.contextItems = state.contextItems.filter( - (item) => !ids.has(getKey(item.id)) + (item) => !ids.has(getKey(item.id)), ); } else { state.history[payload.index].contextItems = state.history[ @@ -337,7 +357,7 @@ export const stateSlice = createSlice({ state, { payload, - }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }> + }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>, ) => { let contextItems = [...state.contextItems].map((item) => { return { ...item, editing: false }; @@ -400,7 +420,7 @@ export const stateSlice = createSlice({ state, { payload, - }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }> + }: PayloadAction<{ ids: ContextItemId[]; index: number | undefined }>, ) => { const ids = payload.ids.map((id) => id.itemId); @@ -436,7 +456,7 @@ export const stateSlice = createSlice({ }, setDefaultModel: (state, { payload }: PayloadAction) => { const model = state.config.models.find( - (model) => model.title === payload + (model) => model.title === payload, ); if (!model) return; return { diff --git a/install-dependencies.ps1 b/install-dependencies.ps1 index 06bb760b7..708cc1d30 100644 --- a/install-dependencies.ps1 +++ b/install-dependencies.ps1 @@ -79,7 +79,7 @@ Pop-Location Write-Output "`nInstalling GUI extension dependencies..." -ForegroundColor White Push-Location gui npm install -npm link core +npm link @continuedev/core npm run build Pop-Location @@ -89,7 +89,7 @@ Push-Location extensions/vscode # This does way too many things inline but is the common denominator between many of the scripts npm install -npm link core +npm link @continuedev/core npm run package diff --git a/pkg/build.js b/pkg/build.js index 4e31ad4c6..414b17c42 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -7,7 +7,7 @@ const esbuildOutputFile = "out/index.js"; const platforms = ["darwin", "linux", "win32"]; const architectures = ["x64", "arm64"]; let targets = platforms.flatMap((platform) => - architectures.map((arch) => `${platform}-${arch}`) + architectures.map((arch) => `${platform}-${arch}`), ); let esbuildOnly = false; @@ -57,7 +57,7 @@ const targetToLanceDb = { } else { resolve(); } - } + }, ); ncp( `node_modules/${mod}`, @@ -69,10 +69,10 @@ const targetToLanceDb = { } else { resolve(); } - } + }, ); - }) - ) + }), + ), ); console.log(`[info] Copied ${DYNAMIC_IMPORTS.join(", ")}`); @@ -105,6 +105,12 @@ const targetToLanceDb = { define: { "import.meta.url": "importMetaUrl" }, }); + // Copy over any worker files + fs.cpSync( + "../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js", + "out/xhr-sync-worker.js", + ); + if (esbuildOnly) { return; } @@ -114,7 +120,7 @@ const targetToLanceDb = { const targetDir = `bin/${target}`; console.log(`[info] Building ${target}...`); execSync( - `./node_modules/.bin/pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}` + `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`, ); // Download and unzip prebuilt sqlite3 binary for the target @@ -125,7 +131,7 @@ const targetToLanceDb = { execSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); fs.copyFileSync( `${targetDir}/build/Release/node_sqlite3.node`, - `${targetDir}/node_sqlite3.node` + `${targetDir}/node_sqlite3.node`, ); fs.unlinkSync(`${targetDir}/build.tar.gz`); fs.rmSync(`${targetDir}/build`, { @@ -136,7 +142,7 @@ const targetToLanceDb = { // Download and unzip prebuilt esbuild binary for the target console.log(`[info] Downloading esbuild for ${target}...`); execSync( - `curl -o ${targetDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz` + `curl -o ${targetDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz`, ); execSync(`tar -xzvf ${targetDir}/esbuild.tgz -C ${targetDir}`); if (target.startsWith("win32")) { diff --git a/pkg/package-lock.json b/pkg/package-lock.json index 845e62db8..5ccdb9584 100644 --- a/pkg/package-lock.json +++ b/pkg/package-lock.json @@ -31,7 +31,8 @@ } }, "../core": { - "version": "1.0.0", + "name": "@continuedev/core", + "version": "1.0.4", "license": "Apache-2.0", "dependencies": { "@mozilla/readability": "^0.5.0", @@ -68,7 +69,7 @@ "sqlite3": "^5.1.7", "tree-sitter-wasms": "^0.1.6", "uuid": "^9.0.1", - "vectordb": "^0.4.3", + "vectordb": "^0.4.12", "web-tree-sitter": "^0.21.0" }, "devDependencies": { @@ -81,6 +82,9 @@ "esbuild": "^0.19.11", "jest": "^29.7.0", "ts-jest": "^29.1.1" + }, + "engines": { + "node": ">=20.11.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/pkg/src/core.ts b/pkg/src/core.ts index eba31a3be..0ee89ff18 100644 --- a/pkg/src/core.ts +++ b/pkg/src/core.ts @@ -8,6 +8,7 @@ import { CodebaseIndexer, PauseToken } from "core/indexing/indexCodebase"; import { logDevData } from "core/util/devdata"; import historyManager from "core/util/history"; import { Message } from "core/util/messenger"; +import { Telemetry } from "core/util/posthog"; import { v4 as uuidv4 } from "uuid"; import { IpcMessenger } from "./messenger"; import { Protocol } from "./protocol"; @@ -40,7 +41,7 @@ export class Core { this.ide, ideSettingsPromise, (text: string) => {}, - () => {}, + (() => this.messenger.send("configUpdate", undefined)).bind(this), ); this.codebaseIndexer = new CodebaseIndexer( this.configHandler, @@ -151,6 +152,11 @@ export class Core { ide, selectedCode: msg.data.selectedCode, }); + + Telemetry.capture("useContextProvider", { + name: provider.description.title, + }); + return items.map((item) => ({ ...item, id, @@ -243,6 +249,10 @@ export class Core { throw new Error(`Unknown slash command ${slashCommandName}`); } + Telemetry.capture("useSlashCommand", { + name: slashCommandName, + }); + for await (const content of slashCommand.run({ input, history,