diff --git a/.changes/extensions/vscode/0.8.58.md b/.changes/extensions/vscode/0.8.58.md new file mode 100644 index 000000000..98c845b97 --- /dev/null +++ b/.changes/extensions/vscode/0.8.58.md @@ -0,0 +1,25 @@ +## 0.8.58 - 2024-11-22 +### Added +* OpenAI predicted outputs support +* Improve codebase retrieval with BM25 +* Support for Grok from xAI +* Chat enhancements including sticking input to bottom +* New UI for cmd+I in sidebar +* Support for Nebius LLM provider +* Support for Ask Sage LLM provider +* Improved reference for config.json +* New @web context provider +* Updates for llama3.2 +* .continuerules file to set system prompt +* .prompt files v2 +* Dedicated UI for docs indexing +* Clickable code symbols in chat +* Use clipboard content as autocomplete context +### Changed +* Improved @docs crawler +* Many improvements to make autocomplete more eager +* Near complete type definition retrieval for TypeScript autocomplete +* Remove footer from chat sidebar +### Fixed +* Brought back the Apply button for all code blocks +* Automatically update codebase index on removed files diff --git a/.changes/extensions/vscode/0.8.59.md b/.changes/extensions/vscode/0.8.59.md new file mode 100644 index 000000000..9f6dfbd04 --- /dev/null +++ b/.changes/extensions/vscode/0.8.59.md @@ -0,0 +1,3 @@ +## 0.8.59 - 2024-11-25 +### Fixed +* Hotfix for Ollama onboarding diff --git a/.changes/unreleased/Added-20241108-113942.yaml b/.changes/unreleased/Added-20241108-113942.yaml deleted file mode 100644 index 987643345..000000000 --- a/.changes/unreleased/Added-20241108-113942.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: OpenAI predicted outputs support -time: 2024-11-08T11:39:42.277047-08:00 diff --git a/.changes/unreleased/Added-20241108-114100.yaml b/.changes/unreleased/Added-20241108-114100.yaml deleted file mode 100644 index af7cb5444..000000000 --- a/.changes/unreleased/Added-20241108-114100.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Improve codebase retrieval with BM25 -time: 2024-11-08T11:41:00.002716-08:00 diff --git a/.changes/unreleased/Added-20241108-114423.yaml b/.changes/unreleased/Added-20241108-114423.yaml deleted file mode 100644 index fc3a6eaf7..000000000 --- a/.changes/unreleased/Added-20241108-114423.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Support for Grok from xAI -time: 2024-11-08T11:44:23.761084-08:00 diff --git a/.changes/unreleased/Added-20241108-114437.yaml b/.changes/unreleased/Added-20241108-114437.yaml deleted file mode 100644 index fab18b954..000000000 --- a/.changes/unreleased/Added-20241108-114437.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Chat enhancements including sticking input to bottom -time: 2024-11-08T11:44:37.408176-08:00 diff --git a/.changes/unreleased/Added-20241108-114450.yaml b/.changes/unreleased/Added-20241108-114450.yaml deleted file mode 100644 index 14644f3e9..000000000 --- a/.changes/unreleased/Added-20241108-114450.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: New UI for cmd+I in sidebar -time: 2024-11-08T11:44:50.682952-08:00 diff --git a/.changes/unreleased/Added-20241108-114612.yaml b/.changes/unreleased/Added-20241108-114612.yaml deleted file mode 100644 index 68d8b27d1..000000000 --- a/.changes/unreleased/Added-20241108-114612.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Support for Nebius LLM provider -time: 2024-11-08T11:46:12.94828-08:00 diff --git a/.changes/unreleased/Added-20241108-114622.yaml b/.changes/unreleased/Added-20241108-114622.yaml deleted file mode 100644 index e91ddb398..000000000 --- a/.changes/unreleased/Added-20241108-114622.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Support for Ask Sage LLM provider -time: 2024-11-08T11:46:22.626907-08:00 diff --git a/.changes/unreleased/Added-20241108-114649.yaml b/.changes/unreleased/Added-20241108-114649.yaml deleted file mode 100644 index 0e7a0c9d0..000000000 --- a/.changes/unreleased/Added-20241108-114649.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Improved reference for config.json -time: 2024-11-08T11:46:49.648545-08:00 diff --git a/.changes/unreleased/Added-20241108-114753.yaml b/.changes/unreleased/Added-20241108-114753.yaml deleted file mode 100644 index 8cb7f1805..000000000 --- a/.changes/unreleased/Added-20241108-114753.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: New @web context provider -time: 2024-11-08T11:47:53.447346-08:00 diff --git a/.changes/unreleased/Added-20241108-114813.yaml b/.changes/unreleased/Added-20241108-114813.yaml deleted file mode 100644 index cd5ba1067..000000000 --- a/.changes/unreleased/Added-20241108-114813.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Updates for llama3.2 -time: 2024-11-08T11:48:13.830692-08:00 diff --git a/.changes/unreleased/Added-20241113-165958.yaml b/.changes/unreleased/Added-20241113-165958.yaml deleted file mode 100644 index 95aaa7c70..000000000 --- a/.changes/unreleased/Added-20241113-165958.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: .continuerules file to set system prompt -time: 2024-11-13T16:59:58.544875-08:00 diff --git a/.changes/unreleased/Added-20241113-170006.yaml b/.changes/unreleased/Added-20241113-170006.yaml deleted file mode 100644 index bc254f8d9..000000000 --- a/.changes/unreleased/Added-20241113-170006.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: .prompt files v2 -time: 2024-11-13T17:00:06.855468-08:00 diff --git a/.changes/unreleased/Changed-20241108-114549.yaml b/.changes/unreleased/Changed-20241108-114549.yaml deleted file mode 100644 index d340736b6..000000000 --- a/.changes/unreleased/Changed-20241108-114549.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Changed -body: Improved @docs crawler -time: 2024-11-08T11:45:49.381554-08:00 diff --git a/.changes/unreleased/Changed-20241108-114850.yaml b/.changes/unreleased/Changed-20241108-114850.yaml deleted file mode 100644 index ab6c2a037..000000000 --- a/.changes/unreleased/Changed-20241108-114850.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Changed -body: Many improvements to make autocomplete more eager -time: 2024-11-08T11:48:50.486502-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114905.yaml b/.changes/unreleased/Fixed-20241108-114905.yaml deleted file mode 100644 index eb590eeb4..000000000 --- a/.changes/unreleased/Fixed-20241108-114905.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Fixed -body: Brought back the Apply button for all code blocks -time: 2024-11-08T11:49:05.021499-08:00 diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml deleted file mode 100644 index 5f16c406c..000000000 --- a/.github/workflows/ts-check.yaml +++ /dev/null @@ -1,100 +0,0 @@ -name: TypeScript Check - -on: - pull_request: - branches: - - main - -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 root node_modules - uses: actions/cache@v3 - with: - path: node_modules - key: ${{ runner.os }}-node-${{ hashFiles('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 - 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 Root Dependencies - run: | - npm ci - - - 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: tsc core - run: | - cd core - npx tsc --noEmit - npm run lint - - - name: tsc extensions/vscode - run: | - cd extensions/vscode - npx tsc --noEmit - npm run lint - - - name: tsc binary - run: | - cd binary - npx tsc --noEmit - - - name: tsc gui - run: | - cd gui - npx tsc --noEmit diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100644 index d59df2ef6..000000000 --- a/.husky/pre-commit +++ /dev/null @@ -1 +0,0 @@ -npx prettier --write . \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b2cfbd9d9..bd395ffef 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -5,17 +5,16 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { aggregateSnippets } from "./aggregateSnippets"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; // @prettier-ignore -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { AutocompleteSnippet } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { getAllSnippets } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; +import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; @@ -32,14 +31,6 @@ const ERRORS_TO_IGNORE = [ "operation was aborted", ]; -export type GetLspDefinitionsFunction = ( - filepath: string, - contents: string, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - export class CompletionProvider { private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -171,28 +162,18 @@ export class CompletionProvider { token = controller.signal; } - ////////// - - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, - // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets(helper); - - const [snippets, diff, clipboardContent, workspaceDirs] = - await Promise.all([ - aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ), - this.ide.getDiff(true), - this.ide.getClipboardContent(), - this.ide.getWorkspaceDirs(), - ]); + const [snippetPayload, workspaceDirs] = await Promise.all([ + getAllSnippets({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); const { prompt, prefix, suffix, completionOptions } = renderPrompt({ - snippets, - diff, - clipboardContent, + snippetPayload, workspaceDirs, helper, }); @@ -288,32 +269,4 @@ export class CompletionProvider { this.loggingService.deleteAbortController(input.completionId); } } - - private async _getExtraSnippets( - helper: HelperVars, - ): Promise { - let extraSnippets = helper.options.useOtherFiles - ? ((await Promise.race([ - this.getDefinitionsFromLsp( - helper.input.filepath, - helper.fullPrefix + helper.fullSuffix, - helper.fullPrefix.length, - this.ide, - helper.lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) - : []; - - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (helper.options.onlyMyCode) { - extraSnippets = extraSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - return extraSnippets; - } } diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 9baf9cd4b..627ca1206 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -87,7 +87,6 @@ This is just another object like the ones in the `"models"` array of `config.jso This object allows you to customize the behavior of tab-autocomplete. The available options are: -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) - `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) - `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) - `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) @@ -107,7 +106,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "apiBase": "https://" }, "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5 } diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts deleted file mode 100644 index f47b9021f..000000000 --- a/core/autocomplete/aggregateSnippets.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { - fillPromptWithSnippets, - rankAndOrderSnippets, - type AutocompleteSnippet, -} from "./context/ranking/index.js"; -import { HelperVars } from "./util/HelperVars.js"; - -function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippet[], - caretWindow: string, -): AutocompleteSnippet[] { - return snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), - ); -} - -export async function aggregateSnippets( - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - contextRetrievalService: ContextRetrievalService, -): Promise { - let snippets = await contextRetrievalService.retrieveCandidateSnippets( - helper, - extraSnippets, - ); - - snippets = filterSnippetsAlreadyInCaretWindow( - snippets, - helper.prunedCaretWindow, - ); - - const scoredSnippets = rankAndOrderSnippets(snippets, helper); - - const finalSnippets = fillPromptWithSnippets( - scoredSnippets, - helper.maxSnippetTokens, - helper.modelName, - ); - - return finalSnippets; -} diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 24f6e9182..72e061fed 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,9 +1,12 @@ import { IDE } from "../.."; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; -import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { @@ -18,79 +21,14 @@ export class ContextRetrievalService { ); } - public async retrieveCandidateSnippets( + public async getSnippetsFromImportDefinitions( helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippet[] = []; - - // Snippets injected by the IDE for IDE-specific reasons - snippets.push(...extraSnippets); - - // If a recently edited range has a line that is a perfect match with the start of the current line - snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); - - // Import definitions of any symbols in near range of the caret - snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - - // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ - if (helper.options.useRootPathContext && helper.treePath) { - snippets.push( - ...(await this.rootPathContextService.getContextForPath( - helper.filepath, - helper.treePath, - )), - ); - } - - return snippets; - } - - private getSnippetsFromRecentlyEditedRanges( - helper: HelperVars, - ): AutocompleteSnippet[] { - if (helper.options.useRecentlyEdited === false) { - return []; - } - - const currentLinePrefix = helper.prunedPrefix - .trim() - .split("\n") - .slice(-1)[0]; - if ( - currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = this.findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - - if (matchingRange) { - return [ - { - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }, - ]; - } - } - - return []; - } - - private async getSnippetsFromImportDefinitions( - helper: HelperVars, - ): Promise { + ): Promise { if (helper.options.useImports === false) { return []; } - const importSnippets = []; + const importSnippets: AutocompleteCodeSnippet[] = []; const fileInfo = this.importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; @@ -104,21 +42,32 @@ export class ContextRetrievalService { for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { - importSnippets.push(...rifs); + const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => { + return { + filepath: rif.filepath, + content: rif.contents, + type: AutocompleteSnippetType.Code, + }; + }); + + importSnippets.push(...snippets); } } } + return importSnippets; } - findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, - ): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); + public async getRootPathSnippets( + helper: HelperVars, + ): Promise { + if (!helper.treePath) { + return []; + } + + return this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); } } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e68763746..1064fd243 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,11 +1,8 @@ -import { Range, RangeInFileWithContents } from "../../../"; +import { RangeInFileWithContents } from "../../../"; import { countTokens } from "../../../llm/countTokens"; +import { AutocompleteSnippetDeprecated } from "../../types"; import { HelperVars } from "../../util/HelperVars"; -export type AutocompleteSnippet = RangeInFileWithContents & { - score?: number; -}; - const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g; export function getSymbolsForSnippet(snippet: string): Set { const symbols = snippet @@ -18,7 +15,7 @@ export function getSymbolsForSnippet(snippet: string): Set { /** * Calculate similarity as number of shared symbols divided by total number of unique symbols between both. */ -export function jaccardSimilarity(a: string, b: string): number { +function jaccardSimilarity(a: string, b: string): number { const aSet = getSymbolsForSnippet(a); const bSet = getSymbolsForSnippet(b); const union = new Set([...aSet, ...bSet]).size; @@ -42,9 +39,9 @@ export function jaccardSimilarity(a: string, b: string): number { * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ export function rankAndOrderSnippets( - ranges: AutocompleteSnippet[], + ranges: AutocompleteSnippetDeprecated[], helper: HelperVars, -): Required[] { +): Required[] { const windowAroundCursor = helper.fullPrefix.slice( -helper.options.slidingWindowSize * @@ -55,11 +52,14 @@ export function rankAndOrderSnippets( (1 - helper.options.slidingWindowPrefixPercentage), ); - const snippets: Required[] = ranges.map((snippet) => ({ - score: - snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), - ...snippet, - })); + const snippets: Required[] = ranges.map( + (snippet) => ({ + score: + snippet.score ?? + jaccardSimilarity(snippet.contents, windowAroundCursor), + ...snippet, + }), + ); const uniqueSnippets = deduplicateSnippets(snippets); return uniqueSnippets.sort((a, b) => a.score - b.score); } @@ -67,11 +67,13 @@ export function rankAndOrderSnippets( /** * Deduplicate code snippets by merging overlapping ranges into a single range. */ -export function deduplicateSnippets( - snippets: Required[], -): Required[] { +function deduplicateSnippets( + snippets: Required[], +): Required[] { // Group by file - const fileGroups: { [key: string]: Required[] } = {}; + const fileGroups: { + [key: string]: Required[]; + } = {}; for (const snippet of snippets) { if (!fileGroups[snippet.filepath]) { fileGroups[snippet.filepath] = []; @@ -88,8 +90,8 @@ export function deduplicateSnippets( } function mergeSnippetsByRange( - snippets: Required[], -): Required[] { + snippets: Required[], +): Required[] { if (snippets.length <= 1) { return snippets; } @@ -97,7 +99,7 @@ function mergeSnippetsByRange( const sorted = snippets.sort( (a, b) => a.range.start.line - b.range.start.line, ); - const merged: Required[] = []; + const merged: Required[] = []; while (sorted.length > 0) { const next = sorted.shift()!; @@ -133,12 +135,12 @@ function mergeOverlappingRangeContents( * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( - snippets: Required[], + snippets: Required[], maxSnippetTokens: number, modelName: string, -): Required[] { +): Required[] { let tokensRemaining = maxSnippetTokens; - const keptSnippets: Required[] = []; + const keptSnippets: Required[] = []; for (let i = 0; i < snippets.length; i++) { const snippet = snippets[i]; const tokenCount = countTokens(snippet.contents, modelName); @@ -151,58 +153,3 @@ export function fillPromptWithSnippets( return keptSnippets; } - -/** - * Remove one range from another range, which may lead to returning two disjoint ranges - */ -function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { - if ( - orig.start.line >= remove.start.line && - orig.end.line <= remove.end.line - ) { - // / | | / - return []; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line >= remove.end.line - ) { - // | / / | - // Splits the range - return [ - { - start: orig.start, - end: remove.start, - }, - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line >= remove.start.line && - orig.end.line >= remove.end.line - ) { - // \ | / | - return [ - { - start: remove.end, - end: orig.end, - }, - ]; - } - if ( - orig.start.line <= remove.start.line && - orig.end.line <= remove.end.line - ) { - // | / | / - return [ - { - start: orig.start, - end: remove.start, - }, - ]; - } - return [orig]; -} diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts deleted file mode 100644 index 61c505c13..000000000 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { RangeInFileWithContents } from "../../../"; - -import { AutocompleteSnippet, jaccardSimilarity } from "./"; - -function* slidingWindow( - content: string, - windowSize: number, -): Generator { - const lines = content.split("\n"); - - let charCount = 0; - let currWindowLines: string[] = []; - for (let i = 0; i < lines.length; i++) { - if (charCount + lines[i].length >= windowSize) { - yield currWindowLines.join("\n"); - currWindowLines = [lines[i]]; - charCount = 0; - } else { - currWindowLines.push(lines[i]); - } - charCount += lines[i].length; - } - - if (currWindowLines.length > 0) { - yield currWindowLines.join("\n"); - } -} - -/** - * Match by similarity over sliding windows of recent documents. - * @param recentFiles - * @param prefix - * @param suffix - */ -export async function slidingWindowMatcher( - recentFiles: RangeInFileWithContents[], - windowAroundCursor: string, - topN: number, - windowSize: number, -): Promise { - // Sorted lowest similarity to highest - const topMatches: Required[] = []; - - for (const { filepath, contents, range } of recentFiles) { - for (const window of slidingWindow(contents, windowSize)) { - const score = jaccardSimilarity(window, windowAroundCursor); - - // Insertion sort - let i = -1; - while (++i < topMatches.length && score > topMatches[i].score) {} - topMatches.splice(i + 1, 0, { filepath, contents, score, range }); - if (topMatches.length > topN) { - topMatches.shift(); - } - } - } - - // TODO: convert the arbitrary window frame to some whole AST node? - return topMatches; -} diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 0147df151..a94e37e38 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -12,7 +12,11 @@ import { } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippet } from "../ranking"; +import { AutocompleteSnippetDeprecated } from "../../types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "../../snippets/types"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -30,7 +34,7 @@ function getSyntaxTreeString( } export class RootPathContextService { - private cache = new LRUCache({ + private cache = new LRUCache({ max: 100, }); @@ -72,8 +76,8 @@ export class RootPathContextService { private async getSnippetsForNode( filepath: string, node: Parser.SyntaxNode, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteSnippetDeprecated[] = []; const language = getFullLanguageName(filepath); let query: Parser.Query | undefined; @@ -123,7 +127,7 @@ export class RootPathContextService { filepath: string, endPosition: Parser.Point, language: LanguageName, - ): Promise { + ): Promise { const definitions = await this.ide.gotoDefinition({ filepath, position: { @@ -153,8 +157,8 @@ export class RootPathContextService { filepath: string, astPath: AstPath, // cursorIndex: number, - ): Promise { - const snippets: AutocompleteSnippet[] = []; + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; let parentKey = filepath; for (const astNode of astPath.filter((node) => @@ -167,7 +171,16 @@ export class RootPathContextService { const foundInCache = this.cache.get(key); const newSnippets = foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); - snippets.push(...newSnippets); + + const formattedSnippets: AutocompleteCodeSnippet[] = newSnippets.map( + (item) => ({ + filepath: item.filepath, + content: item.contents, + type: AutocompleteSnippetType.Code, + }), + ); + + snippets.push(...formattedSnippets); if (!foundInCache) { this.cache.set(key, newSnippets); diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 6097ff797..da178cb66 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -2,7 +2,7 @@ import { streamLines } from "../../../diff/util"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; import { HelperVars } from "../../util/HelperVars"; -import { stopAtStopTokens } from "./charStream"; +import { stopAtStartOf, stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, avoidPathLine, @@ -28,6 +28,7 @@ export class StreamTransformPipeline { let charGenerator = generator; charGenerator = stopAtStopTokens(generator, stopTokens); + charGenerator = stopAtStartOf(charGenerator, suffix); for (const charFilter of helper.lang.charFilters ?? []) { charGenerator = charFilter({ chars: charGenerator, diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index b466ae3cd..d82d9dbac 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -1,12 +1,20 @@ -import { stopAtStopTokens } from "./charStream"; +import { stopAtStartOf, stopAtStopTokens } from "./charStream"; + +async function* createMockStream(chunks: string[]): AsyncGenerator { + for (const chunk of chunks) { + yield chunk; + } +} + +async function streamToString(stream: AsyncGenerator): Promise { + let result = ""; + for await (const chunk of stream) { + result += chunk; + } + return result; +} describe("stopAtStopTokens", () => { - async function* createMockStream(chunks: string[]): AsyncGenerator { - for (const chunk of chunks) { - yield chunk; - } - } - it("should yield characters until a stop token is encountered", async () => { const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]); const stopTokens = ["Stop"]; @@ -30,12 +38,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["END", "STOP", "HALT"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("This is a test. "); + expect(await streamToString(result)).toBe("This is a test. "); }); it("should handle stop tokens split across chunks", async () => { @@ -67,12 +70,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["END"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("This is a complete stream"); + expect(await streamToString(result)).toBe("This is a complete stream"); }); it("should handle empty chunks", async () => { @@ -80,12 +78,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["STOP"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("Hello world! "); + expect(await streamToString(result)).toBe("Hello world! "); }); it("should handle stop token at the beginning of the stream", async () => { @@ -106,12 +99,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["STOP"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("Hello world"); + expect(await streamToString(result)).toBe("Hello world"); }); it("should handle multiple stop tokens of different lengths", async () => { @@ -124,12 +112,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["STOP", "END", "HALT"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("This is a test with multiple "); + expect(await streamToString(result)).toBe("This is a test with multiple "); }); it("should handle an empty stream", async () => { @@ -137,12 +120,7 @@ describe("stopAtStopTokens", () => { const stopTokens = ["STOP"]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe(""); + expect(await streamToString(result)).toBe(""); }); it("should handle an empty stop tokens array", async () => { @@ -166,11 +144,73 @@ describe("stopAtStopTokens", () => { ]; const result = stopAtStopTokens(mockStream, stopTokens); - const output = []; - for await (const char of result) { - output.push(char); - } - - expect(output.join("")).toBe("Hello world!"); + expect(await streamToString(result)).toBe("Hello world!"); + }); +}); + +describe("stopAtStartOf", () => { + const sampleCode = ` { + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: \`Bearer \${this.workOsAccessToken}\`, + }, + }, + ); + const data = await response.json(); + return data.items; + } + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const response = await extras.fetch( + new URL( + \`/proxy/context/\${this.options.id}/retrieve\`, + controlPlaneEnv.CONTROL_PLANE_URL, + ), +`; + /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input +and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ + it("should stop if the start of the suffix is reached", async () => { + const removeLength = 10; + for (let i = 0; i < sampleCode.length - removeLength - 20; i++) { + const removed = sampleCode.slice(i, i + removeLength); + const suffix = sampleCode.slice(i + removeLength); + const response = removed + suffix; + + // split the response but keep spaces + const mockStream = createMockStream(response.split(/(?! )/g)); + const result = stopAtStartOf(mockStream, suffix); + + const resultStr = await streamToString(result); + if (resultStr !== removed) { + throw new Error( + `i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`, + ); + } + } + }); + it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { + const removeLength = 10; + for (let i = 0; i < sampleCode.length - removeLength - 20; i++) { + const removed = sampleCode.slice(i, i + removeLength); + let suffix = sampleCode.slice(i + removeLength); + const response = removed + suffix; + // add a prefix to the suffix + suffix = "strange words;\n which start the suffix#" + suffix; + + // split the response but keep spaces + const mockStream = createMockStream(response.split(/(?! )/g)); + const result = stopAtStartOf(mockStream, suffix); + + const resultStr = await streamToString(result); + if (resultStr !== removed) { + throw new Error( + `i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`, + ); + } + } }); }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts index 9f37e1f58..f4b751ff9 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.ts @@ -117,3 +117,57 @@ export async function* stopAtStopTokens( yield char; } } + +/** + * Asynchronously yields characters from the input stream, stopping if a sequence contained in the beginning of the suffix is encountered. + * */ +export async function* stopAtStartOf( + stream: AsyncGenerator, + suffix: string, + sequenceLength: number = 20, +): AsyncGenerator { + if (suffix.length < sequenceLength) { + for await (const chunk of stream) { + yield chunk; + } + return; + } + + const n = Math.min(suffix.length, 3 * sequenceLength); + let prev = new Array(n + 1).fill(0); + let res = 0; + let buffer = ""; + + for await (const chunk of stream) { + const s1 = chunk; + const m = chunk.length; + for (let i = 1; i <= m; i++) { + // Create a temporary array to store the current row + let curr = new Array(n + 1).fill(0); + for (let j = 1; j <= n; j++) { + if (s1[i - 1] === suffix[j - 1]) { + curr[j] = prev[j - 1] + 1; + res = Math.max(res, curr[j]); + } else { + curr[j] = 0; + } + } + + // Move the current row's data to the previous row + prev = curr; + + if (res > sequenceLength) { + return; + } + + buffer += s1[i - 1]; + + while (buffer.length > sequenceLength) { + yield buffer[0]; + buffer = buffer.slice(1); + } + } + } + + yield buffer; +} diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index 0a99a5a91..5cb05d2c3 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -98,7 +98,7 @@ describe("lineStream", () => { describe("stopAtSimilarLine", () => { it("should stop at the exact same line", async () => { - const lineToTest = "const x = 6;"; + const lineToTest = "const x = 6"; const linesGenerator = await getLineGenerator([ "console.log();", "const y = () => {};", @@ -116,7 +116,7 @@ describe("lineStream", () => { expect(mockFullStop).toHaveBeenCalledTimes(1); }); - it.only("should stop at a similar line", async () => { + it("should stop at a similar line", async () => { const lineToTest = "const x = 6;"; const linesGenerator = await getLineGenerator([ "console.log();", diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index c204783ad..9cbf190ec 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -83,7 +83,7 @@ export const LINES_TO_REMOVE_BEFORE_START = [ "", "[CODE]", "", - "{{FILL_HERE}}" + "{{FILL_HERE}}", ]; export const ENGLISH_START_PHRASES = [ diff --git a/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts deleted file mode 100644 index a25b5d4bf..000000000 --- a/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { noDoubleNewlineAfterClosingBracket } from "./lineStream"; - -describe("noDoubleNewlineAfterClosingBracket", () => { - // Helper function to convert an array to an async generator - async function* arrayToAsyncGenerator(array: T[]): AsyncGenerator { - for (const item of array) { - yield item; - } - } - - // Helper function to collect lines from the async generator - async function collectLines(lines: AsyncIterable): Promise { - const result: string[] = []; - for await (const line of lines) { - result.push(line); - } - return result; - } - - test("should yield all lines when no double newline and no unmatched brackets", async () => { - const inputLines = [ - "function test() {", - ' console.log("Hello World");', - "}", - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); - - test("should yield all lines when double newline but brackets are matched", async () => { - const inputLines = [ - "function test() {", - ' console.log("Hello World");', - "}", - "", - "", - "// End of function", - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); - - test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => { - const inputLines = [ - // "function test() {", - ' console.log("Hello World");', - // Unmatched closing bracket - "}", - "", - "", - "// This should not be yielded", - 'console.log("End");', - ]; - const expectedOutputLines = [' console.log("Hello World");', "}"]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(expectedOutputLines); - }); - - test("should yield all lines when unmatched brackets but no double newline", async () => { - const inputLines = [ - "function test() {", - ' console.log("Hello World");', - "}", - // Unmatched closing bracket - ")", - "// Continue code", - 'console.log("End");', - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); - - test("should continue yielding if unmatched closing bracket occurs after double newline", async () => { - const inputLines = [ - "function test() {", - ' console.log("Hello World");', - "}", - "", - "", - // Unmatched closing bracket after double newline - ")", - 'console.log("End");', - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); - - test("should yield all lines when brackets are matched even with double newline", async () => { - const inputLines = [ - "const arr = [", - " 1, 2, 3,", - "];", - "", - "", - "console.log(arr);", - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); - - test("should stop yielding when unmatched closing bracket occurs before double newline", async () => { - const inputLines = [ - "if (condition) {", - " doSomething();", - "}", - // Unmatched closing bracket - "}", - "", - "", - "doSomethingElse();", - ]; - const expectedOutputLines = [ - "if (condition) {", - " doSomething();", - "}", - "}", - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(expectedOutputLines); - }); - - test("should yield all lines when no unmatched closing brackets and double newline", async () => { - const inputLines = [ - "while (true) {", - " // Infinite loop", - "}", - "", - "", - "// Loop exited", - ]; - const lines = arrayToAsyncGenerator(inputLines); - const outputLines = await collectLines( - noDoubleNewlineAfterClosingBracket(lines), - ); - - expect(outputLines).toEqual(inputLines); - }); -}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index f0584ab48..33924b1b3 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -153,23 +153,35 @@ public class Calculator { POSTGRES_DB: mydb `, }, - // TODO - // { - // description: "Should autocomplete a Markdown list with nested items", - // filename: "test.md", - // input: ` - // - Item 1 - // - Item 2 - // - Subitem 1 - // <|fim|> - // - Item 3 - // `, - // llmOutput: ` - Subitem 2 - // - Subitem 3 - // `, - // expectedCompletion: ` - Subitem 2 - // - Subitem 3`, - // }, + { + description: + "Should filter out suffix generated by LLM (sample from Codestral)", + filename: "test.js", + input: ` + add(number) { + this.result += number; + return this; + } + // Add the subtract method + subtract(number) {<|fim|> + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + }`, + llmOutput: ` this.result -= number; + return this; + } + // Add the multiply method + multiply(number) { + `, + expectedCompletion: undefined, + }, { description: "Should enforce bracket matching in JSON files", filename: "test.json", @@ -181,7 +193,7 @@ public class Calculator { "state": "California", "city": "San BERNARDINO", "coordinates": { - + <|fim|> } }, "employees": [ @@ -230,8 +242,96 @@ public class Calculator { "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], "optional": ["Photoshop", "Illustrator"]`, expectedCompletion: `"latitude": 34.10834, - "longitude": -117.28977 + "longitude": -117.28977`, + }, + { + description: + "Should return nothing when output is duplicated lines in TypeScript", + filename: "file.ts", + input: ` +async getContextForPath( + filepath: string, + astPath: AstPatt, + language: LanguageName, + options: ContextOptions = {}, +<|fim|> + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; + let parentKey = filepath; +`, + llmOutput: ` ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; `, + expectedCompletion: undefined, + }, + { + description: + "Should return partial result when output is duplicated lines in TypeScript", + filename: "file.ts", + input: ` +async getContextForPath( + filepath: string, + astPath: AstPatt, + language: LanguageName, + options: ContextOptions = {}, +<|fim|> + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; + let parentKey = filepath; +`, + llmOutput: `console.log('TEST'); + ): Promise { + const snippets: AutocompleteCodeSnippet[] = []; + `, + expectedCompletion: `console.log('TEST'); + `, + }, + { + description: "Should autocomplete React effect hook", + input: `import React, { useState, useEffect } from "react"; + +export const Timer = () => { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(seconds + 1); + }, 1000); + + <|fim|>; + + return () => clearInterval(interval); + }, [seconds]); + + return ( +
+

