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

fix: address review (codex): harden llama.cpp updates

[._.]/ Adam Eivy90aa599f3a5a
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index a3ce17face..c2f4b54526 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, upgradeLlamaServer,
+ installAudioModel, patchSettingsSlice, getLlamaServerStatus, getLlamaServerUpdateStatus, startLlamaServer, stopLlamaServer, installLlamaServer, upgradeLlamaServer,
downloadSpecDecodeModel, cancelSpecDecodeModelDownload, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,
searchMtplxModels, pullMtplxModel, removeMtplxModel,
saveRuntimeStartupList
@@ -225,7 +225,19 @@ export function LocalLlmTab() {
const loadLlamaStatus = useCallback(() => {
return getLlamaServerStatus({ silent: true })
.then((res) => {
- if (res) setLlamaStatus(res);
+ if (res) {
+ setLlamaStatus(res);
+ // Version/Homebrew metadata is deliberately a separate, non-blocking
+ // request. A slow `--version` probe must not hold up lifecycle state,
+ // presets, or the rest of the Local LLMs page.
+ if (res.installed) {
+ getLlamaServerUpdateStatus({ silent: true })
+ .then((update) => {
+ if (update) setLlamaStatus((previous) => previous ? { ...previous, ...update } : previous);
+ })
+ .catch(() => null);
+ }
+ }
return res;
})
.catch(() => null);
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 678024b6ce..681493068a 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -26,6 +26,7 @@ vi.mock('../../services/api', () => ({
installAudioModel: vi.fn(),
patchSettingsSlice: vi.fn(),
getLlamaServerStatus: vi.fn().mockResolvedValue({ installed: false, running: false }),
+ getLlamaServerUpdateStatus: vi.fn().mockResolvedValue(null),
startLlamaServer: vi.fn(),
stopLlamaServer: vi.fn(),
installLlamaServer: vi.fn().mockResolvedValue({ success: true }),
@@ -270,7 +271,7 @@ describe('LocalLlmTab installed models', () => {
expect(location).toMatch(/^\/local-llm\/playground\?/);
const targets = JSON.parse(new URLSearchParams(location.split('?')[1]).get('targets'));
expect(targets).toEqual(models.slice(0, 6).map((model) => ({ backend: 'ollama', modelId: model.id })));
- });
+ }, 10_000);
it('requires inline confirmation before deleting an installed model', async () => {
await renderTab();
@@ -574,9 +575,11 @@ describe('LocalLlmTab llama-server management', () => {
// component consumes leaks it into the next test's first status read. Reset
// the mock outright here and give it a sane standing default.
beforeEach(async () => {
- const { getLlamaServerStatus } = await import('../../services/api');
+ const { getLlamaServerStatus, getLlamaServerUpdateStatus } = await import('../../services/api');
getLlamaServerStatus.mockReset();
getLlamaServerStatus.mockResolvedValue(llamaReady());
+ getLlamaServerUpdateStatus.mockReset();
+ getLlamaServerUpdateStatus.mockResolvedValue(null);
});
it('renders start form and launches server when llama-server is installed', async () => {
@@ -890,13 +893,15 @@ 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({
+ const { getLlamaServerStatus, getLlamaServerUpdateStatus, upgradeLlamaServer } = await import('../../services/api');
+ getLlamaServerStatus.mockResolvedValue(llamaReady());
+ getLlamaServerUpdateStatus.mockResolvedValueOnce({
version: '0.1.1-dev',
latestVersion: '0.3.0',
updateAvailable: true,
canUpgrade: true,
- }));
+ downloadUrl: 'https://github.com/ggml-org/llama.cpp/releases',
+ });
upgradeLlamaServer.mockResolvedValueOnce({ success: true, note: 'updated and restarted' });
await renderTab();
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 353d147d29..9aaa101cfc 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -101,6 +101,12 @@ 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.
+export const getLlamaServerUpdateStatus = (options) =>
+ request('/local-llm/llama-server/update-status', options);
+
export const startLlamaServer = (config) =>
request('/local-llm/llama-server/start', { method: 'POST', body: JSON.stringify(config) });
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index f818f80573..40a5f4fb91 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -641,16 +641,21 @@ router.post('/capability-tests/delete', asyncHandler(async (req, res) => {
// logs, and the curated target/drafter presets with each GGUF's on-disk state.
// The presets ride along on the status call the launcher already makes so the
// 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.
+// Start to discover a missing file. Disk-only: no Homebrew or Hugging Face call
+// here.
router.get('/llama-server/status', asyncHandler(async (_req, res) => {
- const [status, update, presets] = await Promise.all([
- getLlamaServerStatus(),
- getLlamaServerUpdateStatus(),
- getSpecDecodePresetStatus(),
- ])
+ const [status, presets] = await Promise.all([getLlamaServerStatus(), 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, ...update, presets, specTypes: SPEC_TYPE_SUGGESTIONS })
+ 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.
+router.get('/llama-server/update-status', asyncHandler(async (_req, res) => {
+ res.json(await getLlamaServerUpdateStatus())
}))
// POST /api/local-llm/llama-server/download-model — fetch one preset's GGUF from
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 7acc3bba07..7eab0b361e 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -680,7 +680,16 @@ describe('llama-server routes', () => {
});
});
- it('GET /api/local-llm/llama-server/status includes llama.cpp update metadata', async () => {
+ it('GET /api/local-llm/llama-server/status keeps Homebrew probes out of lifecycle status', async () => {
+ const { getLlamaServerUpdateStatus } = await import('../services/llamaServerManager.js');
+ const res = await request(makeApp()).get('/api/local-llm/llama-server/status');
+
+ expect(res.status).toBe(200);
+ expect(getLlamaServerUpdateStatus).not.toHaveBeenCalled();
+ expect(res.body).not.toHaveProperty('updateAvailable');
+ });
+
+ it('GET /api/local-llm/llama-server/update-status returns llama.cpp update metadata', async () => {
const { getLlamaServerUpdateStatus } = await import('../services/llamaServerManager.js');
getLlamaServerUpdateStatus.mockResolvedValueOnce({
version: '0.1.1-dev',
@@ -690,7 +699,7 @@ describe('llama-server routes', () => {
downloadUrl: 'https://github.com/ggml-org/llama.cpp/releases',
});
- const res = await request(makeApp()).get('/api/local-llm/llama-server/status');
+ const res = await request(makeApp()).get('/api/local-llm/llama-server/update-status');
expect(res.body).toMatchObject({
version: '0.1.1-dev',
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 3f7b7bbac6..52bcc49b53 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -6,7 +6,7 @@
* managed as an optional PM2 process (`portos-llama-server`).
*/
-import { stat } from 'fs/promises';
+import { realpath, stat } from 'fs/promises';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
@@ -132,21 +132,47 @@ async function readBrewLlamaCppInfo() {
return Promise.resolve()
.then(() => JSON.parse(result.stdout))
- .then((payload) => {
+ .then(async (payload) => {
const formula = payload?.formulae?.find((entry) => entry?.name === LLAMA_CPP_FORMULA);
const installed = formula?.installed?.[0];
if (!installed) return null;
+ const prefixResult = await readCommandOutput(
+ 'brew',
+ ['--prefix', LLAMA_CPP_FORMULA],
+ BREW_INFO_TIMEOUT_MS,
+ );
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),
+ prefix: prefixResult.error ? null : prefixResult.stdout.trim().split(/\r?\n/)[0] || null,
};
})
.catch(() => null);
}
+/**
+ * Confirm that the binary found on PATH resolves to Homebrew's linked keg.
+ *
+ * `brew info` reports whether the formula is linked, not which executable the
+ * current PATH resolves. A source build earlier on PATH can therefore coexist
+ * with a linked Homebrew formula; upgrading the formula in that state would
+ * leave the serving process on the old source build. Canonicalize both paths so
+ * the normal `/opt/homebrew/bin` and `/opt/homebrew/opt` symlinks compare as the
+ * same Cellar executable.
+ */
+async function isHomebrewLlamaServer(binaryPath, brewInfo) {
+ if (!binaryPath || !brewInfo?.prefix) return false;
+ const expectedPath = `${brewInfo.prefix}/bin/llama-server`;
+ const [activePath, homebrewPath] = await Promise.all([
+ realpath(binaryPath).catch(() => null),
+ realpath(expectedPath).catch(() => null),
+ ]);
+ return Boolean(activePath && homebrewPath && activePath === homebrewPath);
+}
+
/**
* Probes whether an OpenAI-compatible endpoint responds at the given host/port.
* Shares one implementation with the readiness checklist.
@@ -379,11 +405,12 @@ export async function getLlamaServerUpdateStatus() {
readLlamaServerVersion(binaryPath),
readBrewLlamaCppInfo(),
]);
+ 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),
+ canUpgrade: Boolean(brewInfo?.linked && !brewInfo.pinned && homebrewBinary),
downloadUrl: LLAMA_CPP_DOWNLOAD_URL,
};
}
@@ -705,7 +732,13 @@ async function restartManagedLlamaServer(config, baseline) {
console.error(`❌ llama-server: could not restore the previous configuration after update: ${err.message}`);
return null;
});
- if (started) preTuningConfig = baseline;
+ if (!started) return null;
+ if (!started.online && !(await waitForEndpoint(started.endpoint))) {
+ console.error('❌ llama-server: restored process never answered after update');
+ await stopLlamaServer().catch(() => {});
+ return null;
+ }
+ preTuningConfig = baseline;
return started;
}
@@ -752,6 +785,15 @@ export async function upgradeLlamaServer({ onProgress = () => {} } = {}) {
};
}
+ 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 launch = await readLlamaServerLaunch();
if (launch.readFailed) {
return {
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index df8e501a3e..6ac1e1f7cf 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -23,7 +23,7 @@ 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';
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -59,6 +59,8 @@ describe('llamaServerManager', () => {
let modelDir;
let modelPath;
let draftPath;
+ let homebrewBinaryPath;
+ let homebrewPrefix;
let pm2State = null;
let execPm2Calls = [];
// Failed PM2 reads, on demand. `getAppStatusStrict` answers `null` for a read
@@ -74,6 +76,16 @@ describe('llamaServerManager', () => {
draftPath = join(modelDir, 'draft.gguf');
await writeFile(modelPath, 'gguf');
await writeFile(draftPath, 'gguf');
+ const homebrewRoot = join(modelDir, 'homebrew');
+ const cellarRoot = join(homebrewRoot, 'Cellar', 'llama.cpp', 'build-100');
+ homebrewPrefix = join(homebrewRoot, 'opt', 'llama.cpp');
+ homebrewBinaryPath = join(homebrewRoot, 'bin', 'llama-server');
+ await mkdir(join(cellarRoot, 'bin'), { recursive: true });
+ await mkdir(join(homebrewRoot, 'bin'), { recursive: true });
+ await mkdir(join(homebrewRoot, 'opt'), { recursive: true });
+ await writeFile(join(cellarRoot, 'bin', 'llama-server'), 'binary');
+ await symlink(cellarRoot, homebrewPrefix);
+ await symlink(join(homebrewPrefix, 'bin', 'llama-server'), homebrewBinaryPath);
});
afterAll(async () => {
@@ -173,12 +185,14 @@ describe('llamaServerManager', () => {
});
it('reports the binary version and Homebrew update metadata', async () => {
- const binaryPath = '/opt/homebrew/bin/llama-server';
+ const binaryPath = homebrewBinaryPath;
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(binaryPath);
- const buffered = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command) => ({
+ const buffered = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command, args) => ({
success: true,
code: 0,
- stdout: command === 'brew' ? brewInfoJson() : 'version: 0.1.1-dev (build 100, commit abc123)',
+ stdout: command === 'brew' && args[0] === '--prefix'
+ ? `${homebrewPrefix}\n`
+ : command === 'brew' ? brewInfoJson() : 'version: 0.1.1-dev (build 100, commit abc123)',
stderr: '',
timedOut: false,
}));
@@ -200,11 +214,13 @@ describe('llamaServerManager', () => {
});
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) => ({
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(homebrewBinaryPath);
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command, args) => ({
success: true,
code: 0,
- stdout: command === 'brew' ? brewInfoJson({ pinned: true }) : 'version: 0.1.1-dev',
+ stdout: command === 'brew' && args[0] === '--prefix'
+ ? `${homebrewPrefix}\n`
+ : command === 'brew' ? brewInfoJson({ pinned: true }) : 'version: 0.1.1-dev',
stderr: '',
timedOut: false,
}));
@@ -234,6 +250,26 @@ describe('llamaServerManager', () => {
});
});
+ it('keeps the Homebrew update manual when a source build is first on PATH', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (command, args) => ({
+ success: true,
+ code: 0,
+ stdout: command === 'brew' && args[0] === '--prefix'
+ ? `${homebrewPrefix}\n`
+ : command === 'brew' ? brewInfoJson() : 'version: custom-build',
+ stderr: '',
+ timedOut: false,
+ }));
+
+ await expect(getLlamaServerUpdateStatus()).resolves.toMatchObject({
+ version: 'custom-build',
+ latestVersion: '0.3.0',
+ updateAvailable: true,
+ canUpgrade: false,
+ });
+ });
+
it('rejects start when binary is missing', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);
@@ -592,16 +628,16 @@ describe('llamaServerManager', () => {
});
describe('upgradeLlamaServer', () => {
- const stubBrewInfo = (options) => vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async () => ({
+ const stubBrewInfo = (options) => vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockImplementation(async (_command, args) => ({
success: true,
code: 0,
- stdout: brewInfoJson(options),
+ stdout: args[0] === '--prefix' ? `${homebrewPrefix}\n` : 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');
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(homebrewBinaryPath);
stubBrewInfo();
const progress = vi.fn();
const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockImplementation(async (_cmd, _args, onLine) => {
@@ -624,7 +660,7 @@ describe('llamaServerManager', () => {
});
it('restarts a managed server with its recovered launch configuration', async () => {
- const binaryPath = '/opt/homebrew/bin/llama-server';
+ const binaryPath = homebrewBinaryPath;
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(binaryPath);
stubBrewInfo();
pm2State = {
@@ -647,7 +683,7 @@ describe('llamaServerManager', () => {
});
it('refuses to update when PM2 ownership cannot be determined', async () => {
- vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(homebrewBinaryPath);
stubBrewInfo();
pm2Reads.failures = Infinity;
const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand');
@@ -658,6 +694,43 @@ describe('llamaServerManager', () => {
});
expect(stream).not.toHaveBeenCalled();
});
+
+ it('refuses an automatic update when a source build owns the active binary', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ stubBrewInfo();
+ const stream = vi.spyOn(streamingSpawnModule, 'runStreamingCommand');
+
+ await expect(upgradeLlamaServer()).resolves.toMatchObject({
+ success: false,
+ manualUpdateRequired: true,
+ error: expect.stringMatching(/active llama-server is not the linked Homebrew/i),
+ });
+ expect(stream).not.toHaveBeenCalled();
+ });
+
+ it('does not report success when a managed restart never becomes ready', async () => {
+ const binaryPath = homebrewBinaryPath;
+ 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.mockResolvedValue({ reachable: false });
+ vi.spyOn(streamingSpawnModule, 'runStreamingCommand').mockResolvedValue({ success: true });
+ _resetLlamaServerStateForTests({ relaunchReadyTimeout: 0, pm2ReadRetryDelay: 0 });
+
+ const result = await upgradeLlamaServer();
+
+ expect(result).toMatchObject({
+ success: false,
+ updated: true,
+ error: expect.stringMatching(/could not be restarted/i),
+ });
+ expect(execPm2Calls.filter((args) => args[0] === 'delete').length).toBeGreaterThanOrEqual(2);
+ });
});
// ---- tuning relaunch ----------------------------------------------------