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: launch and manage llama-server as an optional portos-llama-server pm2 process

Adam Eivye43cd89a22e1
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index a02bf8f596..8f7c7d8a16 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -2,27 +2,28 @@
* llama-server process manager
*
* Provides lifecycle management (status probe, start, stop, recent logs)
- * for a local `llama-server` instance running speculative decoding (e.g. DFlash 2).
+ * for a local `llama-server` instance running speculative decoding (e.g. DFlash 2)
+ * managed as an optional PM2 process (`portos-llama-server`).
*/
import { stat } from 'fs/promises';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
-import { killProcessTree } from '../lib/bufferedSpawn.js';
import { expandHome, sleep } from '../lib/fileUtils.js';
import { resolveSpecModelPath } from './specDecodeModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { isPortInUse } from '../lib/platform.js';
import { PORTS } from '../lib/ports.js';
import { ServerError } from '../lib/errorHandler.js';
+import { execPm2, getAppStatus } from './pm2.js';
+
+export const LLAMA_APP = 'portos-llama-server';
-const IS_WIN = process.platform === 'win32';
const MAX_LOG_LINES = 100;
const PROBE_TIMEOUT_MS = 1500;
const STARTUP_WAIT_TIMEOUT_MS = 4000;
-let managedChild = null;
let currentConfig = null;
let recentLogs = [];
let lastExitError = null;
@@ -39,10 +40,7 @@ function appendLog(line) {
/**
* Probes whether an OpenAI-compatible endpoint responds at the given host/port.
- * Shares one implementation with the readiness checklist — the timeout bug this
- * used to carry (a `timeout` key inside the fetch init object, which is not a
- * fetch option, leaving a 500ms poll loop on the 15s default) came from having
- * two copies of the same probe.
+ * Shares one implementation with the readiness checklist.
*/
const probeEndpoint = async (endpoint) =>
(await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS })).reachable;
@@ -52,13 +50,7 @@ const probeEndpoint = async (endpoint) =>
*
* Deliberately a filesystem probe only — `findCommandOnPath` already requires a
* regular file carrying the execute bit, which is all "is it installed?" means.
- * Do NOT re-add a `commandExists`-style `llama-server --version` probe on top:
- * llama.cpp registers its ggml backends (Metal included) at process start, so
- * the first launch after `brew link` — a cold binary, a loaded machine — blows
- * past `commandExists`'s 5s bound. That made the probe report "not installed"
- * for an installed, working binary, and because the timeout killed the process
- * before it finished warming, every retry from the UI failed the same way:
- * "brew completed but llama-server was not found on PATH".
+ * Do NOT re-add a `commandExists`-style `llama-server --version` probe on top.
*
* @returns {string|null} absolute path, or null when it is not on PATH
*/
@@ -68,18 +60,6 @@ function resolveLlamaServerBinary() {
/**
* Fails the start request when a GGUF the launch line names is not on disk.
- *
- * The weights are a SEPARATE download from the binary — several gigabytes the
- * user fetches from Hugging Face themselves — and that is the single most
- * common reason a freshly-installed llama.cpp still cannot serve anything.
- * Without this check llama-server spawns, exits within a second, and the UI
- * reports "started (PID …)" from a process that is already gone; the real cause
- * is one line deep in the server log.
- *
- * Path resolution goes through `resolveSpecModelPath` — the same helper the
- * downloader writes through — so the check and the download can never disagree
- * about which file a relative or `~`-prefixed path means. (`spawn` does no shell
- * expansion, hence the matching `expandHome` on the argv below.)
*/
async function assertModelFileExists(label, modelPath) {
const stats = await stat(resolveSpecModelPath(modelPath)).catch(() => null);
@@ -97,29 +77,45 @@ export async function getLlamaServerStatus() {
const binaryPath = resolveLlamaServerBinary();
const installed = Boolean(binaryPath);
+ const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');
+
const host = currentConfig?.host || '127.0.0.1';
const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;
const endpoint = `http://${host}:${port}/v1`;
- const isManagedActive = Boolean(managedChild && !managedChild.killed && managedChild.exitCode === null);
const reachable = await probeEndpoint(endpoint);
+ let logs = [...recentLogs];
+ if (logs.length === 0 && (isManagedActive || pm2Status?.status)) {
+ try {
+ const pm2LogsResult = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', String(MAX_LOG_LINES)]);
+ const combined = (pm2LogsResult.stdout || '') + '\n' + (pm2LogsResult.stderr || '');
+ const parsedLines = combined.split('\n').map((l) => l.trimEnd()).filter(Boolean);
+ if (parsedLines.length > 0) {
+ logs = parsedLines.slice(-MAX_LOG_LINES);
+ }
+ } catch {
+ // Ignore PM2 log retrieval errors
+ }
+ }
+
return {
installed,
running: isManagedActive || reachable,
managed: isManagedActive,
- pid: isManagedActive ? managedChild.pid : null,
+ pid: isManagedActive ? (pm2Status?.pid || null) : null,
host,
port,
endpoint,
config: isManagedActive ? currentConfig : null,
- recentLogs: [...recentLogs],
+ recentLogs: logs,
lastExitError,
};
}
/**
- * Starts llama-server with the specified model and options.
+ * Starts llama-server with the specified model and options under PM2.
*/
export async function startLlamaServer(options = {}) {
const binaryPath = resolveLlamaServerBinary();
@@ -130,8 +126,9 @@ export async function startLlamaServer(options = {}) {
);
}
- if (managedChild && !managedChild.killed && managedChild.exitCode === null) {
- throw new ServerError(`llama-server is already running with PID ${managedChild.pid}`, { status: 409 });
+ const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ if (pm2Status && pm2Status.status === 'online') {
+ throw new ServerError(`llama-server is already running with PID ${pm2Status.pid}`, { status: 409 });
}
const {
@@ -161,9 +158,7 @@ export async function startLlamaServer(options = {}) {
);
}
- // Validate the weights before building the launch line, and hand `spawn` the
- // EXPANDED paths: it performs no shell expansion, so a `~/models/…` argv entry
- // would reach llama.cpp as a literal directory named `~`.
+ // Validate the weights before building the launch line
await assertModelFileExists('The base model', model.trim());
const draftPath = typeof draftModel === 'string' && draftModel.trim()
? draftModel.trim()
@@ -172,13 +167,6 @@ export async function startLlamaServer(options = {}) {
const args = ['-m', expandHome(model.trim())];
if (draftPath) {
- // `--model-draft` is the drafter flag llama.cpp parses. Newer builds also
- // spell it `--spec-draft-model`, but the legacy name (alias `-md`) is the
- // one every build accepts. `--draft-model` has never existed in any of
- // them, and an unknown flag is fatal — llama.cpp prints
- // `error: invalid argument: …` and exits 1 before loading a single weight,
- // so the typo killed the launch outright rather than quietly dropping
- // speculative decoding.
args.push('--model-draft', expandHome(draftPath));
if (specType) args.push('--spec-type', specType.trim());
}
@@ -192,16 +180,6 @@ export async function startLlamaServer(options = {}) {
recentLogs = [];
appendLog(`Starting: llama-server ${args.join(' ')}`);
- const env = safeChildProcessEnv();
- const spawnOpts = safeChildProcessOptions({
- env,
- shell: false,
- stdio: ['ignore', 'pipe', 'pipe'],
- detached: !IS_WIN,
- });
-
- const child = spawn(binaryPath, args, spawnOpts);
- managedChild = child;
currentConfig = {
model,
draftModel: draftModel || null,
@@ -213,58 +191,60 @@ export async function startLlamaServer(options = {}) {
alias,
};
- child.stdout?.on('data', (chunk) => {
- const lines = chunk.toString().split('\n');
- for (const line of lines) appendLog(line);
- });
+ // Delete stale PM2 entry so our own previous instance doesn't count as a collision
+ await execPm2(['delete', LLAMA_APP]).catch(() => {});
- child.stderr?.on('data', (chunk) => {
- const lines = chunk.toString().split('\n');
- for (const line of lines) appendLog(line);
- });
-
- child.on('error', (err) => {
- appendLog(`Process error: ${err.message}`);
- lastExitError = err.message;
- if (managedChild === child) managedChild = null;
- });
-
- child.on('exit', (code, signal) => {
- appendLog(`Process exited with code ${code}${signal ? ` (signal ${signal})` : ''}`);
- if (code !== 0 && code !== null) {
- lastExitError = `Exited with code ${code}`;
- }
- if (managedChild === child) managedChild = null;
- });
+ await execPm2([
+ 'start', binaryPath,
+ '--name', LLAMA_APP,
+ '--interpreter', 'none',
+ '--no-autorestart',
+ '--',
+ ...args,
+ ]);
// Wait a short beat and verify probe
const startTime = Date.now();
let online = false;
+ let currentProc = null;
while (Date.now() - startTime < STARTUP_WAIT_TIMEOUT_MS) {
- if (child.exitCode !== null) break;
+ currentProc = await getAppStatus(LLAMA_APP).catch(() => null);
+ if (currentProc && (currentProc.status === 'errored' || currentProc.status === 'stopped' || currentProc.status === 'not_found')) {
+ break;
+ }
await sleep(500);
online = await probeEndpoint(endpoint);
if (online) break;
}
- // A child that has already exited is not a started server. Reporting
- // `success: true` here put "llama-server started (PID …)" on screen for a
- // process that died on a bad flag, an unreadable GGUF, or an unsupported
- // `--spec-type` — the user then went looking for a connection problem in
- // OpenCode instead of reading the four log lines that explain it.
- if (child.exitCode !== null || child.signalCode) {
- const tail = recentLogs.slice(-4).join(' | ');
+ if (currentProc && (currentProc.status === 'errored' || currentProc.status === 'stopped' || currentProc.status === 'not_found')) {
+ let tail = '';
+ try {
+ const pm2Logs = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', '15']);
+ const combined = (pm2Logs.stderr || pm2Logs.stdout || '').trim();
+ const lines = combined.split('\n').map((l) => l.trimEnd()).filter(Boolean);
+ for (const line of lines) appendLog(line);
+ tail = lines.slice(-4).join(' | ');
+ } catch {
+ tail = recentLogs.slice(-4).join(' | ');
+ }
+
+ lastExitError = `PM2 status: ${currentProc.status}`;
+
+ await execPm2(['delete', LLAMA_APP]).catch(() => {});
throw new ServerError(
`llama-server exited immediately${lastExitError ? ` (${lastExitError})` : ''}.${tail ? ` Last output: ${tail}` : ''}`,
{ status: 500, code: 'LLAMA_SERVER_EXITED' }
);
}
+ const finalProc = await getAppStatus(LLAMA_APP).catch(() => null);
+
return {
success: true,
running: true,
managed: true,
- pid: child.pid,
+ pid: finalProc?.pid || null,
endpoint,
online,
config: currentConfig,
@@ -275,7 +255,10 @@ export async function startLlamaServer(options = {}) {
* Stops the managed llama-server process.
*/
export async function stopLlamaServer() {
- if (!managedChild || managedChild.killed || managedChild.exitCode !== null) {
+ const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ const isManaged = Boolean(pm2Status && pm2Status.status === 'online');
+
+ if (!isManaged) {
const host = currentConfig?.host || '127.0.0.1';
const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;
const endpoint = `http://${host}:${port}/v1`;
@@ -289,18 +272,10 @@ export async function stopLlamaServer() {
return { success: true, message: 'llama-server is not running' };
}
- const childToKill = managedChild;
- managedChild = null;
+ appendLog(`Stopping ${LLAMA_APP}`);
+ await execPm2(['delete', LLAMA_APP]).catch(() => {});
currentConfig = null;
- appendLog(`Stopping llama-server (PID ${childToKill.pid})`);
- killProcessTree(childToKill, 'SIGTERM', { processGroup: !IS_WIN });
-
- await sleep(600);
- if (!childToKill.killed && childToKill.exitCode === null) {
- killProcessTree(childToKill, 'SIGKILL', { processGroup: !IS_WIN });
- }
-
return { success: true, message: 'llama-server stopped' };
}
@@ -420,11 +395,8 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {
* Clears in-memory test state (used by test suites).
*/
export function _resetLlamaServerStateForTests() {
- if (managedChild && !managedChild.killed && managedChild.exitCode === null) {
- try { managedChild.kill('SIGKILL'); } catch {}
- }
- managedChild = null;
currentConfig = null;
recentLogs = [];
lastExitError = null;
}
+
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index a38f61521f..218a960133 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -5,11 +5,13 @@ import {
stopLlamaServer,
installLlamaServer,
_resetLlamaServerStateForTests,
+ LLAMA_APP,
} from './llamaServerManager.js';
import * as processEnv from '../lib/processEnv.js';
import * as commandExistsModule from '../lib/commandExists.js';
import * as childProcess from '../lib/childProcess.js';
import * as platform from '../lib/platform.js';
+import * as pm2Module from './pm2.js';
import { PORTS } from '../lib/ports.js';
import { EventEmitter } from 'events';
import { mkdtemp, rm, writeFile } from 'fs/promises';
@@ -37,6 +39,8 @@ describe('llamaServerManager', () => {
let modelDir;
let modelPath;
let draftPath;
+ let pm2State = null;
+ let execPm2Calls = [];
beforeAll(async () => {
modelDir = await mkdtemp(join(tmpdir(), 'portos-llama-'));
@@ -53,9 +57,36 @@ describe('llamaServerManager', () => {
beforeEach(() => {
_resetLlamaServerStateForTests();
vi.restoreAllMocks();
+ pm2State = null;
+ execPm2Calls = [];
+
// The host may have an unrelated listener on the requested port (8080 is
// especially common), so lifecycle tests pin the port-discovery result.
vi.spyOn(platform, 'isPortInUse').mockResolvedValue(false);
+
+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
+ execPm2Calls.push(args);
+ const action = args[0];
+ if (action === 'start') {
+ const nameIdx = args.indexOf('--name');
+ const name = nameIdx !== -1 ? args[nameIdx + 1] : args[1];
+ pm2State = { name, status: 'online', pid: 12345 };
+ return { stdout: '', stderr: '' };
+ }
+ if (action === 'delete') {
+ pm2State = null;
+ return { stdout: '', stderr: '' };
+ }
+ if (action === 'logs') {
+ return { stdout: '', stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ vi.spyOn(pm2Module, 'getAppStatus').mockImplementation(async (name) => {
+ if (pm2State && pm2State.name === name) return pm2State;
+ return { name, status: 'not_found', pm2_env: null };
+ });
});
afterEach(() => {
@@ -93,22 +124,9 @@ describe('llamaServerManager', () => {
);
});
- it('spawns llama-server with draftModel and specType arguments', async () => {
+ it('spawns llama-server with draftModel and specType arguments under PM2', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
- const fakeChild = new EventEmitter();
- fakeChild.pid = 12345;
- fakeChild.killed = false;
- fakeChild.exitCode = null;
- fakeChild.stdout = new EventEmitter();
- fakeChild.stderr = new EventEmitter();
-
- let spawnArgs = null;
- vi.spyOn(childProcess, 'spawn').mockImplementation((cmd, args) => {
- spawnArgs = { cmd, args };
- return fakeChild;
- });
-
const result = await startLlamaServer({
model: modelPath,
draftModel: draftPath,
@@ -120,12 +138,15 @@ describe('llamaServerManager', () => {
expect(result.success).toBe(true);
expect(result.pid).toBe(12345);
- expect(spawnArgs.cmd).toBe('/usr/local/bin/llama-server');
- // The drafter flag was once spelled `--draft-model`, which llama.cpp has
- // never accepted — it exits 1 on an unknown flag before touching the
- // weights, so every speculative launch died on arrival. Pinning the exact
- // argv is what keeps a plausible-looking misspelling out.
- expect(spawnArgs.args).toEqual([
+ const startCall = execPm2Calls.find((c) => c[0] === 'start');
+ expect(startCall[1]).toBe('/usr/local/bin/llama-server');
+ expect(startCall.slice(2, 8)).toEqual([
+ '--name', LLAMA_APP,
+ '--interpreter', 'none',
+ '--no-autorestart',
+ '--',
+ ]);
+ expect(startCall.slice(8)).toEqual([
'-m', modelPath,
'--model-draft', draftPath,
'--spec-type', 'draft-dflash',
@@ -145,37 +166,28 @@ describe('llamaServerManager', () => {
it('uses PortOS\'s extension port when no port is supplied', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
- const fakeChild = new EventEmitter();
- fakeChild.pid = 23456;
- fakeChild.killed = false;
- fakeChild.exitCode = null;
- fakeChild.stdout = new EventEmitter();
- fakeChild.stderr = new EventEmitter();
- const spawnSpy = vi.spyOn(childProcess, 'spawn').mockReturnValue(fakeChild);
-
const result = await startLlamaServer({ model: modelPath });
expect(result.endpoint).toBe(`http://127.0.0.1:${PORTS.LLAMA_SERVER}/v1`);
- expect(spawnSpy.mock.calls[0][1]).toContain('--port');
- expect(spawnSpy.mock.calls[0][1]).toContain(String(PORTS.LLAMA_SERVER));
+ const startCall = execPm2Calls.find((c) => c[0] === 'start');
+ expect(startCall).toContain('--port');
+ expect(startCall).toContain(String(PORTS.LLAMA_SERVER));
});
it('rejects before spawning when the requested port is occupied by another process', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
vi.spyOn(platform, 'isPortInUse').mockResolvedValue(true);
- const spawnSpy = vi.spyOn(childProcess, 'spawn');
await expect(startLlamaServer({ model: modelPath, port: 49876 })).rejects.toMatchObject({
code: 'LLAMA_SERVER_PORT_IN_USE',
status: 409,
message: expect.stringContaining('Choose a different port'),
});
- expect(spawnSpy).not.toHaveBeenCalled();
+ expect(execPm2Calls.filter((c) => c[0] === 'start')).toHaveLength(0);
});
it('refuses to start when the GGUF the launch line names is not on disk', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
- const spawnSpy = vi.spyOn(childProcess, 'spawn');
await expect(startLlamaServer({ model: join(modelDir, 'absent.gguf') })).rejects.toThrow(
/base model was not found/i
@@ -185,28 +197,16 @@ describe('llamaServerManager', () => {
);
// The weights are a separate multi-gigabyte download; spawning anyway just
// buries that in a server log.
- expect(spawnSpy).not.toHaveBeenCalled();
+ expect(execPm2Calls.filter((c) => c[0] === 'start')).toHaveLength(0);
});
it('reports a failure — not a PID — when llama-server exits during startup', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
-
- const fakeChild = new EventEmitter();
- fakeChild.pid = 999;
- fakeChild.killed = false;
- fakeChild.exitCode = null;
- fakeChild.stdout = new EventEmitter();
- fakeChild.stderr = new EventEmitter();
-
- vi.spyOn(childProcess, 'spawn').mockImplementation(() => {
- // A real llama.cpp rejects an unsupported --spec-type within a beat.
- setTimeout(() => {
- fakeChild.stderr.emit('data', Buffer.from('error: unknown spec type\n'));
- fakeChild.exitCode = 1;
- fakeChild.emit('exit', 1, null);
- }, 0);
- return fakeChild;
+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
+ if (args[0] === 'logs') return { stdout: '', stderr: 'error: unknown spec type' };
+ return { stdout: '', stderr: '' };
});
+ vi.spyOn(pm2Module, 'getAppStatus').mockResolvedValue({ name: LLAMA_APP, status: 'errored' });
await expect(startLlamaServer({ model: modelPath, specType: 'draft-nope' })).rejects.toThrow(
/llama-server exited immediately/i
@@ -216,16 +216,6 @@ describe('llamaServerManager', () => {
it('stops managed process cleanly', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
- const fakeChild = new EventEmitter();
- fakeChild.pid = 54321;
- fakeChild.killed = false;
- fakeChild.exitCode = null;
- fakeChild.stdout = new EventEmitter();
- fakeChild.stderr = new EventEmitter();
- fakeChild.kill = vi.fn();
-
- vi.spyOn(childProcess, 'spawn').mockReturnValue(fakeChild);
-
await startLlamaServer({ model: modelPath });
const stopResult = await stopLlamaServer();
expect(stopResult.success).toBe(true);