{seconds} seconds have passed.

+
+ ); +};`, + llmOutput: "return () => clearInterval(interval);", + expectedCompletion: undefined, + filename: "Timer.tsx", + }, + { + description: "Should autocomplete simple return statement in TypeScript", + filename: "file.ts", + input: ` + multiply(number) { + this.result *= number; + return <|fim|> + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } +`, + llmOutput: ` this;`, + expectedCompletion: `this;`, }, ]; @@ -530,35 +630,6 @@ export const Counter = () => { expectedCompletion: "0", filename: "Counter.tsx", }, - - { - description: "Should autocomplete React effect hook", - input: `import React, { useState, useEffect } from "react"; - -export const Timer = () => { - const [seconds, setSeconds] = useState(0); - - useEffect(() => { - const interval = setInterval(() => { - setSeconds(seconds + 1); - }, 1000); - - <|fim|>; - - return () => clearInterval(interval); - }, [seconds]); - - return ( -
-

{seconds} seconds have passed.

-
- ); -};`, - llmOutput: "return () => clearInterval(interval);", - expectedCompletion: "return () => clearInterval(interval);", - filename: "Timer.tsx", - }, - { description: "Should autocomplete React component methods", input: `import React from "react"; @@ -746,7 +817,7 @@ func main() { CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), - price DECIMAL(8,2) NOT NULL '0.00', + price DECIMAL(8,2) NOT NULL<|fim|> '0.00', quantity INT NOT NULL DEFAULT '0' ); @@ -1565,7 +1636,19 @@ interface User { age: number; }`, }, + { + description: "Should autocomplete TypeScript interface declarations", + filename: "autocomplete.ts", + input: `interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {} +interface AutocompleteCodeSnippet`, + llmOutput: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + expectedCompletion: ` extends BaseAutocompleteSnippet { + filepath: string; +}`, + }, { description: "Should autocomplete a TypeScript arrow function inside a variable assignment", diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 42ab196b7..8adaa101a 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -18,7 +18,7 @@ export interface AutocompleteFileringTestInput { filename: string; input: string; llmOutput: string; - expectedCompletion: string | null; + expectedCompletion: string | null | undefined; options?: { only?: boolean; }; @@ -54,7 +54,6 @@ export async function testAutocompleteFiltering( const line = prefix.split("\n").length - 1; const character = prefix.split("\n")[line].length; const autocompleteInput: AutocompleteInput = { - clipboardText: "", completionId: "test-completion-id", filepath, pos: { diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index 3d97df9ca..1eb3b37da 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -120,10 +120,5 @@ export function postprocessCompletion({ completion = completion.slice(1); } - // Qwen often adds an extra space to the start - if (llm.model.toLowerCase().includes("qwen") && completion.startsWith(" ")) { - completion = completion.slice(1); - } - return completion; } diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts new file mode 100644 index 000000000..274ff5657 --- /dev/null +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -0,0 +1,136 @@ +import { IDE } from "../../index"; +import { ContextRetrievalService } from "../context/ContextRetrievalService"; +import { GetLspDefinitionsFunction } from "../types"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippetType, +} from "./types"; + +export interface SnippetPayload { + rootPathSnippets: AutocompleteCodeSnippet[]; + importDefinitionSnippets: AutocompleteCodeSnippet[]; + ideSnippets: AutocompleteCodeSnippet[]; + recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + diffSnippets: AutocompleteDiffSnippet[]; + clipboardSnippets: AutocompleteClipboardSnippet[]; +} + +function racePromise(promise: Promise): Promise { + const timeoutPromise = new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }); + + return Promise.race([promise, timeoutPromise]); +} + +// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, +// or they might separately track recently edited ranges) +async function getIdeSnippets( + helper: HelperVars, + ide: IDE, + getDefinitionsFromLsp: GetLspDefinitionsFunction, +): Promise { + const ideSnippets = await getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + ide, + helper.lang, + ); + + if (helper.options.onlyMyCode) { + const workspaceDirs = await ide.getWorkspaceDirs(); + + return ideSnippets.filter((snippet) => + workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)), + ); + } + + return ideSnippets; +} + +function getSnippetsFromRecentlyEditedRanges( + helper: HelperVars, +): AutocompleteCodeSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + return helper.input.recentlyEditedRanges.map((range) => { + return { + filepath: range.filepath, + content: range.lines.join("\n"), + type: AutocompleteSnippetType.Code, + }; + }); +} + +const getClipboardSnippets = async ( + ide: IDE, +): Promise => { + const content = await ide.getClipboardContent(); + + return [content].map((item) => { + return { + content: item.text, + copiedAt: item.copiedAt, + type: AutocompleteSnippetType.Clipboard, + }; + }); +}; + +const getDiffSnippets = async ( + ide: IDE, +): Promise => { + const diff = await ide.getDiff(true); + + return [diff].map((item) => { + return { + content: item, + type: AutocompleteSnippetType.Diff, + }; + }); +}; + +export const getAllSnippets = async ({ + helper, + ide, + getDefinitionsFromLsp, + contextRetrievalService, +}: { + helper: HelperVars; + ide: IDE; + getDefinitionsFromLsp: GetLspDefinitionsFunction; + contextRetrievalService: ContextRetrievalService; +}): Promise => { + const recentlyEditedRangeSnippets = + getSnippetsFromRecentlyEditedRanges(helper); + + const [ + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + diffSnippets, + clipboardSnippets, + ] = await Promise.all([ + racePromise(contextRetrievalService.getRootPathSnippets(helper)), + racePromise( + contextRetrievalService.getSnippetsFromImportDefinitions(helper), + ), + racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)), + racePromise(getDiffSnippets(ide)), + racePromise(getClipboardSnippets(ide)), + ]); + + return { + rootPathSnippets, + importDefinitionSnippets, + ideSnippets, + recentlyEditedRangeSnippets, + diffSnippets, + clipboardSnippets, + }; +}; diff --git a/core/autocomplete/snippets/index.ts b/core/autocomplete/snippets/index.ts new file mode 100644 index 000000000..2a9e1a7ce --- /dev/null +++ b/core/autocomplete/snippets/index.ts @@ -0,0 +1 @@ +export * from "./getAllSnippets"; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts new file mode 100644 index 000000000..e43b59862 --- /dev/null +++ b/core/autocomplete/snippets/types.ts @@ -0,0 +1,29 @@ +export enum AutocompleteSnippetType { + Code = "code", + Diff = "diff", + Clipboard = "clipboard", +} + +interface BaseAutocompleteSnippet { + content: string; + type: AutocompleteSnippetType; +} + +export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet { + filepath: string; + type: AutocompleteSnippetType.Code; +} + +export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Diff; +} + +export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Clipboard; + copiedAt: string; +} + +export type AutocompleteSnippet = + | AutocompleteCodeSnippet + | AutocompleteDiffSnippet + | AutocompleteClipboardSnippet; diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index c64eca26a..6a3464875 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -2,7 +2,11 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; -import { AutocompleteSnippet } from "../context/ranking/index.js"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types.js"; export interface AutocompleteTemplate { compilePrefixSuffix?: ( @@ -73,8 +77,12 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix: string, filepath: string, reponame: string, - snippets: AutocompleteSnippet[], + allSnippets: AutocompleteSnippet[], ): [string, string] => { + const snippets = allSnippets.filter( + (snippet) => snippet.type === AutocompleteSnippetType.Code, + ) as AutocompleteCodeSnippet[]; + if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix]; @@ -86,7 +94,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { filepath, ]); const otherFiles = snippets - .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) + .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.content}`) .join("\n\n"); return [ `${otherFiles}\n\n+++++ ${ @@ -95,14 +103,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { suffix, ]; }, - template: ( - prefix: string, - suffix: string, - filepath: string, - reponame: string, - language: string, - snippets: AutocompleteSnippet[], - ): string => { + template: (prefix: string, suffix: string): string => { return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, completionOptions: { @@ -140,8 +141,7 @@ const starcoder2FimTemplate: AutocompleteTemplate = { ? "" : `${snippets .map((snippet) => { - return snippet.contents; - // return `${getBasename(snippet.filepath)}\n${snippet.contents}`; + return snippet.content; }) .join("")}`; @@ -187,8 +187,12 @@ const codegeexFimTemplate: AutocompleteTemplate = { filepath: string, reponame: string, language: string, - snippets: AutocompleteSnippet[], + allSnippets: AutocompleteSnippet[], ): string => { + const snippets = allSnippets.filter( + (snippet) => snippet.type === AutocompleteSnippetType.Code, + ) as AutocompleteCodeSnippet[]; + const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), filepath, @@ -200,7 +204,7 @@ const codegeexFimTemplate: AutocompleteTemplate = { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets - .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`) + .map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.content}\n`) .join("###REFERENCE:\n")}`; const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`; return prompt; @@ -227,14 +231,7 @@ Fill in the blank to complete the code block. Your response should include only }; const holeFillerTemplate: AutocompleteTemplate = { - template: ( - prefix: string, - suffix: string, - filename: string, - reponame: string, - language: string, - snippets: AutocompleteSnippet[], - ) => { + template: (prefix: string, suffix: string) => { // From https://github.com/VictorTaelin/AI-scripts const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct. diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts new file mode 100644 index 000000000..bc85fb909 --- /dev/null +++ b/core/autocomplete/templating/filtering.ts @@ -0,0 +1,75 @@ +import { countTokens } from "../../llm/countTokens"; +import { SnippetPayload } from "../snippets"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippet, +} from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; +import { isValidSnippet } from "./validation"; + +const getRemainingTokenCount = (helper: HelperVars): number => { + const tokenCount = countTokens(helper.prunedCaretWindow, helper.modelName); + + return helper.options.maxPromptTokens - tokenCount; +}; + +const TOKEN_BUFFER = 10; // We may need extra tokens for snippet description etc. + +/** + * Shuffles an array in place using the Fisher-Yates algorithm. + * @param array The array to shuffle. + * @returns The shuffled array. + */ +const shuffleArray = (array: T[]): T[] => { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; +}; + +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteCodeSnippet[], + caretWindow: string, +): AutocompleteCodeSnippet[] { + return snippets.filter( + (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()), + ); +} + +export const getSnippets = ( + helper: HelperVars, + payload: SnippetPayload, +): AutocompleteSnippet[] => { + const snippets = [ + ...payload.diffSnippets, + ...payload.clipboardSnippets, + ...shuffleArray( + filterSnippetsAlreadyInCaretWindow( + [...payload.rootPathSnippets], + helper.prunedCaretWindow, + ), + ), + ]; + + const finalSnippets = []; + + let remainingTokenCount = getRemainingTokenCount(helper); + + while (remainingTokenCount > 0 && snippets.length > 0) { + const snippet = snippets.shift(); + if (!snippet || !isValidSnippet(snippet)) { + continue; + } + + const snippetSize = + countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER; + + if (remainingTokenCount >= snippetSize) { + finalSnippets.push(snippet); + remainingTokenCount -= snippetSize; + } + } + + return finalSnippets; +}; diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts new file mode 100644 index 000000000..6554de26d --- /dev/null +++ b/core/autocomplete/templating/formatting.ts @@ -0,0 +1,107 @@ +import { getLastNPathParts } from "../../util"; +import { + AutocompleteClipboardSnippet, + AutocompleteCodeSnippet, + AutocompleteDiffSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; +import { HelperVars } from "../util/HelperVars"; + +const getCommentMark = (helper: HelperVars) => { + return helper.lang.singleLineComment; +}; + +const addCommentMarks = (text: string, helper: HelperVars) => { + const lines = [ + ...text + .trim() + .split("\n") + .map((line) => `${getCommentMark(helper)} ${line}`), + ]; + return lines.join("\n"); +}; + +const formatClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): AutocompleteCodeSnippet => { + return formatCodeSnippet({ + filepath: "Untitled.txt", + content: snippet.content, + type: AutocompleteSnippetType.Code, + }); +}; + +const formatCodeSnippet = ( + snippet: AutocompleteCodeSnippet, +): AutocompleteCodeSnippet => { + return { + ...snippet, + content: `Path: ${getLastNPathParts(snippet.filepath, 2)}\n${snippet.content}`, + }; +}; + +const formatDiffSnippet = ( + snippet: AutocompleteDiffSnippet, +): AutocompleteDiffSnippet => { + return snippet; +}; + +const getCurrentFilepath = (helper: HelperVars) => { + return getLastNPathParts(helper.filepath, 2); +}; + +const commentifySnippet = ( + helper: HelperVars, + snippet: AutocompleteSnippet, +): AutocompleteSnippet => { + return { + ...snippet, + content: addCommentMarks(snippet.content, helper), + }; +}; + +const SNIPPET_TYPES_TO_COMMENT = [ + AutocompleteSnippetType.Code, + AutocompleteSnippetType.Clipboard, +]; + +export const formatSnippets = ( + helper: HelperVars, + snippets: AutocompleteSnippet[], +): string => { + const currentFilepathComment = addCommentMarks( + getCurrentFilepath(helper), + helper, + ); + + return ( + snippets + .map((snippet) => { + switch (snippet.type) { + case AutocompleteSnippetType.Code: + return formatCodeSnippet(snippet); + case AutocompleteSnippetType.Diff: + return formatDiffSnippet(snippet); + case AutocompleteSnippetType.Clipboard: + return formatClipboardSnippet(snippet); + } + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + return commentifySnippet(helper, item); + } + + return item; + }) + .map((item) => { + if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { + const commentMark = getCommentMark(helper); + return item.content + `\n${commentMark}\n${commentMark}`; + } + + return item.content + "\n\n"; + }) + .join("\n") + `\n${currentFilepathComment}` + ); +}; diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 6f95923d1..8a2cfaae4 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,8 @@ import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; -import { getBasename, getLastNPathParts } from "../../util"; +import { getBasename } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; import { @@ -11,51 +10,10 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; -import { countTokens } from "../../llm/countTokens"; - -const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => { - const comment = language.singleLineComment; - const lines = [ - ...text - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - ]; - return lines.join("\n"); -}; - -export function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const filePathString = `Path: ${getBasename(filepath)}\n`; - return addCommentMarks(`${filePathString}${snippet}`, language); -} - -function getContextComments( - snippets: AutocompleteSnippet[], - lang: AutocompleteLanguageInfo, - filepath: string, -) { - if (snippets.length === 0) { - return ""; - } - - const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`; - const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - - const formattedSnippets = - headerSnipper + - snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n") + - fileNameSnippet; - - return formattedSnippets; -} +import { AutocompleteCodeSnippet } from "../snippets/types"; +import { SnippetPayload } from "../snippets"; +import { formatSnippets } from "./formatting"; +import { getSnippets } from "./filtering"; function getTemplate(helper: HelperVars): AutocompleteTemplate { if (helper.options.template) { @@ -88,63 +46,14 @@ function renderStringTemplate( }); } -const formatDiff = (helper: HelperVars, diff?: string) => { - if (!diff) return ""; - - const tokenCount = countTokens(diff, helper.modelName); - - if (tokenCount > helper.maxDiffTokens) { - return ""; - } - - return `${diff}\n\n`; -}; - -const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; - -const formatClipboardContent = ( - helper: HelperVars, - { text, copiedAt }: { text: string; copiedAt: string }, -) => { - const currDate = new Date(); - - const isTooOld = - currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE; - - if (isTooOld) { - return ""; - } - - const tokenCount = countTokens(text, helper.modelName); - const isTooLong = tokenCount > helper.maxClipboardTokens; - - if (isTooLong) { - return ""; - } - - return ( - addCommentMarks( - `Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`, - helper.lang, - ) + "\n" - ); -}; - export function renderPrompt({ - snippets, + snippetPayload, workspaceDirs, helper, - diff, - clipboardContent, }: { - snippets: AutocompleteSnippet[]; + snippetPayload: SnippetPayload; workspaceDirs: string[]; helper: HelperVars; - diff?: string; - clipboardContent: { - text: string; - copiedAt: string; - }; }): { prompt: string; prefix: string; @@ -160,6 +69,8 @@ export function renderPrompt({ const { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); + const snippets = getSnippets(helper, snippetPayload); + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint if (compilePrefixSuffix) { @@ -171,17 +82,8 @@ export function renderPrompt({ snippets, ); } else { - const contextComments = getContextComments( - snippets, - helper.lang, - helper.filepath, - ); - const formattedDiff = formatDiff(helper, diff); - const formattedClipboard = formatClipboardContent(helper, clipboardContent); - - prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join( - "", - ); + const formattedSnippets = formatSnippets(helper, snippets); + prefix = [formattedSnippets, prefix].join("\n"); } const prompt = diff --git a/core/autocomplete/templating/validation.ts b/core/autocomplete/templating/validation.ts new file mode 100644 index 000000000..dad55dc5c --- /dev/null +++ b/core/autocomplete/templating/validation.ts @@ -0,0 +1,29 @@ +import { + AutocompleteClipboardSnippet, + AutocompleteSnippet, + AutocompleteSnippetType, +} from "../snippets/types"; + +const MAX_CLIPBOARD_AGE = 5 * 60 * 1000; + +const isValidClipboardSnippet = ( + snippet: AutocompleteClipboardSnippet, +): boolean => { + const currDate = new Date(); + + const isTooOld = + currDate.getTime() - new Date(snippet.copiedAt).getTime() > + MAX_CLIPBOARD_AGE; + + return !isTooOld; +}; + +export const isValidSnippet = (snippet: AutocompleteSnippet): boolean => { + if (snippet.content.trim() === "") return false; + + if (snippet.type === AutocompleteSnippetType.Clipboard) { + return isValidClipboardSnippet(snippet); + } + + return true; +}; diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..23f762556 --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,20 @@ +import { IDE, RangeInFileWithContents } from "../index"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { AutocompleteCodeSnippet } from "./snippets/types"; + +/** + * @deprecated This type should be removed in the future or renamed. + * We have a new interface called AutocompleteSnippet which is more + * general. + */ +export type AutocompleteSnippetDeprecated = RangeInFileWithContents & { + score?: number; +}; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 96261e646..35e0ead64 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -112,7 +112,6 @@ export class AutocompleteLoggingService { multilineCompletions: restOfOutcome.multilineCompletions, time: restOfOutcome.time, useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, }, true, ); diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index c5429fe81..047038493 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -114,17 +114,6 @@ export class HelperVars { get pos() { return this.input.pos; } - get maxSnippetTokens() { - return this.options.maxPromptTokens * this.options.maxSnippetPercentage; - } - - get maxDiffTokens() { - return this.options.maxPromptTokens * this.options.maxDiffPercentage; - } - - get maxClipboardTokens() { - return this.options.maxPromptTokens * this.options.maxClipboardPercentage; - } get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 8d531d026..d54d57bd2 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -18,7 +18,6 @@ export interface AutocompleteInput { pos: Position; recentlyEditedFiles: RangeInFileWithContents[]; recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; // Used for notebook files manuallyPassFileContents?: string; // Used for VS Code git commit input box diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 85116f213..8d44c8bac 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,5 +1,3 @@ -import { config } from "dotenv"; - import { BrowserSerializedContinueConfig, ContinueConfig, diff --git a/core/config/load.ts b/core/config/load.ts index 3aa9ffc8d..e12eb500d 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -528,6 +528,7 @@ function finalToBrowserConfig( embeddingsProvider: final.embeddingsProvider?.id, ui: final.ui, experimental: final.experimental, + docs: final.docs, }; } diff --git a/core/config/types.ts b/core/config/types.ts index f397b1ed7..6c8362e4a 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -176,7 +176,7 @@ declare global { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } - export interface PersistedSessionInfo { + export interface Session { history: ChatHistory; title: string; workspaceDirectory: string; @@ -825,7 +825,6 @@ declare global { export interface TabAutocompleteOptions { disable: boolean; - useCopyBuffer: boolean; useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; @@ -835,14 +834,9 @@ declare global { multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; slidingWindowSize: number; - maxSnippetPercentage: number; - maxDiffPercentage: number; - maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; - useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; } diff --git a/core/core.ts b/core/core.ts index a0a571698..3b6b28016 100644 --- a/core/core.ts +++ b/core/core.ts @@ -19,6 +19,7 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; @@ -494,7 +495,7 @@ export class Core { config.models.find((model) => model.title?.startsWith(msg.data.title)); try { if (model) { - return model.listModels(); + return await model.listModels(); } else { if (msg.data.title === "Ollama") { const models = await new Ollama({ model: "" }).listModels(); @@ -754,8 +755,16 @@ export class Core { this.docsService.setPaused(msg.data.id, msg.data.paused); } }); - on("indexing/initStatuses", async (msg) => { - return this.docsService.initStatuses(); + on("docs/getSuggestedDocs", async (msg) => { + if (hasRequestedDocs) { + return; + } // TODO, remove, hack because of rerendering + hasRequestedDocs = true; + const suggestedDocs = await getAllSuggestedDocs(this.ide); + this.messenger.send("docs/suggestions", suggestedDocs); + }); + on("docs/initStatuses", async (msg) => { + void this.docsService.initStatuses(); }); // @@ -887,3 +896,5 @@ export class Core { // private } + +let hasRequestedDocs = false; diff --git a/core/index.d.ts b/core/index.d.ts index 46454c603..1082f41b7 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -68,8 +68,6 @@ export interface IndexingStatus { url?: string; } -export type IndexingStatusMap = Map; - export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, @@ -237,15 +235,15 @@ export interface Checkpoint { [filepath: string]: string; } -export interface PersistedSessionInfo { - history: ChatHistory; +export interface Session { + sessionId: string; title: string; workspaceDirectory: string; - sessionId: string; + history: ChatHistoryItem[]; checkpoints?: Checkpoint[]; } -export interface SessionInfo { +export interface SessionMetadata { sessionId: string; title: string; dateCreated: string; @@ -415,8 +413,6 @@ export interface ChatHistoryItem { toolCallState?: ToolCallState; } -export type ChatHistory = ChatHistoryItem[]; - // LLM export interface LLMFullCompletionOptions extends BaseCompletionOptions { @@ -1046,7 +1042,6 @@ export interface Reranker { export interface TabAutocompleteOptions { disable: boolean; - useCopyBuffer: boolean; useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; @@ -1057,17 +1052,11 @@ export interface TabAutocompleteOptions { multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; slidingWindowSize: number; - maxSnippetPercentage: number; - maxDiffPercentage: number; - maxClipboardPercentage: number; useCache: boolean; onlyMyCode: boolean; - useOtherFiles: boolean; useRecentlyEdited: boolean; - recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; - useRootPathContext?: boolean; showWhateverWeHaveAtXMs?: number; } @@ -1299,4 +1288,42 @@ export interface BrowserSerializedContinueConfig { reranker?: RerankerDescription; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; + docs?: SiteIndexingConfig[]; } + +// DOCS SUGGESTIONS AND PACKAGE INFO +export interface FilePathAndName { + path: string; + name: string; +} + +export interface PackageFilePathAndName extends FilePathAndName { + packageRegistry: string; // e.g. npm, pypi +} + +export type ParsedPackageInfo = { + name: string; + packageFile: PackageFilePathAndName; + language: string; + version: string; +}; + +export type PackageDetails = { + docsLink?: string; + docsLinkWarning?: string; + title?: string; + description?: string; + repo?: string; + license?: string; +}; + +export type PackageDetailsSuccess = PackageDetails & { + docsLink: string; +}; + +export type PackageDocsResult = { + packageInfo: ParsedPackageInfo; +} & ( + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 838e8fb54..6e841f6be 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,7 +7,6 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingStatusMap, IndexingStatus, SiteIndexingConfig, IdeInfo, @@ -70,6 +69,7 @@ export type AddParams = { favicon?: string; }; + /* General process: - On config update: @@ -86,7 +86,6 @@ export type AddParams = { export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; - static indexingType = "docs"; static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); @@ -136,38 +135,60 @@ export default class DocsService { configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } - readonly statuses: IndexingStatusMap = new Map(); - - // Function for GUI to retrieve initial pending statuses - // And kickoff indexing where needed - async initStatuses() { - this.config?.docs?.forEach(async (doc) => { - const currentStatus = this.statuses.get(doc.startUrl); - if (currentStatus) { - this.handleStatusUpdate(currentStatus); - } else { - this.handleStatusUpdate({ - type: "docs", - id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.id, - isReindexing: false, - progress: 0, - description: "Pending", - status: "pending", - title: doc.title, - debugInfo: `max depth: ${doc.maxDepth}`, - icon: doc.faviconUrl, - url: doc.startUrl, - }); - } - }); - } + readonly statuses: Map = new Map(); handleStatusUpdate(update: IndexingStatus) { this.statuses.set(update.id, update); this.messenger?.send("indexing/statusUpdate", update); } + // A way for gui to retrieve initial statuses + async initStatuses(): Promise { + if (!this.config?.docs) { + return; + } + const metadata = await this.listMetadata(); + + this.config.docs?.forEach((doc) => { + if (!doc.startUrl) { + console.error("Invalid config docs entry, no start"); + return; + } + + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + return currentStatus; + } + + const sharedStatus = { + type: "docs" as IndexingStatus["type"], + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }; + const indexedStatus: IndexingStatus = metadata.find( + (meta) => meta.startUrl === doc.startUrl, + ) + ? { + ...sharedStatus, + progress: 0, + description: "Pending", + status: "pending", + } + : { + ...sharedStatus, + progress: 1, + description: "Complete", + status: "complete", + }; + this.handleStatusUpdate(indexedStatus); + }); + } + abort(startUrl: string) { const status = this.statuses.get(startUrl); if (status) { @@ -362,6 +383,7 @@ export default class DocsService { const indexExists = await this.hasMetadata(startUrl); + // Build status update - most of it is fixed values const fixedStatus: Pick< IndexingStatus, | "type" @@ -383,6 +405,8 @@ export default class DocsService { url: siteIndexingConfig.startUrl, }; + // Clear current indexes if reIndexing + // if (indexExists) { if (reIndex) { await this.deleteIndexes(startUrl); @@ -398,6 +422,12 @@ export default class DocsService { } } + // If not preindexed + const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + if (!isPreIndexedDoc) { + this.addToConfig(siteIndexingConfig); + } + try { this.handleStatusUpdate({ ...fixedStatus, @@ -435,7 +465,7 @@ export default class DocsService { articles.push(article); processedPages++; - await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping + await new Promise((resolve) => setTimeout(resolve, 100)); // Locks down GUI if no sleeping } void Telemetry.capture("docs_pages_crawled", { @@ -788,19 +818,13 @@ export default class DocsService { } } - // Sends "Pending" or current status for each - await this.initStatuses(); - - for (const doc of changedDocs) { - console.log(`Updating indexed doc: ${doc.startUrl}`); - await this.indexAndAdd(doc, true); - } + await Promise.allSettled([ + ...changedDocs.map((doc) => this.indexAndAdd(doc, true)), + ...newDocs.map((doc) => this.indexAndAdd(doc)), + ]); for (const doc of newDocs) { - console.log(`Indexing new doc: ${doc.startUrl}`); void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - - await this.indexAndAdd(doc); } for (const doc of deletedDocs) { @@ -941,7 +965,7 @@ export default class DocsService { ); } - private addToConfig({ siteIndexingConfig }: AddParams) { + private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file const doesDocExist = this.config.docs?.some( @@ -959,13 +983,6 @@ export default class DocsService { private async add(params: AddParams) { await this.addToLance(params); await this.addMetadataToSqlite(params); - - const isPreIndexedDoc = - !!preIndexedDocs[params.siteIndexingConfig.startUrl]; - - if (!isPreIndexedDoc) { - this.addToConfig(params); - } } // Delete methods @@ -1030,10 +1047,7 @@ export default class DocsService { console.log( `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); - await this.initStatuses(); - for (const doc of docs) { - await this.indexAndAdd(doc, true); - } + await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc))); // Important that this only is invoked after we have successfully // cleared and reindex the docs so that the table cannot end up in an diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index e2feb4c59..5ebeb095c 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -250,7 +250,7 @@ export class ChromiumInstaller { private async proposeInstall(site: string) { const msg = - `Unable to crawl documentation site: ${site}\n` + + `Unable to crawl documentation site: "${site}".` + "We recommend installing Chromium. " + "Download progress can be viewed in the developer console."; diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts new file mode 100644 index 000000000..db192489a --- /dev/null +++ b/core/indexing/docs/suggestions/index.ts @@ -0,0 +1,134 @@ +import { + PackageDocsResult, + FilePathAndName, + PackageFilePathAndName, + IDE, + PackageDetails, + ParsedPackageInfo, +} from "../../.."; +import { walkDir } from "../../walkDir"; + +import { PythonPackageCrawler } from "./packageCrawlers/Python"; +import { NodePackageCrawler } from "./packageCrawlers/TsJs"; + +const PACKAGE_CRAWLERS = [NodePackageCrawler, PythonPackageCrawler]; + +export interface PackageCrawler { + packageRegistry: string; + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[]; + parsePackageFile( + file: PackageFilePathAndName, + contents: string, + ): ParsedPackageInfo[]; + getPackageDetails(packageInfo: ParsedPackageInfo): Promise; +} + +export async function getAllSuggestedDocs(ide: IDE) { + const workspaceDirs = await ide.getWorkspaceDirs(); + const results = await Promise.all( + workspaceDirs.map((dir) => { + return walkDir(dir, ide); + }), + ); + const allPaths = results.flat(); // TODO only get files, not dirs. Not critical for now + const allFiles = allPaths.map((path) => ({ + path, + name: path.split(/[\\/]/).pop()!, + })); + + // Build map of language -> package files + const packageFilesByRegistry: Record = {}; + for (const Crawler of PACKAGE_CRAWLERS) { + const crawler = new Crawler(); + const packageFilePaths = crawler.getPackageFiles(allFiles); + packageFilesByRegistry[crawler.packageRegistry] = packageFilePaths; + } + + // Get file contents for all unique package files + const uniqueFilePaths = Array.from( + new Set( + Object.values(packageFilesByRegistry).flatMap((files) => + files.map((file) => file.path), + ), + ), + ); + const fileContentsArray = await Promise.all( + uniqueFilePaths.map(async (path) => { + const contents = await ide.readFile(path); + return { path, contents }; + }), + ); + const fileContents = new Map( + fileContentsArray.map(({ path, contents }) => [path, contents]), + ); + + // Parse package files and build map of language -> packages + const packagesByCrawler: Record = {}; + PACKAGE_CRAWLERS.forEach((Crawler) => { + const crawler = new Crawler(); + packagesByCrawler[crawler.packageRegistry] = []; + const packageFiles = packageFilesByRegistry[crawler.packageRegistry]; + packageFiles.forEach((file) => { + const contents = fileContents.get(file.path); + if (!contents) { + return; + } + const packages = crawler.parsePackageFile(file, contents); + packagesByCrawler[crawler.packageRegistry].push(...packages); + }); + }); + + // Deduplicate packages per language + // TODO - this is where you would allow docs for different versions + // by e.g. using "name-version" as the map key instead of just name + // For now have not allowed + const registries = Object.keys(packagesByCrawler); + registries.forEach((registry) => { + const packages = packagesByCrawler[registry]; + const uniquePackages = Array.from( + new Map(packages.map((pkg) => [pkg.name, pkg])).values(), + ); + packagesByCrawler[registry] = uniquePackages; + }); + + // Get documentation links for all packages + const allDocsResults: PackageDocsResult[] = []; + await Promise.all( + PACKAGE_CRAWLERS.map(async (Crawler) => { + const crawler = new Crawler(); + const packages = packagesByCrawler[crawler.packageRegistry]; + const docsByRegistry = await Promise.all( + packages.map(async (packageInfo) => { + try { + const details = await crawler.getPackageDetails(packageInfo); + if (!details.docsLink) { + return { + packageInfo, + error: `No documentation link found for ${packageInfo.name}`, + }; + } + return { + packageInfo, + details: { + ...details, + docsLink: details.docsLink, + docsLinkWarning: details.docsLink.includes("github.com") + ? "Github docs not supported, find the docs site" + : details.docsLink.includes("docs") + ? undefined + : "May not be a docs site, check the URL", + }, + }; + } catch (error) { + return { + packageInfo, + error: `Error getting package details for ${packageInfo.name}`, + }; + } + }), + ); + allDocsResults.push(...docsByRegistry); + }), + ); + return allDocsResults; +} diff --git a/core/indexing/docs/suggestions/packageCrawlers/Python.ts b/core/indexing/docs/suggestions/packageCrawlers/Python.ts new file mode 100644 index 000000000..3a617568f --- /dev/null +++ b/core/indexing/docs/suggestions/packageCrawlers/Python.ts @@ -0,0 +1,63 @@ +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + PackageFilePathAndName, + ParsedPackageInfo, +} from "../../../.."; + +export class PythonPackageCrawler implements PackageCrawler { + packageRegistry = "pypi"; + + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { + // For Python, we typically look for files like requirements.txt or Pipfile + return files + .filter( + (file) => file.name === "requirements.txt" || file.name === "Pipfile", + ) + .map((file) => ({ + ...file, + packageRegistry: "pypi", + })); + } + + parsePackageFile( + file: PackageFilePathAndName, + contents: string, + ): ParsedPackageInfo[] { + // Assume the fileContent is a string from a requirements.txt formatted file + return contents + .split("\n") + .map((line) => { + const [name, version] = line.split("=="); + return { name, version, packageFile: file, language: "py" }; + }) + .filter((pkg) => pkg.name && pkg.version); + } + + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { + // Fetch metadata from PyPI to find the documentation link + const response = await fetch( + `https://pypi.org/pypi/${packageInfo.name}/json`, + ); + if (!response.ok) { + throw new Error(`Could not fetch data for package ${packageInfo.name}`); + } + const data = await response.json(); + const homePage = data?.info?.home_page as string | undefined; + + return { + docsLink: + (data?.info?.project_urls?.Documentation as string | undefined) ?? + homePage, + title: data?.info?.name as string | undefined, + description: data?.info?.summary as string | undefined, + repo: + (data?.info?.project_urls?.Repository as string | undefined) ?? + homePage, + license: data?.info?.license as string | undefined, + }; + } +} diff --git a/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts new file mode 100644 index 000000000..3a9ef96c2 --- /dev/null +++ b/core/indexing/docs/suggestions/packageCrawlers/TsJs.ts @@ -0,0 +1,77 @@ +import { PackageCrawler } from ".."; +import { + FilePathAndName, + PackageDetails, + PackageFilePathAndName, + ParsedPackageInfo, +} from "../../../.."; + +export class NodePackageCrawler implements PackageCrawler { + packageRegistry = "npm"; + + getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] { + // For Javascript/TypeScript, we look for package.json file + return files + .filter((file) => file.name === "package.json") + .map((file) => ({ + ...file, + packageRegistry: this.packageRegistry, + })); + } + + parsePackageFile( + file: PackageFilePathAndName, + contents: string, + ): ParsedPackageInfo[] { + // Parse the package.json content + const jsonData = JSON.parse(contents) as Record; + const dependencies = Object.entries(jsonData.dependencies || {}).concat( + Object.entries(jsonData.devDependencies || {}), + ); + + // Filter out types packages and check if typescript is present + let foundTypes = false; + const filtered = dependencies.filter(([name, _]) => { + if (name.startsWith("@types/")) { + foundTypes = true; + return false; + } + if (name.includes("typescript")) { + foundTypes = true; + } + return true; + }); + return filtered.map(([name, version]) => ({ + name, + version, + packageFile: file, + language: foundTypes ? "ts" : "js", + })); + } + + async getPackageDetails( + packageInfo: ParsedPackageInfo, + ): Promise { + const { name } = packageInfo; + // Fetch metadata from the NPM registry to find the documentation link + const response = await fetch(`https://registry.npmjs.org/${name}`); + if (!response.ok) { + throw new Error(`Could not fetch data for package ${name}`); + } + const data = await response.json(); + + // const dependencies = Object.keys(packageContentData.dependencies || {}) + // .concat(Object.keys(packageContentData.devDependencies || {})); + // const usesTypescript = dependencies.includes("typescript"); + + return { + docsLink: data.homepage as string | undefined, + title: name, // package.json doesn't have specific title field + description: data.description as string | undefined, + repo: Array.isArray(data.repository) + ? (data.respository[0]?.url as string | undefined) + : undefined, + license: data.license as string | undefined, + }; + } +} diff --git a/core/jest.config.js b/core/jest.config.js index 2567c5891..b92d03e5e 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -8,6 +8,8 @@ export default { moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", "^uuid$": "uuid", // https://stackoverflow.com/a/73626360 + '^@azure/(.*)$': '/node_modules/@azure/$1', + '^mssql$': '/node_modules/mssql' }, extensionsToTreatAsEsm: [".ts"], preset: "ts-jest/presets/default-esm", diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index b9e196b02..b1cb0da93 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,4 @@ -import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; +import { ChatHistoryItem, ChatMessage, MessagePart } from "../index.js"; import { normalizeToMessageParts } from "../util/messageContent.js"; import { modelSupportsTools } from "./autodetect.js"; @@ -78,7 +78,7 @@ const CANCELED_TOOL_CALL_MESSAGE = "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; export function constructMessages( - history: ChatHistory, + history: ChatHistoryItem[], model: string, ): ChatMessage[] { const msgs: ChatMessage[] = []; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 69de3f1d9..c56884e4b 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -397,7 +397,13 @@ class Ollama extends BaseLLM { }, ); const data = await response.json(); - return data.models.map((model: any) => model.name); + if (response.ok) { + return data.models.map((model: any) => model.name); + } else { + throw new Error( + "Failed to list Ollama models. Make sure Ollama is running.", + ); + } } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index bad13a359..35785d359 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -13,10 +13,10 @@ import type { LLMFullCompletionOptions, ModelDescription, ModelRoles, - PersistedSessionInfo, RangeInFile, SerializedContinueConfig, - SessionInfo, + Session, + SessionMetadata, SiteIndexingConfig, ToolCall, } from "../"; @@ -47,10 +47,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { abort: [undefined, void]; // History - "history/list": [ListHistoryOptions, SessionInfo[]]; + "history/list": [ListHistoryOptions, SessionMetadata[]]; "history/delete": [{ id: string }, void]; - "history/load": [{ id: string }, PersistedSessionInfo]; - "history/save": [PersistedSessionInfo, void]; + "history/load": [{ id: string }, Session]; + "history/save": [Session, void]; "devdata/log": [{ tableName: string; data: any }, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ @@ -166,7 +166,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { "indexing/reindex": [{ type: string; id: string }, void]; "indexing/abort": [{ type: string; id: string }, void]; "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; - "indexing/initStatuses": [undefined, void]; + "docs/getSuggestedDocs": [undefined, void]; + "docs/initStatuses": [undefined, void]; addAutocompleteModel: [{ model: ModelDescription }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 0086aa938..bbcfbf3f2 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -48,10 +48,11 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "index/forceReIndexFiles", "index/indexingProgressBarInitialized", // Docs, etc. - "indexing/initStatuses", "indexing/reindex", "indexing/abort", "indexing/setPaused", + "docs/getSuggestedDocs", + "docs/initStatuses", // "completeOnboarding", "addAutocompleteModel", @@ -75,4 +76,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "getWebviewHistoryLength", "signInToControlPlane", "openDialogMessage", + "docs/suggestions", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 0dcdb047f..fb6a8837c 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -4,6 +4,7 @@ import type { ContextItemWithId, IndexingProgressUpdate, IndexingStatus, + PackageDocsResult, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -25,4 +26,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { getWebviewHistoryLength: [undefined, number]; signInToControlPlane: [undefined, void]; openDialogMessage: ["account", void]; + "docs/suggestions": [PackageDocsResult[], void]; }; diff --git a/core/test/util/history.test.ts b/core/test/util/history.test.ts index c69e662a6..270e81248 100644 --- a/core/test/util/history.test.ts +++ b/core/test/util/history.test.ts @@ -1,11 +1,11 @@ import { v4 as uuidv4 } from "uuid"; -import { PersistedSessionInfo } from "../.."; +import { Session } from "../.."; import historyManager from "../../util/history"; import { getSessionFilePath } from "../../util/paths"; const sessionId = uuidv4(); -const testSession: PersistedSessionInfo = { +const testSession: Session = { history: [], title: `${sessionId} title`, workspaceDirectory: "workspaceDir", @@ -43,7 +43,9 @@ describe("Full session lifecycle", () => { // save and list historyManager.save(testSession); const sessions = historyManager.list({}); - const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId); + const sessionExists = sessions.some( + (session) => session?.sessionId === testSession.sessionId, + ); expect(sessionExists).toBe(true); }); @@ -90,7 +92,9 @@ describe("Many sessions created", () => { const offset = 10; const sessions = historyManager.list({ offset: offset, limit: limit }); - const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString()); + const sessionIds = Array.from({ length: limit }, (_, i) => + (i + offset).toString(), + ); const isSessionIdInList = (sessionId: string) => sessions.some((session) => session.sessionId === sessionId); expect(sessionIds.every(isSessionIdInList)).toBe(true); @@ -111,8 +115,9 @@ describe("Many sessions created", () => { const offset = 75; const sessions = historyManager.list({ offset: offset }); - const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) => - (i + offset).toString(), + const sessionIds = Array.from( + { length: sessions.length - offset }, + (_, i) => (i + offset).toString(), ); const isSessionIdInList = (sessionId: string) => diff --git a/core/util/history.ts b/core/util/history.ts index f147c4e07..e68556762 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -1,6 +1,6 @@ import * as fs from "fs"; -import { PersistedSessionInfo, SessionInfo } from "../index.js"; +import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; @@ -18,14 +18,14 @@ function safeParseArray( } class HistoryManager { - list(options: ListHistoryOptions): SessionInfo[] { + list(options: ListHistoryOptions): SessionMetadata[] { const filepath = getSessionsListPath(); if (!fs.existsSync(filepath)) { return []; } const content = fs.readFileSync(filepath, "utf8"); - let sessions = safeParseArray(content) ?? []; + let sessions = safeParseArray(content) ?? []; sessions = sessions.filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; @@ -52,7 +52,7 @@ class HistoryManager { const sessionsListFile = getSessionsListPath(); const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); let sessionsList = - safeParseArray( + safeParseArray( sessionsListRaw, "Error parsing sessions.json", ) ?? []; @@ -67,15 +67,13 @@ class HistoryManager { ); } - load(sessionId: string): PersistedSessionInfo { + load(sessionId: string): Session { try { const sessionFile = getSessionFilePath(sessionId); if (!fs.existsSync(sessionFile)) { throw new Error(`Session file ${sessionFile} does not exist`); } - const session: PersistedSessionInfo = JSON.parse( - fs.readFileSync(sessionFile, "utf8"), - ); + const session: Session = JSON.parse(fs.readFileSync(sessionFile, "utf8")); session.sessionId = sessionId; return session; } catch (e) { @@ -89,11 +87,20 @@ class HistoryManager { } } - save(session: PersistedSessionInfo) { + save(session: Session) { // Save the main session json file + // Explicitely rewriting here to influence the written key order in the file! + // e.g. id at the top, history next, etc. + const orderedSession: Session = { + sessionId: session.sessionId, + title: session.title, + workspaceDirectory: session.workspaceDirectory, + history: session.history, + checkpoints: session.checkpoints, + }; fs.writeFileSync( getSessionFilePath(session.sessionId), - JSON.stringify(session, undefined, 2), + JSON.stringify(orderedSession, undefined, 2), ); // Read and update the sessions list @@ -101,7 +108,7 @@ class HistoryManager { try { const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8"); - let sessionsList: SessionInfo[]; + let sessionsList: SessionMetadata[]; try { sessionsList = JSON.parse(rawSessionsList); } catch (e) { @@ -114,23 +121,23 @@ class HistoryManager { } let found = false; - for (const sessionInfo of sessionsList) { - if (sessionInfo.sessionId === session.sessionId) { - sessionInfo.title = session.title; - sessionInfo.workspaceDirectory = session.workspaceDirectory; + for (const sessionMetadata of sessionsList) { + if (sessionMetadata.sessionId === session.sessionId) { + sessionMetadata.title = session.title; + sessionMetadata.workspaceDirectory = session.workspaceDirectory; found = true; break; } } if (!found) { - const sessionInfo: SessionInfo = { + const sessionMetadata: SessionMetadata = { sessionId: session.sessionId, title: session.title, dateCreated: String(Date.now()), workspaceDirectory: session.workspaceDirectory, }; - sessionsList.push(sessionInfo); + sessionsList.push(sessionMetadata); } fs.writeFileSync( diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 20b96ac47..24e94781c 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,7 +2,6 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - useCopyBuffer: false, useFileSuffix: true, maxPromptTokens: 1024, prefixPercentage: 0.85, @@ -11,17 +10,11 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.5, - maxDiffPercentage: 0.5, - maxClipboardPercentage: 0.5, // yes the percentages do not add up useCache: true, onlyMyCode: true, - useOtherFiles: true, useRecentlyEdited: true, - recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, - useRootPathContext: true, transform: true, showWhateverWeHaveAtXMs: 300, }; diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index dcf6ba234..ccd1dca9d 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -9,14 +9,12 @@ Continue offers a handful of parameters in [`config.json`](../reference.md) that ```json title="config.json" "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5, "multilineCompletions": "always" } ``` -- `useCopyBuffer`: Determines if the clipboard content should be considered in prompt construction. - `maxPromptTokens`: Sets the maximum number of tokens for the prompt, balancing context and speed. - `prefixPercentage`: Defines the proportion of the prompt dedicated to the code before the cursor. - `multilineCompletions`: Controls whether suggestions can span multiple lines ("always", "never", or "auto"). diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 9e03aa756..35789710c 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `disable`: Disable autocomplete (can also be done from IDE settings) - `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) - `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) - `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) - `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) @@ -68,7 +67,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa - `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) - `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. -- `useOtherFiles`: Whether to include context from files outside of the current one. Turning this off should be expected to reduce the accuracy of completions, but might be good for testing. - `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. ### Full example diff --git a/docs/docs/customize/model-providers/more/together.md b/docs/docs/customize/model-providers/more/together.md index b02c83172..e5ed9abd0 100644 --- a/docs/docs/customize/model-providers/more/together.md +++ b/docs/docs/customize/model-providers/more/together.md @@ -1,14 +1,14 @@ # Together -The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/models-inference). Change `~/.continue/config.json` to look like this: +The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this: ```json title="config.json" { "models": [ { - "title": "Together CodeLlama", + "title": "Together Qwen2.5 Coder", "provider": "together", - "model": "codellama-13b", + "model": "Qwen/Qwen2.5-Coder-32B-Instruct", "apiKey": "YOUR_API_KEY" } ] diff --git a/docs/docs/reference.md b/docs/docs/reference.md index f39e68998..5fc3218df 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -83,7 +83,6 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. - `useFileSuffix`: If `true`, includes file suffix in the prompt. - `maxPromptTokens`: Maximum number of tokens for the prompt. - `debounceDelay`: Delay (in ms) before triggering autocomplete. @@ -93,7 +92,6 @@ Specifies options for tab autocompletion behavior. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. -- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). - `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. Example diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index aa2a04d5f..143645591 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -9,14 +9,12 @@ Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你 ```json title="config.json" "tabAutocompleteOptions": { - "useCopyBuffer": false, "maxPromptTokens": 400, "prefixPercentage": 0.5, "multilineCompletions": "always" } ``` -- `useCopyBuffer`: 决定剪贴板的内容是否包含在提示词构建中 - `maxPromptTokens`: 设置提示词的最大 token 数,平衡上下文和速度 - `prefixPercentage`: 决定提示词使用光标前代码的比例 - `multilineCompletions`: 控制建议是否可以跨多行 ("always", "never" 或 "auto") diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index b85cfe323..15cb94c4d 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ ollama run starcoder2:3b - `disable`: 禁用自动补全(也可以在 IDE 配置中完成) - `template`: 一个用来自动补全的可选的模板字符串。它使用 Mustache 模板语言渲染,并且传递 'prefix' 和 'suffix' 变量。(字符串) -- `useCopyBuffer`: 决定 copy buffer 是否考虑为构建提示词。(布尔型) - `useFileSuffix`: 决定是否使用文件后缀在提示词中。(布尔型) - `maxPromptTokens`: 提示词使用的 token 的最大数量。一个较小的数字生成较快的补全,但是较少的上下文。(数字) - `prefixPercentage`: 输入专注于前缀的百分比。(数字) @@ -69,7 +68,6 @@ ollama run starcoder2:3b - `debounceDelay`: 在按键之后触发自动补全的毫秒延迟。(数字) - `multilineCompletions`: 是否启用多行补全 ("always", "never" 或 "auto") 。默认情况下是 "auto" 。 - `useCache`: 是否缓存和重新使用补全,当提示词与前一个相同时。对于测试的目的可能是有用的。 -- `useOtherFiles`: 是否包含当前文件之外的文件的上下文。关闭这个预期会减少补全的准确性,但是对于测试可能是有用的。 - `disableInFiles`: 一个你想要禁用 tab 自动补全的 glob 模式的文件列表。 ### 完整示例 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md index 09dd150a6..a224cf8a8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -83,7 +83,6 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. - `useFileSuffix`: If `true`, includes file suffix in the prompt. - `maxPromptTokens`: Maximum number of tokens for the prompt. - `debounceDelay`: Delay (in ms) before triggering autocomplete. @@ -93,7 +92,6 @@ Specifies options for tab autocompletion behavior. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. -- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). - `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. Example diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/HistoryManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/HistoryManager.kt deleted file mode 100644 index 692a2ee1a..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/HistoryManager.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.github.continuedev.continueintellijextension.`continue` - -import com.github.continuedev.continueintellijextension.constants.getSessionFilePath -import com.github.continuedev.continueintellijextension.constants.getSessionsListPath -import com.google.gson.Gson -import com.google.gson.reflect.TypeToken -import java.io.File -import java.io.FileReader -import java.io.FileWriter -import java.lang.reflect.Type - -typealias PersistedSessionInfo = MutableMap -typealias SessionInfo = MutableMap - -class HistoryManager { - private val gson = Gson() - - fun list(): List { - val filePath = getSessionsListPath() - val file = File(filePath) - - if (!file.exists()) { - return emptyList() - } - - val reader = FileReader(file) - val type: Type = object : TypeToken>() {}.type - val sessions = gson.fromJson>(reader, type) - - return sessions.filter { it["sessionId"] != null } - } - - fun delete(sessionId: String) { - val sessionFile = getSessionFilePath(sessionId) - val file = File(sessionFile) - - if (!file.exists()) { - throw Exception("Session file $sessionFile does not exist") - } - - file.delete() - val sessionsListFile = getSessionsListPath() - val sessionsListRaw = FileReader(File(sessionsListFile)) - - val type: Type = object : TypeToken>() {}.type - var sessionsList = gson.fromJson>(sessionsListRaw, type) - - sessionsList = sessionsList.filter { it["sessionId"] != sessionId } - - val writer = FileWriter(sessionsListFile) - gson.toJson(sessionsList, writer) - writer.close() - } - - fun load(sessionId: String): PersistedSessionInfo { - val sessionFile = getSessionFilePath(sessionId) - val file = File(sessionFile) - - if (!file.exists()) { - throw Exception("Session file $sessionFile does not exist") - } - - val reader = FileReader(file) - val text = reader.readText() - val type: Type = object : TypeToken>() {}.type - val session = gson.fromJson>(text, type) - session["sessionId"] = sessionId - return session - } - - fun save(session: PersistedSessionInfo) { - val writer = FileWriter(getSessionFilePath(session["sessionId"] as String? ?: uuid())) - gson.toJson(session, writer) - writer.close() - - val sessionsListFilePath = getSessionsListPath() - val rawSessionsList = FileReader(File(sessionsListFilePath)) - - val type: Type = object : TypeToken>() {}.type - val sessionsList = gson.fromJson>>(rawSessionsList, type).toMutableList() - - var found = false - for (sessionInfo in sessionsList) { - if (sessionInfo["sessionId"] == session["sessionId"]) { - sessionInfo["title"] = session["title"] as Any - sessionInfo["workspaceDirectory"] = session["workspaceDirectory"] as Any - sessionInfo["dateCreated"] = System.currentTimeMillis().toString() - found = true - break - } - } - - if (!found) { - val sessionInfo = mutableMapOf( - "sessionId" to session["sessionId"], - "title" to session["title"], - "dateCreated" to System.currentTimeMillis().toString(), - "workspaceDirectory" to session["workspaceDirectory"] - ) as MutableMap - sessionsList.add(sessionInfo) - } - - val writerList = FileWriter(sessionsListFilePath) - gson.toJson(sessionsList, writerList) - writerList.close() - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt index 7de018bb2..b4f099d2d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorComponentInlaysManager.kt @@ -51,7 +51,7 @@ class EditorComponentInlaysManager(val editor: EditorImpl, private val onlyOneIn } val wrappedComponent = ComponentWrapper(component) - val offset = editor.document.getLineEndOffset(lineIndex) + val offset = editor.document.getLineStartOffset(lineIndex) return EditorEmbeddedComponentManager.getInstance() .addComponent( @@ -59,7 +59,7 @@ class EditorComponentInlaysManager(val editor: EditorImpl, private val onlyOneIn EditorEmbeddedComponentManager.Properties( EditorEmbeddedComponentManager.ResizePolicy.none(), null, - true, + !editor.inlayModel.getBlockElementsInRange(offset,offset).isEmpty(), showAbove, 0, offset diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index a84bf7f9b..64f1d1bb7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -59,11 +59,12 @@ class VerticalDiffBlock( fun deleteLineAt(line: Int) { val startOffset = editor.document.getLineStartOffset(line) - val endOffset = editor.document.getLineEndOffset(line) + 1 + val endOffset = min(editor.document.getLineEndOffset(line) + 1, editor.document.textLength) val deletedText = editor.document.getText(TextRange(startOffset, endOffset)) deletedLines.add(deletedText.trimEnd()) + // Unable to ensure that text length has not changed, so we need to get it again editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength)) } diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 8dac5cd8c..d33482747 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,7 +5,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). -Pre-release Changes +## 0.8.59 - 2024-11-25 +### Fixed +* Hotfix for Ollama onboarding + +## 0.8.58 - 2024-11-22 ### Added * OpenAI predicted outputs support * Improve codebase retrieval with BM25 @@ -19,11 +23,17 @@ Pre-release Changes * Updates for llama3.2 * .continuerules file to set system prompt * .prompt files v2 +* Dedicated UI for docs indexing +* Clickable code symbols in chat +* Use clipboard content as autocomplete context ### Changed * Improved @docs crawler * Many improvements to make autocomplete more eager +* Near complete type definition retrieval for TypeScript autocomplete +* Remove footer from chat sidebar ### Fixed * Brought back the Apply button for all code blocks +* Automatically update codebase index on removed files ## 0.8.56 - 2024-11-08 ### Added diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index d5c9223a4..23a505118 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2791,10 +2791,6 @@ "description": "Disable tab autocomplete. This can also be done from the IDE settings.", "default": false }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, "useFileSuffix": { "type": "boolean", "description": "Determines whether to use the file suffix in the prompt." @@ -2835,10 +2831,6 @@ "type": "boolean", "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, "disableInFiles": { "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", "type": "array", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 046b4f398..d7316c47f 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.233", + "version": "0.9.235", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.233", + "version": "0.9.235", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -109,7 +109,6 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.14.0", "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", @@ -11609,11 +11608,11 @@ } }, "node_modules/tedious/node_modules/@types/node": { - "version": "22.9.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.0.tgz", - "integrity": "sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==", + "version": "22.10.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.0.tgz", + "integrity": "sha512-XC70cRZVElFHfIUB40FgZOBbgJYFKKMa5nb9lxcwYstFG/Mi+/Y0bGS+rs6Dmhmkpq4pnNiLiuZAbc02YCOnmA==", "dependencies": { - "undici-types": "~6.19.8" + "undici-types": "~6.20.0" } }, "node_modules/tedious/node_modules/bl": { @@ -11981,9 +11980,9 @@ } }, "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==" + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==" }, "node_modules/unified": { "version": "10.1.2", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 3308bc4c1..e127101f3 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.233", + "version": "0.9.236", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -182,7 +182,7 @@ "group": "Continue" }, { - "command": "continue.quickEdit", + "command": "continue.focusEdit", "category": "Continue", "title": "Generate Code", "group": "Continue" diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index c7d0553a0..5d6faef3f 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -153,12 +153,6 @@ export class ContinueCompletionProvider const signal = abortController.signal; token.onCancellationRequested(() => abortController.abort()); - const config = await this.configHandler.loadConfig(); - let clipboardText = ""; - if (config.tabAutocompleteOptions?.useCopyBuffer === true) { - clipboardText = await vscode.env.clipboard.readText(); - } - // Handle notebook cells const pos = { line: position.line, @@ -194,12 +188,6 @@ export class ContinueCompletionProvider } // Handle commit message input box let manuallyPassPrefix: string | undefined = undefined; - if (document.uri.scheme === "vscode-scm") { - return null; - // let diff = await this.ide.getDiff(); - // diff = diff.split("\n").splice(-150).join("\n"); - // manuallyPassPrefix = `${diff}\n\nCommit message: `; - } const input: AutocompleteInput = { completionId: uuidv4(), @@ -208,7 +196,6 @@ export class ContinueCompletionProvider recentlyEditedFiles: [], recentlyEditedRanges: await this.recentlyEditedTracker.getRecentlyEditedRanges(), - clipboardText: clipboardText, manuallyPassFileContents, manuallyPassPrefix, selectedCompletionInfo, diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 90b034a2e..08b16ace7 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,6 +1,4 @@ -import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; -import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { FUNCTION_BLOCK_NODE_TYPES, @@ -11,6 +9,14 @@ import * as vscode from "vscode"; import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; import type Parser from "web-tree-sitter"; +import { + AutocompleteSnippetDeprecated, + GetLspDefinitionsFunction, +} from "core/autocomplete/types"; +import { + AutocompleteCodeSnippet, + AutocompleteSnippetType, +} from "core/autocomplete/snippets/types"; type GotoProviderName = | "vscode.executeDefinitionProvider" @@ -341,7 +347,7 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( cursorIndex: number, ide: IDE, lang: AutocompleteLanguageInfo, -): Promise => { +): Promise => { try { const ast = await getAst(filepath, contents); if (!ast) { @@ -365,8 +371,9 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( } return results.map((result) => ({ - ...result, - score: 0.8, + filepath: result.filepath, + content: result.contents, + type: AutocompleteSnippetType.Code, })); } catch (e) { console.warn("Error getting definitions from LSP: ", e); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 43115ae93..96426b88a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -93,19 +93,44 @@ function addCodeToContextFromRange( }); } -function getCurrentlyHighlightedCode( +function getRangeInFileWithContents( allowEmpty?: boolean, + range?: vscode.Range, ): RangeInFileWithContents | null { const editor = vscode.window.activeTextEditor; + if (editor) { const selection = editor.selection; + const filepath = editor.document.uri.fsPath; + + if (range) { + const contents = editor.document.getText(range); + + return { + range: { + start: { + line: range.start.line, + character: range.start.character, + }, + end: { + line: range.end.line, + character: range.end.character, + }, + }, + filepath, + contents, + }; + } + if (selection.isEmpty && !allowEmpty) { return null; } + // adjust starting position to include indentation const start = new vscode.Position(selection.start.line, 0); - const range = new vscode.Range(start, selection.end); - const contents = editor.document.getText(range); + const selectionRange = new vscode.Range(start, selection.end); + const contents = editor.document.getText(selectionRange); + return { filepath: editor.document.uri.fsPath, contents, @@ -121,13 +146,14 @@ function getCurrentlyHighlightedCode( }, }; } + return null; } async function addHighlightedCodeToContext( webviewProtocol: VsCodeWebviewProtocol | undefined, ) { - const rangeInFileWithContents = getCurrentlyHighlightedCode(); + const rangeInFileWithContents = getRangeInFileWithContents(); if (rangeInFileWithContents) { webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, @@ -218,10 +244,16 @@ async function processDiff( } else if (fullPath) { fullPath = getFullyQualifiedPath(ide, fullPath); } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); + const curFile = await ide.getCurrentFile(); + fullPath = curFile?.path; } - if (!fullPath) return; + if (!fullPath) { + console.warn( + `Unable to resolve filepath while attempting to resolve diff: ${newFilepath}`, + ); + return; + } await ide.openFile(fullPath); @@ -369,7 +401,7 @@ const getCommandsMap: ( // Passthrough for telemetry purposes "continue.defaultQuickAction": async (args: QuickEditShowParams) => { captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); + vscode.commands.executeCommand("continue.focusEdit", args); }, "continue.customQuickActionSendToChat": async ( prompt: string, @@ -461,7 +493,9 @@ const getCommandsMap: ( void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, - "continue.focusEdit": async () => { + // QuickEditShowParams are passed from CodeLens, temp fix + // until we update to new params specific to Edit + "continue.focusEdit": async (args?: QuickEditShowParams) => { captureCommandTelemetry("focusEdit"); focusGUI(); @@ -483,12 +517,13 @@ const getCommandsMap: ( return; } - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), - ); + const range = + args?.range ?? + new vscode.Range(editor.selection.start, editor.selection.end); - const rangeInFileWithContents = getCurrentlyHighlightedCode(true); + editDecorationManager.setDecoration(editor, range); + + const rangeInFileWithContents = getRangeInFileWithContents(true, range); if (rangeInFileWithContents) { sidebar.webviewProtocol?.request( @@ -502,10 +537,6 @@ const getCommandsMap: ( editor.selection.anchor, ); } - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); }, "continue.focusEditWithoutClear": async () => { captureCommandTelemetry("focusEditWithoutClear"); @@ -531,7 +562,7 @@ const getCommandsMap: ( return; } - const rangeInFileWithContents = getCurrentlyHighlightedCode(false); + const rangeInFileWithContents = getRangeInFileWithContents(false); if (rangeInFileWithContents) { sidebar.webviewProtocol?.request( @@ -547,25 +578,21 @@ const getCommandsMap: ( contents, }); } - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); await sidebar.webviewProtocol?.request("exitEditMode", undefined); }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, - }); - quickEdit.show(args); - }, + // "continue.quickEdit": async (args: QuickEditShowParams) => { + // let linesOfCode = undefined; + // if (args.range) { + // linesOfCode = args.range.end.line - args.range.start.line; + // } + // captureCommandTelemetry("quickEdit", { + // linesOfCode, + // }); + // quickEdit.show(args); + // }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b8c303999..0f5a13cff 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -508,6 +508,11 @@ export class VsCodeMessenger { await Promise.all( sessions.map((session) => workOsAuthProvider.removeSession(session.id)), ); + vscode.commands.executeCommand( + "setContext", + "continue.isSignedInToControlPlane", + false, + ); }); } } diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts index 8b856d18f..04e27d7ee 100644 --- a/extensions/vscode/src/quickEdit/EditDecorationManager.ts +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -5,14 +5,10 @@ class EditDecorationManager { constructor(context: vscode.ExtensionContext) { this.decorationType = vscode.window.createTextEditorDecorationType({ - backgroundColor: "rgba(255, 255, 0, 0.1)", - borderWidth: "0 0 0 1px", - borderColor: "rgba(255, 255, 0)", - borderStyle: "solid", + backgroundColor: new vscode.ThemeColor( + "editor.inactiveSelectionBackground", + ), isWholeLine: true, - cursor: "pointer", - // gutterIconPath: context.asAbsolutePath("media/gutterIcon.png"), - gutterIconSize: "contain", }); } diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 0c3f81ada..a9fdb7b9a 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -8,6 +8,7 @@ import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders"; import { useVscTheme } from "./hooks/useVscTheme"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigErrorPage from "./pages/config-error"; +import Edit from "./pages/edit"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; @@ -40,6 +41,10 @@ const router = createMemoryRouter([ path: "/stats", element: , }, + { + path: "/edit", + element: , + }, { path: "/settings", element: , @@ -79,7 +84,6 @@ function App() { const vscTheme = useVscTheme(); const submenuContextProvidersMethods = useSubmenuContextProviders(); - return ( - - Sign out - -
+
+ + Sign out +
) : ( - {JSON.stringify(session.title).slice(1, -1)} + {JSON.stringify(sessionMetadata.title).slice(1, -1)} )}
- {lastPartOfPath(session.workspaceDirectory || "")} + + {lastPartOfPath(sessionMetadata.workspaceDirectory || "")} + {/* Uncomment to show the date */} {/* {date.toLocaleString("en-US", { @@ -119,9 +126,10 @@ export function HistoryTableRow({ { - await deleteSession(session.sessionId); - onDelete(session.sessionId); + onClick={async (e) => { + e.stopPropagation(); + await deleteSession(sessionMetadata.sessionId); + onDelete(sessionMetadata.sessionId); }} > diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index e509a9be9..b872addd4 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,10 +1,10 @@ -import { SessionInfo } from "core"; +import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; -import React, { Fragment, useEffect, useMemo, useState } from "react"; +import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import useHistory from "../../hooks/useHistory"; -import { getFontSize } from "../../util"; +import { getFontSize, getMetaKeyLabel } from "../../util"; import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; @@ -20,13 +20,7 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { - const [sessions, setSessions] = useState([]); - - const deleteSessionInUI = async (sessionId: string) => { - setSessions((prev) => - prev.filter((session) => session.sessionId !== sessionId), - ); - }; + const [sessions, setSessions] = useState([]); const searchInputRef = React.useRef(null); @@ -35,12 +29,12 @@ export function History() { const [searchTerm, setSearchTerm] = useState(""); - const minisearch = useMemo(() => { - return new MiniSearch({ + const minisearch = useRef( + new MiniSearch({ fields: ["title"], storeFields: ["title", "sessionId", "id"], - }); - }, []); + }), + ).current; useEffect(() => { const fetchSessions = async () => { @@ -64,7 +58,27 @@ export function History() { fetchSessions(); }, [lastSessionId]); - const filteredAndSortedSessions: SessionInfo[] = useMemo(() => { + const deleteSessionInUI = async (sessionId: string) => { + setSessions((prev) => + prev.filter((session) => session.sessionId !== sessionId), + ); + minisearch.discard(sessionId); + }; + + const updateSessionInUI = async (session: SessionMetadata) => { + setSessions((prev) => + prev.map((sess) => + sess.sessionId === session.sessionId ? session : sess, + ), + ); + minisearch.replace({ + title: session.title, + sessionId: session.sessionId, + id: session.sessionId, + }); + }; + + const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch .search(searchTerm, { fuzzy: 0.1, @@ -114,7 +128,9 @@ export function History() { {filteredAndSortedSessions.length === 0 && (
No past sessions found. To start a new session, either click the "+" - button or use the keyboard shortcut: Option + Command + N + button or use the keyboard shortcut: {getMetaKeyLabel()} + {` `} + L
)} @@ -152,10 +168,10 @@ export function History() { )} deleteSessionInUI(session.sessionId)} + onDelete={deleteSessionInUI} + onEdit={updateSessionInUI} /> ); diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index d16587427..e937070c9 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -59,11 +59,17 @@ function OnboardingLocalTab() { try { const result = await ideMessenger.request("llm/listModels", { title: ONBOARDING_LOCAL_MODEL_TITLE, - }) - + }); if (result.status === "success") { - setDownloadedOllamaModels(result.content); - setIsOllamaConnected(true); + // TODO - temporary fix, see notes + // https://github.com/continuedev/continue/pull/3059 + if (Array.isArray(result.content)) { + setDownloadedOllamaModels(result.content); + setIsOllamaConnected(true); + } else { + setDownloadedOllamaModels([]); + setIsOllamaConnected(false); + } } else { throw new Error("Failed to fetch models"); } diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index d8a17ec8a..632468a65 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -2,6 +2,7 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; +import { getMetaKeyLabel } from "../../util"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; @@ -37,7 +38,7 @@ export default function AcceptRejectAllButtons({ > {hasSinglePendingApplyStates ? ( - Reject + Reject ({getMetaKeyLabel()}⇧⌫) ) : ( <> Reject @@ -52,7 +53,7 @@ export default function AcceptRejectAllButtons({ > {hasSinglePendingApplyStates ? ( - Accept + Accept ({getMetaKeyLabel()}⇧⏎) ) : ( <> Accept diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 098194886..00134a6f7 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,48 +1,94 @@ import { - CheckCircleIcon, - ChevronDownIcon, - ChevronUpIcon, + CheckIcon, + InformationCircleIcon, + PencilIcon, + PlusIcon, } from "@heroicons/react/24/outline"; -import { SiteIndexingConfig } from "core"; +import { IndexingStatus, PackageDocsResult, SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; -import { useContext, useLayoutEffect, useRef, useState } from "react"; +import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; -import { Button, HelperText, Input, lightGray, SecondaryButton } from ".."; +import { Input, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; -import IndexingStatusViewer from "../indexing/IndexingStatus"; +import { ToolTip } from "../gui/Tooltip"; +import FileIcon from "../FileIcon"; +import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; +import { updateIndexingStatus } from "../../redux/slices/stateSlice"; +import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; function AddDocsDialog() { const posthog = usePostHog(); const dispatch = useDispatch(); - const ref = useRef(null); + const titleRef = useRef(null); + const urlRef = useRef(null); const [title, setTitle] = useState(""); const [startUrl, setStartUrl] = useState(""); const [faviconUrl, setFaviconUrl] = useState(""); - const [isOpen, setIsOpen] = useState(false); - - const [submittedConfig, setSubmittedConfig] = useState(); const ideMessenger = useContext(IdeMessengerContext); const indexingStatuses = useSelector( (store: RootState) => store.state.indexing.statuses, ); + const docsIndexingStatuses: IndexingStatus[] = useMemo(() => { + return Object.values(indexingStatuses).filter( + (status) => status.type === "docs" && status.status === "indexing", + ); + }, [indexingStatuses]); + + const docsSuggestions = useSelector( + (store: RootState) => store.state.docsSuggestions, + ); + + const configDocs = useSelector((store: RootState) => store.state.config.docs); + + const sortedDocsSuggestions = useMemo(() => { + const docsFromConfig = configDocs ?? []; + const filtered = docsSuggestions.filter((sug) => { + const startUrl = sug.details?.docsLink; + return ( + !docsFromConfig.find((d) => d.startUrl === startUrl) && + !docsIndexingStatuses.find((s) => s.id === startUrl) && + (startUrl ? !preIndexedDocs[startUrl] : true) + ); + }); + + filtered.sort((a, b) => { + const rank = (result: PackageDocsResult) => { + if (result.error) { + return 2; + } else if (result.details?.docsLinkWarning) { + return 1; + } else { + return 0; + } + }; + return rank(a) - rank(b); + }); + return filtered; + }, [docsSuggestions, configDocs, docsIndexingStatuses]); + const isFormValid = startUrl && title; useLayoutEffect(() => { setTimeout(() => { - if (ref.current) { - ref.current.focus(); + if (titleRef.current) { + titleRef.current.focus(); } }, 100); - }, [ref]); + }, [titleRef]); + + const closeDialog = () => { + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + }; function onSubmit(e: any) { e.preventDefault(); @@ -55,158 +101,228 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); - setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); posthog.capture("add_docs_gui", { url: startUrl }); - } - if (submittedConfig) { - const status = indexingStatuses[submittedConfig.startUrl]; - return ( -
-
- -

{`Docs added`}

-
-
-

Title: {submittedConfig.title}

-

Start URL: {submittedConfig.startUrl}

- {submittedConfig.rootUrl && ( -

Root URL: {submittedConfig.rootUrl}

- )} - {submittedConfig.maxDepth && ( -

Max depth: {submittedConfig.maxDepth}

- )} - {submittedConfig.faviconUrl && ( -

Favicon URL: {submittedConfig.faviconUrl}

- )} -
- {!!status && ( -
-

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

-
- -
-
- )} -
- { - setSubmittedConfig(undefined); - }} - > - Add another - - -
-
+ // Optimistic status update + dispatch( + updateIndexingStatus({ + type: "docs", + description: "Initializing", + id: startUrl, + embeddingsProviderId: "mock-embeddings-provider-id", + progress: 0, + status: "indexing", + title, + url: startUrl, + }), ); } + const handleSelectSuggestion = (docsResult: PackageDocsResult) => { + if (docsResult.error) { + setTitle(docsResult.packageInfo.name); + setStartUrl(""); + urlRef.current?.focus(); + return; + } + if (docsResult.details?.docsLinkWarning) { + setTitle(docsResult.packageInfo.name); + setStartUrl(docsResult.details.docsLink); + urlRef.current?.focus(); + return; + } + const siteIndexingConfig: SiteIndexingConfig = { + startUrl: docsResult.details.docsLink, + title: docsResult.details.title, + faviconUrl: undefined, + }; + + ideMessenger.post("context/addDocs", siteIndexingConfig); + + posthog.capture("add_docs_gui", { url: startUrl }); + + // Optimistic status update + dispatch( + updateIndexingStatus({ + type: "docs", + description: "Initializing", + id: docsResult.details.docsLink, + embeddingsProviderId: "mock-embeddings-provider-id", + progress: 0, + status: "indexing", + title: docsResult.details.title ?? docsResult.packageInfo.name, + url: docsResult.details.docsLink, + }), + ); + }; + return ( -
-
-

Add a documentation site

- -

- Continue pre-indexes many common documentation sites, but if there's - one you don't see in the dropdown, enter the URL here. +

+
+

Add documentation

+

Add docs

+

+ For the @docs context provider

+ {!!sortedDocsSuggestions.length && ( +

Suggestions

+ )} +
+ {sortedDocsSuggestions.map((docsResult) => { + const { error, details } = docsResult; + const { language, name, version } = docsResult.packageInfo; + const id = `${language}-${name}-${version}`; + return ( +
{ + handleSelectSuggestion(docsResult); + }} + > +
+ {error || details.docsLinkWarning ? ( +
+ + + This may not be a docs page + +
+ ) : ( + + )} +
+
+
+ +
+ {name} +
+
+ {error ? ( + + No docs link found + + ) : ( +
+ {/*
+ +
*/} +

+ {details.docsLink} +

+
+ )} +
+
+ + +

