diff --git a/.cursor/rules/architecture.mdc b/.cursor/rules/architecture.mdc index 5395db1d7..fa25c5600 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 each local engine, 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..1bff41363 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 each local engine 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..51afd0c90 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 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..9a03b8cfe 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 each installed local engine. 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..769072df2 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 each installed local engine. A local start or stop also triggers +a background check for that engine. 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..205c39781 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 engines | 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..027c9feb6 --- /dev/null +++ b/desktop/src/electron/service-bridge/engine-update-checks.ts @@ -0,0 +1,67 @@ +// 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 { EngineTypes } from '@/shared/constants/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): Promise { + if (engine) await checkEngine(engine) + else await Promise.all(EngineTypes.map(checkEngine)) + } + + 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..2a6d934db 100644 --- a/desktop/tests/modular/empty-handlers.test.ts +++ b/desktop/tests/modular/empty-handlers.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from 'vitest' +import type { EngineManagerName, EngineType } from '@/shared/types/engines' import type { getEngineHubModels } from '@/electron/service-bridge/model-catalog' import type { getModularSupervisor } from '@/electron/service-bridge/modular-supervisor' import type { getModularBridgeState } from '@/electron/service-bridge/modular-state' @@ -11,10 +12,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 +39,69 @@ vi.mock('@/electron/service-bridge/model-catalog', () => ({ import { handleServiceBridgeInvoke } from '@/electron/service-bridge/empty-handlers' +describe('local engine update command', () => { + it.each<{ engineType: EngineType; engine: EngineManagerName }>([ + { engineType: 'ollama', engine: 'ollama' }, + { engineType: 'lm-studio', engine: 'lmstudio' }, + { engineType: 'llama-cpp', engine: 'llamacpp' }, + { engineType: 'vllm', engine: 'vllm' } + ])('sends one managed update for $engineType as $engine', async ({ engineType, engine }) => { + mocks.supervisor.sendProcess.mockClear() + mocks.state.getSelfId.mockReturnValue('self') + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType, + nodeId: 'self' + }) + + expect(mocks.supervisor.sendProcess).toHaveBeenCalledOnce() + expect(mocks.supervisor.sendProcess).toHaveBeenCalledWith( + 'broker', + 'engine:update', + { engine }, + 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: 'lm-studio', + nodeId: 'self' + }) + expect(mocks.supervisor.reportError).toHaveBeenCalledWith( + 'Failed to update lmstudio: update rejected', + 'error', + undefined, + { + id: 'engine-manager:update-failed:lmstudio', + nodeId: 'self', + engineType: 'lm-studio', + 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..6f879ef1b --- /dev/null +++ b/desktop/tests/modular/engine-update-checks.test.ts @@ -0,0 +1,253 @@ +// 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: 'lmstudio', installed: true, running: false } + const running = { ...stopped, running: true } + state.applyEngineManagerList({ engines: [stopped, { engine: 'ollama', 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([['lm-studio']]) + + state.applyEngineManagerStatus(stopped) + await vi.advanceTimersByTimeAsync(0) + state.applyEngineManagerStatus(stopped) + expect(check.mock.calls).toEqual([['lm-studio'], ['lm-studio']]) + }) + + it('checks vLLM when enabled or stopped without loading a model', async () => { + const stopped = { engine: 'vllm', installed: true, running: false, awaiting_model: false } + state.applyEngineManagerList({ engines: [stopped] }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + check.mockClear() + + state.applyEngineManagerStatus({ ...stopped, awaiting_model: true }) + await vi.advanceTimersByTimeAsync(0) + expect(check.mock.calls).toEqual([['vllm']]) + + state.applyEngineManagerStatus(stopped) + expect(check.mock.calls).toEqual([['vllm'], ['vllm']]) + }) + + 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 each supported engine and keeps its offers independent of other engines', async () => { + state.applyEngineManagerList({ + engines: [ + { engine: 'ollama', installed: true }, + { engine: 'lmstudio', installed: false }, + { engine: 'llamacpp', installed: true } + ] + }) + const lmStudio = { + currentVersion: '0.4.0', + latestVersion: '0.4.1', + releaseUrl: 'https://lmstudio.ai/changelog', + downloadUrl: 'https://lmstudio.ai/download', + installType: 'external' + } + check.mockImplementation(async engine => { + if (engine === 'llama-cpp') throw new Error('offline') + return { updateAvailable: engine === 'lm-studio' ? lmStudio : available } + }) + checks = watchEngineUpdates(check) + await vi.advanceTimersByTimeAsync(0) + + expect(check.mock.calls).toEqual([['ollama'], ['lm-studio'], ['llama-cpp']]) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'local', engineType: 'ollama' }, + { ...lmStudio, nodeId: 'local', engineType: 'lm-studio' } + ]) + + check.mockClear().mockResolvedValue({ updateAvailable: null }) + await checks.refresh('lm-studio') + expect(check.mock.calls).toEqual([['lm-studio']]) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'local', engineType: '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..4351bfcce --- /dev/null +++ b/desktop/tests/modular/engine-update-controls.test.ts @@ -0,0 +1,247 @@ +// 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('deduplicates and withdraws local notices independently for each engine', () => { + const unsubscribe = subscribeEngineUpdateNotifications(() => 'local-node') + report({ ...update, nodeId: 'peer' }) + const lmStudioUpdate: EngineUpdateAvailable = { + ...update, + engineType: 'lm-studio', + currentVersion: '0.10.0', + releaseUrl: 'https://lmstudio.ai/changelog/lmstudio', + installType: 'external', + downloadUrl: 'https://lmstudio.ai/download#lm-studio-download-heading' + } + report(lmStudioUpdate) + report(update) + report(update) + report({ ...update, latestVersion: '0.10.3' }) + report(lmStudioUpdate) + 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:lm-studio:0.10.2', + '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('LM Studio update available') +}) + +it('opens the local engine settings from the vLLM notification', async () => { + const unsubscribe = subscribeEngineUpdateNotifications(() => 'local-node') + report({ + ...update, + engineType: 'vllm', + releaseUrl: 'https://github.com/vllm-project/vllm/releases/tag/v0.10.2' + }) + 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('vLLM update available') + await act(() => button('Open engine settings')?.click()) + + expect(useOverviewUiStore.getState()).toMatchObject({ + activeTab: 'overview', + focusNodeId: 'local-node' + }) + expect(onClose).toHaveBeenCalledOnce() +}) + +it('shows the managed llama.cpp build tags and dispatches Update', async () => { + const onUpdate = vi.fn<() => void>() + const llama: BackendInfo = { + ...engine, + type: 'llama-cpp', + displayName: 'llama.cpp', + updateAvailable: { + ...update, + engineType: 'llama-cpp', + currentVersion: 'b12001', + latestVersion: 'b12002', + releaseUrl: 'https://github.com/ggml-org/llama.cpp/releases/tag/b12002' + } + } + await act(() => + root.render( + createElement(BackendUpdateBanner, { backend: llama, disabled: false, onUpdate }) + ) + ) + expect(document.body.textContent).toContain('b12001 installed') + expect(document.body.textContent).toContain('llama.cpp b12002 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('opens the headless LM Studio update guide for a newly detected external daemon', async () => { + const onUpdate = vi.fn<() => void>() + const guide = 'https://lmstudio.ai/docs/cli/daemon/daemon-update' + const external: BackendInfo = { + ...engine, + type: 'lm-studio', + displayName: 'LM Studio', + // The update check may detect the daemon before the lifecycle snapshot refreshes. + processStatus: 'not-installed', + updateAvailable: { + ...update, + engineType: 'lm-studio', + installType: 'external', + releaseUrl: guide, + downloadUrl: guide + } + } + await act(() => + root.render( + createElement(BackendUpdateBanner, { + backend: external, + disabled: false, + onUpdate + }) + ) + ) + await act(() => button('Get update')?.click()) + expect(openExternal.mock.calls).toEqual([['https://lmstudio.ai/docs/cli/daemon/daemon-update']]) + expect(button('Update details')).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:lmstudio', + timestamp: 1, + action: 'retry', + engineType: 'lm-studio', + operation: 'update', + message: 'LM Studio 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([['lm-studio', 'local-node']]) +}) diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index a6ef99675..b9bfe3f65 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, update, and remove Ollama, LM Studio, llama.cpp, and vLLM on a PAIR node. --- {/* @@ -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,34 @@ 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. +PAIR checks for updates at startup and every six hours. It also checks an +individual engine in the background when it starts or stops. If the release +service is unreachable, the engine continues normally and PAIR keeps any +previously reported offer for that installation. When PAIR identifies a newer +release, **Overview** shows a message once per engine and release in that +desktop session. Select **Open engine settings** to see the installed and +available versions. + +- **Update** lets PAIR update the copy it installed and controls. PAIR keeps + downloaded models and engine settings and restores the previous running or + stopped state. +- **Get update** opens the vendor's release page or instructions 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. + +| Engine | Release PAIR checks | +| --- | --- | +| Ollama | The latest stable Ollama release. PAIR updates a managed copy in its standard install folder when the official package is available for this platform. | +| LM Studio | The stable release for the installed product and platform. LM Studio's desktop app and its headless daemon (`llmster`) have separate releases. PAIR can update its own headless installation when it controls the daemon or the daemon is stopped. | +| llama.cpp | The latest stable upstream build. For managed installs, PAIR needs matching archives and checksums for your platform and CUDA variant. When those files are unavailable, it can offer the bundled build if that build is newer than yours. | +| vLLM | For a managed install, the version pinned by PAIR for Linux or the matching vLLM and vLLM-Metal versions for Apple Silicon. For an external install, the upstream release for that platform. | + +An update notice requires an identifiable installed version. For a portable +LM Studio AppImage, open LM Studio if its version is only available while it +is running. On Apple Silicon, a vLLM check also needs the installed +vLLM-Metal package version. **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..6c4938155 --- /dev/null +++ b/services/nvpair-engine-manager/engine_updates.go @@ -0,0 +1,363 @@ +// 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}, + engines.NameLlamaCPP: {(*Executor).CheckLlamaCppUpdate, (*Executor).UpdateLlamaCpp}, + engines.NameLMStudio: {(*Executor).CheckLMStudioUpdate, (*Executor).UpdateLMStudio}, + engines.NameVLLM: {(*Executor).CheckVLLMUpdate, (*Executor).UpdateVLLM}, +} + +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..352ee0bd4 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,18 @@ 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", "llamacpp": + err = recoverStagedEngineInstall(installDir, engine) + case "vllm": + err = recoverVLLMUpdate(installDir) + } + 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..8be5dd5ff 100644 --- a/services/nvpair-engine-manager/install_windows_test.go +++ b/services/nvpair-engine-manager/install_windows_test.go @@ -20,9 +20,54 @@ import ( "github.com/stretchr/testify/require" ) -func TestLlamaCPPInstall_PreservesDestinationPathWithSpaces(t *testing.T) { - serverArchive := testZIP(t, "llama-server.exe", "server") - cudartArchive := testZIP(t, "cudart64_12.dll", "runtime") +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_ExtractsBothArchivesWithWindowsPowerShell(t *testing.T) { + // A parent shell can supply an Archive module incompatible with powershell.exe. + modulePath := t.TempDir() + module := filepath.Join(modulePath, "Microsoft.PowerShell.Archive") + require.NoError(t, os.Mkdir(module, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(module, "Microsoft.PowerShell.Archive.psm1"), + []byte("function Expand-Archive { throw 'Incompatible Archive module' }"), 0o600)) + t.Setenv("PSModulePath", modulePath) + + serverArchive := testZIP(t, map[string]string{"llama-server.exe": "server", "LICENSE": "server license"}) + cudartArchive := testZIP(t, map[string]string{"cudart64_12.dll": "runtime", "LICENSE": "runtime license"}) archives := map[string][]byte{ "/server.zip": serverArchive, "/cudart.zip": cudartArchive, @@ -59,6 +104,7 @@ func TestLlamaCPPInstall_PreservesDestinationPathWithSpaces(t *testing.T) { for name, want := range map[string]string{ "llama-server.exe": "server", "cudart64_12.dll": "runtime", + "LICENSE": "runtime license", } { data, err := os.ReadFile(filepath.Join(baseDir, "llamacpp", name)) require.NoError(t, err, "read extracted %s", name) @@ -66,14 +112,16 @@ func TestLlamaCPPInstall_PreservesDestinationPathWithSpaces(t *testing.T) { } } -func testZIP(t *testing.T, name, contents string) []byte { +func testZIP(t *testing.T, files map[string]string) []byte { t.Helper() var buffer bytes.Buffer archive := zip.NewWriter(&buffer) - file, err := archive.Create(name) - require.NoError(t, err, "create zip entry %s", name) - _, err = file.Write([]byte(contents)) - require.NoError(t, err, "write zip entry %s", name) + for name, contents := range files { + file, err := archive.Create(name) + require.NoError(t, err, "create zip entry %s", name) + _, err = file.Write([]byte(contents)) + require.NoError(t, err, "write zip entry %s", name) + } require.NoError(t, archive.Close(), "close zip archive") return buffer.Bytes() } diff --git a/services/nvpair-engine-manager/llamacpp_update.go b/services/nvpair-engine-manager/llamacpp_update.go new file mode 100644 index 000000000..6e714a50b --- /dev/null +++ b/services/nvpair-engine-manager/llamacpp_update.go @@ -0,0 +1,264 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "slices" + "strconv" + "strings" + "time" + + "nvpair-shared/engines" +) + +const llamaReleasesURL = "https://github.com/ggml-org/llama.cpp/releases" + +// The stable release contains a short text file pointing to the numbered build +// that actually publishes the binaries, including the CUDA runtime archives. +const latestLlamaBuildURL = llamaReleasesURL + "/latest/download/nightly-tag.txt" + +type llamaBuild int + +func (b llamaBuild) tag() string { return "b" + strconv.Itoa(int(b)) } + +func parseLlamaBuild(tag string) (llamaBuild, error) { + build, err := strconv.Atoi(strings.TrimPrefix(tag, "b")) + if err != nil || build <= 0 || llamaBuild(build).tag() != tag { + return 0, errors.New("unrecognized llama.cpp build number") + } + return llamaBuild(build), nil +} + +var llamaVersionLine = regexp.MustCompile(`(?m)^version: (?:[^\s]+ \(build ([0-9]+), commit [^()\s]+\)|([0-9]+) \([^()\s]+\))\r?$`) + +func llamaBinaryBuild(ctx context.Context, binPath string) (llamaBuild, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, binPath, "--version") + if runtime.GOOS == "linux" { + // The Linux release ships libllama and its CUDA libraries beside the + // executable. A staged probe must load that copy of the libraries. + libraries := filepath.Dir(binPath) + if inherited := os.Getenv("LD_LIBRARY_PATH"); inherited != "" { + libraries += string(os.PathListSeparator) + inherited + } + cmd.Env = processEnvironment(binPath, map[string]string{"LD_LIBRARY_PATH": libraries}) + } + configureSysProcAttr(cmd) + out, err := cmd.CombinedOutput() + if err != nil { + return 0, fmt.Errorf("read installed llama.cpp build: %w", err) + } + match := llamaVersionLine.FindSubmatch(out) + if match == nil { + return 0, errors.New("llama-server --version did not report a build number") + } + return parseLlamaBuild("b" + string(match[1]) + string(match[2])) +} + +func (e *Executor) latestLlamaBuild(ctx context.Context) (llamaBuild, error) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, latestLlamaBuildURL, nil) + if err != nil { + return 0, err + } + resp, err := e.client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return 0, fmt.Errorf("check llama.cpp stable release: HTTP %d", resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, 65)) + if err != nil { + return 0, err + } + if len(data) > 64 { + return 0, errors.New("invalid llama.cpp stable release pointer") + } + return parseLlamaBuild(strings.TrimSpace(string(data))) +} + +func managedLlamaBinary(st *engineState, binPath string) bool { + if !managedUpdateBinary(st, binPath) { + return false + } + launch, err := launchForState(st, 0, false) + if err != nil { + return false + } + env := processEnvironment(binPath, launch.Env) + if env == nil { + env = os.Environ() + } + st.mu.Lock() + proc := st.proc + st.mu.Unlock() + if proc != nil && !llamaModelsOutsideInstall(st, proc.cmd.Args, proc.cmd.Env) { + return false + } + return llamaModelsOutsideInstall(st, launch.Args, env) +} + +func llamaModelsOutsideInstall(st *engineState, args, env []string) bool { + stores := []string{environmentValue(env, "LLAMA_CACHE"), environmentValue(env, "LLAMA_ARG_MODELS_DIR"), + environmentValue(env, "LLAMA_ARG_MODEL"), environmentValue(env, "LLAMA_ARG_MODELS_PRESET")} + for _, flag := range []string{"--models-dir", "--model", "-m", "--models-preset"} { + if path, ok := launchFlagValue(args, flag); ok { + stores = append(stores, path) + } + } + return modelStoresOutsideInstall(st, stores...) +} + +func (e *Executor) CheckLlamaCppUpdate(ctx context.Context) (*EngineUpdateInfo, error) { + return e.checkInstalledEngineUpdate(ctx, engines.NameLlamaCPP, func(ctx context.Context, st *engineState, s engineUpdateSnapshot) (*EngineUpdateInfo, error) { + if s.processPath != "" && !isOurEngineImage(s.processPath, s.binPath) { + return nil, nil + } + var current llamaBuild + var err error + if s.running { + var props struct { + BuildInfo string `json:"build_info"` + } + if err := e.readRunningEngineVersion(ctx, s.port, "/props", &props); err != nil { + return nil, err + } + tag, _, _ := strings.Cut(props.BuildInfo, "-") + current, err = parseLlamaBuild(tag) + } else { + current, err = llamaBinaryBuild(ctx, s.binPath) + } + if err != nil { + return nil, err + } + var installer *Install + ownership := "external" + if !s.adopted && managedLlamaBinary(st, s.binPath) { + installer, ownership = st.bundledInstall, "managed" + } + target, _, err := e.llamaUpdateRelease(ctx, current, installer) + if err != nil || target <= current { + return nil, err + } + url := llamaReleasesURL + "/tag/" + target.tag() + info := &EngineUpdateInfo{CurrentVersion: current.tag(), LatestVersion: target.tag(), ReleaseURL: url, InstallType: ownership} + if installer == nil { + info.DownloadURL = url + } + return info, nil + }) +} + +// A managed update uses exactly the OS, architecture, CUDA version and archive +// format in the bundled recipe. When a vendor changes variants, the bundled +// checksummed build remains available to older installations. +func (e *Executor) llamaUpdateRelease(ctx context.Context, current llamaBuild, inst *Install) (llamaBuild, *Install, error) { + latest, err := e.latestLlamaBuild(ctx) + if err != nil || inst == nil { + return latest, nil, err + } + pin, err := bundledLlamaBuild(inst) + if err != nil || latest <= pin || current >= latest { + return pin, inst, err + } + release, err := e.githubRelease(ctx, "ggml-org/llama.cpp", "tags/"+latest.tag()) + if err != nil { + return 0, nil, err + } + // Resolve all required assets before offering an update or downloading one. + archive := func(oldURL string) (*Fetch, error) { + name := strings.TrimPrefix(oldURL, llamaReleasesURL+"/download/"+pin.tag()+"/") + name = strings.ReplaceAll(name, "-"+pin.tag()+"-", "-"+latest.tag()+"-") + url := llamaReleasesURL + "/download/" + latest.tag() + "/" + name + return githubReleaseAssetFetch(release.Assets, name, url) + } + candidate := *inst + if inst.Fetch != nil { + candidate.Fetch, err = archive(inst.Fetch.URL) + if err != nil { + return pin, inst, nil + } + } + candidate.Artifacts = slices.Clone(inst.Artifacts) + for i, artifact := range inst.Artifacts { + fetch, err := archive(artifact.URL) + if err != nil { + return pin, inst, nil + } + candidate.Artifacts[i].URL, candidate.Artifacts[i].SHA256 = fetch.URL, fetch.SHA256 + } + return latest, &candidate, nil +} + +func bundledLlamaBuild(inst *Install) (llamaBuild, error) { + var build llamaBuild + check := func(url, checksum string) bool { + tail, ok := strings.CutPrefix(url, llamaReleasesURL+"/download/") + tag, name, hasFile := strings.Cut(tail, "/") + version, err := parseLlamaBuild(tag) + if !ok || !hasFile || name == "" || strings.Contains(name, "/") || !sha256Re.MatchString(checksum) || err != nil || (build != 0 && build != version) { + return false + } + build = version + return true + } + invalid := errors.New("the bundled llama.cpp installer must pin every archive to one checksummed build") + if inst.ModeOrDefault() != "user" || len(inst.Run) == 0 || len(inst.Script) != 0 { + return 0, invalid + } + if inst.Fetch != nil && !check(inst.Fetch.URL, inst.Fetch.SHA256) { + return 0, invalid + } + for _, artifact := range inst.Artifacts { + if !check(artifact.URL, artifact.SHA256) { + return 0, invalid + } + } + if build == 0 { + return 0, invalid + } + return build, nil +} + +func (e *Executor) UpdateLlamaCpp(ctx context.Context) error { + return e.updateStagedEngine(ctx, engines.NameLlamaCPP, managedLlamaBinary, func(ctx context.Context, st *engineState, binPath, staging string) (bool, error) { + current, err := llamaBinaryBuild(ctx, binPath) + if err != nil { + return false, err + } + target, inst, err := e.llamaUpdateRelease(ctx, current, st.bundledInstall) + if err != nil || target <= current { + return false, err + } + if err := e.installArchives(ctx, engines.NameLlamaCPP, inst, map[string]string{"install_dir": staging}); err != nil { + return false, err + } + candidate, err := stagedEngineBinary(st, staging, binPath) + if err != nil { + return false, err + } + version, err := llamaBinaryBuild(ctx, candidate) + if err != nil { + return false, err + } + if version != target { + return false, fmt.Errorf("the downloaded llama.cpp reports build %s, expected %s", version.tag(), target.tag()) + } + return true, nil + }) +} diff --git a/services/nvpair-engine-manager/llamacpp_update_test.go b/services/nvpair-engine-manager/llamacpp_update_test.go new file mode 100644 index 000000000..1b1cfaf9f --- /dev/null +++ b/services/nvpair-engine-manager/llamacpp_update_test.go @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "archive/tar" + "bytes" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func mockLlamaRelease(t *testing.T, e *Executor, tag string, assets []githubReleaseAsset, downloads map[string][]byte) { + t.Helper() + release, err := json.Marshal(githubRelease{Tag: tag, Prerelease: true, Assets: assets}) + require.NoError(t, err) + transport := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body []byte + switch req.URL.String() { + case latestLlamaBuildURL: + body = []byte(tag + "\n") + case "https://api.github.com/repos/ggml-org/llama.cpp/releases/tags/" + tag: + body = release + default: + if req.URL.Hostname() == "127.0.0.1" { + return transport.RoundTrip(req) + } + download, exists := downloads[req.URL.String()] + if !exists { + return nil, fmt.Errorf("unexpected download: %s", req.URL) + } + body = download + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(body)), ContentLength: int64(len(body))}, nil + }) +} + +func llamaTestAsset(tag, name string, data []byte) githubReleaseAsset { + return githubReleaseAsset{Name: name, Digest: fmt.Sprintf("sha256:%x", sha256.Sum256(data)), BrowserDownloadURL: llamaReleasesURL + "/download/" + tag + "/" + name} +} + +func TestCheckLlamaCppUpdate_LinksAnAdoptedServerToTheStableBinaryRelease(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path != "/props" || req.Header.Get(engineIdentityProbeHeader) != "1" { + http.NotFound(w, req) + return + } + _, err := io.WriteString(w, `{"role":"router","build_info":"b99-abc123"}`) + assert.NoError(t, err) + })) + t.Cleanup(server.Close) + manifest := testEngineManifest(filepath.Join(t.TempDir(), "absent")) + manifest.Engine = "llamacpp" + platform := manifest.Platforms[hostKey()] + port, err := strconv.Atoi(strings.TrimPrefix(server.URL, "http://127.0.0.1:")) + require.NoError(t, err) + platform.Runtime.Port = port + platform.Runtime.Ready.HTTP = "http://127.0.0.1:{port}/props" + manifest.Platforms[hostKey()] = platform + e := newTestExecutor(t, manifest) + mockLlamaRelease(t, e, "b100", nil, nil) + + update, err := e.CheckEngineUpdate(t.Context(), "llamacpp") + + require.NoError(t, err) + wantURL := llamaReleasesURL + "/tag/b100" + assert.Equal(t, &EngineUpdateInfo{CurrentVersion: "b99", LatestVersion: "b100", InstallType: "external", ReleaseURL: wantURL, DownloadURL: wantURL}, update) +} + +func TestLlamaUpdateRelease_RequiresEveryCompatibleCUDAArchive(t *testing.T) { + pinURL := llamaReleasesURL + "/download/b99/" + pinned := &Install{ + Artifacts: []InstallArtifact{ + pinnedArtifact("server", pinURL+"llama-b99-bin-win-cuda-12.4-x64.zip", nil), + pinnedArtifact("cudart", pinURL+"cudart-llama-bin-win-cuda-12.4-x64.zip", nil), + }, + Run: []string{"unpack"}, + } + server := llamaTestAsset("b100", "llama-b100-bin-win-cuda-12.4-x64.zip", []byte("server")) + runtime := llamaTestAsset("b100", "cudart-llama-bin-win-cuda-12.4-x64.zip", []byte("cudart")) + t.Run("both matching artifacts", func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + mockLlamaRelease(t, e, "b100", []githubReleaseAsset{server, runtime}, nil) + + target, inst, err := e.llamaUpdateRelease(t.Context(), 98, pinned) + + require.NoError(t, err) + assert.Equal(t, llamaBuild(100), target) + require.Len(t, inst.Artifacts, 2) + assert.Equal(t, server.BrowserDownloadURL, inst.Artifacts[0].URL) + assert.Equal(t, strings.TrimPrefix(runtime.Digest, "sha256:"), inst.Artifacts[1].SHA256) + assert.Equal(t, pinURL+"cudart-llama-bin-win-cuda-12.4-x64.zip", pinned.Artifacts[1].URL) + }) + t.Run("runtime requires a different CUDA version", func(t *testing.T) { + e := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + newRuntime := llamaTestAsset("b100", "cudart-llama-bin-win-cuda-13.5-x64.zip", []byte("cudart")) + mockLlamaRelease(t, e, "b100", []githubReleaseAsset{server, newRuntime}, nil) + + target, inst, err := e.llamaUpdateRelease(t.Context(), 98, pinned) + + require.NoError(t, err) + assert.Equal(t, llamaBuild(99), target) + assert.Equal(t, pinned, inst) + }) +} + +func llamaManagedFixture(t *testing.T, stagedVersion string) (*Executor, string) { + t.Helper() + name := "llama-server" + filepath.Ext(fakeEngineBin) + var archive bytes.Buffer + writer := tar.NewWriter(&archive) + add := func(path string, data []byte) { + t.Helper() + require.NoError(t, writer.WriteHeader(&tar.Header{Name: path, Mode: 0755, Size: int64(len(data))})) + _, err := writer.Write(data) + require.NoError(t, err) + } + binary, err := os.ReadFile(fakeEngineBin) + require.NoError(t, err) + add(name, binary) + add(name+".version-output", []byte("version: 1.0.0 (build "+stagedVersion+", commit 12abcd)\n")) + require.NoError(t, writer.Close()) + asset := llamaTestAsset("b100", "llama-b100-bin-test.tar", archive.Bytes()) + pin := llamaTestAsset("b90", "llama-b90-bin-test.tar", nil) + + manifest := testEngineManifest(filepath.Join("{install_dir}", name)) + manifest.Engine = "llamacpp" + manifest.DisplayName = "llama.cpp" + platform := manifest.Platforms[hostKey()] + platform.ModelsDir = t.TempDir() + platform.Install = &Install{ + Fetch: &Fetch{URL: pin.BrowserDownloadURL, SHA256: strings.TrimPrefix(pin.Digest, "sha256:")}, + Run: []string{"tar", "-xf", "{download}", "-C", "{install_dir}"}, + } + manifest.Platforms[hostKey()] = platform + e := newTestExecutor(t, manifest) + bundled, err := json.Marshal(manifest) + require.NoError(t, err) + e.reg.bundledRaw["llamacpp"] = bundled + st, err := e.state("llamacpp") + require.NoError(t, err) + require.NoError(t, writeInstallMarker(st.installDir, "llamacpp")) + installed := filepath.Join(st.installDir, name) + copyFile(t, fakeEngineBin, installed) + require.NoError(t, os.WriteFile(installed+".version-output", []byte("version: 99 (349cd7)\r\nbuilt with cc for test\n"), 0600)) + mockLlamaRelease(t, e, "b100", []githubReleaseAsset{asset}, map[string][]byte{asset.BrowserDownloadURL: archive.Bytes()}) + return e, installed +} + +func TestUpdateLlamaCpp_UpdatesAStoppedEngineToTheAdvertisedBuild(t *testing.T) { + e, _ := llamaManagedFixture(t, "100") + st, err := e.state("llamacpp") + require.NoError(t, err) + model := filepath.Join(st.modelsDir, "saved.gguf") + require.NoError(t, os.WriteFile(model, []byte("weights"), 0600)) + update, err := e.CheckEngineUpdate(t.Context(), "llamacpp") + require.NoError(t, err) + require.NotNil(t, update) + assert.Equal(t, "managed", update.InstallType) + assert.Equal(t, "b100", update.LatestVersion) + + // Applying the advertised build still works if GitHub's API has since + // rate-limited the node. The archive is available on the download host. + downloads := e.client.Transport + e.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Hostname() == "api.github.com" { + return &http.Response{StatusCode: http.StatusForbidden, Header: http.Header{"Retry-After": {"60"}}, Body: http.NoBody}, nil + } + return downloads.RoundTrip(req) + }) + require.NoError(t, e.UpdateEngine(t.Context(), "llamacpp")) + + update, err = e.CheckEngineUpdate(t.Context(), "llamacpp") + require.NoError(t, err) + assert.Nil(t, update) + status, err := e.Status("llamacpp") + require.NoError(t, err) + assert.False(t, status.Running) + saved, err := os.ReadFile(model) + require.NoError(t, err) + assert.Equal(t, "weights", string(saved)) +} + +func TestUpdateLlamaCpp_RejectsAnArchiveReportingADifferentBuild(t *testing.T) { + e, binPath := llamaManagedFixture(t, "98") + err := e.UpdateEngine(t.Context(), "llamacpp") + require.ErrorContains(t, err, "reports build b98, expected b100") + + build, err := llamaBinaryBuild(t.Context(), binPath) + require.NoError(t, err) + assert.Equal(t, llamaBuild(99), build) +} + +func TestUpdateLlamaCpp_RestartsARunningEngineAtItsPreviousPort(t *testing.T) { + e, installed := llamaManagedFixture(t, "100") + t.Cleanup(e.StopAll) + require.NoError(t, e.Start(t.Context(), "llamacpp")) + before, err := e.Status("llamacpp") + require.NoError(t, err) + + require.NoError(t, e.UpdateEngine(t.Context(), "llamacpp")) + + after, err := e.Status("llamacpp") + require.NoError(t, err) + assert.True(t, after.Running) + assert.Equal(t, before.Port, after.Port) + build, err := llamaBinaryBuild(t.Context(), installed) + require.NoError(t, err) + assert.Equal(t, llamaBuild(100), build) +} + +func TestUpdateLlamaCpp_RefusesACacheInsideTheEngineDirectory(t *testing.T) { + e, binary := llamaManagedFixture(t, "100") + t.Setenv("LLAMA_CACHE", filepath.Join(filepath.Dir(binary), "cached-models")) + require.ErrorContains(t, e.UpdateEngine(t.Context(), "llamacpp"), "PAIR-managed") +} diff --git a/services/nvpair-engine-manager/lmstudio_app_version.go b/services/nvpair-engine-manager/lmstudio_app_version.go new file mode 100644 index 000000000..a90f77eac --- /dev/null +++ b/services/nvpair-engine-manager/lmstudio_app_version.go @@ -0,0 +1,117 @@ +// 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" + "os" + "path/filepath" + "strings" +) + +// lmStudioAppVersion reads the desktop application's version without opening a window. +func lmStudioAppVersion(root, runningVersion string) (string, error) { + version := runningVersion + if version == "" { + path, err := lmStudioInstallPath(root, "app-install-location.json") + if err != nil || path == "" { + return "", err + } + dir := filepath.Dir(path) + resources := filepath.Join(dir, "resources") + if filepath.Base(dir) == "MacOS" { + resources = filepath.Join(filepath.Dir(dir), "Resources") + } + var app struct { + Name string `json:"name"` + Version string `json:"version"` + } + if err := readLMStudioJSONFile(filepath.Join(resources, "app", "package.json"), &app, 1<<20); err != nil { + return "", fmt.Errorf("read installed LM Studio desktop version: %w", err) + } + if app.Name != "lm-studio" { + return "", errors.New("expected the installed LM Studio desktop package") + } + version = app.Version + } + version = strings.Replace(version, "+", "-", 1) + if !lmStudioVersionRE.MatchString(version) { + return "", errors.New("invalid LM Studio desktop version") + } + // After an update, migration history still describes the previous launch. + if runningVersion == "" || strings.Contains(version, "-") { + return version, nil + } + var history struct { + // LM Studio kept its desktop version at the top level before adding per-product records. + DesktopVersion string `json:"lastRecorderdAppVersion"` + DesktopBuild string `json:"lastRecordedAppBuildVersion"` + Targets []struct { + Target string `json:"target"` + Version string `json:"lastRecordedAppVersion"` + Build string `json:"lastRecordedAppBuildVersion"` + } `json:"targetHistories"` + } + // The CLI can omit the running build. Only use the desktop entry for this exact release. + if readLMStudioJSONFile(filepath.Join(root, ".internal", "historical-version-info.json"), &history, 1<<20) == nil { + for _, target := range history.Targets { + if target.Target == "lmstudio" { + history.DesktopVersion, history.DesktopBuild = target.Version, target.Build + break + } + } + full := history.DesktopVersion + "-" + history.DesktopBuild + if history.DesktopVersion == version && lmStudioVersionRE.MatchString(full) { + return full, nil + } + } + return version, nil +} + +// lmStudioInstallPath resolves either the desktop app or daemon marker published by LM Studio. +func lmStudioInstallPath(root, filename string) (string, error) { + var location struct { + Path string `json:"path"` + } + err := readLMStudioJSONFile(filepath.Join(root, ".internal", filename), &location, 8<<10) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("read %s: %w", filename, err) + } + if !filepath.IsAbs(location.Path) { + return "", fmt.Errorf("invalid executable path in %s", filename) + } + info, err := os.Stat(location.Path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + if !info.Mode().IsRegular() { + return "", fmt.Errorf("invalid executable in %s", filename) + } + return location.Path, nil +} + +func readLMStudioJSONFile(path string, result any, limit int64) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, limit+1)) + if err != nil { + return err + } + if int64(len(data)) > limit { + return fmt.Errorf("%s exceeds %d bytes", filepath.Base(path), limit) + } + return json.Unmarshal(data, result) +} diff --git a/services/nvpair-engine-manager/lmstudio_app_version_test.go b/services/nvpair-engine-manager/lmstudio_app_version_test.go new file mode 100644 index 000000000..b9bc1b56f --- /dev/null +++ b/services/nvpair-engine-manager/lmstudio_app_version_test.go @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLMStudioAppVersion_UsesBuildFromMatchingRunningDesktopRelease(t *testing.T) { + test := func(name, running, history, expected string) { + t.Helper() + t.Run(name, func(t *testing.T) { + root := t.TempDir() + internal := filepath.Join(root, ".internal") + require.NoError(t, os.MkdirAll(internal, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(internal, "historical-version-info.json"), []byte(history), 0o600)) + + version, err := lmStudioAppVersion(root, running) + require.NoError(t, err) + assert.Equal(t, expected, version) + }) + } + test("running build is authoritative", "0.4.28+2", "{}", "0.4.28-2") + test("desktop and daemon share a home", "0.4.27", `{"targetHistories":[ + {"target":"daemon","lastRecordedAppVersion":"0.4.27","lastRecordedAppBuildVersion":"8"}, + {"target":"lmstudio","lastRecordedAppVersion":"0.4.27","lastRecordedAppBuildVersion":"2"} + ]}`, "0.4.27-2") + test("earlier desktop format", "0.3.37", `{"lastRecorderdAppVersion":"0.3.37","lastRecordedAppBuildVersion":"1"}`, "0.3.37-1") + test("previous desktop release", "0.4.27", `{"targetHistories":[ + {"target":"lmstudio","lastRecordedAppVersion":"0.4.26","lastRecordedAppBuildVersion":"5"} + ]}`, "0.4.27") + test("daemon history only", "0.4.27", `{"targetHistories":[ + {"target":"daemon","lastRecordedAppVersion":"0.4.27","lastRecordedAppBuildVersion":"8"} + ]}`, "0.4.27") +} + +func TestLMStudioAppVersion_ReadsStoppedDesktopPackage(t *testing.T) { + test := func(name, executable, packagePath string) { + t.Helper() + t.Run(name, func(t *testing.T) { + root := t.TempDir() + exe := filepath.Join(root, executable) + require.NoError(t, os.MkdirAll(filepath.Dir(exe), 0o755)) + require.NoError(t, os.WriteFile(exe, nil, 0o755)) + internal := filepath.Join(root, ".internal") + require.NoError(t, os.MkdirAll(internal, 0o755)) + marker, err := json.Marshal(map[string]string{"path": exe}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(internal, "app-install-location.json"), marker, 0o600)) + manifest := filepath.Join(root, packagePath) + require.NoError(t, os.MkdirAll(filepath.Dir(manifest), 0o755)) + require.NoError(t, os.WriteFile(manifest, []byte(`{"name":"lm-studio","version":"0.4.28+2"}`), 0o600)) + // The user updated the desktop app without opening the new build yet. + require.NoError(t, os.WriteFile(filepath.Join(internal, "historical-version-info.json"), + []byte(`{"lastRecorderdAppVersion":"0.4.28","lastRecordedAppBuildVersion":"1"}`), 0o600)) + + version, err := lmStudioAppVersion(root, "") + require.NoError(t, err) + assert.Equal(t, "0.4.28-2", version) + }) + } + test("unpacked application", "desktop/lm-studio", "desktop/resources/app/package.json") + test("macOS application bundle", "LM Studio.app/Contents/MacOS/LM Studio", "LM Studio.app/Contents/Resources/app/package.json") +} + +func TestLMStudioAppVersion_IgnoresRemovedDesktopInstall(t *testing.T) { + root := t.TempDir() + internal := filepath.Join(root, ".internal") + require.NoError(t, os.MkdirAll(internal, 0o755)) + marker, err := json.Marshal(map[string]string{"path": filepath.Join(root, "uninstalled", "lm-studio")}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(internal, "app-install-location.json"), marker, 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(internal, "historical-version-info.json"), + []byte(`{"lastRecorderdAppVersion":"0.4.27","lastRecordedAppBuildVersion":"2"}`), 0o600)) + + version, err := lmStudioAppVersion(root, "") + require.NoError(t, err) + assert.Empty(t, version) +} diff --git a/services/nvpair-engine-manager/lmstudio_update.go b/services/nvpair-engine-manager/lmstudio_update.go new file mode 100644 index 000000000..134a6d17a --- /dev/null +++ b/services/nvpair-engine-manager/lmstudio_update.go @@ -0,0 +1,312 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "reflect" + "regexp" + "runtime" + "strings" + "time" +) + +const lmStudioDaemonGuide = "https://lmstudio.ai/docs/cli/daemon/daemon-update" + +// LM Studio publishes numeric builds separately from its three-part version. +var lmStudioVersionRE = regexp.MustCompile(`^[0-9]{1,9}\.[0-9]{1,9}\.[0-9]{1,9}(-[0-9]{1,9})?$`) +var lmStudioHostRE = regexp.MustCompile(`^(llmster|LM Studio|Bionic) v([^ ]+) is running \(PID: [0-9]+\)$`) + +type lmStudioTarget struct { + version string + daemon bool + path string // Versioned llmster executable selected by the vendor. + running bool // Host process, including when its HTTP server is off. +} + +func lmStudioHome(cli string) (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + f, err := os.Open(filepath.Join(home, ".lmstudio-home-pointer")) + if errors.Is(err, os.ErrNotExist) { + return filepath.Dir(filepath.Dir(cli)), nil + } + if err != nil { + return "", err + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, 4097)) + root := strings.TrimSpace(string(data)) + if err != nil || len(data) > 4096 || !filepath.IsAbs(root) { + return "", errors.New("invalid LM Studio home pointer") + } + return filepath.Clean(root), nil +} + +// Read the location used by "lms daemon up". Older version directories can +// remain installed, so picking the greatest directory can select the wrong copy. +func lmStudioDaemonInstall(root string) (lmStudioTarget, error) { + path, err := lmStudioInstallPath(root, "llmster-install-location.json") + if path == "" || err != nil { + return lmStudioTarget{}, err + } + version := filepath.Base(filepath.Dir(path)) + name := "llmster" + if runtime.GOOS == "windows" { + name += ".exe" + } + expected := filepath.Join(root, "llmster", version, name) + if !lmStudioVersionRE.MatchString(version) || path != expected { + return lmStudioTarget{}, errors.New("unrecognized llmster installation location") + } + return lmStudioTarget{version: version, daemon: true, path: expected}, nil +} + +// The human-readable status includes the host's product and version. Its JSON +// output omits the version, and "lms --version" reports the separate CLI. +func (e *Executor) lmStudioTarget(ctx context.Context, cli string) (lmStudioTarget, error) { + if cli == "" { + return lmStudioTarget{}, nil + } + ctx, cancel := context.WithTimeout(ctx, lmstudioHostStatusTimeout) + defer cancel() + output, err := e.runCommandOutput(ctx, []string{cli, "daemon", "status"}) + if err != nil { + return lmStudioTarget{}, fmt.Errorf("read LM Studio host: %w", err) + } + root, err := lmStudioHome(cli) + if err != nil { + return lmStudioTarget{}, err + } + status := strings.TrimSpace(output) + var liveVersion string + if status != "LM Studio is not running" { + match := lmStudioHostRE.FindStringSubmatch(status) + if match == nil { + return lmStudioTarget{}, errors.New("unrecognized LM Studio host status") + } + liveVersion = strings.Replace(match[2], "+", "-", 1) + if !lmStudioVersionRE.MatchString(liveVersion) { + return lmStudioTarget{}, errors.New("unrecognized LM Studio host version") + } + switch match[1] { + case "Bionic": + return lmStudioTarget{}, nil + case "LM Studio": + version, err := lmStudioAppVersion(root, liveVersion) + return lmStudioTarget{version: version, running: true}, err + } + } + target, err := lmStudioDaemonInstall(root) + if liveVersion != "" { + // A desktop and headless install can share lms. A running daemon + // whose version disagrees with the local pointer is external. + if err != nil || (liveVersion != target.version && liveVersion != strings.SplitN(target.version, "-", 2)[0]) { + return lmStudioTarget{version: liveVersion, daemon: true, running: true}, nil + } + target.running = true + } + if err != nil || target.daemon { + return target, err + } + // When stopped, lms starts the selected llmster first, then the app. + version, err := lmStudioAppVersion(root, "") + return lmStudioTarget{version: version}, err +} + +func lmStudioNewer(latest, current string) bool { + // A live host sometimes reports only its core version. A same-core build + // update can only be established when the installed build is known. + if !strings.Contains(current, "-") { + latest, _, _ = strings.Cut(latest, "-") + } + return compareVersionParts(versionParts(latest), versionParts(current)) > 0 +} + +func (e *Executor) latestLMStudio(ctx context.Context, target lmStudioTarget) (string, error) { + osName := runtime.GOOS + if osName == "windows" { + osName = "win32" + } + arch := runtime.GOARCH + if arch == "amd64" { + arch = "x86" + } + product := "" + if target.daemon { + product = "daemon/" + } + current, _, _ := strings.Cut(target.version, "-") + endpoint := fmt.Sprintf("https://versions-prod.lmstudio.ai/update/%s%s/%s/%s", product, osName, arch, current) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return "", err + } + var release struct { + OS, Arch, Version, Build string + } + if err := readEngineVersionJSON(e.client, req, &release); err != nil { + return "", fmt.Errorf("check LM Studio release: %w", err) + } + version := release.Version + "-" + release.Build + if release.OS != osName || release.Arch != arch || !lmStudioVersionRE.MatchString(version) { + return "", errors.New("unrecognized LM Studio release") + } + return version, nil +} + +func managedLMStudio(st *engineState, cli string, target lmStudioTarget, running, adopted bool) bool { + if !target.daemon || target.path == "" || adopted || target.running != running { + return false + } + st.mu.Lock() + bundled := st.plat.InstallDir == "" && st.bundledInstall != nil && reflect.DeepEqual(st.plat.Install, st.bundledInstall) + configuredCLI := expandPath(st.plat.Runtime.CLI) + st.mu.Unlock() + if !bundled || configuredCLI != cli { + return false + } + if _, err := readEngineInstallMarker(st.installDir, "lmstudio"); err != nil { + return false + } + home, err := os.UserHomeDir() + if err != nil { + return false + } + root := filepath.Join(home, ".lmstudio") + defaultCLI := filepath.Join(root, "bin", "lms"+filepath.Ext(target.path)) + defaultDaemon := filepath.Join(root, "llmster", target.version, filepath.Base(target.path)) + if cli != defaultCLI || target.path != defaultDaemon || os.Getenv("LMS_API_SERVER_INFO_PATH") != "" { + return false + } + // Upgrades execute a local binary; a redirected version directory must + // never confer the PAIR install marker on another installation. + resolved, err := filepath.EvalSymlinks(target.path) + resolvedRoot, rootErr := filepath.EvalSymlinks(root) + resolvedCLI, cliErr := filepath.EvalSymlinks(cli) + return err == nil && rootErr == nil && cliErr == nil && isManagedInstallPath(resolvedCLI, resolvedRoot) && + resolved == filepath.Join(resolvedRoot, "llmster", target.version, filepath.Base(target.path)) +} + +func (e *Executor) CheckLMStudioUpdate(ctx context.Context) (*EngineUpdateInfo, error) { + return e.checkInstalledEngineUpdate(ctx, "lmstudio", func(ctx context.Context, st *engineState, snap engineUpdateSnapshot) (*EngineUpdateInfo, error) { + target, err := e.lmStudioTarget(ctx, snap.binPath) + if err != nil || target.version == "" { + return nil, err + } + latest, err := e.latestLMStudio(ctx, target) + if err != nil || !lmStudioNewer(latest, target.version) { + return nil, err + } + info := &EngineUpdateInfo{ + CurrentVersion: target.version, + LatestVersion: latest, + InstallType: "external", + ReleaseURL: "https://lmstudio.ai/changelog/lmstudio", + DownloadURL: "https://lmstudio.ai/download#lm-studio-download-heading", + } + if target.daemon { + info.ReleaseURL, info.DownloadURL = lmStudioDaemonGuide, lmStudioDaemonGuide + } + if managedLMStudio(st, snap.binPath, target, snap.running, snap.adopted) { + info.InstallType, info.DownloadURL = "managed", "" + } + return info, nil + }) +} + +func (e *Executor) UpdateLMStudio(ctx context.Context) error { + return e.withEngineUpdate(ctx, "lmstudio", e.updateLMStudio) +} + +func (e *Executor) updateLMStudio(ctx context.Context, st *engineState) (result error) { + found, cli := detectPath(st) + target, err := e.lmStudioTarget(ctx, cli) + if err != nil { + return err + } + st.mu.Lock() + port := st.port + st.mu.Unlock() + presence := e.reconcilePresence(ctx, "lmstudio", st, found, port, false) + st.mu.Lock() + running, adopted := st.running, st.adopted + st.mu.Unlock() + if !found || (presence.Occupied && !running) || !managedLMStudio(st, cli, target, running, adopted) { + return errors.New("updates require a PAIR-managed llmster installation") + } + guard, err := lockEngineInstall(st.installDir) + if err != nil { + return err + } + defer guard.Close() + latest, err := e.latestLMStudio(ctx, target) + if err != nil || !lmStudioNewer(latest, target.version) { + return err + } + if runtime.GOOS == "linux" { + // Match the prerequisite check lms performs before delegating to llmster. + libs, err := e.runCommandOutput(ctx, []string{"ldconfig", "-p"}) + if err != nil || !strings.Contains(libs, "libatomic.so.1") { + return errors.New("llmster updates on Linux require ldconfig and libatomic.so.1") + } + } + if current, err := e.lmStudioTarget(ctx, cli); err != nil || current != target || !managedLMStudio(st, cli, current, running, adopted) { + return errors.New("the LM Studio installation changed during the update check") + } + if err := ctx.Err(); err != nil { + return err + } + if running { + if err := e.doStop(st, "lmstudio"); err != nil { + return err + } + defer func() { + if e.shuttingDown.Load() || e.stopWaiting(st) { + return + } + restartCtx := context.WithoutCancel(ctx) + current, err := e.lmStudioTarget(restartCtx, cli) + if err != nil || !managedLMStudio(st, cli, current, false, false) { + result = errors.Join(result, errors.New("cannot restart llmster because a stopped PAIR installation is no longer selected")) + return + } + result = errors.Join(result, e.doStart(restartCtx, st, "lmstudio", startOpts{RequireOwned: true})) + }() + stopped, err := e.lmStudioTarget(ctx, cli) + if err != nil || stopped.running || stopped.path != target.path { + return errors.New("llmster must be stopped before updating") + } + } + e.emitInstallProgress("lmstudio", "installing", 0) + // lms daemon update delegates to this native updater. Direct execution + // lets PAIR await the versioned, checksum-verified install on Windows + // without its interactive cmd.exe window. The only Windows prompt with + // the daemon stopped is an acknowledgement before the updater exits. + updateCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) + defer cancel() + cmd := exec.CommandContext(updateCtx, target.path, "upgrade", "--channel=stable") + cmd.Dir = filepath.Dir(target.path) + cmd.Stdin = strings.NewReader("\n") + configureSysProcAttr(cmd) + if err := cmd.Run(); err != nil { + return fmt.Errorf("update llmster: %w", err) + } + updated, err := lmStudioDaemonInstall(filepath.Dir(filepath.Dir(cli))) + if err != nil || updated.version == "" || compareVersionParts(versionParts(updated.version), versionParts(latest)) < 0 { + return fmt.Errorf("llmster did not install version %s", latest) + } + return nil +} diff --git a/services/nvpair-engine-manager/lmstudio_update_test.go b/services/nvpair-engine-manager/lmstudio_update_test.go new file mode 100644 index 000000000..23c071b97 --- /dev/null +++ b/services/nvpair-engine-manager/lmstudio_update_test.go @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func lmStudioUpdateFixture(t *testing.T, hostStatus string) (*Executor, *engineState, string) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("LMS_API_SERVER_INFO_PATH", "") + t.Setenv("PAIR_TEST_LMS_HOST", hostStatus) + t.Setenv("PAIR_TEST_LMS_STOP", filepath.Join(home, "last-server-command.json")) + if runtime.GOOS == "linux" { + libDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(libDir, "ldconfig"), []byte("#!/bin/sh\necho libatomic.so.1\n"), 0o755)) + t.Setenv("PATH", libDir+string(os.PathListSeparator)+os.Getenv("PATH")) + } + root := filepath.Join(home, ".lmstudio") + require.NoError(t, os.MkdirAll(filepath.Join(root, "bin"), 0o755)) + copyFile(t, fakeEngineBin, filepath.Join(root, "bin", "lms"+exeExt())) + require.NoError(t, os.MkdirAll(filepath.Join(root, ".internal"), 0o755)) + pointer := filepath.Join(root, ".internal", "llmster-install-location.json") + registerLMStudioDaemon(t, root, "0.0.17-4", pointer) + + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + ex := NewExecutor(reg, NewReporter(nil), func(string, any) {}, t.TempDir()) + st, err := ex.state("lmstudio") + require.NoError(t, err) + st.plat.Runtime.Ready = nil + st.plat.Runtime.Health = nil + st.port = 0 + return ex, st, pointer +} + +func registerLMStudioDaemon(t *testing.T, root, version, pointer string) { + t.Helper() + dir := filepath.Join(root, "llmster", version) + require.NoError(t, os.MkdirAll(dir, 0o755)) + binary := filepath.Join(dir, "llmster"+exeExt()) + copyFile(t, fakeEngineBin, binary) + data, err := json.Marshal(map[string]string{"path": binary}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(pointer, data, 0o600)) +} + +func mockLMStudioRelease(t *testing.T, ex *Executor, product, current, latest, build string) { + t.Helper() + releaseOS := map[string]string{"windows": "win32", "linux": "linux", "darwin": "darwin"}[runtime.GOOS] + releaseArch := map[string]string{"amd64": "x86", "arm64": "arm64"}[runtime.GOARCH] + endpoint := "https://versions-prod.lmstudio.ai/update/" + product + releaseOS + "/" + releaseArch + "/" + current + body, err := json.Marshal(map[string]string{"os": releaseOS, "arch": releaseArch, "version": latest, "build": build}) + require.NoError(t, err) + ex.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.String() != endpoint { + return nil, fmt.Errorf("unexpected release feed %s", req.URL) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(string(body)))}, nil + }) +} + +func TestCheckLMStudioUpdate_UsesTheActiveHostAndItsOwnStableFeed(t *testing.T) { + check := func(name, status, product, current, core, next, build, action, link string) { + t.Run(name, func(t *testing.T) { + ex, st, _ := lmStudioUpdateFixture(t, status) + require.NoError(t, writeInstallMarker(st.installDir, "lmstudio")) + mockLMStudioRelease(t, ex, product, core, next, build) + + offer, err := ex.CheckLMStudioUpdate(t.Context()) + + require.NoError(t, err) + require.NotNil(t, offer) + assert.Equal(t, current, offer.CurrentVersion) + assert.Equal(t, next+"-"+build, offer.LatestVersion) + assert.Equal(t, action, offer.InstallType) + assert.Equal(t, link, offer.DownloadURL) + }) + } + check("managed stopped daemon has a newer build", "LM Studio is not running", "daemon/", "0.0.17-4", "0.0.17", "0.0.17", "10", "managed", "") + check("daemon running independently of PAIR", "llmster v0.0.17+4 is running (PID: 68048)", "daemon/", "0.0.17-4", "0.0.17", "0.1.1", "2", "external", lmStudioDaemonGuide) + check("desktop app takes precedence over installed daemon", "LM Studio v0.4.25+2 is running (PID: 1234)", "", "0.4.25-2", "0.4.25", "0.4.28", "2", "external", "https://lmstudio.ai/download#lm-studio-download-heading") +} + +func TestCheckLMStudioUpdate_ReportsNoUpdateForCurrentBuild(t *testing.T) { + ex, _, _ := lmStudioUpdateFixture(t, "LM Studio is not running") + mockLMStudioRelease(t, ex, "daemon/", "0.0.17", "0.0.17", "4") + + offer, err := ex.CheckLMStudioUpdate(t.Context()) + + require.NoError(t, err) + assert.Nil(t, offer) +} + +func TestUpdateLMStudio_LeavesAnExternalDaemonWithItsOwner(t *testing.T) { + ex, _, _ := lmStudioUpdateFixture(t, "LM Studio is not running") + mockLMStudioRelease(t, ex, "daemon/", "0.0.17", "0.1.1", "2") + + offer, err := ex.CheckLMStudioUpdate(t.Context()) + + require.NoError(t, err) + require.NotNil(t, offer) + assert.Equal(t, "external", offer.InstallType) + assert.Equal(t, lmStudioDaemonGuide, offer.DownloadURL) + require.ErrorContains(t, ex.UpdateLMStudio(t.Context()), "PAIR-managed") +} + +func TestCheckLMStudioUpdate_UsesTheVersionInTheRelocatedVendorHome(t *testing.T) { + ex, st, _ := lmStudioUpdateFixture(t, "LM Studio is not running") + require.NoError(t, writeInstallMarker(st.installDir, "lmstudio")) + relocated := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(relocated, ".internal"), 0o755)) + registerLMStudioDaemon(t, relocated, "0.0.27-1", filepath.Join(relocated, ".internal", "llmster-install-location.json")) + home, err := os.UserHomeDir() + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(home, ".lmstudio-home-pointer"), []byte(relocated), 0o600)) + mockLMStudioRelease(t, ex, "daemon/", "0.0.27", "0.1.1", "2") + + offer, err := ex.CheckLMStudioUpdate(t.Context()) + + require.NoError(t, err) + require.NotNil(t, offer) + assert.Equal(t, "0.0.27-1", offer.CurrentVersion) + assert.Equal(t, "external", offer.InstallType) +} + +func TestUpdateLMStudio_VerifiesTheVendorInstalledTheReleaseAndPreservesStoppedState(t *testing.T) { + ex, st, pointer := lmStudioUpdateFixture(t, "LM Studio is not running") + require.NoError(t, writeInstallMarker(st.installDir, "lmstudio")) + root := filepath.Dir(filepath.Dir(pointer)) + registerLMStudioDaemon(t, root, "0.1.1-2", pointer+".next") + require.NoError(t, os.MkdirAll(st.modelsDir, 0o755)) + model := filepath.Join(st.modelsDir, "downloaded.gguf") + require.NoError(t, os.WriteFile(model, []byte("downloaded model"), 0o600)) + t.Setenv("PAIR_TEST_LLMSTER_POINTER", pointer) + mockLMStudioRelease(t, ex, "daemon/", "0.0.17", "0.1.1", "2") + require.NoError(t, ex.UpdateLMStudio(t.Context())) + + updated, err := lmStudioDaemonInstall(root) + require.NoError(t, err) + assert.Equal(t, "0.1.1-2", updated.version) + assert.FileExists(t, model) + assert.False(t, st.running) +} + +func TestUpdateLMStudio_RestartsTheRunningServerWhenTheVendorSkippedTheUpdate(t *testing.T) { + ex, st, _ := lmStudioUpdateFixture(t, "llmster v0.0.17+4 is running (PID: 68048)") + require.NoError(t, writeInstallMarker(st.installDir, "lmstudio")) + st.installed, st.running, st.healthy = true, true, true + st.port = 1235 + t.Setenv("PAIR_TEST_LMS_STATUS", `{"status":"running","isDaemon":true}`) + t.Setenv("PAIR_TEST_LLMSTER_POINTER", "") // The vendor can return success without promoting a new release. + mockLMStudioRelease(t, ex, "daemon/", "0.0.17", "0.1.1", "2") + + require.ErrorContains(t, ex.UpdateLMStudio(t.Context()), "did not install version 0.1.1-2") + + assert.True(t, st.running) + data, err := os.ReadFile(os.Getenv("PAIR_TEST_LMS_STOP")) + require.NoError(t, err) + var argv []string + require.NoError(t, json.Unmarshal(data, &argv)) + assert.Equal(t, []string{"server", "start", "--port", "1235", "--bind", "127.0.0.1"}, argv) +} 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/manifests/llamacpp.json b/services/nvpair-engine-manager/manifests/llamacpp.json index f89a749b9..fdc0f757e 100644 --- a/services/nvpair-engine-manager/manifests/llamacpp.json +++ b/services/nvpair-engine-manager/manifests/llamacpp.json @@ -31,7 +31,7 @@ { "name": "server", "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11146/llama-b11146-bin-win-cuda-12.4-x64.zip", "sha256": "3c806a6ceccc3dae1c743ceb1a1fb2cce5b76f40bfbd4c6b7b8afb6ef45a5807" }, { "name": "cudart", "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11146/cudart-llama-bin-win-cuda-12.4-x64.zip", "sha256": "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6" } ], - "run": ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "& { $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_SERVER -DestinationPath $env:NVPAIR_INSTALL_DIR -Force; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_CUDART -DestinationPath $env:NVPAIR_INSTALL_DIR -Force }"] + "run": ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "& { $ErrorActionPreference = 'Stop'; $env:PSModulePath = $PSHOME + '\\Modules'; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_SERVER -DestinationPath $env:NVPAIR_INSTALL_DIR -Force; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_CUDART -DestinationPath $env:NVPAIR_INSTALL_DIR -Force }"] }, "runtime": { "bin": "{install_dir}\\llama-server.exe" } }, @@ -42,7 +42,7 @@ { "name": "server", "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11146/llama-b11146-bin-win-cuda-13.4-arm64.zip", "sha256": "a4060b5031a0e862e225d4a7c4aa403852ebedf598906ef8258a86cb77de8351" }, { "name": "cudart", "url": "https://github.com/ggml-org/llama.cpp/releases/download/b11146/cudart-llama-bin-win-cuda-13.4-arm64.zip", "sha256": "642dcde8805b3e3165ca710a5443b3b4044b27d96bd3ee3132473988c9bcb774" } ], - "run": ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "& { $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_SERVER -DestinationPath $env:NVPAIR_INSTALL_DIR -Force; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_CUDART -DestinationPath $env:NVPAIR_INSTALL_DIR -Force }"] + "run": ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "& { $ErrorActionPreference = 'Stop'; $env:PSModulePath = $PSHOME + '\\Modules'; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_SERVER -DestinationPath $env:NVPAIR_INSTALL_DIR -Force; Expand-Archive -LiteralPath $env:NVPAIR_INSTALL_DOWNLOAD_CUDART -DestinationPath $env:NVPAIR_INSTALL_DIR -Force }"] }, "runtime": { "bin": "{install_dir}\\llama-server.exe" } }, diff --git a/services/nvpair-engine-manager/manifests/vllm.json b/services/nvpair-engine-manager/manifests/vllm.json index 0f3a95eae..9adafbb4f 100644 --- a/services/nvpair-engine-manager/manifests/vllm.json +++ b/services/nvpair-engine-manager/manifests/vllm.json @@ -9,8 +9,8 @@ "mode": "user", "run": [ "sh", "-c", - "set -eu; command -v nvidia-smi >/dev/null 2>&1 || { echo 'vLLM needs an NVIDIA GPU and driver (nvidia-smi not found)' >&2; exit 1; }; cuda_major=$(nvidia-smi -q 2>/dev/null | awk -F' *: *' '/^CUDA (UMD )?Version/ {split($2, v, \".\"); print v[1]; exit}'); [ \"${cuda_major:-0}\" -ge 13 ] 2>/dev/null || { echo \"vLLM needs an NVIDIA driver that supports CUDA 13 or newer (found: ${cuda_major:-none}). Update your NVIDIA driver and try again.\" >&2; exit 1; }; free_kb=$(df -Pk \"$2\" | awk 'NR==2 {print $4}'); [ \"${free_kb:-0}\" -ge 26214400 ] || { echo 'vLLM needs at least 25 GB of free disk space for the engine; model downloads need additional space' >&2; exit 1; }; mkdir -p \"$2/uv\"; tar -xzf \"$1\" -C \"$2/uv\" --strip-components=1; export UV_PYTHON_INSTALL_DIR=\"$2/python\" UV_PYTHON_PREFERENCE=only-managed; \"$2/uv/uv\" venv --no-cache --python 3.12 \"$2/venv\"; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"vllm==0.34.0\"", - "vllm-install", "{download}", "{install_dir}" + "set -eu; command -v nvidia-smi >/dev/null 2>&1 || { echo 'vLLM needs an NVIDIA GPU and driver (nvidia-smi not found)' >&2; exit 1; }; cuda_major=$(nvidia-smi -q 2>/dev/null | awk -F' *: *' '/^CUDA (UMD )?Version/ {split($2, v, \".\"); print v[1]; exit}'); [ \"${cuda_major:-0}\" -ge 13 ] 2>/dev/null || { echo \"vLLM needs an NVIDIA driver that supports CUDA 13 or newer (found: ${cuda_major:-none}). Update your NVIDIA driver and try again.\" >&2; exit 1; }; free_kb=$(df -Pk \"$2\" | awk 'NR==2 {print $4}'); [ \"${free_kb:-0}\" -ge 26214400 ] || { echo 'vLLM needs at least 25 GB of free disk space for the engine; model downloads need additional space' >&2; exit 1; }; mkdir -p \"$2/uv\"; tar -xzf \"$1\" -C \"$2/uv\" --strip-components=1; export UV_PYTHON_INSTALL_DIR=\"$2/python\" UV_PYTHON_PREFERENCE=only-managed; \"$2/uv/uv\" venv --no-cache --python 3.12 \"$2/venv\"; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"vllm==$3\"", + "vllm-install", "{download}", "{install_dir}", "0.34.0" ] }, "install_dir": "~/.nvpair/engine-bin/vllm", @@ -74,8 +74,8 @@ }, "run": [ "sh", "-c", - "set -eu; [ \"$(uname -m)\" = arm64 ] || { echo 'vLLM on macOS needs an Apple Silicon Mac (arm64)' >&2; exit 1; }; macos_major=$(sw_vers -productVersion | cut -d. -f1); [ \"${macos_major:-0}\" -ge 15 ] 2>/dev/null || { echo \"vLLM needs macOS 15 or newer (found: ${macos_major:-unknown}). Update macOS and try again.\" >&2; exit 1; }; free_kb=$(df -Pk \"$2\" | awk 'NR==2 {print $4}'); [ \"${free_kb:-0}\" -ge 20971520 ] || { echo 'vLLM needs at least 20 GB of free disk space for the engine; model downloads need additional space' >&2; exit 1; }; mkdir -p \"$2/uv\" \"$2/wheels\"; tar -xzf \"$1\" -C \"$2/uv\" --strip-components=1; export UV_PYTHON_INSTALL_DIR=\"$2/python\" UV_PYTHON_PREFERENCE=only-managed; \"$2/uv/uv\" venv --no-cache --python 3.12 \"$2/venv\"; core_whl=\"$2/wheels/vllm-0.32.0+cpu-cp38-abi3-macosx_11_0_arm64.whl\"; metal_whl=\"$2/wheels/vllm_metal-0.32.0-cp312-cp312-macosx_15_0_arm64.whl\"; curl -fsSL --retry 3 -o \"${core_whl:-}\" 'https://github.com/vllm-project/vllm/releases/download/v0.32.0/vllm-0.32.0%2Bcpu-cp38-abi3-macosx_11_0_arm64.whl'; echo \"c28cf0fede58f02c4886d2794217ec3c7e4bbd22dfeb16b4b32586a8f230bb75 ${core_whl:-}\" | shasum -a 256 -c -; curl -fsSL --retry 3 -o \"${metal_whl:-}\" 'https://github.com/vllm-project/vllm-metal/releases/download/v0.32.0/vllm_metal-0.32.0-cp312-cp312-macosx_15_0_arm64.whl'; echo \"458d34157eb02a6bfb0e293c70485df18f72b7eb1d1ce8f1eefea95ba47ab63c ${metal_whl:-}\" | shasum -a 256 -c -; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"${core_whl:-}\" \"mistral_common==1.12.0\"; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"${metal_whl:-}\"; rm -rf \"$2/wheels\"", - "vllm-install", "{download}", "{install_dir}" + "set -eu; [ \"$(uname -m)\" = arm64 ] || { echo 'vLLM on macOS needs an Apple Silicon Mac (arm64)' >&2; exit 1; }; macos_major=$(sw_vers -productVersion | cut -d. -f1); [ \"${macos_major:-0}\" -ge 15 ] 2>/dev/null || { echo \"vLLM needs macOS 15 or newer (found: ${macos_major:-unknown}). Update macOS and try again.\" >&2; exit 1; }; free_kb=$(df -Pk \"$2\" | awk 'NR==2 {print $4}'); [ \"${free_kb:-0}\" -ge 20971520 ] || { echo 'vLLM needs at least 20 GB of free disk space for the engine; model downloads need additional space' >&2; exit 1; }; mkdir -p \"$2/uv\" \"$2/wheels\"; tar -xzf \"$1\" -C \"$2/uv\" --strip-components=1; export UV_PYTHON_INSTALL_DIR=\"$2/python\" UV_PYTHON_PREFERENCE=only-managed; \"$2/uv/uv\" venv --no-cache --python 3.12 \"$2/venv\"; core_whl=\"$2/wheels/vllm-$3+cpu-cp38-abi3-macosx_11_0_arm64.whl\"; metal_whl=\"$2/wheels/vllm_metal-$3-cp312-cp312-macosx_15_0_arm64.whl\"; curl -fsSL --retry 3 -o \"${core_whl:-}\" \"https://github.com/vllm-project/vllm/releases/download/v$3/vllm-$3%2Bcpu-cp38-abi3-macosx_11_0_arm64.whl\"; echo \"c28cf0fede58f02c4886d2794217ec3c7e4bbd22dfeb16b4b32586a8f230bb75 ${core_whl:-}\" | shasum -a 256 -c -; curl -fsSL --retry 3 -o \"${metal_whl:-}\" \"https://github.com/vllm-project/vllm-metal/releases/download/v$3/vllm_metal-$3-cp312-cp312-macosx_15_0_arm64.whl\"; echo \"458d34157eb02a6bfb0e293c70485df18f72b7eb1d1ce8f1eefea95ba47ab63c ${metal_whl:-}\" | shasum -a 256 -c -; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"${core_whl:-}\" \"mistral_common==1.12.0\"; \"$2/uv/uv\" pip install --no-cache --python \"$2/venv/bin/python\" \"${metal_whl:-}\"; rm -rf \"$2/wheels\"", + "vllm-install", "{download}", "{install_dir}", "0.32.0" ] } } 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/registry_test.go b/services/nvpair-engine-manager/registry_test.go index 09a00be0b..c64270c73 100644 --- a/services/nvpair-engine-manager/registry_test.go +++ b/services/nvpair-engine-manager/registry_test.go @@ -847,7 +847,7 @@ func TestBundledVLLMManifest_PinsTheInstallAndSizesTheLaunchOnEachPlatform(t *te } test("linux/amd64", "vllm==") test("linux/arm64", "vllm==") - test("darwin/arm64", "vllm-0.32.0") + test("darwin/arm64", "vllm-$3+cpu") } func TestBundledVLLMManifest_DeclaresTheModelActionsTheStackReliesOn(t *testing.T) { 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..d3a7e834f 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -147,6 +147,23 @@ 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" { + if output, err := os.ReadFile(os.Args[0] + ".version-output"); err == nil { + fmt.Fprint(os.Stderr, string(output)) + return + } + 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"} { @@ -271,6 +288,14 @@ func main() { time.Sleep(time.Minute) os.Exit(2) case "daemon", "server": + if strings.Join(os.Args[1:], " ") == "daemon status" { + if data, err := os.ReadFile(os.Getenv("PAIR_TEST_LMS_STOP")); err == nil && string(data) == `["daemon","down"]` { + fmt.Println("LM Studio is not running") + return + } + fmt.Println(os.Getenv("PAIR_TEST_LMS_HOST")) + return + } if strings.Join(os.Args[1:], " ") == "daemon status --json" { if os.Getenv("PAIR_TEST_LMS_STATUS") == "command-error" { fmt.Fprintln(os.Stderr, "host status unavailable") @@ -284,6 +309,19 @@ func main() { os.Exit(1) } return + case "upgrade": + // A staged llmster registers its new executable and waits for Enter on Windows. + key, err := bufio.NewReader(os.Stdin).ReadByte() + if err != nil || key != '\n' || strings.Join(os.Args[1:], " ") != "upgrade --channel=stable" { + os.Exit(1) + } + if pointer := os.Getenv("PAIR_TEST_LLMSTER_POINTER"); pointer != "" { + data, err := os.ReadFile(pointer + ".next") + if err != nil || os.WriteFile(pointer, data, 0o600) != nil { + os.Exit(1) + } + } + return case "-I": // stand in for the memory probe's Python -I -c invocation // Distinct readings in the service and engine environments let a test // observe which environment the probe actually received. 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-engine-manager/vllm_update.go b/services/nvpair-engine-manager/vllm_update.go new file mode 100644 index 000000000..028f667eb --- /dev/null +++ b/services/nvpair-engine-manager/vllm_update.go @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "runtime" + "strings" + + "nvpair-shared/engines" +) + +func managedVLLMBinary(st *engineState, bin string) bool { + if !managedUpdateBinary(st, bin) { + return false + } + configured, err := launchForState(st, 0, false) + if err != nil { + return false + } + protected := func(args []string, env hfEnv) bool { + stores := []string{env.home(), env.hubCache(), hfLaunchHub(args, env)} + if model, ok := launchFlagValue(args, "--model"); ok && filepath.IsAbs(model) { + stores = append(stores, model) + } + return modelStoresOutsideInstall(st, stores...) + } + if !protected(configured.Args, engineHFEnv(st)) { + return false + } + st.mu.Lock() + proc := st.proc + st.mu.Unlock() + if proc == nil { + return true + } + launched := hfEnv{} + for _, kv := range proc.cmd.Env { + key, value, ok := strings.Cut(kv, "=") + if ok { + launched[key] = value + } + } + return protected(proc.cmd.Args, launched) +} + +func (e *Executor) UpdateVLLM(ctx context.Context) error { + return e.withEngineUpdate(ctx, engines.NameVLLM, e.updateVLLM) +} + +func (e *Executor) updateVLLM(ctx context.Context, st *engineState) error { + bin, _, err := e.managedUpdateTarget(ctx, st, managedVLLMBinary) + if err != nil { + return err + } + guard, err := lockEngineInstall(st.installDir) + if err != nil { + return err + } + defer guard.Close() + inst := st.bundledInstall + target, err := vllmRecipeVersion(inst) + if err != nil { + return err + } + metal := runtime.GOOS == "darwin" + installed, err := installedVLLMVersions(ctx, bin, metal) + if err != nil { + return err + } + old, err := installed.olderPackage(target, metal) + if err != nil || old == "" { + return err + } + // Fetch and verify the pinned bootstrap before interrupting inference. + archive, err := e.download(ctx, engines.NameVLLM, inst.Fetch) + if err != nil { + return err + } + defer os.Remove(archive) + active, running, err := e.managedUpdateTarget(ctx, st, managedVLLMBinary) + if err != nil { + return err + } + if bin != active { + return errors.New("the detected vLLM installation changed during the update") + } + if err := ctx.Err(); err != nil { + return err + } + if running { + if err := e.doStop(st, engines.NameVLLM); err != nil { + return err + } + } + restart := func(ctx context.Context) error { + if !running || e.shuttingDown.Load() || e.stopWaiting(st) { + return nil + } + return e.doStart(ctx, st, engines.NameVLLM, startOpts{RequireOwned: true}) + } + err = rebuildVLLMInstall(st.installDir, func() error { + e.emitInstallProgress(engines.NameVLLM, "installing", 0) + if err := e.runInstallCommand(ctx, inst, map[string]string{"install_dir": st.installDir, "download": archive}, guard); err != nil { + return err + } + versions, err := installedVLLMVersions(ctx, bin, metal) + if err != nil { + return err + } + // +cpu and +cuNNN identify platform wheel builds. + core, _, _ := strings.Cut(versions.Core, "+") + if core != target || metal && versions.Metal != target { + return fmt.Errorf("installed vLLM does not match the pinned release %s", target) + } + return ctx.Err() + }, func() error { return restart(ctx) }) + if err != nil { + // An unconfirmed rollback must never launch a partially built environment. + if original, probeErr := installedVLLMVersions(context.WithoutCancel(ctx), bin, metal); probeErr == nil && original == installed { + return errors.Join(err, restart(context.WithoutCancel(ctx))) + } + } + return err +} + +const vllmPendingMarker = ".nvpair-vllm-update-in-progress" + +// Python environments have absolute interpreter paths and console scripts. +// Build at the final path, keeping the entire original tree for rollback. +func rebuildVLLMInstall(dir string, build, start func() error) error { + if !filepath.IsAbs(dir) || !isEngineUpdateBackup(dir, engines.NameVLLM) { + return errors.New("cannot rebuild an unowned vLLM installation") + } + marker, err := readEngineInstallMarker(dir, engines.NameVLLM) + if err != nil { + return err + } + backup := dir + ".update-backup" + if err := discardEngineUpdateBackup(dir, engines.NameVLLM); err != nil { + return err + } + if _, err := os.Lstat(backup); !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("vLLM update backup location %s is occupied", backup) + } + prepared, err := os.MkdirTemp(filepath.Dir(dir), ".vllm-update-*") + if err != nil { + return err + } + defer os.RemoveAll(prepared) + if err := os.WriteFile(filepath.Join(prepared, vllmPendingMarker), marker, 0o600); err != nil { + return err + } + if err := renameEngineDirectory(dir, backup); err != nil { + return err + } + if err := renameEngineDirectory(prepared, dir); err != nil { + return errors.Join(err, renameEngineDirectory(backup, dir)) + } + err = build() + if err == nil { + // Only a verified complete install can lose its pending marker. + err = os.Rename(filepath.Join(dir, vllmPendingMarker), installMarkerPath(dir)) + } + if err == nil { + err = start() + } + if err != nil { + if moveErr := renameEngineDirectory(dir, prepared); moveErr != nil { + return errors.Join(err, fmt.Errorf("move failed vLLM aside; previous copy at %s: %w", backup, moveErr)) + } + return errors.Join(err, renameEngineDirectory(backup, dir)) + } + // Rename away from the recovery path before deleting the obsolete copy. + if err := renameEngineDirectory(backup, prepared); err != nil { + slog.Warn("could not retire previous vLLM installation", "err", err) + } + return nil +} + +func recoverVLLMUpdate(dir string) error { + backup := dir + ".update-backup" + if !filepath.IsAbs(dir) { + return nil + } + if _, err := os.Lstat(dir + ".update-lock"); errors.Is(err, os.ErrNotExist) && !isEngineUpdateBackup(backup, engines.NameVLLM) { + return nil + } + guard, err := lockEngineInstall(dir) + if err != nil { + return err + } + defer guard.Close() + if !isEngineUpdateBackup(backup, engines.NameVLLM) { + return nil + } + fi, err := os.Lstat(dir) + if errors.Is(err, os.ErrNotExist) { + return renameEngineDirectory(backup, dir) + } + if err != nil || !fi.IsDir() { + return err + } + pending := filepath.Join(dir, vllmPendingMarker) + fi, err = os.Lstat(pending) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil || !fi.Mode().IsRegular() || fi.Size() > 4096 { + return errors.New("unrecognized vLLM update recovery marker") + } + oldMarker, err := readEngineInstallMarker(backup, engines.NameVLLM) + if err != nil { + return err + } + candidate, err := os.ReadFile(pending) + if err != nil || !bytes.Equal(candidate, oldMarker) { + return errors.New("vLLM update recovery marker does not match its backup") + } + // Park the recognized partial tree before restoring the working one, so + // another interruption can still recover by observing the missing root. + park, err := os.MkdirTemp(filepath.Dir(dir), ".vllm-interrupted-*") + if err != nil { + return err + } + defer os.RemoveAll(park) + if err := renameEngineDirectory(dir, filepath.Join(park, "partial")); err != nil { + return err + } + return renameEngineDirectory(backup, dir) +} diff --git a/services/nvpair-engine-manager/vllm_update_test.go b/services/nvpair-engine-manager/vllm_update_test.go new file mode 100644 index 000000000..8aa4c92bc --- /dev/null +++ b/services/nvpair-engine-manager/vllm_update_test.go @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "nvpair-shared/pythontest" +) + +func TestVLLMVersions_ComparePlatformPackagesWithoutOfferingDowngrades(t *testing.T) { + check := func(name string, installed vllmVersions, target string, metal bool, expected string) { + t.Run(name, func(t *testing.T) { + older, err := installed.olderPackage(target, metal) + require.NoError(t, err) + assert.Equal(t, expected, older) + }) + } + check("release candidate", vllmVersions{Core: "0.34.0rc2"}, "0.34.0", false, "0.34.0rc2") + check("CPU wheel local version label", vllmVersions{Core: "0.32.0+cpu", Metal: "0.32.0"}, "0.32.0", true, "") + check("older Metal plugin", vllmVersions{Core: "0.32.0+cpu", Metal: "0.31.1"}, "0.32.0", true, "0.31.1") + check("newer plugin with an older core", vllmVersions{Core: "0.31.0+cpu", Metal: "0.33.0"}, "0.32.0", true, "") + check("Python post-release", vllmVersions{Core: "0.10.0.post1"}, "0.10.0", false, "") +} + +func TestCheckVLLMRelease_OffersAnExternalUpdateOnlyForAnIdentifiedServer(t *testing.T) { + ex := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + ex.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + var body string + switch req.URL.String() { + case "http://127.0.0.1:8001/version": + assert.Equal(t, "1", req.Header.Get(engineIdentityProbeHeader)) + body = `{"version":"0.30.0"}` + case "https://api.github.com/repos/vllm-project/vllm/releases/latest": + body = `{"tag_name":"v0.35.0"}` + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body))}, nil + }) + + offer, err := ex.checkVLLMRelease(t.Context(), nil, engineUpdateSnapshot{running: true, adopted: true, port: 8001}) + + require.NoError(t, err) + if runtime.GOOS == "darwin" { + assert.Nil(t, offer, "the core endpoint cannot identify a Metal release") + return + } + assert.Equal(t, &EngineUpdateInfo{ + CurrentVersion: "0.30.0", LatestVersion: "0.35.0", InstallType: "external", + ReleaseURL: "https://github.com/vllm-project/vllm/releases/tag/v0.35.0", + DownloadURL: "https://docs.vllm.ai/en/latest/getting_started/installation/gpu/", + }, offer) +} + +func TestUpdateVLLM_RebuildsAtTheCanonicalPathAndPreservesModels(t *testing.T) { + // Create package metadata in a real, empty venv. The bundled fake server + // stands in for the vllm executable; no vLLM wheel or GPU is needed. + python := pythontest.Python3(t) + const build = `import os, pathlib, shutil, sys, venv +server, root, version = sys.argv[1:] +env = pathlib.Path(root) / "venv" +venv.EnvBuilder(with_pip=False, symlinks=os.name != "nt").create(env) +scripts = env / ("Scripts" if os.name == "nt" else "bin") +shutil.copy2(server, scripts / pathlib.Path(server).name) +site = env / ("Lib" if os.name == "nt" else "lib/python%d.%d" % sys.version_info[:2]) / "site-packages" +for package in ["vllm", "vllm-metal"]: + dist = site / (package.replace("-", "_") + "-" + version + ".dist-info") + dist.mkdir() + (dist / "METADATA").write_text("Metadata-Version: 2.1\nName: " + package + "\nVersion: " + version + "\n") +(env / "built-at").write_text(str(env))` + scripts := "bin" + if runtime.GOOS == "windows" { + scripts = "Scripts" + } + engine := testEngineManifest(filepath.Join("{install_dir}", "venv", scripts, filepath.Base(fakeEngineBin))) + engine.Engine = "vllm" + engine.DisplayName = "vLLM" + key := runtime.GOOS + "/" + runtime.GOARCH + platform := engine.Platforms[key] + platform.ModelsDir = t.TempDir() + t.Setenv("HF_HOME", platform.ModelsDir) + platform.Install = &Install{ + Fetch: &Fetch{URL: "https://example.test/uv", SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("test bootstrap")))}, + Run: []string{python, "-I", "-c", build, fakeEngineBin, "{install_dir}", "0.34.0"}, + } + engine.Platforms[key] = platform + ex := newTestExecutor(t, engine) + raw, err := json.Marshal(engine) + require.NoError(t, err) + ex.reg.bundledRaw["vllm"] = raw + st, err := ex.state("vllm") + require.NoError(t, err) + out, err := exec.CommandContext(t.Context(), python, "-I", "-c", build, fakeEngineBin, st.installDir, "0.30.0").CombinedOutput() + require.NoError(t, err, string(out)) + require.NoError(t, writeInstallMarker(st.installDir, "vllm")) + weights := filepath.Join(platform.ModelsDir, "weights") + require.NoError(t, os.WriteFile(weights, []byte("model data"), 0o600)) + ex.client.Transport = roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.String() != platform.Install.Fetch.URL { + return nil, fmt.Errorf("unexpected request: %s", req.URL) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("test bootstrap"))}, nil + }) + + offer, err := ex.CheckVLLMUpdate(t.Context()) + require.NoError(t, err) + require.NotNil(t, offer) + assert.Equal(t, "managed", offer.InstallType) + assert.Equal(t, "0.34.0", offer.LatestVersion) + require.NoError(t, ex.UpdateVLLM(t.Context())) + + offer, err = ex.CheckVLLMUpdate(t.Context()) + require.NoError(t, err) + assert.Nil(t, offer) + builtAt, err := os.ReadFile(filepath.Join(st.installDir, "venv", "built-at")) + require.NoError(t, err) + assert.Equal(t, filepath.Join(st.installDir, "venv"), filepath.Clean(string(builtAt))) + model, err := os.ReadFile(weights) + require.NoError(t, err) + assert.Equal(t, "model data", string(model)) +} + +func TestRebuildVLLMInstall_RestoresOriginalWhenCandidateCannotStart(t *testing.T) { + dir := filepath.Join(t.TempDir(), "vllm") + require.NoError(t, writeInstallMarker(dir, "vllm")) + bin := filepath.Join(dir, "engine") + require.NoError(t, os.WriteFile(bin, []byte("old"), 0o600)) + failure := errors.New("candidate model failed to load") + + err := rebuildVLLMInstall(dir, func() error { + return os.WriteFile(bin, []byte("new"), 0o600) + }, func() error { return failure }) + + require.ErrorIs(t, err, failure) + got, err := os.ReadFile(bin) + require.NoError(t, err) + assert.Equal(t, "old", string(got)) + assert.NoDirExists(t, dir+".update-backup") +} + +func TestRecoverVLLMUpdate_LeavesALiveRebuildAloneAndRestoresAnInterruptedOne(t *testing.T) { + dir := filepath.Join(t.TempDir(), "vllm") + backup := dir + ".update-backup" + require.NoError(t, writeInstallMarker(backup, "vllm")) + marker, err := readEngineInstallMarker(backup, "vllm") + require.NoError(t, err) + require.NoError(t, os.Mkdir(dir, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(dir, vllmPendingMarker), marker, 0o600)) + guard, err := lockEngineInstall(dir) + require.NoError(t, err) + + assert.Error(t, recoverVLLMUpdate(dir)) + assert.DirExists(t, backup) + require.NoError(t, guard.Close()) + require.NoError(t, recoverVLLMUpdate(dir)) + + assert.FileExists(t, installMarkerPath(dir)) + assert.NoFileExists(t, filepath.Join(dir, vllmPendingMarker)) + assert.NoDirExists(t, backup) +} diff --git a/services/nvpair-engine-manager/vllm_version.go b/services/nvpair-engine-manager/vllm_version.go new file mode 100644 index 000000000..b2ecafc9f --- /dev/null +++ b/services/nvpair-engine-manager/vllm_version.go @@ -0,0 +1,188 @@ +// 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" + "os/exec" + "regexp" + "runtime" + "slices" + "strconv" + "strings" + "time" + + "nvpair-shared/engines" +) + +type vllmVersions struct { + Core string `json:"core"` + Metal string `json:"metal"` +} + +// Read package metadata from the CLI's own Python environment. Importing +// vllm during a background check would initialize its inference dependencies. +func installedVLLMVersions(ctx context.Context, bin string, metal bool) (vllmVersions, error) { + python, err := vllmPython(bin) + if err != nil { + return vllmVersions{}, err + } + const probe = `import json, sys +from importlib.metadata import version +print(json.dumps({"core": version("vllm"), "metal": version("vllm-metal") if sys.argv[1] == "true" else ""}))` + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, python, "-I", "-c", probe, strconv.FormatBool(metal)) + configureSysProcAttr(cmd) + output, err := cmd.Output() + if err != nil { + return vllmVersions{}, fmt.Errorf("read installed vLLM package metadata: %w", err) + } + var installed vllmVersions + if err := json.Unmarshal(output, &installed); err != nil { + return vllmVersions{}, err + } + return installed, nil +} + +// vLLM uses Python distribution versions, including post releases and local +// CUDA/CPU wheel labels. A wheel label is not a newer engine release. +var vllmVersionPattern = regexp.MustCompile(`^([0-9]+(?:\.[0-9]+){1,3})(?:(a|b|rc|\.dev|\.post)([0-9]+))?(?:\+[a-zA-Z0-9]+(?:[._-][a-zA-Z0-9]+)*)?$`) + +func vllmVersionKey(version string) ([6]int, error) { + var key [6]int + match := vllmVersionPattern.FindStringSubmatch(version) + if match == nil { + return key, errors.New("unrecognized vLLM release version") + } + for index, field := range strings.Split(match[1], ".") { + n, err := strconv.Atoi(field) + if err != nil { + return key, err + } + key[index] = n + } + if match[2] != "" { + key[4] = map[string]int{".dev": -4, "a": -3, "b": -2, "rc": -1, ".post": 1}[match[2]] + var err error + key[5], err = strconv.Atoi(match[3]) + return key, err + } + return key, nil +} + +// Both macOS distributions are pinned to the same release. Never downgrade +// either package if someone upgraded one independently. +func (v vllmVersions) olderPackage(target string, metal bool) (string, error) { + latest, err := vllmVersionKey(target) + if err != nil { + return "", err + } + installed := []string{v.Core} + if metal { + installed = []string{v.Metal, v.Core} + } + var older string + for _, version := range installed { + current, err := vllmVersionKey(version) + if err != nil { + return "", err + } + switch slices.Compare(current[:], latest[:]) { + case 1: + return "", nil + case -1: + if older == "" { + older = version + } + } + } + return older, nil +} + +// The bundled recipe passes its release as the installer's third positional +// argument. The Linux package and both macOS wheels use that same value. +func vllmRecipeVersion(inst *Install) (string, error) { + if inst == nil || inst.Fetch == nil || inst.Fetch.SHA256 == "" || len(inst.Run) < 2 || inst.Run[len(inst.Run)-2] != "{install_dir}" { + return "", errors.New("vLLM has no pinned installer for this platform") + } + target := inst.Run[len(inst.Run)-1] + _, err := vllmVersionKey(target) + return target, err +} + +func vllmReleaseProject(metal bool) (repo, download string) { + if metal { + return "vllm-project/vllm-metal", "https://github.com/vllm-project/vllm-metal#installation" + } + return "vllm-project/vllm", "https://docs.vllm.ai/en/latest/getting_started/installation/gpu/" +} + +func (e *Executor) CheckVLLMUpdate(ctx context.Context) (*EngineUpdateInfo, error) { + return e.checkInstalledEngineUpdate(ctx, engines.NameVLLM, e.checkVLLMRelease) +} + +func (e *Executor) checkVLLMRelease(ctx context.Context, st *engineState, snapshot engineUpdateSnapshot) (*EngineUpdateInfo, error) { + if snapshot.processPath != "" && !isOurEngineImage(snapshot.processPath, snapshot.binPath) { + return nil, nil + } + metal := runtime.GOOS == "darwin" + repo, download := vllmReleaseProject(metal) + var installed vllmVersions + if snapshot.adopted { + if metal { + // The server reports its core version, not the Metal plugin's. + return nil, nil + } + var reply struct { + Version string `json:"version"` + } + if err := e.readRunningEngineVersion(ctx, snapshot.port, "/version", &reply); err != nil { + return nil, err + } + installed.Core = reply.Version + } else { + var err error + installed, err = installedVLLMVersions(ctx, snapshot.binPath, metal) + if err != nil { + return nil, err + } + } + target, installType := "", "external" + if !snapshot.adopted && managedVLLMBinary(st, snapshot.binPath) { + var err error + target, err = vllmRecipeVersion(st.bundledInstall) + if err != nil { + return nil, err + } + installType = "managed" + download = "" + } else { + release, err := e.latestGitHubRelease(ctx, repo) + if err != nil { + return nil, err + } + target = strings.TrimPrefix(release.Tag, "v") + if release.Tag != "v"+target { + return nil, errors.New("unrecognized vLLM release tag") + } + if metal { + // Upstream publishes Metal separately. Its release number need + // not match the core in a user-provisioned environment. + installed.Core = installed.Metal + } + } + current, err := installed.olderPackage(target, metal) + if err != nil || current == "" { + return nil, err + } + return &EngineUpdateInfo{ + CurrentVersion: current, LatestVersion: target, InstallType: installType, + ReleaseURL: "https://github.com/" + repo + "/releases/tag/v" + target, + DownloadURL: download, + }, nil +} 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..5b31b7555 --- /dev/null +++ b/services/tests/engine_update_test.go @@ -0,0 +1,79 @@ +// 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() + names := []string{engines.NameOllama, engines.NameLMStudio, engines.NameLlamaCPP, engines.NameVLLM} + ports := freePorts(t, len(names)) + // Give each engine an empty installation on the host platform, including + // engines whose bundled manifests normally omit this OS or architecture. + for i, name := range names { + writeUserManifest(t, configDir, map[string]any{ + "engine": name, + "platforms": map[string]any{runtime.GOOS + "/" + runtime.GOARCH: map[string]any{ + "detect": []string{filepath.Join(installDir, name)}, + "install": nil, + "runtime": map[string]any{"port": ports[i]}, + }}, + }) + } + stdin, messages, _, cleanup := startBrokerWithConfigDir(t, configDir, "--engine-manager-path", engineMgrBin) + t.Cleanup(cleanup) + waitForMethod(t, messages, "app:ready", 15*time.Second) + + expectNoUpdate := func(t *testing.T, name string) { + t.Helper() + reply := callRPC(t, stdin, messages, "engine:check-updates", map[string]string{"engine": name}, 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"]) + } + + for _, name := range names { + t.Run(name+" has no update when absent", func(t *testing.T) { expectNoUpdate(t, name) }) + t.Run(name+" cannot be installed by an update", func(t *testing.T) { + reply := callRPC(t, stdin, messages, "engine:update", map[string]string{"engine": name}, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32000, reply.Error.Code) + }) + } + + t.Run("a broken Ollama binary leaves the LM Studio check independent", 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) + expectNoUpdate(t, engines.NameLMStudio) + }) + + 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) + }) + } +}