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

feat: add in-app llama.cpp updates

[._.]/ Adam Eivy646f4d342369
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 62d1900481..a3ce17face 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -10,7 +10,7 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import {
getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
deleteLocalLlmModel, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,
- installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,
+ installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer,
downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,
searchMtplxModels, pullMtplxModel, removeMtplxModel,
saveRuntimeStartupList
@@ -478,6 +478,11 @@ export function LocalLlmTab() {
() => installLlamaServer(),
'llama.cpp installed'
).then(loadLlamaStatus);
+ const runtimeUpgradeLlama = () => runAction(
+ 'runtime-upgrade-llama',
+ () => upgradeLlamaServer(),
+ (r) => r?.note || 'llama.cpp updated'
+ ).then(loadLlamaStatus);
const runtimeStopLlama = () => runAction(
'runtime-stop-llama',
() => stopLlamaServer(),
@@ -916,6 +921,7 @@ export function LocalLlmTab() {
onControlLmStudio={controlLmStudio}
onInstallBackend={installRuntimeBackend}
onInstallLlama={runtimeInstallLlama}
+ onUpgradeLlama={runtimeUpgradeLlama}
onStopLlama={runtimeStopLlama}
onConfigureLlama={() => scrollTo(llamaSectionRef)}
onConfigureMtplx={() => scrollTo(mtplxSectionRef)}
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 5d7af92cb5..678024b6ce 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -29,6 +29,7 @@ vi.mock('../../services/api', () => ({
startLlamaServer: vi.fn(),
stopLlamaServer: vi.fn(),
installLlamaServer: vi.fn().mockResolvedValue({ success: true }),
+ upgradeLlamaServer: vi.fn().mockResolvedValue({ success: true, note: 'updated' }),
downloadSpecDecodeModel: vi.fn(),
cancelSpecDecodeModelDownload: vi.fn(),
}));
@@ -888,6 +889,25 @@ describe('LocalLlmTab llama-server management', () => {
});
});
+ it('updates llama.cpp from the unified runtime row', async () => {
+ const { getLlamaServerStatus, upgradeLlamaServer } = await import('../../services/api');
+ getLlamaServerStatus.mockResolvedValue(llamaReady({
+ version: '0.1.1-dev',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: true,
+ }));
+ upgradeLlamaServer.mockResolvedValueOnce({ success: true, note: 'updated and restarted' });
+
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Update to v0.3.0' }));
+
+ await waitFor(() => {
+ expect(upgradeLlamaServer).toHaveBeenCalledWith();
+ });
+ });
+
it('renders running badge and stops server when llama-server is managed', async () => {
const { getLlamaServerStatus, stopLlamaServer } = await import('../../services/api');
getLlamaServerStatus.mockResolvedValue({
diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsx
index c0cad71868..3233023a65 100644
--- a/client/src/components/settings/RuntimeServersCard.jsx
+++ b/client/src/components/settings/RuntimeServersCard.jsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router';
-import { Cpu, Box, Zap, Gauge, Play, Square, Download, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';
+import { Cpu, Box, Zap, Gauge, Play, Square, Download, ArrowUpCircle, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
/**
@@ -65,8 +65,9 @@ function backendRow({ id, label, icon, data, onStart, onStop, onInstall }) {
* answers on the port means a server the user started in a terminal, which
* PortOS must not offer to stop.
*/
-function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onInstall, startBlockedReason, detail }) {
+function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onInstall, onUpgrade, startBlockedReason, detail }) {
const external = status?.running && status?.managed === false;
+ const updateAvailable = !platformReason && status?.installed && status?.updateAvailable === true;
const state = platformReason ? 'unsupported'
: status?.running ? (external ? 'external' : 'running')
: status?.installed ? 'stopped' : 'missing';
@@ -86,6 +87,11 @@ function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onIn
onStart: !platformReason && status?.installed && !status?.running && !startBlockedReason ? onStart : null,
startBlockedReason: status?.installed && !status?.running ? startBlockedReason : null,
onStop: !external && status?.running ? onStop : null,
+ version: status?.version || null,
+ latestVersion: status?.latestVersion || null,
+ updateAvailable,
+ onUpgrade: updateAvailable && status?.canUpgrade ? onUpgrade : null,
+ updateUrl: updateAvailable && !status?.canUpgrade ? status?.downloadUrl : null,
};
}
@@ -168,6 +174,15 @@ function ServerRow({ row, busy, actionInProgress, children }) {
{row.endpoint && (
<code className="text-xs text-gray-500 truncate max-w-full">{row.endpoint}</code>
)}
+ {row.version && <span className="text-xs text-gray-500">v{row.version}</span>}
+ {row.updateAvailable && row.latestVersion && (
+ <span
+ className="text-xs text-port-warning"
+ title={`${row.label} v${row.latestVersion} is available (you have ${row.version ? `v${row.version}` : 'an older version'})`}
+ >
+ v{row.latestVersion} available
+ </span>
+ )}
{row.pm2 && row.runAtStartup && (
<span className="px-1.5 py-0.5 text-xs rounded border border-port-success/40 text-port-success" title="This PM2 process is in the saved list `pm2 resurrect` replays at boot">
starts at boot
@@ -225,6 +240,29 @@ function ServerRow({ row, busy, actionInProgress, children }) {
Stop
</button>
)}
+ {row.onUpgrade && (
+ <button
+ 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`}
+ >
+ {actionInProgress === `runtime-upgrade-${row.id}` ? <BrailleSpinner /> : <ArrowUpCircle size={12} />}
+ {row.latestVersion ? `Update to v${row.latestVersion}` : 'Update'}
+ </button>
+ )}
+ {row.updateUrl && (
+ <a
+ href={row.updateUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={`${neutralBtn} no-underline text-port-warning`}
+ title={`${row.label} has an update, but PortOS cannot update this installation automatically`}
+ >
+ <ExternalLink size={12} />
+ Update available
+ </a>
+ )}
</div>
</div>
);
@@ -242,6 +280,7 @@ export default function RuntimeServersCard({
onControlLmStudio,
onInstallBackend,
onInstallLlama,
+ onUpgradeLlama,
onStopLlama,
onConfigureLlama,
onConfigureMtplx,
@@ -282,6 +321,7 @@ export default function RuntimeServersCard({
icon: Zap,
status: llamaStatus,
onInstall: onInstallLlama,
+ onUpgrade: onUpgradeLlama,
onStop: onStopLlama,
// llama-server takes a REQUIRED model path, and which GGUF (plus which
// drafter and spec type) is a real choice — so there is no honest one-click
diff --git a/client/src/components/settings/RuntimeServersCard.test.jsx b/client/src/components/settings/RuntimeServersCard.test.jsx
index f5590a5993..38e5652ea2 100644
--- a/client/src/components/settings/RuntimeServersCard.test.jsx
+++ b/client/src/components/settings/RuntimeServersCard.test.jsx
@@ -14,6 +14,7 @@ const renderCard = (props = {}) => {
onControlLmStudio: vi.fn(),
onInstallBackend: vi.fn(),
onInstallLlama: vi.fn(),
+ onUpgradeLlama: vi.fn(),
onStopLlama: vi.fn(),
onConfigureLlama: vi.fn(),
onConfigureMtplx: vi.fn(),
@@ -83,6 +84,46 @@ describe('RuntimeServersCard', () => {
expect(handlers.onConfigureLlama).toHaveBeenCalled();
});
+ it('shows a llama.cpp update and delegates the action to the runtime handler', () => {
+ const handlers = renderCard({
+ llamaStatus: {
+ installed: true,
+ running: false,
+ version: '0.1.1-dev',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: true,
+ },
+ });
+ const llama = row('llama.cpp');
+
+ expect(within(llama).getByText('v0.1.1-dev')).toBeInTheDocument();
+ expect(within(llama).getByText('v0.3.0 available')).toBeInTheDocument();
+ fireEvent.click(within(llama).getByRole('button', { name: 'Update to v0.3.0' }));
+
+ expect(handlers.onUpgradeLlama).toHaveBeenCalledWith();
+ });
+
+ it('links to llama.cpp release notes when Homebrew cannot update the installation', () => {
+ renderCard({
+ llamaStatus: {
+ installed: true,
+ running: false,
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: false,
+ downloadUrl: 'https://github.com/ggml-org/llama.cpp/releases',
+ },
+ });
+ const llama = row('llama.cpp');
+
+ expect(within(llama).queryByRole('button', { name: /Update to/ })).toBeNull();
+ expect(within(llama).getByRole('link', { name: /Update available/ })).toHaveAttribute(
+ 'href',
+ 'https://github.com/ggml-org/llama.cpp/releases',
+ );
+ });
+
// MTPLX cannot unload its checkpoint in place, so PortOS stops the process
// when it goes idle and the next request starts it again. A manual Start would
// only pin 20GB ahead of a request that may never come.
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 3804a79dc6..353d147d29 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -110,6 +110,11 @@ 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.
+export const upgradeLlamaServer = () =>
+ request('/local-llm/llama-server/upgrade', { method: 'POST' });
+
// Fetch one speculative-decoding preset's GGUF (role: 'model' | 'draftModel')
// from Hugging Face into the path the launcher passes llama.cpp. Byte progress
// arrives on the `llamaServer:download` socket event, not in this response —
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index a740402993..f818f80573 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -39,7 +39,14 @@ import {
localLlmMtplxRemoveSchema,
localLlmSpecModelDownloadSchema
} from '../lib/validation.js'
-import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'
+import {
+ getLlamaServerStatus,
+ getLlamaServerUpdateStatus,
+ startLlamaServer,
+ stopLlamaServer,
+ installLlamaServer,
+ upgradeLlamaServer,
+} from '../services/llamaServerManager.js'
import { MTPLX_APP, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'
import { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'
import { saveProcessList } from '../services/pm2.js'
@@ -636,10 +643,14 @@ router.post('/capability-tests/delete', asyncHandler(async (req, res) => {
// card can render "not downloaded + Download" instead of making the user press
// Start to discover a missing file. Disk-only: no Hugging Face call here.
router.get('/llama-server/status', asyncHandler(async (_req, res) => {
- const [status, presets] = await Promise.all([getLlamaServerStatus(), getSpecDecodePresetStatus()])
+ const [status, update, presets] = await Promise.all([
+ getLlamaServerStatus(),
+ getLlamaServerUpdateStatus(),
+ getSpecDecodePresetStatus(),
+ ])
// Spec-type suggestions ride along for the same reason the presets do: the
// card renders the server's list instead of keeping a copy that can rot.
- res.json({ ...status, presets, specTypes: SPEC_TYPE_SUGGESTIONS })
+ res.json({ ...status, ...update, presets, specTypes: SPEC_TYPE_SUGGESTIONS })
}))
// POST /api/local-llm/llama-server/download-model — fetch one preset's GGUF from
@@ -695,6 +706,25 @@ router.post('/llama-server/install', asyncHandler(async (req, res) => {
res.json(result)
}))
+// POST /api/local-llm/llama-server/upgrade — update a Homebrew-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) => {
+ const io = req.app.get('io')
+ const onProgress = (data) => io?.emit('localLlm:progress', data)
+ const result = await upgradeLlamaServer({ onProgress }).catch((err) => {
+ onProgress({ event: 'error', message: `llama.cpp update failed: ${err.message}` })
+ throw err
+ })
+ resetProviderReadinessCache()
+ if (!result.success) {
+ onProgress({ event: 'error', message: result.error || 'llama.cpp update failed' })
+ throw new ServerError(result.error || 'llama.cpp update failed', { status: 502 })
+ }
+ onProgress({ event: 'complete', message: `llama.cpp updated${result.note ? ` — ${result.note}` : ''}` })
+ res.json(result)
+}))
+
// === MTPLX (native-MTP Qwen on Apple Silicon) ================================
// Managed exactly like llama-server: a PM2 process (`portos-mtplx`) PortOS can
// start, stop, log, and — via /save-startup below — persist across a reboot.
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 53f28c8416..7acc3bba07 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -87,9 +87,17 @@ vi.mock('../services/localModelAgentBenchmark.js', () => ({
vi.mock('../services/llamaServerManager.js', () => ({
getLlamaServerStatus: vi.fn(async () => ({ installed: true, running: false })),
+ getLlamaServerUpdateStatus: vi.fn(async () => ({
+ version: null,
+ latestVersion: null,
+ updateAvailable: false,
+ canUpgrade: false,
+ downloadUrl: 'https://github.com/ggml-org/llama.cpp/releases',
+ })),
startLlamaServer: vi.fn(async () => ({ success: true, pid: 123 })),
stopLlamaServer: vi.fn(async () => ({ success: true })),
installLlamaServer: vi.fn(async () => ({ success: true, message: 'installed' })),
+ upgradeLlamaServer: vi.fn(async () => ({ success: true, note: 'updated' })),
}));
// The launcher's curated presets (and their weights' on-disk state) ride along
@@ -672,6 +680,26 @@ describe('llama-server routes', () => {
});
});
+ it('GET /api/local-llm/llama-server/status includes llama.cpp update metadata', async () => {
+ const { getLlamaServerUpdateStatus } = await import('../services/llamaServerManager.js');
+ getLlamaServerUpdateStatus.mockResolvedValueOnce({
+ version: '0.1.1-dev',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: true,
+ downloadUrl: 'https://github.com/ggml-org/llama.cpp/releases',
+ });
+
+ const res = await request(makeApp()).get('/api/local-llm/llama-server/status');
+
+ expect(res.body).toMatchObject({
+ version: '0.1.1-dev',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: true,
+ });
+ });
+
it('GET /api/local-llm/llama-server/status publishes the drafter-free spec types', async () => {
// The card renders the picker from this list, so a launch with no drafter
// GGUF (`ngram-map-k`) has to be reachable without the user knowing the
@@ -738,4 +766,20 @@ describe('llama-server routes', () => {
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true, message: 'installed' });
});
+
+ it('POST /api/local-llm/llama-server/upgrade emits progress and returns the result', async () => {
+ const { upgradeLlamaServer } = await import('../services/llamaServerManager.js');
+ upgradeLlamaServer.mockResolvedValueOnce({ success: true, note: 'updated and restarted' });
+ const app = makeApp();
+
+ const res = await request(app).post('/api/local-llm/llama-server/upgrade');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ success: true, note: 'updated and restarted' });
+ expect(upgradeLlamaServer).toHaveBeenCalledWith({ onProgress: expect.any(Function) });
+ expect(app.get('io').emit).toHaveBeenCalledWith(
+ 'localLlm:progress',
+ { event: 'complete', message: 'llama.cpp updated — updated and restarted' },
+ );
+ });
});
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 682aa423ba..3f7b7bbac6 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -20,6 +20,8 @@ import { isPortInUse } from '../lib/platform.js';
import { PORTS } from '../lib/ports.js';
import { tuningSpecsFor } from '../lib/localModelTuning.js';
import { ServerError } from '../lib/errorHandler.js';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { runStreamingCommand } from '../lib/streamingSpawn.js';
import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';
// `settings.js` is lazy-imported at its call sites below, never statically: it
// eagerly resolves `fileUtils.PATHS` at module load, which drags PATHS into the
@@ -32,6 +34,11 @@ export { LLAMA_APP };
const PROBE_TIMEOUT_MS = 1500;
const STARTUP_WAIT_TIMEOUT_MS = 4000;
+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;
+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;
// llama.cpp's own in-place idle unload. See `supportsSleepIdle`.
@@ -78,6 +85,68 @@ let currentConfig = null;
let preTuningConfig = null;
let lastExitError = null;
+/**
+ * Run a small local command and retain its output without throwing. Version and
+ * Homebrew metadata are optional decorations on status, so a missing/broken
+ * command must not take the runtime status endpoint down with it.
+ */
+async function readCommandOutput(command, args, timeoutMs) {
+ const result = await bufferedSpawn(command, args, { timeoutMs, shell: false });
+ return {
+ error: result.success
+ ? null
+ : result.error || new Error(result.timedOut ? `timed out after ${timeoutMs}ms` : `exited with code ${result.code}`),
+ stdout: result.stdout || '',
+ stderr: result.stderr || '',
+ };
+}
+
+/**
+ * Read the version printed by the installed llama-server binary. Different
+ * llama.cpp builds have used both `version: X` and `version X`, so accept both
+ * spellings while keeping the status field to the useful short version token.
+ */
+function parseLlamaServerVersion(output) {
+ const match = String(output || '').match(/\bversion\s*:?\s+([^\s(]+)/i);
+ return match?.[1]?.replace(/^v/, '') || null;
+}
+
+async function readLlamaServerVersion(binaryPath) {
+ const result = await readCommandOutput(binaryPath, ['--version'], VERSION_PROBE_TIMEOUT_MS);
+ return result.error ? null : parseLlamaServerVersion(`${result.stdout}\n${result.stderr}`);
+}
+
+/**
+ * Read Homebrew's formula metadata for the installed llama.cpp package.
+ * `outdated` is authoritative here: llama.cpp's installed Homebrew version is
+ * often a build number while the current formula uses a release version, so a
+ * generic semver comparison would report false positives.
+ */
+async function readBrewLlamaCppInfo() {
+ const result = await readCommandOutput(
+ 'brew',
+ ['info', '--json=v2', '--formula', LLAMA_CPP_FORMULA],
+ BREW_INFO_TIMEOUT_MS,
+ );
+ if (result.error) return null;
+
+ return Promise.resolve()
+ .then(() => JSON.parse(result.stdout))
+ .then((payload) => {
+ const formula = payload?.formulae?.find((entry) => entry?.name === LLAMA_CPP_FORMULA);
+ const installed = formula?.installed?.[0];
+ if (!installed) return null;
+ return {
+ installedVersion: String(installed.version || ''),
+ latestVersion: formula?.versions?.stable ? String(formula.versions.stable) : null,
+ outdated: formula.outdated === true,
+ pinned: formula.pinned === true,
+ linked: Boolean(formula.linked_keg),
+ };
+ })
+ .catch(() => null);
+}
+
/**
* Probes whether an OpenAI-compatible endpoint responds at the given host/port.
* Shares one implementation with the readiness checklist.
@@ -288,6 +357,37 @@ export async function getLlamaServerStatus() {
};
}
+/**
+ * Check whether the installed llama.cpp formula has a newer Homebrew 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.
+ */
+export async function getLlamaServerUpdateStatus() {
+ const binaryPath = resolveLlamaServerBinary();
+ if (!binaryPath) {
+ return {
+ version: null,
+ latestVersion: null,
+ updateAvailable: false,
+ canUpgrade: false,
+ downloadUrl: LLAMA_CPP_DOWNLOAD_URL,
+ };
+ }
+
+ const [version, brewInfo] = await Promise.all([
+ readLlamaServerVersion(binaryPath),
+ readBrewLlamaCppInfo(),
+ ]);
+ return {
+ version: version || brewInfo?.installedVersion || null,
+ latestVersion: brewInfo?.latestVersion || null,
+ updateAvailable: Boolean(brewInfo?.outdated),
+ canUpgrade: Boolean(brewInfo?.linked && !brewInfo.pinned),
+ downloadUrl: LLAMA_CPP_DOWNLOAD_URL,
+ };
+}
+
/**
* `getLlamaServerStatus`, re-read while PM2 answers nothing at all.
*
@@ -594,6 +694,153 @@ export async function stopLlamaServer() {
*/
const waitForPortRelease = daemon.waitForPortRelease;
+/**
+ * Put a managed server back after an upgrade attempt. The model may take longer
+ * than the normal port-release race, so wait before asking `startLlamaServer`
+ * to validate the preserved launch configuration.
+ */
+async function restartManagedLlamaServer(config, baseline) {
+ await waitForPortRelease(config.port ?? PORTS.LLAMA_SERVER);
+ const started = await startLlamaServer(config).catch((err) => {
+ console.error(`❌ llama-server: could not restore the previous configuration after update: ${err.message}`);
+ return null;
+ });
+ if (started) preTuningConfig = baseline;
+ return started;
+}
+
+async function upgradeFailureResult(message, managedConfig, baseline, updated = false) {
+ const restored = managedConfig ? await restartManagedLlamaServer(managedConfig, baseline) : null;
+ const restoreNote = managedConfig && !restored
+ ? ' PortOS could not restore the llama-server process.'
+ : '';
+ return {
+ success: false,
+ ...(updated ? { updated: true } : {}),
+ error: `${message}${restoreNote}`,
+ };
+}
+
+/**
+ * Upgrade a Homebrew-installed llama.cpp binary in place.
+ *
+ * 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.
+ */
+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.',
+ };
+ }
+
+ const launch = await readLlamaServerLaunch();
+ if (launch.readFailed) {
+ return {
+ success: false,
+ error: 'PortOS could not read PM2 to determine whether it owns llama-server. Try the update again in a moment.',
+ };
+ }
+ if (launch.managed && !launch.config?.model) {
+ return {
+ success: false,
+ error: 'PortOS could not recover llama-server\'s launch configuration, so it left the running process untouched.',
+ };
+ }
+ const managedConfig = launch.managed ? launch.config : null;
+ const baseline = preTuningConfig;
+
+ if (managedConfig) {
+ onProgress({ event: 'progress', message: 'Stopping llama-server before updating…' });
+ const stopped = await stopLlamaServer();
+ if (!stopped.success) {
+ return {
+ success: false,
+ error: stopped.message || 'PortOS could not stop the managed llama-server before updating.',
+ };
+ }
+ }
+
+ onProgress({ event: 'progress', message: 'Updating llama.cpp via Homebrew…' });
+ const upgraded = await runStreamingCommand(
+ 'brew',
+ ['upgrade', LLAMA_CPP_FORMULA],
+ (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'}.`,
+ 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()) {
+ return upgradeFailureResult(
+ `llama.cpp was upgraded, but its llama-server binary is not on PATH${linked.error ? `: ${linked.error}` : '.'}`,
+ managedConfig,
+ baseline,
+ true,
+ );
+ }
+ }
+
+ // A new binary may gain support for a cached compatibility flag such as
+ // --sleep-idle-seconds. Re-probe it before the preserved launch line returns.
+ sleepIdleSupport.clear();
+
+ if (managedConfig) {
+ onProgress({ event: 'progress', message: 'Restarting llama-server with its previous settings…' });
+ const restarted = await restartManagedLlamaServer(managedConfig, baseline);
+ if (!restarted) {
+ return {
+ success: false,
+ updated: true,
+ error: 'llama.cpp was upgraded, but llama-server could not be restarted with its previous settings.',
+ };
+ }
+ return {
+ success: true,
+ note: 'Updated llama.cpp and restarted llama-server with its previous settings.',
+ };
+ }
+
+ return {
+ success: true,
+ note: 'Updated llama.cpp. The new binary will be used the next time llama-server starts.',
+ };
+}
+
/**
* Block until the endpoint answers, or the readiness budget elapses.
* `false` means it never answered — which is a wedged process, not a slow one.
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index 2defbe8956..df8e501a3e 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -8,6 +8,8 @@ import {
captureLlamaServerConfig,
restoreLlamaServerConfig,
installLlamaServer,
+ getLlamaServerUpdateStatus,
+ upgradeLlamaServer,
_resetLlamaServerStateForTests,
LLAMA_APP,
} from './llamaServerManager.js';
@@ -17,6 +19,8 @@ import * as childProcess from '../lib/childProcess.js';
import * as platform from '../lib/platform.js';
import * as openAiModelsProbe from '../lib/openAiModelsProbe.js';
import * as pm2Module from './pm2.js';
+import * as bufferedSpawnModule from '../lib/bufferedSpawn.js';
+import * as streamingSpawnModule from '../lib/streamingSpawn.js';
import { PORTS } from '../lib/ports.js';
import { EventEmitter } from 'events';
import { mkdtemp, rm, writeFile } from 'fs/promises';
@@ -38,6 +42,17 @@ function endProcess(child, code) {
child.emit('close', code);
}
+const brewInfoJson = ({ installedVersion = 'build-100', latestVersion = '0.3.0', outdated = true, pinned = false, linkedKeg = 'build-100' } = {}) => JSON.stringify({
+ formulae: [{
+ name: 'llama.cpp',
+ versions: { stable: latestVersion },
+ installed: [{ version: installedVersion }],
+ outdated,
+ pinned,
+ linked_keg: linkedKeg,
+ }],
+});
+
describe('llamaServerManager', () => {
// startLlamaServer refuses to spawn for a GGUF that is not on disk, so the
// lifecycle tests need real files to point at.
@@ -157,6 +172,68 @@ describe('llamaServerManager', () => {
expect(execProbe).not.toHaveBeenCalled();
});
+ it('reports the binary version and Homebrew update metadata', async () => {
+ const binaryPath = '/opt/homebrew/bin/llama-server';
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(binaryPath);
+ const buffered = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command) => ({
+ success: true,
+ code: 0,
+ stdout: command === 'brew' ? brewInfoJson() : 'version: 0.1.1-dev (build 100, commit abc123)',
+ stderr: '',
+ timedOut: false,
+ }));
+
+ const status = await getLlamaServerUpdateStatus();
+
+ expect(status).toMatchObject({
+ version: '0.1.1-dev',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: true,
+ });
+ expect(buffered).toHaveBeenCalledWith(binaryPath, ['--version'], { timeoutMs: 5000, shell: false });
+ expect(buffered).toHaveBeenCalledWith(
+ 'brew',
+ ['info', '--json=v2', '--formula', 'llama.cpp'],
+ { timeoutMs: 15_000, shell: false },
+ );
+ });
+
+ it('does not offer an automatic update for a pinned Homebrew formula', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command) => ({
+ success: true,
+ code: 0,
+ stdout: command === 'brew' ? brewInfoJson({ pinned: true }) : 'version: 0.1.1-dev',
+ stderr: '',
+ timedOut: false,
+ }));
+
+ await expect(getLlamaServerUpdateStatus()).resolves.toMatchObject({
+ updateAvailable: true,
+ canUpgrade: false,
+ latestVersion: '0.3.0',
+ });
+ });
+
+ it('keeps a custom llama-server build updateable by manual means only', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command) => ({
+ success: command !== 'brew',
+ code: command === 'brew' ? 1 : 0,
+ stdout: command === 'brew' ? '' : 'version: custom-build',
+ stderr: command === 'brew' ? 'Error: No available formula' : '',
+ timedOut: false,
+ }));
+
+ await expect(getLlamaServerUpdateStatus()).resolves.toMatchObject({
+ version: 'custom-build',
+ latestVersion: null,
+ updateAvailable: false,
+ canUpgrade: false,
+ });
+ });
+
it('rejects start when binary is missing', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);
@@ -514,6 +591,75 @@ describe('llamaServerManager', () => {
await expect(installLlamaServer()).rejects.toThrow(/brew link --overwrite llama\.cpp/i);
});
+ describe('upgradeLlamaServer', () => {
+ const stubBrewInfo = (options) => vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async () => ({
+ success: true,
+ code: 0,
+ stdout: brewInfoJson(options),
+ stderr: '',
+ timedOut: false,
+ }));
+
+ it('updates an idle installation through Homebrew without starting it', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
+ stubBrewInfo();
+ const progress = vi.fn();
+ const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockImplementation(async (_cmd, _args, onLine) => {
+ onLine('Updated llama.cpp');
+ return { success: true };
+ });
+
+ const result = await upgradeLlamaServer({ onProgress: progress });
+
+ expect(result).toMatchObject({ success: true });
+ expect(stream).toHaveBeenCalledWith(
+ 'brew',
+ ['upgrade', 'llama.cpp'],
+ expect.any(Function),
+ { timeoutMs: 30 * 60 * 1000 },
+ );
+ expect(progress).toHaveBeenCalledWith({ event: 'progress', message: 'Updating llama.cpp via Homebrew…' });
+ expect(progress).toHaveBeenCalledWith({ event: 'progress', message: 'Updated llama.cpp' });
+ expect(execPm2Calls.some((args) => args[0] === 'start' || args[0] === 'delete')).toBe(false);
+ });
+
+ it('restarts a managed server with its recovered launch configuration', async () => {
+ const binaryPath = '/opt/homebrew/bin/llama-server';
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(binaryPath);
+ stubBrewInfo();
+ pm2State = {
+ name: LLAMA_APP,
+ status: 'online',
+ pid: 321,
+ args: ['-m', modelPath, '--port', String(PORTS.LLAMA_SERVER), '--alias', 'example-model'],
+ };
+ openAiModelsProbe.probeOpenAiModels.mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));
+ vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockResolvedValue({ success: true });
+
+ const result = await upgradeLlamaServer();
+
+ expect(result).toMatchObject({ success: true });
+ expect(execPm2Calls.some((args) => args[0] === 'delete')).toBe(true);
+ const startCall = execPm2Calls.find((args) => args[0] === 'start');
+ expect(startCall).toContain(modelPath);
+ expect(startCall).toContain('--alias');
+ expect(startCall).toContain('example-model');
+ });
+
+ it('refuses to update when PM2 ownership cannot be determined', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
+ stubBrewInfo();
+ pm2Reads.failures = Infinity;
+ const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand');
+
+ await expect(upgradeLlamaServer()).resolves.toMatchObject({
+ success: false,
+ error: expect.stringMatching(/could not read PM2/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