From 2869cf50781317eddf55dde8248a247953f53d99 Mon Sep 17 00:00:00 2001 From: lkyu <67578466+lkyu-ly@users.noreply.github.com> Date: Thu, 20 Feb 2025 01:07:24 +0800 Subject: [PATCH 1/8] Update domain in docusaurus.config.js Change site url from `continue.dev` to `docs.continue.dev` so as to generate a correct sitemap. --- docs/docusaurus.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c97113a0a..0ca029806 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -19,7 +19,7 @@ const config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://continue.dev", + url: "https://docs.continue.dev", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: "/", From dbdf72ea84215e59caa5fe9ea159248a56413118 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 13 Feb 2025 12:10:19 +0100 Subject: [PATCH 2/8] Pull missing ollama models Signed-off-by: Fred Bricon --- core/index.d.ts | 4 ++ core/llm/index.ts | 22 ++++++- core/llm/llms/Ollama.ts | 37 +++++++++++- core/util/ollamaHelper.ts | 60 ++++++++++++++++++- .../src/autocomplete/completionProvider.ts | 21 +++++-- extensions/vscode/src/commands.ts | 44 +++++++++++++- extensions/vscode/src/webviewProtocol.ts | 50 ++++++++++------ gui/src/pages/gui/StreamError.tsx | 12 ++-- 8 files changed, 214 insertions(+), 36 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 7cbf0e25b..c0c7e1453 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions { ): string | ChatMessage[]; } +export interface ModelInstaller { + installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise; +} + export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { diff --git a/core/llm/index.ts b/core/llm/index.ts index ccbad6699..3abed5f0b 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -19,6 +19,7 @@ import { LLMFullCompletionOptions, LLMOptions, ModelCapability, + ModelInstaller, PromptLog, PromptTemplate, RequestOptions, @@ -58,6 +59,17 @@ import { toFimBody, } from "./openaiTypeConverters.js"; + +export class LLMError extends Error { + constructor(message: string, public llm: ILLM) { + super(message); + } +} + +export function isModelInstaller(provider: any): provider is ModelInstaller { + return provider && typeof provider.installModel === 'function'; +} + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM { if (!resp.ok) { let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + const error = JSON.parse(text)?.error?.replace(/"/g, "'"); + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + throw new LLMError(text, this);// No need to add HTTP status details } else if (text.includes("/api/chat")) { text = "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; @@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } + //if e instance of LLMError, rethrow + if (e instanceof LLMError) { + throw e; + } throw new Error(e.message); } }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index ee822eb27..675fd8663 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,9 +1,10 @@ import { JSONSchema7, JSONSchema7Object } from "json-schema"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; type OllamaChatMessage = { role: "tool" | "user" | "assistant" | "system"; @@ -123,7 +124,7 @@ interface OllamaTool { }; } -class Ollama extends BaseLLM { +class Ollama extends BaseLLM implements ModelInstaller{ static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", @@ -574,6 +575,38 @@ class Ollama extends BaseLLM { } return embedding; } + + public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise { + const modelInfo = await getRemoteModelInfo(modelName, signal); + 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 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); + } + } + } } export default Ollama; diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index a00e869dd..2d5266318 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -1,6 +1,13 @@ +import crypto from "crypto"; +import { exec } from "node:child_process"; import path from "node:path"; import { IDE } from ".."; -import { exec } from "node:child_process"; + +export interface ModelInfo { + id: string; + size: number; + digest: string; +} export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { @@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise { }); } } + +export async function getRemoteModelInfo( + modelId: string, + signal?: AbortSignal, + ): Promise { + const start = Date.now(); + const [modelName, tag = "latest"] = modelId.split(":"); + const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`; + try { + const sig = signal ? signal : AbortSignal.timeout(3000); + const response = await fetch(url, { signal: sig }); + + if (!response.ok) { + throw new Error(`Failed to fetch the model page: ${response.statusText}`); + } + + // First, read the response body as an ArrayBuffer to compute the digest + const buffer = await response.arrayBuffer(); + const digest = getDigest(buffer); + + // Then, decode the ArrayBuffer into a string and parse it as JSON + const text = new TextDecoder().decode(buffer); + const manifest = JSON.parse(text) as { + config: { size: number }; + layers: { size: number }[]; + }; + const modelSize = + manifest.config.size + + manifest.layers.reduce((sum, layer) => sum + layer.size, 0); + + const data: ModelInfo = { + id: modelId, + size: modelSize, + digest, + }; + // Cache the successful result + return data; + } catch (error) { + console.error(`Error fetching or parsing model info: ${error}`); + } finally { + const elapsed = Date.now() - start; + console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`); + } + return undefined; + } + + function getDigest(buffer: ArrayBuffer): string { + const hash = crypto.createHash("sha256"); + hash.update(new Uint8Array(buffer)); + return hash.digest("hex"); + } \ No newline at end of file diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 497de3875..8c0721d53 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,8 +21,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; +import { startLocalOllama } from "core/util/ollamaHelper"; const Diff = require("diff"); @@ -44,15 +44,22 @@ export class ContinueCompletionProvider { private onError(e: any) { let options = ["Documentation"]; - if (e.message.includes("Ollama may not be installed")) { + let message = e.message; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { options.push("Download Ollama"); - } else if (e.message.includes("Ollama may not be running")) { + } else if (message.includes("Ollama may not be running")) { options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && e.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; } - if (e.message.includes("Please sign in with GitHub")) { + if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( - e.message, + message, this.configHandler.reloadConfig.bind(this.configHandler), () => { void this.webviewProtocol.request("openOnboardingCard", undefined); @@ -60,7 +67,7 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(e.message, ...options).then((val) => { + vscode.window.showErrorMessage(message, ...options).then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( @@ -71,6 +78,8 @@ export class ContinueCompletionProvider vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); } else if (val === "Start Ollama") { startLocalOllama(this.ide); + } else if (val === "Install Model" && e.llm) { + vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index fa6b44c2a..697768d4c 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, RangeInFileWithContents } from "core"; +import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -14,13 +14,13 @@ import readLastLines from "read-last-lines"; import * as vscode from "vscode"; import { - StatusBarStatus, getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, getStatusBarStatus, getStatusBarStatusFromQuickPickItemLabel, quickPickStatusText, setupStatusBar, + StatusBarStatus, } from "./autocomplete/statusBar"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; @@ -32,6 +32,7 @@ import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; +import { isModelInstaller } from "core/llm"; import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -996,6 +997,19 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, + "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + try { + if (!isModelInstaller(llmProvider)) { + const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : + 'Missing LLM Provider'; + throw new Error(msg); + } + await installModelWithProgress(modelName, llmProvider); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + } + } }; }; @@ -1037,6 +1051,32 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; +async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = (details: string, worked?: number, total?: number) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; + } + windowProgress.report({ message: details, increment }); + } + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); + }); + await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + }); +} + export function registerAllCommands( context: vscode.ExtensionContext, ide: VsCodeIde, diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 14854f1c3..3f2c6ea44 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,6 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; +import { ILLM } from "core"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,27 +88,40 @@ export class VsCodeWebviewProtocol } } catch (e: any) { let message = e.message; + let llmProvider: ILLM | undefined; //Intercept Ollama errors for special handling - if (message.includes("Ollama may not")) { - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); + if (message.includes("Ollama may not") || message.includes("`ollama run")) { + let modelName : string | undefined; + const options = []; + if (message.includes("be installed")) { + options.push("Download Ollama"); + } else if (message.includes("be running")) { + options.push("Start Ollama"); + } else if (message.includes("`ollama run")) { + modelName = e.message.match(/`ollama run (.*)`/)?.[1]; + if (e.llm) { + llmProvider = e.llm; } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } - }); - return; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + if (modelName) { + options.push("Install Model"); } + } + if (options.length > 0) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); + // Show native vscode error message instead, with options to download/start Ollama + vscode.window.showErrorMessage(message, ...options).then(async (val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model") { + vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); + } + }); + return; + } } respond({ done: true, error: e.message, status: "error" }); diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 36d3853b1..635a9ae3e 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -66,11 +66,13 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ) { message = error["message"]; const parts = message?.split(" ") ?? []; - const status = parts[0] === "HTTP" ? parts[1] : parts[0]; - if (status) { - const code = Number(status); - if (!Number.isNaN(statusCode)) { - statusCode = code; + if (parts.length > 1) { + const status = parts[0] === "HTTP" ? parts[1] : parts[0]; + if (status) { + const code = Number(status); + if (!Number.isNaN(code)) { + statusCode = code; + } } } } From d9c3d447b9d20b447489d4d147490e5ad60957a5 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 6 Mar 2025 15:20:25 +0100 Subject: [PATCH 3/8] Refactor Ollama error management Signed-off-by: Fred Bricon --- .../src/autocomplete/completionProvider.ts | 26 ++---- extensions/vscode/src/commands.ts | 80 ++++++++++++------- .../vscode/src/diff/vertical/manager.ts | 9 ++- extensions/vscode/src/util/errorHandling.ts | 49 ++++++++++++ extensions/vscode/src/webviewProtocol.ts | 44 ++-------- 5 files changed, 119 insertions(+), 89 deletions(-) create mode 100644 extensions/vscode/src/util/errorHandling.ts diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 8c0721d53..f74de8409 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -22,7 +22,7 @@ import { } from "./statusBar"; import type { IDE } from "core"; -import { startLocalOllama } from "core/util/ollamaHelper"; +import { handleLLMError } from "../util/errorHandling"; const Diff = require("diff"); @@ -43,20 +43,10 @@ export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { private onError(e: any) { - let options = ["Documentation"]; - let message = e.message; - let modelName = undefined; - if (message.includes("Ollama may not be installed")) { - options.push("Download Ollama"); - } else if (message.includes("Ollama may not be running")) { - options = ["Start Ollama"]; // We want "Start" to be the only choice - } else if (message.includes("ollama run") && e.llm) { - //extract model name from error message matching the pattern "ollama run " - modelName = message.match(/`ollama run (.*)`/)?.[1]; - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - options = [`Install Model`]; + if (handleLLMError(e)) { + return; } - + let message = e.message; if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( message, @@ -67,19 +57,13 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(message, ...options).then((val) => { + vscode.window.showErrorMessage(message, "Documentation").then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( "https://docs.continue.dev/features/tab-autocomplete", ), ); - } else if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - startLocalOllama(this.ide); - } else if (val === "Install Model" && e.llm) { - vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 697768d4c..e9b973a2a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,12 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; +import { + ContextMenuConfig, + ILLM, + ModelInstaller, + RangeInFileWithContents, +} from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -997,19 +1002,25 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, - "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + "continue.installModel": async ( + modelName: string, + llmProvider: ILLM | undefined, + ) => { try { if (!isModelInstaller(llmProvider)) { - const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : - 'Missing LLM Provider'; + const msg = llmProvider + ? `LLM provider '${llmProvider.providerName}' does not support installing models` + : "Missing LLM Provider"; throw new Error(msg); } await installModelWithProgress(modelName, llmProvider); } catch (e) { const message = e instanceof Error ? e.message : String(e); - vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + vscode.window.showErrorMessage( + `Failed to install '${modelName}': ${message}`, + ); } - } + }, }; }; @@ -1051,30 +1062,43 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; -async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { - return vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Installing model '${modelName}'`, - cancellable: true, - }, async (windowProgress, token) => { - let currentProgress: number = 0; - const progressWrapper = (details: string, worked?: number, total?: number) => { - let increment = 0; - if (worked && total) { - const progressValue = Math.round((worked / total) * 100); - increment = progressValue - currentProgress; - currentProgress = progressValue; - } - windowProgress.report({ message: details, increment }); +async function installModelWithProgress( + modelName: string, + modelInstaller: ModelInstaller, +) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, + async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = ( + details: string, + worked?: number, + total?: number, + ) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; } - const abortController = new AbortController(); - token.onCancellationRequested(() => { - console.log(`Pulling ${modelName} model was cancelled`); - abortController.abort(); - }); - await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + windowProgress.report({ message: details, increment }); + }; + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); }); + await modelInstaller.installModel( + modelName, + abortController.signal, + progressWrapper, + ); + }, + ); } export function registerAllCommands( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index a62406b00..b51462a3c 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -255,7 +256,9 @@ export class VerticalDiffManager { this.enableDocumentChangeListener(); } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } } finally { vscode.commands.executeCommand( "setContext", @@ -446,7 +449,9 @@ export class VerticalDiffManager { return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } return undefined; } finally { vscode.commands.executeCommand( diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts new file mode 100644 index 000000000..de68f0ce2 --- /dev/null +++ b/extensions/vscode/src/util/errorHandling.ts @@ -0,0 +1,49 @@ +import * as vscode from "vscode"; + +function supportSpecialHandling(error: any): boolean { + let message: string | undefined = error.message; + return message !== undefined && message.toLowerCase().includes("ollama"); +} + +/** + * @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 { + if (!supportSpecialHandling(error)) { + return false; + } + let message: string = error.message; + let options: string[] | undefined; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { + options = ["Download Ollama"]; + } else if (message.includes("Ollama may not be running")) { + options = ["Start Ollama"]; // We want "Start" to be the only choice + } 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]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; + } + if (options === undefined) { + console.log("Found an unhandled Ollama error: ", message); + return false; + } + + vscode.window.showErrorMessage(message, ...options).then((val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model" && error.llm) { + //Eventually, we might be able to support installing models for other LLM providers than Ollama + vscode.commands.executeCommand( + "continue.installModel", + modelName, + error.llm, + ); + } + }); + return true; +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 3f2c6ea44..0d58532ae 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,7 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; -import { ILLM } from "core"; +import { handleLLMError } from "./util/errorHandling"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,44 +87,12 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - let message = e.message; - let llmProvider: ILLM | undefined; - //Intercept Ollama errors for special handling - if (message.includes("Ollama may not") || message.includes("`ollama run")) { - let modelName : string | undefined; - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); - } else if (message.includes("`ollama run")) { - modelName = e.message.match(/`ollama run (.*)`/)?.[1]; - if (e.llm) { - llmProvider = e.llm; - } - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - if (modelName) { - options.push("Install Model"); - } - } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } else if (val === "Install Model") { - vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); - } - }); - return; - } + if (handleLLMError(e)) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); } - - respond({ done: true, error: e.message, status: "error" }); + let message = e.message; + respond({ done: true, error: message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); console.error( From 954d91cfe8d3d9a684213d6aba9b513dd5ddc2a9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 6 Mar 2025 11:59:46 -0800 Subject: [PATCH 4/8] better autodetect names --- core/config/load.ts | 3 ++- core/config/yaml/models.ts | 3 ++- core/util/text.ts | 6 ++++++ gui/src/components/modelSelection/ModelSelectionListbox.tsx | 3 +-- 4 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 core/util/text.ts diff --git a/core/config/load.ts b/core/config/load.ts index 873577d8c..8005ff555 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,6 +71,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -272,7 +273,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${llm.title} - ${modelName}`, + title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index c6916b010..240a7044e 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,6 +3,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; +import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -127,7 +128,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${llm.title} - ${modelName}`, + name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, uniqueId, ideSettings, diff --git a/core/util/text.ts b/core/util/text.ts new file mode 100644 index 000000000..e4870dfa0 --- /dev/null +++ b/core/util/text.ts @@ -0,0 +1,6 @@ +export const capitalizeFirstLetter = (val: string) => { + if (val.length === 0) { + return ""; + } + return val[0].toUpperCase() + val.slice(1); +}; diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index d48ffceed..596cddb9b 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -1,11 +1,10 @@ -import { Transition } from "@headlessui/react"; +import { Listbox, Transition } from "@headlessui/react"; import { CheckIcon, ChevronUpDownIcon, CubeIcon, } from "@heroicons/react/24/outline"; import { Fragment } from "react"; -import { Listbox } from "@headlessui/react"; import styled from "styled-components"; import { defaultBorderRadius, From 0917ddf9a534891c267d659de7f776df59bad65d Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 22:53:42 -0800 Subject: [PATCH 5/8] remove "Autodetect" --- core/config/load.ts | 3 +-- core/config/yaml/models.ts | 3 +-- extensions/vscode/package-lock.json | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 8005ff555..3636b4bf8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,7 +71,6 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -273,7 +272,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + title: modelName, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 240a7044e..b4392d519 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,7 +3,6 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; -import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -128,7 +127,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + name: modelName, }, uniqueId, ideSettings, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index cbcebc34e..ed46978a0 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From c0fc96945d26670105d4652e3d751879cd2213e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 08:21:49 -0800 Subject: [PATCH 6/8] ignore ssh tests on forks --- .github/workflows/pr_checks.yaml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 5fe472a10..7ed61ec89 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -303,7 +303,13 @@ jobs: cd extensions/vscode npm ci npm run e2e:compile - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT From 98739c63eccca5b3177935510d5196c20486e2f4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:29:00 -0800 Subject: [PATCH 7/8] fix ignore api key tests --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7ed61ec89..da4d69970 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} From 1be8ed69ecab06faced15882e425c562cfae3dd1 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:42:12 -0800 Subject: [PATCH 8/8] attempt to fix flaky walkdir test --- core/indexing/walkDir.test.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8ded86670..50d21c778 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -192,12 +192,7 @@ describe("walkDir functions", () => { it("should skip symlinks", async () => { const filePath = path.join(TEST_DIR_PATH, "real.ts"); addToTestDir([["real.ts", "content"]]); - fs.symlink( - filePath, - path.join(TEST_DIR_PATH, "symlink.ts"), - "file", - () => {}, - ); + fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file"); const files = await walkDirs(testIde);