diff --git a/.cursor/rules/architecture.mdc b/.cursor/rules/architecture.mdc index 5395db1d7..d2aff2644 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 on the selected node identifies the installed version, + selects the release, and applies managed updates. The desktop and TUI use + the engine manager's paired-peer control surface for remote engines. - 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..6e968d420 100644 --- a/.cursor/rules/system-architecture.mdc +++ b/.cursor/rules/system-architecture.mdc @@ -211,8 +211,11 @@ 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. + Desktop and TUI use `engine:check-updates` and `engine:update` locally. + On a paired node, `engine:remote-check-updates` and `engine:remote-update` + delegate both operations to the target engine manager. It selects the + release, verifies ownership, and supplies vendor links for external copies. - 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..88ba7be1a 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 + update engines on this machine or a paired one, remove local engines, 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..23411fedb 100644 --- a/desktop/docs/architecture.md +++ b/desktop/docs/architecture.md @@ -208,6 +208,12 @@ 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. +Each node's engine manager compares versions, determines installation +ownership, and applies managed updates. For a paired node the desktop requests +the check or update through the peer control surface. The bridge publishes +availability by node and engine through the 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..5ebb2d899 100644 --- a/desktop/docs/frontend-api.md +++ b/desktop/docs/frontend-api.md @@ -94,7 +94,10 @@ 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 selected local or + paired node. For an external installation, the engine row links to the + vendor instructions or release reported by that node. - `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..fbe7304bc 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 | @@ -110,6 +111,7 @@ | `engine:preview-launch` | request (we call) | ⚠️ not called | | `engine:remote-apply-settings` | request (we call) | ⚠️ not called | | `engine:remote-cancel-pull` | request (we call) | ✅ yes | +| `engine:remote-check-updates` | request (we call) | ✅ yes | | `engine:remote-delete-model` | request (we call) | ✅ yes | | `engine:remote-get-installed` | request (we call) | ✅ yes | | `engine:remote-get-settings` | request (we call) | ⚠️ not called | @@ -120,6 +122,7 @@ | `engine:remote-start` | request (we call) | ✅ yes | | `engine:remote-stop` | request (we call) | ✅ yes | | `engine:remote-unload-model` | request (we call) | ✅ yes | +| `engine:remote-update` | request (we call) | ✅ yes | | `engine:restart` | request (we call) | ⚠️ not called | | `engine:set-port` | request (we call) | ⚠️ not called | | `engine:start` | request (we call) | ✅ yes | @@ -127,6 +130,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 +279,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 +289,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..d3f0eaf99 100644 --- a/desktop/docs/services-backend.md +++ b/desktop/docs/services-backend.md @@ -170,9 +170,14 @@ 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 -remote control surface where supported. +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. For a paired node, the desktop requests +`engine:remote-check-updates` with the node and engine. Selecting **Update** +sends `engine:update` locally or `engine:remote-update` to the peer. The +selected node determines ownership and runs its own updater. ### Cancelling a download diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index 5fd72a98f..c0472b27f 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -27,9 +27,9 @@ history. | llama.cpp backend | Integrated | Desktop and TUI expose install, lifecycle, catalog pull, inventory, load/unload, endpoints, routing, and demo traffic | | vLLM engine | Integrated (Linux, macOS arm64) | Desktop and TUI expose install, lifecycle, the cached-model list, switching the served model (Load), Hugging Face catalog search and download, endpoints and routing; eject (stops the engine), delete of cached models; no demo traffic | | 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 | +| Remote engine lifecycle | Partial | Remote install, start, stop, status, update checks, managed updates, 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 local install sends `engine:install` with `start: true`, so a successful install +starts the engine. A local 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. @@ -291,9 +291,9 @@ Personal AI Router synthesizes one centralized pending-action state while waitin terminal backend notifications. It never treats optimistic state as authoritative. -Remote cluster support includes status, install, start, stop, model pull, and -remote model load, unload (eject), and delete via the `ec` surface. Uninstall -and update remain local-only. +Remote cluster support includes status, install, start, stop, update checks, +managed updates, and model pull, load, unload (eject), and delete via the +`ec` surface. Uninstall requires the local client. Server port, proxy port, and engine arguments are one authoritative record owned by the node running the engine, read and written through the broker's @@ -358,7 +358,7 @@ Load uses a separate 10/31-minute response-header budget: | `OLLAMA_LOAD_PENDING_TIMEOUT_MS` (`pending-actions.store.ts`) | 32min | Ollama's Load control stays locked beyond the remote path's 31-minute header budget, while backend success or failure still clears it immediately. | | `PENDING_TIMEOUT_MS` | 60s | Unchanged for every other command, including an Ollama delete. | | `remoteReadyResponseHeaderTimeout` (`remoteclient.go`) | 31min | Start, settings apply, delete, Ollama and vLLM loads (a vLLM load restarts vLLM on the new model), and download cancel can answer only after slow work on the peer, so `waitsForEngineReadiness` sends them to the client pool `NewManager` (`manager.go`) creates with this budget. | -| `remoteResponseHeaderTimeout` (`remoteclient.go`) | 30s | Every other remote call, a streamed pull or install included. It bounds only how long the peer takes to begin its answer, not how long the call runs. | +| `remoteResponseHeaderTimeout` (`remoteclient.go`) | 30s | Every other remote call, including a streamed pull, install, or update. It bounds only how long the peer takes to begin its answer, not how long the call runs. | The net is a backstop, not the mechanism: a delete now ends the spinner on real backend truth either way. On success the refreshed `list_models` drops the model; diff --git a/desktop/src/electron/main.ts b/desktop/src/electron/main.ts index 05db8504c..a4cb988e7 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,12 @@ if (!gotTheLock || exitRequested) { registerAllIpc() initializeUpdater() + const unsubscribeEngineUpdates = subscribeEngineUpdateNotifications(nodeId => { + const state = getModularBridgeState() + if (nodeId === state.getSelfId()) return 'This node' + return state.getNodesInitial().nodes[nodeId]?.name || nodeId + }) + 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..76b28c052 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( + 'Select an identified node to update its engine.', + '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 @@ -438,13 +441,8 @@ async function toggleRemoteEngine( /** * Dispatch a UI engine command to a remote peer via `nvpair-engine-manager`'s - * `engine:remote-*` client methods (cluster-scoped mTLS `ec` surface). Install, - * start/stop, pull, and model load/unload/delete are supported remotely; - * uninstall and update remain local-only. Ports are not commands at all — they - * travel the settings channels, which do reach a peer. - * (optimistic status, awaited completion, authoritative refresh) lives on the - * supervisor because the backend settles these ops only via the RPC reply, never - * a terminal notification. + * `engine:remote-*` client methods (cluster-scoped mTLS `ec` surface). The + * supervisor tracks progress until the RPC completes and refreshes peer state. */ function routeRemoteEngineCommand(payload: WsInvokeRequest<'engine:command'>): void { const supervisor = getModularSupervisor() @@ -458,7 +456,27 @@ function routeRemoteEngineCommand(payload: WsInvokeRequest<'engine:command'>): v switch (payload.command) { case 'install': case 'installAll': - void supervisor.installEngineRemote(nodeId, engine, payload.engineType, true) + void supervisor.installOrUpdateEngineRemote( + nodeId, + engine, + payload.engineType, + 'install', + true + ) + break + case 'update': + if (!getModularBridgeState().canCheckEngineUpdate(nodeId, payload.engineType)) { + refuseRemote( + 'Updating requires a connected, paired node with this engine installed.' + ) + break + } + void supervisor.installOrUpdateEngineRemote( + nodeId, + engine, + payload.engineType, + 'update' + ) break case 'toggle': void toggleRemoteEngine(nodeId, engine, payload.engineType) @@ -477,10 +495,7 @@ function routeRemoteEngineCommand(payload: WsInvokeRequest<'engine:command'>): v } break case 'uninstall': - case 'update': - refuseRemote( - `${payload.command} is only available on the local node — remote uninstall/update is not supported yet.` - ) + refuseRemote('Engines can only be uninstalled on the local node.') break case 'deleteModel': case 'loadModel': @@ -522,7 +537,7 @@ async function handleEngineCommand(payload?: WsInvokeRequest<'engine:command'>): // action; LM Studio and llama.cpp use their manifest `load_model` actions. // Remote peers: `nvpair-engine-manager` exposes `engine:remote-*` client methods - // (cluster mTLS `ec` surface) for install/start/stop/pull and model ops. + // (cluster mTLS `ec` surface) for lifecycle and model operations. // Local-only ops are refused in {@link routeRemoteEngineCommand}. noteStopRequest(payload) const selfId = getModularBridgeState().getSelfId() 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..6518e80cc --- /dev/null +++ b/desktop/src/electron/service-bridge/engine-update-checks.ts @@ -0,0 +1,74 @@ +// 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 for the same node and engine. */ +export function watchEngineUpdates( + check: (nodeId: string, engine: EngineType) => Promise +): { + refresh: (engine?: EngineType, nodeId?: string) => Promise + stop: () => void +} { + const state = getModularBridgeState() + let active = true + const checking = new Set() + const requested = new Set() + + async function checkEngine(nodeId: string, engine: EngineType): Promise { + const key = `${nodeId}:${engine}` + requested.add(key) + if (checking.has(key)) return + checking.add(key) + try { + while (active && requested.delete(key)) { + if (!state.canCheckEngineUpdate(nodeId, engine)) return + try { + const result = await check(nodeId, engine) + if (active && !requested.has(key)) { + state.applyEngineUpdateCheck(nodeId, engine, result) + } + } catch (error) { + log.verbose({ + sublevel: 'engine-manager', + message: `${engine} update check on ${nodeId} unavailable: ${getErrorString(error)}` + }) + } + } + } finally { + checking.delete(key) + } + } + + async function refresh(engine?: EngineType, nodeId?: string): Promise { + const selfId = state.getSelfId() + if (!selfId) return + if (engine) await checkEngine(nodeId ?? selfId, engine) + else { + const nodes = Array.from(new Set([selfId, ...state.getClusterPeerIds()])) + await Promise.all(nodes.flatMap(id => EngineTypes.map(type => checkEngine(id, type)))) + } + } + + 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..ff037431d 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' @@ -66,15 +67,10 @@ interface EnginePresence { } /** - * Authoritative install/run facts for a remote peer's engine, read from that - * peer's cluster-scoped `ec` control surface via `engine:remote-get-installed` - * (pin-based mTLS). Unlike {@link EnginePresence} — which is inferred from mDNS - * proxy advertisement and can only ever say "up/down" — these are the peer - * engine-manager's own truth: whether it is installed, whether it is running, - * and the configured server port (present even while stopped). Only available - * for clustered, reachable peers; when absent we fall back to presence. + * Installed and running state reported by the node's engine manager, locally + * or through a pinned peer's control surface. */ -interface RemoteEngineFacts { +interface EngineManagerFacts { installed: boolean running: boolean starting: boolean @@ -83,6 +79,17 @@ interface RemoteEngineFacts { port: number } +function engineManagerFacts(obj: JsonObject): EngineManagerFacts { + return { + installed: booleanValue(obj.installed), + running: booleanValue(obj.running), + starting: booleanValue(obj.starting), + awaitingModel: booleanValue(obj.awaiting_model), + healthy: booleanValue(obj.healthy), + port: numberValue(obj.port) + } +} + /** * The process status an engine-manager `EngineStatus` reports. `starting` covers * a start in flight whoever began it (install-then-start, a settings restart, a @@ -254,6 +261,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,22 +971,16 @@ class ModularBridgeState { vllm: 0 } private selfId: string | null = null + private engineUpdates = new Map() + private refreshEngineUpdates?: (engineType?: EngineType, nodeId?: string) => void + private clusterPeerIds: ReadonlySet = new Set() /** * Authoritative local-engine facts from `nvpair-engine-manager`, keyed by * engine type. Stored independent of `selfId` because engine-manager * reports before the self node is discovered, then resolved against * `selfId` at emit time. */ - private engineManagerFacts = new Map< - EngineType, - { - installed: boolean - running: boolean - starting: boolean - awaitingModel: boolean - port: number - } - >() + private engineManagerFacts = new Map() /** * The engines `nvpair-engine-manager` lists for this host. It leaves out an * engine the host cannot run, such as vLLM on Windows, which is then @@ -1048,7 +1056,7 @@ class ModularBridgeState { * failed poll — see `refreshRemoteEngineStatus`. Dropped when the node is * evicted. */ - private remoteEngineFacts = new Map() + private remoteEngineFacts = new Map() /** The engines each peer's engine manager lists, as {@link localEngineList} is for this host. */ private remoteEngineLists = new Map>() /** @@ -1135,8 +1143,98 @@ 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?.() + } + + getClusterPeerIds(): ReadonlySet { + return this.clusterPeerIds + } + + setClusterPeerIds(peers: ReadonlySet): void { + const previous = this.clusterPeerIds + this.clusterPeerIds = peers + for (const peer of previous) { + if (!peers.has(peer)) this.dropRemoteEngineFacts(peer) + } + for (const peer of peers) { + if (!previous.has(peer)) this.dropRemoteEngineFacts(peer) + } + } + + canCheckEngineUpdate(nodeId: string, engine: EngineType): boolean { + if (!this.selfId) return false + if (nodeId === this.selfId) return this.localEngineList?.has(engine) ?? false + return ( + this.clusterPeerIds.has(nodeId) && + this.remoteEngineFacts.get(this.remoteOpKey(nodeId, engine))?.installed === true + ) + } + + setEngineUpdateRefresher(refresh?: (engineType?: EngineType, nodeId?: string) => void): void { + this.refreshEngineUpdates = refresh + } + + clearEngineUpdates(): void { + for (const update of this.engineUpdates.values()) { + this.clearEngineUpdate(update.nodeId, update.engineType) + } + } + + private clearEngineUpdate(nodeId: string | null, engineType: EngineType): void { + if (!nodeId || !this.engineUpdates.delete(this.remoteOpKey(nodeId, engineType))) return + emitBridgePush('engines:state-changed', { + nodeId, + engineType, + updateAvailable: null + }) + } + + applyEngineUpdateCheck( + nodeId: string, + engineType: EngineType, + result: JsonValue | undefined + ): void { + if (!this.canCheckEngineUpdate(nodeId, engineType)) return + const value = objectValue(result)?.updateAvailable + if (value === null) { + this.clearEngineUpdate(nodeId, 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 key = this.remoteOpKey(nodeId, engineType) + const previous = this.engineUpdates.get(key) + if ( + previous?.currentVersion === currentVersion && + previous.latestVersion === latestVersion && + previous.releaseUrl === releaseUrl && + previous.downloadUrl === downloadUrl && + previous.installType === installType + ) + return + this.engineUpdates.set(key, 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 +1303,7 @@ class ModularBridgeState { statuses, models, activeProgress: Array.from(this.activePulls.values()), - updateAvailable: [] + updateAvailable: Array.from(this.engineUpdates.values()) } } @@ -1262,10 +1360,12 @@ class ModularBridgeState { /** Local fallback upsert used only when `nvpair-errors` is not running. */ upsertError(error: ServiceError): void { - this.errors = [error, ...this.errors.filter(existing => existing.id !== error.id)].slice( - 0, - 200 - ) + this.errors = [ + error, + ...this.errors.filter( + existing => existing.nodeId !== error.nodeId || existing.id !== error.id + ) + ].slice(0, 200) emitBridgePush('errors:update', [...this.errors]) } @@ -1370,15 +1470,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(this.selfId, engineType) + this.emitLocalEngineStatus(engineType) + } } } @@ -1393,19 +1497,33 @@ class ModularBridgeState { const engineType = engineTypeFromManagerName(stringValue(obj.engine)) if (!engineType) return - this.engineManagerFacts.set(engineType, { - installed: booleanValue(obj.installed), - running: booleanValue(obj.running), - starting: booleanValue(obj.starting), - awaitingModel: booleanValue(obj.awaiting_model), - port: numberValue(obj.port) - }) + const previous = this.engineManagerFacts.get(engineType) + const facts = engineManagerFacts(obj) + 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) + this.refreshAfterEngineState(this.selfId, engineType, previous, facts) + } + + private refreshAfterEngineState( + nodeId: string | null, + engineType: EngineType, + previous: EngineManagerFacts | undefined, + facts: EngineManagerFacts + ): void { + if (!nodeId) return + // 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(nodeId, engineType) + this.refreshEngineUpdates?.(engineType, nodeId) + } } /** @@ -1427,10 +1545,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) @@ -1803,14 +1927,7 @@ class ModularBridgeState { if (!engineObj) continue const engineType = engineTypeFromManagerName(stringValue(engineObj.engine)) if (!engineType || !isProxyEngine(engineType)) continue - this.remoteEngineFacts.set(this.remoteOpKey(nodeId, engineType), { - installed: booleanValue(engineObj.installed), - running: booleanValue(engineObj.running), - starting: booleanValue(engineObj.starting), - awaitingModel: booleanValue(engineObj.awaiting_model), - healthy: booleanValue(engineObj.healthy), - port: numberValue(engineObj.port) - }) + this.recordRemoteEngineStatus(nodeId, engineType, engineObj) seen.add(engineType) } // A peer leaves out an engine it cannot run. An empty listing says nothing. @@ -1818,6 +1935,7 @@ class ModularBridgeState { for (const engine of PROXY_ENGINES) { if (!seen.has(engine)) { this.remoteEngineFacts.delete(this.remoteOpKey(nodeId, engine)) + this.clearEngineUpdate(nodeId, engine) } this.emitRemoteEngineStatus(nodeId, engine) } @@ -1836,22 +1954,29 @@ class ModularBridgeState { if (!isProxyEngine(engineType)) return const obj = objectValue(result) if (!obj) return - this.remoteEngineFacts.set(this.remoteOpKey(nodeId, engineType), { - installed: booleanValue(obj.installed), - running: booleanValue(obj.running), - starting: booleanValue(obj.starting), - awaitingModel: booleanValue(obj.awaiting_model), - healthy: booleanValue(obj.healthy), - port: numberValue(obj.port) - }) + this.recordRemoteEngineStatus(nodeId, engineType, obj) this.emitRemoteEngineStatus(nodeId, engineType) } + private recordRemoteEngineStatus(nodeId: string, engine: EngineType, obj: JsonObject): void { + const key = this.remoteOpKey(nodeId, engine) + const previous = this.remoteEngineFacts.get(key) + const facts = engineManagerFacts(obj) + this.remoteEngineFacts.set(key, facts) + this.refreshAfterEngineState(nodeId, engine, previous, facts) + } + + finishRemoteEngineUpdate(nodeId: string, engine: EngineType): void { + this.clearEngineUpdate(nodeId, engine) + this.refreshEngineUpdates?.(engine, nodeId) + } + /** Forget a node's authoritative remote-engine facts (on eviction/leave). */ private dropRemoteEngineFacts(nodeId: string): void { this.remoteEngineLists.delete(nodeId) for (const engine of PROXY_ENGINES) { this.remoteEngineFacts.delete(this.remoteOpKey(nodeId, engine)) + this.clearEngineUpdate(nodeId, engine) } } @@ -2176,6 +2301,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(nodeId, 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..acfea91c3 100644 --- a/desktop/src/electron/service-bridge/modular-supervisor.ts +++ b/desktop/src/electron/service-bridge/modular-supervisor.ts @@ -17,6 +17,7 @@ import { EnginesListingModelsWhenStopped } from '@/shared/constants/engines' import { createStructuredLogger } from '@/shared/utils/log' import getErrorString from '@/shared/utils/get-error-string' import { currentPlatform } from '@/shared/utils/platform' +import { engineProgressKey } from '@/shared/utils/engine-progress' import { getModularBridgeState, isUpstreamUnreachableError, @@ -33,6 +34,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' @@ -363,15 +365,9 @@ class ModularSupervisor { // broker restarts within one app process without adding a second auto-start // source of truth (the backend still owns lifecycle persistence). private firstOpenEngineStartDone = false - // Pinned cluster peer UUIDs (seeded from `nodes:get-initial` at broker ready, - // then kept current by the `nodes:changed` membership push, self excluded). - // These are the only nodes whose `ec` control surface we can reach, so they - // scope the remote-engine-status polling. Keyed by `ClusterNode.nodeUuid` — - // the backend keys peers by hostUuid, and it is the same key - // discovery/`engine:remote-*` use, never the hostname. - private clusterPeerIds = new Set() - // Light interval that re-polls clusterPeerIds' authoritative engine status. + // Light interval that re-polls peers' 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 +522,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 @@ -541,7 +538,6 @@ class ModularSupervisor { for (const timer of this.discoveryModelRetryTimers.values()) clearTimeout(timer) this.discoveryModelRetryTimers.clear() this.discoveryModelRetryAttempts.clear() - this.clusterPeerIds.clear() this.brokerHydrationDone = false // Teardown is timed phase by phase because a slow quit is otherwise @@ -748,6 +744,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 @@ -907,11 +904,14 @@ class ModularSupervisor { * carries pending invites, which have no reachable control surface yet. */ private setClusterPeerIds(members: ClusterNode[]): void { - const selfId = getModularBridgeState().getSelfId() - this.clusterPeerIds = new Set( - members - .filter(m => m.state === 'member' && m.nodeUuid && m.nodeUuid !== selfId) - .map(m => m.nodeUuid) + const state = getModularBridgeState() + const selfId = state.getSelfId() + state.setClusterPeerIds( + new Set( + members + .filter(m => m.state === 'member' && m.nodeUuid && m.nodeUuid !== selfId) + .map(m => m.nodeUuid) + ) ) } @@ -928,8 +928,8 @@ class ModularSupervisor { this.setClusterPeerIds(members) log.info({ sublevel: 'broker', - message: `cluster peer seed: ${this.clusterPeerIds.size} remote member(s)`, - data: { peerIds: Array.from(this.clusterPeerIds) } + message: 'Cluster peers initialized', + data: { peerIds: Array.from(getModularBridgeState().getClusterPeerIds()) } }) } catch (err) { log.warn({ @@ -992,7 +992,7 @@ class ModularSupervisor { private async refreshAllRemoteEngineStatus(): Promise { if (!this.brokerReady) return const selfId = getModularBridgeState().getSelfId() - const peerIds = new Set(this.clusterPeerIds) + const peerIds = new Set(getModularBridgeState().getClusterPeerIds()) for (const node of getModularBridgeState().getAvailableNodes()) { if (node.id && node.id !== selfId) peerIds.add(node.id) } @@ -1062,12 +1062,25 @@ 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((nodeId, engineType) => { + const engine = engineManagerName(engineType) + return nodeId === getModularBridgeState().getSelfId() + ? this.callProcess('broker', 'engine:check-updates', { engine }, 30_000) + : this.callProcess( + 'broker', + 'engine:remote-check-updates', + { node: nodeId, engine }, + 30_000 + ) + }) for (const engine of obj.engines) { this.refreshManagedEngineModels(engine) } @@ -1079,6 +1092,12 @@ class ModularSupervisor { } } + private stopEngineUpdateChecks(): void { + this.engineUpdateChecks?.stop() + this.engineUpdateChecks = undefined + getModularBridgeState().setClusterPeerIds(new Set()) + } + /** * 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 @@ -1888,40 +1907,54 @@ class ModularSupervisor { } /** - * Install (and optionally start) an engine on a remote peer via - * `engine:remote-install`. Streams progress frames as `engine:remote-progress` - * but its terminal is only the awaited RPC reply, so we clear the optimistic - * `installing` op here and refresh the peer's authoritative status. + * A peer streams install and update progress through the same channel. + * Its terminal RPC reply confirms whether the operation succeeded. */ - async installEngineRemote( + async installOrUpdateEngineRemote( nodeId: string, engine: string, engineType: EngineType, - start: boolean + operation: 'install' | 'update', + start = false ): Promise { const state = getModularBridgeState() state.beginRemoteEngineOp(nodeId, engineType, 'installing') try { - await this.callProcess( - 'broker', - 'engine:remote-install', - { node: nodeId, engine, start }, - PULL_TIMEOUT_MS - ) - await this.refreshRemoteEngineStatus(nodeId) + if (operation === 'update') { + const result = await this.callProcess( + 'broker', + 'engine:remote-update', + { node: nodeId, engine }, + PULL_TIMEOUT_MS + ) + state.applyRemoteEngineStatusResult(nodeId, engineType, objectValue(result)?.status) + state.finishRemoteEngineUpdate(nodeId, engineType) + } else { + await this.callProcess( + 'broker', + 'engine:remote-install', + { node: nodeId, engine, start }, + PULL_TIMEOUT_MS + ) + await this.refreshRemoteEngineStatus(nodeId) + } } catch (err) { + // A lost connection can interrupt the stream before its terminal frame. + emitBridgePush('engines:progress-cleared', { + key: engineProgressKey({ nodeId, engineType, operation: 'install' }) + }) // Use engine-manager's canonical error identity so a rejection here // upserts the backend's own report (and offers retry) rather than // duplicating it under a UI-synthesized id. this.reportError( - `Failed to install ${engine} on ${nodeId}: ${getErrorString(err)}`, + `Failed to ${operation} ${engine} on ${nodeId}: ${getErrorString(err)}`, 'error', - `engine-remote-install:${nodeId}:${engine}`, + `engine-remote-${operation}:${nodeId}:${engine}`, { - id: `engine-manager:install-failed:${engine}`, + id: `engine-manager:${operation}-failed:${engine}`, nodeId, - engineType: engine, - operation: 'install', + engineType, + operation, action: 'retry' } ) 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..5e8fa9d73 --- /dev/null +++ b/desktop/src/electron/updater/engine-update-notification.ts @@ -0,0 +1,39 @@ +// 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' + +export function subscribeEngineUpdateNotifications( + getNodeLabel: (nodeId: string) => string +): () => 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 (updateAvailable === undefined) return + + const key = `engine-update:${nodeId}:${engineType}` + const id = updateAvailable ? `${key}:${updateAvailable.latestVersion}` : null + const currentNotice = currentNotices.get(key) + if (currentNotice && currentNotice !== id) dismissOverviewMessage(currentNotice) + if (!id || !updateAvailable) { + currentNotices.delete(key) + return + } + currentNotices.set(key, id) + if (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. ${getNodeLabel(nodeId)} 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..b70e325ef 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 { +/** Update reported by the engine manager on the named node. */ +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..0746dcf2e 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 => + state.getInfo(nodeId, backend.type) + ) + 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. @@ -153,8 +158,8 @@ export function BackendRow({ ) }, [displayBackend.processStatus, isUnavailable]) - const nodeOs = useNodesStore(state => state.nodes.get(nodeId)?.os) - const targetOs = nodeOs ?? window.windowApi.platform + const node = useNodesStore(state => state.nodes.get(nodeId)) + const targetOs = node?.os ?? window.windowApi.platform const handleToggle = useCallback(() => { window.pairApi.engines.toggle(backend.type, nodeId) @@ -185,18 +190,10 @@ export function BackendRow({ setExpanded(prev => !prev) }, [isUnavailable]) - // Install/start/stop, model pull, and the settings editor work on clustered - // peers; uninstall, update, and model load/delete remain local-only. const controlsDisabled = isTransitioning const content = expanded ? ( - - {canShowAccordions && ( )} @@ -237,6 +234,16 @@ 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..fbd537376 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,16 +15,14 @@ const BANNER_LINK_STYLE: CSSProperties = { lineHeight: 1 } -function displayVersion(version: string): string { - return version.startsWith('v') ? version : `v${version}` -} - export function BackendUpdateBanner({ backend, + remoteNodeName, disabled, onUpdate }: { backend: BackendInfo + remoteNodeName?: string disabled: boolean onUpdate: () => void }) { @@ -33,41 +32,64 @@ 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 + {remoteNodeName && updateAvailable.installType === 'external' + ? `. Update manually on ${remoteNodeName}.` + : ''} - - - + {(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..834f22a6b 100644 --- a/desktop/src/ui/components/ErrorModal.tsx +++ b/desktop/src/ui/components/ErrorModal.tsx @@ -7,10 +7,11 @@ 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 { useEngineUpdateAvailableStore } from '@/ui/stores/engine-update-available.store' import { useNodesStore } from '@/ui/stores/nodes.store' import { isEngineType } from '@/shared/utils/engines' import type { ServiceError } from '@/shared/types/errors' -import type { NodeItem } from '@/shared/types/nodes' interface ErrorModalFilter { nodeId?: string @@ -34,6 +35,7 @@ interface ErrorModalFilter { export function ErrorModal({ filter }: { filter?: ErrorModalFilter }) { const errors = useErrorsStore(state => state.errors) const clearError = useErrorsStore(state => state.clearError) + const selfId = useConnectionStore(state => state.selfId) const [dismissedKey, setDismissedKey] = useState(null) const matched = useMemo(() => { @@ -46,11 +48,21 @@ export function ErrorModal({ filter }: { filter?: ErrorModalFilter }) { const matchedKey = useMemo(() => errorDismissalKey(matched), [matched]) + const clear = useCallback( + (error: ServiceError) => { + // The peer's engine manager owns its update errors. errors.clear(id) + // addresses this node and could clear its own error with the same ID. + if (error.operation === 'update' && error.nodeId && error.nodeId !== selfId) return + clearError(error.id) + }, + [clearError, selfId] + ) + const handleDismiss = useCallback(() => { if (matchedKey === dismissedKey) return setDismissedKey(matchedKey) - matched.forEach(err => clearError(err.id)) - }, [clearError, dismissedKey, matched, matchedKey]) + matched.forEach(clear) + }, [clear, dismissedKey, matched, matchedKey]) if (matched.length === 0) return null @@ -70,7 +82,7 @@ export function ErrorModal({ filter }: { filter?: ErrorModalFilter }) { ))} @@ -99,7 +111,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, canUpdate: boolean): (() => void) | null { if (error.action !== 'retry') return null const { engineType, nodeId, operation, modelName } = error if (!engineType || !isEngineType(engineType) || !nodeId) return null @@ -107,6 +119,8 @@ function buildRetry(error: ServiceError): (() => void) | null { switch (operation) { case 'install': return () => engines.install(engineType, nodeId) + case 'update': + return canUpdate ? () => engines.update(engineType, nodeId) : null case 'uninstall': return () => engines.uninstall(engineType, nodeId) case 'start': @@ -118,13 +132,6 @@ function buildRetry(error: ServiceError): (() => void) | null { } } -function resolveNodeLabel(nodes: Map, nodeId: string): string | null { - const node = nodes.get(nodeId) - if (node?.name) return node.name - if (node?.ipAddress) return node.ipAddress - return null -} - function nodeErrorPrefix(severity: ServiceError['severity'], nodeLabel: string | null): string { const target = nodeLabel ? `node ${nodeLabel}` : 'a node' if (severity === 'warning') return `A warning has occurred on ${target}; ` @@ -154,16 +161,24 @@ function ErrorBanner({ hideNodePrefix }: { error: ServiceError - onClear: (id: string) => void + onClear: (error: ServiceError) => void hideNodePrefix: boolean }) { - const nodeLabel = useNodesStore(state => - error.nodeId ? resolveNodeLabel(state.nodes, error.nodeId) : null - ) + const node = useNodesStore(state => (error.nodeId ? state.nodes.get(error.nodeId) : undefined)) + const nodeLabel = node?.name || node?.ipAddress || null 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 hasManagedUpdate = useEngineUpdateAvailableStore(state => + error.operation === 'update' && + error.nodeId && + error.engineType && + isEngineType(error.engineType) + ? state.getInfo(error.nodeId, error.engineType)?.installType === 'managed' + : false + ) + const retry = buildRetry(error, isLocalNode || (node?.status === 'active' && hasManagedUpdate)) return ( @@ -172,7 +187,7 @@ function ErrorBanner({ kind="primary" size="small" onClick={() => { - onClear(error.id) + onClear(error) retry() }} > 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..a5a05c701 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,17 @@ type BridgeState = ReturnType const mocks = vi.hoisted(() => ({ state: { - getSelfId: vi.fn() + getSelfId: vi.fn(), + canCheckEngineUpdate: vi.fn(), + beginLocalEngineOp: vi.fn(), + clearPendingEngineOp: vi.fn() }, supervisor: { - callProcess: vi.fn() + callProcess: vi.fn(), + hasProcess: vi.fn(() => true), + installOrUpdateEngineRemote: vi.fn(), + sendProcess: vi.fn(), + reportError: vi.fn() } })) @@ -33,6 +41,114 @@ 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('waits for a local node identity before routing an update', async () => { + mocks.supervisor.sendProcess.mockClear() + mocks.supervisor.installOrUpdateEngineRemote.mockClear() + mocks.state.getSelfId.mockReturnValue(null) + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'ollama', + nodeId: 'peer' + }) + expect(mocks.supervisor.sendProcess).not.toHaveBeenCalled() + expect(mocks.supervisor.installOrUpdateEngineRemote).not.toHaveBeenCalled() + expect(mocks.supervisor.reportError).toHaveBeenCalledWith( + 'Select an identified node to update its engine.', + 'warning', + 'engine-cmd:update' + ) + }) +}) + +describe('remote engine update command', () => { + it('routes the update to the selected peer and engine', async () => { + mocks.supervisor.sendProcess.mockClear() + mocks.state.getSelfId.mockReturnValue('self') + mocks.state.canCheckEngineUpdate.mockReturnValue(true) + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'lm-studio', + nodeId: 'peer' + }) + + expect(mocks.state.canCheckEngineUpdate).toHaveBeenCalledWith('peer', 'lm-studio') + expect(mocks.supervisor.installOrUpdateEngineRemote).toHaveBeenCalledWith( + 'peer', + 'lmstudio', + 'lm-studio', + 'update' + ) + expect(mocks.supervisor.sendProcess).not.toHaveBeenCalled() + }) + + it('declines a peer whose engine is unavailable', async () => { + mocks.supervisor.installOrUpdateEngineRemote.mockClear() + mocks.state.getSelfId.mockReturnValue('self') + mocks.state.canCheckEngineUpdate.mockReturnValue(false) + await handleServiceBridgeInvoke('engine:command', { + command: 'update', + engineType: 'lm-studio', + nodeId: 'peer' + }) + + expect(mocks.supervisor.installOrUpdateEngineRemote).not.toHaveBeenCalled() + expect(mocks.supervisor.reportError).toHaveBeenCalledWith( + 'Updating requires a connected, paired node with this engine installed.', + 'warning', + 'engine-cmd:remote:update' + ) + }) +}) + 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..ef01e53ed --- /dev/null +++ b/desktop/tests/modular/engine-update-checks.test.ts @@ -0,0 +1,321 @@ +// 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('engine update checks', () => { + const state = getModularBridgeState() + const check = vi.fn<(nodeId: string, engine: EngineType) => Promise>() + const sixHours = 6 * 60 * 60 * 1000 + let checks: ReturnType + let unsubscribe: (() => void) | undefined + + beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + state.setClusterPeerIds(new Set()) + 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([['local', 'lm-studio']]) + + state.applyEngineManagerStatus(stopped) + await vi.advanceTimersByTimeAsync(0) + state.applyEngineManagerStatus(stopped) + expect(check.mock.calls).toEqual([ + ['local', 'lm-studio'], + ['local', '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([['local', 'vllm']]) + + state.applyEngineManagerStatus(stopped) + expect(check.mock.calls).toEqual([ + ['local', 'vllm'], + ['local', '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([['local', '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 (_node, 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([ + ['local', 'ollama'], + ['local', 'lm-studio'], + ['local', '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([['local', 'lm-studio']]) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...available, nodeId: 'local', engineType: 'ollama' } + ]) + }) + + it('checks installed engines on paired peers and keeps offers scoped to their nodes', async () => { + state.setClusterPeerIds(new Set(['peer'])) + checks = watchEngineUpdates(check) + const installed = { engine: 'ollama', installed: true, running: false } + const inventory = { engines: [installed, { engine: 'vllm', installed: false }] } + state.applyRemoteEngineFacts('stranger', inventory) + state.applyRemoteEngineFacts('peer', inventory) + state.applyRemoteEngineFacts('peer', inventory) + await vi.advanceTimersByTimeAsync(0) + + expect(check.mock.calls).toEqual([ + ['local', 'ollama'], + ['peer', 'ollama'] + ]) + const localOffer = { ...available, nodeId: 'local', engineType: 'ollama' } + const peerOffer = { ...available, nodeId: 'peer', engineType: 'ollama' } + expect(state.getEngineInitialState().updateAvailable).toEqual([localOffer, peerOffer]) + + check.mockClear().mockRejectedValue(new Error('offline')) + state.applyRemoteEngineStatusResult('peer', 'ollama', { ...installed, running: true }) + await vi.advanceTimersByTimeAsync(0) + state.applyRemoteEngineFacts('peer', inventory) + await vi.advanceTimersByTimeAsync(0) + expect(check.mock.calls).toEqual([ + ['peer', 'ollama'], + ['peer', 'ollama'] + ]) + expect(state.getEngineInitialState().updateAvailable).toEqual([localOffer, peerOffer]) + + check.mockClear() + await vi.advanceTimersByTimeAsync(sixHours) + expect(check.mock.calls).toEqual([ + ['local', 'ollama'], + ['peer', 'ollama'] + ]) + check.mockClear() + state.finishRemoteEngineUpdate('peer', 'ollama') + await vi.advanceTimersByTimeAsync(0) + expect(check.mock.calls).toEqual([['peer', 'ollama']]) + expect(state.getEngineInitialState().updateAvailable).toEqual([localOffer]) + }) + + it('discards an in-flight offer when the peer leaves the cluster', async () => { + const pending = Promise.withResolvers() + state.setClusterPeerIds(new Set(['peer'])) + check.mockImplementation(async node => + node === 'peer' ? pending.promise : { updateAvailable: null } + ) + checks = watchEngineUpdates(check) + state.applyRemoteEngineFacts('peer', { engines: [{ engine: 'ollama', installed: true }] }) + expect(check).toHaveBeenCalledWith('peer', 'ollama') + state.setClusterPeerIds(new Set()) + pending.resolve({ updateAvailable: available }) + await vi.advanceTimersByTimeAsync(0) + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + }) + + 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..5358347f8 --- /dev/null +++ b/desktop/tests/modular/engine-update-controls.test.ts @@ -0,0 +1,335 @@ +// 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 { NodeItem } from '@/shared/types/nodes' +import type { IEngineApi } from '@/ui/api/engine-api' +import { AppMessageModal } from '@/ui/components/AppMessageModal' +import { BackendRow } from '@/ui/components/BackendRow/BackendRow' +import { BackendUpdateBanner } from '@/ui/components/BackendRow/BackendUpdateBanner' +import { ErrorModal } from '@/ui/components/ErrorModal' +import { useConnectionStore } from '@/ui/stores/connection.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 { useErrorsStore } from '@/ui/stores/errors.store' +import { useNodesStore } from '@/ui/stores/nodes.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) + const modal = ({ children, open }: { children?: ReactNode; open: boolean }) => + open ? container({ children }) : null + return { ...kit, ModalRoot: modal, 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 +} + +const peer: NodeItem = { + id: 'peer-node', + name: 'Studio workstation', + status: 'active', + ipAddress: '192.0.2.5', + port: 8080, + allIpAddresses: ['192.0.2.5'], + topology: { cpu: { model: 'CPU', cores: 8, threads: 16 }, gpus: [], ram: 32, storage: [] }, + os: 'Linux' +} + +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 }) + useNodesStore.setState({ nodes: new Map() }) + useEngineUpdateAvailableStore.setState({ entries: new Map() }) + vi.restoreAllMocks() + 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 notices independently for each node and engine', () => { + const unsubscribe = subscribeEngineUpdateNotifications(nodeId => + nodeId === peer.id ? peer.name : 'This node' + ) + const peerUpdate = { ...update, nodeId: peer.id } + report(peerUpdate) + 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(peerUpdate) + report({ ...update, latestVersion: '0.10.3' }) + report(lmStudioUpdate) + publishPush('engines:state-changed', { + nodeId: 'local-node', + engineType: 'ollama', + updateAvailable: null + }) + publishPush('engines:state-changed', { + nodeId: peer.id, + engineType: 'ollama', + updateAvailable: null + }) + unsubscribe() + expect(vi.mocked(showOverviewMessage).mock.calls.map(([message]) => message.id)).toEqual([ + 'engine-update:peer-node:ollama:0.10.2', + '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'], + ['engine-update:peer-node:ollama:0.10.2'] + ]) + expect(vi.mocked(showOverviewMessage).mock.calls[1][0].title).toBe('LM Studio update available') +}) + +it('names the peer and opens its engine settings from the vLLM notification', async () => { + const unsubscribe = subscribeEngineUpdateNotifications(() => peer.name) + report({ + ...update, + nodeId: peer.id, + 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') + expect(document.body.textContent).toContain('Studio workstation has 0.10.1 installed') + await act(() => button('Open engine settings')?.click()) + + expect(useOverviewUiStore.getState()).toMatchObject({ + activeTab: 'overview', + focusNodeId: peer.id + }) + expect(onClose).toHaveBeenCalledOnce() +}) + +it('updates the selected peer using its own available version', async () => { + const sendUpdate = vi.fn() + vi.stubGlobal('pairApi', { engines: { update: sendUpdate } }) + vi.spyOn(useEngineStatusStore.getState(), 'initialize').mockResolvedValue() + vi.spyOn(useEngineModelsStore.getState(), 'initialize').mockResolvedValue() + useConnectionStore.setState({ selfId: 'local-node' }) + useNodesStore.setState({ nodes: new Map([[peer.id, peer]]) }) + useEngineUpdateAvailableStore.setState({ + entries: new Map([ + ['local-node:ollama', update], + ['peer-node:ollama', { ...update, nodeId: peer.id, latestVersion: '0.11.0' }] + ]) + }) + await act(() => + root.render( + createElement(BackendRow, { backend: engine, nodeId: peer.id, statusKnown: true }) + ) + ) + expect(document.body.textContent).toContain('Ollama v0.11.0 is available') + await act(() => button('Update')?.click()) + expect(sendUpdate.mock.calls).toEqual([['ollama', peer.id]]) + + await act(() => + useNodesStore.setState({ nodes: new Map([[peer.id, { ...peer, status: 'offline' }]]) }) + ) + expect(button('Update')?.disabled).toBe(true) +}) + +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('identifies the peer to update manually and opens the official Ollama downloads', async () => { + const onUpdate = vi.fn<() => void>() + const external: BackendInfo = { + ...engine, + updateAvailable: { + ...update, + nodeId: peer.id, + installType: 'external', + downloadUrl: 'https://ollama.com/download' + } + } + await act(() => + root.render( + createElement(BackendUpdateBanner, { + backend: external, + remoteNodeName: peer.name, + disabled: false, + onUpdate + }) + ) + ) + expect(document.body.textContent).toContain('Update manually on Studio workstation.') + 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 local update or a reachable peer’s current managed update', async () => { + const retry = vi.fn() + const clear = vi.fn<(id: string) => void>() + vi.stubGlobal('pairApi', { engines: { update: retry }, errors: { clear } }) + 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(() => + useEngineUpdateAvailableStore.setState({ + entries: new Map([ + ['peer-node:lm-studio', { ...update, nodeId: peer.id, engineType: 'lm-studio' }] + ]) + }) + ) + expect(button('Retry')).toBeUndefined() + await act(() => useNodesStore.setState({ nodes: new Map([[peer.id, peer]]) })) + await act(() => button('Retry')?.click()) + expect(retry.mock.calls).toEqual([['lm-studio', peer.id]]) + expect(clear).not.toHaveBeenCalled() + + await act(() => useErrorsStore.setState({ errors: [{ ...failure, nodeId: 'local-node' }] })) + await act(() => button('Retry')?.click()) + expect(retry.mock.calls).toEqual([ + ['lm-studio', peer.id], + ['lm-studio', 'local-node'] + ]) + expect(clear.mock.calls).toEqual([[failure.id]]) +}) diff --git a/desktop/tests/modular/modular-supervisor-readiness.test.ts b/desktop/tests/modular/modular-supervisor-readiness.test.ts index 9d8db5170..1e38d8378 100644 --- a/desktop/tests/modular/modular-supervisor-readiness.test.ts +++ b/desktop/tests/modular/modular-supervisor-readiness.test.ts @@ -10,6 +10,7 @@ import { const mocks = vi.hoisted(() => ({ bridgeState: { handleNotification: vi.fn(), + setClusterPeerIds: vi.fn(), getSelfId: vi.fn(() => null), getProxyPort: vi.fn(() => null) }, diff --git a/desktop/tests/modular/remote-engine-update.test.ts b/desktop/tests/modular/remote-engine-update.test.ts new file mode 100644 index 000000000..8f5ffc39e --- /dev/null +++ b/desktop/tests/modular/remote-engine-update.test.ts @@ -0,0 +1,144 @@ +// 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 type { JsonValue } from '@/electron/service-bridge/json-rpc-subprocess' +import { getModularBridgeState } from '@/electron/service-bridge/modular-state' +import { getModularSupervisor } from '@/electron/service-bridge/modular-supervisor' +import { subscribePush } from '@/electron/service-bridge/push-bus' +import type { EngineType } from '@/shared/types/engines' + +vi.mock('electron', () => ({ + app: { isPackaged: false, getAppPath: () => process.cwd() }, + BrowserWindow: { getAllWindows: () => [] } +})) +vi.mock('@/electron/window', () => ({ createOverviewWindow: vi.fn() })) + +describe('applying a managed update on a peer', () => { + const state = getModularBridgeState() + const supervisor = getModularSupervisor() + const offer = { + installType: 'managed', + currentVersion: '0.4.0', + latestVersion: '0.5.0', + releaseUrl: 'https://lmstudio.ai/changelog/lmstudio' + } + const status = { engine: 'lmstudio', installed: true, running: true, port: 1235 } + const peerStatus = () => + state + .getEngineInitialState() + .statuses.find(s => s.nodeId === 'peer' && s.engineType === 'lm-studio')?.processStatus + + beforeEach(() => { + state.setSelfId('self') + state.setClusterPeerIds(new Set(['peer'])) + state.handleNotification({ + source: 'broker', + method: 'discovery:nodes-changed', + params: { + nodes: [ + { + hostUuid: 'peer', + name: 'Peer', + ipAddress: '192.0.2.71', + port: 14318, + trusted: true, + clustered: true + } + ] + } + }) + state.applyRemoteEngineFacts('peer', { engines: [status] }) + state.applyEngineUpdateCheck('peer', 'lm-studio', { updateAvailable: offer }) + }) + + afterEach(() => { + state.setEngineUpdateRefresher(undefined) + state.setClusterPeerIds(new Set()) + state.clearError('engine-manager:update-failed:lmstudio') + vi.restoreAllMocks() + }) + + it('sends the update to the peer and rechecks its offer after completion', async () => { + const refresh = vi.fn<(engineType?: EngineType, nodeId?: string) => void>() + state.setEngineUpdateRefresher(refresh) + const reply = Promise.withResolvers() + const call = vi.spyOn(supervisor, 'callProcess').mockReturnValue(reply.promise) + + const applying = supervisor.installOrUpdateEngineRemote( + 'peer', + 'lmstudio', + 'lm-studio', + 'update' + ) + expect(call).toHaveBeenCalledWith( + 'broker', + 'engine:remote-update', + { node: 'peer', engine: 'lmstudio' }, + expect.any(Number) + ) + expect(peerStatus()).toBe('installing') + + reply.resolve({ opId: 'update-1', status: { ...status, running: false } }) + await applying + expect(peerStatus()).toBe('stopped') + expect(state.getEngineInitialState().updateAvailable).toEqual([]) + expect(refresh).toHaveBeenCalledWith('lm-studio', 'peer') + }) + + it('restores the peer status and reports a retry on the same peer after rejection', async ({ + onTestFinished + }) => { + const push = vi.fn[0]>() + onTestFinished(subscribePush(push)) + vi.spyOn(supervisor, 'callProcess').mockRejectedValue(new Error('peer update rejected')) + + await supervisor.installOrUpdateEngineRemote('peer', 'lmstudio', 'lm-studio', 'update') + + expect(peerStatus()).toBe('running') + expect(push).toHaveBeenCalledWith({ + channel: 'engines:progress-cleared', + payload: { key: 'peer:lm-studio:install' } + }) + expect(state.getEngineInitialState().updateAvailable).toEqual([ + { ...offer, engineType: 'lm-studio', nodeId: 'peer' } + ]) + expect(state.getErrors()).toEqual([ + expect.objectContaining({ + id: 'engine-manager:update-failed:lmstudio', + message: expect.stringContaining('peer update rejected'), + severity: 'error', + nodeId: 'peer', + engineType: 'lm-studio', + operation: 'update', + action: 'retry' + }) + ]) + }) + + it('publishes the peer’s update download progress and clears it on completion', ({ + onTestFinished + }) => { + const push = vi.fn[0]>() + onTestFinished(subscribePush(push)) + const frame = { node: 'peer', engine: 'lmstudio', op: 'update' } + + state.applyRemoteEngineProgress({ ...frame, stage: 'downloading', percent: 42 }) + expect(push).toHaveBeenCalledWith({ + channel: 'engines:progress-changed', + payload: expect.objectContaining({ + nodeId: 'peer', + engineType: 'lm-studio', + operation: 'install', + status: 'downloading', + percent: 42 + }) + }) + + state.applyRemoteEngineProgress({ ...frame, stage: 'done' }) + expect(push).toHaveBeenCalledWith({ + channel: 'engines:progress-cleared', + payload: { key: 'peer:lm-studio:install' } + }) + }) +}) diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index a6ef99675..d48474cf2 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,39 @@ first. ## Updating and Uninstalling an Engine -PAIR does not currently offer to update an engine, because it does not yet detect -newer engine versions. To move an NVPAIR-installed Ollama or LM Studio to the -vendor's current release, uninstall it and install it again, which keeps your -models as described below. llama.cpp installs the build pinned by your version of -PAIR. Update an engine you installed yourself with its own installer. +The desktop app checks local engines at startup and paired engines when it +first receives the peer's engine list. It checks again every six hours and +when an engine starts or stops. If the release service is unreachable, the +engine continues normally and PAIR keeps any previously reported offer for +that installation. + +When a newer version is available, **Overview** shows a notice once per +machine, engine, and release in that desktop session. Select **Open engine +settings** on the notice 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. + Follow those instructions on the machine where the engine is installed. + +If GitHub rate-limits a release lookup, wait until the time in the error +message, then select **Retry** in the desktop app or press **Shift+U** in +the TUI's engine list. + +| 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 @@ -237,9 +265,11 @@ architecture guide. ## Managing Engines on Other Machines -After systems are paired, you can view another machine's engines from -**Overview** and, where supported, start or stop engines and pull models on that -peer. +After systems are paired, open the peer's **Engine settings** from **Overview**. +You can start and stop engines, pull models, and update a managed engine there. +When you select **Update**, the peer downloads and applies the update on its own +machine. Both machines must run a version of PAIR that supports remote engine +updates for an offer to appear. Some actions stay **local only** on each machine: uninstalling an engine and changing its CORS settings. Perform those on the machine that owns the @@ -309,9 +339,10 @@ the cancel to finish and then starts. ![An engine's model list showing the Load, Eject, and Delete actions against a downloaded model.](assets/onboarding/engine-lifecycle/04-model-actions.png) -On a headless machine the terminal interface covers installing, starting, -stopping, restarting, and uninstalling an engine; pulling a model or cancelling -its download; and listing, loading, unloading, or deleting models. +On a headless machine the terminal interface covers installing, updating, +starting, stopping, restarting, and uninstalling engines. You can also pull, +list, load, unload, or delete models and cancel downloads from the +[node's detail screen](terminal-interface.mdx#look-at-one-machine). PAIR does **not** warm models. Starting an engine does not pre-load models into memory, and it holds nothing ready in advance. Depending on the engine, a model diff --git a/docs/terminal-interface.mdx b/docs/terminal-interface.mdx index f7ebf0728..7925628c6 100644 --- a/docs/terminal-interface.mdx +++ b/docs/terminal-interface.mdx @@ -273,6 +273,7 @@ between with `h` / `l`: | Key | Action | | --- | --- | | `i` | Install | +| `U` (Shift+U) | Apply an available managed update on the selected machine | | `s` | Start | | `x` | Stop | | `r` | Restart (this machine only) | @@ -281,6 +282,17 @@ between with `h` / `l`: | `p` | Change the proxy port | | `a` | Edit the startup arguments | +An engine row shows when an update is available. Select it to see the installed +and available versions. For a PAIR-managed engine, press `U` to start the update +immediately. For an externally managed engine, follow the displayed vendor link +on the machine where the engine is installed. A paired machine checks its own +installation and runs its own update. + +The terminal checks installed engines when you open the node, after an engine +starts or stops, and every six hours while the node stays open. Checks fail +quietly when the release service is unreachable. Set `NVPAIR_NO_UPDATE_CHECK=1` +to disable these background checks. + Each engine has two ports, and they are easy to confuse: - **ENGINE PORT** is where the engine itself listens. PAIR talks to it there. @@ -448,8 +460,8 @@ time you run it. Nothing is reported when the check cannot reach the network, because an unreachable feed is not news. To stop it checking at all, set `NVPAIR_NO_UPDATE_CHECK=1` -before starting `nvpair`. A copy you build yourself with `go build` never -checks. One built with `services/build.sh` or `services/build.bat` does, because +before starting `nvpair`. A copy you build yourself with `go build` skips the +PAIR release check. One built with `services/build.sh` or `services/build.bat` checks, because those scripts record the release number in it. ## Look at Errors and Logs diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 2f41e9393..f4cd16092 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) | @@ -330,6 +332,8 @@ Requests (caller → service): | `engine:models` | — | `{ models: [string], modelsByEngine: { : [string] }, loadedByEngine: { : [string] }, downloadedByEngine: { : [string] } }` — the flat de-duplicated union of every running engine's models, the per-engine breakdown keyed by engine name, and the per-engine set of models currently **loaded in memory** (all normalized from each engine's `list_models` / `loaded_models` action `result` spec). `modelsByEngine` carries a key for every running engine whose inventory was successfully queried, including an empty list = "running, no models available"; a missing key means not running / not queryable / invalid response. `loadedByEngine` uses the same known-empty distinction for residency and also omits engines with no loaded endpoint. For an engine with `advertised_models: "loaded"`, `modelsByEngine` holds only the served model's name, which is what a request may be routed to, and `downloadedByEngine` holds its `list_models` inventory, read whenever it is installed, running or not, so a model manager keeps its rows after an Eject. Its `loadedByEngine` names the served model by its `--model` (the `root` of vLLM's `/v1/models`), not a `--served-model-name` alias, so it matches the inventory, and is `[]` while it is stopped. A missing `downloadedByEngine` key means the inventory was not read. The `/v1/models` HTTP surface returns the same shape. | | `engine:remote-get-installed` | `{ node }` | `{ engines: [EngineStatus] }` fetched from the remote node over `ec` mTLS | | `engine:remote-install` | `{ node, engine, start? }` | `{ opId, status: EngineStatus }` after the remote install (live progress via `engine:remote-progress`) | +| `engine:remote-check-updates` | `{ node, engine }` | The target's `engine:check-updates` result. The target identifies the installed version, applicable release, and vendor URL for an external installation. | +| `engine:remote-update` | `{ node, engine }` | `{ opId, status: EngineStatus }` after the target applies a managed update. `engine:remote-progress` carries `op: "update"`. | | `engine:remote-pull-model` | `{ node, engine, model?, params?, opId? }` | `{ opId, result }` after the remote pull (live progress via `engine:remote-progress`). An `opId`, under the same rules as `engine:action`'s, names the pull in place of a minted one: on its `engine:remote-progress` frames, in the reply, and to the peer. Held until every `engine:remote-cancel-pull` of that download sent before it has ended, so a retry cannot reach the peer ahead of the cancel it follows and be stopped by it | | `engine:remote-cancel-pull` | `{ node, engine, model }` | the remote cancellation result. Held until every `engine:remote-pull-model` of that download sent before it has been accepted by the peer or has ended, so a cancel dispatched right behind a pull, or behind a duplicate of it, cannot reach the peer first | | `engine:remote-start` | `{ node, engine, port? }` | `EngineStatus` from the remote node (always the manifest's `runtime.bind`; no per-call bind override on the remote path) | @@ -399,7 +403,7 @@ stop runs as no download yet, so that download's frames leave it out, and a client that names its requests can tell the cancelled download's late frames from its retry's, which name the same engine and model), `engine:remote-progress{opId, node, engine, model, op, stage, percent?, message, opIds?}` -(relayed live progress for a remote install/pull, a pull's terminal frame +(relayed live progress for a remote install, update, or pull, a pull's terminal frame included, which the initiator sends itself when the peer's stream dropped it; `opId` is the one the client named an `engine:remote-pull-model` with, or else one minted for the operation; only the last of this machine's pulls of one @@ -444,7 +448,7 @@ The `engine:remote-*` methods are the client half of remote engine management: engine-manager resolves the target `node` in an `ec` peer directory (fed by its own `discovery:subscribe{services:[ec]}` to the broker relay), dials that peer's `ec` surface over pin-based cluster mTLS, and — for -`remote-install` / `remote-pull-model` — keys the operation by an `opId`, the +`remote-install`, `remote-update`, and `remote-pull-model` — keys the operation by an `opId`, the one the caller named a pull with or else one it mints, relays each streamed progress frame up as `engine:remote-progress`, and settles the request with the terminal result. Each NDJSON progress or terminal frame uses the shared @@ -453,7 +457,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. @@ -753,6 +757,8 @@ Endpoints (all under `/v1`): |---|---|---| | `GET /v1/engines` | JSON | remote `engine:get-installed` | | `POST /v1/engines/install` | NDJSON stream | remote install (+ optional start) with live progress | +| `POST /v1/engines/check-updates` | JSON | accepts `{ engine }` and returns the target's `{ updateAvailable }` | +| `POST /v1/engines/update` | NDJSON stream | accepts `{ engine, opId }`, applies a managed update on the target, and returns its final status | | `POST /v1/models/pull` | NDJSON stream | remote model pull with live progress | | `POST /v1/models/cancel-pull` | JSON | remote `engine:cancel-pull` | | `POST /v1/engines/start` | JSON | remote start → `EngineStatus` | diff --git a/services/nvpair-engine-manager/controlserver.go b/services/nvpair-engine-manager/controlserver.go index 7cf7c968c..03474624c 100644 --- a/services/nvpair-engine-manager/controlserver.go +++ b/services/nvpair-engine-manager/controlserver.go @@ -62,6 +62,8 @@ func (s *controlServer) mux() *http.ServeMux { s.settingsRoutes(mux) mux.HandleFunc(controlEnginesPath, s.requirePin(s.handleEngines)) mux.HandleFunc(controlInstallPath, s.requirePin(s.handleInstall)) + mux.HandleFunc(controlCheckUpdatesPath, s.requirePin(s.handleCheckUpdates)) + mux.HandleFunc(controlUpdatePath, s.requirePin(s.handleUpdate)) mux.HandleFunc(controlPullPath, s.requirePin(s.handlePull)) mux.HandleFunc(controlCancelPullPath, s.requirePin(s.handleCancelPull)) mux.HandleFunc(controlLoadPath, s.requirePin(s.handleLoad)) diff --git a/services/nvpair-engine-manager/controlstream.go b/services/nvpair-engine-manager/controlstream.go index 313f78a0b..b771422cf 100644 --- a/services/nvpair-engine-manager/controlstream.go +++ b/services/nvpair-engine-manager/controlstream.go @@ -4,7 +4,7 @@ package main // controlstream.go holds the long-running ec endpoints that stream live -// progress: remote install and remote model pull. Both return a chunked +// progress: remote install, engine update, and model pull. Each returns a chunked // application/x-ndjson body — zero or more {"type":"progress",...} frames as the // operation advances, terminated by exactly one {"type":"result",...} or // {"type":"error",...} frame. The initiating node relays each progress frame up @@ -154,9 +154,8 @@ func (s *controlServer) handlePull(w http.ResponseWriter, r *http.Request) { // frame (or an error frame) last. run executes on the request context, so a // disconnected initiator cancels the operation. // -// A pull's stream carries only the frames of the download its request runs -// as, which download reports; an install's, with no download, carries all of -// the engine's. +// A pull streams its claimed download. An update streams installer steps +// emitted while that request owns the engine's operation lock. func (s *controlServer) streamOp(w http.ResponseWriter, r *http.Request, opID, engine, op string, download func() uint64, run func(ctx context.Context) (streamFrame, error)) { flusher, ok := w.(http.Flusher) if !ok { @@ -167,8 +166,16 @@ func (s *controlServer) streamOp(w http.ResponseWriter, r *http.Request, opID, e w.WriteHeader(http.StatusOK) flusher.Flush() - events, cancelSub := s.exec.progress.subscribe(engine) - defer cancelSub() + var events <-chan ProgressEvent + if op == "update" { + progress := make(chan ProgressEvent, 64) + events = progress + r = r.WithContext(context.WithValue(r.Context(), remoteUpdateProgressKey{}, progress)) + } else { + var unsubscribe func() + events, unsubscribe = s.exec.progress.subscribe(engine) + defer unsubscribe() + } enc := json.NewEncoder(w) // The subscription is per engine, so a pull's stream also sees the diff --git a/services/nvpair-engine-manager/controlupdate_test.go b/services/nvpair-engine-manager/controlupdate_test.go new file mode 100644 index 000000000..679170ecc --- /dev/null +++ b/services/nvpair-engine-manager/controlupdate_test.go @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "nvpair-shared/clustertrust" + "nvpair-shared/clustertrusttest" + "nvpair-shared/noderec" +) + +func TestRemoteUpdate_ChecksAndUpdatesOnlyTheSelectedPeer(t *testing.T) { + controllerDir, targetDir := t.TempDir(), t.TempDir() + clustertrusttest.Join(t, controllerDir, "cluster", "controller") + clustertrusttest.Join(t, targetDir, "cluster", "target") + writePinFromCert(t, controllerDir, "target", filepath.Join(targetDir, "node.crt")) + writePinFromCert(t, targetDir, "controller", filepath.Join(controllerDir, "node.crt")) + + controller, controllerBinary := ollamaUpdateFixture(t, "1.1.0", false) + require.NoError(t, os.WriteFile(controllerBinary+".version", []byte("0.9.0"), 0o600)) + target, targetBinary := ollamaUpdateFixture(t, "1.1.0", false) + mesh := clustertrust.Open(targetDir) + server := httptest.NewUnstartedServer((&controlServer{exec: target, mesh: mesh}).mux()) + server.TLS = mesh.ServerTLSConfig() + server.StartTLS() + t.Cleanup(server.Close) + + var output bytes.Buffer + manager := NewManager(NewCodec(&output), controller, clustertrust.Open(controllerDir)) + t.Cleanup(manager.remoteHTTP.CloseIdle) + t.Cleanup(manager.readyHTTP.CloseIdle) + addr, err := net.ResolveTCPAddr("tcp", server.Listener.Addr().String()) + require.NoError(t, err) + manager.peers.set([]noderec.DirectoryNode{{ + HostUUID: "target-host", ClusterUUID: "target", IP: addr.IP.String(), + IdentityVerification: noderec.IdentityPinned, Trusted: true, + Services: map[noderec.ServiceKey]noderec.ServiceStatus{noderec.ServiceEngineControl: {Port: addr.Port}}, + }}) + id := json.RawMessage("1") + request := &Message{ID: &id, Method: "engine:remote-check-updates", Params: json.RawMessage(`{"node":"target-host","engine":"ollama"}`)} + manager.runRemote(t.Context(), request, remoteOrder{}) + var check Message + require.NoError(t, json.NewDecoder(&output).Decode(&check)) + require.Nil(t, check.Error) + assert.JSONEq(t, `{"updateAvailable":{"currentVersion":"1.0.0","latestVersion":"1.1.0","installType":"managed","releaseUrl":"https://github.com/ollama/ollama/releases/tag/v1.1.0"}}`, string(check.Result)) + + request.Method = "engine:remote-update" + manager.runRemote(t.Context(), request, remoteOrder{}) + var progress []remoteProgress + var updated struct { + OpID string `json:"opId"` + Status EngineStatus `json:"status"` + } + decoder := json.NewDecoder(&output) + for decoder.More() { + var msg Message + require.NoError(t, decoder.Decode(&msg)) + require.Nil(t, msg.Error) + if msg.ID != nil { + require.NoError(t, json.Unmarshal(msg.Result, &updated)) + assert.False(t, decoder.More(), "the request ends with its result") + break + } + require.Equal(t, "engine:remote-progress", msg.Method) + var event remoteProgress + require.NoError(t, json.Unmarshal(msg.Params, &event)) + progress = append(progress, event) + } + require.NotEmpty(t, updated.OpID) + assert.Equal(t, "ollama", updated.Status.Engine) + assert.True(t, updated.Status.Installed) + assert.False(t, updated.Status.Running) + require.NotEmpty(t, progress) + for _, event := range progress { + assert.Equal(t, "target-host", event.Node) + assert.Equal(t, "ollama", event.Engine) + assert.Equal(t, "update", event.Op) + assert.Equal(t, updated.OpID, event.OpID) + } + targetVersion, err := ollamaBinaryVersion(t.Context(), targetBinary) + require.NoError(t, err) + assert.Equal(t, "1.1.0", targetVersion) + controllerVersion, err := ollamaBinaryVersion(t.Context(), controllerBinary) + require.NoError(t, err) + assert.Equal(t, "0.9.0", controllerVersion) +} + +func TestControlUpdate_OffersVendorDownloadAndRefusesToReplaceExternalEngine(t *testing.T) { + target, bin := ollamaUpdateFixture(t, "1.1.0", false) + require.NoError(t, os.Remove(installMarkerPath(filepath.Dir(bin)))) + server := &controlServer{exec: target} + check := httptest.NewRecorder() + server.handleCheckUpdates(check, httptest.NewRequest(http.MethodPost, controlCheckUpdatesPath, strings.NewReader(`{"engine":"ollama"}`))) + require.Equal(t, http.StatusOK, check.Code) + assert.JSONEq(t, `{"updateAvailable":{"currentVersion":"1.0.0","latestVersion":"1.1.0","installType":"external","downloadUrl":"https://ollama.com/download","releaseUrl":"https://github.com/ollama/ollama/releases/tag/v1.1.0"}}`, check.Body.String()) + + update := httptest.NewRecorder() + server.handleUpdate(update, httptest.NewRequest(http.MethodPost, controlUpdatePath, strings.NewReader(`{"engine":"ollama","opId":"external-update"}`))) + frames := decodeFrames(t, update.Body.String()) + require.NotEmpty(t, frames) + terminal := frames[len(frames)-1] + assert.Equal(t, "error", terminal.Type) + assert.Equal(t, "external-update", terminal.OpID) + assert.Contains(t, terminal.Message, "PAIR-managed") + version, err := ollamaBinaryVersion(t.Context(), bin) + require.NoError(t, err) + assert.Equal(t, "1.0.0", version) +} + +func TestRemoteUpdate_RelaysOnlyProgressFromItsOwnOperation(t *testing.T) { + exec := newTestExecutor(t, testEngineManifest(fakeEngineBin)) + var localProgress installProgressRecorder + exec.emit = localProgress.emit + state, err := exec.state("fake") + require.NoError(t, err) + // An install already holds the engine lock when the peer subscribes. + state.lockOperation() + installEvents, unsubscribe := exec.progress.subscribe("fake") + defer unsubscribe() + rec := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, controlUpdatePath, nil) + (&controlServer{exec: exec}).streamOp(rec, request, "op1", "fake", "update", nil, func(ctx context.Context) (streamFrame, error) { + exec.emitInstallProgress("fake", "installing", 80) + state.unlockOperation() + err := exec.withEngineUpdate(ctx, "fake", func(context.Context, *engineState) error { + exec.emitPullProgress(ProgressEvent{Engine: "fake", Op: "pull", Model: "demo", Stage: "downloading", Percent: 30}) + exec.emitInstallProgress("fake", "verified", 50) + return nil + }) + exec.emitInstallProgress("fake", "downloading", 10) + return streamFrame{Type: "result"}, err + }) + + require.Equal(t, []streamFrame{ + {Type: "progress", OpID: "op1", Engine: "fake", Op: "update", Stage: "verified", Percent: 50}, + {Type: "progress", OpID: "op1", Engine: "fake", Op: "update", Stage: "done", Percent: 100}, + {Type: "result"}, + }, decodeFrames(t, rec.Body.String())) + assert.Equal(t, []ProgressEvent{ + {Engine: "fake", Op: "install", Stage: "installing", Percent: 80}, + {Engine: "fake", Op: "pull", Model: "demo", Stage: "downloading", Percent: 30}, + {Engine: "fake", Op: "install", Stage: "downloading", Percent: 10}, + }, publishedFrames(installEvents), "an install subscriber must not receive the update's installer frames") + assert.Contains(t, localProgress.events, map[string]any{"engine": "fake", "stage": "verified", "percent": 50}) + assert.Contains(t, localProgress.events, map[string]any{"engine": "fake", "stage": "done", "percent": 100}) +} + +func TestControlUpdateRoutes_RejectUnpinnedRequests(t *testing.T) { + mux := (&controlServer{mesh: clustertrust.Open(t.TempDir())}).mux() + for _, path := range []string{controlCheckUpdatesPath, controlUpdatePath} { + t.Run(path, func(t *testing.T) { + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"engine":"ollama"}`))) + assert.Equal(t, http.StatusForbidden, rec.Code) + }) + } +} diff --git a/services/nvpair-engine-manager/controlupdates.go b/services/nvpair-engine-manager/controlupdates.go new file mode 100644 index 000000000..42a756954 --- /dev/null +++ b/services/nvpair-engine-manager/controlupdates.go @@ -0,0 +1,69 @@ +// 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" + + "nvpair-shared/engines" +) + +const ( + controlCheckUpdatesPath = "/v1/engines/check-updates" + controlUpdatePath = "/v1/engines/update" +) + +type engineUpdateRequest struct { + Engine string `json:"engine"` + OpID string `json:"opId,omitempty"` +} + +func readUpdateRequest(w http.ResponseWriter, r *http.Request) (req engineUpdateRequest, ok bool) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return req, false + } + if err := json.NewDecoder(io.LimitReader(r.Body, maxControlBody)).Decode(&req); err != nil { + http.Error(w, "invalid JSON body", http.StatusBadRequest) + return req, false + } + if _, ok := engines.ByName(req.Engine); !ok { + http.Error(w, fmt.Sprintf("unknown engine %q", req.Engine), http.StatusBadRequest) + return req, false + } + return req, true +} + +func (s *controlServer) handleCheckUpdates(w http.ResponseWriter, r *http.Request) { + req, ok := readUpdateRequest(w, r) + if !ok { + return + } + update, err := s.exec.CheckEngineUpdate(r.Context(), req.Engine) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(engineUpdateResult{UpdateAvailable: update}) +} + +func (s *controlServer) handleUpdate(w http.ResponseWriter, r *http.Request) { + req, ok := readUpdateRequest(w, r) + if !ok { + return + } + s.streamOp(w, r, req.OpID, req.Engine, "update", nil, func(ctx context.Context) (streamFrame, error) { + if err := s.exec.UpdateEngine(ctx, req.Engine); err != nil { + return streamFrame{}, err + } + st, err := s.exec.Status(req.Engine) + return streamFrame{Type: "result", OpID: req.OpID, Engine: req.Engine, Op: "update", Status: &st}, err + }) +} 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..bb1934c4a --- /dev/null +++ b/services/nvpair-engine-manager/engine_updates.go @@ -0,0 +1,373 @@ +// 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 engineUpdateResult struct { + UpdateAvailable *EngineUpdateInfo `json:"updateAvailable"` +} + +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() + // An update waiting behind another install or update must only stream + // progress emitted while it owns this engine's operation lock. + if progress, ok := ctx.Value(remoteUpdateProgressKey{}).(chan ProgressEvent); ok { + e.progress.setUpdateStream(engine, progress) + defer e.progress.setUpdateStream(engine, nil) + } + // 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..0653a90cc 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, engineUpdateResult{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": @@ -359,6 +370,7 @@ func (m *Manager) handleMessage(ctx context.Context, msg *Message) { go func() { m.respondOrErr(msg, nil, wait(ctx)) }() case "engine:remote-get-installed", "engine:remote-install", "engine:remote-pull-model", + "engine:remote-check-updates", "engine:remote-update", "engine:remote-load-model", "engine:remote-unload-model", "engine:remote-delete-model", "engine:remote-cancel-pull", "engine:remote-start", "engine:remote-stop": // Place a remote pull, and a cancel chasing one, here for the same @@ -449,6 +461,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 +608,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/progress.go b/services/nvpair-engine-manager/progress.go index dc4bc027e..2fd7d731d 100644 --- a/services/nvpair-engine-manager/progress.go +++ b/services/nvpair-engine-manager/progress.go @@ -12,7 +12,7 @@ import "sync" type ProgressEvent struct { Model string `json:"model,omitempty"` Engine string `json:"engine"` - Op string `json:"op"` // "install" | "pull" + Op string `json:"op"` // "install" | "update" | "pull" Stage string `json:"stage,omitempty"` Percent int `json:"percent"` Message string `json:"message,omitempty"` @@ -49,9 +49,10 @@ func wirePercentIncluded(pct int) bool { // harmless — each stream's authoritative terminal result is the out-of-band // final frame, never a hub frame. type progressHub struct { - mu sync.Mutex - next int - subs map[int]*progressSub + mu sync.Mutex + next int + subs map[int]*progressSub + updates map[string]chan<- ProgressEvent } type progressSub struct { @@ -60,7 +61,17 @@ type progressSub struct { } func newProgressHub() *progressHub { - return &progressHub{subs: make(map[int]*progressSub)} + return &progressHub{subs: make(map[int]*progressSub), updates: make(map[string]chan<- ProgressEvent)} +} + +type remoteUpdateProgressKey struct{} + +// Updates reuse the installer. Its progress belongs exclusively to the remote +// request while withEngineUpdate owns the engine's lifecycle lock. +func (h *progressHub) setUpdateStream(engine string, progress chan<- ProgressEvent) { + h.mu.Lock() + defer h.mu.Unlock() + h.updates[engine] = progress } // subscribe registers interest in one engine's progress (empty engine = all). @@ -89,6 +100,14 @@ func (h *progressHub) subscribe(engine string) (<-chan ProgressEvent, func()) { func (h *progressHub) publish(ev ProgressEvent) { h.mu.Lock() defer h.mu.Unlock() + if progress := h.updates[ev.Engine]; progress != nil && ev.Op == "install" { + ev.Op = "update" + select { + case progress <- ev: + default: + } + return + } for _, sub := range h.subs { if sub.engine != "" && sub.engine != ev.Engine { continue 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/remote.go b/services/nvpair-engine-manager/remote.go index 5b6cd4168..f4978e951 100644 --- a/services/nvpair-engine-manager/remote.go +++ b/services/nvpair-engine-manager/remote.go @@ -441,6 +441,9 @@ func (m *Manager) runRemote(ctx context.Context, msg *Message, order remoteOrder m.codec.RespondError(msg.ID, -32602, "node is required") return } + if (msg.Method == "engine:remote-check-updates" || msg.Method == "engine:remote-update") && !m.validUpdateEngine(msg, p.Engine) { + return + } peer, ok := m.peers.lookup(p.Node) if !ok { m.codec.RespondError(msg.ID, -32000, "node "+p.Node+" is not a discovered ec peer") @@ -457,14 +460,29 @@ func (m *Manager) runRemote(ctx context.Context, msg *Message, order remoteOrder res, err := client.getEngines(ctx) m.respondOrErr(msg, res, err) - case "engine:remote-install": + case "engine:remote-check-updates": + ctx, cancel := context.WithTimeout(ctx, remoteResponseHeaderTimeout) + defer cancel() + data, err := client.postJSON(ctx, controlCheckUpdatesPath, p.Engine, engineUpdateRequest{Engine: p.Engine}) + var result engineUpdateResult + if err == nil { + err = json.Unmarshal(data, &result) + } + m.respondOrErr(msg, result, err) + + case "engine:remote-install", "engine:remote-update": if p.Engine == "" { m.codec.RespondError(msg.ID, -32602, "engine is required") return } opID := newOpID() - body := installRequest{OpID: opID, Engine: p.Engine, Start: p.Start} - terminal, err := client.stream(ctx, controlInstallPath, body, m.remoteProgressFn(opID, peer.nodeID), nil) + path := controlInstallPath + var body any = installRequest{OpID: opID, Engine: p.Engine, Start: p.Start} + if msg.Method == "engine:remote-update" { + path = controlUpdatePath + body = engineUpdateRequest{OpID: opID, Engine: p.Engine} + } + terminal, err := client.stream(ctx, path, body, m.remoteProgressFn(opID, peer.nodeID), nil) if err != nil { m.codec.RespondError(msg.ID, -32000, err.Error()) return diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index ad6b4213a..0ba4ba564 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 | @@ -330,6 +332,8 @@ Requests (caller → service): | `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [CatalogModel], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**. Ollama, LM Studio, and vLLM have fixed sources; llama.cpp uses its selected source. Ollama's is compiled in (`catalog/ollama-models.json`, no network), LM Studio's is the `lmstudio-community` Hugging Face org fetched live and cached, and llama.cpp's Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched live and cached, offered as `repo:Q4_K_M`. vLLM offers open, text-generating safetensors repos from Hugging Face. Both llama.cpp and vLLM are `searchable`: a `query` searches llama.cpp's selected source for GGUF repos or Hugging Face for vLLM safetensors repos, each query cached on its own, and is echoed back; a query over 100 characters is an error rather than being shortened; other sources ignore it and return their whole list. `platform` and `arch` are the GOOS and GOARCH the models will be installed on; omitting both means this host, and naming a platform without an arch leaves the arch unknown rather than borrowing this host's. `appleOnly` rows (MLX) are kept only for a `darwin`/`arm64` target. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame — every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | | `engine:remote-get-installed` | `{ node }` | `{ engines: [EngineStatus] }` from the remote node | | `engine:remote-install` | `{ node, engine, start? }` | `{ opId, status }` after the remote install | +| `engine:remote-check-updates` | `{ node, engine }` | The target's `engine:check-updates` result, including its vendor URL for an external installation. A failed check returns an error. | +| `engine:remote-update` | `{ node, engine }` | `{ opId, status: EngineStatus }` after the target updates its managed installation. Progress is published as `engine:remote-progress` with `op: "update"`. | | `engine:remote-pull-model` | `{ node, engine, model?, params?, opId? }` | `{ opId, result }` after the remote pull; `opId` is the caller's, or one minted for it (§14) | | `engine:remote-load-model` | `{ node, engine, model }` | the remote action result | | `engine:remote-unload-model` | `{ node, engine, model }` | the remote action result | @@ -357,7 +361,7 @@ return a partial list. `GET /v1/models` instead returns 503 in those cases, so peers keep their previous model list. If only one engine's model-list action fails, the HTTP response still includes results from engines that succeeded. -Notifications (service → caller): `ready{version}`, `engine:state-changed{EngineStatus}`, `engine:models-changed{engine, models}` (pushed when an engine's served, loaded-in-memory or downloaded model list changes; `models` is the full `engine:models` shape), `engine:install-progress{engine, stage, percent?, error?}` (`error` on the terminal `failed` frame), `engine:pull-progress{engine, model, op, stage, percent?, message, opIds?}` (live progress for a local model pull driven via `engine:action{action:"pull_model"}` — the local counterpart of `engine:remote-progress`; `opIds` names the requests the frame speaks for by the `opId` each was sent with, and is absent when none named one), `engine:remote-progress{opId, node, engine, model, op, stage, percent?, message, opIds?}` (live progress relayed from a remote install/pull; `opId` is the one an `engine:remote-pull-model` was sent with, or else one minted for the operation, and `opIds`, on the frame a pull's download ends on, names the download's other pulls that ended here before that pull did; `model` is set for a pull and absent for an install), and `errors:report` / `errors:clear` (consumed by `nvpair-errors` via the Broker). `install` / `start` / `stop` / `restart` / `action` / `remote-*` each run in their own goroutine so the read loop never blocks; their responses arrive when the op completes. +Notifications (service → caller): `ready{version}`, `engine:state-changed{EngineStatus}`, `engine:models-changed{engine, models}` (pushed when an engine's served, loaded-in-memory or downloaded model list changes; `models` is the full `engine:models` shape), `engine:install-progress{engine, stage, percent?, error?}` (`error` on the terminal `failed` frame), `engine:pull-progress{engine, model, op, stage, percent?, message, opIds?}` (live progress for a local model pull driven via `engine:action{action:"pull_model"}` — the local counterpart of `engine:remote-progress`; `opIds` names the requests the frame speaks for by the `opId` each was sent with, and is absent when none named one), `engine:remote-progress{opId, node, engine, model, op, stage, percent?, message, opIds?}` (live progress relayed from a remote install, update, or pull; `opId` is the one an `engine:remote-pull-model` was sent with, or else one minted for the operation, and `opIds`, on the frame a pull's download ends on, names the download's other pulls that ended here before that pull did; `model` is set for a pull and absent for an install or update), and `errors:report` / `errors:clear` (consumed by `nvpair-errors` via the Broker). `install` / `update` / `start` / `stop` / `restart` / `action` / `remote-*` each run in their own goroutine so the read loop never blocks; their responses arrive when the op completes. `percent` on all three progress notifications follows one rule: it is present only when the step is measurable (download bytes, byte-progress pulls) or terminal (`100` on install `done` / `already-installed`, `-1` on install `failed` and pull `error`). An indeterminate step omits it — the install `verified` and `installing` stages always do, because the install command is opaque — and a consumer renders the stage alone rather than a percentage. @@ -377,11 +381,11 @@ Example `engine:pull-progress` (stdout): - `manifest_version` gates manifest-schema evolution: unknown optional fields are ignored (backward-compatible growth); a version higher than supported is rejected. ### 7.2 Remote engine management (the `ec` surface) -With `--control-port` and a clustered `--cluster-dir`, engine-manager serves a cluster-scoped remote-control surface over pin-based mTLS (`nvpair-shared/clustertrust`): it presents this node's cluster leaf, requires a client cert, and `403`s any caller that isn't a byte-for-byte pinned cluster peer. The listener is bound whenever `--control-port` is set and admits callers by live membership — its leaf is resolved per handshake, so an unclustered node presents none and every handshake is refused — so no restart is needed on `cluster:identity-changed`; the broker registers `ec` whenever a cluster dir is configured. Routes under `/v1`: `GET /engines`, streaming `POST /engines/install` and `/models/pull` (chunked NDJSON — zero+ `{"type":"progress"}` frames then one terminal `{"type":"result"}`/`{"type":"error"}` frame; a pull's stream carries only the frames of the download its request runs as, and its progress frames and result name that download in `download`, the peer's ID for it), non-streaming `POST /models/{load,unload,delete,cancel-pull}`, and non-streaming `POST /engines/{start,stop}` returning `EngineStatus`. +With `--control-port` and a clustered `--cluster-dir`, engine-manager serves a cluster-scoped remote-control surface over pin-based mTLS (`nvpair-shared/clustertrust`): it presents this node's cluster leaf, requires a client cert, and `403`s any caller that isn't a byte-for-byte pinned cluster peer. The listener is bound whenever `--control-port` is set and admits callers by live membership — its leaf is resolved per handshake, so an unclustered node presents none and every handshake is refused — so no restart is needed on `cluster:identity-changed`; the broker registers `ec` whenever a cluster dir is configured. Routes under `/v1`: `GET /engines`, streaming `POST /engines/install`, `/engines/update`, and `/models/pull` (chunked NDJSON — zero+ `{"type":"progress"}` frames then one terminal `{"type":"result"}`/`{"type":"error"}` frame; a pull's stream carries only the frames of the download its request runs as, and its progress frames and result name that download in `download`, the peer's ID for it), non-streaming `POST /engines/check-updates` returning `{ updateAvailable }`, non-streaming `POST /models/{load,unload,delete,cancel-pull}`, and non-streaming `POST /engines/{start,stop}` returning `EngineStatus`. The `engine:remote-*` methods are the client half. Engine-manager subscribes to the broker relay with `discovery:subscribe{services:[ec]}` and replaces its `ec` directory from each `discovery:nodes` snapshot. Admission requires `identityVerification: "local"`, or `identityVerification: "pinned"` with `trusted: true`, together with an `ec` service, a nonzero service port, and at least one candidate address. Entries are keyed by verified `hostUuid`; owned local records need no peer pin for directory admission, and unverified records are excluded. -For each call, engine-manager resolves the target `node` from that directory, refreshes the live mesh, and requires clustered membership and a current target pin before dialing the `ec` surface over mTLS. It relays each streamed progress frame up as `engine:remote-progress` (keyed by the `opId` the caller named a pull with, or else a minted one) and settles the request on the terminal frame. Remote install/pull run for the operation's full duration (no broker-imposed timeout); remote stop and model unload are fast request/response. Remote start, model delete, Ollama and vLLM model loads (a vLLM load restarts the engine on the new model), and download cancel can answer only after slow work on the peer — an engine reaching readiness, a model loading, a download stopping — so they use the readiness-sized response budget, and remote start waits for the engine's bounded readiness result. +For each call, engine-manager resolves the target `node` from that directory, refreshes the live mesh, and requires clustered membership and a current target pin before dialing the `ec` surface over mTLS. It relays each streamed progress frame up as `engine:remote-progress` (keyed by the `opId` the caller named a pull with, or else a minted one) and settles the request on the terminal frame. Remote install, update, and pull run for the operation's full duration (no broker-imposed timeout); remote stop and model unload are fast request/response. Remote start, model delete, Ollama and vLLM model loads (a vLLM load restarts the engine on the new model), and download cancel can answer only after slow work on the peer — an engine reaching readiness, a model loading, a download stopping — so they use the readiness-sized response budget, and remote start waits for the engine's bounded readiness result. The remote client reads NDJSON one line at a time with the shared worker-path 8 MiB buffer limit (`remoteStreamFrameBytes = maxFrameBytes`), including the line 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-tui/README.md b/services/nvpair-tui/README.md index 7c918daff..35cb5fb67 100644 --- a/services/nvpair-tui/README.md +++ b/services/nvpair-tui/README.md @@ -110,6 +110,15 @@ ships in `cli-bin` and the app's updater replaces it. which its progress reports carry, so a late report from the ended download is not taken for the new one's and does not bring the ended one back. +Opening a local or paired node checks its installed engines for updates. The +TUI checks again when an engine starts or stops and every six hours while the +node detail screen is open. A newer release appears as **update** in the +**Installed** column. Select the engine to see its installed and available +versions. For a PAIR-managed engine, press uppercase `U` in **Engines** to +install the update on the selected node. For an external installation, the +detail screen shows the vendor's update URL. Checks fail quietly offline. +`NVPAIR_NO_UPDATE_CHECK` disables automatic checks. + `p` opens a catalog browser over the engine's downloadable models, served by the backend's `engine:catalog`. Sorting (`o`) is local. So is filtering (`/`) for a source that cannot search, such as Ollama's list of thousands of entries. For diff --git a/services/nvpair-tui/ui/engineswire.go b/services/nvpair-tui/ui/engineswire.go index e052c411d..19bbed409 100644 --- a/services/nvpair-tui/ui/engineswire.go +++ b/services/nvpair-tui/ui/engineswire.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "strconv" + "time" "nvpair-shared/engines" "nvpair-tui/rpc" @@ -65,10 +66,11 @@ type engineOp struct { // engineOps are the lifecycle operations, keyed by the local method name. The // remote variants take a node and cover a deliberately smaller set: the manager -// has remote install/start/stop but no remote restart, uninstall, or port +// has remote install/update/start/stop but no remote restart, uninstall, or port // change, because those need process ownership on the target host. var engineOps = map[string]engineOp{ "install": {method: "engine:install", what: "install"}, + "update": {method: "engine:update", what: "update"}, "start": {method: "engine:start", what: "start"}, "stop": {method: "engine:stop", what: "stop"}, "restart": {method: "engine:restart", what: "restart", localOnly: true}, @@ -77,9 +79,11 @@ var engineOps = map[string]engineOp{ // remoteEngineMethods maps a local lifecycle method to its remote counterpart. var remoteEngineMethods = map[string]string{ - "engine:install": "engine:remote-install", - "engine:start": "engine:remote-start", - "engine:stop": "engine:remote-stop", + "engine:update": "engine:remote-update", + "engine:check-updates": "engine:remote-check-updates", + "engine:install": "engine:remote-install", + "engine:start": "engine:remote-start", + "engine:stop": "engine:remote-stop", } // modelAction is one model operation: the remote method that performs it on a @@ -230,21 +234,24 @@ type engineOpMsg struct { // machine and uses the local method; otherwise the remote counterpart is used // and the node travels in the params. func engineCmd(client *rpc.Client, node, engine, method, op, what string) tea.Cmd { + return callEngine(client, node, engine, method, callTimeout, func(_ *rpc.Message, err error) tea.Msg { + return classifyOpResult(what, engine, op, err) + }) +} + +func callEngine(client *rpc.Client, node, engine, method string, budget time.Duration, decode func(*rpc.Message, error) tea.Msg) tea.Cmd { params := map[string]any{"engine": engine} if node != "" { remote, ok := remoteEngineMethods[method] if !ok { return func() tea.Msg { - return engineOpMsg{what: what, engine: engine, - err: errors.New("not supported on a remote node")} + return decode(nil, errors.New("not supported on a remote node")) } } method = remote params["node"] = node } - return call(client, method, params, func(_ *rpc.Message, err error) tea.Msg { - return classifyOpResult(what, engine, op, err) - }) + return callWithin(client, budget, method, params, decode) } // modelRequest is the method and params of a model operation against a node: @@ -435,6 +442,7 @@ var longRunningOps = map[string]bool{ "pull": true, "load": true, "install": true, + "update": true, "uninstall": true, "start": true, "restart": true, diff --git a/services/nvpair-tui/ui/engineswire_test.go b/services/nvpair-tui/ui/engineswire_test.go index fe1f4a113..5865f5b60 100644 --- a/services/nvpair-tui/ui/engineswire_test.go +++ b/services/nvpair-tui/ui/engineswire_test.go @@ -198,8 +198,6 @@ func TestDownloadOpID_IsOneTheEngineManagerAccepts(t *testing.T) { // than saying nothing. Quick operations get no such excuse, because a deadline // there is a real fault. func TestDeadlineLeniency_TracksOperationLength(t *testing.T) { - // Only operations engineOps actually declares: the TUI offers no engine - // update, so listing one here would assert against a path nothing reaches. // Start and restart wait on the engine's readiness probe, which the // manifests allow up to thirty minutes, so a deadline on either is a slow // reply rather than a failed start. @@ -213,6 +211,7 @@ func TestDeadlineLeniency_TracksOperationLength(t *testing.T) { longRunning("pull remains running", "pull") longRunning("load remains running", "load") longRunning("install remains running", "install") + longRunning("update remains running", "update") longRunning("uninstall remains running", "uninstall") longRunning("start remains running", "start") longRunning("restart remains running", "restart") diff --git a/services/nvpair-tui/ui/engineupdates.go b/services/nvpair-tui/ui/engineupdates.go new file mode 100644 index 000000000..be74634b8 --- /dev/null +++ b/services/nvpair-tui/ui/engineupdates.go @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package ui + +import ( + "encoding/json" + "net/url" + "os" + "slices" + "strings" + "time" + + "nvpair-shared/engines" + "nvpair-tui/rpc" + + tea "github.com/charmbracelet/bubbletea" +) + +type engineUpdateOffer struct { + CurrentVersion string `json:"currentVersion"` + LatestVersion string `json:"latestVersion"` + InstallType string `json:"installType"` + DownloadURL string `json:"downloadUrl"` +} + +// A new screen or installation gets a new state. An outstanding check or +// apply reply carries that pointer so it can only change the original row. +type engineUpdateState struct { + offer *engineUpdateOffer + running, starting, awaitingModel bool + checking, checkAgain bool + apply *engineUpdateOperation +} + +// The terminal progress frame and the RPC reply can arrive in either order. +type engineUpdateOperation struct { + terminal string + detached bool +} + +// The node's inventory can arrive every five seconds. Ask the vendor when +// installation or lifecycle state changes and on the six-hour refresh. +func (d *nodeDetail) syncEngineUpdates(periodic bool) tea.Cmd { + if d.enginesStale || !d.enginesQueryable() || strings.TrimSpace(os.Getenv(disableUpdateCheckEnv)) != "" { + return nil + } + for id := range d.engineUpdates { + if !slices.ContainsFunc(d.engines, func(e engineStatus) bool { return e.Engine == id && e.Installed }) { + delete(d.engineUpdates, id) + } + } + var cmds []tea.Cmd + for _, e := range d.engines { + if _, supported := engines.ByName(e.Engine); !supported || !e.Installed { + continue + } + entry := d.engineUpdates[e.Engine] + changed := entry == nil || entry.running != e.Running || entry.starting != e.Starting || entry.awaitingModel != e.AwaitingModel + if entry == nil { + entry = &engineUpdateState{} + d.engineUpdates[e.Engine] = entry + } + entry.running, entry.starting, entry.awaitingModel = e.Running, e.Starting, e.AwaitingModel + if !e.Starting && (changed || periodic) { + cmds = append(cmds, d.checkEngineUpdate(e.Engine, entry)) + } + } + return tea.Batch(cmds...) +} + +type engineUpdateCheckedMsg struct { + engine string + entry *engineUpdateState + offer *engineUpdateOffer + ok bool +} + +func (d *nodeDetail) checkEngineUpdate(engine string, entry *engineUpdateState) tea.Cmd { + if entry.apply != nil || !d.enginesQueryable() || d.enginesStale { + return nil + } + if entry.checking { + entry.checkAgain = true + return nil + } + entry.checking = true + return d.own(callEngine(d.client, d.nodeArg(), engine, "engine:check-updates", callTimeout, func(reply *rpc.Message, err error) tea.Msg { + msg := engineUpdateCheckedMsg{engine: engine, entry: entry} + var result struct { + Offer json.RawMessage `json:"updateAvailable"` + } + if err == nil && json.Unmarshal(reply.Result, &result) == nil && json.Unmarshal(result.Offer, &msg.offer) == nil { + msg.ok = msg.offer == nil || msg.offer.valid() + } + return msg + })) +} + +func (offer *engineUpdateOffer) valid() bool { + // These values will be written to a terminal, including on a peer's behalf. + printable := func(s string, limit int) bool { + return s != "" && len(s) <= limit && strings.IndexFunc(s, func(r rune) bool { return r < '!' || r > '~' }) < 0 + } + if !printable(offer.CurrentVersion, 128) || !printable(offer.LatestVersion, 128) { + return false + } + if offer.InstallType == "managed" { + return true + } + if offer.InstallType != "external" || !printable(offer.DownloadURL, 2048) { + return false + } + u, err := url.Parse(offer.DownloadURL) + return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil +} + +func (d *nodeDetail) receiveEngineUpdateCheck(msg engineUpdateCheckedMsg) tea.Cmd { + entry := msg.entry + if d.engineUpdates[msg.engine] != entry { + return nil + } + entry.checking = false + if entry.checkAgain { + entry.checkAgain = false + return d.checkEngineUpdate(msg.engine, entry) + } + // A failed or unavailable check leaves the last confirmed offer on screen. + if msg.ok && entry.apply == nil { + entry.offer = msg.offer + d.refreshEngines() + } + return nil +} + +func (d *nodeDetail) engineUpdateOffer(engine string) *engineUpdateOffer { + entry := d.engineUpdates[engine] + if entry == nil || entry.apply != nil || d.enginesStale || !d.enginesQueryable() { + return nil + } + return entry.offer +} + +type engineUpdateAppliedMsg struct { + engineOpMsg + entry *engineUpdateState +} + +func (d *nodeDetail) applyEngineUpdate(e *engineStatus) tea.Cmd { + if e == nil || !e.Installed { + return nil + } + offer := d.engineUpdateOffer(e.Engine) + if offer == nil || offer.InstallType != "managed" { + return nil + } + entry := d.engineUpdates[e.Engine] + entry.apply = &engineUpdateOperation{} + d.refreshEngines() + d.status.busy("updating %s on %s...", e.label(), d.node.name) + // Match the desktop's remote transfer budget for a full engine download. + const updateBudget = 6 * time.Hour + engine := e.Engine + op := engineOps["update"] + return d.own(callEngine(d.client, d.nodeArg(), engine, op.method, updateBudget, func(_ *rpc.Message, err error) tea.Msg { + return engineUpdateAppliedMsg{classifyOpResult(op.what, engine, "update", err), entry} + })) +} + +func (d *nodeDetail) finishEngineUpdate(msg engineUpdateAppliedMsg) tea.Cmd { + entry := d.engineUpdates[msg.engine] + if entry != msg.entry || entry.apply == nil { + return nil + } + if msg.detached && entry.apply.terminal == "" { + entry.apply.detached = true + if !d.promptArmed() { + d.status.info("update %s on %s is continuing in the background", d.engineLabel(msg.engine), d.node.name) + } + return nil + } + switch { + case msg.detached: + // The terminal frame already reported the outcome. + if entry.apply.terminal == "done" { + entry.offer = nil + } + case msg.err != nil: + if !d.promptArmed() { + d.status.error("update %s on %s failed: %s", d.engineLabel(msg.engine), d.node.name, msg.err) + } + default: + entry.offer = nil + if !d.promptArmed() { + d.status.ok("updated %s on %s", d.engineLabel(msg.engine), d.node.name) + } + } + entry.apply = nil + d.refreshEngines() + return d.checkEngineUpdate(msg.engine, entry) +} + +func (d *nodeDetail) showEngineUpdateProgress(engine, stage string, percent *int, failure string) tea.Cmd { + if !d.promptArmed() { + switch stage { + case "done": + d.status.ok("updated %s on %s", d.engineLabel(engine), d.node.name) + case "failed": + d.status.error("update %s on %s failed: %s", d.engineLabel(engine), d.node.name, failure) + default: + d.status.busy("update %s on %s: %s%s", d.engineLabel(engine), d.node.name, stage, progressPercent(percent)) + } + } + // Another console may have started this update. Our own update reply + // schedules the check even if its last progress frame never reaches us. + entry := d.engineUpdates[engine] + if entry == nil || (stage != "done" && stage != "failed") { + return nil + } + if entry.apply != nil { + entry.apply.terminal = stage + if entry.apply.detached { + return d.finishEngineUpdate(engineUpdateAppliedMsg{engineOpMsg{engine: engine, detached: true}, entry}) + } + } else if stage == "done" && entry.offer != nil { + entry.offer = nil + d.refreshEngines() + return d.checkEngineUpdate(engine, entry) + } + return nil +} diff --git a/services/nvpair-tui/ui/engineupdates_test.go b/services/nvpair-tui/ui/engineupdates_test.go new file mode 100644 index 000000000..9ce4821bf --- /dev/null +++ b/services/nvpair-tui/ui/engineupdates_test.go @@ -0,0 +1,228 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package ui + +import ( + "encoding/json" + "net" + "testing" + "time" + + "nvpair-tui/rpc" + + tea "github.com/charmbracelet/bubbletea" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const managedUpdateResult = `{"updateAvailable":{ + "currentVersion":"0.9.5", "latestVersion":"0.10.0", "installType":"managed", + "releaseUrl":"https://github.com/ollama/ollama/releases/tag/v0.10.0" +}}` + +// Each test answers the broker calls made by the detail screen, without running +// a service or fetching any vendor release. +func engineUpdateBroker(t *testing.T) (*rpc.Client, *rpc.Codec) { + t.Helper() + controller, broker := net.Pipe() + t.Cleanup(func() { + assert.NoError(t, broker.Close()) + assert.NoError(t, controller.Close()) + }) + require.NoError(t, broker.SetDeadline(time.Now().Add(5*time.Second))) + client := rpc.NewClient(controller, controller) + go client.Run(t.Context()) + return client, rpc.NewCodec(broker, broker) +} + +func answerUpdateCall(t *testing.T, cmd tea.Cmd, broker *rpc.Codec, method string, params map[string]string, response rpc.Message) tea.Msg { + t.Helper() + require.NotNil(t, cmd) + done := make(chan tea.Msg, 1) + go func() { done <- cmd() }() + request, err := broker.Read() + require.NoError(t, err) + require.Equal(t, method, request.Method) + var got map[string]string + require.NoError(t, json.Unmarshal(request.Params, &got)) + assert.Equal(t, params, got) + response.JSONRPC, response.ID = "2.0", request.ID + require.NoError(t, broker.Write(&response)) + select { + case result := <-done: + return result + case <-time.After(2 * time.Second): + t.Fatal("the detail screen did not receive the broker reply") + return nil + } +} + +func TestEngineUpdates_ApplyManagedReleaseOnSelectedNode(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + test := func(name string, node nodeRow, checkMethod, updateMethod string, wantParams map[string]string, updateResult string) { + t.Run(name, func(t *testing.T) { + client, broker := engineUpdateBroker(t) + d := newNodeDetail(client, node) + d.SetSize(120, 30) + check, _ := d.update(detailEnginesMsg{engines: []engineStatus{{Engine: "ollama", Installed: true}}}) + d.update(answerUpdateCall(t, check, broker, checkMethod, wantParams, rpc.Message{Result: json.RawMessage(managedUpdateResult)})) + + assert.Contains(t, d.View(), "0.9.5") + assert.Contains(t, d.View(), "0.10.0") + apply := d.handleKeyForTest(t, "U") + assert.Nil(t, d.handleKeyForTest(t, "U"), "repeated key presses must issue only one update") + reply := answerUpdateCall(t, apply, broker, updateMethod, wantParams, rpc.Message{Result: json.RawMessage(updateResult)}) + d.update(reply) + assert.NotContains(t, d.View(), "0.10.0", "the applied update should leave the engine row") + }) + } + test("this machine", nodeRow{key: "self", name: "my-node", self: true, presence: presenceOnline}, "engine:check-updates", "engine:update", + map[string]string{"engine": "ollama"}, `{"engine":"ollama","installed":true}`) + test("paired peer", nodeRow{key: "peer-id", name: "peer-host", membership: membershipMember, presence: presenceOnline}, + "engine:remote-check-updates", "engine:remote-update", map[string]string{"engine": "ollama", "node": "peer-id"}, + `{"opId":"test-update","status":{"engine":"ollama","installed":true}}`) +} + +func TestEngineUpdates_ShowExternalInstructionsForThePairedNode(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + client, broker := engineUpdateBroker(t) + d := remoteDetail() + d.client, d.node.membership = client, membershipMember + const external = `{"updateAvailable":{ + "currentVersion":"0.0.17-4", "latestVersion":"0.1.1-2", "installType":"external", + "releaseUrl":"https://lmstudio.ai/changelog", + "downloadUrl":"https://lmstudio.ai/docs/cli/daemon/daemon-update" + }}` + check, _ := d.update(detailEnginesMsg{engines: []engineStatus{{Engine: "lmstudio", Installed: true}}}) + d.update(answerUpdateCall(t, check, broker, "engine:remote-check-updates", map[string]string{"engine": "lmstudio", "node": "peer"}, rpc.Message{Result: json.RawMessage(external)})) + + assert.Contains(t, d.View(), "https://lmstudio.ai/docs/cli/daemon/daemon-update") + assert.Nil(t, d.handleKeyForTest(t, "U"), "an external installation must stay under its owner's control") +} + +func TestEngineUpdates_KeepThePeersOutcomeWhenTheRequestTimesOut(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + start := func(t *testing.T) (*nodeDetail, engineUpdateAppliedMsg) { + t.Helper() + d := remoteDetail() + client, broker := engineUpdateBroker(t) + d.client, d.node.membership = client, membershipMember + check, _ := d.update(detailEnginesMsg{engines: []engineStatus{{Engine: "ollama", DisplayName: "Ollama", Installed: true}}}) + d.update(answerUpdateCall(t, check, broker, "engine:remote-check-updates", map[string]string{"node": "peer", "engine": "ollama"}, rpc.Message{Result: json.RawMessage(managedUpdateResult)})) + require.NotNil(t, d.handleKeyForTest(t, "U")) + return d, engineUpdateAppliedMsg{engineOpMsg{engine: "ollama", detached: true}, d.engineUpdates["ollama"]} + } + t.Run("timeout waits for the peer to report failure before allowing retry", func(t *testing.T) { + d, timeout := start(t) + d.update(timeout) + assert.Nil(t, d.handleKeyForTest(t, "U")) + d.update(progressPush(t, "engine:remote-progress", map[string]any{ + "node": "peer", "op": "update", "engine": "ollama", "stage": "failed", "message": "disk full", + })) + assert.Contains(t, d.View(), "disk full") + assert.NotNil(t, d.handleKeyForTest(t, "U")) + }) + t.Run("success before timeout remains visible", func(t *testing.T) { + d, timeout := start(t) + d.update(progressPush(t, "engine:remote-progress", map[string]any{ + "node": "peer", "op": "update", "engine": "ollama", "stage": "done", + })) + d.update(timeout) + assert.Contains(t, d.View(), "updated Ollama on peer-host") + assert.Nil(t, d.handleKeyForTest(t, "U")) + }) +} + +func TestEngineUpdates_KeepLastOfferWhenALifecycleCheckFails(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + client, broker := engineUpdateBroker(t) + d := localDetail() + d.client = client + params := map[string]string{"engine": "ollama"} + engine := engineStatus{Engine: "ollama", Installed: true} + inventory := func() tea.Cmd { + cmd, _ := d.update(detailEnginesMsg{engines: []engineStatus{engine}}) + return cmd + } + d.update(answerUpdateCall(t, inventory(), broker, "engine:check-updates", params, rpc.Message{Result: json.RawMessage(managedUpdateResult)})) + require.Nil(t, inventory(), "repeated inventory should reuse the confirmed offer") + + engine.Running = true + d.update(answerUpdateCall(t, inventory(), broker, "engine:check-updates", params, rpc.Message{Error: &rpc.RPCError{Code: -32000, Message: "vendor unreachable"}})) + assert.Contains(t, d.View(), "0.10.0") + assert.NotContains(t, d.View(), "vendor unreachable") + require.Nil(t, inventory()) + + engine.Running = false + d.update(answerUpdateCall(t, inventory(), broker, "engine:check-updates", params, rpc.Message{Result: json.RawMessage(`{"updateAvailable":null}`)})) + assert.NotContains(t, d.View(), "0.10.0") +} + +func TestEngineUpdates_IgnoreOffersFromAPreviousInstallation(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + d := localDetail() + client, broker := engineUpdateBroker(t) + d.client = client + installed := detailEnginesMsg{engines: []engineStatus{{Engine: "ollama", Installed: true}}} + params := map[string]string{"engine": "ollama"} + check, _ := d.update(installed) + oldOffer := answerUpdateCall(t, check, broker, "engine:check-updates", params, rpc.Message{Result: json.RawMessage(managedUpdateResult)}) + + d.update(detailEnginesMsg{}) + check, _ = d.update(installed) + d.update(answerUpdateCall(t, check, broker, "engine:check-updates", params, rpc.Message{Result: json.RawMessage(`{"updateAvailable":null}`)})) + d.update(oldOffer) + + assert.NotContains(t, d.View(), "0.10.0") + assert.Nil(t, d.handleKeyForTest(t, "U"), "the old installation's offer must not enable an update") +} + +func TestEngineUpdates_CheckEachInstalledEngineEverySixHours(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + d := localDetail() + client, calls := removalBroker(t, "") + d.client = client + checks := func(cmd tea.Cmd) { + t.Helper() + require.NotNil(t, cmd) + batch, ok := cmd().(tea.BatchMsg) + require.True(t, ok, "each installed engine should have its own check") + var checked []string + for _, check := range batch { + d.update(check()) + method, params := receivedCall(t, calls) + assert.Equal(t, "engine:check-updates", method) + checked = append(checked, params["engine"]) + } + assert.ElementsMatch(t, []string{"ollama", "lmstudio", "llamacpp", "vllm"}, checked) + } + now := time.Now() + initial, _ := d.update(detailEnginesMsg{engines: []engineStatus{ + {Engine: "ollama", Installed: true}, {Engine: "lmstudio", Installed: true}, + {Engine: "llamacpp", Installed: true}, {Engine: "vllm", Installed: true}, + }}) + checks(initial) + early, _ := d.update(TickMsg{Now: now.Add(5 * time.Hour)}) + assert.Nil(t, early) + due, _ := d.update(TickMsg{Now: now.Add(6 * time.Hour)}) + checks(due) +} + +func TestEngineUpdates_SkipChecksForUnpairedPeersAndWhenDisabled(t *testing.T) { + engine := detailEnginesMsg{engines: []engineStatus{{Engine: "ollama", Installed: true}}} + t.Run("unpaired peer", func(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "") + d := remoteDetail() + d.client, _ = engineUpdateBroker(t) + cmd, _ := d.update(engine) + assert.Nil(t, cmd) + }) + t.Run("disabled on this machine", func(t *testing.T) { + t.Setenv(disableUpdateCheckEnv, "1") + d := localDetail() + d.client, _ = engineUpdateBroker(t) + cmd, _ := d.update(engine) + assert.Nil(t, cmd) + }) +} diff --git a/services/nvpair-tui/ui/nodedetail.go b/services/nvpair-tui/ui/nodedetail.go index bd2d70966..e39bdbc1d 100644 --- a/services/nvpair-tui/ui/nodedetail.go +++ b/services/nvpair-tui/ui/nodedetail.go @@ -60,12 +60,14 @@ type nodeDetail struct { client *rpc.Client node nodeRow - engines []engineStatus - engineTable table.Model - models modelsResult - modelTable table.Model - modelRows []detailModelRow - pane detailPane + engines []engineStatus + engineUpdates map[string]*engineUpdateState + nextEngineUpdateCheck time.Time + engineTable table.Model + models modelsResult + modelTable table.Model + modelRows []detailModelRow + pane detailPane // proxy carries the client-facing endpoint ports for this machine, so the // port a client connects to sits beside the engine it reaches. Left nil for // a peer, whose proxies we do not configure. @@ -220,6 +222,7 @@ var ( detailBackKey = key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "back")) detailPaneKey = key.NewBinding(key.WithKeys("left", "right", "h", "l"), key.WithHelp("h/l", "pane")) detailInstallKey = key.NewBinding(key.WithKeys("i"), key.WithHelp("i", "install")) + detailUpdateKey = key.NewBinding(key.WithKeys("U"), key.WithHelp("U", "update")) detailStartKey = key.NewBinding(key.WithKeys("s"), key.WithHelp("s", "start")) detailStopKey = key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "stop")) detailRestartKey = key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "restart")) @@ -275,12 +278,14 @@ func newNodeDetail(client *rpc.Client, node nodeRow) *nodeDetail { ti := textinput.New() detailRefreshes++ d := &nodeDetail{ - client: client, - node: node, - engineTable: newTable(detailEngineColumns(defaultTableWidth, !node.self)), - modelTable: newTable(detailModelColumns(defaultTableWidth)), - input: ti, - refreshGen: detailRefreshes, + client: client, + node: node, + engineTable: newTable(detailEngineColumns(defaultTableWidth, !node.self)), + modelTable: newTable(detailModelColumns(defaultTableWidth)), + input: ti, + refreshGen: detailRefreshes, + engineUpdates: make(map[string]*engineUpdateState), + nextEngineUpdateCheck: time.Now().Add(updateCheckInterval), } if node.self { d.proxy = newProxyTracker() @@ -427,6 +432,7 @@ func (d *nodeDetail) own(cmd tea.Cmd) tea.Cmd { // "Online" and "Member" here until the screen was reopened. func (d *nodeDetail) followNode(row nodeRow, found bool) { was := d.node.membership + oldKey := d.node.key hardwareHeight := d.hardwareHeight() if found { // Manual association can arrive after opening the detail, and its key @@ -453,8 +459,9 @@ func (d *nodeDetail) followNode(row nodeRow, found bool) { // it was a member offers controls that can no longer do anything. It goes, // and the empty-list hint says why. Rejoining needs nothing here: the // engine poll asks again once the node is queryable. - if d.remote() && was == membershipMember && d.node.membership != membershipMember { + if d.remote() && (oldKey != d.node.key || was == membershipMember && d.node.membership != membershipMember) { d.engines = nil + clear(d.engineUpdates) d.enginesStale = false d.refreshEngines() d.sizeEngineTable() @@ -620,12 +627,27 @@ func (d *nodeDetail) update(msg tea.Msg) (tea.Cmd, bool) { // behind it. Recorded instead, and rendered as a note beside the // engine list, the way an unreachable node's telemetry already is. d.enginesStale = true + d.refreshEngines() return nil, true } d.enginesStale = false d.engines = msg.engines + cmd := d.syncEngineUpdates(false) d.refreshEngines() d.SetSize(d.width, d.height) + return cmd, true + + case engineUpdateCheckedMsg: + return d.receiveEngineUpdateCheck(msg), true + + case engineUpdateAppliedMsg: + return d.finishEngineUpdate(msg), true + + case TickMsg: + if !msg.Now.Before(d.nextEngineUpdateCheck) { + d.nextEngineUpdateCheck = msg.Now.Add(updateCheckInterval) + return d.syncEngineUpdates(true), true + } return nil, true case detailModelsMsg: @@ -758,14 +780,17 @@ func (d *nodeDetail) handleNotification(msg *rpc.Message) tea.Cmd { for i, existing := range d.engines { if existing.Engine == e.Engine { d.engines[i] = e + cmd := d.syncEngineUpdates(false) d.refreshEngines() - return nil + return cmd } } d.engines = append(d.engines, e) + cmd := d.syncEngineUpdates(false) d.refreshEngines() // A new engine row changes the split between the two tables. d.sizeEngineTable() + return cmd case "engine:settings-changed": // The saved state, from whoever changed it — this screen, the desktop @@ -817,6 +842,9 @@ func (d *nodeDetail) handleNotification(msg *rpc.Message) tea.Cmd { Error string `json:"error"` } decodeOrLog(msg.Method, msg.Params, &p) + if entry := d.engineUpdates[p.Engine]; entry != nil && entry.apply != nil { + return d.showEngineUpdateProgress(p.Engine, p.Stage, p.Percent, p.Error) + } if d.promptArmed() { return nil } @@ -834,6 +862,9 @@ func (d *nodeDetail) handleNotification(msg *rpc.Message) tea.Cmd { // multi-hundred-megabyte download, and between two frames more than six // seconds apart an expiring line leaves the screen looking idle. d.status.busy("install %s: %s%s", d.engineLabel(p.Engine), p.Stage, progressPercent(p.Percent)) + if entry := d.engineUpdates[p.Engine]; p.Stage == "done" && entry != nil && entry.offer != nil { + return d.checkEngineUpdate(p.Engine, entry) + } case "engine:pull-progress": // Local pulls only. The engine manager emits this for its own downloads @@ -867,6 +898,12 @@ func (d *nodeDetail) handleNotification(msg *rpc.Message) tea.Cmd { if p.Node != d.node.key { return nil } + if p.Op == "update" { + if d.remote() && d.enginesQueryable() { + return d.showEngineUpdateProgress(p.Engine, p.Stage, p.Percent, p.Message) + } + return nil + } // A peer's pull reports on the same frames as this machine's, model // and all, and a download that outlasted its reply has no other way // to say how it went. @@ -1291,6 +1328,8 @@ func (d *nodeDetail) handleEngineKey(msg tea.KeyMsg) tea.Cmd { switch { case key.Matches(msg, detailInstallKey): return d.lifecycle(engine, "install") + case key.Matches(msg, detailUpdateKey): + return d.applyEngineUpdate(engine) case key.Matches(msg, detailStartKey): return d.lifecycle(engine, "start") case key.Matches(msg, detailStopKey): @@ -1940,7 +1979,11 @@ func (d *nodeDetail) refreshEngines() { } else if e.AwaitingModel { running = "no model" } - row := table.Row{e.label(), yesNo(e.Installed), running, yesNo(e.Healthy), port} + installed := yesNo(e.Installed) + if d.engineUpdateOffer(e.Engine) != nil { + installed = "update" + } + row := table.Row{e.label(), installed, running, yesNo(e.Healthy), port} if d.proxy != nil { row = append(row, d.proxyPortCell(e.Engine)) } @@ -2129,6 +2172,17 @@ func (d *nodeDetail) View() string { enginesBody += "\n" + footerStyle.Render(fmt.Sprintf( " %s is not answering - this list may be out of date.", d.node.name)) } + if engine := d.selectedEngine(); engine != nil { + if offer := d.engineUpdateOffer(engine.Engine); offer != nil { + note := fmt.Sprintf("%s %s is available (%s installed).", engine.label(), offer.LatestVersion, offer.CurrentVersion) + if offer.InstallType == "external" { + note += fmt.Sprintf(" To update it on %s, visit %s", d.node.name, offer.DownloadURL) + } else if d.pane == detailEngines { + note += " Press U to update." + } + enginesBody += "\n" + footerStyle.Render(indentWrap(note, d.width)) + } + } modelsEmpty := "" if len(d.modelRows) == 0 { modelsEmpty = footerStyle.Render(d.emptyModelsHint()) @@ -2421,6 +2475,11 @@ func (d *nodeDetail) Help() []key.Binding { } bindings := []key.Binding{detailBackKey, detailPaneKey} if d.pane == detailEngines { + if engine := d.selectedEngine(); engine != nil { + if offer := d.engineUpdateOffer(engine.Engine); offer != nil && offer.InstallType == "managed" { + bindings = append(bindings, detailUpdateKey) + } + } bindings = append(bindings, detailInstallKey, detailStartKey, detailStopKey) // The settings keys are offered on a peer too: the engine manager // relays them, and whether a particular engine will accept the write diff --git a/services/nvpair-ui-broker/README.md b/services/nvpair-ui-broker/README.md index 5b9759bc5..c9b68763b 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. Local engines use `engine:check-updates` and `engine:update`. For a pinned peer the broker forwards `engine:remote-check-updates` and `engine:remote-update`, and relays `engine:remote-progress` during the update. 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..20b139bc0 --- /dev/null +++ b/services/tests/engine_update_test.go @@ -0,0 +1,89 @@ +// 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_RelaysEngineUpdateRequests(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) + }) + } + + for _, method := range []string{"engine:remote-check-updates", "engine:remote-update"} { + t.Run(method+" resolves the selected peer", func(t *testing.T) { + params := map[string]string{"node": "missing-update-peer", "engine": engines.NameOllama} + reply := callRPC(t, stdin, messages, method, params, 10*time.Second) + require.NotNil(t, reply.Error) + assert.Equal(t, -32000, reply.Error.Code) + assert.Contains(t, reply.Error.Message, "missing-update-peer is not a discovered ec peer") + }) + } +} diff --git a/services/tests/remote_engine_test.go b/services/tests/remote_engine_test.go index 53af6c19f..9d12bb56a 100644 --- a/services/tests/remote_engine_test.go +++ b/services/tests/remote_engine_test.go @@ -28,6 +28,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "sync" "testing" @@ -39,6 +40,15 @@ import ( "nvpair-shared/jsonrpc" ) +func announceEnginePeer(t *testing.T, stdin io.Writer, uuid string, port int) { + t.Helper() + snapshot := fmt.Sprintf(`{"jsonrpc":"2.0","method":"discovery:nodes","params":{"nodes":[`+ + `{"hostUuid":%q,"name":"nodeB","ip":"127.0.0.1","clusterUuid":%q,"trusted":true,`+ + `"identityVerification":"pinned","discoveryRecordId":"peer-b",`+ + `"services":{"ec":{"port":%d}},"lastSeen":0}]}}`, uuid, uuid, port) + writeRawFrame(t, stdin, snapshot) +} + // mintClusterIdentity writes a self-signed cluster leaf (node.crt + node.key) // for uuid into dir and returns the certificate PEM (for cross-pinning). func mintClusterIdentity(t *testing.T, dir, uuid string) string { @@ -121,11 +131,7 @@ func TestRemoteEngine_ReturnsInstalledEnginesForPeer(t *testing.T) { // Seed A's ec peer directory with node B. handleMessage processes this // synchronously before the next frame, so the directory is populated by the // time the remote request is read. - snapshot := fmt.Sprintf(`{"jsonrpc":"2.0","method":"discovery:nodes","params":{"nodes":[`+ - `{"hostUuid":%q,"name":"nodeB","ip":"127.0.0.1","clusterUuid":%q,"trusted":true,`+ - `"identityVerification":"pinned","discoveryRecordId":"peer-b",`+ - `"services":{"ec":{"port":%d}},"lastSeen":0}]}}`, uuidB, uuidB, portB) - writeRawFrame(t, aStdin, snapshot) + announceEnginePeer(t, aStdin, uuidB, portB) // Fire the remote read and await the response. writeRawFrame(t, aStdin, fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"engine:remote-get-installed","params":{"node":%q}}`, uuidB)) @@ -162,17 +168,62 @@ func TestRemoteEngine_RejectsUntrusted(t *testing.T) { t.Cleanup(aCleanup) waitForMethod(t, aMsgs, "engine:ready", 10*time.Second) - snapshot := fmt.Sprintf(`{"jsonrpc":"2.0","method":"discovery:nodes","params":{"nodes":[`+ - `{"hostUuid":%q,"name":"nodeB","ip":"127.0.0.1","clusterUuid":%q,"trusted":true,`+ - `"identityVerification":"pinned","discoveryRecordId":"peer-b",`+ - `"services":{"ec":{"port":%d}},"lastSeen":0}]}}`, uuidB, uuidB, portB) - writeRawFrame(t, aStdin, snapshot) - writeRawFrame(t, aStdin, fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"engine:remote-get-installed","params":{"node":%q}}`, uuidB)) + announceEnginePeer(t, aStdin, uuidB, portB) + for _, method := range []string{"engine:remote-get-installed", "engine:remote-check-updates", "engine:remote-update"} { + t.Run(method, func(t *testing.T) { + resp := callRPC(t, aStdin, aMsgs, method, map[string]string{"node": uuidB, "engine": "ollama"}, 10*time.Second) + require.NotNil(t, resp.Error) + assert.Contains(t, resp.Error.Message, "HTTP 403") + }) + } +} - resp := waitForResponse(t, aMsgs, 15*time.Second) - require.NotNil(t, resp.Error, "expected an error from an unpinned caller, got result") - require.Contains(t, resp.Error.Message, "HTTP 403", "the discovered peer must reject the caller at its pin gate") - t.Logf("unpinned caller correctly refused: %+v", resp.Error) +func TestRemoteEngineUpdate_UsesTheSelectedPeersInstallation(t *testing.T) { + controllerDir, targetDir := t.TempDir(), t.TempDir() + const controller, target = "update-controller", "update-target" + controllerCert := mintClusterIdentity(t, controllerDir, controller) + targetCert := mintClusterIdentity(t, targetDir, target) + writePin(t, targetDir, controller, controllerCert) + writePin(t, controllerDir, target, targetCert) + + targetHome := t.TempDir() + externalBinary := filepath.Join(targetHome, "external-ollama.exe") + ports := freePorts(t, 2) + writeUserManifest(t, targetHome, map[string]any{ + "engine": "ollama", + "platforms": map[string]any{runtime.GOOS + "/" + runtime.GOARCH: map[string]any{ + "detect": []string{externalBinary}, "install": nil, + "runtime": map[string]any{"port": ports[1]}, + }}, + }) + _, stopTarget := startEngineManagerServer(t, targetDir, ports[0], "HOME="+targetHome, "USERPROFILE="+targetHome, + "LOCALAPPDATA="+targetHome, "APPDATA="+targetHome, "XDG_CONFIG_HOME="+targetHome) + t.Cleanup(stopTarget) + waitForPort(t, "127.0.0.1", ports[0], 10*time.Second) + stdin, messages, stopController := startEngineManagerStdio(t, controllerDir) + t.Cleanup(stopController) + waitForMethod(t, messages, "engine:ready", 10*time.Second) + announceEnginePeer(t, stdin, target, ports[0]) + + params := map[string]string{"node": target, "engine": "ollama"} + check := callRPC(t, stdin, messages, "engine:remote-check-updates", params, 10*time.Second) + require.Nil(t, check.Error) + assert.JSONEq(t, `{"updateAvailable":null}`, string(check.Result)) + + // Only the target sees this file. Its invalid contents make the version + // lookup fail locally before it could contact a release provider. + externalContents := []byte("invalid executable") + require.NoError(t, os.WriteFile(externalBinary, externalContents, 0o600)) + check = callRPC(t, stdin, messages, "engine:remote-check-updates", params, 10*time.Second) + require.NotNil(t, check.Error) + assert.Contains(t, check.Error.Message, "read installed Ollama version") + + update := callRPC(t, stdin, messages, "engine:remote-update", params, 10*time.Second) + require.NotNil(t, update.Error) + assert.Contains(t, update.Error.Message, "PAIR-managed Ollama installation") + contentsAfterUpdate, err := os.ReadFile(externalBinary) + require.NoError(t, err) + assert.Equal(t, externalContents, contentsAfterUpdate) } // engine:remote-cancel-pull goes from node A to node B across the same