Prevent entire indexing process from stopping on error and surface messages to Indexing menu

This commit is contained in:
Ting-Wai To 2025-07-01 13:33:17 -07:00
parent c86e88ff0c
commit 057809b242
7 changed files with 243 additions and 85 deletions

1
core/index.d.ts vendored
View file

@ -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.

View file

@ -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(

View file

@ -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],
};
}
}

View file

@ -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,

View file

@ -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

View file

@ -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() {
<IndexingProgressSubtext update={update} onClick={onClick} />
{update.status === "failed" && (
{(update.status === "failed" ||
(update.warnings && update.warnings.length > 0)) && (
<div className="mt-4">
<IndexingProgressErrorText update={update} />
</div>

View file

@ -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 (
<div>
<div
className="flex cursor-pointer items-center gap-2 italic text-yellow-600"
onClick={() => setShowWarnings(!showWarnings)}
>
<span className="leading-relaxed">
{update.warnings.length} warning
{update.warnings.length > 1 ? "s" : ""} during indexing
</span>
<ChevronRightIcon
className={`h-3 w-3 transition-transform duration-300 ${
showWarnings ? "rotate-90" : ""
}`}
/>
</div>
<div
className={`ml-3 overflow-hidden transition-all duration-300 ease-in-out ${
showWarnings ? "mt-2 max-h-96 opacity-100" : "max-h-0 opacity-0"
}`}
>
{/* Warning messages */}
<div className="space-y-1">
{update.warnings.map((warning, index) => (
<div key={index} className="text-xs">
• {warning}
</div>
))}
</div>
{/* Action Buttons */}
<div className="flex flex-row items-center justify-end gap-2 pt-4">
{/* Copy all warnings to clipboard */}
<GhostButton
onClick={() => copyWarningsToClipboard(update.warnings)}
className="flex items-center !px-1.5 !py-0.5 text-xs"
>
<ClipboardIcon className="mr-1 h-3 w-3" />
<span>Copy output</span>
</GhostButton>
{/* Open dev tools to view logs */}
<GhostButton
onClick={() => {
ideMessenger.post("toggleDevTools", undefined);
}}
className="flex items-center !px-1.5 !py-0.5 text-xs"
>
<ArrowTopRightOnSquareIcon className="mr-1 h-3 w-3" />
<span>View Logs</span>
</GhostButton>
</div>
</div>
</div>
);
}
// Show error for failed status
return (
<div className="flex items-center gap-2 italic text-red-600">
<XCircleIcon className="h-4 w-4" />