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: avoid llama-server port collisions

Adam Eivy08553eabeb58
diff --git a/client/src/components/providers/ProviderReadiness.test.jsx b/client/src/components/providers/ProviderReadiness.test.jsx
index 8c115006ef..07b2611a6b 100644
--- a/client/src/components/providers/ProviderReadiness.test.jsx
+++ b/client/src/components/providers/ProviderReadiness.test.jsx
@@ -8,14 +8,14 @@ const renderWithRouter = (ui) => render(<MemoryRouter>{ui}</MemoryRouter>);
const readiness = (overrides = {}) => ({
kind: 'llama',
label: 'llama.cpp',
- endpoint: 'http://127.0.0.1:8080/v1',
+ endpoint: 'http://127.0.0.1:5568/v1',
manageUrl: '/settings/local-llm',
docsUrl: 'https://example.com/llama-docs',
ready: false,
setup: null,
checks: [
{ id: 'runtime', label: 'llama.cpp installed', ok: true, detail: '`llama-server` is on PortOS\'s PATH.', fixHint: null },
- { id: 'server', label: 'llama.cpp server responding', ok: false, detail: 'Nothing answered at http://127.0.0.1:8080/v1 (connection refused).', fixHint: 'Start llama.cpp — it serves GGUF weights you download yourself.' },
+ { id: 'server', label: 'llama.cpp server responding', ok: false, detail: 'Nothing answered at http://127.0.0.1:5568/v1 (connection refused).', fixHint: 'Start llama.cpp — it serves GGUF weights you download yourself.' },
{ id: 'model', label: 'Model `dflash` available', ok: null, detail: 'Cannot be checked until the server responds.', fixHint: null },
],
...overrides,
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index e32f93884b..06cc93d90b 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -51,7 +51,10 @@ const specWeightEntries = (preset) => [preset?.model, preset?.draftModel].filter
// Defaults for the advanced numeric fields. They are applied when the server is
// launched rather than on every keystroke: a controlled number input that coerces
// as you type snaps back to its default the moment you clear it to retype.
-const LLAMA_NUMBER_DEFAULTS = { port: 8080, ctxSize: 32768, nGpuLayers: 99 };
+// Keep the launcher default aligned with server/lib/ports.js. 8080 is a common
+// IPFS / Tomcat / local-dashboard port and is not a safe default for a managed
+// daemon.
+const LLAMA_NUMBER_DEFAULTS = { port: 5568, ctxSize: 32768, nGpuLayers: 99 };
const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';
@@ -420,7 +423,7 @@ export function LocalLlmTab() {
model: '',
draftModel: '',
specType: 'draft-dspark',
- port: 8080,
+ port: 5568,
host: '127.0.0.1',
ctxSize: 32768,
nGpuLayers: 99,
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index dbda0da2f0..40300f9518 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -676,7 +676,7 @@ describe('LocalLlmTab llama-server management', () => {
managed: true,
presets: specPresets(),
pid: 9999,
- endpoint: 'http://127.0.0.1:8080/v1',
+ endpoint: 'http://127.0.0.1:5568/v1',
config: { model: 'models/base.gguf', draftModel: 'models/draft.gguf', specType: 'draft-dflash' },
});
stopLlamaServer.mockResolvedValueOnce({ success: true });
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index d8e71a98bf..c57f3b8416 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -258,7 +258,7 @@ describe('local-daemon readiness on the provider card', () => {
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
api.getProviders.mockResolvedValue({
- providers: [{ id: 'opencode-llama-tui', name: 'OpenCode llama TUI', type: 'tui', command: 'opencode', args: [], enabled: true, endpoint: 'http://127.0.0.1:8080/v1', llamaBacked: true }],
+ providers: [{ id: 'opencode-llama-tui', name: 'OpenCode llama TUI', type: 'tui', command: 'opencode', args: [], enabled: true, endpoint: 'http://127.0.0.1:5568/v1', llamaBacked: true }],
activeProvider: null,
});
});
@@ -269,7 +269,7 @@ describe('local-daemon readiness on the provider card', () => {
'opencode-llama-tui': {
kind: 'llama',
label: 'llama.cpp',
- endpoint: 'http://127.0.0.1:8080/v1',
+ endpoint: 'http://127.0.0.1:5568/v1',
manageUrl: '/settings/local-llm',
docsUrl: 'https://example.com/docs',
ready: false,
diff --git a/data.reference/providers.json b/data.reference/providers.json
index a308f45a96..945b192391 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -236,14 +236,14 @@
"type": "tui",
"command": "opencode",
"args": [],
- "endpoint": "http://127.0.0.1:8080/v1",
+ "endpoint": "http://127.0.0.1:5568/v1",
"models": ["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"],
"defaultModel": "dflash",
"llamaBacked": true,
"timeout": 600000,
"enabled": true,
"envVars": {
- "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8080/v1\"}}}}"
+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:5568/v1\"}}}}"
},
"secretEnvVars": [],
"tuiPromptDelayMs": 2500,
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 99c73c83e5..5d42a54713 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -34,6 +34,7 @@ Common port labels:
| 5559 | portos-autofixer | api | Autofixer daemon API |
| 5560 | portos-autofixer-ui | ui | Autofixer web UI |
| 5561 | portos-db (Docker container) | - | Infrastructure dependency: PostgreSQL Docker container provisioned by `scripts/setup-db.js` / Docker Compose (not a PM2 process in `server/services/apps.js`; native mode uses system pg on 5432). |
+| 5568 | llama-server | - | Loopback speculative-decoding server managed from Settings → Local LLM |
## How `:5555`, `:5553`, and `:5554` Relate
@@ -118,7 +119,7 @@ PortOS automatically detects ports from env vars:
| Range | Purpose |
|-------|---------|
| 5553-5561 | PortOS core services (includes the `:5553` loopback mirror and the `portos-db` Docker container on `:5561`) |
-| 5562-5569 | Reserved for PortOS extensions |
+| 5562-5569 | Reserved for PortOS extensions (5568 is the managed llama-server default) |
| 5570-5599 | User applications |
PostgreSQL in native mode listens on the system default `:5432`, outside these ranges.
diff --git a/docs/features/dflash2.md b/docs/features/dflash2.md
index ba7076c507..01852a094b 100644
--- a/docs/features/dflash2.md
+++ b/docs/features/dflash2.md
@@ -13,7 +13,7 @@ PortOS integrates both through the **OpenCode llama TUI** provider preset and th
## What PortOS Adds
1. **OpenCode llama TUI Provider**:
- - An attachable `tui` coding-agent provider preset (`opencode-llama-tui`) configured to connect to `http://127.0.0.1:8080/v1`.
+ - An attachable `tui` coding-agent provider preset (`opencode-llama-tui`) configured to connect to `http://127.0.0.1:5568/v1`.
- Seeded with default model aliases `["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"]` with default `dflash`. The launcher keeps `--alias dflash` for every drafter family so this alias resolves regardless of which one you run.
- Fully enabled by default and equipped with OpenCode's agentic file-writing harness, tool calling, and session persistence.
2. **Model Refresh**:
@@ -70,7 +70,7 @@ DFlash 2 pairs (require a source build of llama.cpp [#27342](https://github.com/
- Drafter: `z-lab/Muse-Glimmer-30B-DFlash2-GGUF` (e.g. `Muse-Glimmer-30B-DFlash2-Q4_K_M.gguf`)
### 2. Launch llama-server
-Start `llama-server` on loopback port `8080` with speculative decoding enabled
+Start `llama-server` on loopback port `5568` with speculative decoding enabled
(`--spec-type draft-dflash` for a DFlash drafter, `draft-dspark` for a DSpark one):
```bash
@@ -78,7 +78,7 @@ llama-server \
-m models/Qwen3.8-27B-Q4_K_M.gguf \
--model-draft models/Qwen3.8-27B-DSpark-BF16.gguf \
--spec-type draft-dspark \
- --port 8080 \
+ --port 5568 \
--host 127.0.0.1 \
--alias dflash \
--ctx-size 32768 \
diff --git a/docs/research/2026-08-19-dspark-vs-dflash2.md b/docs/research/2026-08-19-dspark-vs-dflash2.md
index a878bdf1d6..33710a57d4 100644
--- a/docs/research/2026-08-19-dspark-vs-dflash2.md
+++ b/docs/research/2026-08-19-dspark-vs-dflash2.md
@@ -100,9 +100,10 @@ still be wrong:
[Qwen3.8 27B MLX evaluation](./2026-08-16-qwen38-mlx-macos.md) both declined.
- **A user who wants it needs nothing from PortOS.** `mlx-dspark serve` listens
on `127.0.0.1:8080` and speaks `/v1/chat/completions` and `/v1/models` — the
- exact endpoint the shipped `opencode-llama-tui` provider preset already points
- at. Stop `llama-server`, start `mlx-dspark serve`, hit **Refresh Models**. Any
- integration PortOS wrote would duplicate that for no gain.
+ same OpenAI-compatible API as the shipped `opencode-llama-tui` provider.
+ Configure that provider for 8080 if you use this external server, then hit
+ **Refresh Models**. Any integration PortOS wrote would duplicate that for no
+ gain.
- Its own caveats narrow the win further: MoE targets (Nemotron 1.10×,
Qwen3.6-35B-A3B 1.32×) and 2-bit Bonsai (1.07×) barely clear break-even, and
hybrid targets can't batch.
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 51ceaefdbd..4503501d04 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -48,6 +48,7 @@ const PORTS = {
AUTOFIXER: 5559, // Autofixer API
AUTOFIXER_UI: 5560, // Autofixer UI
POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)
+ LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server
POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)
};
diff --git a/scripts/migrations/283-llama-server-port.js b/scripts/migrations/283-llama-server-port.js
new file mode 100644
index 0000000000..e1af7525fa
--- /dev/null
+++ b/scripts/migrations/283-llama-server-port.js
@@ -0,0 +1,58 @@
+/**
+ * Move the shipped llama-server endpoint off common port 8080.
+ *
+ * Port 8080 is frequently occupied by IPFS, Tomcat, local dashboards, and
+ * other developer services. The managed llama-server now uses PortOS's
+ * reserved extension port, 5568. Only the exact provider configuration shipped
+ * by migration 280 is rewritten; a user who chose another endpoint keeps it.
+ */
+
+import { readProvidersDoc, writeJsonAtomic } from './_lib.js';
+
+const OLD_ENDPOINT = 'http://127.0.0.1:8080/v1';
+const NEW_ENDPOINT = 'http://127.0.0.1:5568/v1';
+const PROVIDER_ID = 'opencode-llama-tui';
+
+const storedLlamaConfig = (provider) => {
+ const raw = provider?.envVars?.OPENCODE_CONFIG_CONTENT;
+ if (typeof raw !== 'string' || raw.trim() === '') return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+};
+
+export default {
+ async up({ rootDir }) {
+ const doc = await readProvidersDoc({ rootDir });
+ if (!doc.ok) return { ok: false, reason: doc.reason, updated: 0 };
+
+ const provider = doc.providers[PROVIDER_ID];
+ if (!provider || provider.endpoint !== OLD_ENDPOINT) {
+ return { ok: true, reason: 'already-current-or-custom', updated: 0 };
+ }
+
+ const config = storedLlamaConfig(provider);
+ // An unparsable or differently pointed OpenCode config is user-owned. Do
+ // not make the displayed endpoint disagree with the config that actually
+ // controls the spawned CLI.
+ const configuredBaseUrl = config?.provider?.llama?.options?.baseURL;
+ if (config === undefined || (configuredBaseUrl && configuredBaseUrl !== OLD_ENDPOINT)) {
+ return { ok: true, reason: 'custom-config', updated: 0 };
+ }
+
+ provider.endpoint = NEW_ENDPOINT;
+ if (configuredBaseUrl === OLD_ENDPOINT) {
+ config.provider.llama.options.baseURL = NEW_ENDPOINT;
+ provider.envVars = {
+ ...provider.envVars,
+ OPENCODE_CONFIG_CONTENT: JSON.stringify(config),
+ };
+ }
+
+ await writeJsonAtomic(doc.path, doc.config);
+ console.log(`📝 ${doc.path}: moved ${PROVIDER_ID} from ${OLD_ENDPOINT} to ${NEW_ENDPOINT}`);
+ return { ok: true, reason: 'updated', updated: 1 };
+ },
+};
diff --git a/scripts/migrations/283-llama-server-port.test.js b/scripts/migrations/283-llama-server-port.test.js
new file mode 100644
index 0000000000..97109250dc
--- /dev/null
+++ b/scripts/migrations/283-llama-server-port.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './283-llama-server-port.js';
+
+const OLD_ENDPOINT = 'http://127.0.0.1:8080/v1';
+const NEW_ENDPOINT = 'http://127.0.0.1:5568/v1';
+const oldConfig = () => JSON.stringify({
+ permission: 'allow',
+ provider: { llama: { options: { baseURL: OLD_ENDPOINT } } },
+});
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+
+describe('migration 283 — llama-server port', () => {
+ let rootDir;
+ let providersPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-283-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ providersPath = join(rootDir, 'data/providers.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('moves the shipped endpoint and embedded OpenCode URL together', async () => {
+ writeJson(providersPath, {
+ activeProvider: 'claude-code',
+ providers: {
+ 'opencode-llama-tui': {
+ id: 'opencode-llama-tui',
+ endpoint: OLD_ENDPOINT,
+ envVars: { OPENCODE_CONFIG_CONTENT: oldConfig() },
+ },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ const provider = readJson(providersPath).providers['opencode-llama-tui'];
+ expect(provider.endpoint).toBe(NEW_ENDPOINT);
+ expect(JSON.parse(provider.envVars.OPENCODE_CONFIG_CONTENT).provider.llama.options.baseURL)
+ .toBe(NEW_ENDPOINT);
+ });
+
+ it('preserves a provider whose OpenCode config points at a custom endpoint', async () => {
+ const customEndpoint = 'http://127.0.0.1:8090/v1';
+ writeJson(providersPath, {
+ providers: {
+ 'opencode-llama-tui': {
+ id: 'opencode-llama-tui',
+ endpoint: OLD_ENDPOINT,
+ envVars: {
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
+ provider: { llama: { options: { baseURL: customEndpoint } } },
+ }),
+ },
+ },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ expect(readJson(providersPath).providers['opencode-llama-tui'].endpoint).toBe(OLD_ENDPOINT);
+ });
+});
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index fde81f66b3..b4be767743 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -156,14 +156,14 @@
"type": "tui",
"command": "opencode",
"args": [],
- "endpoint": "http://127.0.0.1:8080/v1",
+ "endpoint": "http://127.0.0.1:5568/v1",
"models": ["dflash", "qwen3.8-27b-dflash2", "Muse-Glimmer-30B-DFlash2"],
"defaultModel": "dflash",
"llamaBacked": true,
"timeout": 600000,
"enabled": true,
"envVars": {
- "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:8080/v1\"}}}}"
+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"llama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"llama.cpp (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:5568/v1\"}}}}"
},
"secretEnvVars": [],
"tuiPromptDelayMs": 2500,
diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.js
index 0af4f6e849..9b6c57a5cd 100644
--- a/server/lib/localProviderRuntime.js
+++ b/server/lib/localProviderRuntime.js
@@ -21,8 +21,8 @@
* `localModelHealing.js` re-exports it for its existing callers.
*
* Endpoint resolution deliberately prefers the provider's OWN configuration
- * over any default: a user who moved llama-server to port 8090 edited
- * `OPENCODE_CONFIG_CONTENT` (or `endpoint`), and probing 8080 anyway would
+ * over any default: a user who moved llama-server to another port edited
+ * `OPENCODE_CONFIG_CONTENT` (or `endpoint`), and probing the old default anyway would
* report their working setup as broken.
*/
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 81721797d9..8e815f7221 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -9,6 +9,7 @@
* `mediaValidation` namespace.
*/
import { z } from 'zod';
+import { PORTS } from './ports.js';
// OpenWorld snapshot pipeline (issue #877): how often to capture a city-state
// frame and how many to retain. Validated as a settings slice on PUT /api/settings;
@@ -165,7 +166,7 @@ export const localLlmLlamaServerStartSchema = z.object({
model: z.string().trim().min(1).max(500),
draftModel: z.string().trim().max(500).optional().nullable(),
specType: z.string().trim().max(100).optional().default('draft-dflash'),
- port: z.coerce.number().int().min(1).max(65535).optional().default(8080),
+ port: z.coerce.number().int().min(1).max(65535).optional().default(PORTS.LLAMA_SERVER),
host: z.string().trim().max(100).optional().default('127.0.0.1'),
ctxSize: z.coerce.number().int().min(512).max(1048576).optional().default(32768),
nGpuLayers: z.coerce.number().int().min(0).max(999).optional().default(99),
diff --git a/server/lib/openAiModelsProbe.js b/server/lib/openAiModelsProbe.js
index d70531589d..6694271ca2 100644
--- a/server/lib/openAiModelsProbe.js
+++ b/server/lib/openAiModelsProbe.js
@@ -22,7 +22,7 @@ import { readResponseJson } from './readResponseJson.js';
/**
* The one-token reason a probe failed, for a UI that has a line to spend on it.
* `describeFetchError` returns the whole cause chain (`fetch failed: ECONNREFUSED:
- * connect ECONNREFUSED 127.0.0.1:8080`); the code alone is what tells the user
+ * connect ECONNREFUSED <host>:<port>`); the code alone is what tells the user
* "nothing is listening" from "the host is wedged", and the two timeout
* spellings mean the same thing to them.
*/
diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.js
index 2c967c6a07..a146585b3d 100644
--- a/server/lib/opencodeConfig.js
+++ b/server/lib/opencodeConfig.js
@@ -19,6 +19,9 @@
*/
import { getOpencodeLocalProviderNamespace, isOpencodeCommand } from './providerModels.js';
+import { PORTS } from './ports.js';
+
+const LLAMA_SERVER_BASE_URL = `http://127.0.0.1:${PORTS.LLAMA_SERVER}/v1`;
/**
* Base OpenCode provider entries for the local OpenAI-compatible daemons.
@@ -39,7 +42,7 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {
llama: {
npm: '@ai-sdk/openai-compatible',
name: 'llama.cpp (local)',
- options: { baseURL: 'http://127.0.0.1:8080/v1' },
+ options: { baseURL: LLAMA_SERVER_BASE_URL },
},
orcarouter: {
npm: '@ai-sdk/openai-compatible',
diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.js
index df1cd53dde..bf5fac40d4 100644
--- a/server/lib/opencodeConfig.test.js
+++ b/server/lib/opencodeConfig.test.js
@@ -109,7 +109,7 @@ describe('buildOpencodeConfig', () => {
expect(cfg.provider.llama).toMatchObject({
npm: '@ai-sdk/openai-compatible',
name: 'llama.cpp (local)',
- options: { baseURL: 'http://127.0.0.1:8080/v1' },
+ options: { baseURL: 'http://127.0.0.1:5568/v1' },
});
expect(cfg.provider.llama.models).toEqual({
dflash: { name: 'dflash', tool_call: true },
diff --git a/server/lib/ports.js b/server/lib/ports.js
index 233af4ce4f..d98e4df94d 100644
--- a/server/lib/ports.js
+++ b/server/lib/ports.js
@@ -15,6 +15,7 @@ export const PORTS = {
AUTOFIXER: 5559, // Autofixer API
AUTOFIXER_UI: 5560, // Autofixer UI
POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)
+ LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding server
POSTGRES_NATIVE: 5432 // System PostgreSQL (PGMODE=native)
};
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index ff5bc096e5..a02bf8f596 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -13,6 +13,8 @@ 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';
const IS_WIN = process.platform === 'win32';
@@ -96,7 +98,7 @@ export async function getLlamaServerStatus() {
const installed = Boolean(binaryPath);
const host = currentConfig?.host || '127.0.0.1';
- const port = currentConfig?.port || 8080;
+ const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;
const endpoint = `http://${host}:${port}/v1`;
const isManagedActive = Boolean(managedChild && !managedChild.killed && managedChild.exitCode === null);
@@ -136,7 +138,7 @@ export async function startLlamaServer(options = {}) {
model,
draftModel,
specType = 'draft-dflash',
- port = 8080,
+ port = PORTS.LLAMA_SERVER,
host = '127.0.0.1',
ctxSize = 32768,
nGpuLayers = 99,
@@ -152,6 +154,12 @@ export async function startLlamaServer(options = {}) {
if (reachable) {
throw new ServerError(`Port ${port} is already in use by an active server at ${endpoint}`, { status: 409 });
}
+ if (await isPortInUse(port)) {
+ throw new ServerError(
+ `Port ${port} is already in use on ${host}. Choose a different port under Advanced options before starting llama-server.`,
+ { status: 409, code: 'LLAMA_SERVER_PORT_IN_USE' }
+ );
+ }
// Validate the weights before building the launch line, and hand `spawn` the
// EXPANDED paths: it performs no shell expansion, so a `~/models/…` argv entry
@@ -269,7 +277,7 @@ export async function startLlamaServer(options = {}) {
export async function stopLlamaServer() {
if (!managedChild || managedChild.killed || managedChild.exitCode !== null) {
const host = currentConfig?.host || '127.0.0.1';
- const port = currentConfig?.port || 8080;
+ const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;
const endpoint = `http://${host}:${port}/v1`;
const reachable = await probeEndpoint(endpoint);
if (reachable) {
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index e433d9483c..a38f61521f 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -9,6 +9,8 @@ import {
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 { PORTS } from '../lib/ports.js';
import { EventEmitter } from 'events';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
@@ -51,6 +53,9 @@ describe('llamaServerManager', () => {
beforeEach(() => {
_resetLlamaServerStateForTests();
vi.restoreAllMocks();
+ // 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);
});
afterEach(() => {
@@ -137,6 +142,37 @@ describe('llamaServerManager', () => {
expect(status.pid).toBe(12345);
});
+ 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));
+ });
+
+ 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();
+ });
+
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');
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
index 7bf2fa1e37..684d2143f1 100644
--- a/server/services/providerReadiness.test.js
+++ b/server/services/providerReadiness.test.js
@@ -8,7 +8,7 @@ const llamaProvider = (overrides = {}) => ({
type: 'tui',
command: 'opencode',
llamaBacked: true,
- endpoint: 'http://127.0.0.1:8080/v1',
+ endpoint: 'http://127.0.0.1:5568/v1',
models: ['dflash'],
defaultModel: 'dflash',
...overrides,
@@ -230,7 +230,7 @@ describe('getProviderReadinessMap', () => {
// Both llama providers point at the same daemon: one probe for the batch,
// not one per provider. A stock install ships several providers per
// endpoint, and this runs on a 20s poll.
- expect(probed).toEqual(['http://127.0.0.1:8080/v1']);
+ expect(probed).toEqual(['http://127.0.0.1:5568/v1']);
expect(map['opencode-llama'].ready).toBe(true);
});