diff --git a/.cursor/rules/architecture.mdc b/.cursor/rules/architecture.mdc index 5395db1d7..e3c948d31 100644 --- a/.cursor/rules/architecture.mdc +++ b/.cursor/rules/architecture.mdc @@ -69,6 +69,9 @@ The binary inventory and launch ownership live in `nvpair-engine-manager` owns lifecycle and model operations. - Engine server ports and proxy ports are persisted by their backend owners. +- The engine manager identifies the installed version, selects the appropriate + release for local Ollama, and applies managed updates. The desktop + schedules checks and presents the reported action. - Desired engine state is restored by the backend. - Leave shutdown ordering to the broker. Its shutdown stops the proxy, then the engines through `engine:prepare-shutdown`, then the workers. Clients do not diff --git a/.cursor/rules/system-architecture.mdc b/.cursor/rules/system-architecture.mdc index fe2f8c7da..041eb89f4 100644 --- a/.cursor/rules/system-architecture.mdc +++ b/.cursor/rules/system-architecture.mdc @@ -211,8 +211,10 @@ detail of either; a change to one is a change to both. Neither drives the other. `nvpair-engine-manager` owns lifecycle, port, desired-state, and model operations. -- Local lifecycle supports install, start, stop, uninstall, update, and port - changes. +- Local lifecycle supports install, start, stop, uninstall, and port changes. + The desktop checks local Ollama through `engine:check-updates` and + sends `engine:update` for managed updates. An external update opens the + engine manager's vendor download URL for the detected installation. - Remote lifecycle uses the engine manager's remote control methods where available. - `engine:prepare-shutdown` stops processes without clearing persisted desired diff --git a/README.md b/README.md index d1bc38df7..6d251881d 100644 --- a/README.md +++ b/README.md @@ -236,8 +236,9 @@ Each entry assumes the ones before it. most users need. When you update, **[Release notes](docs/release-notes.mdx)** lists what changed and the **[Upgrade guide](docs/upgrade-guide.mdx)** covers any steps the update needs. -3. **[Managing engines](docs/engine-lifecycle.mdx)** — install, start, stop, - update, and uninstall engines; what PAIR restores after you quit or relaunch. +3. **[Managing engines](docs/engine-lifecycle.mdx)** — install, start, stop, and + uninstall engines, check for Ollama updates on this machine, and see what PAIR + restores on relaunch. 4. **[Engine settings](docs/engine-settings.mdx)** — change an engine's ports and its launch command, on this machine or a paired one, and give a browser access to your models. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index d51203ca9..31a55d05e 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -217,6 +217,7 @@ binaries across the Windows, Linux, and macOS targets. First-party modules | `github.com/rivo/uniseg` | v0.4.7 | MIT | | `github.com/xo/terminfo` | v0.0.0-20220910002029-abceb7e1c41e | MIT | | `github.com/yusufpapurcu/wmi` | v1.2.4 | MIT | +| `golang.org/x/mod` | v0.12.0 | BSD-3-Clause | | `golang.org/x/net` | v0.58.0 | BSD-3-Clause | | `golang.org/x/sys` | v0.47.0 | BSD-3-Clause | | `golang.org/x/text` | v0.3.8 | BSD-3-Clause | @@ -7212,6 +7213,42 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` +### golang.org/x/mod v0.12.0 + +License: BSD-3-Clause + +Repository: https://golang.org/x/mod + +```text +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + ### golang.org/x/net v0.58.0 License: BSD-3-Clause diff --git a/desktop/docs/architecture.md b/desktop/docs/architecture.md index e666011a3..5b2e283e5 100644 --- a/desktop/docs/architecture.md +++ b/desktop/docs/architecture.md @@ -208,6 +208,11 @@ closed `EngineType` union and narrows external strings with `isEngineType()`. `engineManagerName()` / `engineTypeFromManagerName()` are the one place that translation to and from the engine manager's own spelling lives. +The desktop schedules release checks for local Ollama. The engine manager +compares versions, determines installation ownership, and applies managed +updates. The bridge publishes availability through the existing engine snapshot +and `engines:state-changed` updates. + ### Model downloads A download is started with `engine:action{pull_model}`, or diff --git a/desktop/docs/frontend-api.md b/desktop/docs/frontend-api.md index b9f89dd1b..054706798 100644 --- a/desktop/docs/frontend-api.md +++ b/desktop/docs/frontend-api.md @@ -94,7 +94,9 @@ They do not imply a WebSocket connection. Browser clients are not supported. - `getInitialState()` returns engine statuses, models, active progress, and available updates. -- `toggle`, `install`, `uninstall`, and `update` manage engine lifecycle. +- `toggle`, `install`, and `uninstall` manage engine lifecycle. `update` applies + an available release to a PAIR-managed engine on the local node. For an external + installation, the engine row links to the vendor's update instructions or release. - `pullModel`, `cancelModelPull`, `loadModel`, `unloadModel`, `deleteModel`, and `setModelExpiry` manage models. - `searchHub(engineType, nodeId)` returns the curated model catalog for a diff --git a/desktop/docs/services-api.md b/desktop/docs/services-api.md index 61cb7e6d5..510eec6ec 100644 --- a/desktop/docs/services-api.md +++ b/desktop/docs/services-api.md @@ -97,6 +97,7 @@ | `engine:action` | request (we call) | ✅ yes | | `engine:cancel-pull` | request (we call) | ✅ yes | | `engine:catalog` | request (we call) | ✅ yes | +| `engine:check-updates` | request (we call) | ✅ yes | | `engine:configure-launch` | request (we call) | ⚠️ not called | | `engine:configured-ports` | request (we call) | ⚠️ not called | | `engine:describe` | request (we call) | ⚠️ not called | @@ -127,6 +128,7 @@ | `engine:stop` | request (we call) | ✅ yes | | `engine:uninstall` | request (we call) | ✅ yes | | `engine:uninstall-managed` | request (we call) | ✅ yes | +| `engine:update` | request (we call) | ✅ yes | | `error` | request (we call) | ✅ yes | | `internal:set-reserved-port` | request (we call) | ⚠️ not called | @@ -275,7 +277,9 @@ | `discovery:subscribe` | request (we call) | ✅ yes | | `discovery:unsubscribe` | request (we call) | ⚠️ not called | | `engine:apply-settings` | request (we call) | ✅ yes | +| `engine:check-updates` | request (we call) | ✅ yes | | `engine:configure-launch` | request (we call) | ⚠️ not called | +| `engine:get-installed` | request (we call) | ✅ yes | | `engine:get-settings` | request (we call) | ✅ yes | | `engine:install` | request (we call) | ✅ yes | | `engine:preview-settings` | request (we call) | ✅ yes | @@ -283,9 +287,11 @@ | `engine:set-port` | request (we call) | ⚠️ not called | | `engine:set-reserved-port` | request (we call) | ⚠️ not called | | `engine:start` | request (we call) | ✅ yes | +| `engine:status` | request (we call) | ✅ yes | | `engine:stop` | request (we call) | ✅ yes | | `engine:subscribe` | request (we call) | ✅ yes | | `engine:unsubscribe` | request (we call) | ⚠️ not called | +| `engine:update` | request (we call) | ✅ yes | | `errors:get-initial` | request (we call) | ✅ yes | | `internal:set-reserved-port` | request (we call) | ⚠️ not called | | `node/add` | request (we call) | ✅ yes | diff --git a/desktop/docs/services-backend.md b/desktop/docs/services-backend.md index 3a1c23279..18552cc9b 100644 --- a/desktop/docs/services-backend.md +++ b/desktop/docs/services-backend.md @@ -170,8 +170,12 @@ one centralized pending-action layer so controls respond immediately while waiting for authoritative state. Pending state clears on matching engine state, progress, or error pushes. -Local engine operations include install, start, stop, uninstall, update, port -changes, and model actions. Remote cluster operations use the engine manager's +Local engine operations include install, start, stop, uninstall, port changes, +and model actions. The desktop calls `engine:check-updates` at startup and every +six hours for local Ollama. Starting or stopping Ollama also triggers a +background check. The bridge projects each successful result into +`updateAvailable` for the renderer. Selecting **Update** sends `engine:update` +for a managed installation. Remote cluster operations use the engine manager's remote control surface where supported. ### Cancelling a download diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index 5fd72a98f..6581d3168 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -29,7 +29,7 @@ history. | Local engine lifecycle | Complete | Install, start, stop, uninstall, update, and port configuration | | Remote engine lifecycle | Partial | Remote install, start, stop, status, and model pull are supported | | Engine models | Partial | Core list, pull, load, unload, and supported delete actions are wired | -| Engine version metadata | Backend-limited | The backend status surface does not provide a complete version/install-owner/update contract | +| Engine version metadata | Local Ollama | The engine manager compares the installed version with the applicable platform release and distinguishes managed and external installs. | | Errors | Complete | Broker-relayed registry with peer synchronization | | Workloads | Complete after subscription | Local and peer workload events feed one Electron catalog | | Cluster pairing | Complete | PIN pairing, identity, membership, leave, and removal | @@ -279,11 +279,11 @@ genuinely foreign listener (with an actionable error). Personal AI Router treats desired state as authoritative and surfaces a stop error as guidance, not as a sign the OFF choice was discarded. -For ease of use, Personal AI Router issues starts in two additional cases and -keeps no auto-start list of its own: every install sends `engine:install` with -`start: true`, so a successful install (or managed update) starts the engine; -and on the first app open Personal AI Router starts every already-installed local -engine once. Both paths rely on the backend recording desired-enabled as a side +Every install sends `engine:install` with `start: true`, so a successful install +starts the engine. A managed engine update uses `engine:update` and preserves +the engine's running or stopped state. On the first app open Personal AI Router +starts every already-installed local engine once. Install and first-open starts +rely on the engine manager recording desired-enabled as a side effect of start, so `nvpair-engine-manager` remains the single owner of desired-state persistence and restoration. diff --git a/desktop/src/electron/main.ts b/desktop/src/electron/main.ts index 05db8504c..328ff4587 100644 --- a/desktop/src/electron/main.ts +++ b/desktop/src/electron/main.ts @@ -26,6 +26,8 @@ import { macPrivilege } from '@/electron/services/mac-privilege-service' import { registerAllIpc } from '@/electron/ipc' import { destroyConnector, destroyConnectorSync, initializeConnector } from '@/electron/connector' import { initializeUpdater } from '@/electron/updater' +import { subscribeEngineUpdateNotifications } from '@/electron/updater/engine-update-notification' +import { getModularBridgeState } from '@/electron/service-bridge/modular-state' import { ensureNvpairOnPath } from '@/electron/nvpair-command' import { isAppDataWipeScheduled } from '@/electron/app-data-wipe-orchestrator' import { destroyInferenceDemoSync, stopInferenceDemo } from '@/electron/inference-demo' @@ -162,6 +164,10 @@ if (!gotTheLock || exitRequested) { registerAllIpc() initializeUpdater() + const unsubscribeEngineUpdates = subscribeEngineUpdateNotifications(() => + getModularBridgeState().getSelfId() + ) + app.once('will-quit', unsubscribeEngineUpdates) // Bound startup on broker `app:ready` before opening the normal Overview. // Proxy readiness is not part of this gate — it is an asynchronous diff --git a/desktop/src/electron/service-bridge/empty-handlers.ts b/desktop/src/electron/service-bridge/empty-handlers.ts index e26c8ac62..df013fa73 100644 --- a/desktop/src/electron/service-bridge/empty-handlers.ts +++ b/desktop/src/electron/service-bridge/empty-handlers.ts @@ -240,15 +240,21 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): // Use the engine-manager's stable error key. If the manager already reported // the operation failure, nvpair-errors upserts this fallback instead of showing // a duplicate; admission/transport failures still get a visible error. - const failPendingOp = (action: string, operation: 'install' | 'uninstall') => { + const failPendingOp = (operation: 'install' | 'uninstall' | 'update') => { return (error: string): void => { state.clearPendingEngineOp(payload.engineType) - supervisor.reportError(`Failed to ${action} ${engine}: ${error}`, 'error', undefined, { - id: `engine-manager:${operation}-failed:${engine}`, - engineType: engine, - operation, - action: 'retry' - }) + supervisor.reportError( + `Failed to ${operation} ${engine}: ${error}`, + 'error', + undefined, + { + id: `engine-manager:${operation}-failed:${engine}`, + nodeId: payload.nodeId, + engineType: payload.engineType, + operation, + action: 'retry' + } + ) } } const failAction = @@ -273,7 +279,7 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): 'broker', 'engine:install', { engine, start: true }, - failPendingOp('install', 'install'), + failPendingOp('install'), true ) break @@ -283,28 +289,25 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): 'broker', 'engine:uninstall', { engine }, - failPendingOp('uninstall', 'uninstall'), + failPendingOp('uninstall'), true ) break case 'update': - // The engine-manager serializes per-engine ops via its lifecycle - // lock, so the queued install waits for the uninstall to finish. The - // uninstall's engine:state-changed briefly clears this, then the - // install's progress re-establishes `installing`. + if (!payload.nodeId || payload.nodeId !== state.getSelfId()) { + supervisor.reportError( + 'Engine updates are available on the local node.', + 'warning', + 'engine-cmd:update' + ) + break + } state.beginLocalEngineOp(payload.engineType, 'installing') supervisor.sendProcess( 'broker', - 'engine:uninstall', + 'engine:update', { engine }, - failPendingOp('update', 'uninstall'), - true - ) - supervisor.sendProcess( - 'broker', - 'engine:install', - { engine, start: true }, - failPendingOp('update', 'install'), + failPendingOp('update'), true ) break diff --git a/desktop/src/electron/service-bridge/engine-update-checks.ts b/desktop/src/electron/service-bridge/engine-update-checks.ts new file mode 100644 index 000000000..2f6d60c7e --- /dev/null +++ b/desktop/src/electron/service-bridge/engine-update-checks.ts @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createStructuredLogger } from '@/shared/utils/log' +import getErrorString from '@/shared/utils/get-error-string' +import type { EngineType } from '@/shared/types/engines' +import type { JsonValue } from './json-rpc-subprocess' +import { getModularBridgeState } from './modular-state' + +const log = createStructuredLogger('service-bridge') +const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000 + +/** One timer per broker. Coalesce lifecycle changes independently for each engine. */ +export function watchEngineUpdates(check: (engine: EngineType) => Promise): { + refresh: (engine?: EngineType) => Promise + stop: () => void +} { + const state = getModularBridgeState() + let active = true + const checking = new Set() + const requested = new Set() + + async function checkEngine(engine: EngineType): Promise { + requested.add(engine) + if (checking.has(engine)) return + checking.add(engine) + try { + while (active && requested.delete(engine)) { + const nodeId = state.getSelfId() + if (!nodeId || !state.supportsEngine(engine)) return + try { + const result = await check(engine) + if (active && !requested.has(engine)) { + state.applyEngineUpdateCheck(nodeId, engine, result) + } + } catch (error) { + log.verbose({ + sublevel: 'engine-manager', + message: `${engine} update check unavailable: ${getErrorString(error)}` + }) + } + } + } finally { + checking.delete(engine) + } + } + + async function refresh(engine: EngineType = 'ollama'): Promise { + if (engine === 'ollama') await checkEngine(engine) + } + + const timer = setInterval(() => void refresh(), CHECK_INTERVAL_MS) + state.setEngineUpdateRefresher(refresh) + void refresh() + return { + refresh, + stop(): void { + if (!active) return + active = false + clearInterval(timer) + state.setEngineUpdateRefresher(undefined) + state.clearEngineUpdates() + } + } +} diff --git a/desktop/src/electron/service-bridge/modular-state.ts b/desktop/src/electron/service-bridge/modular-state.ts index c873ccd17..aaefe9b29 100644 --- a/desktop/src/electron/service-bridge/modular-state.ts +++ b/desktop/src/electron/service-bridge/modular-state.ts @@ -8,6 +8,7 @@ import type { EngineProgress, EngineStatusData, EngineType, + EngineUpdateAvailable, ModelItem } from '@/shared/types/engines' import type { LogEntry, LogPage } from '@/shared/types/log' @@ -254,6 +255,13 @@ function stringValue(value: JsonValue | undefined): string { return typeof value === 'string' ? value : '' } +/** The local engine manager selects the vendor URLs for this installation. */ +function updateLink(value: JsonValue | undefined): string | undefined { + if (typeof value !== 'string' || !URL.canParse(value)) return undefined + const url = new URL(value) + return url.protocol === 'https:' && !url.username && !url.password ? url.href : undefined +} + function numberValue(value: JsonValue | undefined): number { return typeof value === 'number' ? value : 0 } @@ -957,6 +965,8 @@ class ModularBridgeState { vllm: 0 } private selfId: string | null = null + private engineUpdates = new Map() + private refreshEngineUpdates?: (engineType?: EngineType) => void /** * Authoritative local-engine facts from `nvpair-engine-manager`, keyed by * engine type. Stored independent of `selfId` because engine-manager @@ -1135,8 +1145,77 @@ class ModularBridgeState { setSelfId(nodeUuid: string): void { const trimmed = nodeUuid.trim() if (!trimmed || this.selfId === trimmed) return + this.clearEngineUpdates() this.selfId = trimmed emitBridgePush('state:request-refresh', undefined) + this.refreshEngineUpdates?.() + } + + supportsEngine(engine: EngineType): boolean { + return this.localEngineList?.has(engine) ?? false + } + + setEngineUpdateRefresher(refresh?: (engineType?: EngineType) => void): void { + this.refreshEngineUpdates = refresh + } + + clearEngineUpdates(): void { + for (const engine of this.engineUpdates.keys()) this.clearEngineUpdate(engine) + } + + private clearEngineUpdate(engineType: EngineType): void { + const update = this.engineUpdates.get(engineType) + if (!update) return + this.engineUpdates.delete(engineType) + emitBridgePush('engines:state-changed', { + nodeId: update.nodeId, + engineType, + updateAvailable: null + }) + } + + applyEngineUpdateCheck( + nodeId: string, + engineType: EngineType, + result: JsonValue | undefined + ): void { + if (nodeId !== this.selfId || !this.supportsEngine(engineType)) return + const value = objectValue(result)?.updateAvailable + if (value === null) { + this.clearEngineUpdate(engineType) + return + } + const info = objectValue(value) + if (!info) return + const currentVersion = stringValue(info.currentVersion) + const latestVersion = stringValue(info.latestVersion) + const releaseUrl = updateLink(info.releaseUrl) + const downloadUrl = updateLink(info.downloadUrl) + const installType = info.installType + if (!currentVersion || !latestVersion || !releaseUrl) return + if (info.downloadUrl !== undefined && !downloadUrl) return + const release = { nodeId, engineType, currentVersion, latestVersion, releaseUrl } + let update: EngineUpdateAvailable + if (installType === 'external' && downloadUrl) { + update = { ...release, installType, downloadUrl } + } else if (installType === 'managed') { + update = { ...release, installType, ...(downloadUrl && { downloadUrl }) } + } else return + const previous = this.engineUpdates.get(engineType) + if ( + previous?.currentVersion === currentVersion && + previous.latestVersion === latestVersion && + previous.releaseUrl === releaseUrl && + previous.downloadUrl === downloadUrl && + previous.installType === installType + ) + return + this.engineUpdates.set(engineType, update) + emitBridgePush('engines:state-changed', { + nodeId, + engineType, + updateAvailable: update + }) } /** Bound proxy port for an engine reported by the broker, or null if unknown. */ @@ -1205,7 +1284,7 @@ class ModularBridgeState { statuses, models, activeProgress: Array.from(this.activePulls.values()), - updateAvailable: [] + updateAvailable: Array.from(this.engineUpdates.values()) } } @@ -1370,15 +1449,19 @@ class ModularBridgeState { if (!Array.isArray(list)) return const listed = new Set() for (const entry of list) { - this.applyEngineManagerStatus(entry) const engineType = engineTypeFromManagerName(stringValue(objectValue(entry)?.engine)) if (engineType) listed.add(engineType) } // An empty listing says nothing about what the host can run. if (listed.size === 0) return this.localEngineList = listed + for (const entry of list) this.applyEngineManagerStatus(entry) for (const engineType of EngineTypes) { - if (!listed.has(engineType)) this.emitLocalEngineStatus(engineType) + if (!listed.has(engineType)) { + this.engineManagerFacts.delete(engineType) + this.clearEngineUpdate(engineType) + this.emitLocalEngineStatus(engineType) + } } } @@ -1393,19 +1476,29 @@ class ModularBridgeState { const engineType = engineTypeFromManagerName(stringValue(obj.engine)) if (!engineType) return - this.engineManagerFacts.set(engineType, { + const previous = this.engineManagerFacts.get(engineType) + const facts = { installed: booleanValue(obj.installed), running: booleanValue(obj.running), starting: booleanValue(obj.starting), awaitingModel: booleanValue(obj.awaiting_model), port: numberValue(obj.port) - }) + } + this.engineManagerFacts.set(engineType, facts) // A fresh authoritative state is the resolution of whatever op was in // flight (start/stop done, install `done`+installed, uninstall removed). // Drop the optimistic status without re-emitting here — the emit below // already carries the resolved, fact-derived status. this.discardPendingOp(engineType) this.emitLocalEngineStatus(engineType) + // Enabling vLLM can leave it awaiting a model without a serving process. + const lifecycleChanged = + !facts.starting && + (facts.running !== previous?.running || facts.awaitingModel !== previous?.awaitingModel) + if (facts.installed !== previous?.installed || lifecycleChanged) { + if (!facts.installed) this.clearEngineUpdate(engineType) + this.refreshEngineUpdates?.(engineType) + } } /** @@ -1427,10 +1520,16 @@ class ModularBridgeState { * `errors:report` that carries no `engine:state-changed` (LM Studio * start-command failure, uninstall failure, install failure). Called by the * supervisor's error demux. `operation` is the engine-manager error's - * `operation` field (`start` | `install` | `uninstall`). + * `operation` field (`start` | `install` | `uninstall` | `update`). */ failLocalEngineOp(engineManagerEngine: string, operation: string): void { - if (operation !== 'start' && operation !== 'install' && operation !== 'uninstall') return + if ( + operation !== 'start' && + operation !== 'install' && + operation !== 'uninstall' && + operation !== 'update' + ) + return const engineType = engineTypeFromManagerName(engineManagerEngine) ?? (isEngineType(engineManagerEngine) ? engineManagerEngine : null) @@ -2176,6 +2275,10 @@ class ModularBridgeState { // done / already-installed -> success, failed -> error (percent -1). // On any terminal stage we clear the ephemeral progress entry. if (stage === 'done' || stage === 'already-installed' || stage === 'failed') { + if (stage !== 'failed') { + if (stage === 'done') this.clearEngineUpdate(engineType) + this.refreshEngineUpdates?.(engineType) + } emitBridgePush('engines:progress-cleared', { key: `${nodeId}:${engineType}:install` }) diff --git a/desktop/src/electron/service-bridge/modular-supervisor.ts b/desktop/src/electron/service-bridge/modular-supervisor.ts index 8d23bae35..8bb37e388 100644 --- a/desktop/src/electron/service-bridge/modular-supervisor.ts +++ b/desktop/src/electron/service-bridge/modular-supervisor.ts @@ -33,6 +33,7 @@ import { type ProxyEngine } from './proxy-engines' import { emitBridgePush } from './broadcaster' +import { watchEngineUpdates } from './engine-update-checks' import { parseEngineSettings } from './engine-settings' import { resolvePullCatchError } from './pull-error-handling' import { serviceLogLevel } from './service-log-level' @@ -372,6 +373,7 @@ class ModularSupervisor { private clusterPeerIds = new Set() // Light interval that re-polls clusterPeerIds' authoritative engine status. private remoteStatusTimer: ReturnType | null = null + private engineUpdateChecks?: ReturnType // Debounced follow-up poll when discovery:nodes-changed lands — the ec peer // directory in engine-manager is fed from that relay and may not be ready for // the first broker-ready sweep. @@ -526,6 +528,7 @@ class ModularSupervisor { // Mark teardown first so the broker's exit during stop() is treated as a // deliberate shutdown, not a crash. this.shuttingDown = true + this.stopEngineUpdateChecks() if (this.remoteStatusDebounceTimer) { clearTimeout(this.remoteStatusDebounceTimer) this.remoteStatusDebounceTimer = null @@ -748,6 +751,7 @@ class ModularSupervisor { if (!isCurrent()) return this.processes.delete(child.name as ModularProcessName) if (child.name === 'broker') { + this.stopEngineUpdateChecks() this.brokerReady = false this.brokerHydrationDone = false this.isReady = false @@ -1062,12 +1066,22 @@ class ModularSupervisor { } private async hydrateEngineManager(): Promise { - if (!this.processes.has('broker')) return + const broker = this.processes.get('broker') + if (!broker) return try { const result = await this.callProcess('broker', 'engine:get-installed') + if (this.processes.get('broker') !== broker || this.shuttingDown) return const obj = objectValue(result) - if (!obj || !Array.isArray(obj.engines)) return + if (!obj || !Array.isArray(obj.engines) || obj.engines.length === 0) return getModularBridgeState().applyEngineManagerList(result) + this.engineUpdateChecks ??= watchEngineUpdates(engine => + this.callProcess( + 'broker', + 'engine:check-updates', + { engine: engineManagerName(engine) }, + 30_000 + ) + ) for (const engine of obj.engines) { this.refreshManagedEngineModels(engine) } @@ -1079,6 +1093,11 @@ class ModularSupervisor { } } + private stopEngineUpdateChecks(): void { + this.engineUpdateChecks?.stop() + this.engineUpdateChecks = undefined + } + /** * On the very first app open, start every already-installed local engine. * The backend persists desired-enabled as a side effect of start, so this is diff --git a/desktop/src/electron/updater/engine-update-notification.ts b/desktop/src/electron/updater/engine-update-notification.ts new file mode 100644 index 000000000..d6c3c92fe --- /dev/null +++ b/desktop/src/electron/updater/engine-update-notification.ts @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { subscribePush } from '@/electron/service-bridge/push-bus' +import { dismissOverviewMessage, showOverviewMessage } from '@/electron/window' +import { EngineDisplayNames } from '@/shared/constants/engines' +import type { EngineType } from '@/shared/types/engines' + +export function subscribeEngineUpdateNotifications( + getLocalNodeId: () => string | null +): () => void { + const notifiedVersions = new Set() + const currentNotices = new Map() + return subscribePush(event => { + if (event.channel !== 'engines:state-changed') return + const { nodeId, engineType, updateAvailable } = event.payload + if (nodeId !== getLocalNodeId() || updateAvailable === undefined) return + + const id = updateAvailable + ? `engine-update:${nodeId}:${engineType}:${updateAvailable.latestVersion}` + : null + const currentNotice = currentNotices.get(engineType) + if (currentNotice && currentNotice !== id) dismissOverviewMessage(currentNotice) + currentNotices.set(engineType, id) + if (!id || !updateAvailable || notifiedVersions.has(id)) return + notifiedVersions.add(id) + const name = EngineDisplayNames[engineType] + showOverviewMessage({ + id, + kind: 'update', + title: `${name} update available`, + body: `${name} ${updateAvailable.latestVersion} is available. This node has ${updateAvailable.currentVersion} installed.`, + actionLabel: 'Open engine settings', + action: { type: 'open-engine-settings', nodeId } + }) + }) +} diff --git a/desktop/src/electron/window.ts b/desktop/src/electron/window.ts index 1a2d4a109..3a80b5ea5 100644 --- a/desktop/src/electron/window.ts +++ b/desktop/src/electron/window.ts @@ -250,6 +250,15 @@ export function showOverviewMessage(message: OverviewMessage): void { enqueueOverviewCommand({ type: 'message', message }, false) } +/** Withdraw a notice that has become obsolete while Overview was closed or open. */ +export function dismissOverviewMessage(id: string): void { + pendingOverviewCommands = pendingOverviewCommands.filter( + command => command.type !== 'message' || command.message.id !== id + ) + if (getOverviewWindow() && overviewReady) + enqueueOverviewCommand({ type: 'dismiss-message', id }, false) +} + // Background throttling is left at Chromium's default (on). With it off, a hidden // or occluded window kept animating at full frame rate: the GPU process sat at // 50-80% of a core and the never-shown tray window at ~5% around the clock. diff --git a/desktop/src/shared/types/engines.ts b/desktop/src/shared/types/engines.ts index 356fd8a14..cc4026f20 100644 --- a/desktop/src/shared/types/engines.ts +++ b/desktop/src/shared/types/engines.ts @@ -82,21 +82,17 @@ export interface EngineProgress { error?: string } -/** - * Available engine-update signal for one engine on one node. The backend - * reports it per node; PAIR receives it through `engines:state-changed` and - * the renderer's `engine-update-available.store`, so the Edit Node UI can - * surface an Update affordance for any node — local or remote — the user can - * reach in the cluster. - */ -export interface EngineUpdateAvailable { +/** Local engine manager update reported in the bridge snapshot and state patches. */ +export type EngineUpdateAvailable = { nodeId: string engineType: EngineType currentVersion: string latestVersion: string releaseUrl: string - installType: 'managed' | 'external' -} +} & ( + | { installType: 'managed'; downloadUrl?: string } + | { installType: 'external'; downloadUrl: string } +) export interface EngineModels { engineType: EngineType diff --git a/desktop/src/shared/types/overview.ts b/desktop/src/shared/types/overview.ts index f04ad5d54..6999c8dfe 100644 --- a/desktop/src/shared/types/overview.ts +++ b/desktop/src/shared/types/overview.ts @@ -5,7 +5,10 @@ export type OverviewTab = 'overview' | 'settings' /** What an Overview message modal's action button does when clicked. */ -export type OverviewMessageAction = 'open-update' | 'open-service' +type OverviewMessageAction = + | 'open-update' + | 'open-service' + | { type: 'open-engine-settings'; nodeId: string } /** * A one-off message surfaced as a modal on the Overview window. Replaces the @@ -28,3 +31,4 @@ export interface OverviewMessage { export type OverviewCommand = | { type: 'focus-node'; nodeId: string } | { type: 'message'; message: OverviewMessage } + | { type: 'dismiss-message'; id: string } diff --git a/desktop/src/ui/components/AppMessageModal.tsx b/desktop/src/ui/components/AppMessageModal.tsx index 9683ce7b4..61dd66232 100644 --- a/desktop/src/ui/components/AppMessageModal.tsx +++ b/desktop/src/ui/components/AppMessageModal.tsx @@ -27,10 +27,13 @@ export function AppMessageModal({ onClose: () => void }) { const openSettings = useOverviewUiStore(s => s.openSettings) + const focusNodeEngineSettings = useOverviewUiStore(s => s.focusNodeEngineSettings) const handleAction = (): void => { if (message.action === 'open-update' || message.action === 'open-service') { openSettings('service') + } else if (message.action?.type === 'open-engine-settings') { + focusNodeEngineSettings(message.action.nodeId) } onClose() } diff --git a/desktop/src/ui/components/BackendRow/BackendFooter.tsx b/desktop/src/ui/components/BackendRow/BackendFooter.tsx index fc7ece399..cb7981f46 100644 --- a/desktop/src/ui/components/BackendRow/BackendFooter.tsx +++ b/desktop/src/ui/components/BackendRow/BackendFooter.tsx @@ -8,6 +8,7 @@ import { OpenInNew } from '@/ui/components/icons' import type { BackendInfo } from '@/ui/types/engine-info' import type { PlatformDisplayName } from '@/shared/types/platform' import { canAutoInstallBackendForOs } from '@/ui/utils/backend-target-os' +import { displayEngineVersion } from '@/ui/utils/status' const INLINE_LINK_STYLE: CSSProperties = { alignItems: 'center', @@ -16,10 +17,6 @@ const INLINE_LINK_STYLE: CSSProperties = { lineHeight: 1 } -function displayVersion(version: string): string { - return version.startsWith('v') ? version : `v${version}` -} - export function BackendFooter({ backend, targetOs, @@ -47,11 +44,7 @@ export function BackendFooter({ window.windowApi.window.openExternal(url) }, []) - const installedVersion = backend.installedVersion - ? displayVersion(backend.installedVersion) - : backend.updateAvailable - ? displayVersion(backend.updateAvailable.currentVersion) - : null + const installedVersion = backend.installedVersion ?? backend.updateAvailable?.currentVersion return ( @@ -94,7 +87,7 @@ export function BackendFooter({ )} {installedVersion && ( - {installedVersion} + {displayEngineVersion(installedVersion)} )} diff --git a/desktop/src/ui/components/BackendRow/BackendRow.tsx b/desktop/src/ui/components/BackendRow/BackendRow.tsx index 49986a4e2..7de09a3be 100644 --- a/desktop/src/ui/components/BackendRow/BackendRow.tsx +++ b/desktop/src/ui/components/BackendRow/BackendRow.tsx @@ -13,6 +13,7 @@ import { useEngineStatusStore } from '@/ui/stores/engine-status.store' import { useNodesStore } from '@/ui/stores/nodes.store' import { useEngineProgressStore } from '@/ui/stores/engine-progress.store' +import { useEngineUpdateAvailableStore } from '@/ui/stores/engine-update-available.store' import { usePendingActionsStore } from '@/ui/stores/pending-actions.store' import type { EngineCommandType } from '@/shared/types/engine-api' @@ -92,6 +93,12 @@ export function BackendRow({ s.getLifecyclePending(nodeId, backend.type) ) + const selfId = useConnectionStore(state => state.selfId) + const isLocalNode = nodeId === selfId + const updateAvailable = useEngineUpdateAvailableStore(state => + isLocalNode ? state.getInfo(nodeId, backend.type) : undefined + ) + const displayBackend = useMemo((): BackendInfo => { // While an optimistic lifecycle command is in flight, show its // transitional status so the header spins immediately. Real transition @@ -99,10 +106,11 @@ export function BackendRow({ const synthetic = lifecyclePending ? syntheticPendingStatus(lifecyclePending, backend.processStatus) : null - const base: BackendInfo = - synthetic && synthetic !== backend.processStatus - ? { ...backend, processStatus: synthetic } - : backend + const base: BackendInfo = { + ...backend, + processStatus: synthetic ?? backend.processStatus, + updateAvailable + } if (installProgress) { return { ...base, @@ -113,10 +121,7 @@ export function BackendRow({ } } return base - }, [installProgress, backend, lifecyclePending]) - - const selfId = useConnectionStore(state => state.selfId) - const isLocalNode = nodeId === selfId + }, [installProgress, backend, lifecyclePending, updateAvailable]) // Remote peers may not have polled engine facts yet; refresh status when the // accordion opens so LM Studio and other engines are not stuck as Unavailable. @@ -191,12 +196,6 @@ export function BackendRow({ const content = expanded ? ( - - {canShowAccordions && ( )} @@ -237,6 +236,11 @@ export function BackendRow({ targetOs={targetOs} onInstall={handleInstall} /> + {expanded && } {content} diff --git a/desktop/src/ui/components/BackendRow/BackendUpdateBanner.tsx b/desktop/src/ui/components/BackendRow/BackendUpdateBanner.tsx index 57779bc6a..e2ca3d588 100644 --- a/desktop/src/ui/components/BackendRow/BackendUpdateBanner.tsx +++ b/desktop/src/ui/components/BackendRow/BackendUpdateBanner.tsx @@ -5,6 +5,7 @@ import { useCallback } from 'react' import type { CSSProperties } from 'react' import { Banner, Button, Flex, Stack, Text } from '@nvidia/foundations-react-core' import { OpenInNew } from '@/ui/components/icons' +import { displayEngineVersion } from '@/ui/utils/status' import type { BackendInfo } from '@/ui/types/engine-info' const BANNER_LINK_STYLE: CSSProperties = { @@ -14,10 +15,6 @@ const BANNER_LINK_STYLE: CSSProperties = { lineHeight: 1 } -function displayVersion(version: string): string { - return version.startsWith('v') ? version : `v${version}` -} - export function BackendUpdateBanner({ backend, disabled, @@ -33,41 +30,61 @@ export function BackendUpdateBanner({ window.windowApi.window.openExternal(url) }, []) - const isTransitioning = - backend.processStatus === 'installing' || backend.processStatus === 'uninstalling' - const showUpdateBanner = - backend.processStatus !== 'not-installed' && !isTransitioning && !!backend.updateAvailable - - if (!showUpdateBanner || !backend.updateAvailable) return null - const updateAvailable = backend.updateAvailable + const { processStatus, updateAvailable } = backend + if ( + !updateAvailable || + processStatus === 'unsupported' || + processStatus === 'uninstalling' || + processStatus === 'installing' || + (processStatus === 'not-installed' && updateAvailable.installType === 'managed') + ) + return null return ( - + - {updateAvailable.installType === 'managed' - ? `Update available: ${displayVersion(updateAvailable.latestVersion)}` - : `New ${backend.displayName} release: ${displayVersion(updateAvailable.latestVersion)}`} + {backend.displayName} {displayEngineVersion(updateAvailable.latestVersion)}{' '} + is available + + + {displayEngineVersion(updateAvailable.currentVersion)} installed - - - + {(updateAvailable.installType === 'managed' || + updateAvailable.releaseUrl !== updateAvailable.downloadUrl) && ( + + + + )} - {updateAvailable.installType === 'managed' && ( + {updateAvailable.installType === 'managed' ? ( + ) : ( + )} diff --git a/desktop/src/ui/components/ErrorModal.tsx b/desktop/src/ui/components/ErrorModal.tsx index dde1d82bc..fa53c306f 100644 --- a/desktop/src/ui/components/ErrorModal.tsx +++ b/desktop/src/ui/components/ErrorModal.tsx @@ -7,6 +7,7 @@ import { DialogHeader } from './DialogHeader' import { errorDismissalKey } from '@/ui/utils/error-modal-dismissal' import { InlineErrorBanner } from './InlineErrorBanner' import { useErrorsStore } from '@/ui/stores/errors.store' +import { useConnectionStore } from '@/ui/stores/connection.store' import { useNodesStore } from '@/ui/stores/nodes.store' import { isEngineType } from '@/shared/utils/engines' import type { ServiceError } from '@/shared/types/errors' @@ -99,7 +100,7 @@ function bannerStatus(severity: ServiceError['severity']): 'info' | 'warning' | * `null` (no button) when the action isn't `retry` or the error lacks the * engine/node/model context needed to re-dispatch. */ -function buildRetry(error: ServiceError): (() => void) | null { +function buildRetry(error: ServiceError, isLocalNode: boolean): (() => void) | null { if (error.action !== 'retry') return null const { engineType, nodeId, operation, modelName } = error if (!engineType || !isEngineType(engineType) || !nodeId) return null @@ -107,6 +108,8 @@ function buildRetry(error: ServiceError): (() => void) | null { switch (operation) { case 'install': return () => engines.install(engineType, nodeId) + case 'update': + return isLocalNode ? () => engines.update(engineType, nodeId) : null case 'uninstall': return () => engines.uninstall(engineType, nodeId) case 'start': @@ -163,7 +166,8 @@ function ErrorBanner({ const showNodePrefix = Boolean(error.nodeId) && !hideNodePrefix const displayMessage = formatErrorMessage(error, nodeLabel, showNodePrefix) const severity = bannerStatus(error.severity) - const retry = buildRetry(error) + const isLocalNode = useConnectionStore(state => state.selfId === error.nodeId) + const retry = buildRetry(error, isLocalNode) return ( diff --git a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx index 37ef126ae..2ac44e5d9 100644 --- a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx +++ b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx @@ -6,7 +6,6 @@ import { Stack } from '@nvidia/foundations-react-core' import { useNodesStore } from '@/ui/stores/nodes.store' import { useEngineModelsStore } from '@/ui/stores/engine-models.store' import { useEngineStatusStore } from '@/ui/stores/engine-status.store' -import { useEngineUpdateAvailableStore } from '@/ui/stores/engine-update-available.store' import { useConnectionStore } from '@/ui/stores/connection.store' import type { BackendInfo } from '@/ui/types/engine-info' import { @@ -29,7 +28,7 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { const selfId = useConnectionStore(state => state.selfId) // The fingerprints below subscribe to the engine stores so this component - // re-renders when the underlying status/models/update data changes. The + // re-renders when the underlying status or model data changes. The // actual data is read from the stores via getState() in the map below. const engineFingerprint = useEngineStatusStore(state => { const nodeStatuses = state.statusByNode.get(nodeId) @@ -42,15 +41,6 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { } return parts.join('|') }) - const updateAvailableFingerprint = useEngineUpdateAvailableStore(state => { - const parts: string[] = [] - for (const [k, v] of state.entries) { - if (!k.startsWith(`${nodeId}:`)) continue - parts.push(`${k}:${v.currentVersion}->${v.latestVersion}:${v.installType}`) - } - return parts.join('|') - }) - void updateAvailableFingerprint const modelsFingerprint = useEngineModelsStore(state => { let fp = '' for (const type of EnabledEngineTypes) { @@ -89,7 +79,6 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { // without this flag a never-reported remote engine spins forever. const statusKnown = statusStore.statusByNode.get(nodeId)?.has(type) ?? false const models = useEngineModelsStore.getState().getModels(nodeId, type) - const updateAvailable = useEngineUpdateAvailableStore.getState().getInfo(nodeId, type) return { backend: { @@ -103,8 +92,7 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { modelsKnown: models.inventoryKnown, docsUrl: EngineDefaultLinks[type]?.docsUrl, installUrl: EngineDefaultLinks[type]?.installUrl, - installedVersion: status.installedVersion, - updateAvailable + installedVersion: status.installedVersion }, statusKnown } diff --git a/desktop/src/ui/hooks/useOverviewCommands.ts b/desktop/src/ui/hooks/useOverviewCommands.ts index 11191d3ef..d6e191319 100644 --- a/desktop/src/ui/hooks/useOverviewCommands.ts +++ b/desktop/src/ui/hooks/useOverviewCommands.ts @@ -27,6 +27,8 @@ export function useOverviewCommands(): { const unsubscribe = window.windowApi.window.onOverviewCommand(command => { if (command.type === 'focus-node') { focusNodeEngineSettings(command.nodeId) + } else if (command.type === 'dismiss-message') { + setMessages(prev => prev.filter(message => message.id !== command.id)) } else { setMessages(prev => prev.some(m => m.id === command.message.id) ? prev : [...prev, command.message] diff --git a/desktop/src/ui/stores/engine-update-available.store.ts b/desktop/src/ui/stores/engine-update-available.store.ts index aee1702ef..f0d3e4082 100644 --- a/desktop/src/ui/stores/engine-update-available.store.ts +++ b/desktop/src/ui/stores/engine-update-available.store.ts @@ -4,12 +4,8 @@ /** * Engine update-available store -- ephemeral, push-driven. * - * Sole owner of per-engine "update available" state in the renderer. The - * backend reports an available engine update per node and delivers it as an - * `engines:state-changed` push patch scoped to the originating `nodeId`. We - * mirror those into a `Map<{nodeId, engineType}, UpdateAvailableInfo>` so - * `EditNodeApp` can surface update affordances for any node — local **or** - * remote — that the user has access to. + * Seeds Engine settings from the bridge snapshot and applies subsequent + * `engines:state-changed` patches for the same node and engine type. * * Entries are cleared on an explicit `updateAvailable: null` patch and when a * node departs (`nodes:remove`), so a rejoin never resurfaces a stale update @@ -18,15 +14,14 @@ */ import { create } from 'zustand' import type { EngineInitialState } from '@/shared/types/engine-api' -import type { UpdateAvailableInfo } from '@/ui/types/engine-info' -import type { EngineType } from '@/shared/types/engines' +import type { EngineType, EngineUpdateAvailable } from '@/shared/types/engines' function key(nodeId: string, engineType: string): string { return `${nodeId}:${engineType}` } interface EngineUpdateAvailableState { - entries: Map + entries: Map initialize(initial?: EngineInitialState): Promise cleanup(): void /** @@ -34,7 +29,7 @@ interface EngineUpdateAvailableState { * none is currently published. Returning `undefined` lets callers spread * directly into `BackendInfo` without sentinel handling. */ - getInfo(nodeId: string, engineType: EngineType): UpdateAvailableInfo | undefined + getInfo(nodeId: string, engineType: EngineType): EngineUpdateAvailable | undefined } let unsubs: Array<() => void> = [] @@ -49,14 +44,9 @@ export const useEngineUpdateAvailableStore = create( unsubs = [] try { const initial = initialSnapshot ?? (await window.pairApi.engines.getInitialState()) - const map = new Map() + const map = new Map() for (const update of initial.updateAvailable) { - map.set(key(update.nodeId, update.engineType), { - currentVersion: update.currentVersion, - latestVersion: update.latestVersion, - releaseUrl: update.releaseUrl, - installType: update.installType - }) + map.set(key(update.nodeId, update.engineType), update) } set({ entries: map }) } catch { @@ -74,12 +64,7 @@ export const useEngineUpdateAvailableStore = create( } return } - map.set(key(patch.nodeId, patch.engineType), { - currentVersion: patch.updateAvailable.currentVersion, - latestVersion: patch.updateAvailable.latestVersion, - releaseUrl: patch.updateAvailable.releaseUrl, - installType: patch.updateAvailable.installType - }) + map.set(key(patch.nodeId, patch.engineType), patch.updateAvailable) set({ entries: map }) }), // Drop a departed node's update entries so a rejoin never resurfaces a diff --git a/desktop/src/ui/types/engine-info.ts b/desktop/src/ui/types/engine-info.ts index b9d820c23..34c424e5e 100644 --- a/desktop/src/ui/types/engine-info.ts +++ b/desktop/src/ui/types/engine-info.ts @@ -4,6 +4,7 @@ import type { EngineType, EngineSource, + EngineUpdateAvailable, ModelItemStatus, ModelExpiry, EngineProcessStatus @@ -53,36 +54,6 @@ export interface BackendInstallProgress { percent?: number } -/** - * Update availability info surfaced by the universal `EngineVersionChecker`. - * - * Cluster-replicated: every node runs its own checker against its own - * installed engines, writes results into `ClusterState`, and broadcasts - * `EngineUpdateAvailableEvent` / `EngineUpdateClearedEvent` to peers. Each - * receiving node forwards them to its renderer as - * `engines:state-changed` patches scoped to - * the originating `nodeId`. The renderer's `engine-update-available.store` - * keys entries by `(nodeId, engineType)` so the Edit Node window can show - * an Update affordance for any node — local **or** remote — that the user - * has access to. Entries are cleared automatically when the originating - * node drops out of `ClusterState`. - * - * `installType`: - * - `managed` — PAIR owns the binary (e.g. `{userData}/ollama`), so the UI - * shows a one-click "Update" button that dispatches the `update` engine - * command on the engine's owning node. - * - `external` — the binary lives outside `{userData}` (user installed - * Ollama themselves, llama.cpp via brew, etc.). The UI shows an info - * banner with release notes and an optional CTA to install a PAIR-managed - * copy; PAIR never modifies external installs in place. - */ -export interface UpdateAvailableInfo { - currentVersion: string - latestVersion: string - releaseUrl: string - installType: 'managed' | 'external' -} - export interface BackendInfo { type: EngineType displayName: string @@ -116,11 +87,6 @@ export interface BackendInfo { manuallyStopped?: boolean /** True when this backend should auto-start on app launch */ autoStart?: boolean - /** - * Set when this backend's owning node has detected a newer GitHub - * release. Replicated cluster-wide so the Edit Node UI can surface an - * Update affordance for any node the user has access to, not only - * `selfId`. See `UpdateAvailableInfo` above. - */ - updateAvailable?: UpdateAvailableInfo + /** Present when the engine manager reports a supported update. */ + updateAvailable?: EngineUpdateAvailable } diff --git a/desktop/src/ui/utils/status.ts b/desktop/src/ui/utils/status.ts index f5f782756..f99c7305a 100644 --- a/desktop/src/ui/utils/status.ts +++ b/desktop/src/ui/utils/status.ts @@ -3,6 +3,11 @@ import type { EngineProcessStatus } from '@/shared/types/engines' +/** Preserve vendor build labels such as llama.cpp's b12345. */ +export function displayEngineVersion(version: string): string { + return /^\d+\./.test(version) ? `v${version}` : version +} + export const statusLabel: Record = { running: 'Running', 'awaiting-model': 'Select a model', diff --git a/desktop/tests/modular/empty-handlers.test.ts b/desktop/tests/modular/empty-handlers.test.ts index bcc67fec6..4b45049e1 100644 --- a/desktop/tests/modular/empty-handlers.test.ts +++ b/desktop/tests/modular/empty-handlers.test.ts @@ -11,10 +11,15 @@ type BridgeState = ReturnType const mocks = vi.hoisted(() => ({ state: { - getSelfId: vi.fn() + getSelfId: vi.fn(), + beginLocalEngineOp: vi.fn(), + clearPendingEngineOp: vi.fn() }, supervisor: { - callProcess: vi.fn() + callProcess: vi.fn(), + hasProcess: vi.fn(() => true), + sendProcess: vi.fn(), + reportError: vi.fn() } })) @@ -33,6 +38,64 @@ vi.mock('@/electron/service-bridge/model-catalog', () => ({ import { handleServiceBridgeInvoke } from '@/electron/service-bridge/empty-handlers' +describe('local engine update command', () => { + it('sends one managed Ollama update', async () => { + mocks.supervisor.sendProcess.mockClear() + mocks.state.getSelfId.mockReturnValue('self') + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'ollama', + nodeId: 'self' + }) + + expect(mocks.supervisor.sendProcess).toHaveBeenCalledOnce() + expect(mocks.supervisor.sendProcess).toHaveBeenCalledWith( + 'broker', + 'engine:update', + { engine: 'ollama' }, + expect.any(Function), + true + ) + }) + + it('retains the local node and UI engine identifier when a managed update is rejected', async () => { + mocks.state.getSelfId.mockReturnValue('self') + mocks.supervisor.sendProcess.mockImplementationOnce((_name, _method, _params, onError) => { + onError?.('update rejected', true) + }) + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'ollama', + nodeId: 'self' + }) + expect(mocks.supervisor.reportError).toHaveBeenCalledWith( + 'Failed to update ollama: update rejected', + 'error', + undefined, + { + id: 'engine-manager:update-failed:ollama', + nodeId: 'self', + engineType: 'ollama', + operation: 'update', + action: 'retry' + } + ) + }) + + it('does not dispatch a peer update to the local engine manager', async () => { + mocks.supervisor.sendProcess.mockClear() + mocks.state.getSelfId.mockReturnValue('self') + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'ollama', + nodeId: 'peer' + }) + + expect(mocks.supervisor.sendProcess).not.toHaveBeenCalled() + expect(mocks.supervisor.reportError).toHaveBeenCalled() + }) +}) + describe('manual node removal', () => { // The desktop knows a broker node key. Its request must select that key // explicitly so an identical worker entry name cannot remove another entry. diff --git a/desktop/tests/modular/engine-update-checks.test.ts b/desktop/tests/modular/engine-update-checks.test.ts new file mode 100644 index 000000000..ca42ee211 --- /dev/null +++ b/desktop/tests/modular/engine-update-checks.test.ts @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getModularBridgeState } from '@/electron/service-bridge/modular-state' +import { watchEngineUpdates } from '@/electron/service-bridge/engine-update-checks' +import { subscribePush } from '@/electron/service-bridge/push-bus' +import type { EngineType } from '@/shared/types/engines' +import type { JsonValue } from '@/electron/service-bridge/json-rpc-subprocess' + +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) + +const available = { + currentVersion: '1.0.0', + latestVersion: '1.2.0', + releaseUrl: 'https://github.com/ollama/ollama/releases/tag/v1.2.0', + installType: 'managed' +} + +describe('local engine update checks', () => { + const state = getModularBridgeState() + const check = vi.fn<(engine: EngineType) => Promise>() + const sixHours = 6 * 60 * 60 * 1000 + let checks: ReturnType + let unsubscribe: (() => void) | undefined + + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + state.setSelfId('local') + state.applyEngineManagerList({ engines: [{ engine: 'ollama', installed: true }] }) + check.mockReset().mockResolvedValue({ updateAvailable: available }) + }) + afterEach(() => { + unsubscribe?.() + unsubscribe = undefined + checks.stop() + vi.useRealTimers() + }) + + it('publishes the startup offer once and clears it when a later check finds no update', async () => { + const patches: JsonValue[] = [] + unsubscribe = subscribePush(event => { + if ( + event.channel === 'engines:state-changed' && + event.payload.updateAvailable !== undefined + ) { + patches.push(event.payload.updateAvailable?.latestVersion ?? null) + } + }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + const offer = { ...available, nodeId: 'local', engineType: 'ollama' } + expect(state.getEngineInitialState().updateAvailable).toEqual([offer]) + + await vi.advanceTimersByTimeAsync(sixHours) + expect(check).toHaveBeenCalledTimes(2) + expect(patches).toEqual(['1.2.0']) + + check.mockResolvedValue({ updateAvailable: null }) + await checks.refresh() + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + expect(patches).toEqual(['1.2.0', null]) + }) + + it('checks only the engine that started or stopped, once per transition', async () => { + const stopped = { engine: 'ollama', installed: true, running: false } + const running = { ...stopped, running: true } + state.applyEngineManagerList({ + engines: [stopped, { engine: 'lmstudio', installed: true }] + }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + check.mockClear() + + state.applyEngineManagerStatus({ ...stopped, starting: true }) + expect(check).not.toHaveBeenCalled() + state.applyEngineManagerStatus(running) + await vi.advanceTimersByTimeAsync(0) + state.applyEngineManagerStatus({ ...running, healthy: true }) + expect(check.mock.calls).toEqual([['ollama']]) + + state.applyEngineManagerStatus(stopped) + await vi.advanceTimersByTimeAsync(0) + state.applyEngineManagerStatus(stopped) + expect(check.mock.calls).toEqual([['ollama'], ['ollama']]) + }) + + it('publishes a completed start and keeps the previous offer when its update check fails', async () => { + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + const offline = Promise.withResolvers() + check.mockClear().mockReturnValueOnce(offline.promise) + + state.applyEngineManagerStatus({ engine: 'ollama', installed: true, running: true }) + expect(check.mock.calls).toEqual([['ollama']]) + expect(state.getEngineInitialState().statuses).toContainEqual( + expect.objectContaining({ + nodeId: 'local', + engineType: 'ollama', + processStatus: 'running' + }) + ) + + offline.reject(new Error('offline')) + await vi.advanceTimersByTimeAsync(0) + + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'local', engineType: 'ollama' } + ]) + }) + + it('checks only Ollama when other engines are installed or change state', async () => { + state.applyEngineManagerList({ + engines: [ + { engine: 'ollama', installed: true }, + { engine: 'llamacpp', installed: true } + ] + }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + expect(check.mock.calls).toEqual([['ollama']]) + + state.applyEngineManagerStatus({ engine: 'llamacpp', installed: true, running: true }) + await vi.advanceTimersByTimeAsync(0) + expect(check.mock.calls).toEqual([['ollama']]) + }) + + it('requires a valid vendor download link for external installations', async () => { + check.mockResolvedValue({ updateAvailable: { ...available, installType: 'external' } }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + + check.mockResolvedValue({ + updateAvailable: { + ...available, + installType: 'external', + downloadUrl: 'file:///installer' + } + }) + await checks.refresh('ollama') + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + }) + + it('coalesces refreshes after a lifecycle change without showing the old offer', async () => { + const previous = Promise.withResolvers() + check.mockReturnValueOnce(previous.promise).mockResolvedValue({ updateAvailable: null }) + const offeredVersions: string[] = [] + unsubscribe = subscribePush(event => { + if (event.channel === 'engines:state-changed' && event.payload.updateAvailable) { + offeredVersions.push(event.payload.updateAvailable.latestVersion) + } + }) + checks = watchEngineUpdates(check) + + void checks.refresh() + void checks.refresh() + expect(check).toHaveBeenCalledOnce() + previous.resolve({ updateAvailable: available }) + await vi.advanceTimersByTimeAsync(0) + + expect(check).toHaveBeenCalledTimes(2) + expect(offeredVersions).toEqual([]) + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + }) + + it('clears the installed offer on completion before a failed release check', async () => { + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + expect(state.getEngineInitialState().updateAvailable).toHaveLength(1) + check.mockRejectedValue(new Error('release feed unavailable')) + + state.applyEngineManagerProgress({ engine: 'ollama', stage: 'done' }) + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + await vi.advanceTimersByTimeAsync(0) + + expect(check).toHaveBeenCalledTimes(2) + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + }) + + it('keeps the offer when the installer finds Ollama already installed', async () => { + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + check.mockRejectedValue(new Error('release feed unavailable')) + + state.applyEngineManagerProgress({ engine: 'ollama', stage: 'already-installed' }) + await vi.advanceTimersByTimeAsync(0) + + expect(check).toHaveBeenCalledTimes(2) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'local', engineType: 'ollama' } + ]) + }) + + it('checks the new local identity and removes the old node offer', async () => { + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + state.setSelfId('replacement') + + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + await vi.advanceTimersByTimeAsync(0) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'replacement', engineType: 'ollama' } + ]) + }) + + it('ignores a check that completes after shutdown', async () => { + const pending = Promise.withResolvers() + check.mockReturnValueOnce(pending.promise) + checks = watchEngineUpdates(check) + + checks.stop() + pending.resolve({ updateAvailable: available }) + await vi.advanceTimersByTimeAsync(sixHours) + + expect(check).toHaveBeenCalledOnce() + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + }) +}) diff --git a/desktop/tests/modular/engine-update-controls.test.ts b/desktop/tests/modular/engine-update-controls.test.ts new file mode 100644 index 000000000..380a86f80 --- /dev/null +++ b/desktop/tests/modular/engine-update-controls.test.ts @@ -0,0 +1,188 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// @vitest-environment jsdom + +import { act, createElement, type ReactNode } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { subscribeEngineUpdateNotifications } from '@/electron/updater/engine-update-notification' +import { publishPush } from '@/electron/service-bridge/push-bus' +import { dismissOverviewMessage, showOverviewMessage } from '@/electron/window' +import type { EngineUpdateAvailable } from '@/shared/types/engines' +import type { ServiceError } from '@/shared/types/errors' +import type { IEngineApi } from '@/ui/api/engine-api' +import { AppMessageModal } from '@/ui/components/AppMessageModal' +import { BackendUpdateBanner } from '@/ui/components/BackendRow/BackendUpdateBanner' +import { ErrorModal } from '@/ui/components/ErrorModal' +import { useConnectionStore } from '@/ui/stores/connection.store' +import { useErrorsStore } from '@/ui/stores/errors.store' +import { useOverviewUiStore } from '@/ui/stores/overview-ui.store' +import type { BackendInfo } from '@/ui/types/engine-info' + +vi.mock('@/electron/window', () => ({ + showOverviewMessage: vi.fn(), + dismissOverviewMessage: vi.fn() +})) + +// JSDOM does not implement the native modal dialog lifecycle. +vi.mock('@nvidia/foundations-react-core', async importOriginal => { + const kit = await importOriginal() + const container = ({ children }: { children?: ReactNode }) => + createElement('div', null, children) + return { ...kit, ModalRoot: container, ModalDialog: container, ModalContent: container } +}) + +const update: EngineUpdateAvailable = { + nodeId: 'local-node', + engineType: 'ollama', + currentVersion: '0.10.1', + latestVersion: '0.10.2', + releaseUrl: 'https://github.com/ollama/ollama/releases/tag/v0.10.2', + installType: 'managed' +} + +const engine: BackendInfo = { + type: 'ollama', + displayName: 'Ollama', + source: 'detected', + processStatus: 'stopped', + port: null, + proxyPort: null, + models: [], + modelsKnown: true, + updateAvailable: update +} + +let root: Root +const openExternal = vi.fn<(url: string) => Promise>() + +beforeEach(() => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) + vi.stubGlobal('windowApi', { window: { openExternal } }) + root = createRoot(document.body.appendChild(document.createElement('div'))) + vi.clearAllMocks() +}) + +afterEach(async () => { + await act(() => root.unmount()) + document.body.replaceChildren() + useOverviewUiStore.setState({ activeTab: 'overview', focusNodeId: null }) + useErrorsStore.setState({ errors: [] }) + useConnectionStore.setState({ selfId: null }) + vi.unstubAllGlobals() +}) + +function button(label: string): HTMLButtonElement | undefined { + return Array.from(document.querySelectorAll('button')).find( + el => el.textContent.trim() === label + ) +} + +function report(updateAvailable: EngineUpdateAvailable): void { + const { nodeId, engineType } = updateAvailable + publishPush('engines:state-changed', { nodeId, engineType, updateAvailable }) +} + +it('shows a local Ollama notification once per release and withdraws it when cleared', () => { + const unsubscribe = subscribeEngineUpdateNotifications(() => 'local-node') + report({ ...update, nodeId: 'peer' }) + report(update) + report(update) + report({ ...update, latestVersion: '0.10.3' }) + publishPush('engines:state-changed', { + nodeId: 'local-node', + engineType: 'ollama', + updateAvailable: null + }) + unsubscribe() + expect(vi.mocked(showOverviewMessage).mock.calls.map(([message]) => message.id)).toEqual([ + 'engine-update:local-node:ollama:0.10.2', + 'engine-update:local-node:ollama:0.10.3' + ]) + expect(vi.mocked(dismissOverviewMessage).mock.calls).toEqual([ + ['engine-update:local-node:ollama:0.10.2'], + ['engine-update:local-node:ollama:0.10.3'] + ]) + expect(vi.mocked(showOverviewMessage).mock.calls[0][0].title).toBe('Ollama update available') +}) + +it('opens the local engine settings from the Ollama notification', async () => { + const unsubscribe = subscribeEngineUpdateNotifications(() => 'local-node') + report(update) + unsubscribe() + const [[message]] = vi.mocked(showOverviewMessage).mock.calls + const onClose = vi.fn<() => void>() + useOverviewUiStore.getState().openSettings('service') + await act(() => root.render(createElement(AppMessageModal, { message, onClose }))) + expect(document.body.textContent).toContain('Ollama update available') + await act(() => button('Open engine settings')?.click()) + + expect(useOverviewUiStore.getState()).toMatchObject({ + activeTab: 'overview', + focusNodeId: 'local-node' + }) + expect(onClose).toHaveBeenCalledOnce() +}) + +it('shows the installed and available Ollama versions and dispatches Update', async () => { + const onUpdate = vi.fn<() => void>() + await act(() => + root.render( + createElement(BackendUpdateBanner, { backend: engine, disabled: false, onUpdate }) + ) + ) + expect(document.body.textContent).toContain('v0.10.1 installed') + expect(document.body.textContent).toContain('Ollama v0.10.2 is available') + await act(() => button('Update')?.click()) + + expect(onUpdate).toHaveBeenCalledOnce() + expect(openExternal).not.toHaveBeenCalled() +}) + +it('opens the official download and release notes for an externally installed Ollama', async () => { + const onUpdate = vi.fn<() => void>() + const external: BackendInfo = { + ...engine, + updateAvailable: { + ...update, + installType: 'external', + downloadUrl: 'https://ollama.com/download' + } + } + await act(() => + root.render( + createElement(BackendUpdateBanner, { backend: external, disabled: false, onUpdate }) + ) + ) + await act(() => button('Get update')?.click()) + await act(() => button('Update details')?.click()) + + expect(openExternal.mock.calls).toEqual([ + ['https://ollama.com/download'], + ['https://github.com/ollama/ollama/releases/tag/v0.10.2'] + ]) + expect(button('Update')).toBeUndefined() + expect(onUpdate).not.toHaveBeenCalled() +}) + +it('retries a failed update only for the affected local engine', async () => { + const retry = vi.fn() + vi.stubGlobal('pairApi', { engines: { update: retry }, errors: { clear: vi.fn() } }) + useConnectionStore.setState({ selfId: 'local-node' }) + const failure: ServiceError = { + id: 'engine-manager:update-failed:ollama', + timestamp: 1, + action: 'retry', + engineType: 'ollama', + operation: 'update', + message: 'Ollama update failed', + nodeId: 'peer-node' + } + useErrorsStore.setState({ errors: [failure] }) + await act(() => root.render(createElement(ErrorModal, {}))) + expect(button('Retry')).toBeUndefined() + + await act(() => useErrorsStore.setState({ errors: [{ ...failure, nodeId: 'local-node' }] })) + await act(() => button('Retry')?.click()) + expect(retry.mock.calls).toEqual([['ollama', 'local-node']]) +}) diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index a6ef99675..5e94c24cc 100644 --- a/docs/engine-lifecycle.mdx +++ b/docs/engine-lifecycle.mdx @@ -1,6 +1,6 @@ --- title: Managing Engines in NVIDIA PAIR -description: Install, start, stop, update, and remove the Ollama, LM Studio, and llama.cpp engines that NVIDIA PAIR uses to run models. +description: Install, start, stop, and remove engines on a PAIR node, and check the local Ollama installation for updates. --- {/* @@ -10,8 +10,8 @@ SPDX-License-Identifier: Apache-2.0 An **engine** is the local inference runtime NVIDIA PAIR uses to run models. Today that means Ollama, LM Studio, llama.cpp, or vLLM on a given machine. -PAIR can install and run those engines for you, or work with a supported -existing Ollama or LM Studio installation. This page explains what you can +PAIR can install and run those engines for you or use an existing installation +it recognizes. This page explains what you can expect when you install, start, stop, or remove an engine, and how to move one to a newer release. @@ -81,7 +81,7 @@ When you install an engine, consider the following: - If Ollama or LM Studio is already running on the machine, PAIR can **adopt** that install instead of downloading another copy. Adoption helps when the usual engine port is already in use. -- llama.cpp is always a PAIR-managed install. Windows and Linux download fixed +- When PAIR installs llama.cpp, Windows and Linux download fixed checksum-pinned CUDA server/runtime archives. Apple silicon Macs download the standard Metal-enabled archive, and Intel Macs download the CPU-only build, because upstream builds it without Metal. The engine download, roughly @@ -190,11 +190,24 @@ first. ## Updating and Uninstalling an Engine -PAIR does not currently offer to update an engine, because it does not yet detect -newer engine versions. To move an NVPAIR-installed Ollama or LM Studio to the -vendor's current release, uninstall it and install it again, which keeps your -models as described below. llama.cpp installs the build pinned by your version of -PAIR. Update an engine you installed yourself with its own installer. +The desktop checks the local Ollama installation at startup, every six hours, +and when Ollama starts or stops. If the release service is unreachable, Ollama +continues normally and PAIR keeps any previously reported offer. When PAIR +finds a newer stable release, **Overview** shows a message once per release in +that desktop session. Select **Open engine settings** to see the installed and +available versions. + +- **Update** lets PAIR update the copy it installed in its standard folder when + the official package is available for this platform. PAIR keeps downloaded + models and settings and restores the previous running or stopped state. +- **Get update** opens Ollama's download page for a user-installed copy or an + installation whose ownership PAIR cannot confirm. + +If GitHub rate-limits a release lookup, wait until the time in the error +message, then select **Retry** in the desktop app. + +Use the vendor's installer to update an existing LM Studio installation. +PAIR installs the llama.cpp and vLLM builds pinned for the platform. **Uninstall** removes the NVPAIR-installed copy of an engine, and applies only to an engine PAIR installed. Use it when you no longer want PAIR to own that engine diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 2f41e9393..ed869ecef 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -316,6 +316,8 @@ Requests (caller → service): | `engine:describe` | `{ engine }` | the engine's manifest | | `engine:status` | `{ engine, port? }` | `EngineStatus`; an error for an engine this host cannot run | | `engine:install` | `{ engine, start?, port?, bind? }` | `EngineStatus` (after install; also starts it if `start:true`) | +| `engine:check-updates` | `{ engine }` | `{ updateAvailable: null }` or `{ updateAvailable: { currentVersion, latestVersion, releaseUrl, installType, downloadUrl? } }` for the local engine. `releaseUrl` links to release information. `installType` is `managed` or `external`. External offers include the vendor's `downloadUrl`. Failed lookups return an RPC error. | +| `engine:update` | `{ engine }` | `EngineStatus` after updating the PAIR-managed installation. Preserves the prior running or stopped state. | | `engine:uninstall` | `{ engine }` | `EngineStatus` (after removal) | | `engine:uninstall-managed` | — | `{ engines: [{ engine, removed, error? }] }` — removes every engine this service installed, selected by its install marker, each through the `engine:uninstall` path. Backs "reset all data" in both clients; downloaded models are kept. Neither `removed` nor `error` means the engine was left alone as not ours | | `engine:start` | `{ engine, port?, bind? }` | `EngineStatus` (after readiness) | @@ -453,7 +455,7 @@ accumulated CLI output. The limit applies per frame so a long operation can report progress throughout its lifetime. They fail if this node isn't clustered or the target isn't a pinned cluster peer. See "Remote engine management" below. -`engine:install`, `engine:start`, `engine:stop`, `engine:restart`, +`engine:check-updates`, `engine:update`, `engine:install`, `engine:start`, `engine:stop`, `engine:restart`, `engine:set-port`, and `engine:action` run in their own goroutine on the service side, so the read loop never blocks and their responses arrive when the op finishes. diff --git a/services/nvpair-engine-manager/engine_release_cache_test.go b/services/nvpair-engine-manager/engine_release_cache_test.go new file mode 100644 index 000000000..18a3b0955 --- /dev/null +++ b/services/nvpair-engine-manager/engine_release_cache_test.go @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "io" + "net/http" + "strconv" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func releaseAPIResponse(status int, headers http.Header, body string) (*http.Response, error) { + return &http.Response{StatusCode: status, Header: headers, Body: io.NopCloser(strings.NewReader(body))}, nil +} + +func TestGitHubRelease_PausesOtherRepositoriesUntilTheRateLimitResets(t *testing.T) { + check := func(name string, status int, headers http.Header, body string, wait time.Duration) { + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + reset := time.Now().Add(wait) + if headers.Get("X-RateLimit-Remaining") == "0" { + headers.Set("X-RateLimit-Reset", strconv.FormatInt(reset.Unix(), 10)) + } + calls := 0 + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + return releaseAPIResponse(status, headers, body) + } + return releaseAPIResponse(http.StatusOK, nil, `{"tag_name":"v1"}`) + }) + + _, err := e.githubRelease(t.Context(), "ggml-org/llama.cpp", "tags/b100") + require.ErrorContains(t, err, reset.UTC().Format(time.RFC1123)) + time.Sleep(wait - time.Second) + _, err = e.githubRelease(t.Context(), "ollama/ollama", "latest") + require.ErrorContains(t, err, reset.UTC().Format(time.RFC1123)) + require.Equal(t, 1, calls) + + time.Sleep(time.Second) + release, err := e.githubRelease(t.Context(), "ollama/ollama", "latest") + require.NoError(t, err) + assert.Equal(t, "v1", release.Tag) + assert.Equal(t, 2, calls) + }) + }) + } + check("exhausted hourly quota", http.StatusForbidden, http.Header{"X-Ratelimit-Remaining": {"0"}}, "", 5*time.Minute) + check("explicit retry delay", http.StatusTooManyRequests, http.Header{"Retry-After": {"90"}}, "", 90*time.Second) + check("secondary limit without a retry header", http.StatusForbidden, nil, `{"message":"You have exceeded a secondary rate limit."}`, time.Minute) +} + +func TestGitHubRelease_LeavesOtherRepositoriesAvailableAfterAnAccessDenial(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if strings.Contains(req.URL.Path, "ggml-org/llama.cpp") { + return releaseAPIResponse(http.StatusForbidden, nil, `{"message":"Access denied"}`) + } + return releaseAPIResponse(http.StatusOK, nil, `{"tag_name":"v1"}`) + }) + + _, err := e.githubRelease(t.Context(), "ggml-org/llama.cpp", "tags/b100") + require.ErrorContains(t, err, "HTTP 403") + assert.NotContains(t, err.Error(), "rate limit") + release, err := e.githubRelease(t.Context(), "ollama/ollama", "latest") + require.NoError(t, err) + assert.Equal(t, "v1", release.Tag) +} + +func TestGitHubRelease_FetchesANewTagImmediately(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + tag := strings.TrimPrefix(req.URL.Path, "/repos/ggml-org/llama.cpp/releases/tags/") + return releaseAPIResponse(http.StatusOK, nil, `{"tag_name":"`+tag+`"}`) + }) + + _, err := e.githubRelease(t.Context(), "ggml-org/llama.cpp", "tags/b100") + require.NoError(t, err) + release, err := e.githubRelease(t.Context(), "ggml-org/llama.cpp", "tags/b101") + require.NoError(t, err) + assert.Equal(t, "b101", release.Tag) +} + +func TestGitHubRelease_RefreshesLatestAfterItsCacheExpires(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + body := `{"tag_name":"v1"}` + e.client.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) { + return releaseAPIResponse(http.StatusOK, nil, body) + }) + release, err := e.githubRelease(t.Context(), "ollama/ollama", "latest") + require.NoError(t, err) + require.Equal(t, "v1", release.Tag) + + body = `{"tag_name":"v2"}` + time.Sleep(15 * time.Minute) + release, err = e.githubRelease(t.Context(), "ollama/ollama", "latest") + require.NoError(t, err) + assert.Equal(t, "v2", release.Tag) + }) +} + +func TestGitHubRelease_CancelingAWaiterKeepsTheSharedRequestRunning(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + var calls atomic.Int32 + resume := make(chan struct{}) + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + calls.Add(1) + select { + case <-resume: + return releaseAPIResponse(http.StatusOK, nil, `{"tag_name":"b100"}`) + case <-req.Context().Done(): + return nil, req.Context().Err() + } + }) + request := func(ctx context.Context) <-chan error { + done := make(chan error, 1) + go func() { + _, err := e.githubRelease(ctx, "ggml-org/llama.cpp", "tags/b100") + done <- err + }() + return done + } + original := request(t.Context()) + synctest.Wait() + ctx, cancel := context.WithCancel(t.Context()) + waiter := request(ctx) + synctest.Wait() + + cancel() + assert.ErrorIs(t, <-waiter, context.Canceled) + close(resume) + assert.NoError(t, <-original) + assert.Equal(t, int32(1), calls.Load()) + }) +} diff --git a/services/nvpair-engine-manager/engine_update_check.go b/services/nvpair-engine-manager/engine_update_check.go new file mode 100644 index 000000000..3df15766f --- /dev/null +++ b/services/nvpair-engine-manager/engine_update_check.go @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type engineUpdateSnapshot struct { + binPath string + processPath string + port int + running bool + adopted bool +} + +type githubReleaseAsset struct { + Name string `json:"name"` + Digest string `json:"digest"` + BrowserDownloadURL string `json:"browser_download_url"` +} + +type githubRelease struct { + Tag string `json:"tag_name"` + Assets []githubReleaseAsset `json:"assets"` + Draft bool `json:"draft"` + Prerelease bool `json:"prerelease"` +} + +// Each upstream has one entry. A new tagged release replaces the old entry. +// The gate lets concurrent clients share a lookup and cancel their own wait. +type cachedGitHubRelease struct { + gate chan struct{} + ref string + release *githubRelease + expires time.Time +} + +// A version probe can read a local executable or listener and then wait on a +// remote release feed. Keep that I/O outside the lifecycle lock and discard +// the result if the installation changed while the check was in flight. +func (e *Executor) checkInstalledEngineUpdate( + ctx context.Context, + engine string, + check func(context.Context, *engineState, engineUpdateSnapshot) (*EngineUpdateInfo, error), +) (*EngineUpdateInfo, error) { + manifest, ok := e.reg.Get(engine) + if !ok { + return nil, nil + } + if _, ok := manifest.HostPlatform(); !ok { + return nil, nil + } + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + st, err := e.state(engine) + if err != nil { + return nil, err + } + if _, err := e.statusWithContext(ctx, engine, 0, true); err != nil { + return nil, err + } + st.mu.Lock() + if st.opDone != nil { + st.mu.Unlock() + return nil, fmt.Errorf("%s is changing state", engine) + } + if !st.installed { + st.mu.Unlock() + return nil, nil + } + snapshot := engineUpdateSnapshot{binPath: st.binPath, port: st.port, running: st.running, adopted: st.adopted} + if st.proc != nil { + snapshot.processPath = st.proc.cmd.Path + } + revision := st.revision + st.mu.Unlock() + + result, err := check(ctx, st, snapshot) + if err != nil { + return nil, err + } + st.mu.Lock() + defer st.mu.Unlock() + if st.revision != revision { + return nil, fmt.Errorf("%s changed during the update check", engine) + } + return result, nil +} + +func readEngineVersionJSON(client *http.Client, req *http.Request, result any) error { + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("HTTP %d", resp.StatusCode) + } + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(result) +} + +// Use the node's original loopback port. A PAIR proxy marks identity probes +// as unsupported, and a redirect could supply a different engine's version. +func (e *Executor) readRunningEngineVersion(ctx context.Context, port int, path string, result any) error { + endpoint := url.URL{Scheme: "http", Host: fmt.Sprintf("127.0.0.1:%d", port), Path: path} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return err + } + req.Header.Set(engineIdentityProbeHeader, "1") + client := *e.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return readEngineVersionJSON(&client, req, result) +} + +func (e *Executor) latestGitHubRelease(ctx context.Context, repo string) (*githubRelease, error) { + return e.githubRelease(ctx, repo, "latest") +} + +// Providers choose their upstream repository. A provider that resolves an +// exact vendor-recommended tag may accept a release GitHub labels prerelease. +func (e *Executor) githubRelease(ctx context.Context, repo, ref string) (*githubRelease, error) { + tag, tagged := strings.CutPrefix(ref, "tags/") + if ref != "latest" && (!tagged || tag == "" || tag == "." || tag == ".." || url.PathEscape(tag) != tag) { + return nil, fmt.Errorf("invalid GitHub release reference %q", ref) + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + e.mu.Lock() + entry := e.githubReleases[repo] + if entry == nil { + entry = &cachedGitHubRelease{gate: make(chan struct{}, 1)} + e.githubReleases[repo] = entry + } + e.mu.Unlock() + select { + case entry.gate <- struct{}{}: + defer func() { <-entry.gate }() + case <-ctx.Done(): + return nil, ctx.Err() + } + if err := ctx.Err(); err != nil { + return nil, err + } + if entry.ref == ref && time.Now().Before(entry.expires) { + return entry.release, nil + } + e.mu.Lock() + retryAt := e.githubRetryAt + e.mu.Unlock() + if time.Now().Before(retryAt) { + return nil, githubRateLimitError(retryAt) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/"+repo+"/releases/"+ref, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/vnd.github+json") + resp, err := e.client.Do(req) + if err != nil { + return nil, fmt.Errorf("check %s releases: %w", repo, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + if retryAt := githubRateLimitReset(resp); !retryAt.IsZero() { + e.mu.Lock() + if retryAt.After(e.githubRetryAt) { + e.githubRetryAt = retryAt + } + e.mu.Unlock() + return nil, fmt.Errorf("check %s releases: HTTP %d: %w", repo, resp.StatusCode, githubRateLimitError(retryAt)) + } + if resp.StatusCode == http.StatusForbidden { + return nil, fmt.Errorf("GitHub denied access to %s release metadata (HTTP 403). Check this node's access to api.github.com", repo) + } + return nil, fmt.Errorf("check %s releases: HTTP %d", repo, resp.StatusCode) + } + var release githubRelease + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&release); err != nil { + return nil, fmt.Errorf("check %s releases: %w", repo, err) + } + if release.Tag == "" || release.Draft || (!tagged && release.Prerelease) || (tagged && release.Tag != tag) { + return nil, fmt.Errorf("%s did not return the requested release %q", repo, ref) + } + // The vendor's stable pointer is still read on each llama.cpp check. + // Reuse its exact build and checksums through the six-hour check window. + ttl := 15 * time.Minute + if tagged { + ttl = 6 * time.Hour + } + entry.ref, entry.release, entry.expires = ref, &release, time.Now().Add(ttl) + return entry.release, nil +} + +func githubRateLimitError(retryAt time.Time) error { + return fmt.Errorf("GitHub's API rate limit was reached. Retry after %s", retryAt.UTC().Format(time.RFC1123)) +} + +func githubRateLimitReset(resp *http.Response) time.Time { + if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests { + return time.Time{} + } + now := time.Now() + if seconds, err := strconv.ParseUint(resp.Header.Get("Retry-After"), 10, 32); err == nil { + return now.Add(time.Duration(seconds) * time.Second) + } + exhausted := resp.Header.Get("X-RateLimit-Remaining") == "0" + if exhausted { + if reset, err := strconv.ParseInt(resp.Header.Get("X-RateLimit-Reset"), 10, 64); err == nil && reset > now.Unix() { + return time.Unix(reset, 0) + } + } + // GitHub can report a secondary limit in its JSON message without a + // Retry-After header. Keep unrelated HTTP 403 responses distinguishable. + if !exhausted && resp.StatusCode == http.StatusForbidden { + var details struct{ Message string } + if json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&details) != nil || !strings.Contains(strings.ToLower(details.Message), "rate limit") { + return time.Time{} + } + } + return now.Add(time.Minute) +} diff --git a/services/nvpair-engine-manager/engine_updates.go b/services/nvpair-engine-manager/engine_updates.go new file mode 100644 index 000000000..aadb9d389 --- /dev/null +++ b/services/nvpair-engine-manager/engine_updates.go @@ -0,0 +1,360 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "syscall" + "time" + + "nvpair-shared/engines" +) + +type EngineUpdateInfo struct { + CurrentVersion string `json:"currentVersion"` + LatestVersion string `json:"latestVersion"` + ReleaseURL string `json:"releaseUrl"` + DownloadURL string `json:"downloadUrl,omitempty"` + InstallType string `json:"installType"` +} + +type engineUpdater struct { + check func(*Executor, context.Context) (*EngineUpdateInfo, error) + update func(*Executor, context.Context) error +} + +var engineUpdaters = map[string]engineUpdater{ + engines.NameOllama: {(*Executor).CheckOllamaUpdate, (*Executor).UpdateOllama}, +} + +func (e *Executor) CheckEngineUpdate(ctx context.Context, engine string) (*EngineUpdateInfo, error) { + provider, ok := engineUpdaters[engine] + if !ok { + return nil, fmt.Errorf("update checks are not supported for engine %q", engine) + } + return provider.check(e, ctx) +} + +func (e *Executor) UpdateEngine(ctx context.Context, engine string) error { + provider, ok := engineUpdaters[engine] + if !ok { + return fmt.Errorf("updates are not supported for engine %q", engine) + } + return provider.update(e, ctx) +} + +// The vendor recipe determines the exact release URL and platform archive. +// Accept the published digest only for that same asset. +func githubReleaseAssetFetch(assets []githubReleaseAsset, name, url string) (*Fetch, error) { + for _, asset := range assets { + if asset.Name != name || asset.BrowserDownloadURL != url { + continue + } + digest, ok := strings.CutPrefix(asset.Digest, "sha256:") + if ok && sha256Re.MatchString(digest) { + return &Fetch{URL: url, SHA256: digest}, nil + } + break + } + return nil, fmt.Errorf("no checksum-verified release asset for %s", name) +} + +// An update may replace only a PAIR-owned binary installed using the bundled +// recipe. A custom installer or install directory may contain unrelated files. +func managedUpdateBinary(st *engineState, binPath string) bool { + if !filepath.IsAbs(st.installDir) || st.bundledInstall == nil || !reflect.DeepEqual(st.plat.Install, st.bundledInstall) || + !isManagedInstallPath(binPath, st.installDir) { + return false + } + if _, err := readEngineInstallMarker(st.installDir, st.manifest.Engine); err != nil { + return false + } + resolvedDir, err := filepath.EvalSymlinks(st.installDir) + if err != nil { + return false + } + resolvedBin, err := filepath.EvalSymlinks(binPath) + return err == nil && isManagedInstallPath(resolvedBin, resolvedDir) && modelStoresOutsideInstall(st, st.modelsDir) +} + +// Protect configured and running model stores, including stores reached via +// filesystem links, before an update removes the previous engine tree. +func modelStoresOutsideInstall(st *engineState, stores ...string) bool { + dirInfo, err := os.Lstat(st.installDir) + if err != nil || !dirInfo.IsDir() { + return false + } + for _, store := range stores { + if store == "" { + continue + } + if !filepath.IsAbs(store) { + return false + } + location := locateStore(store) + if location.is(dirInfo) || location.under(dirInfo) || location.contains(st.installDir) { + return false + } + } + return true +} + +// The brief gap between the two directory renames can span a shutdown. +// Restore the previous managed tree before detection or auto-start sees it +// as missing. A promoted candidate already contains a verified executable. +func recoverStagedEngineInstall(dir, engine string) error { + if _, err := os.Lstat(dir); !errors.Is(err, os.ErrNotExist) { + return err + } + backup := dir + ".update-backup" + if !isEngineUpdateBackup(backup, engine) { + return nil + } + guard, err := lockEngineInstall(dir) + if err != nil { + return err + } + defer guard.Close() + // Another manager may have finished the swap before we acquired the lock. + if _, err := os.Lstat(dir); !errors.Is(err, os.ErrNotExist) { + return err + } + return renameEngineDirectory(backup, dir) +} + +// Windows can briefly keep an executable's directory locked after the +// version probe or server process exits. Bound the wait even during rollback. +func renameEngineDirectory(from, to string) error { + const ( + accessDenied = syscall.Errno(5) + sharingViolation = syscall.Errno(32) + lockViolation = syscall.Errno(33) + ) + for attempt := 1; ; attempt++ { + err := os.Rename(from, to) + if err == nil || runtime.GOOS != "windows" || attempt == 9 { + return err + } + var errno syscall.Errno + if !errors.As(err, &errno) || (errno != accessDenied && errno != sharingViolation && errno != lockViolation) { + return err + } + time.Sleep(time.Duration(attempt) * 100 * time.Millisecond) + } +} + +func isEngineUpdateBackup(backup, engine string) bool { + info, err := os.Lstat(backup) + if err != nil || !info.IsDir() { + return false + } + _, err = readEngineInstallMarker(backup, engine) + return err == nil +} + +func readEngineInstallMarker(dir, engine string) ([]byte, error) { + p := installMarkerPath(dir) + info, err := os.Lstat(p) + if err != nil || !info.Mode().IsRegular() || info.Size() > 4096 { + return nil, fmt.Errorf("no valid PAIR install marker for %s", engine) + } + data, err := os.ReadFile(p) + var marker installMarker + if err != nil || json.Unmarshal(data, &marker) != nil || marker.Engine != engine { + return nil, fmt.Errorf("no valid PAIR install marker for %s", engine) + } + return data, nil +} + +func discardEngineUpdateBackup(dir, engine string) error { + backup := dir + ".update-backup" + if filepath.IsAbs(dir) && isEngineUpdateBackup(backup, engine) { + return os.RemoveAll(backup) + } + return nil +} + +// withEngineUpdate serializes provider work with engine lifecycle operations. +// An explicit Stop or shutdown can interrupt long transfers and installations. +func (e *Executor) withEngineUpdate(ctx context.Context, engine string, op func(context.Context, *engineState) error) (result error) { + st, err := e.state(engine) + if err != nil { + return err + } + st.lockOperation() + defer st.unlockOperation() + // Stop and prepare-shutdown cancel the transfer before waiting on opMu. + // doStart registers its own cancellation callback during restart. + ctx, cancel := context.WithCancel(ctx) + st.mu.Lock() + st.startCancel = cancel + st.mu.Unlock() + defer func() { + cancel() + st.mu.Lock() + st.startCancel = nil + st.mu.Unlock() + }() + defer func() { + if result != nil { + e.emitInstallFrame(engine, "failed", 0, result.Error()) + return + } + e.reporter.clear("engine-manager:update-failed:" + engine) + e.emitInstallProgress(engine, "done", 100) + e.emitState(engine) + }() + if e.shuttingDown.Load() || e.stopWaiting(st) { + return context.Canceled + } + return op(ctx, st) +} + +// The provider stages and verifies its release while the old engine runs. +// Returning false means the installed copy is already current. +func (e *Executor) updateStagedEngine(ctx context.Context, engine string, eligible func(*engineState, string) bool, stage func(context.Context, *engineState, string, string) (bool, error)) error { + return e.withEngineUpdate(ctx, engine, func(ctx context.Context, st *engineState) error { + if st.bundledInstall == nil || !installedByPAIR(st.installDir) { + return fmt.Errorf("updates require a PAIR-managed %s installation", st.manifest.DisplayName) + } + guard, err := lockEngineInstall(st.installDir) + if err != nil { + return err + } + defer guard.Close() + binPath, _, err := e.managedUpdateTarget(ctx, st, eligible) + if err != nil { + return err + } + staging, err := os.MkdirTemp(filepath.Dir(st.installDir), "."+engine+"-update-*") + if err != nil { + return err + } + defer os.RemoveAll(staging) + ready, err := stage(ctx, st, binPath, staging) + if err != nil || !ready { + return err + } + target, running, err := e.managedUpdateTarget(ctx, st, eligible) + if err != nil { + return err + } + if target != binPath { + return fmt.Errorf("the active %s installation changed during the download", st.manifest.DisplayName) + } + marker, err := readEngineInstallMarker(st.installDir, engine) + if err != nil { + return err + } + if err := os.WriteFile(installMarkerPath(staging), marker, 0o600); err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if e.shuttingDown.Load() || e.stopWaiting(st) { + return context.Canceled + } + return e.replaceEngineInstall(ctx, st, staging, running) + }) +} + +func (e *Executor) managedUpdateTarget(ctx context.Context, st *engineState, eligible func(*engineState, string) bool) (string, bool, error) { + found, binary := detectPath(st) + if !found || !eligible(st, binary) { + return "", false, fmt.Errorf("updates require a PAIR-managed %s installation", st.manifest.DisplayName) + } + st.mu.Lock() + port := st.port + st.mu.Unlock() + presence := e.reconcilePresence(ctx, st.manifest.Engine, st, true, port, false) + st.mu.Lock() + defer st.mu.Unlock() + if st.adopted || presence.Occupied && (st.proc == nil || !isOurEngineImage(st.proc.cmd.Path, binary)) { + return "", false, fmt.Errorf("%s is running under external management", st.manifest.DisplayName) + } + return binary, st.running, nil +} + +func stagedEngineBinary(st *engineState, staging, binPath string) (string, error) { + rel, err := filepath.Rel(st.installDir, binPath) + if err != nil { + return "", err + } + stagedBinary := filepath.Join(staging, rel) + resolved, err := filepath.EvalSymlinks(stagedBinary) + resolvedStage, stageErr := filepath.EvalSymlinks(staging) + if err != nil || stageErr != nil || !isManagedInstallPath(resolved, resolvedStage) { + return "", fmt.Errorf("the %s archive does not contain its expected executable", st.manifest.DisplayName) + } + return stagedBinary, nil +} + +func (e *Executor) replaceEngineInstall(ctx context.Context, st *engineState, staging string, running bool) error { + engine, name := st.manifest.Engine, st.manifest.DisplayName + dir := st.installDir + backup := dir + ".update-backup" + // A completed swap can leave a verified previous copy if PAIR exits + // before cleanup. Never remove an unrelated directory at this path. + if _, err := os.Lstat(backup); err == nil { + if !isEngineUpdateBackup(backup, engine) { + return fmt.Errorf("%s update backup location %q is occupied", name, backup) + } + if err := os.RemoveAll(backup); err != nil { + return fmt.Errorf("remove previous %s backup: %w", name, err) + } + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + if running { + if err := e.doStop(st, engine); err != nil { + return err + } + } + restoreRunning := func(failure error) error { + if running && !e.shuttingDown.Load() && !e.stopWaiting(st) { + if restartErr := e.doStart(context.WithoutCancel(ctx), st, engine, startOpts{RequireOwned: true}); restartErr != nil { + return errors.Join(failure, fmt.Errorf("restart previous %s: %w", name, restartErr)) + } + } + return failure + } + if err := renameEngineDirectory(dir, backup); err != nil { + return restoreRunning(fmt.Errorf("back up installed %s: %w", name, err)) + } + if err := renameEngineDirectory(staging, dir); err != nil { + if rollbackErr := renameEngineDirectory(backup, dir); rollbackErr != nil { + return errors.Join(err, fmt.Errorf("restore %s from %s: %w", name, backup, rollbackErr)) + } + return restoreRunning(err) + } + if running { + if err := e.doStart(ctx, st, engine, startOpts{RequireOwned: true}); err != nil { + // doStart terminates a failed candidate before it returns. Move + // it back into staging so restoring the old copy needs no delete. + if moveErr := renameEngineDirectory(dir, staging); moveErr != nil { + return errors.Join(err, fmt.Errorf("move failed %s aside (previous copy at %s): %w", name, backup, moveErr)) + } + if rollbackErr := renameEngineDirectory(backup, dir); rollbackErr != nil { + return errors.Join(err, fmt.Errorf("restore %s from %s: %w", name, backup, rollbackErr)) + } + return restoreRunning(err) + } + } + // Retire the recovery name before cleanup. A partially removed backup + // must never be mistaken for a recoverable installation. + if err := renameEngineDirectory(backup, staging); err != nil { + slog.Warn("could not retire previous engine after update", "engine", engine, "err", err) + } + return nil +} diff --git a/services/nvpair-engine-manager/executor.go b/services/nvpair-engine-manager/executor.go index a4073a7a3..fc3354067 100644 --- a/services/nvpair-engine-manager/executor.go +++ b/services/nvpair-engine-manager/executor.go @@ -55,6 +55,9 @@ type engineState struct { plat *Platform logs *logBuffer installDir string + // bundledInstall is the unmodified vendor recipe, available only when + // this engine's active install directory matches the bundled location. + bundledInstall *Install // modelsDir is the resolved {models_dir}: the engine's model store, which no // removal this service performs may delete. Empty when the manifest declares // none, in which case uninstall has nothing to preserve. @@ -192,12 +195,14 @@ type Executor struct { // or a stop command, which later StopAll callers retry. The sweep writes it // without retryMu, since stopAllOnce returns to no caller before the sweep // finishes; retryMu serializes the retries that follow. - retryMu sync.Mutex - failedStops []string - mu sync.Mutex - engines map[string]*engineState - modelScope *http.Server - modelScopeURL string + retryMu sync.Mutex + failedStops []string + mu sync.Mutex + githubReleases map[string]*cachedGitHubRelease + githubRetryAt time.Time + engines map[string]*engineState + modelScope *http.Server + modelScopeURL string } func NewExecutor(reg *Registry, reporter *Reporter, emit func(string, any), baseDir string) *Executor { @@ -217,6 +222,7 @@ func NewExecutor(reg *Registry, reporter *Reporter, emit func(string, any), base pullCleanupTimeout: 5 * time.Second, loadedPollInterval: defaultLoadedPollSeconds * time.Second, loadedPoke: make(chan struct{}, 1), + githubReleases: make(map[string]*cachedGitHubRelease), engines: make(map[string]*engineState), } } @@ -306,6 +312,16 @@ func (e *Executor) state(engine string) (*engineState, error) { port: plat.Runtime.Port, installDir: installDir, } + if bundled, ok := e.reg.bundledPlatform(engine); ok && plat.InstallDir == bundled.InstallDir && filepath.IsAbs(installDir) { + st.bundledInstall = bundled.Install + switch engine { + case "ollama": + err = recoverStagedEngineInstall(installDir, engine) + } + if err != nil { + return nil, fmt.Errorf("recover %s installation: %w", m.DisplayName, err) + } + } if plat.ModelsDir != "" { st.modelsDir = expandPath(plat.ModelsDir) } diff --git a/services/nvpair-engine-manager/go.mod b/services/nvpair-engine-manager/go.mod index b5a1308ba..96a68449c 100644 --- a/services/nvpair-engine-manager/go.mod +++ b/services/nvpair-engine-manager/go.mod @@ -4,6 +4,7 @@ go 1.25.0 require ( github.com/stretchr/testify v1.12.1 + golang.org/x/mod v0.12.0 nvpair-shared v0.0.0-00010101000000-000000000000 ) diff --git a/services/nvpair-engine-manager/go.sum b/services/nvpair-engine-manager/go.sum index 4c4d6e0eb..af62aef9c 100644 --- a/services/nvpair-engine-manager/go.sum +++ b/services/nvpair-engine-manager/go.sum @@ -4,5 +4,7 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index 4c4c2b024..3d67a97c2 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -7,6 +7,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" "log/slog" @@ -16,6 +17,8 @@ import ( "os" "os/exec" "path" + "path/filepath" + "runtime" "strings" "time" ) @@ -61,6 +64,23 @@ func (e *Executor) Install(ctx context.Context, engine string) error { e.reportInstallFailed(engine, err) return err } + if st.bundledInstall != nil { + if err := os.MkdirAll(filepath.Dir(st.installDir), 0o755); err != nil { + return err + } + guard, err := lockEngineInstall(st.installDir) + if err != nil { + e.reportInstallFailed(engine, err) + return err + } + defer guard.Close() + // Another manager may have completed installation since detection. + if found, _ := e.Detect(engine); found { + e.reporter.clear(installFailedID(engine)) + e.emitInstallProgress(engine, "already-installed", 100) + return nil + } + } if err := os.MkdirAll(st.installDir, 0o755); err != nil { return fmt.Errorf("create install dir: %w", err) } @@ -85,44 +105,9 @@ func (e *Executor) Install(ctx context.Context, engine string) error { e.reportInstallFailed(engine, werr) return werr } - } else { - if inst.Fetch != nil { - e.emitInstallProgress(engine, "downloading", 0) - dp, err := e.download(ctx, engine, inst.Fetch) - if err != nil { - e.reportInstallFailed(engine, err) - return err - } - defer os.Remove(dp) - vars["download"] = dp - e.emitInstallProgress(engine, "verified", 0) - } - if len(inst.Artifacts) > 0 { - paths, artifactVars, err := e.downloadInstallArtifacts(ctx, engine, inst.Artifacts) - defer removeDownloadedFiles(paths) - if err != nil { - e.reportInstallFailed(engine, err) - return err - } - maps.Copy(vars, artifactVars) - e.emitInstallProgress(engine, "verified", 50) - } - if len(inst.Run) > 0 { - e.emitInstallProgress(engine, "installing", 0) - args, err := resolveArgs(inst.Run, vars) - if err != nil { - e.reportInstallFailed(engine, err) - return err - } - for i := range args { - args[i] = expandPath(args[i]) - } - if err := e.runCommandWithEnv(ctx, args, installCommandEnv(vars, inst.Artifacts)); err != nil { - werr := fmt.Errorf("install command failed: %w", err) - e.reportInstallFailed(engine, werr) - return werr - } - } + } else if err := e.installArchives(ctx, engine, inst, vars); err != nil { + e.reportInstallFailed(engine, err) + return err } if !e.waitDetect(engine, true, e.detectTimeout) { @@ -141,6 +126,47 @@ func (e *Executor) Install(ctx context.Context, engine string) error { return nil } +func (e *Executor) installArchives(ctx context.Context, engine string, inst *Install, vars map[string]string) error { + if inst.Fetch != nil { + e.emitInstallProgress(engine, "downloading", 0) + dp, err := e.download(ctx, engine, inst.Fetch) + if err != nil { + return err + } + defer os.Remove(dp) + vars["download"] = dp + e.emitInstallProgress(engine, "verified", 0) + } + if len(inst.Artifacts) > 0 { + paths, artifactVars, err := e.downloadInstallArtifacts(ctx, engine, inst.Artifacts) + defer removeDownloadedFiles(paths) + if err != nil { + return err + } + maps.Copy(vars, artifactVars) + e.emitInstallProgress(engine, "verified", 50) + } + if len(inst.Run) == 0 { + return nil + } + e.emitInstallProgress(engine, "installing", 0) + return e.runInstallCommand(ctx, inst, vars) +} + +func (e *Executor) runInstallCommand(ctx context.Context, inst *Install, vars map[string]string, installLock ...*os.File) error { + args, err := resolveArgs(inst.Run, vars) + if err != nil { + return err + } + for i := range args { + args[i] = expandPath(args[i]) + } + if err := runManifestCommand(ctx, args, installCommandEnv(vars, inst.Artifacts), installLock...); err != nil { + return fmt.Errorf("install command failed: %w", err) + } + return nil +} + // Uninstall runs the manifest's uninstall command (user-mode), stopping // the engine first. No-op if the engine isn't currently detected. func (e *Executor) Uninstall(ctx context.Context, engine string) error { @@ -150,6 +176,22 @@ func (e *Executor) Uninstall(ctx context.Context, engine string) error { } st.lockOperation() defer st.unlockOperation() + if st.bundledInstall != nil { + guard, err := lockEngineInstall(st.installDir) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + if guard != nil { + defer guard.Close() + } + } + if st.bundledInstall != nil && (engine == "ollama" || engine == "llamacpp" || engine == "vllm") { + // An interrupted update can leave both the promoted installation and + // its backup. Explicit removal must retire that recovery path too. + if err := discardEngineUpdateBackup(st.installDir, engine); err != nil { + return err + } + } if ok, _ := e.Detect(engine); !ok { // Already gone — by its own uninstaller, or by hand. Drop our ownership // claim with it: left behind, it would authorise removing a copy the @@ -432,14 +474,10 @@ func (e *Executor) runCommand(ctx context.Context, argv []string) error { return runManifestCommand(ctx, argv, nil) } -func (e *Executor) runCommandWithEnv(ctx context.Context, argv []string, environment map[string]string) error { - return runManifestCommand(ctx, argv, environment) -} - // runManifestCommand is independent of any Executor so the standalone // --uninstall-managed pass can run a manifest's uninstall command without // building the service's full runtime. -func runManifestCommand(ctx context.Context, argv []string, environment map[string]string) error { +func runManifestCommand(ctx context.Context, argv []string, environment map[string]string, installLock ...*os.File) error { if len(argv) == 0 { return nil } @@ -451,6 +489,12 @@ func runManifestCommand(ctx context.Context, argv []string, environment map[stri } } configureSysProcAttr(cmd) // hide the console window on Windows + if len(installLock) != 0 && runtime.GOOS != "windows" { + // Hold the update lock in the installer too. A replacement manager + // must wait for an orphaned installer before restoring the old venv. + cmd.ExtraFiles = installLock + } + cmd.Cancel = func() error { return signalPID(cmd.Process.Pid, true) } out, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("%v: %s", err, strings.TrimSpace(string(out))) diff --git a/services/nvpair-engine-manager/install_windows_test.go b/services/nvpair-engine-manager/install_windows_test.go index 2a603746c..84d9abeca 100644 --- a/services/nvpair-engine-manager/install_windows_test.go +++ b/services/nvpair-engine-manager/install_windows_test.go @@ -20,6 +20,43 @@ import ( "github.com/stretchr/testify/require" ) +func TestOllamaDirectoryRename_WaitsForWindowsToReleaseTheDirectory(t *testing.T) { + parent := t.TempDir() + staged := filepath.Join(parent, "staged") + installed := filepath.Join(parent, "ollama") + require.NoError(t, os.Mkdir(staged, 0o700)) + // A directory opened without delete sharing reproduces the handle left + // briefly open after Windows finishes executing the staged binary. + handle, err := os.Open(staged) + require.NoError(t, err) + closed := make(chan error, 1) + time.AfterFunc(200*time.Millisecond, func() { closed <- handle.Close() }) + + err = renameEngineDirectory(staged, installed) + + require.NoError(t, <-closed) + require.NoError(t, err) + assert.DirExists(t, installed) +} + +func TestReplaceOllamaInstall_RestoresCurrentVersionWhenStagingRemainsLocked(t *testing.T) { + e, binary := ollamaUpdateFixture(t, "1.1.0", false) + st, err := e.state("ollama") + require.NoError(t, err) + staged := t.TempDir() + handle, err := os.Open(staged) + require.NoError(t, err) + + err = e.replaceEngineInstall(t.Context(), st, staged, false) + + require.NoError(t, handle.Close()) + require.Error(t, err) + version, err := ollamaBinaryVersion(t.Context(), binary) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) + assert.NoDirExists(t, st.installDir+".update-backup") +} + func TestLlamaCPPInstall_PreservesDestinationPathWithSpaces(t *testing.T) { serverArchive := testZIP(t, "llama-server.exe", "server") cudartArchive := testZIP(t, "cudart64_12.dll", "runtime") diff --git a/services/nvpair-engine-manager/manager.go b/services/nvpair-engine-manager/manager.go index bb9a2111c..11381c9fb 100644 --- a/services/nvpair-engine-manager/manager.go +++ b/services/nvpair-engine-manager/manager.go @@ -15,6 +15,7 @@ import ( "nvpair-shared/applog" "nvpair-shared/clustertrust" + "nvpair-shared/engines" enginesettings "nvpair-shared/enginesettings" "nvpair-shared/noderec" "nvpair-shared/reach" @@ -260,6 +261,16 @@ func (m *Manager) handleMessage(ctx context.Context, msg *Message) { m.codec.Respond(msg.ID, map[string]any{"engines": m.exec.GetInstalled()}) }() + case "engine:check-updates": + var p engineParam + if !m.parse(msg, &p) || !m.validUpdateEngine(msg, p.Engine) { + return + } + go func() { + update, err := m.exec.CheckEngineUpdate(ctx, p.Engine) + m.respondOrErr(msg, map[string]any{"updateAvailable": update}, err) + }() + // Removes the engines PAIR installed. Long-running — each engine goes // through the full uninstall — so it runs off the read loop like the other // lifecycle operations. @@ -313,7 +324,7 @@ func (m *Manager) handleMessage(ctx context.Context, msg *Message) { case "engine:catalog": go m.runCatalog(ctx, msg) - case "engine:install", "engine:uninstall", "engine:start", "engine:stop", "engine:restart": + case "engine:install", "engine:uninstall", "engine:update", "engine:start", "engine:stop", "engine:restart": go m.runOp(ctx, msg) case "engine:set-port": @@ -449,6 +460,11 @@ func (m *Manager) runOp(ctx context.Context, msg *Message) { } case "engine:uninstall": err = m.exec.Uninstall(ctx, p.Engine) + case "engine:update": + if !m.validUpdateEngine(msg, p.Engine) { + return + } + err = m.exec.UpdateEngine(ctx, p.Engine) case "engine:start": err = start() case "engine:stop": @@ -591,6 +607,14 @@ func (m *Manager) parse(msg *Message, v any) bool { return true } +func (m *Manager) validUpdateEngine(msg *Message, engine string) bool { + if _, ok := engines.ByName(engine); !ok { + m.codec.RespondError(msg.ID, -32602, fmt.Sprintf("unknown engine %q", engine)) + return false + } + return true +} + func (m *Manager) respondOrErr(msg *Message, result any, err error) { if err != nil { m.codec.RespondError(msg.ID, -32000, err.Error()) diff --git a/services/nvpair-engine-manager/ollama_update.go b/services/nvpair-engine-manager/ollama_update.go new file mode 100644 index 000000000..a996bc2c1 --- /dev/null +++ b/services/nvpair-engine-manager/ollama_update.go @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "strings" + + "nvpair-shared/engines" +) + +// managedOllamaBinary is shared with the version check, so the UI offers a +// managed update only for a layout the updater can safely replace. +func managedOllamaBinary(st *engineState, binPath string) bool { + if !managedUpdateBinary(st, binPath) { + return false + } + // Ollama's models may have been relocated via its launch environment. + // Preserve both the store used by a running daemon and the configured one + // that would be used after restart, including a store reached via a link. + launch, err := launchForState(st, 0, false) + if err != nil { + return false + } + env := processEnvironment(binPath, launch.Env) + if env == nil { + env = os.Environ() + } + configuredStore := strings.Trim(strings.TrimSpace(environmentValue(env, "OLLAMA_MODELS")), `"'`) + if configuredStore == "" { + configuredStore = filepath.Join(environmentValue(env, homeVariable()), ".ollama", "models") + } + return modelStoresOutsideInstall(st, ollamaBlobsDir(st), configuredStore) +} + +// UpdateOllama stages a checksum-verified archive before replacing the +// original installation. +func (e *Executor) UpdateOllama(ctx context.Context) error { + return e.updateStagedEngine(ctx, engines.NameOllama, managedOllamaBinary, e.stageOllamaUpdate) +} + +func (e *Executor) stageOllamaUpdate(ctx context.Context, st *engineState, binPath, staging string) (bool, error) { + current, err := ollamaBinaryVersion(ctx, binPath) + if err != nil { + return false, err + } + release, err := e.latestOllamaRelease(ctx) + if err != nil { + return false, err + } + order, err := compareOllamaVersions(current, release.Version) + if err != nil || order >= 0 { + return false, err + } + + return true, e.stageOllamaRelease(ctx, st, release, staging, binPath) +} + +func (release *ollamaRelease) archiveFor(inst *Install) (*Fetch, error) { + if inst == nil || inst.ModeOrDefault() != "user" || inst.Fetch == nil || len(inst.Run) == 0 { + return nil, errors.New("Ollama has no supported archive installer for this platform") + } + // Use the platform archive named by the installer, pinned to the release + // we just checked. A floating vendor URL could change between requests. + name := path.Base(inst.Fetch.URL) + url := "https://github.com/ollama/ollama/releases/download/v" + release.Version + "/" + name + return githubReleaseAssetFetch(release.Assets, name, url) +} + +func (e *Executor) stageOllamaRelease(ctx context.Context, st *engineState, release *ollamaRelease, stage, binPath string) error { + inst := st.bundledInstall + fetch, err := release.archiveFor(inst) + if err != nil { + return err + } + pinned := *inst + pinned.Fetch = fetch + if err := e.installArchives(ctx, engines.NameOllama, &pinned, map[string]string{"install_dir": stage}); err != nil { + return err + } + stagedBinary, err := stagedEngineBinary(st, stage, binPath) + if err != nil { + return err + } + version, err := ollamaBinaryVersion(ctx, stagedBinary) + if err != nil { + return fmt.Errorf("verify staged Ollama: %w", err) + } + if version != release.Version { + return fmt.Errorf("the downloaded Ollama reports version %s, expected %s", version, release.Version) + } + return nil +} diff --git a/services/nvpair-engine-manager/ollama_update_test.go b/services/nvpair-engine-manager/ollama_update_test.go new file mode 100644 index 000000000..fdf21961c --- /dev/null +++ b/services/nvpair-engine-manager/ollama_update_test.go @@ -0,0 +1,308 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "archive/tar" + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The installer extracts a small, local tar archive on every platform. Its +// executable is the same fake that the service lifecycle tests start/stop. +func ollamaUpdateFixture(t *testing.T, stagedVersion string, failStart bool) (*Executor, string) { + t.Helper() + t.Setenv("OLLAMA_MODELS", t.TempDir()) + name := "ollama" + filepath.Ext(fakeEngineBin) + bin := filepath.Join("{install_dir}", name) + manifest := testEngineManifest(bin) + manifest.Engine = "ollama" + manifest.DisplayName = "Ollama" + platformKey := runtime.GOOS + "/" + runtime.GOARCH + platform := manifest.Platforms[platformKey] + platform.ModelsDir = os.Getenv("OLLAMA_MODELS") + platform.Uninstall = &Uninstall{Remove: []string{"{install_dir}"}} + platform.Install = &Install{ + Fetch: &Fetch{URL: "https://ollama.com/download/ollama-test.tar"}, + Run: []string{"tar", "-xf", "{download}", "-C", "{install_dir}"}, + } + manifest.Platforms[platformKey] = platform + e := newTestExecutor(t, manifest) + bundled, err := json.Marshal(manifest) + require.NoError(t, err) + e.reg.bundledRaw["ollama"] = bundled + st, err := e.state("ollama") + require.NoError(t, err) + require.NoError(t, writeInstallMarker(st.installDir, "ollama")) + installed := filepath.Join(st.installDir, name) + copyFile(t, fakeEngineBin, installed) + require.NoError(t, os.WriteFile(installed+".version", []byte("1.0.0"), 0o600)) + t.Cleanup(e.StopAll) + + var archive bytes.Buffer + tw := tar.NewWriter(&archive) + add := func(path string, data []byte) { + t.Helper() + require.NoError(t, tw.WriteHeader(&tar.Header{Name: path, Size: int64(len(data)), Mode: 0o755})) + _, err := tw.Write(data) + require.NoError(t, err) + } + exe, err := os.ReadFile(fakeEngineBin) + require.NoError(t, err) + add(name, exe) + add(name+".version", []byte(stagedVersion)) + if failStart { + add(name+".fail-start", nil) + } + require.NoError(t, tw.Close()) + const assetURL = "https://github.com/ollama/ollama/releases/download/v1.1.0/ollama-test.tar" + release, err := json.Marshal(githubRelease{ + Tag: "v1.1.0", + Assets: []githubReleaseAsset{{Name: "ollama-test.tar", Digest: fmt.Sprintf("sha256:%x", sha256.Sum256(archive.Bytes())), BrowserDownloadURL: assetURL}}, + }) + require.NoError(t, err) + loopback := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var data []byte + switch req.URL.String() { + case latestOllamaReleaseURL: + data = release + case assetURL: + data = archive.Bytes() + default: + if req.URL.Hostname() != "127.0.0.1" { + return nil, fmt.Errorf("unexpected request to %s", req.URL) + } + return loopback.RoundTrip(req) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(data)), ContentLength: int64(len(data))}, nil + }) + return e, installed +} + +func TestUpdateOllama_PreservesModelsAndLeavesStoppedEngineOff(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + model := filepath.Join(os.Getenv("OLLAMA_MODELS"), "model") + require.NoError(t, os.WriteFile(model, []byte("model data"), 0o600)) + + require.NoError(t, e.UpdateEngine(t.Context(), "ollama")) + + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.1.0", version) + status, err := e.Status("ollama") + require.NoError(t, err) + assert.True(t, status.Installed) + assert.False(t, status.Enabled) + assert.False(t, status.Running) + data, err := os.ReadFile(model) + require.NoError(t, err) + assert.Equal(t, "model data", string(data)) +} + +func TestUpdateOllama_RestartsRunningEngineAtItsPreviousPort(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + require.NoError(t, e.Start(t.Context(), "ollama")) + before, err := e.Status("ollama") + require.NoError(t, err) + + require.NoError(t, e.UpdateOllama(t.Context())) + + status, err := e.Status("ollama") + require.NoError(t, err) + assert.True(t, status.Running) + assert.True(t, status.Enabled) + assert.True(t, status.Healthy) + assert.Equal(t, before.Port, status.Port) + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.1.0", version) +} + +func TestUpdateOllama_RestoresRunningVersionWhenNewReleaseFailsToStart(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", true) + require.NoError(t, e.Start(t.Context(), "ollama")) + + require.Error(t, e.UpdateOllama(t.Context())) + + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) + status, err := e.Status("ollama") + require.NoError(t, err) + assert.True(t, status.Enabled) + assert.True(t, status.Running) + assert.True(t, status.Healthy) +} + +func TestUpdateOllama_RejectsUnexpectedArchiveVersionBeforeStoppingEngine(t *testing.T) { + e, _ := ollamaUpdateFixture(t, "0.9.0", false) + require.NoError(t, e.Start(t.Context(), "ollama")) + st, err := e.state("ollama") + require.NoError(t, err) + st.mu.Lock() + process := st.proc + st.mu.Unlock() + + require.ErrorContains(t, e.UpdateOllama(t.Context()), "reports version 0.9.0, expected 1.1.0") + + st.mu.Lock() + defer st.mu.Unlock() + assert.Same(t, process, st.proc) + assert.True(t, st.running) +} + +func TestUpdateOllama_RefusesModelStoreInsideManagedDirectory(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + t.Setenv("OLLAMA_MODELS", filepath.Join(filepath.Dir(installed), "models")) + + require.ErrorContains(t, e.UpdateOllama(t.Context()), "PAIR-managed Ollama installation") + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) +} + +func TestUpdateOllama_LeavesCustomInstallerUnderUserControl(t *testing.T) { + e, _ := ollamaUpdateFixture(t, "1.1.0", false) + st, err := e.state("ollama") + require.NoError(t, err) + st.plat.Install.Run = []string{"custom-ollama-install"} + + require.ErrorContains(t, e.UpdateOllama(t.Context()), "PAIR-managed Ollama installation") +} + +func TestUpdateEngine_LeavesRelocatedInstallationsUnderUserControl(t *testing.T) { + e, binary := ollamaUpdateFixture(t, "1.1.0", false) + manifest, ok := e.reg.Get("ollama") + require.True(t, ok) + platform := manifest.Platforms[hostKey()] + platform.InstallDir = t.TempDir() + manifest.Platforms[hostKey()] = platform + relocated := filepath.Join(platform.InstallDir, filepath.Base(binary)) + copyFile(t, binary, relocated) + require.NoError(t, writeInstallMarker(platform.InstallDir, "ollama")) + restarted := NewExecutor(e.reg, NewReporter(nil), nil, e.baseDir) + + err := restarted.UpdateEngine(t.Context(), "ollama") + + require.ErrorContains(t, err, "PAIR-managed Ollama installation") + assert.FileExists(t, relocated) +} + +func TestUpdateOllama_LeavesInstalledVersionInPlaceWhenArchiveChecksumDiffers(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + transport := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "github.com" { + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader([]byte("changed bytes")))}, nil + } + return transport.RoundTrip(req) + }) + + require.ErrorContains(t, e.UpdateOllama(t.Context()), "checksum mismatch") + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) +} + +func TestOllamaStatus_RestoresOriginalWhenInterruptedBetweenRenames(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + dir := filepath.Dir(installed) + require.NoError(t, os.Rename(dir, dir+".update-backup")) + restarted := NewExecutor(e.reg, NewReporter(nil), nil, e.baseDir) + + status, err := restarted.Status("ollama") + + require.NoError(t, err) + assert.True(t, status.Installed) + version, err := ollamaBinaryVersion(context.Background(), installed) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) +} + +func TestOllamaRecovery_LeavesBackupInPlaceWhileAnotherManagerIsUpdating(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + dir := filepath.Dir(installed) + guard, err := lockEngineInstall(dir) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, guard.Close()) }) + require.NoError(t, renameEngineDirectory(dir, dir+".update-backup")) + other := NewExecutor(e.reg, NewReporter(nil), nil, e.baseDir) + + _, err = other.Status("ollama") + + require.Error(t, err) + assert.NoDirExists(t, dir) + assert.FileExists(t, filepath.Join(dir+".update-backup", filepath.Base(installed))) +} + +func TestOllamaUninstall_PreservesAnInstallationBeingUpdatedByAnotherManager(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + guard, err := lockEngineInstall(filepath.Dir(installed)) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, guard.Close()) }) + + require.Error(t, e.Uninstall(t.Context(), "ollama")) + assert.FileExists(t, installed) +} + +func TestUninstallOllama_PreventsInterruptedUpdateBackupFromRestoringRemovedEngine(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + dir := filepath.Dir(installed) + require.NoError(t, writeInstallMarker(dir+".update-backup", "ollama")) + + require.NoError(t, e.Uninstall(t.Context(), "ollama")) + + restarted := NewExecutor(e.reg, NewReporter(nil), nil, e.baseDir) + status, err := restarted.Status("ollama") + require.NoError(t, err) + assert.False(t, status.Installed) + assert.NoDirExists(t, dir+".update-backup") +} + +func TestUpdateOllama_ShutdownCancelsStalledDownload(t *testing.T) { + e, installed := ollamaUpdateFixture(t, "1.1.0", false) + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + started := make(chan struct{}) + transport := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "github.com" { + close(started) + <-req.Context().Done() + return nil, req.Context().Err() + } + return transport.RoundTrip(req) + }) + result := make(chan error, 1) + go func() { result <- e.UpdateOllama(ctx) }() + select { + case <-started: + case err := <-result: + t.Fatalf("update ended before requesting the archive: %v", err) + case <-ctx.Done(): + t.Fatal("archive download did not start") + } + + e.StopAll() + + require.NoError(t, ctx.Err(), "shutdown waited for the download's deadline") + require.ErrorIs(t, <-result, context.Canceled) + version, err := ollamaBinaryVersion(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) +} diff --git a/services/nvpair-engine-manager/ollama_version.go b/services/nvpair-engine-manager/ollama_version.go new file mode 100644 index 000000000..f1c15ff0c --- /dev/null +++ b/services/nvpair-engine-manager/ollama_version.go @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "os/exec" + "strings" + "time" + + "golang.org/x/mod/semver" + "nvpair-shared/engines" +) + +type ollamaRelease struct { + Version string + Assets []githubReleaseAsset +} + +// CheckOllamaUpdate returns nil for an absent or current installation. A failed +// check is reported separately so clients can retain their last known result. +func (e *Executor) CheckOllamaUpdate(ctx context.Context) (*EngineUpdateInfo, error) { + return e.checkInstalledEngineUpdate(ctx, engines.NameOllama, e.checkOllamaRelease) +} + +func (e *Executor) checkOllamaRelease(ctx context.Context, st *engineState, snapshot engineUpdateSnapshot) (*EngineUpdateInfo, error) { + // A second installation can become the first detected path while the + // original is serving. Its version and the updater's target must agree. + if snapshot.processPath != "" && !isOurEngineImage(snapshot.processPath, snapshot.binPath) { + return nil, nil + } + var current string + var err error + if snapshot.running { + current, err = e.runningOllamaVersion(ctx, snapshot.port) + } else { + current, err = ollamaBinaryVersion(ctx, snapshot.binPath) + } + if err != nil { + return nil, err + } + release, err := e.latestOllamaRelease(ctx) + if err != nil { + return nil, err + } + order, err := compareOllamaVersions(current, release.Version) + if err != nil || order >= 0 { + return nil, err + } + result := &EngineUpdateInfo{ + CurrentVersion: current, + LatestVersion: release.Version, + ReleaseURL: "https://github.com/ollama/ollama/releases/tag/v" + release.Version, + InstallType: "external", + DownloadURL: "https://ollama.com/download", + } + if !snapshot.adopted && managedOllamaBinary(st, snapshot.binPath) { + // A release can be public before its archive for this platform is ready. + if _, err := release.archiveFor(st.bundledInstall); err != nil { + return nil, nil + } + result.InstallType = "managed" + result.DownloadURL = "" + } + return result, nil +} + +func (e *Executor) runningOllamaVersion(ctx context.Context, port int) (string, error) { + var reply struct { + Version string `json:"version"` + } + if err := e.readRunningEngineVersion(ctx, port, "/api/version", &reply); err != nil { + return "", fmt.Errorf("read running Ollama version: %w", err) + } + return normalizedOllamaVersion(reply.Version) +} + +func ollamaBinaryVersion(ctx context.Context, binPath string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, binPath, "--version") + // The CLI asks OLLAMA_HOST for its server version before printing its own. + // Query only the selected binary, even when the user routes to a remote host. + cmd.Env = processEnvironment(binPath, map[string]string{"OLLAMA_HOST": "http://127.0.0.1:0"}) + configureSysProcAttr(cmd) + out, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("read installed Ollama version: %w", err) + } + return parseOllamaBinaryVersion(string(out)) +} + +func parseOllamaBinaryVersion(output string) (string, error) { + var version string + for line := range strings.Lines(output) { + line = strings.TrimSpace(line) + if v, ok := strings.CutPrefix(line, "Warning: client version is "); ok { + return normalizedOllamaVersion(v) + } + if v, ok := strings.CutPrefix(line, "ollama version is "); ok { + version = v + } + } + return normalizedOllamaVersion(version) +} + +func (e *Executor) latestOllamaRelease(ctx context.Context) (*ollamaRelease, error) { + release, err := e.latestGitHubRelease(ctx, "ollama/ollama") + if err != nil { + return nil, err + } + tag := release.Tag + version, err := normalizedOllamaVersion(tag) + if err != nil || !strings.HasPrefix(tag, "v") || semver.Prerelease(tag) != "" { + return nil, errors.New("Ollama release feed did not return a stable version") + } + return &ollamaRelease{Version: version, Assets: release.Assets}, nil +} + +func normalizedOllamaVersion(raw string) (string, error) { + version := strings.TrimPrefix(raw, "v") + core, _, _ := strings.Cut(version, "-") + core, _, _ = strings.Cut(core, "+") + if strings.Count(core, ".") != 2 || !semver.IsValid("v"+version) { + return "", errors.New("unrecognized Ollama version") + } + return version, nil +} + +func compareOllamaVersions(current, latest string) (int, error) { + a, err := normalizedOllamaVersion(current) + if err != nil { + return 0, err + } + b, err := normalizedOllamaVersion(latest) + if err != nil { + return 0, err + } + return semver.Compare("v"+a, "v"+b), nil +} diff --git a/services/nvpair-engine-manager/ollama_version_test.go b/services/nvpair-engine-manager/ollama_version_test.go new file mode 100644 index 000000000..78a8f2076 --- /dev/null +++ b/services/nvpair-engine-manager/ollama_version_test.go @@ -0,0 +1,306 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const latestOllamaReleaseURL = "https://api.github.com/repos/ollama/ollama/releases/latest" + +func TestCompareOllamaVersions_OrdersReleasesBySemanticVersion(t *testing.T) { + check := func(name, current, latest string, expected int) { + t.Run(name, func(t *testing.T) { + order, err := compareOllamaVersions(current, latest) + require.NoError(t, err) + assert.Equal(t, expected, order) + }) + } + check("minor version crosses a decimal place", "0.9.5", "v0.10.0", -1) + check("installed version is ahead", "0.10.1", "0.10.0", 1) + check("stable release supersedes an installed release candidate", "0.10.0-rc.1", "0.10.0", -1) + check("build metadata does not affect ordering", "0.10.0+build.1", "0.10.0", 0) +} + +func TestParseOllamaBinaryVersion_ReturnsTheSelectedBinaryVersion(t *testing.T) { + version, err := parseOllamaBinaryVersion("ollama version is 0.10.0\nWarning: client version is 0.9.5\n") + require.NoError(t, err) + assert.Equal(t, "0.9.5", version) +} + +func TestLatestOllamaRelease_RejectsIncompleteOrUnstableFeedEntries(t *testing.T) { + reject := func(name, body string) { + t.Run(name, func(t *testing.T) { + ex := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + mockOllamaFeed(t, ex, http.StatusOK, body) + _, err := ex.latestOllamaRelease(t.Context()) + require.Error(t, err) + }) + } + reject("missing tag", `{}`) + reject("incomplete version", `{"tag_name":"v0.9"}`) + reject("draft release", `{"tag_name":"v0.10.0","draft":true}`) + reject("prerelease flag", `{"tag_name":"v0.10.0","prerelease":true}`) + reject("prerelease version", `{"tag_name":"v0.10.0-rc.1"}`) +} + +func TestGitHubRelease_AcceptsOnlyThePublishedTagRequestedByTheProvider(t *testing.T) { + for _, tc := range []struct { + name string + body string + wantTag string + }{ + {"vendor selected a tag GitHub labels prerelease", `{"tag_name":"b12345","prerelease":true}`, "b12345"}, + {"draft", `{"tag_name":"b12345","draft":true}`, ""}, + {"different tag", `{"tag_name":"b12346"}`, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + assert.Equal(t, "https://api.github.com/repos/ggml-org/llama.cpp/releases/tags/b12345", req.URL.String()) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(tc.body))}, nil + }) + + release, err := e.githubRelease(t.Context(), "ggml-org/llama.cpp", "tags/b12345") + + if tc.wantTag == "" { + require.Error(t, err) + assert.Nil(t, release) + return + } + require.NoError(t, err) + require.NotNil(t, release) + assert.Equal(t, tc.wantTag, release.Tag) + }) + } +} + +func mockOllamaFeed(t *testing.T, ex *Executor, status int, body string) { + t.Helper() + transport := ex.client.Transport + ex.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Hostname() == "127.0.0.1" { + return transport.RoundTrip(req) + } + if req.URL.String() != latestOllamaReleaseURL { + return nil, fmt.Errorf("unexpected release request: %s", req.URL) + } + return &http.Response{ + StatusCode: status, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(body)), + }, nil + }) +} + +func TestCheckOllamaUpdate_ReportsAnUpdateForAStoppedExternalBinary(t *testing.T) { + bin := filepath.Join(t.TempDir(), filepath.Base(fakeEngineBin)) + copyFile(t, fakeEngineBin, bin) + require.NoError(t, os.WriteFile(bin+".version", []byte("0.9.5"), 0o600)) + manifest := testEngineManifest(bin) + manifest.Engine = "ollama" + ex := newTestExecutor(t, manifest) + mockOllamaFeed(t, ex, http.StatusOK, `{"tag_name":"v0.10.0"}`) + + update, err := ex.CheckOllamaUpdate(t.Context()) + + require.NoError(t, err) + assert.Equal(t, &EngineUpdateInfo{ + CurrentVersion: "0.9.5", + LatestVersion: "0.10.0", + ReleaseURL: "https://github.com/ollama/ollama/releases/tag/v0.10.0", + InstallType: "external", + DownloadURL: "https://ollama.com/download", + }, update) +} + +func TestCheckOllamaUpdate_OffersManagedUpdatesWhenThePlatformArchiveIsReady(t *testing.T) { + manifest := testEngineManifest(filepath.Join("{install_dir}", filepath.Base(fakeEngineBin))) + manifest.Engine = "ollama" + key := runtime.GOOS + "/" + runtime.GOARCH + platform := manifest.Platforms[key] + platform.Install = &Install{ + Fetch: &Fetch{URL: "https://ollama.com/download/ollama-test.zip"}, + Run: []string{"unzip", "{download}", "-d", "{install_dir}"}, + } + manifest.Platforms[key] = platform + bundled, err := json.Marshal(manifest) + require.NoError(t, err) + installedOllama := func(t *testing.T) *Executor { + t.Helper() + ex := newTestExecutor(t, manifest) + ex.reg.bundledRaw["ollama"] = bundled + st, err := ex.state("ollama") + require.NoError(t, err) + require.NoError(t, writeInstallMarker(st.installDir, "ollama")) + bin := filepath.Join(st.installDir, filepath.Base(fakeEngineBin)) + copyFile(t, fakeEngineBin, bin) + require.NoError(t, os.WriteFile(bin+".version", []byte("0.9.5"), 0o600)) + return ex + } + t.Setenv("OLLAMA_MODELS", t.TempDir()) + + t.Run("platform archive published", func(t *testing.T) { + ex := installedOllama(t) + mockOllamaFeed(t, ex, http.StatusOK, `{ + "tag_name": "v0.10.0", + "assets": [{ + "name": "ollama-test.zip", + "digest": "sha256:00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff", + "browser_download_url": "https://github.com/ollama/ollama/releases/download/v0.10.0/ollama-test.zip" + }] + }`) + update, err := ex.CheckOllamaUpdate(t.Context()) + require.NoError(t, err) + require.NotNil(t, update) + assert.Equal(t, "managed", update.InstallType) + assert.Empty(t, update.DownloadURL) + }) + t.Run("platform archive missing", func(t *testing.T) { + ex := installedOllama(t) + mockOllamaFeed(t, ex, http.StatusOK, `{"tag_name":"v0.10.0","assets":[]}`) + update, err := ex.CheckOllamaUpdate(t.Context()) + require.NoError(t, err) + assert.Nil(t, update) + }) +} + +func TestCheckOllamaUpdate_ChecksAnAdoptedServerWithNoLocalBinary(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path != "/api/version" || req.Header.Get(engineIdentityProbeHeader) != "1" { + http.NotFound(w, req) + return + } + _, err := io.WriteString(w, `{"version":"0.9.5"}`) + assert.NoError(t, err) + })) + t.Cleanup(server.Close) + port, err := strconv.Atoi(strings.TrimPrefix(server.URL, "http://127.0.0.1:")) + require.NoError(t, err) + manifest := testEngineManifest(filepath.Join(t.TempDir(), "absent")) + manifest.Engine = "ollama" + key := runtime.GOOS + "/" + runtime.GOARCH + platform := manifest.Platforms[key] + platform.Runtime.Port = port + platform.Runtime.Ready.HTTP = "http://127.0.0.1:{port}/api/version" + manifest.Platforms[key] = platform + ex := newTestExecutor(t, manifest) + mockOllamaFeed(t, ex, http.StatusOK, `{"tag_name":"v0.10.0"}`) + + update, err := ex.CheckOllamaUpdate(t.Context()) + + require.NoError(t, err) + require.NotNil(t, update) + assert.Equal(t, "0.9.5", update.CurrentVersion) + assert.Equal(t, "external", update.InstallType) +} + +func TestCheckOllamaUpdate_SkipsASecondInstallationWhileTheOriginalIsRunning(t *testing.T) { + preferred := filepath.Join(t.TempDir(), filepath.Base(fakeEngineBin)) + copyFile(t, fakeEngineBin, preferred) + manifest := testEngineManifest(preferred) + manifest.Engine = "ollama" + ex := newTestExecutor(t, manifest) + st, err := ex.state("ollama") + require.NoError(t, err) + st.proc = &managedProc{cmd: exec.Command(fakeEngineBin)} + st.running = true + + update, err := ex.CheckOllamaUpdate(t.Context()) + + require.NoError(t, err) + assert.Nil(t, update) +} + +func TestCheckOllamaUpdate_ChecksTheFeedOnlyForInstalledEngines(t *testing.T) { + manifest := testEngineManifest(filepath.Join(t.TempDir(), "absent")) + manifest.Engine = "ollama" + ex := newTestExecutor(t, manifest) + ex.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + t.Errorf("unexpected network request for an absent engine: %s", req.URL) + return nil, errors.New("unexpected network request") + }) + + update, err := ex.CheckOllamaUpdate(t.Context()) + + require.NoError(t, err) + assert.Nil(t, update) +} + +func TestCheckOllamaUpdate_SkipsHostsWithNoSupportedInstallation(t *testing.T) { + check := func(name string, manifest *Manifest) { + t.Run(name, func(t *testing.T) { + e := newTestExecutor(t, manifest) + + update, err := e.CheckOllamaUpdate(t.Context()) + + require.NoError(t, err) + assert.Nil(t, update) + }) + } + check("no Ollama manifest", testEngineManifest(fakeEngineBin)) + check("manifest has no host platform", &Manifest{Engine: "ollama"}) +} + +func TestCheckOllamaUpdate_DiscardsReleaseWhenInstallationChangesDuringCheck(t *testing.T) { + bin := filepath.Join(t.TempDir(), filepath.Base(fakeEngineBin)) + copyFile(t, fakeEngineBin, bin) + require.NoError(t, os.WriteFile(bin+".version", []byte("0.9.5"), 0o600)) + manifest := testEngineManifest(bin) + manifest.Engine = "ollama" + e := newTestExecutor(t, manifest) + mockOllamaFeed(t, e, http.StatusOK, `{"tag_name":"v0.10.0"}`) + feed := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + // A status refresh observes that the previously checked executable + // disappeared while the service was waiting on the release feed. + require.NoError(t, os.Remove(bin)) + installed, err := e.Detect("ollama") + require.NoError(t, err) + require.False(t, installed) + return feed.RoundTrip(req) + }) + + update, err := e.CheckOllamaUpdate(t.Context()) + + require.ErrorContains(t, err, "changed during the update check") + assert.Nil(t, update) +} + +func TestCheckOllamaUpdate_DistinguishesACurrentVersionFromAReleaseCheckFailure(t *testing.T) { + bin := filepath.Join(t.TempDir(), filepath.Base(fakeEngineBin)) + copyFile(t, fakeEngineBin, bin) + require.NoError(t, os.WriteFile(bin+".version", []byte("0.10.0"), 0o600)) + manifest := testEngineManifest(bin) + manifest.Engine = "ollama" + t.Run("current version clears the notification", func(t *testing.T) { + ex := newTestExecutor(t, manifest) + mockOllamaFeed(t, ex, http.StatusOK, `{"tag_name":"v0.10.0"}`) + update, err := ex.CheckOllamaUpdate(t.Context()) + require.NoError(t, err) + assert.Nil(t, update) + }) + t.Run("rate limited check returns an error", func(t *testing.T) { + ex := newTestExecutor(t, manifest) + mockOllamaFeed(t, ex, http.StatusTooManyRequests, "") + update, err := ex.CheckOllamaUpdate(t.Context()) + require.ErrorContains(t, err, "HTTP 429") + assert.Nil(t, update) + }) +} diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 8277e8322..96168ad1f 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -688,23 +688,27 @@ func (r *Registry) applyLocationOverrides(dir string) { // (un-overridden) manifest for an engine, used to decide whether a chosen // port is back at the default (so its override file can be dropped). func (r *Registry) bundledDefaultPort(engine string) (int, bool) { - raw, ok := r.bundledRaw[engine] + p, ok := r.bundledPlatform(engine) if !ok { return 0, false } + return p.Runtime.Port, true +} + +func (r *Registry) bundledPlatform(engine string) (*Platform, bool) { + raw, ok := r.bundledRaw[engine] + if !ok { + return nil, false + } merged, err := applyPlatformDefaults(raw) if err != nil { - return 0, false + return nil, false } var m Manifest if err := json.Unmarshal(merged, &m); err != nil { - return 0, false - } - p, ok := m.HostPlatform() - if !ok { - return 0, false + return nil, false } - return p.Runtime.Port, true + return m.HostPlatform() } // mergeOntoBundled deep-merges an override manifest's raw JSON onto the diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index ad6b4213a..da59a1abe 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -316,6 +316,8 @@ Requests (caller → service): | `engine:describe` | `{ engine }` | the engine's manifest | | `engine:status` | `{ engine, port? }` | `EngineStatus`; an error for an engine this host cannot run | | `engine:install` | `{ engine }` | `EngineStatus` (after install) | +| `engine:check-updates` | `{ engine }` | `{ updateAvailable: null }` when the engine is absent or no applicable update is available. A newer release yields `{ updateAvailable: { currentVersion, latestVersion, releaseUrl, installType, downloadUrl? } }`. `releaseUrl` links to release information. `installType` is `managed` or `external`. External offers include `downloadUrl` for the vendor's update page. Failed lookups return an RPC error. | +| `engine:update` | `{ engine }` | `EngineStatus` after updating a local managed installation. Checks ownership and preserves the running or stopped state. External installs are refused. | | `engine:uninstall` | `{ engine }` | `EngineStatus` (after removal) | | `engine:uninstall-managed` | — | `{ engines: [{ engine, removed, error? }] }` — removes the engines this service installed, selected by their install marker, each through the `engine:uninstall` path. Backs both clients' "reset all data"; the platform uninstallers reach the same code through `--uninstall-managed` because they have no broker. Neither `removed` nor `error` means the engine was left alone as not ours. | | `engine:start` | `{ engine, port?, bind? }` | `EngineStatus` (after readiness); a non-loopback `bind` is rejected with `-32602` (`bind must be a loopback address`) unless the `engine_allow_lan_bind` node setting is on | diff --git a/services/nvpair-engine-manager/testdata/fakeengine/main.go b/services/nvpair-engine-manager/testdata/fakeengine/main.go index 5d0f6c875..54d2cbfc7 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -147,6 +147,19 @@ func downloadUntilInterrupted(interrupts int) { } func main() { + // Installed and staged test executables each report their own release. + if len(os.Args) == 2 && os.Args[1] == "--version" { + version, err := os.ReadFile(os.Args[0] + ".version") + if err != nil { + os.Exit(2) + } + fmt.Fprintln(os.Stderr, "Warning: could not connect to a running Ollama instance") + fmt.Fprintf(os.Stderr, "Warning: client version is %s\n", version) + return + } + if _, err := os.Stat(os.Args[0] + ".fail-start"); err == nil { + os.Exit(1) + } if path := os.Getenv("PAIR_TEST_ENV_FILE"); path != "" { values := map[string]string{} for _, key := range []string{"OLLAMA_ORIGINS", "PAIR_TEST_LITERAL", "PAIR_TEST_EMPTY", "OLLAMA_HOST", "MODEL_ENDPOINT"} { diff --git a/services/nvpair-engine-manager/update_lock.go b/services/nvpair-engine-manager/update_lock.go new file mode 100644 index 000000000..3941c79ca --- /dev/null +++ b/services/nvpair-engine-manager/update_lock.go @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +// The desktop and TUI can each own a manager. Keep the lock file beside the +// canonical directory so directory replacement never changes its identity. +// Closing the file releases the lock. Removing it could let two owners lock +// different inodes at the same name. +func lockEngineInstall(dir string) (*os.File, error) { + if !filepath.IsAbs(dir) { + return nil, fmt.Errorf("cannot lock a relative engine installation path") + } + path := dir + ".update-lock" + guard, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + entry, err := os.Lstat(path) + if err == nil && entry.Mode().IsRegular() { + var file os.FileInfo + file, err = guard.Stat() + if err == nil && os.SameFile(file, entry) { + if err = tryEngineInstallLock(guard); err == nil { + return guard, nil + } + } + } + guard.Close() + return nil, fmt.Errorf("engine installation lock is busy or invalid: %s", path) +} diff --git a/services/nvpair-engine-manager/update_lock_unix.go b/services/nvpair-engine-manager/update_lock_unix.go new file mode 100644 index 000000000..70e6f01ac --- /dev/null +++ b/services/nvpair-engine-manager/update_lock_unix.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows + +package main + +import ( + "os" + "syscall" +) + +func tryEngineInstallLock(guard *os.File) error { + return syscall.Flock(int(guard.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) +} diff --git a/services/nvpair-engine-manager/update_lock_windows.go b/services/nvpair-engine-manager/update_lock_windows.go new file mode 100644 index 000000000..05480e963 --- /dev/null +++ b/services/nvpair-engine-manager/update_lock_windows.go @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows + +package main + +import ( + "os" + + "golang.org/x/sys/windows" +) + +func tryEngineInstallLock(guard *os.File) error { + return windows.LockFileEx(windows.Handle(guard.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}) +} diff --git a/services/nvpair-ui-broker/README.md b/services/nvpair-ui-broker/README.md index 5b9759bc5..40ee0216e 100644 --- a/services/nvpair-ui-broker/README.md +++ b/services/nvpair-ui-broker/README.md @@ -640,7 +640,7 @@ Opt into / out of the `engine:` stream (off by default). Acks `{ subscrib #### `engine:` (generic relay) -Any other `engine:*` request is forwarded to `nvpair-engine-manager` verbatim and its response relayed straight back. This covers the whole engine control plane: `engine:get-installed`, `engine:describe`, `engine:status`, `engine:install`, `engine:uninstall`, `engine:start`, `engine:stop`, `engine:restart`, `engine:action`, `engine:logs`, `engine:errors`, `engine:models`. Lifecycle ops run for minutes (reporting progress via the `engine:install-progress` / `engine:state-changed` push events), so the relay imposes **no broker-side timeout** — fire the request and watch the event stream for the outcome. Error `-32000 "engine-manager not available"` when no engine-manager is supervised. +Any other `engine:*` request is forwarded to `nvpair-engine-manager` verbatim and its response relayed straight back. This includes `engine:check-updates` and `engine:update` for local engines. See the [engine manager's JSON-RPC surface](../nvpair-engine-manager/README.md#json-rpc-surface) for all methods. Lifecycle ops run for minutes (reporting progress via the `engine:install-progress` / `engine:state-changed` push events), so the relay imposes **no broker-side timeout** — fire the request and watch the event stream for the outcome. Error `-32000 "engine-manager not available"` when no engine-manager is supervised. `engine:set-port` is **not** in that generic set. Like `-proxy:set-port` it is intercepted and run through the authoritative settings operation, so moving an engine's server port from a port-only caller validates and restarts exactly as the full editor does, and persists as a manifest override that survives a restart. Its response is the engine's `engine:status` result. diff --git a/services/nvpair-ui-broker/broker.go b/services/nvpair-ui-broker/broker.go index e8c64694c..0b4b970e4 100644 --- a/services/nvpair-ui-broker/broker.go +++ b/services/nvpair-ui-broker/broker.go @@ -3631,7 +3631,7 @@ func (b *Broker) relayToEngineInOrder(msg *Message) { } func (b *Broker) relayToEngineNow(msg *Message) { - if needsOllamaPortGate(msg.Method, msg.Params) && b.ollamaFacadeIsPendingBackend() { + if b.ollamaFacadeIsPendingBackend() && needsEnginePortGate(engines.NameOllama, msg.Method, msg.Params) { go func() { select { case <-b.ollamaPortReady: @@ -3648,7 +3648,7 @@ func (b *Broker) relayToEngineNow(msg *Message) { }() return } - if needsLMStudioPortGate(msg.Method, msg.Params) && b.lmstudioPortOwnershipPending() { + if b.lmstudioPortOwnershipPending() && needsEnginePortGate(engines.NameLMStudio, msg.Method, msg.Params) { go func() { select { case <-b.lmstudioPortReady: diff --git a/services/nvpair-ui-broker/lmstudioport.go b/services/nvpair-ui-broker/lmstudioport.go index a7366627a..2b86670f5 100644 --- a/services/nvpair-ui-broker/lmstudioport.go +++ b/services/nvpair-ui-broker/lmstudioport.go @@ -72,24 +72,6 @@ func (b *Broker) lmstudioPortOwnershipPending() bool { } } -// needsLMStudioPortGate mirrors needsOllamaPortGate: these are the client -// requests that can probe and adopt the configured port, so they must wait -// while :1234 is changing hands. engine:install is gated for the same reason -// as the rest — an install that starts the engine assigns it a port, and doing -// that mid-transition can land on the port the proxy is about to take. -func needsLMStudioPortGate(method string, params json.RawMessage) bool { - if method == "engine:get-installed" { - return true - } - if method != "engine:status" && method != "engine:install" && method != "engine:start" && method != "engine:restart" { - return false - } - var request struct { - Engine string `json:"engine"` - } - return json.Unmarshal(params, &request) == nil && request.Engine == "lmstudio" -} - func lmstudioSetPortRequest(method string, params json.RawMessage) (int, bool) { if method != "engine:set-port" { return 0, false diff --git a/services/nvpair-ui-broker/lmstudioport_test.go b/services/nvpair-ui-broker/lmstudioport_test.go index a47d9d07d..bf647e5ba 100644 --- a/services/nvpair-ui-broker/lmstudioport_test.go +++ b/services/nvpair-ui-broker/lmstudioport_test.go @@ -308,10 +308,13 @@ func TestLMStudioRequests_WaitForPortGate(t *testing.T) { func TestLMStudioPortGate_MatchesRequestsThatRequireStablePorts(t *testing.T) { test := func(name, method, params string, want bool) { t.Run(name, func(t *testing.T) { - assert.Equal(t, want, needsLMStudioPortGate(method, json.RawMessage(params))) + assert.Equal(t, want, needsEnginePortGate("lmstudio", method, json.RawMessage(params))) }) } test("inventory waits", "engine:get-installed", `{}`, true) + test("LM Studio update check waits", "engine:check-updates", `{"engine":"lmstudio"}`, true) + test("LM Studio update waits", "engine:update", `{"engine":"lmstudio"}`, true) + test("Ollama update check does not wait", "engine:check-updates", `{"engine":"ollama"}`, false) test("LM Studio status waits", "engine:status", `{"engine":"lmstudio"}`, true) test("LM Studio start waits", "engine:start", `{"engine":"lmstudio"}`, true) test("LM Studio restart waits", "engine:restart", `{"engine":"lmstudio"}`, true) diff --git a/services/nvpair-ui-broker/proxyport.go b/services/nvpair-ui-broker/proxyport.go index 298a3c023..38a6e8760 100644 --- a/services/nvpair-ui-broker/proxyport.go +++ b/services/nvpair-ui-broker/proxyport.go @@ -392,20 +392,20 @@ func (b *Broker) rejectOllamaHostAliasPort(msg *Message, port int, owner string) return true } -// needsOllamaPortGate reports the client requests that can probe and adopt the -// configured Ollama port. While :11434 is changing from backend to facade, -// those probes must wait or they can mistake the proxy for a local engine. -func needsOllamaPortGate(method string, params json.RawMessage) bool { - if method == "engine:get-installed" { +// Presence checks and operations that can start an engine must wait while +// its compatibility port is changing hands between the engine and the proxy. +func needsEnginePortGate(engine, method string, params json.RawMessage) bool { + switch method { + case "engine:get-installed": return true - } - if method != "engine:status" && method != "engine:install" && method != "engine:start" && method != "engine:restart" { + case "engine:status", "engine:check-updates", "engine:install", "engine:update", "engine:start", "engine:restart": + var request struct { + Engine string `json:"engine"` + } + return json.Unmarshal(params, &request) == nil && request.Engine == engine + default: return false } - var request struct { - Engine string `json:"engine"` - } - return json.Unmarshal(params, &request) == nil && request.Engine == "ollama" } // reconcileProxyPortOnReady runs after the proxy announces a bound port diff --git a/services/nvpair-ui-broker/proxyport_test.go b/services/nvpair-ui-broker/proxyport_test.go index 74cd8c583..e69929da6 100644 --- a/services/nvpair-ui-broker/proxyport_test.go +++ b/services/nvpair-ui-broker/proxyport_test.go @@ -433,10 +433,13 @@ func TestBroker_DoesNotExposeInternalReservationSetter(t *testing.T) { func TestNeedsOllamaPortGate_IdentifiesRequestsRequiringStablePort(t *testing.T) { test := func(name, method, params string, want bool) { t.Run(name, func(t *testing.T) { - assert.Equal(t, want, needsOllamaPortGate(method, []byte(params))) + assert.Equal(t, want, needsEnginePortGate("ollama", method, []byte(params))) }) } test("inventory waits", "engine:get-installed", `{}`, true) + test("Ollama update check waits", "engine:check-updates", `{"engine":"ollama"}`, true) + test("llama.cpp update check does not wait", "engine:check-updates", `{"engine":"llamacpp"}`, false) + test("Ollama update waits", "engine:update", `{"engine":"ollama"}`, true) test("Ollama status waits", "engine:status", `{"engine":"ollama"}`, true) test("Ollama install waits", "engine:install", `{"engine":"ollama"}`, true) test("Ollama start waits", "engine:start", `{"engine":"ollama"}`, true) diff --git a/services/tests/engine_update_test.go b/services/tests/engine_update_test.go new file mode 100644 index 000000000..3c69c2ca4 --- /dev/null +++ b/services/tests/engine_update_test.go @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package tests + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "nvpair-shared/engines" +) + +func TestBroker_RelaysLocalEngineUpdateRequests(t *testing.T) { + configDir := t.TempDir() + installDir := t.TempDir() + writeUserManifest(t, configDir, map[string]any{ + "engine": engines.NameOllama, + "platforms": map[string]any{runtime.GOOS + "/" + runtime.GOARCH: map[string]any{ + "detect": []string{filepath.Join(installDir, engines.NameOllama)}, + "install": nil, + "runtime": map[string]any{"port": freePorts(t, 1)[0]}, + }}, + }) + stdin, messages, _, cleanup := startBrokerWithConfigDir(t, configDir, "--engine-manager-path", engineMgrBin) + t.Cleanup(cleanup) + waitForMethod(t, messages, "app:ready", 15*time.Second) + + t.Run("absent Ollama has no update", func(t *testing.T) { + reply := callRPC(t, stdin, messages, "engine:check-updates", map[string]string{"engine": engines.NameOllama}, 10*time.Second) + require.Nil(t, reply.Error) + var result map[string]any + require.NoError(t, json.Unmarshal(reply.Result, &result)) + require.Contains(t, result, "updateAvailable") + assert.Nil(t, result["updateAvailable"]) + }) + t.Run("an update cannot install absent Ollama", func(t *testing.T) { + reply := callRPC(t, stdin, messages, "engine:update", map[string]string{"engine": engines.NameOllama}, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32000, reply.Error.Code) + }) + + t.Run("a broken Ollama executable reports a check error", func(t *testing.T) { + require.NoError(t, os.WriteFile(filepath.Join(installDir, engines.NameOllama), []byte("invalid executable"), 0o600)) + reply := callRPC(t, stdin, messages, "engine:check-updates", map[string]string{"engine": engines.NameOllama}, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32000, reply.Error.Code) + }) + + for _, method := range []string{"engine:check-updates", "engine:update"} { + t.Run(method+" rejects an unknown engine", func(t *testing.T) { + reply := callRPC(t, stdin, messages, method, map[string]string{"engine": "unknown"}, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32602, reply.Error.Code) + }) + t.Run(method+" requires an engine name", func(t *testing.T) { + reply := callRPC(t, stdin, messages, method, map[string]string{}, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32602, reply.Error.Code) + }) + } +}