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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop a failed PM2 read from looking like an externally-started llama-server (#4780)
[._.]/ Adam Eivy396c06584ed8
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 3e77b4a915..bb73ce9fbb 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1263,7 +1263,12 @@ export function LocalLlmTab() {: <span className="text-gray-500">none — speculative decoding off</span>}</p></div>- {llamaStatus.managed ? (+ {/* `managed` is a THREE-state field: `true` ours, `false`+ somebody else's, `null` PM2 could not be read. A plain+ truthiness test told a user whose own daemon PortOS had merely+ failed to read that they had started it in a terminal — and+ hid the Stop button for a server PortOS does own. */}+ {llamaStatus.managed === true ? (<buttononClick={handleStopLlama}disabled={llamaLoading}@@ -1272,10 +1277,14 @@ export function LocalLlmTab() {{llamaLoading ? <BrailleSpinner /> : <PowerOff size={13} />}Stop Server</button>- ) : (+ ) : llamaStatus.managed === false ? (<span className="text-xs text-gray-500 italic">Running as external process</span>+ ) : (+ <span className="text-xs text-gray-500 italic">+ PM2 status could not be read — this may not be an external server+ </span>)}</div></div>diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 136461adb2..e0293991c2 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -834,6 +834,28 @@ describe('LocalLlmTab llama-server management', () => {});});+ // `managed` has three states: `true` ours, `false` somebody else's, `null`+ // PM2 could not be read. A truthiness test told a user whose own daemon+ // PortOS had merely failed to read that they had started it in a terminal.+ it('does not call a server external when PM2 could not be read', async () => {+ const { getLlamaServerStatus } = await import('../../services/api');+ getLlamaServerStatus.mockResolvedValue({+ installed: true,+ running: true,+ managed: null,+ presets: specPresets(),+ pid: null,+ endpoint: 'http://127.0.0.1:5568/v1',+ config: { model: 'models/base.gguf', specType: 'draft-dflash', alias: 'dflash' },+ });++ await renderTab();++ expect(await screen.findByText(/PM2 status could not be read/)).toBeInTheDocument();+ expect(screen.queryByText(/Running as external process/)).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Stop Server/ })).not.toBeInTheDocument();+ });+// `localLlm:progress` is shared with the measurement paths, and an overnight// sweep emits a `complete` frame PER MODEL. Answering those here would reload// the status and re-query the Hugging Face catalog once per measured model,diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex c89fed7022..be77eda5a4 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -33,6 +33,13 @@ const PORT_RELEASE_TIMEOUT_MS = 5000;// Mutable only through the test seam below: a suite asserting the give-up path// cannot sit through two real minutes of polling.let relaunchReadyTimeoutMs = 120000;+// How many times a path that would REFUSE on an unreadable PM2 re-reads it+// first. See `readLlamaServerStatusRetrying`.+const PM2_READ_RETRIES = 2;+// Mutable only through the test seam below, for the same reason as the readiness+// budget above.+const PM2_READ_RETRY_DELAY_MS = 250;+let pm2ReadRetryDelayMs = PM2_READ_RETRY_DELAY_MS;let currentConfig = null;// The launch line the daemon was serving BEFORE PortOS put an assessment tuning@@ -198,7 +205,13 @@ export async function getLlamaServerStatus() {host,port,endpoint,- config: isManagedActive ? currentConfig : null,+ // NOT nulled on a failed read. `currentConfig` is the launch line PortOS+ // itself last started this daemon on, and a subprocess hiccup reading PM2 is+ // no evidence it stopped serving it. Nulling it here collapsed `managed:+ // null` ("could not tell") straight back into `managed: false` ("somebody+ // else's daemon") for every caller guarding on `!managed || !config?.model`+ // — defeating, one line later, the entire point of the null sentinel.+ config: isManagedActive || isReadFailed ? currentConfig : null,// Is this PM2 app in the saved dump `pm2 resurrect` replays at boot?// `null` = the dump could not be read, which is not the same as "no".runAtStartup: savedApps === null ? null : savedApps.includes(LLAMA_APP),@@ -207,6 +220,29 @@ export async function getLlamaServerStatus() {};}+/**+ * `getLlamaServerStatus`, re-read while PM2 answers nothing at all.+ *+ * `managed: null` is "the PM2 read FAILED", and a failed read is a transient+ * subprocess/IPC hiccup far more often than a standing condition — `fetchJlist`+ * caches successes only, so each attempt is a genuine second read rather than+ * the same cached null handed back.+ *+ * Every caller below turns a `null` into a refusal, and a refusal costs a+ * measured assessment its whole reading: an untuned run that cannot be applied+ * is filed `applied: false`, which `getAssessmentReport` drops from `scorable`,+ * which takes the BASELINE row `compareTunings` ranks everything else against+ * off the table. One blip is not worth that, so ask again before answering.+ */+async function readLlamaServerStatusRetrying() {+ let status = await getLlamaServerStatus();+ for (let attempt = 0; status.managed === null && attempt < PM2_READ_RETRIES; attempt += 1) {+ await sleep(pm2ReadRetryDelayMs);+ status = await getLlamaServerStatus();+ }+ return status;+}+/*** Starts llama-server with the specified model and options under PM2.*/@@ -637,8 +673,11 @@ export async function relaunchLlamaServerWithAlias(alias) {* types is only possible if something can put those flags on the launch line* between runs.*- * It refuses rather than guesses in the two cases where it cannot know what to- * relaunch:+ * It refuses rather than guesses in the three cases where it cannot know what to+ * relaunch, or must not:+ * - PM2 could not be read (even after `readLlamaServerStatusRetrying` asked+ * again), so PortOS cannot prove it owns the process. Reported as its own+ * `retryable` refusal, never as the external-ownership one below;* - nothing is running, so there is no model path to reuse;* - something IS listening but PortOS did not start it (an externally-launched* llama-server), so stopping it would kill a process the user owns.@@ -707,8 +746,9 @@ const CLEARED_TUNING = Object.freeze(Object.fromEntries(const asLaunched = (value) => (value === undefined || value === null || value === false ? null : value);/**- * The launch configuration currently in effect, or `null` when PortOS is not the- * one running llama-server (nothing to put back, and nothing it may touch).+ * The launch configuration currently in effect, or `null` when llama-server is+ * not running or is somebody else's (nothing to put back, and nothing PortOS may+ * touch). An unreadable PM2 is NOT one of those: see below.** Paired with `restoreLlamaServerConfig`: a tuning sweep relaunches the daemon* once per variant and would otherwise leave the last variant's flags in place@@ -716,8 +756,13 @@ const asLaunched = (value) => (value === undefined || value === null || value ==* of what they chose.*/export async function captureLlamaServerConfig() {- const status = await getLlamaServerStatus();- return status.running && status.managed && status.config?.model ? status.config : null;+ const status = await readLlamaServerStatusRetrying();+ // `managed !== false`, not `managed`: capturing is a READ, and the only thing+ // a capture can cost is `restoreLlamaServerConfig` later refusing to act on+ // it — which does its own ownership check against a fresh status. Capturing+ // nothing because PM2 blipped is the expensive answer: the sweep then clears+ // the user's own launch flags with no record of what they were.+ return status.running && status.managed !== false && status.config?.model ? status.config : null;}/**@@ -732,13 +777,26 @@ export async function captureLlamaServerConfig() {* llama-server is stopped and the install's `llama` provider is dead until* somebody notices. The captured configuration is a known-good launch line and* nothing holds the port (`startLlamaServer` refuses if anything does), so it is- * started rather than refused. Only a server that is running and NOT- * PortOS-managed is off limits — that one belongs to somebody else.+ * started rather than refused. Only a RUNNING server PortOS does not own is off+ * limits — either because it belongs to somebody else (`managed: false`) or+ * because PM2 could not be read to find out (`managed: null`, reported as its+ * own retryable refusal rather than as somebody else's process).*/export async function restoreLlamaServerConfig(config) {if (!config?.model) return { restored: false, reason: 'nothing was captured' };- const status = await getLlamaServerStatus();- if (status.running && !status.managed) {+ const status = await readLlamaServerStatusRetrying();+ // Split from the refusal below, not folded into it: a server PortOS cannot+ // READ is not a server somebody else started. Both still refuse — PortOS must+ // not stop a process it cannot prove it owns — but only one of them is worth+ // trying again, and only one of them is true.+ if (status.running && status.managed === null) {+ return {+ restored: false,+ retryable: true,+ reason: 'PortOS could not read PM2, so it cannot tell whether this llama-server is its own to restart',+ };+ }+ if (status.running && status.managed === false) {return { restored: false, reason: 'llama-server is now running outside PortOS, so its launch line is not PortOS\'s to change' };}@@ -776,7 +834,26 @@ export async function relaunchLlamaServerWithTuning(tuning = {}, { reset = falsereturn { applied: null, reason: null, config: currentConfig };}- const status = await getLlamaServerStatus();+ const status = await readLlamaServerStatusRetrying();+ // Checked BEFORE `running`, and before anything is discarded. `managed: null`+ // means the PM2 read failed even on retry, so PortOS knows neither what is+ // running nor whether it owns it — and the `!running` branch below would clear+ // `preTuningConfig`, throwing away the only record of the launch line PortOS+ // displaced, on the strength of a read that never happened.+ //+ // It still refuses: PortOS cannot confirm it may restart this daemon, and+ // filing the reading as a trustworthy baseline would be worse. But it refuses+ // as itself — "could not read PM2", retryable — rather than borrowing the+ // wording of an external-ownership refusal, which sends a user who owns the+ // daemon looking for a process that does not exist.+ if (status.managed === null) {+ return {+ applied: false,+ retryable: true,+ reason: 'PortOS could not read PM2, so it cannot tell whether it owns this llama-server. Try again in a moment.',+ config: status.config || null,+ };+ }if (!status.running) {// Whatever carried the tuning is gone; the next start is untuned by// construction, so there is nothing left to undo.@@ -977,12 +1054,13 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {/*** Clears in-memory test state (used by test suites).*/-export function _resetLlamaServerStateForTests({ relaunchReadyTimeout } = {}) {+export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRetryDelay } = {}) {currentConfig = null;preTuningConfig = null;logs.reset();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;+ pm2ReadRetryDelayMs = Number.isFinite(pm2ReadRetryDelay) ? pm2ReadRetryDelay : PM2_READ_RETRY_DELAY_MS;}diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex 44a2dbe45b..09a9d63f75 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -46,6 +46,12 @@ describe('llamaServerManager', () => {let draftPath;let pm2State = null;let execPm2Calls = [];+ // Failed PM2 reads, on demand. `getAppStatusStrict` answers `null` for a read+ // that FAILED — distinct from a successful read that found no process — and+ // several paths must not mistake that for "not PortOS's". Set `failures` to+ // the number of reads to fail, or `Infinity` for a PM2 that never answers+ // again; `count` is what a retry assertion reads.+ let pm2Reads = { failures: 0, count: 0 };beforeAll(async () => {modelDir = await mkdtemp(join(tmpdir(), 'portos-llama-'));@@ -60,10 +66,13 @@ describe('llamaServerManager', () => {});beforeEach(() => {- _resetLlamaServerStateForTests();+ // Zero retry delay: the paths that re-read an unreadable PM2 are asserted+ // here, and a suite must not sit through the production backoff to see them.+ _resetLlamaServerStateForTests({ pm2ReadRetryDelay: 0 });vi.restoreAllMocks();pm2State = null;execPm2Calls = [];+ pm2Reads = { failures: 0, count: 0 };// The host may have an unrelated listener on the requested port (8080 is// especially common), so lifecycle tests pin the port-discovery result.@@ -109,6 +118,13 @@ describe('llamaServerManager', () => {});vi.spyOn(pm2Module, 'getAppStatusStrict').mockImplementation(async (name) => {+ pm2Reads.count += 1;+ if (pm2Reads.failures > 0) {+ // `Infinity - 1` is still `Infinity`, so a permanent outage needs no+ // special case here.+ pm2Reads.failures -= 1;+ return null;+ }if (pm2State && pm2State.name === name) return pm2State;return { name, status: 'not_found', pm2_env: null };});@@ -358,6 +374,33 @@ describe('llamaServerManager', () => {expect(status.lastExitError).toBe('Failed to read PM2 status');});+ // `managed: null` exists to say "could not tell", but nulling `config` on the+ // same failed read handed every caller guarding on `!managed ||+ // !config?.model` the same answer as "somebody else started it".+ it('keeps the last known launch line when the PM2 read fails', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');+ await startLlamaServer({ model: modelPath, port: PORTS.LLAMA_SERVER });++ pm2Reads.failures = Infinity;+ const status = await getLlamaServerStatus();++ expect(status.managed).toBeNull();+ expect(status.config?.model).toBe(modelPath);+ });++ // A read that SUCCEEDED and found nothing is real evidence: there is no+ // launch line, and reporting a stale one would be a lie in the other+ // direction.+ it('reports no launch line when the PM2 read succeeds and finds nothing', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');+ await startLlamaServer({ model: modelPath, port: PORTS.LLAMA_SERVER });+ pm2State = null;++ const status = await getLlamaServerStatus();+ expect(status.managed).toBe(false);+ expect(status.config).toBeNull();+ });+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 };@@ -599,10 +642,12 @@ describe('llamaServerManager', () => {// is not a restart — only a stop/start pair is.const restarted = () => execPm2Calls.some((c) => c[0] === 'start' || c[0] === 'delete');+ const probeTracksPm2 = () => vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')+ .mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));+const started = async () => {vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');- vi.spyOn(openAiModelsProbe, 'probeOpenAiModels')- .mockImplementation(async () => ({ reachable: pm2State?.status === 'online' }));+ probeTracksPm2();await startLlamaServer({ model: modelPath, port: PORTS.LLAMA_SERVER });};@@ -800,6 +845,97 @@ describe('llamaServerManager', () => {expect(await captureLlamaServerConfig()).toBeNull();});+ // ── An unreadable PM2 is a THIRD answer ──────────────────────────────────+ // `getAppStatusStrict` returning null means the read failed, not that the+ // daemon is somebody else's. Telling a user who owns this server that they+ // started it in a terminal points them at a fix for a problem they do not+ // have — and, worse, files their baseline reading as un-applied.++ it('refuses an unreadable PM2 as itself, not as an external llama-server', async () => {+ await started();+ execPm2Calls = [];+ pm2Reads.failures = Infinity;+ const readsBefore = pm2Reads.count;++ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 512 });++ expect(result.applied).toBe(false);+ expect(result.retryable).toBe(true);+ expect(result.reason).toMatch(/could not read PM2/i);+ expect(result.reason).not.toMatch(/outside PortOS/i);+ expect(restarted()).toBe(false);+ // The bypass probe for the retry: it asked more than once before+ // answering, so a single blip cannot decide this.+ expect(pm2Reads.count - readsBefore).toBeGreaterThan(1);+ });++ it('applies the tuning anyway when only the first PM2 read fails', async () => {+ await started();+ execPm2Calls = [];+ pm2Reads.failures = 1;++ const result = await relaunchLlamaServerWithTuning({ ubatchSize: 512 });++ expect(result.applied).toBe(true);+ expect(launchArgs()).toContain('-ub');+ });++ // The regression #4759 turned expensive: an UNTUNED run now relaunches too,+ // and on an unreadable PM2 the old code took the `!running` exit, which+ // cleared the pre-tuning launch line. The baseline that run existed to+ // restore was gone by the time PM2 answered again, so the model's "Backend+ // defaults" row — the one `compareTunings` ranks every tuned reading+ // against — never appeared at all.+ it('does not discard the pre-tuning baseline on an unreadable PM2', async () => {+ await started();+ await relaunchLlamaServerWithTuning({ ubatchSize: 512, flashAttn: true });++ // PM2 unreadable AND the endpoint slow to answer — the state that used to+ // read as "nothing is running, so there is nothing left to undo".+ pm2Reads.failures = Infinity;+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });+ const refused = await relaunchLlamaServerWithTuning({});+ expect(refused.applied).toBe(false);+ expect(refused.retryable).toBe(true);++ // PM2 answers again, and the launch line PortOS displaced is still there+ // to put back.+ pm2Reads.failures = 0;+ probeTracksPm2();+ execPm2Calls = [];+ const cleared = await relaunchLlamaServerWithTuning({});++ expect(cleared.applied).toBeNull();+ expect(restarted()).toBe(true);+ expect(launchArgs()).not.toContain('--flash-attn');+ expect(launchArgs()).not.toContain('-ub');+ });++ // Capturing is a READ. Capturing nothing because PM2 blipped is what costs+ // the user their launch flags: the sweep clears them either way, and the+ // restore then has no record of what they were.+ it('captures the last known launch line when the PM2 read fails', async () => {+ await started();+ pm2Reads.failures = Infinity;++ expect((await captureLlamaServerConfig())?.model).toBe(modelPath);+ });++ it('refuses a restore on an unreadable PM2 without calling it somebody else\'s server', async () => {+ await started();+ const captured = await captureLlamaServerConfig();+ pm2Reads.failures = Infinity;+ execPm2Calls = [];++ const result = await restoreLlamaServerConfig(captured);++ expect(result.restored).toBe(false);+ expect(result.retryable).toBe(true);+ expect(result.reason).toMatch(/could not read PM2/i);+ expect(result.reason).not.toMatch(/outside PortOS/i);+ expect(restarted()).toBe(false);+ });+it('restoring nothing is a no-op rather than a restart', async () => {await started();execPm2Calls = [];