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(review): address codex review findings on pm2 cache bypass, strict status, and config recovery

Adam Eivyedda2b18cae1
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 8f7c7d8a16..ae90eb13ee 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -16,7 +16,7 @@ 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';
+import { execPm2, getAppStatusStrict, clearJlistCache } from './pm2.js';
export const LLAMA_APP = 'portos-llama-server';
@@ -70,6 +70,41 @@ async function assertModelFileExists(label, modelPath) {
);
}
+/**
+ * Reconstructs the launch config from PM2 process args if PortOS restarted
+ * while the PM2 process remained online.
+ */
+function parseConfigFromArgs(args) {
+ if (!args) return null;
+ const list = Array.isArray(args) ? args : String(args).split(' ');
+ const getArg = (flag) => {
+ const idx = list.indexOf(flag);
+ return idx !== -1 && idx + 1 < list.length ? list[idx + 1] : null;
+ };
+
+ const model = getArg('-m') || getArg('--model');
+ if (!model) return null;
+
+ const draftModel = getArg('--model-draft') || getArg('--spec-draft-model') || getArg('-md');
+ const specType = getArg('--spec-type') || 'draft-dflash';
+ const port = getArg('--port') ? Number(getArg('--port')) : PORTS.LLAMA_SERVER;
+ const host = getArg('--host') || '127.0.0.1';
+ const ctxSize = getArg('--ctx-size') ? Number(getArg('--ctx-size')) : 32768;
+ const nGpuLayers = getArg('-ngl') !== null ? Number(getArg('-ngl')) : 99;
+ const alias = getArg('--alias') || 'dflash';
+
+ return {
+ model,
+ draftModel,
+ specType,
+ port,
+ host,
+ ctxSize,
+ nGpuLayers,
+ alias,
+ };
+}
+
/**
* Returns current status of llama-server (binary availability, running state, config, logs).
*/
@@ -77,9 +112,14 @@ export async function getLlamaServerStatus() {
const binaryPath = resolveLlamaServerBinary();
const installed = Boolean(binaryPath);
- const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ const pm2Status = await getAppStatusStrict(LLAMA_APP);
+ const isReadFailed = pm2Status === null;
const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');
+ if (!currentConfig && isManagedActive && pm2Status?.args) {
+ currentConfig = parseConfigFromArgs(pm2Status.args);
+ }
+
const host = currentConfig?.host || '127.0.0.1';
const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;
const endpoint = `http://${host}:${port}/v1`;
@@ -87,13 +127,22 @@ export async function getLlamaServerStatus() {
const reachable = await probeEndpoint(endpoint);
let logs = [...recentLogs];
- if (logs.length === 0 && (isManagedActive || pm2Status?.status)) {
+ if (isManagedActive || (pm2Status && pm2Status.status !== 'not_found')) {
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);
+ const seen = new Set(logs);
+ for (const line of parsedLines) {
+ if (!seen.has(line)) {
+ logs.push(line);
+ seen.add(line);
+ }
+ }
+ if (logs.length > MAX_LOG_LINES) {
+ logs = logs.slice(-MAX_LOG_LINES);
+ }
}
} catch {
// Ignore PM2 log retrieval errors
@@ -103,14 +152,14 @@ export async function getLlamaServerStatus() {
return {
installed,
running: isManagedActive || reachable,
- managed: isManagedActive,
+ managed: isReadFailed ? null : isManagedActive,
pid: isManagedActive ? (pm2Status?.pid || null) : null,
host,
port,
endpoint,
config: isManagedActive ? currentConfig : null,
recentLogs: logs,
- lastExitError,
+ lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,
};
}
@@ -126,7 +175,7 @@ export async function startLlamaServer(options = {}) {
);
}
- const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ const pm2Status = await getAppStatusStrict(LLAMA_APP);
if (pm2Status && pm2Status.status === 'online') {
throw new ServerError(`llama-server is already running with PID ${pm2Status.pid}`, { status: 409 });
}
@@ -193,6 +242,7 @@ export async function startLlamaServer(options = {}) {
// Delete stale PM2 entry so our own previous instance doesn't count as a collision
await execPm2(['delete', LLAMA_APP]).catch(() => {});
+ clearJlistCache();
await execPm2([
'start', binaryPath,
@@ -202,17 +252,19 @@ export async function startLlamaServer(options = {}) {
'--',
...args,
]);
+ clearJlistCache();
// 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) {
- currentProc = await getAppStatus(LLAMA_APP).catch(() => null);
+ await sleep(500);
+ clearJlistCache();
+ currentProc = await getAppStatusStrict(LLAMA_APP);
if (currentProc && (currentProc.status === 'errored' || currentProc.status === 'stopped' || currentProc.status === 'not_found')) {
break;
}
- await sleep(500);
online = await probeEndpoint(endpoint);
if (online) break;
}
@@ -232,13 +284,14 @@ export async function startLlamaServer(options = {}) {
lastExitError = `PM2 status: ${currentProc.status}`;
await execPm2(['delete', LLAMA_APP]).catch(() => {});
+ clearJlistCache();
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);
+ const finalProc = await getAppStatusStrict(LLAMA_APP);
return {
success: true,
@@ -255,7 +308,7 @@ export async function startLlamaServer(options = {}) {
* Stops the managed llama-server process.
*/
export async function stopLlamaServer() {
- const pm2Status = await getAppStatus(LLAMA_APP).catch(() => null);
+ const pm2Status = await getAppStatusStrict(LLAMA_APP);
const isManaged = Boolean(pm2Status && pm2Status.status === 'online');
if (!isManaged) {
@@ -273,7 +326,12 @@ export async function stopLlamaServer() {
}
appendLog(`Stopping ${LLAMA_APP}`);
- await execPm2(['delete', LLAMA_APP]).catch(() => {});
+ try {
+ await execPm2(['delete', LLAMA_APP]);
+ clearJlistCache();
+ } catch (err) {
+ throw new ServerError(`Failed to stop llama-server: ${err.message}`, { status: 500 });
+ }
currentConfig = null;
return { success: true, message: 'llama-server stopped' };
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index 218a960133..e2f208e555 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -70,7 +70,9 @@ describe('llamaServerManager', () => {
if (action === 'start') {
const nameIdx = args.indexOf('--name');
const name = nameIdx !== -1 ? args[nameIdx + 1] : args[1];
- pm2State = { name, status: 'online', pid: 12345 };
+ const dashIdx = args.indexOf('--');
+ const procArgs = dashIdx !== -1 ? args.slice(dashIdx + 1) : [];
+ pm2State = { name, status: 'online', pid: 12345, args: procArgs };
return { stdout: '', stderr: '' };
}
if (action === 'delete') {
@@ -87,6 +89,11 @@ describe('llamaServerManager', () => {
if (pm2State && pm2State.name === name) return pm2State;
return { name, status: 'not_found', pm2_env: null };
});
+
+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockImplementation(async (name) => {
+ if (pm2State && pm2State.name === name) return pm2State;
+ return { name, status: 'not_found', pm2_env: null };
+ });
});
afterEach(() => {
@@ -206,7 +213,7 @@ describe('llamaServerManager', () => {
if (args[0] === 'logs') return { stdout: '', stderr: 'error: unknown spec type' };
return { stdout: '', stderr: '' };
});
- vi.spyOn(pm2Module, 'getAppStatus').mockResolvedValue({ name: LLAMA_APP, status: 'errored' });
+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockResolvedValue({ name: LLAMA_APP, status: 'errored' });
await expect(startLlamaServer({ model: modelPath, specType: 'draft-nope' })).rejects.toThrow(
/llama-server exited immediately/i
@@ -224,6 +231,45 @@ describe('llamaServerManager', () => {
expect(status.managed).toBe(false);
});
+ it('recovers launch configuration from PM2 args after server restarts', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ pm2State = {
+ name: LLAMA_APP,
+ status: 'online',
+ pid: 98765,
+ args: ['-m', modelPath, '--model-draft', draftPath, '--port', '8090', '--host', '127.0.0.1'],
+ };
+
+ const status = await getLlamaServerStatus();
+ expect(status.managed).toBe(true);
+ expect(status.pid).toBe(98765);
+ expect(status.port).toBe(8090);
+ expect(status.endpoint).toBe('http://127.0.0.1:8090/v1');
+ expect(status.config?.model).toBe(modelPath);
+ expect(status.config?.draftModel).toBe(draftPath);
+ });
+
+ it('surfaces unknown/degraded state when PM2 read fails', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockResolvedValue(null);
+
+ const status = await getLlamaServerStatus();
+ expect(status.managed).toBeNull();
+ expect(status.lastExitError).toBe('Failed to read PM2 status');
+ });
+
+ it('propagates error when stopping PM2 process fails', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ pm2State = { name: LLAMA_APP, status: 'online', pid: 12345 };
+
+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
+ if (args[0] === 'delete') throw new Error('PM2 daemon down');
+ return { stdout: '', stderr: '' };
+ });
+
+ await expect(stopLlamaServer()).rejects.toThrow(/Failed to stop llama-server: PM2 daemon down/);
+ });
+
it('installs llama.cpp via Homebrew when brew is available', async () => {
vi.spyOn(commandExistsModule, 'commandExists').mockImplementation(async (cmd) => true);
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/opt/homebrew/bin/llama-server');
diff --git a/server/services/pm2.js b/server/services/pm2.js
index bb3d61099e..b2971a0a16 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -15,6 +15,18 @@ const jlistCache = new Map();
const jlistInflight = new Map();
const cacheKey = (pm2Home) => pm2Home || '_default';
+/**
+ * Invalidate the jlist TTL cache (e.g. after mutations like start/stop/delete).
+ * @param {string|null} [pm2Home=null]
+ */
+export function clearJlistCache(pm2Home = null) {
+ if (pm2Home !== undefined && pm2Home !== null) {
+ jlistCache.delete(cacheKey(pm2Home));
+ } else {
+ jlistCache.clear();
+ }
+}
+
// Resolve PM2 CLI binary path from our local dependency using require.resolve
// to handle hoisted node_modules correctly.
const require = createRequire(import.meta.url);
@@ -295,7 +307,8 @@ function shapeProcStatus(proc) {
uptime: proc.pm2_env?.pm_uptime ? Date.now() - proc.pm2_env.pm_uptime : null,
restarts: proc.pm2_env?.restart_time || 0,
unstableRestarts: proc.pm2_env?.unstable_restarts || 0,
- createdAt: proc.pm2_env?.created_at || null
+ createdAt: proc.pm2_env?.created_at || null,
+ args: proc.pm2_env?.args || null
};
}