{`Version: ${version}`}

+

{`Found in ${docsResult.packageInfo.packageFile.path}`}

+
+
+
+ ); + })} +
+
+
+
+ + + + {/*
+ +
*/} +
+
+ + Add + +
+
+
-
- - - - -
setIsOpen((prev) => !prev)} - > - {isOpen ? ( - - ) : ( - - )} - Advanced + +
+
+ {docsIndexingStatuses.length ? ( +

+ + It is safe to close this form while indexing +

+ ) : null}
- - {isOpen && ( -
- -
- )} - -
- -
- + {/* */} +
); } diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 7685109ba..8a3a67fe8 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -71,7 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (
{mergedIndexingStates.map((state) => { - return ; + return ; })}
); diff --git a/gui/src/components/indexing/DocsIndexingPeeks.tsx b/gui/src/components/indexing/DocsIndexingPeeks.tsx new file mode 100644 index 000000000..d63012865 --- /dev/null +++ b/gui/src/components/indexing/DocsIndexingPeeks.tsx @@ -0,0 +1,83 @@ +import { useDispatch, useSelector } from "react-redux"; + +import { IndexingStatus } from "core"; +import { useMemo } from "react"; +import { useNavigate } from "react-router-dom"; +import { ArrowPathIcon } from "@heroicons/react/24/outline"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; + +export interface DocsIndexingPeekProps { + status: IndexingStatus; +} + +function DocsIndexingPeek({ status }: DocsIndexingPeekProps) { + const navigate = useNavigate(); + const dispatch = useDispatch(); + + const progressPercentage = useMemo(() => { + return Math.min(100, Math.max(0, status.progress * 100)); + }, [status.progress]); + + return ( +
{ + navigate("/more"); + dispatch(setShowDialog(false)); + dispatch(setDialogMessage(undefined)); + }} + > +

+ {status.title} +

+
+
+
+
+ + {progressPercentage.toFixed(0)}% + + {/* */} +
+
+ ); +} + +interface DocsIndexingPeeksProps { + statuses: IndexingStatus[]; +} + +function DocsIndexingPeekList({ statuses }: DocsIndexingPeeksProps) { + const config = useSelector((store: RootState) => store.state.config); + const configDocs = config.docs ?? []; + // const docs + return ( +
+

+ Currently Indexing: +

+
+ {statuses.length ? ( + statuses.map((status) => { + return ; + }) + ) : ( +

None

+ )} +
+
+ ); +} + +export default DocsIndexingPeekList; diff --git a/gui/src/components/indexing/IndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx similarity index 68% rename from gui/src/components/indexing/IndexingStatus.tsx rename to gui/src/components/indexing/DocsIndexingStatus.tsx index 6fe72c741..4fb5013cd 100644 --- a/gui/src/components/indexing/IndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -1,6 +1,6 @@ -import { IndexingStatus } from "core"; +import { IndexingStatus, SiteIndexingConfig } from "core"; import { PropsWithChildren, useContext, useMemo } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { usePostHog } from "posthog-js/react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { @@ -12,9 +12,10 @@ import { XMarkIcon, } from "@heroicons/react/24/outline"; import { updateIndexingStatus } from "../../redux/slices/stateSlice"; +import { RootState } from "../../redux/store"; interface IndexingStatusViewerProps { - status: IndexingStatus; + docConfig: SiteIndexingConfig; } const STATUS_TO_ICON: Record = { @@ -27,33 +28,43 @@ const STATUS_TO_ICON: Record = { failed: XMarkIcon, // Since we show an erorr message below }; -function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { +function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); const posthog = usePostHog(); const dispatch = useDispatch(); + // const status = undefined; + const status = useSelector( + (store: RootState) => store.state.indexing.statuses[docConfig.startUrl], + ); + const reIndex = () => ideMessenger.post("indexing/reindex", { - type: status.type, - id: status.id, + type: "docs", + id: docConfig.startUrl, }); const abort = () => { ideMessenger.post("indexing/abort", { - type: status.type, - id: status.id, + type: "docs", + id: docConfig.startUrl, }); // Optimistic abort status - dispatch( - updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), - ); + if (status) { + dispatch( + updateIndexingStatus({ ...status, status: "aborted", progress: 0 }), + ); + } }; const progressPercentage = useMemo(() => { + if (!status) { + return 0; + } return Math.min(100, Math.max(0, status.progress * 100)); - }, [status.progress]); + }, [status?.progress]); - const Icon = STATUS_TO_ICON[status.status]; + const Icon = STATUS_TO_ICON[status?.status]; return (
@@ -62,24 +73,26 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { className={`flex flex-row items-center justify-between gap-2 text-sm`} >
{ - if (status.url) { + if (status?.url) { ideMessenger.post("openUrl", status.url); } }} > - {status.icon ? ( - doc icon + {docConfig.faviconUrl ? ( + doc icon ) : null}

- {status.title ?? status.id} + {docConfig.title ?? docConfig.startUrl}

- {!!status.url && ( - - )} +
- {status.status === "pending" ? ( + {status?.status === "pending" ? (
Pending...
) : (
@@ -87,7 +100,7 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { {Icon ? ( ) : null} @@ -98,7 +111,7 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) {
{}, deleted: () => {}, pending: () => {}, - }[status.status] + }[status?.status] } > { @@ -130,18 +143,16 @@ function IndexingStatusViewer({ status }: IndexingStatusViewerProps) { paused: "", deleted: "", pending: "", - }[status.status] + }[status?.status] } - {/* {status.status === "indexing" && ( */} - {status.description} + {status?.description} - {/* )} */}
); } -export default IndexingStatusViewer; +export default DocsIndexingStatus; diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx new file mode 100644 index 000000000..84fdba903 --- /dev/null +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -0,0 +1,57 @@ +import { useMemo } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "./DocsIndexingStatus"; +import { SecondaryButton } from ".."; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import AddDocsDialog from "../dialogs/AddDocsDialog"; +import DocsIndexingStatus from "./DocsIndexingStatus"; + +function DocsIndexingStatuses() { + const dispatch = useDispatch(); + const config = useSelector((store: RootState) => store.state.config); + const configDocs = config.docs ?? []; + + // const indexingStatuses = useSelector( + // (store: RootState) => store.state.indexing.statuses, + // ); + // const docsStatuses = useMemo(() => { + // const docs = Object.values(indexingStatuses).filter( + // (status) => status.type === "docs" && status.status !== "deleted", + // ); + // return docs; + // }, [indexingStatuses]); + + return ( +
+
+

@docs indexes

+ {configDocs.length ? ( + { + dispatch(setShowDialog(true)); + dispatch(setDialogMessage()); + }} + > + Add + + ) : null} +
+ + Manage your documentation sources + +
+ {configDocs.map((doc) => { + return ; + })} +
+
+ ); +} + +export default DocsIndexingStatuses; diff --git a/gui/src/components/indexing/IndexingStatuses.tsx b/gui/src/components/indexing/IndexingStatuses.tsx deleted file mode 100644 index 7441212f9..000000000 --- a/gui/src/components/indexing/IndexingStatuses.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; -import IndexingStatusViewer from "./IndexingStatus"; -import { Button, SecondaryButton } from ".."; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; -import AddDocsDialog from "../dialogs/AddDocsDialog"; - -function IndexingStatuses() { - const indexingStatuses = useSelector( - (store: RootState) => store.state.indexing.statuses, - ); - const docsStatuses = useMemo(() => { - const docs = Object.values(indexingStatuses).filter( - (status) => status.type === "docs" && status.status !== "deleted", - ); - return docs; - }, [indexingStatuses]); - const dispatch = useDispatch(); - - return ( -
-
-

@docs indexes

- {/*
- -
*/} - {/* TODO add some way to hide, scroll, etc. */} -
- - Manage your documentation sources - - {/*
*/} - {docsStatuses.length ? ( - docsStatuses.map((status) => { - return ; - }) - ) : ( - { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - }} - > - Add Docs - - )} -
- //
- ); -} - -export default IndexingStatuses; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 49e3196de..dae812dcf 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -382,7 +382,6 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { ) : ( <> {subMenuTitle && {subMenuTitle}} - {/* */} {allItems.length ? ( allItems.map((item, index) => ( { height="20px" width="20px" filename={item.description} - > + /> )} {!showFileIconForItem(item) && ( <> @@ -414,7 +413,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
{ - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }) - : undefined, + Mention.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }), isInEditMode ? AddCodeToEdit.configure({ HTMLAttributes: { @@ -594,7 +588,7 @@ function TipTapEditor(props: TipTapEditorProps) { if (isOSREnabled) { handleJetBrainsOSRMetaKeyIssues(e, editor); - } else { + } else if (!isJetBrains()) { await handleVSCMetaKeyIssues(e, editor); } }; @@ -653,6 +647,8 @@ function TipTapEditor(props: TipTapEditorProps) { useWebviewListener( "focusContinueInput", async (data) => { + dispatch(clearCodeToEdit()); + if (!props.isMainInput) { return; } @@ -818,13 +814,6 @@ function TipTapEditor(props: TipTapEditorProps) { const [activeKey, setActiveKey] = useState(null); - useEffect(() => { - if (shouldAddFileForEditing && props.isMainInput) { - insertCharacterWithWhitespace("#"); - dispatch(setShouldAddFileForEditing(false)); - } - }, [shouldAddFileForEditing]); - const insertCharacterWithWhitespace = useCallback( (char: string) => { const text = editor.getText(); diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index 21fafc2f5..c316e769f 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -8,7 +8,7 @@ import { import { defaultBorderRadius, vscEditorBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { isJetBrains } from "../../util"; -import { isTerminalCodeBlock } from "./utils"; +import { isTerminalCodeBlock, getTerminalCommand } from "./utils"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { CopyIconButton } from "../gui/CopyIconButton"; import useUIConfig from "../../hooks/useUIConfig"; @@ -88,6 +88,12 @@ export default function StepContainerPreActionButtons({ }); } + async function onClickRunTerminal(): Promise { + if (shouldRunTerminalCmd) { + return ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent)); + } + } + // Handle apply keyboard shortcut useWebviewListener( "applyCodeFromChat", @@ -120,7 +126,7 @@ export default function StepContainerPreActionButtons({ diff --git a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx index 1f37407be..2b256929f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx @@ -17,7 +17,7 @@ export default function GeneratingCodeLoader({ return ( - {showLineCount ? linesGeneratedText : "Generating..."} + {showLineCount ? linesGeneratedText : "Generating"} ); diff --git a/gui/src/components/svg/DiscordIcon.tsx b/gui/src/components/svg/DiscordIcon.tsx new file mode 100644 index 000000000..8e46b3ccb --- /dev/null +++ b/gui/src/components/svg/DiscordIcon.tsx @@ -0,0 +1,27 @@ +interface DiscordIconProps extends React.SVGProps { + size?: number; +} + +export function DiscordIcon({ + size = 24, + className, + ...props +}: DiscordIconProps) { + return ( + + + + ); +} diff --git a/gui/src/components/svg/GithubIcon.tsx b/gui/src/components/svg/GithubIcon.tsx new file mode 100644 index 000000000..13a258305 --- /dev/null +++ b/gui/src/components/svg/GithubIcon.tsx @@ -0,0 +1,27 @@ +interface GithubIconProps extends React.SVGProps { + size?: number; +} + +export function GithubIcon({ + size = 24, + className, + ...props +}: GithubIconProps) { + return ( + + + + ); +} diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 43fc7ef56..bddd3fbbe 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -138,13 +138,13 @@ export class IdeMessenger implements IIdeMessenger { const handler = (event: any) => { if (event.data.messageId === messageId) { window.removeEventListener("message", handler); - resolve(event.data.data); + resolve(event.data.data as WebviewMessengerResult); } }; window.addEventListener("message", handler); this.post(messageType, data, messageId); - }) as any; + }); } async *streamRequest( diff --git a/gui/src/context/SubmenuContextProviders.ts b/gui/src/context/SubmenuContextProviders.ts index 5be351a08..e25efe14c 100644 --- a/gui/src/context/SubmenuContextProviders.ts +++ b/gui/src/context/SubmenuContextProviders.ts @@ -1,11 +1,15 @@ import { ContextSubmenuItem } from "core"; import { createContext } from "react"; +export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem { + providerTitle: string; +} + export const SubmenuContextProvidersContext = createContext<{ getSubmenuContextItems: ( providerTitle: string | undefined, query: string, - ) => (ContextSubmenuItem & { providerTitle: string })[]; + ) => ContextSubmenuItemWithProvider[]; addItem: (providerTitle: string, item: ContextSubmenuItem) => void; }>({ getSubmenuContextItems: () => [], diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index bfbbb353f..32bee26e0 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,14 +1,14 @@ import { Dispatch } from "@reduxjs/toolkit"; -import { PersistedSessionInfo, SessionInfo } from "core"; +import { Session, SessionMetadata } from "core"; +import { renderChatMessage } from "core/util/messageContent"; import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession, updateSessionTitle } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { renderChatMessage } from "core/util/messageContent"; const MAX_TITLE_LENGTH = 100; @@ -20,7 +20,13 @@ function truncateText(text: string, maxLength: number) { } function useHistory(dispatch: Dispatch) { - const state = useSelector((state: RootState) => state.state); + const sessionId = useSelector((store: RootState) => store.state.sessionId); + const config = useSelector((store: RootState) => store.state.config); + const history = useSelector((store: RootState) => store.state.history); + const checkpoints = useSelector( + (store: RootState) => store.state.checkpoints, + ); + const title = useSelector((store: RootState) => store.state.title); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -32,7 +38,7 @@ function useHistory(dispatch: Dispatch) { async function getHistory( offset?: number, limit?: number, - ): Promise { + ): Promise { const result = await ideMessenger.request("history/list", { offset, limit, @@ -49,24 +55,18 @@ function useHistory(dispatch: Dispatch) { } async function saveSession(openNewSession: boolean = true) { - if (state.history.length === 0) return; + if (history.length === 0) return; - const stateCopy = { ...state }; - if (openNewSession) { - dispatch(newSession()); - updateLastSessionId(stateCopy.sessionId); - } - await new Promise((resolve) => setTimeout(resolve, 10)); - - if (state.config?.ui?.getChatTitles && stateCopy.title === "New Session") { + let currentTitle = title; + if (config?.ui?.getChatTitles && currentTitle === "New Session") { try { // Check if we have first assistant response - let assistantResponse = stateCopy.history + let assistantResponse = history ?.filter((h) => h.message.role === "assistant")[0] ?.message?.content?.toString(); if (assistantResponse) { - stateCopy.title = await getChatTitle(assistantResponse); + currentTitle = await getChatTitle(assistantResponse); } } catch (e) { throw new Error("Unable to get chat title"); @@ -74,31 +74,38 @@ function useHistory(dispatch: Dispatch) { } // Fallback if we get an error above or if the user has not set getChatTitles - let title = - stateCopy.title === "New Session" + let newTitle = + currentTitle === "New Session" ? truncateText( - renderChatMessage(stateCopy.history[0].message) + renderChatMessage(history[0].message) .split("\n") .filter((l) => l.trim() !== "") .slice(-1)[0] || "", MAX_TITLE_LENGTH, ) - : stateCopy.title?.length > 0 - ? stateCopy.title - : (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page. + : currentTitle?.length > 0 + ? currentTitle + : (await getSession(sessionId)).title; // to ensure titles are synced with updates from history page. - const sessionInfo: PersistedSessionInfo = { - history: stateCopy.history, - title: title, - sessionId: stateCopy.sessionId, + const session: Session = { + sessionId, + title: newTitle, workspaceDirectory: window.workspacePaths?.[0] || "", - checkpoints: stateCopy.checkpoints, + history, + checkpoints, }; - return await ideMessenger.request("history/save", sessionInfo); + await ideMessenger.request("history/save", session); + + if (openNewSession) { + dispatch(newSession()); + updateLastSessionId(sessionId); + } else { + dispatch(updateSessionTitle(newTitle)); + } } - async function getSession(id: string): Promise { + async function getSession(id: string): Promise { const result = await ideMessenger.request("history/load", { id }); if (result.status === "error") { throw new Error(result.error); @@ -106,16 +113,16 @@ function useHistory(dispatch: Dispatch) { return result.content; } - async function updateSession(sessionInfo: PersistedSessionInfo) { - return await ideMessenger.request("history/save", sessionInfo); + async function updateSession(session: Session) { + return await ideMessenger.request("history/save", session); } async function deleteSession(id: string) { return await ideMessenger.request("history/delete", { id }); } - async function loadSession(id: string): Promise { - updateLastSessionId(state.sessionId); + async function loadSession(id: string): Promise { + updateLastSessionId(sessionId); const result = await ideMessenger.request("history/load", { id }); if (result.status === "error") { throw new Error(result.error); @@ -126,7 +133,7 @@ function useHistory(dispatch: Dispatch) { return sessionContent; } - async function loadLastSession(): Promise { + async function loadLastSession(): Promise { const lastSessionId = getLocalStorage("lastSessionId"); if (lastSessionId) { return await loadSession(lastSessionId); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 19588c94e..866ebd0a1 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -10,6 +10,7 @@ import { setInactive, setSelectedProfileId, setTTSActive, + updateDocsSuggestions, updateIndexingStatus, } from "../redux/slices/stateSlice"; import { AppDispatch, RootState } from "../redux/store"; @@ -51,9 +52,12 @@ function useSetup(dispatch: AppDispatch) { loadConfig(); const interval = setInterval(() => { if (initialConfigLoad.current) { + // Docs init on config load + ideMessenger.post("docs/getSuggestedDocs", undefined); + ideMessenger.post("docs/initStatuses", undefined); + // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); - ideMessenger.post("indexing/initStatuses", undefined); return; } loadConfig(); @@ -113,6 +117,10 @@ function useSetup(dispatch: AppDispatch) { } }, []); + useWebviewListener("docs/suggestions", async (data) => { + dispatch(updateDocsSuggestions(data)); + }); + const defaultModelTitle = useSelector( (store: RootState) => store.state.defaultModelTitle, ); diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx deleted file mode 100644 index 26cb145d4..000000000 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { removeCodeToEdit } from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; -import CodeToEditListItem from "./CodeToEditListItem"; - -import { CodeToEdit, RangeInFileWithContents } from "core"; -import AddFileButton from "./AddFileButton"; - -export default function WorkingSet() { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const editModeState = useSelector((state: RootState) => state.editModeState); - - const hasCodeToEdit = editModeState.codeToEdit.length > 0; - - const title = - editModeState.codeToEdit.length === 0 - ? "Code to edit" - : editModeState.codeToEdit.length === 1 - ? "Code to edit (1 item)" - : `Code to edit (${editModeState.codeToEdit.length} items)`; - - function onDelete(rif: RangeInFileWithContents) { - dispatch(removeCodeToEdit(rif)); - } - - function onClickFilename(code: CodeToEdit) { - if ("range" in code) { - ideMessenger.ide.showLines( - code.filepath, - code.range.start.line, - code.range.end.line, - ); - } else { - ideMessenger.ide.openFile(code.filepath); - } - } - - const codeToEditItems = [...editModeState.codeToEdit] - .reverse() - .map((code, i) => ( - - )); - - return ( -
-
- {title} - -
- - {hasCodeToEdit && ( -
    - {codeToEditItems} -
- )} -
- ); -} diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index e743a3834..81648b41b 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -15,7 +15,7 @@ import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; -import IndexingStatuses from "../../components/indexing/IndexingStatuses"; +import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses"; function MorePage() { useNavigationListener(); @@ -52,7 +52,7 @@ function MorePage() {
- +
diff --git a/gui/src/pages/Edit/AddFileButton.tsx b/gui/src/pages/edit/AddFileButton.tsx similarity index 53% rename from gui/src/pages/Edit/AddFileButton.tsx rename to gui/src/pages/edit/AddFileButton.tsx index 2f9e0f0dd..8e8096eab 100644 --- a/gui/src/pages/Edit/AddFileButton.tsx +++ b/gui/src/pages/edit/AddFileButton.tsx @@ -1,27 +1,29 @@ -import { useContext, useState, useRef, useEffect } from "react"; +import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; import { useDispatch } from "react-redux"; import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; import { addCodeToEdit } from "../../redux/slices/editModeState"; import { Listbox } from "@headlessui/react"; -export default function AddFileButton() { +export interface AddFileButtonProps { + onClick: () => void; +} + +export default function AddFileButton({ onClick }: AddFileButtonProps) { const buttonRef = useRef(null); const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - function onClickAddFileToCodeToEdit() { - dispatch(setShouldAddFileForEditing(true)); - } - async function handleAddAllOpenFiles() { const openFiles = await ideMessenger.ide.getOpenFiles(); + const filesData = await Promise.all( + openFiles.map(async (filepath) => { + const contents = await ideMessenger.ide.readFile(filepath); + return { filepath, contents }; + }), + ); - for (const filepath of openFiles) { - const contents = await ideMessenger.ide.readFile(filepath); - dispatch(addCodeToEdit({ filepath, contents })); - } + dispatch(addCodeToEdit(filesData)); } return ( @@ -29,14 +31,14 @@ export default function AddFileButton() {
{ e.preventDefault(); e.stopPropagation(); - onClickAddFileToCodeToEdit(); + onClick(); }} > @@ -45,17 +47,15 @@ export default function AddFileButton() {
-
+
- + Add all open files diff --git a/gui/src/pages/edit/AddFileCombobox.tsx b/gui/src/pages/edit/AddFileCombobox.tsx new file mode 100644 index 000000000..3750a448e --- /dev/null +++ b/gui/src/pages/edit/AddFileCombobox.tsx @@ -0,0 +1,130 @@ +import { useState, useContext, useEffect, useRef } from "react"; +import { + ContextSubmenuItemWithProvider, + SubmenuContextProvidersContext, +} from "../../context/SubmenuContextProviders"; +import { Combobox } from "@headlessui/react"; +import FileIcon from "../../components/FileIcon"; +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; + +export interface AddFileComboboxProps { + onSelect: (filepaths: string[]) => void; + onEscape: () => void; +} + +export default function AddFileCombobox({ + onSelect, + onEscape, +}: AddFileComboboxProps) { + const [query, setQuery] = useState(""); + const [selectedFiles, setSelectedFiles] = useState< + ContextSubmenuItemWithProvider[] + >([]); + + const inputRef = useRef(null); + const buttonRef = useRef(null); + const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext); + const allFiles = getSubmenuContextItems("file", ""); + const codeToEdit = useSelector( + (state: RootState) => state.editModeState.codeToEdit, + ); + const remainingFiles = allFiles.filter( + (file) => !codeToEdit.find((code) => code.filepath === file.id), + ); + + useEffect(() => { + if (inputRef.current) { + inputRef.current.focus(); + } + }, []); + + const filteredFiles = + query === "" + ? remainingFiles + : remainingFiles.filter((file) => + file.title.toLowerCase().includes(query.toLowerCase()), + ); + + return ( +
+ { + setSelectedFiles(files); + onSelect(files.map((file) => file.id)); + buttonRef.current?.click(); + }} + > + {({ open }) => ( +
+ + { + if (!open) { + buttonRef.current?.click(); + } + }} + onFocus={() => { + buttonRef.current?.click(); + }} + className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 focus:outline-none" + onChange={(event) => setQuery(event.target.value)} + placeholder="Type to search files..." + onKeyDown={(e) => { + if (e.key === "Escape" && !open) { + onEscape(); + } + }} + /> + + + {filteredFiles.length > 0 ? ( + filteredFiles.map((file) => ( + + `relative flex w-full cursor-pointer px-2 py-1 text-left text-xs ${ + active + ? "bg-vsc-list-active-background text-vsc-list-active-foreground" + : "" + }` + } + > + {({ active, selected }) => ( +
+
+ + {file.title} +
+ + + {file.description} + +
+ )} +
+ )) + ) : ( +
+ No results +
+ )} +
+
+ )} +
+
+ ); +} diff --git a/gui/src/pages/edit/CodeToEdit.tsx b/gui/src/pages/edit/CodeToEdit.tsx new file mode 100644 index 000000000..659255942 --- /dev/null +++ b/gui/src/pages/edit/CodeToEdit.tsx @@ -0,0 +1,97 @@ +import { useContext, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { + removeCodeToEdit, + addCodeToEdit, +} from "../../redux/slices/editModeState"; +import { RootState } from "../../redux/store"; +import CodeToEditListItem from "./CodeToEditListItem"; +import { CodeToEdit, RangeInFileWithContents } from "core"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import { XMarkIcon } from "@heroicons/react/24/outline"; + +export default function WorkingSet() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const [showAddFileCombobox, setShowAddFileCombobox] = useState(false); + const codeToEdit = useSelector( + (state: RootState) => state.editModeState.codeToEdit, + ); + + const title = + codeToEdit.length === 0 + ? "Code to edit" + : codeToEdit.length === 1 + ? "Code to edit (1 item)" + : `Code to edit (${codeToEdit.length} items)`; + + function onDelete(rif: RangeInFileWithContents) { + dispatch(removeCodeToEdit(rif)); + } + + function onClickFilename(code: CodeToEdit) { + if ("range" in code) { + ideMessenger.ide.showLines( + code.filepath, + code.range.start.line, + code.range.end.line, + ); + } else { + ideMessenger.ide.openFile(code.filepath); + } + } + + async function onSelectFilesToAdd(filepaths: string[]) { + const filePromises = filepaths.map(async (filepath) => { + const contents = await ideMessenger.ide.readFile(filepath); + return { contents, filepath }; + }); + + const fileResults = await Promise.all(filePromises); + + for (const file of fileResults) { + dispatch(addCodeToEdit(file)); + } + } + + return ( +
+
+ {title} + setShowAddFileCombobox(true)} /> +
+ + {codeToEdit.length > 0 && ( +
    + {codeToEdit.map((code, i) => ( + + ))} +
+ )} + + {showAddFileCombobox && ( +
+
+ setShowAddFileCombobox(false)} + /> +
+ { + setShowAddFileCombobox(false); + }} + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" + /> +
+ )} +
+ ); +} diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/edit/CodeToEditListItem.tsx similarity index 87% rename from gui/src/pages/Edit/CodeToEditListItem.tsx rename to gui/src/pages/edit/CodeToEditListItem.tsx index 8d84ef34b..d2cdb638d 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/edit/CodeToEditListItem.tsx @@ -40,7 +40,10 @@ export default function CodeToEditListItem({ let title = filepath; if ("range" in code) { - title += ` (${code.range.start.line + 1} - ${code.range.end.line + 1})`; + const start = code.range.start.line + 1; + const end = code.range.end.line + 1; + title += + start === end ? ` - Inserting at line ${start}` : ` (${start} - ${end})`; } const source = @@ -53,11 +56,11 @@ export default function CodeToEditListItem({ return (
  • setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} >
    {showCodeSnippet ? ( @@ -88,7 +91,7 @@ export default function CodeToEditListItem({ {title}
    -
    +
    { e.stopPropagation(); @@ -98,6 +101,7 @@ export default function CodeToEditListItem({ />
    + {showCodeSnippet && (
    diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/edit/Edit.tsx similarity index 100% rename from gui/src/pages/Edit/Edit.tsx rename to gui/src/pages/edit/Edit.tsx diff --git a/gui/src/pages/Edit/getMultifileEditPrompt.ts b/gui/src/pages/edit/getMultifileEditPrompt.ts similarity index 100% rename from gui/src/pages/Edit/getMultifileEditPrompt.ts rename to gui/src/pages/edit/getMultifileEditPrompt.ts diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx index 885043989..d00dd533d 100644 --- a/gui/src/pages/error.tsx +++ b/gui/src/pages/error.tsx @@ -1,37 +1,80 @@ import { useDispatch } from "react-redux"; import { useNavigate, useRouteError } from "react-router-dom"; import { newSession } from "../redux/slices/stateSlice"; -import ContinueButton from "../components/mainInput/ContinueButton"; -import { vscBackground } from "../components"; +import { GithubIcon } from "../components/svg/GithubIcon"; +import { DiscordIcon } from "../components/svg/DiscordIcon"; +import { useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { Button, SecondaryButton } from "../components"; +import { ArrowPathIcon, FlagIcon } from "@heroicons/react/24/outline"; -export default function ErrorPage() { +const GITHUB_LINK = "https://github.com/continuedev/continue/issues/new/choose"; +const DISCORD_LINK = "https://discord.com/invite/EfJEfdFnDQ"; + +const ErrorPage: React.FC = () => { const error: any = useRouteError(); console.error(error); const dispatch = useDispatch(); const navigate = useNavigate(); + const messenger = useContext(IdeMessengerContext); + const openUrl = (url: string) => { + if (messenger) { + messenger.post("openUrl", url); + } + }; + + const [initialLoad, setInitialLoad] = useState(true); + useEffect(() => { + setTimeout(() => { + setInitialLoad(false); + }, 500); + }, []); return ( -
    -

    Error in Continue React App

    -

    - {error.statusText || error.message} -

    -
    -

    Click below to Continue

    -
    - +

    Error in Continue UI

    + +
    +        {error.statusText || error.message}
    +      
    + + + +

    Report the issue:

    +
    + openUrl(GITHUB_LINK)} + className="flex items-center space-x-2 rounded-lg px-4 py-2 text-white" + > + + + openUrl(DISCORD_LINK)} + className="flex items-center rounded-lg" + > + + +
    ); -} +}; + +export default ErrorPage; diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index 489bc7b41..79db2a804 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -24,13 +24,21 @@ export const editModeStateSlice = createSlice({ name: "editModeState", initialState, reducers: { - addCodeToEdit: (state, { payload }: PayloadAction) => { - const entryExists = state.codeToEdit.some((entry) => - isCodeToEditEqual(entry, payload), + addCodeToEdit: ( + state, + { payload }: PayloadAction, + ) => { + const entries = Array.isArray(payload) ? payload : [payload]; + + const newEntries = entries.filter( + (entry) => + !state.codeToEdit.some((existingEntry) => + isCodeToEditEqual(existingEntry, entry), + ), ); - if (!entryExists) { - state.codeToEdit.push(payload); + if (newEntries.length > 0) { + state.codeToEdit.push(...newEntries); } }, focusEdit: (state) => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index d0f3e0790..f3b71c060 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -13,8 +13,9 @@ import { ContextItemWithId, FileSymbolMap, IndexingStatus, - PersistedSessionInfo, + PackageDocsResult, PromptLog, + Session, ToolCall, } from "core"; import { BrowserSerializedContinueConfig } from "core/config/load"; @@ -53,9 +54,10 @@ type State = { nextCodeBlockToApplyIndex: number; indexing: { hiddenChatPeekTypes: Record; - statuses: Record; + statuses: Record; // status id -> status }; streamAborter: AbortController; + docsSuggestions: PackageDocsResult[]; }; const initialState: State = { @@ -97,6 +99,7 @@ const initialState: State = { }, }, streamAborter: new AbortController(), + docsSuggestions: [], }; export const stateSlice = createSlice({ @@ -365,10 +368,7 @@ export const stateSlice = createSlice({ } } }, - newSession: ( - state, - { payload }: PayloadAction, - ) => { + newSession: (state, { payload }: PayloadAction) => { state.streamAborter.abort(); state.streamAborter = new AbortController(); @@ -390,6 +390,9 @@ export const stateSlice = createSlice({ state.curCheckpointIndex = 0; } }, + updateSessionTitle: (state, { payload }: PayloadAction) => { + state.title = payload; + }, addHighlightedCode: ( state, { @@ -535,6 +538,12 @@ export const stateSlice = createSlice({ [payload.type]: payload.hidden, }; }, + updateDocsSuggestions: ( + state, + { payload }: PayloadAction, + ) => { + state.docsSuggestions = payload; + }, }, extraReducers: (builder) => { @@ -560,6 +569,7 @@ export const { setInactive, streamUpdate, newSession, + updateSessionTitle, resubmitAtIndex, addHighlightedCode, setDefaultModel, @@ -586,6 +596,7 @@ export const { cancelToolCall, acceptToolCall, setToolGenerated, + updateDocsSuggestions, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index 268815ae4..499a78d7b 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -64,13 +64,6 @@ export const uiStateSlice = createSlice({ setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, - setShouldAddFileForEditing: ( - state, - action: PayloadAction, - ) => { - state.shouldAddFileForEditing = action.payload; - }, - // Tools toggleUseTools: (state) => { state.useTools = !state.useTools; @@ -101,7 +94,6 @@ export const { setDialogMessage, setDialogEntryOn, setShowDialog, - setShouldAddFileForEditing, toggleUseTools, toggleToolSetting, } = uiStateSlice.actions; diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index df3f2b218..409004e08 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -106,9 +106,11 @@ export const gatherContext = createAsyncThunk< ); if (promptPreamble) { - typeof content === "string" - ? (content += promptPreamble) - : (content.at(-1).text += promptPreamble); + if (typeof content === "string") { + content = promptPreamble + content; + } else { + content[0].text = promptPreamble + content[0].text; + } } // dispatch(addContextItems(contextItems)); diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts index 25f3066e7..6d7afb632 100644 --- a/gui/src/redux/thunks/handleErrors.ts +++ b/gui/src/redux/thunks/handleErrors.ts @@ -11,10 +11,6 @@ export const handleErrors = createAsyncThunk< await runStream(); } catch (e: any) { console.debug("Error streaming response: ", e); - extra.ideMessenger.post("showToast", [ - "error", - `Error streaming response: ${e.message}`, - ]); } finally { dispatch(setInactive()); // triggerSave(!save); TODO diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 7ec8df9e8..c837eea75 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -51,6 +51,11 @@ module.exports = { "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", "vsc-find-match-selected": "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", + "vsc-foreground-muted": "var(--vscode-foreground-muted, #999)", + "vsc-description-foreground": + "var(--vscode-descriptionForeground, #999)", + "vsc-input-placeholder-foreground": + "var(--vscode-input-placeholderForeground, #999)", }, }, }, diff --git a/manual-testing-sandbox/test.java b/manual-testing-sandbox/Calculator.java similarity index 99% rename from manual-testing-sandbox/test.java rename to manual-testing-sandbox/Calculator.java index 0f22df25a..b9b9147e9 100644 --- a/manual-testing-sandbox/test.java +++ b/manual-testing-sandbox/Calculator.java @@ -11,6 +11,7 @@ public class Calculator { return this; } + public double getResult() { return result; } diff --git a/manual-testing-sandbox/nested-folder/package.json b/manual-testing-sandbox/nested-folder/package.json new file mode 100644 index 000000000..5bcec0c8f --- /dev/null +++ b/manual-testing-sandbox/nested-folder/package.json @@ -0,0 +1,45 @@ +{ + "name": "my-react-project", + "version": "1.0.0", + "description": "A React project using Radix UI for accessible components", + "main": "index.js", + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "keywords": [ + "react", + "radix-ui", + "accessibility", + "frontend" + ], + "author": "Your Name", + "license": "MIT", + "dependencies": { + "@radix-ui/react-accordion": "^1.0.0", + "@radix-ui/react-alert-dialog": "^1.0.0", + "@radix-ui/react-checkbox": "^1.0.0", + "react": "^18.0.0", + "react-dom": "^18.0.0", + "react-scripts": "^5.0.0" + }, + "devDependencies": { + "@types/react": "^18.0.0", + "@types/react-dom": "^18.0.0", + "typescript": "^4.5.0" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt new file mode 100644 index 000000000..87f2e654b --- /dev/null +++ b/manual-testing-sandbox/requirements.txt @@ -0,0 +1,57 @@ +# Core packages +numpy==1.21.2 +pandas==1.3.3 +scipy==1.7.1 + +# Web development +flask==2.0.2 +django==3.2.7 + +# Request handling +requests==2.26.0 +httpx==0.19.0 + +# Machine Learning +scikit-learn==0.24.2 +tensorflow==2.6.0 + +# Data visualization +matplotlib==3.4.3 +seaborn==0.11.2 +plotly==5.3.1 + +# Natural Language Processing +nltk==3.6.3 +spacy==3.1.2 + +# Deep Learning +torch==1.9.1 +keras==2.6.0 + +# Image processing +pillow==8.3.2 +opencv-python==4.5.3.56 + +# Data handling and manipulation +beautifulsoup4==4.10.0 +sqlalchemy==1.4.25 +xlrd==2.0.1 +openpyxl==3.0.9 + +# Utilities +pyyaml==5.4.1 +python-dotenv==0.19.0 + +# Testing +pytest==6.2.5 + +# Logging and Debugging +loguru==0.5.3 + +# Asynchronous Programming +aiohttp==3.7.4 + +# Others +jupyter==1.0.0 +gunicorn==20.1.0 +psycopg2==2.9.1 \ No newline at end of file diff --git a/manual-testing-sandbox/testCalculator.js b/manual-testing-sandbox/testCalculator.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/package.json b/package.json index e5dbe76f2..3009e5d12 100644 --- a/package.json +++ b/package.json @@ -2,11 +2,7 @@ "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", - "husky": "^9.1.7", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" - }, - "scripts": { - "prepare": "husky" } } diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 876115d11..2170a116b 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -130,7 +130,6 @@ export type UiOptions = z.infer; export const tabAutocompleteOptionsSchema = z.object({ disable: z.boolean(), - useCopyBuffer: z.boolean(), useFileSuffix: z.boolean(), maxPromptTokens: z.number(), debounceDelay: z.number(), @@ -141,14 +140,9 @@ export const tabAutocompleteOptionsSchema = z.object({ multilineCompletions: z.enum(["always", "never", "auto"]), slidingWindowPrefixPercentage: z.number(), slidingWindowSize: z.number(), - maxSnippetPercentage: z.number(), - maxDiffPercentage: z.number(), - maxClipboardPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), - useOtherFiles: z.boolean(), useRecentlyEdited: z.boolean(), - recentLinePrefixMatchMinLength: z.number(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), });