From 8296cd10ac12c4fe0aa094734b340032c1558634 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Tue, 7 Jan 2025 17:34:58 +0100 Subject: [PATCH 1/4] Add the ability to start Ollama when it's stopped Signed-off-by: Fred Bricon --- core/llm/index.ts | 9 +- core/util/ollamaHelper.ts | 38 +++++++++ core/util/start_ollama.sh | 84 +++++++++++++++++++ .../scripts/prepackage-cross-platform.js | 4 + extensions/vscode/scripts/prepackage.js | 1 + extensions/vscode/scripts/utils.js | 21 +++++ extensions/vscode/src/VsCodeIde.ts | 12 ++- .../src/autocomplete/completionProvider.ts | 5 ++ 8 files changed, 164 insertions(+), 10 deletions(-) create mode 100644 core/util/ollamaHelper.ts create mode 100755 core/util/start_ollama.sh diff --git a/core/llm/index.ts b/core/llm/index.ts index 5c0253e86..4608c9bda 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -55,6 +55,7 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; +import { isOllamaInstalled } from "../util/ollamaHelper.js"; export abstract class BaseLLM implements ILLM { static providerName: string; @@ -414,9 +415,11 @@ export abstract class BaseLLM implements ILLM { e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") ) { - throw new Error( - "Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai.", - ); + const message = (await isOllamaInstalled()) ? + "Failed to connect to local Ollama instance. Ollama appears to be stopped. It needs to be running." : + "Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai." + ; + throw new Error(message); } } throw new Error(e.message); diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts new file mode 100644 index 000000000..9520de678 --- /dev/null +++ b/core/util/ollamaHelper.ts @@ -0,0 +1,38 @@ +import path from "node:path"; +import { IDE } from ".."; +import { exec } from "node:child_process"; + +export async function isOllamaInstalled(): Promise { + return new Promise((resolve, _reject) => { + const command = process.platform === "win32" ? "where ollama" : "which ollama"; + exec(command, (error, _stdout, _stderr) => { + resolve(!error); + }); + }); +} + +export async function startLocalOllama(ide: IDE): Promise { + let startCommand: string | undefined; + + switch (process.platform) { + case "darwin"://MacOS + startCommand = "open -a Ollama.app\n"; + break; + + case "win32"://Windows + startCommand = `& "ollama app.exe"\n`; + break; + + default: //Linux... + const start_script_path = path.resolve(__dirname, './start_ollama.sh'); + if (await ide.fileExists(`file:/${start_script_path}`)) { + startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`; + console.log(`Ollama Linux startup script at : ${start_script_path}`); + } else { + ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) + } + } + if (startCommand) { + return ide.runCommand(startCommand); + } +} diff --git a/core/util/start_ollama.sh b/core/util/start_ollama.sh new file mode 100755 index 000000000..ead153d2e --- /dev/null +++ b/core/util/start_ollama.sh @@ -0,0 +1,84 @@ +#!/bin/bash + +# Timeout for waiting for Ollama to start (in seconds) +readonly TIMEOUT=60 +readonly OLLAMA_API_URL="http://localhost:11434/api/version" + +# Check if a command exists +command_exists() { + command -v "$1" >/dev/null 2>&1 +} + +# Check if Ollama is already running +ollama_is_running() { + VERSION=$(curl -s --fail --max-time 1 "$OLLAMA_API_URL" | grep '"version"' | awk -F: '{ print $2 }' | sed -e 's/.*"\([^"]*\)".*/\1/') + test -n "$VERSION" +} + +# Determine if running in a container environment +in_container() { + [[ -f /.dockerenv || -f /run/.containerenv ]] +} + +# Start Ollama service or background process +start_ollama() { + local start_method="${1:-background}" + echo "Starting Ollama ($start_method)..." + + if [[ "$start_method" == "service" ]]; then + if in_container; then + service ollama start || return $? + else + sudo systemctl start ollama || return $? + fi + else + nohup ollama serve >/dev/null 2>&1 & + fi + + # Wait for Ollama to start. TIMEOUT * 4, since we sleep 1/4 sec on each iteration + for _ in $(seq 1 $((TIMEOUT * 4))); do + if ollama_is_running; then + echo -e "\nOllama started successfully." + return 0 + fi + (( _ % 2 == 0 )) && printf "." + sleep 0.25 + done + + echo -e "\nTimeout: Failed to start Ollama." + return 1 +} + +# Main script execution +main() { + # Early exit if Ollama is already running + if ollama_is_running; then + echo "Ollama is already running." + return 0 + fi + + # Try starting via service if possible + if in_container; then + if service --status-all 2>&1 | grep -qw 'ollama'; then + start_ollama service || return $? + return 0 + fi + elif command_exists systemctl; then + if systemctl list-unit-files ollama.service >/dev/null 2>&1; then + start_ollama service || return $? + return 0 + fi + fi + + # Fallback to background process + if command_exists ollama; then + start_ollama || return 1 + else + echo "Error: Ollama is not installed or not in the PATH." >&2 + return 1 + fi +} + +# Run the main function and exit with its status +main +exit $? diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 8da238311..f7bedc06c 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -25,6 +25,7 @@ const { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, copyTokenizers, + copyScripts, } = require("./utils"); // Clear folders that will be packaged to ensure clean slate @@ -108,6 +109,9 @@ async function package(target, os, arch, exe) { // copy llama tokenizers to out copyTokenizers(); + // Copy Linux scripts + await copyScripts(); + // *** Install @lancedb binary *** const lancePackageToInstall = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 833087058..4f3650ff0 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -222,6 +222,7 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/llm/llamaTokenizerWorkerPool.mjs", "../../../core/llm/llamaTokenizer.mjs", "../../../core/llm/tiktokenWorkerPool.mjs", + "../../../core/util/start_ollama.sh" ]; for (const f of filesToCopy) { diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 550d0246c..4f9ce187c 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -505,6 +505,26 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } } +async function copyScripts() { + process.chdir(path.join(continueDir, "extensions", "vscode")); + console.log("[info] Copying scripts from core"); + await new Promise((resolve, reject) => { + ncp( + path.join(__dirname, "../../../core/scripts"), + path.join(__dirname, "../out"), + { dereference: true }, + (error) => { + if (error) { + console.warn("[error] Error copying script files", error); + reject(error); + } else { + resolve(); + } + }, + ); + }); +} + module.exports = { copyConfigSchema, installNodeModules, @@ -519,4 +539,5 @@ module.exports = { downloadSqliteBinary, downloadRipgrepBinary, copyTokenizers, + copyScripts }; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index faa60cfd4..457cd5985 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -399,16 +399,14 @@ class VsCodeIde implements IDE { } async runCommand(command: string): Promise { + let terminal : vscode.Terminal | undefined; if (vscode.window.terminals.length) { - const terminal = - vscode.window.activeTerminal ?? vscode.window.terminals[0]; - terminal.show(); - terminal.sendText(command, false); + terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0]; } else { - const terminal = vscode.window.createTerminal(); - terminal.show(); - terminal.sendText(command, false); + terminal = vscode.window.createTerminal(); } + terminal.show(); + terminal.sendText(command, false); } async saveFile(fileUri: string): Promise { diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index f5388e397..3d86f64aa 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -23,6 +23,7 @@ import * as URI from "uri-js"; import type { IDE } from "core"; import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { startLocalOllama } from "core/util/ollamaHelper"; interface DiffType { count: number; @@ -44,6 +45,8 @@ export class ContinueCompletionProvider const options = ["Documentation"]; if (e.message.includes("https://ollama.ai")) { options.push("Download Ollama"); + } else if (e.message.includes("Ollama appears to be stopped")) { + options.unshift("Start Ollama"); // We want "Start" to be the default choice } if (e.message.includes("Please sign in with GitHub")) { @@ -65,6 +68,8 @@ export class ContinueCompletionProvider ); } else if (val === "Download Ollama") { vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val == "Start Ollama") { + startLocalOllama(this.ide); } }); } From 3e09a438569a2bd28c2bbb158416b5234ec12643 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Wed, 8 Jan 2025 20:02:01 +0100 Subject: [PATCH 2/4] Allow reusing specific terminal in Ide.runCommand Signed-off-by: Fred Bricon --- core/index.d.ts | 9 +++++++-- core/protocol/ide.ts | 3 ++- core/protocol/messenger/messageIde.ts | 5 +++-- core/util/filesystem.ts | 3 ++- core/util/ollamaHelper.ts | 5 ++++- extensions/vscode/src/VsCodeIde.ts | 19 +++++++++++++------ 6 files changed, 31 insertions(+), 13 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index e4f3ff143..01fb4b5c0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -630,7 +630,7 @@ export interface IDE { openUrl(url: string): Promise; - runCommand(command: string): Promise; + runCommand(command: string, options?: TerminalOptions): Promise; saveFile(fileUri: string): Promise; @@ -1230,4 +1230,9 @@ export type PackageDocsResult = { } & ( | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } -); + ); + +export interface TerminalOptions { + reuseTerminal?: boolean, + terminalName?: string, +} diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 4df3cb95b..8c0d2557c 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -14,6 +14,7 @@ import type { Range, RangeInFile, Thread, + TerminalOptions } from "../"; export interface GetGhTokenArgs { @@ -28,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { showVirtualFile: [{ name: string; content: string }, void]; openFile: [{ path: string }, void]; openUrl: [string, void]; - runCommand: [{ command: string }, void]; + runCommand: [{ command: string, options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 9f46602c1..aaa567f39 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -13,6 +13,7 @@ import type { Problem, Range, RangeInFile, + TerminalOptions, Thread, } from "../.."; @@ -151,8 +152,8 @@ export class MessageIde implements IDE { await this.request("openUrl", url); } - async runCommand(command: string): Promise { - await this.request("runCommand", { command }); + async runCommand(command: string, options?: TerminalOptions): Promise { + await this.request("runCommand", { command, options }); } async saveFile(fileUri: string): Promise { diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 45ac7a7c5..b4297f7bc 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -13,6 +13,7 @@ import { Problem, Range, RangeInFile, + TerminalOptions, Thread, ToastType, } from "../index.js"; @@ -190,7 +191,7 @@ class FileSystemIde implements IDE { return Promise.resolve(); } - runCommand(command: string): Promise { + runCommand(command: string, options?: TerminalOptions): Promise { return Promise.resolve(); } diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index 9520de678..936c6339b 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -33,6 +33,9 @@ export async function startLocalOllama(ide: IDE): Promise { } } if (startCommand) { - return ide.runCommand(startCommand); + return ide.runCommand(startCommand, { + reuseTerminal: true, + terminalName: "Start Ollama" + }); } } diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 457cd5985..2cec274e9 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -25,6 +25,7 @@ import type { Location, Problem, RangeInFile, + TerminalOptions, Thread, } from "core"; @@ -398,12 +399,18 @@ class VsCodeIde implements IDE { ); } - async runCommand(command: string): Promise { - let terminal : vscode.Terminal | undefined; - if (vscode.window.terminals.length) { - terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0]; - } else { - terminal = vscode.window.createTerminal(); + async runCommand(command: string, options: TerminalOptions = {reuseTerminal: true}): Promise { + let terminal: vscode.Terminal | undefined; + if (vscode.window.terminals.length && options.reuseTerminal) { + if (options.terminalName) { + terminal = vscode.window.terminals.find(t => t?.name === options.terminalName); + } else { + terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0]; + } + } + + if( !terminal) { + terminal = vscode.window.createTerminal(options?.terminalName); } terminal.show(); terminal.sendText(command, false); From 4b45666262125f6a7a135080c45aeb91c601e074 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 9 Jan 2025 14:56:33 +0100 Subject: [PATCH 3/4] Fix call to where.exe on Windows Signed-off-by: Fred Bricon --- core/util/ollamaHelper.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index 936c6339b..1e9c52490 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -4,7 +4,7 @@ import { exec } from "node:child_process"; export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { - const command = process.platform === "win32" ? "where ollama" : "which ollama"; + const command = process.platform === "win32" ? "where.exe ollama" : "which ollama"; exec(command, (error, _stdout, _stderr) => { resolve(!error); }); From 66f53debf113d0996795f0fe61375cc29c70021f Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 9 Jan 2025 16:48:06 +0100 Subject: [PATCH 4/4] Simplify Ollama error messages Signed-off-by: Fred Bricon --- core/llm/index.ts | 4 ++-- extensions/vscode/src/autocomplete/completionProvider.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index 4608c9bda..0b48d867c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -416,8 +416,8 @@ export abstract class BaseLLM implements ILLM { e.message.includes("http://127.0.0.1:11434") ) { const message = (await isOllamaInstalled()) ? - "Failed to connect to local Ollama instance. Ollama appears to be stopped. It needs to be running." : - "Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai." + "Unable to connect to local Ollama instance. Ollama may not be running." : + "Unable to connect to local Ollama instance. Ollama may not be installed or may not running." ; throw new Error(message); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 3d86f64aa..3fe832d3a 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -43,9 +43,9 @@ export class ContinueCompletionProvider { private onError(e: any) { const options = ["Documentation"]; - if (e.message.includes("https://ollama.ai")) { + if (e.message.includes("Ollama may not be installed")) { options.push("Download Ollama"); - } else if (e.message.includes("Ollama appears to be stopped")) { + } else if (e.message.includes("Ollama may not be running")) { options.unshift("Start Ollama"); // We want "Start" to be the default choice }