Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Install and update llama.cpp with winget on Windows

[._.]/ Adam Eivyb07de1511a9d
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 0dde3cd843..2f8508351a 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -819,6 +819,9 @@ export function LocalLlmTab({ view }) {
: drafterConfigured && !drafterInUse
? 'The Drafter Model will be ignored — none of these spec types use one.'
: '';
+ // Resolved server-side, because the browser has no idea what OS it is talking
+ // to; absent until the first status lands, and the copy below says so.
+ const llamaInstallCommand = llamaStatus?.installCommand;
const llamaStartBlockedReason = llamaModelMissing
? 'Enter a Target Base Model path to enable Start'
: baseWeightMissing
@@ -1158,7 +1161,7 @@ export function LocalLlmTab({ view }) {
</div>
<p className="text-xs text-gray-400 leading-relaxed">
- Speculative decoding pairs a small drafter with your target model for 2–3× faster generation at identical output. You can launch and manage a local <code className="text-gray-300">llama-server</code> from PortOS and connect using the <strong className="text-white">OpenCode llama TUI</strong> provider. <strong className="text-white">DSpark</strong> (<code className="text-gray-300">draft-dspark</code>) works on a stock <code className="text-gray-300">brew install llama.cpp</code>; the DFlash 2 presets need a from-source build of an unmerged llama.cpp branch. No drafter GGUF to hand? The <code className="text-gray-300">ngram-*</code> spec types under Advanced options draft from the context window alone.
+ Speculative decoding pairs a small drafter with your target model for 2–3× faster generation at identical output. You can launch and manage a local <code className="text-gray-300">llama-server</code> from PortOS and connect using the <strong className="text-white">OpenCode llama TUI</strong> provider. <strong className="text-white">DSpark</strong> (<code className="text-gray-300">draft-dspark</code>) works on a stock llama.cpp{llamaInstallCommand ? <> (<code className="text-gray-300">{llamaInstallCommand}</code>)</> : null}; the DFlash 2 presets need a from-source build of an unmerged llama.cpp branch. No drafter GGUF to hand? The <code className="text-gray-300">ngram-*</code> spec types under Advanced options draft from the context window alone.
</p>
{llamaStatus?.running ? (
@@ -1479,7 +1482,9 @@ export function LocalLlmTab({ view }) {
<div className="space-y-1">
<p className="font-semibold">llama-server was not detected on system PATH.</p>
<p className="text-gray-300">
- Install via Homebrew or compile the DFlash 2-enabled branch from source.
+ {llamaInstallCommand
+ ? <>Install it with <code className="text-gray-300">{llamaInstallCommand}</code>, or compile the DFlash 2-enabled branch from source.</>
+ : <>Install it from your platform&apos;s package manager, or compile the DFlash 2-enabled branch from source.</>}
</p>
</div>
<button
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 91840597b6..dd9918980c 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -1007,6 +1007,28 @@ describe('LocalLlmTab llama-server management', () => {
});
});
+ it('names the install command the SERVER reports, not a hardcoded Homebrew one', async () => {
+ // The browser cannot know what OS the install runs on, so this copy has to
+ // come off the status payload — a Windows user was previously told to run
+ // `brew install llama.cpp`, which does not exist there.
+ const { getLlamaServerStatus } = await import('../../services/api');
+ getLlamaServerStatus.mockResolvedValue({
+ installed: false,
+ running: false,
+ managed: false,
+ packageManager: 'winget',
+ packageManagerLabel: 'winget',
+ installCommand: 'winget install ggml.llamacpp',
+ presets: specPresets(),
+ });
+
+ await renderTab();
+
+ await screen.findByRole('button', { name: /Install llama\.cpp/ });
+ expect(screen.getAllByText('winget install ggml.llamacpp').length).toBeGreaterThan(0);
+ expect(screen.queryByText('brew install llama.cpp')).not.toBeInTheDocument();
+ });
+
it('updates llama.cpp from the unified runtime row', async () => {
const { getLlamaServerStatus, getLlamaServerUpdateStatus, upgradeLlamaServer } = await import('../../services/api');
getLlamaServerStatus.mockResolvedValue(llamaReady());
diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsx
index ceb5d318bf..03b6405641 100644
--- a/client/src/components/settings/RuntimeServersCard.jsx
+++ b/client/src/components/settings/RuntimeServersCard.jsx
@@ -90,6 +90,8 @@ function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onIn
version: status?.version || null,
latestVersion: status?.latestVersion || null,
updateAvailable,
+ // Named in the tooltip so the button never promises the wrong tool.
+ updateVia: status?.packageManagerLabel || null,
onUpgrade: updateAvailable && status?.canUpgrade ? onUpgrade : null,
updateUrl: updateAvailable && !status?.canUpgrade ? status?.downloadUrl : null,
};
@@ -245,7 +247,7 @@ function ServerRow({ row, busy, actionInProgress, children }) {
onClick={() => row.onUpgrade()}
disabled={busy}
className={`${accentBtn} bg-port-success/20 hover:bg-port-success/30 text-port-success`}
- title={row.latestVersion ? `Update ${row.label} to v${row.latestVersion} through Homebrew` : `Update ${row.label} through Homebrew`}
+ title={`Update ${row.label}${row.latestVersion ? ` to v${row.latestVersion}` : ''}${row.updateVia ? ` through ${row.updateVia}` : ''}`}
>
{actionInProgress === `runtime-upgrade-${row.id}` ? <BrailleSpinner /> : <ArrowUpCircle size={12} />}
{row.latestVersion ? `Update to v${row.latestVersion}` : 'Update'}
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 9c7638cb2a..141b70722d 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -118,9 +118,9 @@ export const saveRuntimeStartupList = () =>
export const getLlamaServerStatus = (options) =>
request('/local-llm/llama-server/status', options);
-// Optional version/Homebrew metadata for the Local LLMs runtime card. Kept
-// separate from lifecycle status because the provider version probe and Homebrew
-// query can be slow on a cold machine.
+// Optional version/package-manager metadata for the Local LLMs runtime card.
+// Kept separate from lifecycle status because the provider version probe and the
+// `brew info` / `winget list` query can be slow on a cold machine.
export const getLlamaServerUpdateStatus = (options) =>
request('/local-llm/llama-server/update-status', options);
@@ -133,8 +133,9 @@ export const stopLlamaServer = () =>
export const installLlamaServer = () =>
request('/local-llm/llama-server/install', { method: 'POST' });
-// Upgrade a Homebrew-installed llama.cpp binary. A managed llama-server is
-// restarted by the server with its existing launch configuration.
+// Upgrade a package-manager-installed llama.cpp binary (Homebrew on macOS/Linux,
+// winget on Windows). A managed llama-server is restarted by the server with its
+// existing launch configuration.
export const upgradeLlamaServer = () =>
request('/local-llm/llama-server/upgrade', { method: 'POST' });
diff --git a/docs/features/dflash2.md b/docs/features/dflash2.md
index 42c55950c3..41c4047c3c 100644
--- a/docs/features/dflash2.md
+++ b/docs/features/dflash2.md
@@ -6,7 +6,7 @@
PortOS integrates both through the **OpenCode llama TUI** provider preset and the managed local `llama-server`.
-> **Which one to run:** `--spec-type draft-dspark` **merged into llama.cpp on 2026-07-28** ([#25173](https://github.com/ggml-org/llama.cpp/pull/25173)) and works on a stock `brew install llama.cpp`. DFlash 2's engine modules are **still an open PR** ([#27342](https://github.com/ggml-org/llama.cpp/pull/27342)) and need a from-source build of that branch. llama.cpp falls back **silently** on a spec-type/drafter mismatch rather than erroring, so a DFlash 2 drafter on a stock build degrades quietly. Start with DSpark unless you have built the DFlash 2 branch. Full comparison: [DSpark vs DFlash 2](../research/2026-08-19-dspark-vs-dflash2.md).
+> **Which one to run:** `--spec-type draft-dspark` **merged into llama.cpp on 2026-07-28** ([#25173](https://github.com/ggml-org/llama.cpp/pull/25173)) and works on a stock llama.cpp (`brew install llama.cpp` on macOS/Linux, `winget install ggml.llamacpp` on Windows — the LLMs page Install button runs whichever applies). DFlash 2's engine modules are **still an open PR** ([#27342](https://github.com/ggml-org/llama.cpp/pull/27342)) and need a from-source build of that branch. llama.cpp falls back **silently** on a spec-type/drafter mismatch rather than erroring, so a DFlash 2 drafter on a stock build degrades quietly. Start with DSpark unless you have built the DFlash 2 branch. Full comparison: [DSpark vs DFlash 2](../research/2026-08-19-dspark-vs-dflash2.md).
> **On an NVIDIA RTX 3090?** There is a shorter path than building llama.cpp from a branch. Upstream froze a working DFlash 2 setup for that exact card — patched vLLM 0.27.1 plus a requantized Qwen3.8-27B, shipped as a Docker compose project — and PortOS fronts it with its own OpenCode presets. You get DFlash 2 drafting and prefix caching without vendoring an unmerged engine patch, at the cost of the container holding the whole 24 GB card. See [vLLM Qwen3.8-27B on an RTX 3090](./qwen38-rtx3090.md). It is CUDA-only: Apple Silicon stays on DSpark or [MTPLX](./mtplx.md). On a **Hopper or Blackwell** card there is a third path — [SGLang Qwen3.8-27B](./sglang-qwen38.md), an official image with no speculative overlay by default (DFlash 2 there needs an SGLang newer than the pinned tag).
diff --git a/server/lib/README.md b/server/lib/README.md
index ca562e8659..5cc6bbdd8a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -369,6 +369,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `modelAbuseGuard.js` | Pinned model-abuse boundary contract: Prompt Guard metadata, deterministic abuse signals, classifier-envelope validation, chunk/timeout limits, and fixed install requirements. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
| `specDecodePresets.js` | Curated llama-server speculative-decoding presets (target + drafter GGUF paths, `--spec-type`, and the Hugging Face repo/quant each file comes from) plus `findSpecDecodePreset` / `specDecodeSource` / `hfSearchUrl`. Also owns the `--spec-type` vocabulary: `SPEC_TYPE_SUGGESTIONS` (published to the launcher card), `parseSpecTypes` (the flag is a comma-separated list) and `isDraftSpecType` (the `draft-` prefix is what needs a drafter GGUF — every `ngram-*` type runs without one). Server-owned so the launcher card can offer a Download button per file. Pure. |
+| `llamaCppInstall.js` | Where a llama.cpp install comes from on this host, for `services/llamaServerManager.js`. `llamaCppInstallPlan(platform)` → the frozen descriptor for that platform's package manager — Homebrew on macOS/Linux (`brew install llama.cpp`), winget on Windows (`winget install ggml.llamacpp`) — carrying `manager`, `managerLabel`, `packageId`, `installCommand`, the install/upgrade (and, for winget, list/upgrade-check) argv, and the three refusal strings a caller would otherwise hardcode: `missingManagerError`, `notInstalledError`, `pathRepairHint`. The LLMs page renders `installCommand` out of the llama-server status payload, which is what stopped a Windows install prompt from telling the user to run Homebrew. Also the winget-side readers Homebrew needs no equivalent for: `parseWingetPackageFields(stdout, id)` (winget has NO machine-readable output mode and LOCALIZED table headers, so fields are read positionally from the tokens after the id token — `Version [Available] [Source]`; `null` = not installed), `wingetLinkDirs(env)` (the portable-shim directories winget adds to the USER PATH, which an already-running server has not inherited) and `isWingetManagedPath` (counterpart of the manager's `isHomebrewLlamaServer`: a source build earlier on PATH must not be offered a `winget upgrade`). Every WinGet path is reasoned about with `path.win32` regardless of host, so both branches are coverable from a macOS/Linux checkout. Pure. |
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
diff --git a/server/lib/index.js b/server/lib/index.js
index 09423fc8b7..bf1bf97255 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -337,6 +337,7 @@ export * from './localLlmCatalog.js';
export * from './modelAbuseGuard.js';
export * from './localLlmDisk.js';
export * from './specDecodePresets.js';
+export * from './llamaCppInstall.js';
export * from './localModelHeuristics.js';
export * from './localModelAssessment.js';
export * from './localModelTuning.js';
diff --git a/server/lib/llamaCppInstall.js b/server/lib/llamaCppInstall.js
new file mode 100644
index 0000000000..7f4a6609a2
--- /dev/null
+++ b/server/lib/llamaCppInstall.js
@@ -0,0 +1,137 @@
+/**
+ * Where a llama.cpp install comes from on this host, and how to read what the
+ * platform's package manager knows about it.
+ *
+ * llama.cpp publishes an official package for both managers PortOS can drive:
+ * Homebrew on macOS/Linux (`brew install llama.cpp`) and winget on Windows
+ * (`winget install ggml.llamacpp`, a portable zip whose shims land in WinGet's
+ * Links directory). Keeping the descriptor here — rather than branching on
+ * `process.platform` at each call site in `services/llamaServerManager.js` —
+ * is what lets the LLMs page name the command that actually works instead of
+ * telling a Windows user to run Homebrew.
+ *
+ * Pure: every entry point takes the platform (and, for the WinGet paths, the
+ * environment) as an argument, so both branches are coverable from either OS.
+ */
+
+// The WinGet helpers below always reason about WINDOWS paths, whatever host is
+// running them — that is what keeps them coverable from a macOS/Linux checkout,
+// where `path.isAbsolute('C:\\…')` is false and would quietly answer "no".
+import { win32 as winPath } from 'path';
+
+export const LLAMA_CPP_DOWNLOAD_URL = 'https://github.com/ggml-org/llama.cpp/releases';
+export const LLAMA_CPP_BREW_FORMULA = 'llama.cpp';
+export const LLAMA_CPP_WINGET_ID = 'ggml.llamacpp';
+
+// `--disable-interactivity` keeps winget from drawing a prompt no one can answer
+// from a spawned child, and the two `--accept-*` flags stand in for the source
+// and package agreements it otherwise blocks on the first time.
+const WINGET_FLAGS = ['--exact', '--disable-interactivity'];
+const WINGET_AGREEMENTS = ['--accept-source-agreements', '--accept-package-agreements'];
+
+const WINGET_LIST_ARGS = ['list', '--id', LLAMA_CPP_WINGET_ID, ...WINGET_FLAGS];
+
+const BREW_PLAN = Object.freeze({
+ manager: 'brew',
+ managerLabel: 'Homebrew',
+ packageId: LLAMA_CPP_BREW_FORMULA,
+ installCommand: `brew install ${LLAMA_CPP_BREW_FORMULA}`,
+ installArgs: Object.freeze(['install', LLAMA_CPP_BREW_FORMULA]),
+ upgradeArgs: Object.freeze(['upgrade', LLAMA_CPP_BREW_FORMULA]),
+ missingManagerError:
+ 'Homebrew was not found. Please install Homebrew from https://brew.sh or build llama.cpp from source.',
+ notInstalledError:
+ `llama.cpp is not installed through Homebrew, so PortOS cannot update it here. Install it with Homebrew or update your source build manually: ${LLAMA_CPP_DOWNLOAD_URL}`,
+ pathRepairHint: `try running \`brew link --overwrite ${LLAMA_CPP_BREW_FORMULA}\` manually`,
+});
+
+const WINGET_PLAN = Object.freeze({
+ manager: 'winget',
+ managerLabel: 'winget',
+ packageId: LLAMA_CPP_WINGET_ID,
+ installCommand: `winget install ${LLAMA_CPP_WINGET_ID}`,
+ installArgs: Object.freeze(['install', '--id', LLAMA_CPP_WINGET_ID, ...WINGET_FLAGS, ...WINGET_AGREEMENTS]),
+ upgradeArgs: Object.freeze(['upgrade', '--id', LLAMA_CPP_WINGET_ID, ...WINGET_FLAGS, ...WINGET_AGREEMENTS]),
+ // Presence and installed version.
+ listArgs: Object.freeze([...WINGET_LIST_ARGS]),
+ // The same listing, restricted to packages winget has a newer build for — that
+ // row IS the staleness signal, since winget has no `outdated` field the way
+ // `brew info --json` does, and llama.cpp's versions are build numbers
+ // (`b10730`) that no semver comparison orders.
+ upgradeCheckArgs: Object.freeze([...WINGET_LIST_ARGS, '--upgrade-available']),
+ missingManagerError:
+ `winget was not found. Install "App Installer" from the Microsoft Store, or download a Windows llama.cpp build from ${LLAMA_CPP_DOWNLOAD_URL} and put its bin directory on PATH.`,
+ notInstalledError:
+ `llama.cpp is not installed through winget, so PortOS cannot update it here. Install it with \`winget install ${LLAMA_CPP_WINGET_ID}\` or update your own build manually: ${LLAMA_CPP_DOWNLOAD_URL}`,
+ pathRepairHint:
+ 'restart PortOS so it picks up the PATH entry winget added, or add WinGet\'s Links directory to PATH manually',
+});
+
+/**
+ * The install descriptor for a platform.
+ * @param {string} platform a `process.platform` value
+ */
+export function llamaCppInstallPlan(platform) {
+ return platform === 'win32' ? WINGET_PLAN : BREW_PLAN;
+}
+
+/**
+ * Pull one package's fields out of `winget list` table output.
+ *
+ * winget has no machine-readable output mode, and its table is column-aligned
+ * under LOCALIZED headers, so the header row cannot be used to find the columns.
+ * The package id is a whitespace-free token that appears nowhere else in the
+ * table, so the fields are read positionally from the tokens that follow it:
+ * `Version [Available] [Source]`. Padding for an empty column collapses under a
+ * whitespace split, which is why the caller must not index past what the
+ * specific invocation guarantees — `--upgrade-available` guarantees `Available`,
+ * a plain `list` does not.
+ *
+ * @param {string} stdout raw `winget list` output
+ * @param {string} packageId the exact id that was queried
+ * @returns {string[]|null} the fields after the id, or `null` when the package
+ * is not listed (winget prints "No installed package found…", not an error).
+ */
+export function parseWingetPackageFields(stdout, packageId) {
+ const wanted = String(packageId || '').toLowerCase();
+ if (!wanted) return null;
+ for (const line of String(stdout || '').split(/\r?\n/)) {
+ const fields = line.trim().split(/\s+/).filter(Boolean);
+ const index = fields.findIndex((field) => field.toLowerCase() === wanted);
+ if (index !== -1) return fields.slice(index + 1);
+ }
+ return null;
+}
+
+/**
+ * The directories winget links a portable package's executables into. Both
+ * scopes are returned because PortOS cannot know which one the user's install
+ * chose, and neither is guaranteed to exist.
+ */
+export function wingetLinkDirs(env = process.env) {
+ return wingetRoots(env).map((root) => winPath.join(root, 'Links'));
+}
+
+/** The per-user and machine-wide directories winget installs packages under. */
+function wingetRoots(env) {
+ return [
+ env.LOCALAPPDATA ? winPath.join(env.LOCALAPPDATA, 'Microsoft', 'WinGet') : null,
+ env.ProgramFiles ? winPath.join(env.ProgramFiles, 'WinGet') : null,
+ ].filter(Boolean);
+}
+
+/**
+ * Is this binary one winget installed?
+ *
+ * The Windows counterpart of `services/llamaServerManager.js#isHomebrewLlamaServer`:
+ * a source build or a hand-extracted release zip earlier on PATH must not be
+ * offered a `winget upgrade`, which would swap a package the running process is
+ * not using. Compared case-insensitively because Windows paths are.
+ */
+export function isWingetManagedPath(binaryPath, env = process.env) {
+ if (!binaryPath || !winPath.isAbsolute(binaryPath)) return false;
+ const candidate = winPath.normalize(binaryPath).toLowerCase();
+ return wingetRoots(env).some((root) => (
+ candidate.startsWith(winPath.normalize(root).toLowerCase() + winPath.sep)
+ ));
+}
diff --git a/server/lib/llamaCppInstall.test.js b/server/lib/llamaCppInstall.test.js
new file mode 100644
index 0000000000..c7cde6bb45
--- /dev/null
+++ b/server/lib/llamaCppInstall.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect } from 'vitest';
+import {
+ LLAMA_CPP_WINGET_ID,
+ isWingetManagedPath,
+ llamaCppInstallPlan,
+ parseWingetPackageFields,
+ wingetLinkDirs,
+} from './llamaCppInstall.js';
+
+// Windows-shaped fixtures, deliberately usable from a macOS/Linux checkout —
+// these helpers reason about Windows paths regardless of the host.
+const WIN_ENV = { LOCALAPPDATA: 'C:\\Users\\example\\AppData\\Local', ProgramFiles: 'C:\\Program Files' };
+
+describe('llamaCppInstallPlan', () => {
+ it('installs through winget on Windows and Homebrew everywhere else', () => {
+ expect(llamaCppInstallPlan('win32')).toMatchObject({
+ manager: 'winget',
+ installCommand: 'winget install ggml.llamacpp',
+ });
+ for (const platform of ['darwin', 'linux']) {
+ expect(llamaCppInstallPlan(platform)).toMatchObject({
+ manager: 'brew',
+ installCommand: 'brew install llama.cpp',
+ });
+ }
+ });
+
+ it('gives winget the non-interactive flags a spawned child needs', () => {
+ const { installArgs, upgradeArgs } = llamaCppInstallPlan('win32');
+ for (const args of [installArgs, upgradeArgs]) {
+ expect(args).toContain('--disable-interactivity');
+ expect(args).toContain('--accept-source-agreements');
+ expect(args).toContain('--accept-package-agreements');
+ expect(args).toContain('--exact');
+ }
+ });
+});
+
+describe('parseWingetPackageFields', () => {
+ // winget has no machine-readable output mode, so these are the shapes the real
+ // command actually prints — including the localized-header case the parser
+ // must not depend on.
+ it('reads the version off an installed package with no update', () => {
+ const stdout = [
+ 'Name Id Version Source',
+ '---------------------------------------',
+ 'llama.cpp ggml.llamacpp b10500 winget',
+ ].join('\n');
+ expect(parseWingetPackageFields(stdout, LLAMA_CPP_WINGET_ID)).toEqual(['b10500', 'winget']);
+ });
+
+ it('exposes the newer build as the second field when winget lists one', () => {
+ const stdout = [
+ 'Name Id Version Available Source',
+ '-------------------------------------------------',
+ 'llama.cpp ggml.llamacpp b10500 b10730 winget',
+ '1 upgrades available.',
+ ].join('\r\n');
+ expect(parseWingetPackageFields(stdout, LLAMA_CPP_WINGET_ID)?.[1]).toBe('b10730');
+ });
+
+ it('finds the row under a localized header', () => {
+ const stdout = [
+ 'Nom ID Version Disponible Source',
+ '--------------------------------------------------',
+ 'llama.cpp ggml.llamacpp b10500 b10730 winget',
+ ].join('\n');
+ expect(parseWingetPackageFields(stdout, LLAMA_CPP_WINGET_ID)?.[1]).toBe('b10730');
+ });
+
+ it('answers null for winget\'s "not installed" message', () => {
+ expect(parseWingetPackageFields('No installed package found matching input criteria.', LLAMA_CPP_WINGET_ID))
+ .toBeNull();
+ expect(parseWingetPackageFields('', LLAMA_CPP_WINGET_ID)).toBeNull();
+ });
+});
+
+describe('isWingetManagedPath', () => {
+ it('claims a binary under either WinGet root', () => {
+ expect(isWingetManagedPath('C:\\Users\\example\\AppData\\Local\\Microsoft\\WinGet\\Links\\llama-server.exe', WIN_ENV))
+ .toBe(true);
+ // Case-insensitively: Windows paths are, and PATH lookups spell them freely.
+ expect(isWingetManagedPath('c:\\program files\\winget\\packages\\ggml.llamacpp\\llama-server.exe', WIN_ENV))
+ .toBe(true);
+ });
+
+ it('leaves a hand-installed build alone', () => {
+ // The whole point of the check: a source build or an unzipped release
+ // earlier on PATH must not be offered a `winget upgrade` that would swap a
+ // package the serving process is not using.
+ expect(isWingetManagedPath('C:\\tools\\llama.cpp\\llama-server.exe', WIN_ENV)).toBe(false);
+ expect(isWingetManagedPath('llama-server.exe', WIN_ENV)).toBe(false);
+ expect(isWingetManagedPath(null, WIN_ENV)).toBe(false);
+ });
+
+ it('claims nothing when the environment names no WinGet root', () => {
+ expect(isWingetManagedPath('C:\\Users\\example\\AppData\\Local\\Microsoft\\WinGet\\Links\\llama-server.exe', {}))
+ .toBe(false);
+ expect(wingetLinkDirs({})).toEqual([]);
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 4470a0bac6..2c05f189d3 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -689,10 +689,10 @@ router.get('/llama-server/status', asyncHandler(async (_req, res) => {
res.json({ ...status, presets, specTypes: SPEC_TYPE_SUGGESTIONS })
}))
-// GET /api/local-llm/llama-server/update-status — optional Homebrew/version
-// metadata for the Local LLMs page. Keep it out of the lifecycle status request:
-// a slow Homebrew installation or a backend-initializing `--version` probe must
-// not delay ordinary runtime status and preset rendering.
+// GET /api/local-llm/llama-server/update-status — optional package-manager and
+// version metadata for the Local LLMs page. Keep it out of the lifecycle status
+// request: a slow `brew info` / `winget list` or a backend-initializing
+// `--version` probe must not delay ordinary runtime status and preset rendering.
router.get('/llama-server/update-status', asyncHandler(async (_req, res) => {
res.json(await getLlamaServerUpdateStatus())
}))
@@ -741,7 +741,8 @@ router.post('/llama-server/stop', asyncHandler(async (_req, res) => {
res.json(result)
}))
-// POST /api/local-llm/llama-server/install — install llama.cpp via Homebrew
+// POST /api/local-llm/llama-server/install — install llama.cpp through this
+// platform package manager (Homebrew on macOS/Linux, winget on Windows)
router.post('/llama-server/install', asyncHandler(async (req, res) => {
const io = req.app.get('io')
const onProgress = (data) => io?.emit('localLlm:progress', data)
@@ -750,7 +751,7 @@ router.post('/llama-server/install', asyncHandler(async (req, res) => {
res.json(result)
}))
-// POST /api/local-llm/llama-server/upgrade — update a Homebrew-installed
+// POST /api/local-llm/llama-server/upgrade — update a package-manager-installed
// llama.cpp binary, restarting a llama-server process PortOS owns with the same
// launch configuration. An externally-started process is left alone.
router.post('/llama-server/upgrade', asyncHandler(async (req, res) => {
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index a8e919051a..6403dbaecb 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -7,6 +7,8 @@
*/
import { realpath, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { delimiter } from 'path';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
@@ -17,6 +19,14 @@ import { resolveSpecModelPath } from './specDecodeModels.js';
import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { isPortInUse } from '../lib/platform.js';
+import {
+ LLAMA_CPP_BREW_FORMULA,
+ LLAMA_CPP_DOWNLOAD_URL,
+ isWingetManagedPath,
+ llamaCppInstallPlan,
+ parseWingetPackageFields,
+ wingetLinkDirs,
+} from '../lib/llamaCppInstall.js';
import { PORTS } from '../lib/ports.js';
import { tuningSpecsFor } from '../lib/localModelTuning.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -37,10 +47,11 @@ const STARTUP_WAIT_TIMEOUT_MS = 4000;
const STARTUP_POLL_DELAY_MS = 500;
const RELAUNCH_READY_TIMEOUT_MS = 120000;
const RELAUNCH_POLL_DELAY_MS = 1000;
-const LLAMA_CPP_FORMULA = 'llama.cpp';
-const LLAMA_CPP_DOWNLOAD_URL = 'https://github.com/ggml-org/llama.cpp/releases';
const VERSION_PROBE_TIMEOUT_MS = 5000;
const BREW_INFO_TIMEOUT_MS = 15_000;
+// winget rebuilds its source index on the first query of a session, which takes
+// longer than any single `brew info`.
+const WINGET_LIST_TIMEOUT_MS = 60_000;
const UPGRADE_TIMEOUT_MS = 30 * 60 * 1000;
// `llama-server --help` is a fast local exec; this only bounds a wedged binary.
const HELP_PROBE_TIMEOUT_MS = 5000;
@@ -52,6 +63,10 @@ const SLEEP_IDLE_FLAG = '--sleep-idle-seconds';
const sleepIdleSupport = new Map();
// See `configuredSleepIdleMinutes`. Only `_resetLlamaServerStateForTests` writes it.
let sleepIdleMinutesOverride = null;
+// Which package manager PortOS drives for llama.cpp. Only the test seam writes
+// it, so both the Homebrew and the winget path stay coverable from either OS.
+let platformOverride = null;
+const installPlan = () => llamaCppInstallPlan(platformOverride || process.platform);
// How long a relaunch waits for the kernel to release the old listener.
const PORT_RELEASE_TIMEOUT_MS = 5000;
// How long a relaunch waits for the new process to answer. `startLlamaServer`
@@ -131,7 +146,7 @@ async function readLlamaServerVersion(binaryPath) {
async function readBrewLlamaCppInfo() {
const result = await readCommandOutput(
'brew',
- ['info', '--json=v2', '--formula', LLAMA_CPP_FORMULA],
+ ['info', '--json=v2', '--formula', LLAMA_CPP_BREW_FORMULA],
BREW_INFO_TIMEOUT_MS,
);
if (result.error) return null;
@@ -139,12 +154,12 @@ async function readBrewLlamaCppInfo() {
return Promise.resolve()
.then(() => JSON.parse(result.stdout))
.then(async (payload) => {
- const formula = payload?.formulae?.find((entry) => entry?.name === LLAMA_CPP_FORMULA);
+ const formula = payload?.formulae?.find((entry) => entry?.name === LLAMA_CPP_BREW_FORMULA);
const installed = formula?.installed?.[0];
if (!installed) return null;
const prefixResult = await readCommandOutput(
'brew',
- ['--prefix', LLAMA_CPP_FORMULA],
+ ['--prefix', LLAMA_CPP_BREW_FORMULA],
BREW_INFO_TIMEOUT_MS,
);
return {
@@ -179,6 +194,74 @@ async function isHomebrewLlamaServer(binaryPath, brewInfo) {
return Boolean(activePath && homebrewPath && activePath === homebrewPath);
}
+/**
+ * Homebrew's answer to "what is installed, is it stale, and may PortOS update
+ * it?", in the shape every caller below consumes.
+ *
+ * `blockedReason` is what makes this the single manager-specific step: a pinned
+ * or unlinked formula, or a source build sitting earlier on PATH, all stay the
+ * user's to update by hand, and each refusal has to say which. `null` means
+ * PortOS may run the upgrade, so `canUpgrade` is simply its absence.
+ */
+async function readBrewPackageStatus(binaryPath) {
+ const brewInfo = await readBrewLlamaCppInfo();
+ if (!brewInfo) return null;
+ const blockedReason = brewInfo.pinned
+ ? 'llama.cpp is pinned in Homebrew. Unpin it before asking PortOS to update it.'
+ : !brewInfo.linked
+ ? 'Homebrew has llama.cpp installed, but its keg is not linked to the llama-server on PATH. Link the formula manually before asking PortOS to update it.'
+ : !(await isHomebrewLlamaServer(binaryPath, brewInfo))
+ ? `The active llama-server is not the linked Homebrew llama.cpp binary, so PortOS left it untouched. Update that installation manually: ${LLAMA_CPP_DOWNLOAD_URL}`
+ : null;
+ return {
+ installedVersion: brewInfo.installedVersion || null,
+ latestVersion: brewInfo.latestVersion || null,
+ outdated: brewInfo.outdated === true,
+ canUpgrade: blockedReason === null,
+ blockedReason,
+ };
+}
+
+/**
+ * The same shape, read from winget.
+ *
+ * winget has no `brew info --json` equivalent, so this asks two questions in
+ * parallel instead of parsing one payload: `winget list` says whether the
+ * package is installed at all (and at what version), and the same query with
+ * `--upgrade-available` lists it only when a newer build exists. Neither answer
+ * is a version comparison PortOS performs — llama.cpp versions are build
+ * numbers (`b10730`), which no semver comparison orders correctly.
+ */
+async function readWingetPackageStatus(binaryPath, plan) {
+ const [listed, upgradable] = await Promise.all([
+ readCommandOutput('winget', plan.listArgs, WINGET_LIST_TIMEOUT_MS),
+ readCommandOutput('winget', plan.upgradeCheckArgs, WINGET_LIST_TIMEOUT_MS),
+ ]);
+ if (listed.error) return null;
+ const installedFields = parseWingetPackageFields(listed.stdout, plan.packageId);
+ if (!installedFields) return null;
+ // Only the `--upgrade-available` table is guaranteed to carry the `Available`
+ // column, so the newer version is read from that run and nowhere else.
+ const upgradeFields = upgradable.error ? null : parseWingetPackageFields(upgradable.stdout, plan.packageId);
+ const ours = isWingetManagedPath(binaryPath);
+ return {
+ installedVersion: installedFields[0] || null,
+ latestVersion: upgradeFields?.[1] || null,
+ outdated: Boolean(upgradeFields),
+ canUpgrade: ours,
+ blockedReason: ours
+ ? null
+ : `The active llama-server is not the winget-installed llama.cpp, so PortOS left it untouched. Update that installation manually: ${LLAMA_CPP_DOWNLOAD_URL}`,
+ };
+}
+
+/** Package metadata for whichever manager this platform uses, or `null`. */
+const readPackageStatus = (plan, binaryPath) => (
+ plan.manager === 'winget'
+ ? readWingetPackageStatus(binaryPath, plan)
+ : readBrewPackageStatus(binaryPath)
+);
+
/**
* Probes whether an OpenAI-compatible endpoint responds at the given host/port.
* Shares one implementation with the readiness checklist.
@@ -379,9 +462,18 @@ export async function getLlamaServerEndpoint() {
export async function getLlamaServerStatus() {
const binaryPath = resolveLlamaServerBinary();
const installed = Boolean(binaryPath);
+ const plan = installPlan();
return {
...await daemon.getStatusBase({ installed }),
+ // How llama.cpp is installed HERE, so the LLMs page can name the command
+ // instead of guessing. Carried on the lifecycle status rather than on the
+ // update probe below, because the not-installed card is exactly the one
+ // that has to name it — and it never reaches that probe, which needs a
+ // binary to ask about.
+ packageManager: plan.manager,
+ packageManagerLabel: plan.managerLabel,
+ installCommand: plan.installCommand,
// The SAVED window, which is what the settings field edits. What the running
// process actually got is `config.sleepIdleMinutes` — they differ until the
// next start, because this is a launch flag.
@@ -390,7 +482,7 @@ export async function getLlamaServerStatus() {
}
/**
- * Check whether the installed llama.cpp formula has a newer Homebrew build.
+ * Check whether this platform's package manager has a newer llama.cpp build.
* This is kept separate from the lifecycle status probe because the latter is
* also used by performance/ownership paths that must remain disk-and-process
* local; the LLMs page calls this explicit update-information path.
@@ -407,16 +499,15 @@ export async function getLlamaServerUpdateStatus() {
};
}
- const [version, brewInfo] = await Promise.all([
+ const [version, packageStatus] = await Promise.all([
readLlamaServerVersion(binaryPath),
- readBrewLlamaCppInfo(),
+ readPackageStatus(installPlan(), binaryPath),
]);
- const homebrewBinary = await isHomebrewLlamaServer(binaryPath, brewInfo);
return {
- version: version || brewInfo?.installedVersion || null,
- latestVersion: brewInfo?.latestVersion || null,
- updateAvailable: Boolean(brewInfo?.outdated),
- canUpgrade: Boolean(brewInfo?.linked && !brewInfo.pinned && homebrewBinary),
+ version: version || packageStatus?.installedVersion || null,
+ latestVersion: packageStatus?.latestVersion || null,
+ updateAvailable: Boolean(packageStatus?.outdated),
+ canUpgrade: Boolean(packageStatus?.canUpgrade),
downloadUrl: LLAMA_CPP_DOWNLOAD_URL,
};
}
@@ -451,7 +542,7 @@ export async function startLlamaServer(options = {}) {
const binaryPath = resolveLlamaServerBinary();
if (!binaryPath) {
throw new ServerError(
- 'llama-server binary was not found on PATH. Install it via Homebrew (`brew install llama.cpp`) or build from source.',
+ `llama-server binary was not found on PATH. Install it with \`${installPlan().installCommand}\` or build from source.`,
{ status: 400 }
);
}
@@ -764,44 +855,39 @@ async function upgradeFailureResult(message, managedConfig, baseline, updated =
}
/**
- * Upgrade a Homebrew-installed llama.cpp binary in place.
+ * Refuse an upgrade PortOS has no business running, with the reason.
+ *
+ * A package PortOS did not install — a source build, a hand-extracted release
+ * zip, a pinned or unlinked keg — must be left alone: swapping the package would
+ * not touch the binary actually on PATH, so the user would be told their runtime
+ * was updated while the serving process stayed exactly as stale as before.
*
- * A managed llama-server is stopped before Homebrew swaps the binary and then
- * restarted with the exact launch configuration it was using. An external
- * process is never stopped; changing the package only takes effect for it when
- * its owner starts it again.
+ * Manager-agnostic on purpose: `readPackageStatus` is the ONE place that knows
+ * how each package manager answers "may PortOS update this?", so a new manager
+ * is registered there and in its plan rather than adding a branch here.
+ *
+ * @returns {Promise<object|null>} a failure result, or `null` to proceed
*/
-export async function upgradeLlamaServer({ onProgress = () => {} } = {}) {
- const brewInfo = await readBrewLlamaCppInfo();
- if (!brewInfo) {
- return {
- success: false,
- error: `llama.cpp is not installed through Homebrew, so PortOS cannot update it here. Install it with Homebrew or update your source build manually: ${LLAMA_CPP_DOWNLOAD_URL}`,
- };
- }
- if (brewInfo.pinned) {
- return {
- success: false,
- manualUpdateRequired: true,
- error: 'llama.cpp is pinned in Homebrew. Unpin it before asking PortOS to update it.',
- };
- }
- if (!brewInfo.linked) {
- return {
- success: false,
- manualUpdateRequired: true,
- error: 'Homebrew has llama.cpp installed, but its keg is not linked to the llama-server on PATH. Link the formula manually before asking PortOS to update it.',
- };
- }
+async function upgradePreflight(plan, binaryPath) {
+ const status = await readPackageStatus(plan, binaryPath);
+ if (!status) return { success: false, error: plan.notInstalledError };
+ if (status.canUpgrade) return null;
+ return { success: false, manualUpdateRequired: true, error: status.blockedReason };
+}
+/**
+ * Upgrade a package-manager-installed llama.cpp binary in place.
+ *
+ * A managed llama-server is stopped before the package manager swaps the binary
+ * and then restarted with the exact launch configuration it was using. An
+ * external process is never stopped; changing the package only takes effect for
+ * it when its owner starts it again.
+ */
+export async function upgradeLlamaServer({ onProgress = () => {} } = {}) {
+ const plan = installPlan();
const binaryPath = resolveLlamaServerBinary();
- if (!(await isHomebrewLlamaServer(binaryPath, brewInfo))) {
- return {
- success: false,
- manualUpdateRequired: true,
- error: `The active llama-server is not the linked Homebrew llama.cpp binary, so PortOS left it untouched. Update that installation manually: ${LLAMA_CPP_DOWNLOAD_URL}`,
- };
- }
+ const refusal = await upgradePreflight(plan, binaryPath);
+ if (refusal) return refusal;
const launch = await readLlamaServerLaunch();
if (launch.readFailed) {
@@ -830,35 +916,27 @@ export async function upgradeLlamaServer({ onProgress = () => {} } = {}) {
}
}
- onProgress({ event: 'progress', message: 'Updating llama.cpp via Homebrew…' });
+ onProgress({ event: 'progress', message: `Updating llama.cpp via ${plan.managerLabel}…` });
const upgraded = await runStreamingCommand(
- 'brew',
- ['upgrade', LLAMA_CPP_FORMULA],
+ plan.manager,
+ plan.upgradeArgs,
(message) => onProgress({ event: 'progress', message }),
{ timeoutMs: UPGRADE_TIMEOUT_MS },
);
if (!upgraded.success) {
return upgradeFailureResult(
- `llama.cpp upgrade failed: ${upgraded.error || 'Homebrew reported an unknown error'}.`,
+ `llama.cpp upgrade failed: ${upgraded.error || `${plan.managerLabel} reported an unknown error`}.`,
managedConfig,
baseline,
);
}
- // Homebrew normally keeps a linked formula linked across an upgrade, but an
- // unlinked keg should not leave the newly-upgraded runtime invisible to PATH.
if (!resolveLlamaServerBinary()) {
- onProgress({ event: 'progress', message: 'llama.cpp upgraded but is not linked — linking…' });
- const linked = await runStreamingCommand(
- 'brew',
- ['link', '--overwrite', LLAMA_CPP_FORMULA],
- (message) => onProgress({ event: 'progress', message }),
- { timeoutMs: 60_000 },
- );
- if (!linked.success || !resolveLlamaServerBinary()) {
+ const { repaired, detail } = await repairBinaryOnPath(plan, safeChildProcessEnv(), onProgress);
+ if (!repaired) {
return upgradeFailureResult(
- `llama.cpp was upgraded, but its llama-server binary is not on PATH${linked.error ? `: ${linked.error}` : '.'}`,
+ `llama.cpp was upgraded, but its llama-server binary is not on PATH${detail ? `: ${detail}` : '.'}`,
managedConfig,
baseline,
true,
@@ -1336,7 +1414,7 @@ function linkLlamaCpp(env) {
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
});
- const child = spawn('brew', ['link', '--overwrite', 'llama.cpp'], spawnOpts);
+ const child = spawn('brew', ['link', '--overwrite', LLAMA_CPP_BREW_FORMULA], spawnOpts);
let output = '';
const collect = (chunk) => { output += chunk.toString(); };
child.stdout?.on('data', collect);
@@ -1351,18 +1429,70 @@ function linkLlamaCpp(env) {
}
/**
- * Installs llama.cpp via Homebrew.
+ * Adopt winget's portable-shim directory onto this process's PATH.
+ *
+ * winget links a portable package's executables into a Links directory and adds
+ * that directory to the USER environment — a change an already-running PortOS
+ * does not inherit, so a perfectly successful install would otherwise report
+ * "llama-server was not found on PATH" until the server was restarted. Extending
+ * `process.env.PATH` fixes both this process's own lookups and every child it
+ * spawns, since `safeChildProcessEnv` derives from `process.env`.
+ *
+ * @returns {string|null} the newly-visible binary path, or null if it is not there
+ */
+function adoptWingetLinkDirs() {
+ const existing = (process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
+ // Only directories that are actually there: `findCommandOnPath` walks every
+ // PATH entry against every PATHEXT extension with a synchronous stat, so a
+ // dead entry taxes every later lookup for the life of the process.
+ const missing = wingetLinkDirs().filter((dir) => !existing.includes(dir) && existsSync(dir));
+ if (missing.length > 0) process.env.PATH = [...existing, ...missing].join(delimiter);
+ return resolveLlamaServerBinary();
+}
+
+/**
+ * Put llama.cpp's binary on PATH when the package manager left it off.
+ *
+ * The two managers land in this state for different reasons and get out of it
+ * in different ways, but from here they look identical — the manager reports a
+ * package it installed, and PATH still finds nothing. `brew install`/`brew
+ * upgrade` can leave a keg unlinked ("Warning: llama.cpp X is already
+ * installed, it's just not linked."); winget puts its portable shims in a Links
+ * directory it adds to the USER environment, which an already-running PortOS has
+ * not inherited. Shared by the install and upgrade paths so a change to either
+ * story is made once.
+ *
+ * Resolves rather than rejecting: a failed repair falls through to the caller's
+ * own error message, and `detail` is what makes that message diagnosable.
+ *
+ * @returns {Promise<{repaired: boolean, detail: string|null}>}
+ */
+async function repairBinaryOnPath(plan, env, onProgress) {
+ if (plan.manager === 'winget') {
+ return { repaired: Boolean(adoptWingetLinkDirs()), detail: null };
+ }
+ onProgress({ event: 'progress', message: 'llama.cpp is installed but not linked — linking…' });
+ const { linked, output } = await linkLlamaCpp(env);
+ return {
+ repaired: Boolean(linked && resolveLlamaServerBinary()),
+ // A `brew link` conflict can list every clashing file, so cap what rides
+ // along into the caller's error message.
+ detail: output ? output.slice(0, 500) : null,
+ };
+}
+
+/**
+ * Installs llama.cpp through this platform's package manager — Homebrew on
+ * macOS/Linux, winget on Windows.
*/
export async function installLlamaServer({ onProgress = () => {} } = {}) {
- const brewExists = await commandExists('brew', ['--version']);
- if (!brewExists) {
- throw new ServerError(
- 'Homebrew was not found. Please install Homebrew from https://brew.sh or build llama.cpp from source.',
- { status: 400 }
- );
+ const plan = installPlan();
+ const managerExists = await commandExists(plan.manager, ['--version']);
+ if (!managerExists) {
+ throw new ServerError(plan.missingManagerError, { status: 400 });
}
- onProgress({ event: 'start', message: 'Installing llama.cpp via Homebrew…' });
+ onProgress({ event: 'start', message: `Installing llama.cpp via ${plan.managerLabel}…` });
const env = safeChildProcessEnv();
const spawnOpts = safeChildProcessOptions({
env,
@@ -1370,7 +1500,7 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
stdio: ['ignore', 'pipe', 'pipe'],
});
- const child = spawn('brew', ['install', 'llama.cpp'], spawnOpts);
+ const child = spawn(plan.manager, plan.installArgs, spawnOpts);
return new Promise((resolve, reject) => {
child.stdout?.on('data', (d) => {
@@ -1388,7 +1518,7 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
child.on('error', (err) => {
if (settled) return;
settled = true;
- reject(new ServerError(`Failed to run brew: ${err.message}`, { status: 500 }));
+ reject(new ServerError(`Failed to run ${plan.manager}: ${err.message}`, { status: 500 }));
});
// Async listener on a child-process event: it runs outside the Express
// lifecycle AND outside this Promise executor's own throw path, so an
@@ -1399,17 +1529,14 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
settled = true;
try {
let binaryPath = resolveLlamaServerBinary();
- let linkOutput = '';
-
- // `brew install` exits 0 without linking when the keg is already
- // installed but unlinked ("Warning: llama.cpp X is already installed,
- // it's just not linked."). Link it explicitly rather than leaving that
- // warning as a dead end for the caller.
+ // The manager reported success but PATH finds nothing — an unlinked keg
+ // or a Links directory this process has not picked up. Repair it rather
+ // than leaving that as a dead end for the caller.
+ let repairDetail = null;
if (!binaryPath && code === 0) {
- onProgress({ event: 'progress', message: 'llama.cpp keg is installed but not linked — linking…' });
- const { linked, output } = await linkLlamaCpp(env);
- linkOutput = output;
- if (linked) binaryPath = resolveLlamaServerBinary();
+ const repair = await repairBinaryOnPath(plan, env, onProgress);
+ repairDetail = repair.detail;
+ if (repair.repaired) binaryPath = resolveLlamaServerBinary();
}
if (binaryPath) {
@@ -1418,14 +1545,10 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
return;
}
- // A `brew link` conflict can list every clashing file, so cap what
- // rides along into the error message.
- const hint = linkOutput
- ? `brew link said: ${linkOutput.slice(0, 500)}`
- : 'try running `brew link --overwrite llama.cpp` manually';
+ const hint = repairDetail ? `${plan.manager} said: ${repairDetail}` : plan.pathRepairHint;
const msg = code === 0
- ? `brew completed but llama-server was not found on PATH — ${hint}`
- : `brew install llama.cpp failed (exit code ${code})`;
+ ? `${plan.manager} completed but llama-server was not found on PATH — ${hint}`
+ : `${plan.installCommand} failed (exit code ${code})`;
reject(new ServerError(msg, { status: 500 }));
} catch (err) {
reject(new ServerError(`Failed to verify the llama.cpp install: ${err.message}`, { status: 500 }));
@@ -1444,10 +1567,14 @@ export function _resetLlamaServerStateForTests({
relaunchPollDelay,
pm2ReadRetryDelay,
sleepIdleMinutes = 0,
+ platform = null,
} = {}) {
sleepIdleSupport.clear();
// Pinned rather than read from disk — see `configuredSleepIdleMinutes`.
sleepIdleMinutesOverride = sleepIdleMinutes;
+ // `null` = use the real host platform, which is what every suite that is not
+ // specifically exercising the other package manager's path wants.
+ platformOverride = platform;
currentConfig = null;
preTuningConfig = null;
daemon.resetLogs();
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index f56043d3b1..79e9349d39 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -25,7 +25,7 @@ import { PORTS } from '../lib/ports.js';
import { EventEmitter } from 'events';
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
-import { join } from 'path';
+import { delimiter, join } from 'path';
function fakeSpawnProcess() {
const child = new EventEmitter();
@@ -50,8 +50,11 @@ const FAST_TIMING = {
pm2ReadRetryDelay: 0,
};
+// Pinned to darwin so the Homebrew paths are exercised identically on every
+// developer's OS — otherwise the same assertions would run against winget on a
+// Windows checkout. The winget half pins `platform: 'win32'` the same way.
const resetForTest = (overrides = {}) => {
- _resetLlamaServerStateForTests({ ...FAST_TIMING, ...overrides });
+ _resetLlamaServerStateForTests({ ...FAST_TIMING, platform: 'darwin', ...overrides });
};
const brewInfoJson = ({ installedVersion = 'build-100', latestVersion = '0.3.0', outdated = true, pinned = false, linkedKeg = 'build-100' } = {}) => JSON.stringify({
@@ -772,6 +775,155 @@ describe('llamaServerManager', () => {
});
});
+ // ---- Windows (winget) ---------------------------------------------------
+ // llama.cpp ships an official winget package, so Windows gets the same
+ // install/update buttons as macOS rather than a Homebrew command it cannot
+ // run. Everything here pins `platform: 'win32'` so the branch is covered from
+ // any developer's OS.
+ describe('winget', () => {
+ const WINGET_BINARY = 'C:\\Users\\example\\AppData\\Local\\Microsoft\\WinGet\\Links\\llama-server.exe';
+ const wingetTable = (available) => [
+ 'Name Id Version Available Source',
+ '-------------------------------------------------',
+ `llama.cpp ggml.llamacpp b10500 ${available ? 'b10730 ' : ''}winget`,
+ ].join('\n');
+ // `--upgrade-available` lists the package ONLY when a newer build exists;
+ // the plain listing always does. That difference is the staleness signal.
+ const stubWinget = ({ installed = true, outdated = true } = {}) =>
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command, args) => {
+ if (command !== 'winget') return { success: true, code: 0, stdout: 'version: b10500', stderr: '', timedOut: false };
+ const checkingUpgrade = args.includes('--upgrade-available');
+ const listed = installed && (!checkingUpgrade || outdated);
+ return {
+ success: true,
+ code: 0,
+ stdout: listed ? wingetTable(checkingUpgrade) : 'No installed package found matching input criteria.',
+ stderr: '',
+ timedOut: false,
+ };
+ });
+
+ beforeEach(() => {
+ resetForTest({ platform: 'win32' });
+ vi.stubEnv('LOCALAPPDATA', 'C:\\Users\\example\\AppData\\Local');
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+
+ it('names the winget command on a host with no llama-server', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);
+
+ await expect(getLlamaServerStatus()).resolves.toMatchObject({
+ installed: false,
+ packageManager: 'winget',
+ packageManagerLabel: 'winget',
+ installCommand: 'winget install ggml.llamacpp',
+ });
+ });
+
+ it('reports an available winget build as an update PortOS can apply', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(WINGET_BINARY);
+ const buffered = stubWinget();
+
+ await expect(getLlamaServerUpdateStatus()).resolves.toMatchObject({
+ version: 'b10500',
+ latestVersion: 'b10730',
+ updateAvailable: true,
+ canUpgrade: true,
+ });
+ expect(buffered).toHaveBeenCalledWith(
+ 'winget',
+ ['list', '--id', 'ggml.llamacpp', '--exact', '--disable-interactivity', '--upgrade-available'],
+ { timeoutMs: 60_000, shell: false },
+ );
+ });
+
+ it('keeps a hand-installed Windows build updateable by manual means only', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('C:\\tools\\llama.cpp\\llama-server.exe');
+ stubWinget();
+
+ await expect(getLlamaServerUpdateStatus()).resolves.toMatchObject({
+ latestVersion: 'b10730',
+ updateAvailable: true,
+ canUpgrade: false,
+ });
+ });
+
+ it('installs through winget without any Homebrew step', async () => {
+ vi.spyOn(commandExistsModule, 'commandExists').mockImplementation(async (cmd) => cmd === 'winget');
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(WINGET_BINARY);
+ const spawnCalls = [];
+ vi.spyOn(childProcess, 'spawn').mockImplementation((cmd, args) => {
+ spawnCalls.push({ cmd, args });
+ const child = fakeSpawnProcess();
+ setTimeout(() => endProcess(child, 0), 10);
+ return child;
+ });
+
+ await expect(installLlamaServer()).resolves.toMatchObject({ success: true });
+ expect(spawnCalls).toEqual([{
+ cmd: 'winget',
+ args: ['install', '--id', 'ggml.llamacpp', '--exact', '--disable-interactivity', '--accept-source-agreements', '--accept-package-agreements'],
+ }]);
+ });
+
+ it("adopts winget's Links directory when the new shim is not on PATH yet", async () => {
+ // winget adds that directory to the USER environment, a change an already
+ // running PortOS never inherits — so a perfectly successful install would
+ // otherwise report "llama-server was not found on PATH" until a restart.
+ const localAppData = await mkdtemp(join(tmpdir(), 'portos-winget-'));
+ const links = join(localAppData, 'Microsoft', 'WinGet', 'Links');
+ await mkdir(links, { recursive: true });
+ vi.stubEnv('LOCALAPPDATA', localAppData);
+ vi.stubEnv('PATH', process.env.PATH || '');
+ vi.spyOn(commandExistsModule, 'commandExists').mockImplementation(async (cmd) => cmd === 'winget');
+ vi.spyOn(processEnv, 'findCommandOnPath').mockImplementation(() => (
+ (process.env.PATH || '').split(delimiter).includes(links) ? join(links, 'llama-server.exe') : null
+ ));
+ vi.spyOn(childProcess, 'spawn').mockImplementation(() => {
+ const child = fakeSpawnProcess();
+ setTimeout(() => endProcess(child, 0), 10);
+ return child;
+ });
+
+ await expect(installLlamaServer()).resolves.toMatchObject({ success: true });
+ expect((process.env.PATH || '').split(delimiter)).toContain(links);
+ await rm(localAppData, { recursive: true, force: true });
+ });
+ it('rejects install with a winget hint rather than a Homebrew one', async () => {
+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(false);
+
+ await expect(installLlamaServer()).rejects.toThrow(/winget was not found/i);
+ });
+
+ it('updates a winget installation in place', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(WINGET_BINARY);
+ stubWinget();
+ const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockResolvedValue({ success: true });
+
+ await expect(upgradeLlamaServer()).resolves.toMatchObject({ success: true });
+ expect(stream).toHaveBeenCalledWith(
+ 'winget',
+ ['upgrade', '--id', 'ggml.llamacpp', '--exact', '--disable-interactivity', '--accept-source-agreements', '--accept-package-agreements'],
+ expect.any(Function),
+ { timeoutMs: 30 * 60 * 1000 },
+ );
+ });
+
+ it('refuses to update a llama-server winget did not install', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('C:\\tools\\llama.cpp\\llama-server.exe');
+ stubWinget();
+ const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand');
+
+ await expect(upgradeLlamaServer()).resolves.toMatchObject({
+ success: false,
+ manualUpdateRequired: true,
+ error: expect.stringMatching(/not the winget-installed llama\.cpp/i),
+ });
+ expect(stream).not.toHaveBeenCalled();
+ });
+ });
+
// ---- tuning relaunch ----------------------------------------------------
// The sweep half of measured assessments: put new flags on the launch line
// between runs. Every failure mode here has to leave the daemon USABLE — it