diff --git a/core/index.d.ts b/core/index.d.ts index dae7f2e36..fdee1f262 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -57,6 +57,7 @@ export interface IndexingProgressUpdate { | "disabled" | "cancelled"; debugInfo?: string; + warnings?: string[]; } // This is more or less a V2 of IndexingProgressUpdate for docs etc. diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index bf79b093e..d04eca7ee 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -35,7 +35,8 @@ type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; - artifactId = "codeSnippets"; + static artifactId = "codeSnippets"; + artifactId: string = CodeSnippetsCodebaseIndex.artifactId; constructor(private readonly ide: IDE) {} @@ -220,7 +221,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Compute for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; - let snippets: SnippetChunk[] = []; try { snippets = await this.getSnippetsInFile( diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index d2de0c512..e867399fd 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -48,6 +48,16 @@ export class CodebaseIndexer { private codebaseIndexingState: IndexingProgressUpdate; private readonly pauseToken: PauseToken; + private getUserFriendlyIndexName(artifactId: string): string { + if (artifactId === FullTextSearchCodebaseIndex.artifactId) + return "Full text search"; + if (artifactId === CodeSnippetsCodebaseIndex.artifactId) + return "Code snippets"; + if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking"; + if (artifactId.startsWith("vectordb")) return "Embedding"; + return artifactId; // fallback to original + } + // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, // e.g. a `SQLITE_BUSY` error. errorsRegexesToClearIndexesOn = [ @@ -314,6 +324,7 @@ export class CodebaseIndexer { status: "loading", }; const beginTime = Date.now(); + let collectedWarnings: string[] = []; for (const directory of dirs) { const dirBasename = getUriPathBasename(directory); @@ -344,45 +355,52 @@ export class CodebaseIndexer { const repoName = await this.ide.getRepoName(directory); let nextLogThreshold = 0; - try { - for await (const updateDesc of this.indexFiles( - directory, - directoryFiles, - branch, - repoName, - )) { - // Handle pausing in this loop because it's the only one really taking time - if (abortSignal.aborted) { - yield { - progress: 0, - desc: "Indexing cancelled", - status: "cancelled", - }; - return; - } - if (this.pauseToken.paused) { - yield* this.yieldUpdateAndPause(); - } - yield updateDesc; - if (updateDesc.progress >= nextLogThreshold) { - // log progress every 2.5% - nextLogThreshold += 0.025; - this.logProgress( - beginTime, - Math.floor(directoryFiles.length * updateDesc.progress), - updateDesc.progress, - ); - } + for await (const updateDesc of this.indexFiles( + directory, + directoryFiles, + branch, + repoName, + )) { + // Handle pausing in this loop because it's the only one really taking time + if (abortSignal.aborted) { + yield { + progress: 0, + desc: "Indexing cancelled", + status: "cancelled", + }; + return; + } + if (this.pauseToken.paused) { + yield* this.yieldUpdateAndPause(); + } + + // Collect warnings from indexFiles + if (updateDesc.warnings && updateDesc.warnings.length > 0) { + collectedWarnings = [...updateDesc.warnings]; + } + + yield updateDesc; + if (updateDesc.progress >= nextLogThreshold) { + // log progress every 2.5% + nextLogThreshold += 0.025; + this.logProgress( + beginTime, + Math.floor(directoryFiles.length * updateDesc.progress), + updateDesc.progress, + ); } - } catch (err) { - yield this.handleErrorAndGetProgressUpdate(err); - return; } } + + // Final completion message with preserved warnings yield { progress: 1, - desc: "Indexing Complete", + desc: + collectedWarnings.length > 0 + ? `Indexing completed with ${collectedWarnings.length} warning(s)` + : "Indexing Complete", status: "done", + warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined, }; this.logProgress(beginTime, 0, 1); } @@ -490,6 +508,8 @@ export class CodebaseIndexer { const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; + const warnings: string[] = []; + for (const codebaseIndex of indexesToBuild) { const tag: IndexTag = { directory, @@ -500,45 +520,101 @@ export class CodebaseIndexer { progress: progress, desc: `Planning changes for ${codebaseIndex.artifactId} index...`, status: "indexing", + warnings: warnings.length > 0 ? [...warnings] : undefined, }; - const [results, lastUpdated, markComplete] = - await getComputeDeleteAddRemove( - tag, - { ...stats }, - (filepath) => this.ide.readFile(filepath), - repoName, - ); - const totalOps = this.totalIndexOps(results); - let completedOps = 0; - // Don't update if nothing to update. Some of the indices might do unnecessary setup work - if (totalOps > 0) { - for (const subResult of this.batchRefreshIndexResults(results)) { - for await (const { desc } of codebaseIndex.update( + try { + const [results, lastUpdated, markComplete] = + await getComputeDeleteAddRemove( tag, - subResult, - markComplete, + { ...stats }, + (filepath) => this.ide.readFile(filepath), repoName, - )) { - yield { - progress, - desc, - status: "indexing", - }; - } - completedOps += - subResult.compute.length + - subResult.del.length + - subResult.addTag.length + - subResult.removeTag.length; - progress = - (completedIndexCount + completedOps / totalOps) * - (1 / indexesToBuild.length); - } - } + ); + const totalOps = this.totalIndexOps(results); + let completedOps = 0; - await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); - completedIndexCount += 1; + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (totalOps > 0) { + for (const subResult of this.batchRefreshIndexResults(results)) { + try { + for await (const { desc } of codebaseIndex.update( + tag, + subResult, + markComplete, + repoName, + )) { + yield { + progress, + desc, + status: "indexing", + warnings: warnings.length > 0 ? [...warnings] : undefined, + }; + } + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); + } catch (err) { + // Collect non-fatal errors as warnings and continue + const warningMsg = + err instanceof Error ? err.message : String(err); + const friendlyName = this.getUserFriendlyIndexName( + codebaseIndex.artifactId, + ); + warnings.push(`${friendlyName}: ${warningMsg}`); + console.warn(`${friendlyName}: ${warningMsg}`, err); + + // Complete this batch and continue with next + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); + } + } + } + + await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); + completedIndexCount += 1; + } catch (err) { + // Handle errors during planning phase + const cause = getRootCause(err as Error); + if (cause instanceof LLMError) { + // LLM errors are critical, re-throw them + throw cause; + } + + // Collect planning errors as warnings and continue to next index + const errorMsg = err instanceof Error ? err.message : String(err); + const friendlyName = this.getUserFriendlyIndexName( + codebaseIndex.artifactId, + ); + warnings.push(`${friendlyName}: ${errorMsg}`); + console.warn( + `Warning during ${codebaseIndex.artifactId} planning:`, + err, + ); + completedIndexCount += 1; + progress = completedIndexCount * (1 / indexesToBuild.length); + } + } + + // Final update with any collected warnings + if (warnings.length > 0) { + yield { + progress: 1, + desc: `Indexing completed with ${warnings.length} warning(s)`, + status: "done", + warnings: [...warnings], + }; } } diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 1bac74e4a..8016d04d3 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -55,7 +55,6 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.compute.length; i++) { const item = results.compute[i]; - // Insert chunks const chunks = await db.all( "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?", @@ -68,7 +67,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { [item.path, chunk.content], ); await db.run( - `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) + `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET path = excluded.path, diff --git a/core/indexing/README.md b/core/indexing/README.md index 2a7375f00..94bf196aa 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -20,10 +20,10 @@ The indexing process does the following: All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used. -`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file +`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 -`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` -`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. +`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex` +`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. ## Known problems diff --git a/core/llm/stream.ts b/core/llm/stream.ts deleted file mode 100644 index 5902ec114..000000000 --- a/core/llm/stream.ts +++ /dev/null @@ -1,114 +0,0 @@ -export async function* toAsyncIterable( - nodeReadable: NodeJS.ReadableStream, -): AsyncGenerator { - for await (const chunk of nodeReadable) { - // @ts-ignore - yield chunk as Uint8Array; - } -} - -export async function* streamResponse( - response: Response, -): AsyncGenerator { - if (response.status !== 200) { - throw new Error(await response.text()); - } - - if (!response.body) { - throw new Error("No response body returned."); - } - - // Get the major version of Node.js - const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10); - - if (nodeMajorVersion >= 20) { - // Use the new API for Node 20 and above - const stream = (ReadableStream as any).from(response.body); - for await (const chunk of stream.pipeThrough( - new TextDecoderStream("utf-8"), - )) { - yield chunk; - } - } else { - // Fallback for Node versions below 20 - // Streaming with this method doesn't work as version 20+ does - const decoder = new TextDecoder("utf-8"); - const nodeStream = response.body as unknown as NodeJS.ReadableStream; - for await (const chunk of toAsyncIterable(nodeStream)) { - yield decoder.decode(chunk, { stream: true }); - } - } -} - -function parseDataLine(line: string): any { - const json = line.startsWith("data: ") - ? line.slice("data: ".length) - : line.slice("data:".length); - - try { - const data = JSON.parse(json); - if (data.error) { - throw new Error(`Error streaming response: ${data.error}`); - } - - return data; - } catch (e) { - throw new Error(`Malformed JSON sent from server: ${json}`); - } -} - -function parseSseLine(line: string): { done: boolean; data: any } { - if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { - return { done: true, data: undefined }; - } - if (line.startsWith("data:")) { - return { done: false, data: parseDataLine(line) }; - } - if (line.startsWith(": ping")) { - return { done: true, data: undefined }; - } - return { done: false, data: undefined }; -} - -export async function* streamSse(response: Response): AsyncGenerator { - let buffer = ""; - for await (const value of streamResponse(response)) { - buffer += value; - - let position: number; - while ((position = buffer.indexOf("\n")) >= 0) { - const line = buffer.slice(0, position); - buffer = buffer.slice(position + 1); - - const { done, data } = parseSseLine(line); - if (done) { - break; - } - if (data) { - yield data; - } - } - } - - if (buffer.length > 0) { - const { done, data } = parseSseLine(buffer); - if (!done && data) { - yield data; - } - } -} - -export async function* streamJSON(response: Response): AsyncGenerator { - let buffer = ""; - for await (const value of streamResponse(response)) { - buffer += value; - - let position; - while ((position = buffer.indexOf("\n")) >= 0) { - const line = buffer.slice(0, position); - const data = JSON.parse(line); - yield data; - buffer = buffer.slice(position + 1); - } - } -} diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 7b21232d6..6d9319fd3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -39,7 +39,7 @@ type NextEditModelName = "mercury-coder-nextedit" | "this field is not used"; const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { template: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{userExcerpts}}}\`\`\`", + "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", }, "this field is not used": { template: "NEXT_EDIT", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index cf8b8f679..7ec001795 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": "1.1.54", + "version": "1.1.55", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgress.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgress.tsx index 7b80f7dde..6347409c1 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgress.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgress.tsx @@ -1,17 +1,18 @@ import { IndexingProgressUpdate } from "core"; +import { usePostHog } from "posthog-js/react"; import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { isJetBrains } from "../../../util"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import IndexingProgressBar from "./IndexingProgressBar"; -import IndexingProgressIndicator from "./IndexingProgressIndicator"; -import IndexingProgressTitleText from "./IndexingProgressTitleText"; -import IndexingProgressSubtext from "./IndexingProgressSubtext"; -import { usePostHog } from "posthog-js/react"; + import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; -import { setShowDialog, setDialogMessage } from "../../../redux/slices/uiSlice"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { isJetBrains } from "../../../util"; +import IndexingProgressBar from "./IndexingProgressBar"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; +import IndexingProgressIndicator from "./IndexingProgressIndicator"; +import IndexingProgressSubtext from "./IndexingProgressSubtext"; +import IndexingProgressTitleText from "./IndexingProgressTitleText"; export function getProgressPercentage( progress: IndexingProgressUpdate["progress"], @@ -119,7 +120,8 @@ function IndexingProgress() { - {update.status === "failed" && ( + {(update.status === "failed" || + (update.warnings && update.warnings.length > 0)) && (
diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx index 33d4818ad..09b06b758 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx @@ -1,12 +1,27 @@ -import { XCircleIcon } from "@heroicons/react/24/outline"; +import { + ArrowTopRightOnSquareIcon, + ChevronRightIcon, + ClipboardIcon, + XCircleIcon, +} from "@heroicons/react/24/outline"; import { IndexingProgressUpdate } from "core"; +import { useContext, useState } from "react"; +import { GhostButton } from "../../../components"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppSelector } from "../../../redux/hooks"; export interface IndexingProgressErrorTextProps { update: IndexingProgressUpdate; } +const copyWarningsToClipboard = (warnings: string[] = []) => { + const warningsText = warnings.join("\n"); + void navigator.clipboard.writeText(warningsText); +}; + function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { + const ideMessenger = useContext(IdeMessengerContext); + const [showWarnings, setShowWarnings] = useState(false); const embeddingsProvider = useAppSelector( (state) => state.config.config.selectedModelByRole.embed, ); @@ -30,6 +45,71 @@ function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { ); } + // Show warnings if they exist (for completed indexing with warnings) + if ( + update.warnings && + update.warnings.length > 0 && + update.status !== "failed" + ) { + return ( +
+
setShowWarnings(!showWarnings)} + > + + {update.warnings.length} warning + {update.warnings.length > 1 ? "s" : ""} during indexing + + +
+ +
+ {/* Warning messages */} +
+ {update.warnings.map((warning, index) => ( +
+ • {warning} +
+ ))} +
+ + {/* Action Buttons */} +
+ {/* Copy all warnings to clipboard */} + copyWarningsToClipboard(update.warnings)} + className="flex items-center !px-1.5 !py-0.5 text-xs" + > + + Copy output + + + {/* Open dev tools to view logs */} + { + ideMessenger.post("toggleDevTools", undefined); + }} + className="flex items-center !px-1.5 !py-0.5 text-xs" + > + + View Logs + +
+
+
+ ); + } + + // Show error for failed status return (
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 126c4e894..700e5352e 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -4,7 +4,6 @@ import { } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; -import { streamResponse } from "core/llm/stream"; import { renderChatMessage } from "core/util/messageContent"; import { useCallback, @@ -239,11 +238,11 @@ export function Chat() { [ history, selectedModels, - streamResponse, mode, isInEdit, codeToEdit, toolCallState, + currentToolCallApplyState, ], ); diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index 540b9c79e..f73d61dba 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -81,7 +81,17 @@ export function parseDataLine(line: string): any { try { const data = JSON.parse(json); if (data.error) { - throw new Error(`Error streaming response: ${data.error}`); + if ( + data.error && + typeof data.error === "object" && + "message" in data.error + ) { + console.error("Error in streamed response:", data.error); + throw new Error(`Error streaming response: ${data.error.message}`); + } + throw new Error( + `Error streaming response: ${JSON.stringify(data.error)}`, + ); } return data; diff --git a/scripts/install-dependencies.ps1 b/scripts/install-dependencies.ps1 index 5556e58f5..e783f94b4 100644 --- a/scripts/install-dependencies.ps1 +++ b/scripts/install-dependencies.ps1 @@ -76,6 +76,12 @@ if (($null -eq $node)) { Write-Host "`nInstalling root-level dependencies..." -ForegroundColor White npm install +Write-Host "`nBuilding openai-adapters..." -ForegroundColor White +Push-Location packages/openai-adapters +npm install +npm run build +Pop-Location + Write-Host "`nBuilding config-yaml..." -ForegroundColor White Push-Location packages/config-yaml npm install diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index 092028b37..503aabbcd 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -30,6 +30,12 @@ fi echo "Installing root-level dependencies..." npm install +echo "Building openai-adapters..." +pushd packages/openai-adapters +npm install +npm run build +popd + echo "Building config-yaml..." pushd packages/config-yaml npm install