Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(engine): die App folgt dem Motor auf den Port, den er wirklich hat

purple6f3f855ebd17
diff --git a/src/api/__tests__/builtin-engine-port-sync.test.ts b/src/api/__tests__/builtin-engine-port-sync.test.ts
new file mode 100644
index 00000000..5df26fd1
--- /dev/null
+++ b/src/api/__tests__/builtin-engine-port-sync.test.ts
@@ -0,0 +1,58 @@
+/**
+ * GH #118: the engine port stopped being a constant in 2.6.8, so the managed
+ * slot has to be told where the engine actually came up. This is the applier,
+ * the half that touches the provider store.
+ *
+ * Run: npx vitest run src/api/__tests__/builtin-engine-port-sync.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useProviderStore } from '../../stores/providerStore'
+import { syncBuiltinEnginePort } from '../builtin-ensure'
+
+const DEFAULTS = structuredClone(useProviderStore.getState().providers)
+const openai = () => useProviderStore.getState().providers.openai
+
+beforeEach(() => {
+ useProviderStore.setState({ providers: structuredClone(DEFAULTS) })
+})
+
+describe('syncBuiltinEnginePort', () => {
+ it('follows the engine when it had to take another port', () => {
+ expect(openai().baseUrl).toBe('http://127.0.0.1:8127/v1')
+ syncBuiltinEnginePort(8137)
+ expect(openai().baseUrl).toBe('http://127.0.0.1:8137/v1')
+ })
+
+ it('leaves the slot alone when the engine is on the port it already names', () => {
+ syncBuiltinEnginePort(8127)
+ expect(openai().baseUrl).toBe('http://127.0.0.1:8127/v1')
+ })
+
+ // Negative control: the openai slot is shared. A user running LM Studio or a
+ // remote OpenAI-compatible server must never have their endpoint moved by our
+ // engine's port choice.
+ it('never rewrites a slot that is not our managed engine', () => {
+ useProviderStore.getState().setProviderConfig('openai', {
+ name: 'LM Studio',
+ baseUrl: 'http://localhost:1234/v1',
+ managed: false,
+ })
+ syncBuiltinEnginePort(8137)
+ expect(openai().baseUrl).toBe('http://localhost:1234/v1')
+ })
+
+ it('never rewrites a disabled slot', () => {
+ useProviderStore.getState().setProviderConfig('openai', { enabled: false })
+ syncBuiltinEnginePort(8137)
+ expect(openai().baseUrl).toBe('http://127.0.0.1:8127/v1')
+ })
+
+ // Negative control: `bundled_engine_status` on a stopped engine, an older
+ // backend, or a failed call can all hand back something that is not a port.
+ it('ignores a non-port answer instead of corrupting the slot', () => {
+ for (const bad of [undefined, null, 'later', 0, -5, 99999]) {
+ syncBuiltinEnginePort(bad)
+ expect(openai().baseUrl).toBe('http://127.0.0.1:8127/v1')
+ }
+ })
+})
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
index d125e83e..718b4232 100644
--- a/src/api/builtin-ensure.ts
+++ b/src/api/builtin-ensure.ts
@@ -20,6 +20,7 @@ import { log } from '../lib/logger'
import { useProviderStore } from '../stores/providerStore'
import { useSettingsStore } from '../stores/settingsStore'
import { builtinSlotStatus, type SlotStatus } from '../lib/builtin-slot-status'
+import { baseUrlNeedingEnginePort } from '../lib/engine-port'
import { AGENT_CONTEXT_CAP } from '../lib/context-window'
import { ENGINE_DEFAULT_CTX, preservedSwapCtx } from '../lib/builtin-ctx'
import {
@@ -44,6 +45,14 @@ interface BundledList {
models?: Array<{ name: string; path: string; ctx_train?: number | null }>
}
+/** What `start_bundled_engine` / `swap_bundled_model` answer. `port` is the
+ * port the engine ACTUALLY came up on, which since GH #118 need not be the
+ * preferred one. */
+interface EngineStartResult {
+ status?: string
+ port?: number
+}
+
// Coalesce concurrent sends (chat + title generation) into ONE health-check /
// restart. start_bundled_engine blocks until /health is green, so awaiting the
// same promise is exactly "wait for the restart the other call kicked off".
@@ -102,6 +111,32 @@ export function isManagedBuiltinSlot(): boolean {
return !!cfg?.enabled && cfg.managed === true
}
+/**
+ * Point the managed slot at the port the engine really came up on.
+ *
+ * GH #118: the Rust side may now take the next free port when 8127 is held, so
+ * the one place that knows the answer is the start/status result. Without this
+ * the slot would keep asking 8127 and the user would get a refused connection
+ * to a healthy engine, which is the ticket's symptom with a different cause.
+ *
+ * Only the app's OWN managed slot on a loopback URL is ever touched, and only
+ * when the port really differs. Never throws: a slot that cannot be updated is
+ * not a reason to fail a start.
+ */
+export function syncBuiltinEnginePort(port: unknown): void {
+ try {
+ const store = useProviderStore.getState()
+ const cfg = store.providers.openai
+ if (!cfg?.enabled || cfg.managed !== true) return
+ const next = baseUrlNeedingEnginePort(cfg.baseUrl, port)
+ if (!next) return
+ log.info('[builtin-engine] the engine moved port, the slot follows', { from: cfg.baseUrl, to: next })
+ store.setProviderConfig('openai', { baseUrl: next })
+ } catch (err) {
+ log.warn('[builtin-engine] could not follow the engine port', { err })
+ }
+}
+
/**
* Is the engine about to answer with the wrong model.
*
@@ -231,7 +266,9 @@ async function loadBuiltinModel(modelName: string): Promise<void> {
// the same model and tuning, so an engine that is merely still warming up is
// never torn down and restarted for nothing.
const cmd = status?.running && !rightModel ? 'swap_bundled_model' : 'start_bundled_engine'
- await trackEngineSwap(backendCall(cmd, { modelPath: hit.path, tuning }))
+ syncBuiltinEnginePort(
+ (await trackEngineSwap(backendCall<EngineStartResult>(cmd, { modelPath: hit.path, tuning })))?.port,
+ )
// The engine is a different process with a different ctx now. Tell the
// header and the token counter to re-read it, so the number on screen is the
// one llama-server actually started with even when the raise above was
@@ -329,7 +366,11 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {
refusedCtxByPath.set(hit.path, want)
// Fall back to the previous tuning so the chat engine is not left dead.
try {
- await trackEngineSwap(backendCall('start_bundled_engine', { modelPath: hit.path, tuning }))
+ syncBuiltinEnginePort(
+ (await trackEngineSwap(
+ backendCall<EngineStartResult>('start_bundled_engine', { modelPath: hit.path, tuning }),
+ ))?.port,
+ )
announceContextReload()
} catch { /* the lazy self-heal on the next send takes over */ }
}
@@ -429,7 +470,8 @@ export async function diagnoseBuiltinEngine(
const pick = runnable.find((m) => m.name === bare) ?? runnable[0]
try {
const tuning = useSettingsStore.getState().settings.builtinEngine
- await backendCall('start_bundled_engine', { modelPath: pick.path, tuning })
+ const started = await backendCall<EngineStartResult>('start_bundled_engine', { modelPath: pick.path, tuning })
+ syncBuiltinEnginePort(started?.port)
return { ok: true, reason: '', repaired: true }
} catch (e) {
return {
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 1a108157..d7616a29 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -12,6 +12,7 @@
*/
import { backendCall } from './backend'
+import { syncBuiltinEnginePort } from './builtin-ensure'
import { trackEngineSwap } from './engine-swap-gate'
import { prefixModelName } from './providers'
import { useProviderStore } from '../stores/providerStore'
@@ -48,6 +49,17 @@ export interface BundledModel {
vision?: boolean
}
+/** What a start / swap answers. `port` is the port the engine ACTUALLY came
+ * up on: since GH #118 the Rust side may take the next free one when the
+ * preferred port is held, and every caller has to follow it there. */
+export interface EngineStartResult {
+ status: string
+ port: number
+ model_path: string
+ ctx?: number | null
+ retried?: boolean
+}
+
export interface EngineStatus {
running: boolean
healthy: boolean
@@ -97,10 +109,18 @@ export function isManagedBuiltinActive(): boolean {
* Registered with the swap gate so a send that arrives while the engine is
* still coming up waits for it instead of hitting the dead port (counter-check
* round 2, 2026-08-29). */
-export function startBundledEngine(modelPath: string, tuning?: BuiltinEngineTuning) {
- return trackEngineSwap(
- backendCall('start_bundled_engine', { modelPath, tuning: tuning ?? tuningFromSettings() }),
+export async function startBundledEngine(modelPath: string, tuning?: BuiltinEngineTuning) {
+ const res = await trackEngineSwap(
+ backendCall<EngineStartResult>('start_bundled_engine', {
+ modelPath,
+ tuning: tuning ?? tuningFromSettings(),
+ }),
)
+ // The engine may have landed on another port (GH #118). The slot that talks
+ // to it has to be told, or the very next request is refused by a port
+ // nobody is listening on, which is the ticket's own symptom.
+ syncBuiltinEnginePort(res?.port)
+ return res
}
/** Stop the managed engine child if one is running. */
@@ -109,8 +129,13 @@ export function stopBundledEngine() {
}
/** Engine health + which model is loaded on which port. */
-export function bundledEngineStatus() {
- return backendCall<EngineStatus>('bundled_engine_status')
+export async function bundledEngineStatus() {
+ const status = await backendCall<EngineStatus>('bundled_engine_status')
+ // A RUNNING engine is the only honest source for the port. A stopped one
+ // reports the preferred port as a placeholder, and following that would undo
+ // a fallback the next start is about to reuse.
+ if (status?.running) syncBuiltinEnginePort(status.port)
+ return status
}
/** Swap the loaded model (stop → start on the same port).
@@ -118,10 +143,15 @@ export function bundledEngineStatus() {
* This is the call the model picker makes on every activation, and the one the
* counter-check raced: two switches in a row, then a send into the restart gap.
* Registering it here is what lets the send path wait it out. */
-export function swapBundledModel(modelPath: string, tuning?: BuiltinEngineTuning) {
- return trackEngineSwap(
- backendCall('swap_bundled_model', { modelPath, tuning: tuning ?? tuningFromSettings() }),
+export async function swapBundledModel(modelPath: string, tuning?: BuiltinEngineTuning) {
+ const res = await trackEngineSwap(
+ backendCall<EngineStartResult>('swap_bundled_model', {
+ modelPath,
+ tuning: tuning ?? tuningFromSettings(),
+ }),
)
+ syncBuiltinEnginePort(res?.port)
+ return res
}
/** Start the built-in embeddings server (P5) with a specific embedding GGUF.
diff --git a/src/lib/__tests__/engine-port.test.ts b/src/lib/__tests__/engine-port.test.ts
new file mode 100644
index 00000000..30d6be56
--- /dev/null
+++ b/src/lib/__tests__/engine-port.test.ts
@@ -0,0 +1,87 @@
+/**
+ * GH #118 (nayffy, 2026-08-27, Windows 11, v2.6.6): "Built in engine test fails
+ * and console shows GET http://127.0.0.1:8127/v1/models net::ERR_CONNECTION_REFUSED".
+ *
+ * Since 2.6.8 the engine may take the next free port when 8127 is held, so the
+ * slot that talks to it has to follow. These pin the two halves that could turn
+ * that repair back into the bug: a slot that does not follow, and a slot that
+ * follows something it has no business rewriting.
+ *
+ * Run: npx vitest run src/lib/__tests__/engine-port.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ baseUrlNeedingEnginePort,
+ enginePortFromBaseUrl,
+ withEnginePort,
+} from '../engine-port'
+
+describe('enginePortFromBaseUrl', () => {
+ it('reads the port off the shipped built-in slot', () => {
+ expect(enginePortFromBaseUrl('http://127.0.0.1:8127/v1')).toBe(8127)
+ expect(enginePortFromBaseUrl('http://localhost:1234/v1')).toBe(1234)
+ expect(enginePortFromBaseUrl('http://[::1]:8127/v1')).toBe(8127)
+ })
+
+ it('answers null when there is no port to read', () => {
+ expect(enginePortFromBaseUrl('http://127.0.0.1/v1')).toBeNull()
+ expect(enginePortFromBaseUrl('https://api.anthropic.com')).toBeNull()
+ expect(enginePortFromBaseUrl('')).toBeNull()
+ expect(enginePortFromBaseUrl('not a url')).toBeNull()
+ })
+})
+
+describe('withEnginePort', () => {
+ it('swaps the port and keeps scheme, host and path', () => {
+ expect(withEnginePort('http://127.0.0.1:8127/v1', 8137)).toBe('http://127.0.0.1:8137/v1')
+ expect(withEnginePort('http://[::1]:8127/v1', 8137)).toBe('http://[::1]:8137/v1')
+ })
+
+ it('adds a port to a URL that had none', () => {
+ expect(withEnginePort('http://127.0.0.1/v1', 8137)).toBe('http://127.0.0.1:8137/v1')
+ })
+
+ it('returns junk unchanged instead of mangling it', () => {
+ expect(withEnginePort('not a url', 8137)).toBe('not a url')
+ expect(withEnginePort('http://127.0.0.1:8127/v1', 0)).toBe('http://127.0.0.1:8127/v1')
+ expect(withEnginePort('http://127.0.0.1:8127/v1', 70000)).toBe('http://127.0.0.1:8127/v1')
+ })
+})
+
+describe('baseUrlNeedingEnginePort: the slot follows the engine, and only the engine', () => {
+ it('rewrites the built-in slot when the engine moved off 8127', () => {
+ // The whole ticket in one line: healthy engine, wrong port in the slot.
+ expect(baseUrlNeedingEnginePort('http://127.0.0.1:8127/v1', 8137)).toBe(
+ 'http://127.0.0.1:8137/v1',
+ )
+ })
+
+ it('writes nothing when the slot already points at the engine', () => {
+ expect(baseUrlNeedingEnginePort('http://127.0.0.1:8127/v1', 8127)).toBeNull()
+ })
+
+ // Negative control, and the reason this function exists rather than a plain
+ // string replace: the same openai slot can hold a remote OpenAI-compatible
+ // server. Repointing that at a loopback port would be a far worse bug than
+ // the one being fixed.
+ it('never touches a host that is not this machine', () => {
+ expect(baseUrlNeedingEnginePort('https://api.together.xyz/v1', 8137)).toBeNull()
+ expect(baseUrlNeedingEnginePort('http://192.168.0.54:1234/v1', 8137)).toBeNull()
+ expect(baseUrlNeedingEnginePort('http://box.local:8127/v1', 8137)).toBeNull()
+ })
+
+ it('accepts localhost and the IPv6 loopback as this machine', () => {
+ expect(baseUrlNeedingEnginePort('http://localhost:8127/v1', 8137)).toBe(
+ 'http://localhost:8137/v1',
+ )
+ expect(baseUrlNeedingEnginePort('http://[::1]:8127/v1', 8137)).toBe('http://[::1]:8137/v1')
+ })
+
+ // Negative control: a status call on a stopped engine can carry all sorts of
+ // non-answers, and none of them may move the slot.
+ it('ignores anything that is not a port number', () => {
+ for (const bad of [undefined, null, '8137', 0, -1, 70000, 1.5, NaN]) {
+ expect(baseUrlNeedingEnginePort('http://127.0.0.1:8127/v1', bad)).toBeNull()
+ }
+ })
+})
diff --git a/src/lib/engine-port.ts b/src/lib/engine-port.ts
new file mode 100644
index 00000000..4db05f77
--- /dev/null
+++ b/src/lib/engine-port.ts
@@ -0,0 +1,73 @@
+/**
+ * The port the managed built-in engine actually runs on, and the base URL the
+ * `openai` slot has to carry so requests reach it.
+ *
+ * GH #118 (nayffy, 2026-08-27, Windows 11): the engine port was a constant in
+ * two places, `http://127.0.0.1:8127/v1` in the provider slot and 8127 in Rust,
+ * and nothing could move. Since the Rust side may now take the next free port
+ * when 8127 is held (a leftover llama-server, or one of the port ranges Windows
+ * reserves for Hyper-V and WSL), the slot has to follow it. A slot pointing at
+ * the old port would produce exactly the symptom the ticket describes, a
+ * refused connection to a server that is up and healthy one port away.
+ *
+ * Pure on purpose, and deliberately narrow: only a LOOPBACK base URL is ever
+ * rewritten. The same slot can hold LM Studio or a remote OpenAI-compatible
+ * server the user configured, and moving somebody else's port would be a much
+ * worse bug than the one this fixes.
+ */
+
+/** Hosts that mean "this machine". Anything else is not ours to rewrite. */
+const LOOPBACK = /^(?:127\.0\.0\.1|localhost|\[::1\])$/i
+
+/** `http://host:port/rest` split into scheme, host[:port] and the rest. */
+const URL_SHAPE = /^(https?:\/\/)([^/?#]+)([/?#].*)?$/i
+
+function isPort(value: unknown): value is number {
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 65535
+}
+
+/** Split `host:port` into its two halves. The port half is null when absent. */
+function splitHostPort(hostPort: string): { host: string; port: number | null } {
+ const idx = hostPort.lastIndexOf(':')
+ if (idx < 0) return { host: hostPort, port: null }
+ const tail = hostPort.slice(idx + 1)
+ // `[::1]` carries colons of its own, so a tail that is not all digits is
+ // part of the host, not a port.
+ if (!/^\d+$/.test(tail)) return { host: hostPort, port: null }
+ const port = Number(tail)
+ return { host: hostPort.slice(0, idx), port: isPort(port) ? port : null }
+}
+
+/** The port a base URL points at, or null when it names none. */
+export function enginePortFromBaseUrl(baseUrl: string): number | null {
+ const m = String(baseUrl ?? '').match(URL_SHAPE)
+ return m ? splitHostPort(m[2]).port : null
+}
+
+/** The same base URL with `port` substituted. Unparseable input is returned
+ * unchanged rather than mangled. */
+export function withEnginePort(baseUrl: string, port: number): string {
+ const m = String(baseUrl ?? '').match(URL_SHAPE)
+ if (!m || !isPort(port)) return baseUrl
+ const { host } = splitHostPort(m[2])
+ return `${m[1]}${host}:${port}${m[3] ?? ''}`
+}
+
+/**
+ * The base URL the managed slot must be written to so it reaches the engine on
+ * `port`, or null when there is nothing to write.
+ *
+ * Null covers every case where a rewrite would be wrong or pointless: a port
+ * that is not a port, a slot that already names it, and a host that is not this
+ * machine.
+ */
+export function baseUrlNeedingEnginePort(baseUrl: string, port: unknown): string | null {
+ if (!isPort(port)) return null
+ const m = String(baseUrl ?? '').match(URL_SHAPE)
+ if (!m) return null
+ const { host } = splitHostPort(m[2])
+ if (!LOOPBACK.test(host)) return null
+ if (enginePortFromBaseUrl(baseUrl) === port) return null
+ const next = withEnginePort(baseUrl, port)
+ return next === baseUrl ? null : next
+}