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

make the model-id relaunch single-flight and cover its route

Adam Eivy52ca5adbdad8
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 99c290671b..4b74ba57bc 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -51,6 +51,13 @@ 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
@@ -482,7 +489,14 @@ 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' });
}
- const result = await relaunchLlamaServerWithAlias(wanted);
+ if (serveModelInFlight) {
+ throw new ServerError('Another local-server relaunch is already running. Wait for it to finish.', { status: 409, code: 'SERVE_MODEL_IN_FLIGHT' });
+ }
+ 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; });
// The daemon's launch line just changed under the readiness caches, and the
// page polls them within seconds.
resetProviderReadinessCache();
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
index c66aaf12c3..7f98a26977 100644
--- a/server/routes/providers.readiness.test.js
+++ b/server/routes/providers.readiness.test.js
@@ -7,7 +7,13 @@ const readinessService = vi.hoisted(() => ({
getProviderReadinessMap: vi.fn(),
resetProviderReadinessCache: vi.fn(),
}));
-vi.mock('../services/providerReadiness.js', () => readinessService);
+// PARTIAL mock, same reasoning as the setup service below: the route derives the
+// model id it will serve through the REAL `servedModelId`, so a fully-stubbed
+// 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() }));
+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,
// and a stubbed copy would let a route accepting an action the service cannot
@@ -166,3 +172,124 @@ describe('POST /api/providers/readiness/setup', () => {
expect(response.status).toBe(400);
});
});
+
+// The mismatch the serve-model route exists for: llama.cpp serves one model per
+// process under the `--alias` on its launch line, so a provider pinned to
+// another id is fixed by renaming the SERVER, not by downloading anything.
+const LLAMA_TUI = {
+ id: 'opencode-llama-tui',
+ name: 'OpenCode llama TUI',
+ type: 'tui',
+ command: 'opencode',
+ llamaBacked: true,
+ endpoint: 'http://127.0.0.1:5568/v1',
+ models: ['dflash', 'qwen3.8-27b-dflash2'],
+ defaultModel: 'qwen3.8-27b-dflash2',
+};
+
+describe('POST /api/providers/readiness/serve-model', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ llamaService.relaunchLlamaServerWithAlias.mockResolvedValue({ applied: true, reason: null, config: null });
+ });
+
+ it('relaunches under the id the provider sends, re-derived from the stored record', async () => {
+ const response = await request(app([LLAMA_TUI]))
+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ success: true, model: 'qwen3.8-27b-dflash2', relaunched: true });
+ // The id comes from the record, never from the query string.
+ expect(llamaService.relaunchLlamaServerWithAlias).toHaveBeenCalledWith('qwen3.8-27b-dflash2');
+ // The readiness caches remember the OLD served id, and the page polls them
+ // within seconds.
+ expect(readinessService.resetProviderReadinessCache).toHaveBeenCalled();
+ });
+
+ it('strips the OpenCode namespace before naming the alias', async () => {
+ // `llama/dflash` addresses the OpenCode provider entry; the daemon only ever
+ // answers under the bare alias, so relaunching under the prefixed form would
+ // leave the check failing exactly as before.
+ await request(app([{ ...LLAMA_TUI, defaultModel: 'llama/qwen3.8-27b-dflash2' }]))
+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');
+
+ expect(llamaService.relaunchLlamaServerWithAlias).toHaveBeenCalledWith('qwen3.8-27b-dflash2');
+ });
+
+ // `applied: null` = the daemon already answered under that id. Reporting a
+ // restart would have the user waiting for a reload that never happened.
+ it('reports relaunched: false when the daemon already serves that id', async () => {
+ llamaService.relaunchLlamaServerWithAlias.mockResolvedValueOnce({ applied: null, reason: null, config: null });
+
+ const response = await request(app([LLAMA_TUI]))
+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ success: true, relaunched: false });
+ });
+
+ it('surfaces the refusal — with its fix — when PortOS did not start the daemon', async () => {
+ llamaService.relaunchLlamaServerWithAlias.mockResolvedValueOnce({
+ applied: false,
+ reason: 'llama-server is not running under PortOS, so its launch line is not PortOS\'s to change.',
+ config: null,
+ });
+
+ const response = await request(app([LLAMA_TUI]))
+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');
+
+ expect(response.status).toBe(409);
+ expect(response.body.error).toMatch(/not running under PortOS/);
+ });
+
+ // Ollama names a model after the weights it loaded — there is no launch-line
+ // label to change, so the route must refuse rather than relaunch something.
+ it('refuses a runtime that has no model id to rename', async () => {
+ const response = await request(app([CLAUDE_OLLAMA]))
+ .post('/api/providers/readiness/serve-model?provider=claude-ollama');
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('NO_MODEL_ALIAS');
+ expect(llamaService.relaunchLlamaServerWithAlias).not.toHaveBeenCalled();
+ });
+
+ it('refuses a provider that selects no specific model', async () => {
+ const response = await request(app([{ ...LLAMA_TUI, defaultModel: '' }]))
+ .post('/api/providers/readiness/serve-model?provider=opencode-llama-tui');
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('NO_DEFAULT_MODEL');
+ expect(llamaService.relaunchLlamaServerWithAlias).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown provider', async () => {
+ const response = await request(app([LLAMA_TUI]))
+ .post('/api/providers/readiness/serve-model?provider=nope');
+
+ expect(response.status).toBe(404);
+ 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);
+ });
+});