From 6a67514fcf108bd0eb6989777abaed02ce2e61e7 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 17 Apr 2025 18:16:14 +0200 Subject: [PATCH 1/2] fix: report indexing errors in webview Signed-off-by: Fred Bricon --- core/core.ts | 12 ------------ .../config/IndexingProgress/IndexingProgressBar.tsx | 3 ++- .../IndexingProgress/IndexingProgressErrorText.tsx | 2 +- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/core/core.ts b/core/core.ts index 5f90dd36d..e8678336e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1010,13 +1010,6 @@ export class Core { this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; - // TODO reconsider this status overwrite? - // original goal was to not concern users with edge noncritical errors - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } void this.messenger.request("indexProgress", updateToSend); this.codebaseIndexingState = updateToSend; @@ -1045,11 +1038,6 @@ export class Core { files, )) { let updateToSend = { ...update }; - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } void this.messenger.request("indexProgress", updateToSend); this.codebaseIndexingState = updateToSend; diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx index 5de74fb3f..fa8e07097 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx @@ -6,7 +6,8 @@ export interface IndexingProgressBarProps { } function IndexingProgressBar({ update }: IndexingProgressBarProps) { - const progressPercentage = getProgressPercentage(update.progress); + // Show 100% red progress bar if indexing failed + const progressPercentage = update.status === "failed" ? 100 : getProgressPercentage(update.progress); return (
diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx index e7a19f612..33d4818ad 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx @@ -31,7 +31,7 @@ function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { } return ( -
+
{update.desc}
From 1dc58c63ab174f579e860d778ae85e73f6fb8c9d Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 17 Apr 2025 18:17:37 +0200 Subject: [PATCH 2/2] fix: allow downloading missing embedder on Ollama, in VS Code Signed-off-by: Fred Bricon --- core/core.ts | 60 ++++++++++---- core/index.d.ts | 4 + core/indexing/CodebaseIndexer.ts | 9 ++- core/indexing/docs/DocsService.ts | 12 +++ core/llm/index.ts | 2 +- core/llm/llms/Docker.ts | 32 +++++++- core/llm/llms/Ollama.ts | 79 +++++++++++++------ core/protocol/ide.ts | 1 + core/util/errors.ts | 13 +++ .../src/autocomplete/completionProvider.ts | 7 +- .../vscode/src/extension/VsCodeMessenger.ts | 15 ++-- extensions/vscode/src/util/errorHandling.ts | 9 ++- extensions/vscode/src/webviewProtocol.ts | 2 +- 13 files changed, 191 insertions(+), 54 deletions(-) create mode 100644 core/util/errors.ts diff --git a/core/core.ts b/core/core.ts index e8678336e..15e66e21d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -52,6 +52,7 @@ import { MCPManagerSingleton } from "./context/mcp"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; +import { LLMError } from "./llm"; import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; @@ -1005,18 +1006,23 @@ export class Core { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshDirs( - paths, - this.indexingCancellationController.signal, - )) { - let updateToSend = { ...update }; + try { + for await (const update of (await this.codebaseIndexerPromise).refreshDirs( + paths, + this.indexingCancellationController.signal, + )) { + let updateToSend = { ...update }; - void this.messenger.request("indexProgress", updateToSend); - this.codebaseIndexingState = updateToSend; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; - if (update.status === "failed") { - void this.sendIndexingErrorTelemetry(update); + if (update.status === "failed") { + void this.sendIndexingErrorTelemetry(update); + } } + } catch (e: any) { + console.log(`Failed refreshing codebase index directories : ${e}`); + this.handleIndexingError(e); } this.messenger.send("refreshSubmenuItems", { @@ -1034,17 +1040,22 @@ export class Core { return; } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshFiles( - files, - )) { - let updateToSend = { ...update }; + try{ + for await (const update of (await this.codebaseIndexerPromise).refreshFiles( + files, + )) { + let updateToSend = { ...update }; - void this.messenger.request("indexProgress", updateToSend); - this.codebaseIndexingState = updateToSend; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; - if (update.status === "failed") { - void this.sendIndexingErrorTelemetry(update); + if (update.status === "failed") { + void this.sendIndexingErrorTelemetry(update); + } } + } catch (e: any) { + console.log(`Failed refreshing codebase index files : ${e}`); + this.handleIndexingError(e); } this.messenger.send("refreshSubmenuItems", { @@ -1054,4 +1065,19 @@ export class Core { } // private + handleIndexingError(e: any) { + if (e instanceof LLMError) { + // Need to report this specific error to the IDE for special handling + this.messenger.request("reportError", e); + } + // broadcast indexing error + let updateToSend: IndexingProgressUpdate = { + progress: 0, + status: "failed", + desc: e.message, + }; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; + void this.sendIndexingErrorTelemetry(updateToSend); + } } diff --git a/core/index.d.ts b/core/index.d.ts index 5711f9d9e..bb06aa382 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -153,6 +153,10 @@ export interface ModelInstaller { signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void, ): Promise; + + isInstallingModel( + modelName: string + ): Promise; } export type ContextProviderType = "normal" | "query" | "submenu"; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index f0f1cd4bb..0bd1f57b6 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -7,6 +7,8 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; +import { LLMError } from "../llm/index.js"; +import { getRootCause } from "../util/errors.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; @@ -350,6 +352,10 @@ export class CodebaseIndexer { ): IndexingProgressUpdate { console.log("error when indexing: ", err); if (err instanceof Error) { + const cause = getRootCause(err); + if (cause instanceof LLMError) { + throw cause; + } return this.errorToProgressUpdate(err); } return { @@ -361,7 +367,8 @@ export class CodebaseIndexer { } private errorToProgressUpdate(err: Error): IndexingProgressUpdate { - let errMsg: string = `${err}`; + const cause = getRootCause(err); + let errMsg: string = `${cause}`; let shouldClearIndexes = false; // Check if any of the error regexes match diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 0bd7ba93a..cc9eef842 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -36,6 +36,7 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import type * as LanceType from "vectordb"; +import { LLMError } from "../../llm"; import { DocsCache, SiteIndexingResults } from "./DocsCache"; // Purposefully lowercase because lancedb converts @@ -421,6 +422,7 @@ export default class DocsService { return false; } + // eslint-disable-next-line max-statements async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, forceReindex: boolean = false, @@ -506,6 +508,16 @@ export default class DocsService { try { await provider.embed(["continue-test-run"]); } catch (e) { + if (e instanceof LLMError) { + // Report the error to the IDE + this.messenger?.request("reportError", e); + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Failed to test embeddings connection. ${e}`, + status: "failed", + progress: 1, + }); console.error("Failed to test embeddings connection", e); return; } diff --git a/core/llm/index.ts b/core/llm/index.ts index e3d8004bb..2b0e508d9 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -72,7 +72,7 @@ export class LLMError extends Error { } export function isModelInstaller(provider: any): provider is ModelInstaller { - return provider && typeof provider.installModel === "function"; + return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";; } type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts index d9c3d5c58..131f45b14 100644 --- a/core/llm/llms/Docker.ts +++ b/core/llm/llms/Docker.ts @@ -1,3 +1,4 @@ +import { Mutex } from "async-mutex"; import { spawn } from "child_process"; import { LLMOptions, ModelInstaller } from "../../index.js"; import OpenAI from "./OpenAI.js"; @@ -47,6 +48,9 @@ class Docker extends OpenAI implements ModelInstaller { "deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M", }; + private static modelsBeingInstalled: Set = new Set(); + private static modelsBeingInstalledMutex = new Mutex(); + constructor(options: LLMOptions) { super(options); @@ -164,6 +168,16 @@ class Docker extends OpenAI implements ModelInstaller { ): Promise { const targetModel = this.modelMap[modelName] || modelName; + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + if (Docker.modelsBeingInstalled.has(modelName)) { + throw new Error(`Model '${modelName}' is already being installed.`); + } + Docker.modelsBeingInstalled.add(modelName); + } finally { + release(); + } + try { // Report starting the installation progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100); @@ -184,12 +198,28 @@ class Docker extends OpenAI implements ModelInstaller { return { success: true, stdout, stderr }; } catch (error) { console.error(`Failed to install Docker model ${targetModel}:`, error); - // Fix: Type check the error before accessing message property +// Fix: Type check the error before accessing message property const errorMessage = error instanceof Error ? error.message : String(error); throw new Error( `Failed to install Docker model ${targetModel}: ${errorMessage}`, ); + } finally { + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + Docker.modelsBeingInstalled.delete(modelName); + } finally { + release(); + } + } + } + + public async isInstallingModel(modelName: string): Promise { + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + return Docker.modelsBeingInstalled.has(modelName); + } finally { + release(); } } } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 173692de3..9db223b79 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,3 +1,4 @@ +import { Mutex } from "async-mutex"; import { JSONSchema7, JSONSchema7Object } from "json-schema"; import { @@ -138,6 +139,9 @@ class Ollama extends BaseLLM implements ModelInstaller { maxEmbeddingBatchSize: 64, }; + private static modelsBeingInstalled: Set = new Set(); + private static modelsBeingInstalledMutex = new Mutex(); + private fimSupported: boolean = false; constructor(options: LLMOptions) { @@ -592,33 +596,62 @@ class Ollama extends BaseLLM implements ModelInstaller { if (!modelInfo) { throw new Error(`'${modelName}' not found in the Ollama registry!`); } - const response = await fetch(this.getEndpoint("api/pull"), { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, - body: JSON.stringify({ name: modelName }), - signal, - }); - const reader = response.body?.getReader(); - //TODO: generate proper progress based on modelInfo size - while (true) { - const { done, value } = (await reader?.read()) || { - done: true, - value: undefined, - }; - if (done) { - break; + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + if (Ollama.modelsBeingInstalled.has(modelName)) { + throw new Error(`Model '${modelName}' is already being installed.`); } + Ollama.modelsBeingInstalled.add(modelName); + } finally { + release(); + } - const chunk = new TextDecoder().decode(value); - const lines = chunk.split("\n").filter(Boolean); - for (const line of lines) { - const data = JSON.parse(line); - progressReporter?.(data.status, data.completed, data.total); + try { + const response = await fetch(this.getEndpoint("api/pull"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal, + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = (await reader?.read()) || { + done: true, + value: undefined, + }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split("\n").filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } } + } finally { + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + Ollama.modelsBeingInstalled.delete(modelName); + } finally { + release(); + } + } + } + + public async isInstallingModel(modelName: string): Promise { + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + return Ollama.modelsBeingInstalled.has(modelName); + } finally { + release(); } } } diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 1646d848e..72e328415 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ControlPlaneSessionInfo | undefined, ]; logoutOfControlPlane: [undefined, void]; + reportError:[any, void]; }; export type ToWebviewOrCoreFromIdeProtocol = { diff --git a/core/util/errors.ts b/core/util/errors.ts new file mode 100644 index 000000000..02d87b00a --- /dev/null +++ b/core/util/errors.ts @@ -0,0 +1,13 @@ + +/** + * Recursively retrieves the root cause of an error by traversing through its `cause` property. + * + * @param err - The error object to analyze. It can be of any type. + * @returns The root cause of the error, or the original error if no further cause is found. + */ +export function getRootCause(err: any): any { + if (err.cause) { + return getRootCause(err.cause); + } + return err; +} \ No newline at end of file diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 05e263117..381d9117a 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,11 +5,11 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { startLocalOllama } from "core/util/ollamaHelper"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; +import { handleLLMError } from "../util/errorHandling"; import { showFreeTrialLoginMessage } from "../util/messages"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -24,7 +24,6 @@ import { } from "./statusBar"; import type { IDE } from "core"; -import { handleLLMError } from "../util/errorHandling"; interface VsCodeCompletionInput { document: vscode.TextDocument; @@ -34,8 +33,8 @@ interface VsCodeCompletionInput { export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { - private onError(e: any) { - if (handleLLMError(e)) { + private async onError(e: any) { + if (await handleLLMError(e)) { return; } let message = e.message; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index d0ada4fc4..49de7f758 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -22,6 +22,7 @@ import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; +import { handleLLMError } from "../util/errorHandling"; import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; @@ -237,11 +238,11 @@ export class VsCodeMessenger { /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { this.onWebview(messageType, async (msg) => { - return await this.inProcessMessenger.externalRequest( - messageType, - msg.data, - msg.messageId, - ); + return await this.inProcessMessenger.externalRequest( + messageType, + msg.data, + msg.messageId, + ); }); }); @@ -410,5 +411,9 @@ export class VsCodeMessenger { this.onWebviewOrCore("getUniqueId", async (msg) => { return await ide.getUniqueId(); }); + + this.onWebviewOrCore("reportError", async (msg) => { + handleLLMError(msg.data); + }); } } diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts index de68f0ce2..c866e1907 100644 --- a/extensions/vscode/src/util/errorHandling.ts +++ b/extensions/vscode/src/util/errorHandling.ts @@ -1,3 +1,5 @@ +import { ILLM } from "core"; +import { isModelInstaller } from "core/llm"; import * as vscode from "vscode"; function supportSpecialHandling(error: any): boolean { @@ -9,7 +11,7 @@ function supportSpecialHandling(error: any): boolean { * @param error Handles common LLM errors. Currently only handles Ollama-related errors. * @returns true if error is handled, false otherwise */ -export function handleLLMError(error: any): boolean { +export async function handleLLMError(error: any): Promise { if (!supportSpecialHandling(error)) { return false; } @@ -23,6 +25,11 @@ export function handleLLMError(error: any): boolean { } else if (message.includes("ollama run") && error.llm) { //extract model name from error message matching the pattern "ollama run " modelName = message.match(/`ollama run (.*)`/)?.[1]; + const llm = error.llm as ILLM; + if (isModelInstaller(llm) && await llm.isInstallingModel(modelName!)){ + console.log(`${llm.providerName} already installing ${modelName}`); + return false; + } message = `Model "${modelName}" is not found in Ollama. You need to install it.`; options = [`Install Model`]; } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 0d58532ae..a22e3b312 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -87,7 +87,7 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - if (handleLLMError(e)) { + if (await handleLLMError(e)) { // Respond without an error, so the UI doesn't show the error component respond({ done: true, status: "error" }); }