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
address review (codex): scope, baseline, and sentinel fixes on the model-id relaunch
Adam Eivy661453f543c3
diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 4b74ba57bc..d6392d9c12 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -16,10 +16,11 @@ import {stopRuntimeInstaller,} from '../services/providerRuntimeInstaller.js';import { getProviderReadinessMap, resetProviderReadinessCache, servedModelId } from '../services/providerReadiness.js';-import { relaunchLlamaServerWithAlias } from '../services/llamaServerManager.js';+import { getLlamaServerEndpoint, relaunchLlamaServerWithAlias } from '../services/llamaServerManager.js';+import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';import { getProviderPrerequisiteMap } from '../services/providerPrerequisites.js';import { runLocalRuntimeSetup, SETUP_ACTIONS } from '../services/localRuntimeSetup.js';-import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';+import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';/**@@ -51,13 +52,6 @@ let runtimeInstallInFlight = null;// never what a double-click meant.let runtimeSetupInFlight = false;-// And for the model-id relaunch lane. Two providers can point at ONE-// llama-server, so a second relaunch arriving mid-flight would stop the daemon-// the first one just started and leave whichever finished last on the port —-// with the first caller reporting a success that no longer describes anything-// running. Single-flight for the same reason the setup lane above is.-let serveModelInFlight = false;-/*** Sanitize a provider object for client responses.* Strips apiKey (replaces with hasApiKey boolean) and redacts secretEnvVars@@ -489,19 +483,49 @@ export function createPortOSProviderRoutes(aiToolkit) {throw new ServerError('This provider selects no specific model, so there is nothing to serve it as.', { status: 400, code: 'NO_DEFAULT_MODEL' });}- if (serveModelInFlight) {- throw new ServerError('Another local-server relaunch is already running. Wait for it to finish.', { status: 409, code: 'SERVE_MODEL_IN_FLIGHT' });+ // The provider's OWN endpoint, not the runtime's default: a second+ // llama-server on another loopback port is a different daemon, and PortOS+ // only manages one (`portos-llama-server`). Without this the button on a+ // provider pointed at that second server would restart the managed one under+ // the second one's model id — breaking the provider that WAS working and+ // leaving the clicked one mismatched exactly as before.+ const managedEndpoint = await getLlamaServerEndpoint();+ // Compared by PORT, not by string: the manager renders its host as+ // `127.0.0.1` while a provider may spell the same daemon `localhost`, and a+ // string compare would refuse a setup that works. `localRuntimeForProvider`+ // already guarantees `runtime.endpoint` is a local-instance host, so a+ // matching port is the same daemon.+ if (localEndpointPort(runtime.endpoint) !== localEndpointPort(managedEndpoint)) {+ throw new ServerError(+ `This provider points at ${runtime.endpoint}, but the llama-server PortOS manages serves ${managedEndpoint}. Add \`--alias ${wanted}\` to that server's own launch line instead.`,+ { status: 409, code: 'LLAMA_ENDPOINT_MISMATCH' },+ );+ }++ // A relaunch reloads multi-gigabyte weights onto the accelerator, and an+ // assessment sweep relaunches the same daemon on its own schedule — so this+ // takes the machine-wide claim those jobs take rather than a lock private to+ // this route. Zero timeout: an interactive click refuses immediately with+ // who holds it rather than queueing behind hours of sweep.+ const claim = await claimHeavyLocalJob({ kind: 'llama-server model id', id: wanted, timeoutMs: 0 });+ if (!claim.ok) {+ throw new ServerError(claim.message, { status: 409, code: 'LOCAL_ACCELERATOR_BUSY' });}- serveModelInFlight = true;// `relaunchLlamaServerWithAlias` resolves for every expected refusal, so- // this covers the unexpected throw — the lock must not survive it, or the- // route is dead until the process restarts.- const result = await relaunchLlamaServerWithAlias(wanted).finally(() => { serveModelInFlight = false; });+ // this covers the unexpected throw — the claim must not survive it, or every+ // later heavy local job is refused until the process exits.+ const result = await relaunchLlamaServerWithAlias(wanted).finally(() => claim.release());// The daemon's launch line just changed under the readiness caches, and the// page polls them within seconds.resetProviderReadinessCache();if (result.applied === false) {- throw new ServerError(result.reason, { status: 409, code: 'SERVE_MODEL_FAILED', context: { model: wanted } });+ throw new ServerError(result.reason, {+ // A PM2 read that failed says nothing about the daemon — the fix is to+ // retry, not to go edit a launch line.+ status: result.retryable ? 503 : 409,+ code: result.retryable ? 'SERVE_MODEL_UNAVAILABLE' : 'SERVE_MODEL_FAILED',+ context: { model: wanted },+ });}res.json({success: true,diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.jsindex 7f98a26977..57a70ae8f0 100644--- a/server/routes/providers.readiness.test.js+++ b/server/routes/providers.readiness.test.js@@ -12,7 +12,12 @@ const readinessService = vi.hoisted(() => ({// module would hand it `undefined` and the route would throw before it ever// reached the daemon.vi.mock('../services/providerReadiness.js', async (importOriginal) => ({ ...(await importOriginal()), ...readinessService }));-const llamaService = vi.hoisted(() => ({ relaunchLlamaServerWithAlias: vi.fn() }));+const llamaService = vi.hoisted(() => ({+ relaunchLlamaServerWithAlias: vi.fn(),+ // The route checks that the provider points at the daemon PortOS actually+ // manages before relaunching it, so the suite has to say where that is.+ getLlamaServerEndpoint: vi.fn(),+}));vi.mock('../services/llamaServerManager.js', async (importOriginal) => ({ ...(await importOriginal()), ...llamaService }));const setupService = vi.hoisted(() => ({ runLocalRuntimeSetup: vi.fn() }));// PARTIAL mock: `SETUP_ACTIONS` is the closed set the route validates against,@@ -191,6 +196,7 @@ describe('POST /api/providers/readiness/serve-model', () => {beforeEach(() => {vi.clearAllMocks();llamaService.relaunchLlamaServerWithAlias.mockResolvedValue({ applied: true, reason: null, config: null });+ llamaService.getLlamaServerEndpoint.mockResolvedValue('http://127.0.0.1:5568/v1');});it('relaunches under the id the provider sends, re-derived from the stored record', async () => {@@ -270,26 +276,44 @@ describe('POST /api/providers/readiness/serve-model', () => {expect(llamaService.relaunchLlamaServerWithAlias).not.toHaveBeenCalled();});- // Two providers can point at ONE llama-server, so a second relaunch arriving- // mid-flight would stop the daemon the first one just started.- it('is single-flight — a concurrent relaunch is refused, not raced', async () => {- let release;- llamaService.relaunchLlamaServerWithAlias.mockImplementationOnce(- () => new Promise((resolve) => { release = () => resolve({ applied: true, reason: null, config: null }); }),- );- const server = app([LLAMA_TUI]);-- // `.then()` is what starts a RequestBuilder — holding the builder alone- // never sends, so the second request would find the lane free.- const first = request(server).post('/api/providers/readiness/serve-model?provider=opencode-llama-tui').then((r) => r);- // Let the first request reach the in-flight guard before the second lands.- await vi.waitFor(() => expect(release).toBeTypeOf('function'));- const second = await request(server).post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');-- expect(second.status).toBe(409);- expect(second.body.code).toBe('SERVE_MODEL_IN_FLIGHT');- release();- expect((await first).status).toBe(200);- expect(llamaService.relaunchLlamaServerWithAlias).toHaveBeenCalledTimes(1);+ // The manager renders its host as `127.0.0.1` while a provider may spell the+ // same daemon `localhost`. A string compare would refuse a working setup.+ it('accepts a differently-spelled host for the same daemon', async () => {+ const response = await request(app([{ ...LLAMA_TUI, endpoint: 'http://localhost:5568/v1' }]))+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');++ expect(response.status).toBe(200);+ expect(llamaService.relaunchLlamaServerWithAlias).toHaveBeenCalledWith('qwen3.8-27b-dflash2');+ });++ // PortOS manages exactly one llama-server. A provider pointed at a SECOND one+ // on another loopback port must not restart the managed daemon under the+ // second one's model id — that breaks the provider that was working and+ // leaves the clicked one mismatched exactly as before.+ it('refuses a provider pointed at a llama-server PortOS does not manage', async () => {+ const response = await request(app([{ ...LLAMA_TUI, endpoint: 'http://127.0.0.1:5569/v1' }]))+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');++ expect(response.status).toBe(409);+ expect(response.body.code).toBe('LLAMA_ENDPOINT_MISMATCH');+ expect(response.body.error).toMatch(/--alias qwen3\.8-27b-dflash2/);+ expect(llamaService.relaunchLlamaServerWithAlias).not.toHaveBeenCalled();+ });++ // A PM2 read that failed says nothing about the daemon — the fix is to retry,+ // not to go edit a launch line, so it must not share the 409 refusal.+ it('reports a PM2 read failure as retryable, not as an external daemon', async () => {+ llamaService.relaunchLlamaServerWithAlias.mockResolvedValueOnce({+ applied: false,+ retryable: true,+ reason: 'PortOS could not read PM2 to find out what llama-server is running. Try again in a moment.',+ config: null,+ });++ const response = await request(app([LLAMA_TUI]))+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');++ expect(response.status).toBe(503);+ expect(response.body.code).toBe('SERVE_MODEL_UNAVAILABLE');});});diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 74ce33bfa0..c89fed7022 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -545,13 +545,21 @@ async function relaunchWithConfig(next, previous) {* `managed: false` covers both "nothing is running" and "something is listening* that PortOS did not start" — neither is a launch line PortOS may change.*- * @returns {Promise<{managed: boolean, config: object|null}>}+ * `readFailed: true` is a THIRD answer and must not collapse into either: it+ * means PM2 itself could not be read (`getAppStatusStrict`'s null sentinel), so+ * PortOS does not know what is running. Reporting that as "not PortOS's" would+ * tell a user who owns the daemon to go add `--alias` to a launch line PortOS+ * wrote — the fix is to retry. `getLlamaServerStatus` draws the same+ * distinction (`isReadFailed`).+ *+ * @returns {Promise<{managed: boolean, config: object|null, readFailed: boolean}>}*/export async function readLlamaServerLaunch() {const pm2Status = await getAppStatusStrict(LLAMA_APP);- if (!pm2Status || pm2Status.status !== 'online') return { managed: false, config: null };+ if (pm2Status === null) return { managed: false, config: null, readFailed: true };+ if (pm2Status.status !== 'online') return { managed: false, config: null, readFailed: false };if (!currentConfig && pm2Status.args) currentConfig = parseConfigFromArgs(pm2Status.args);- return { managed: true, config: currentConfig };+ return { managed: true, config: currentConfig, readFailed: false };}/**@@ -575,7 +583,15 @@ export async function relaunchLlamaServerWithAlias(alias) {const wanted = String(alias ?? '').trim();if (!wanted) return { applied: false, reason: 'No model id was given to serve under.', config: null };- const { managed, config } = await readLlamaServerLaunch();+ const { managed, config, readFailed } = await readLlamaServerLaunch();+ if (readFailed) {+ return {+ applied: false,+ retryable: true,+ reason: 'PortOS could not read PM2 to find out what llama-server is running. Try again in a moment.',+ config: null,+ };+ }if (!managed || !config?.model) {return {applied: false,@@ -592,10 +608,13 @@ export async function relaunchLlamaServerWithAlias(alias) {const baseline = preTuningConfig;console.log(`🦙 llama-server: relaunching to answer as ${wanted} (was ${config.alias || 'unset'})`);const outcome = await relaunchWithConfig({ ...config, alias: wanted }, config);- // Every outcome leaves the same weights and the same tuning flags on the port- // — the renamed line on success, the original one on either failure — so the- // displaced baseline is still the line to put back later, whichever it was.- preTuningConfig = baseline;+ // The baseline is the line a later untuned assessment RELAUNCHES, so it has to+ // carry the new id or that assessment silently renames the daemon back and+ // re-breaks the provider this button just fixed. Only the alias moves: every+ // other field of the baseline is the user's own launch line, which a rename+ // does not touch. On either failure path the original alias is what is back on+ // the port, so the baseline stays exactly as captured.+ preTuningConfig = outcome.ok && baseline ? { ...baseline, alias: wanted } : baseline;if (outcome.rejected) {return { applied: false, reason: `llama-server rejected the relaunch: ${outcome.rejected}`, config: outcome.config };}diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex 37e39cbc30..44a2dbe45b 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -527,6 +527,51 @@ describe('llamaServerManager', () => {expect(execPm2Calls.some((c) => c[0] === 'start' || c[0] === 'delete')).toBe(false);});+ // The regression this pins: an untuned assessment RELAUNCHES the pre-tuning+ // baseline. If that baseline keeps the old alias, it silently renames the+ // daemon back and re-breaks the provider the rename just fixed.+ it('carries the new id into the pre-tuning baseline a later untune restores', async () => {+ await startedAs('dflash');+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });+ await relaunchLlamaServerWithAlias('qwen3.8-27b-dflash2');+ execPm2Calls = [];++ // The untuned measurement: puts the pre-tuning launch line back.+ await relaunchLlamaServerWithTuning({});++ const args = lastStartArgs();+ expect(args[args.indexOf('--alias') + 1]).toBe('qwen3.8-27b-dflash2');+ // ...and it is still a genuine untune: the tuning flag is gone.+ expect(args).not.toContain('-ub');+ });++ // A rejected rename leaves the ORIGINAL alias on the port, so the baseline+ // must stay exactly as captured or the untune would rename to an id nothing+ // ever served.+ it('leaves the baseline alone when the rename never takes', async () => {+ await startedAs('dflash');+ await relaunchLlamaServerWithTuning({ ubatchSize: 512 });+ // Fail only the renamed launch; the restore that follows must succeed.+ const fakeExec = pm2Module.execPm2.getMockImplementation();+ let starts = 0;+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ if (args[0] === 'start' && starts++ === 0) {+ pm2State = { name: LLAMA_APP, status: 'errored', pid: null, args: [] };+ execPm2Calls.push(args);+ return { stdout: '', stderr: '' };+ }+ return fakeExec(args);+ });++ const result = await relaunchLlamaServerWithAlias('qwen3.8-27b-dflash2');+ expect(result.applied).toBe(false);++ execPm2Calls = [];+ await relaunchLlamaServerWithTuning({});+ const args = lastStartArgs();+ expect(args[args.indexOf('--alias') + 1]).toBe('dflash');+ });+it('refuses a blank model id without touching the daemon', async () => {await startedAs('dflash');execPm2Calls = [];