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/llm/index.ts b/core/llm/index.ts index 5c0253e86..0b48d867c 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()) ? + "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); } } throw new Error(e.message); 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 new file mode 100644 index 000000000..1e9c52490 --- /dev/null +++ b/core/util/ollamaHelper.ts @@ -0,0 +1,41 @@ +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.exe 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, { + reuseTerminal: true, + terminalName: "Start Ollama" + }); + } +} 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..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,17 +399,21 @@ class VsCodeIde implements IDE { ); } - async runCommand(command: string): Promise { - if (vscode.window.terminals.length) { - const terminal = - vscode.window.activeTerminal ?? vscode.window.terminals[0]; - terminal.show(); - terminal.sendText(command, false); - } else { - const terminal = vscode.window.createTerminal(); - terminal.show(); - terminal.sendText(command, false); + 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); } async saveFile(fileUri: string): Promise { diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d6053869c..c10d4d5f1 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -22,6 +22,7 @@ import { } from "./statusBar"; import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; const Diff = require("diff"); @@ -44,8 +45,10 @@ 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 may not be running")) { + options.unshift("Start Ollama"); // We want "Start" to be the default choice } if (e.message.includes("Please sign in with GitHub")) { @@ -67,6 +70,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); } }); }