Commit 0ce7f213b for llama.cpp

commit 0ce7f213b0749fa4dee4e87d8ae7bf63e621c1ad
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date:   Tue Nov 24 17:38:56 2026 +0100

    ui: run Llama Chat apart from llama-server, named in config.json or npx --server (#32945)

    * ui: run Llama Chat apart from llama-server, named in config.json

    The app reads config.json, a file next to index.html, once before it
    starts. A "server" URL in it sends every API request there instead of
    to the app's own origin: /props, /v1, /models, /tools, the CORS proxy
    and the realtime socket. Without one nothing changes.

    npx llama-chat --server <url> answers that file itself, and
    npx llama-chat build --server <url> writes it. The service worker
    leaves it out of its cache, so a host can change it without a new
    build.

    Assisted-by: Claude (Fable 5.2)

    * ui: release Llama Chat 0.2.0 with --server

    Bumps @ggml-org/llama-chat and llama-chat to 0.2.0 so the publish
    workflow ships the --server flag to npx once this reaches master.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: expect the Llama Chat name in the PWA manifest e2e test

    #32890 named the PWA Llama Chat by default, but the E2E test still
    expected llama-ui, so the UI workflow failed on master and on every UI PR.

    Assisted-by: Claude (Opus 5.5 Medium)

diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md
index 6ba2e8957..c7da94dd8 100644
--- a/ui/apps/chat/README.md
+++ b/ui/apps/chat/README.md
@@ -19,13 +19,14 @@ It works with a llama-server in either mode: **MODEL** (one model) or **ROUTER**
 Llama Chat is published to npm as [`@ggml-org/llama-chat`](https://www.npmjs.com/package/@ggml-org/llama-chat), with [`llama-chat`](https://www.npmjs.com/package/llama-chat) as its short name. It serves the prebuilt app as static files on localhost, or writes them to a folder for any static file server (see [Self-hosting](#self-hosting)); it brings no server and no models of its own. It needs Node.js 20 or later.

 ```bash
-npx @ggml-org/llama-chat                 # serve it on http://127.0.0.1:3000 and open the browser
-npx llama-chat --host 0.0.0.0 --no-open  # the same, by its short name, reachable from other devices
-npx llama-chat build                     # write the static app to ./llama-chat instead
+npx @ggml-org/llama-chat --server http://localhost:8080  # serve it on http://127.0.0.1:3000 for that llama-server
+npx llama-chat --host 0.0.0.0 --no-open                  # by its short name, reachable from other devices
+npx llama-chat build                                     # write the static app to ./llama-chat instead
 ```

 | Flag                              | Default     | What it does                                                                                |
 | --------------------------------- | ----------- | ------------------------------------------------------------------------------------------- |
+| `--server <url>`                  |             | The llama-server the app talks to, e.g. `http://localhost:8080`; also for `build`           |
 | `--port <n>`                      | `3000`      | Fixed, so the origin, and the chats the browser stores under it, stay the same between runs |
 | `--host <addr>`                   | `127.0.0.1` | `0.0.0.0` to open it to the LAN                                                             |
 | `--open` / `--no-open`            | open        | Opens the default browser once it listens                                                   |
@@ -33,13 +34,19 @@ npx llama-chat build                     # write the static app to ./llama-chat

 The bare command is the documented form; `start` is accepted as an alias for it. `build` takes `--out <dir>` (default `./llama-chat`) and `--force`, which lets it write into a folder that is not empty.

-How it works: the CLI only serves the files of `dist`, with llama-server's headers for the UI (`index.html` cross-origin isolated, the PWA files revalidated, hashed assets cached for good), and forwards nothing. The browser talks to each llama-server you add in the app by URL directly, so llama-server's own rules apply: start it with `--cors-origins http://127.0.0.1:3000` (the address you open) when it restricts origins, as it does with tools or MCP enabled, and with `--api-key` when it is reachable from the LAN. An `http://` page like this one can reach a plain `http://` llama-server on the LAN, which an `https://` page cannot.
+How it works: the CLI only serves the files of `dist`, with llama-server's headers for the UI (`index.html` cross-origin isolated, the PWA files revalidated, hashed assets cached for good), and forwards nothing. The browser talks to the llama-server named with `--server` directly, so llama-server's own rules apply: start it with `--cors-origins http://127.0.0.1:3000` (the address you open) when it restricts origins, as it does with tools or MCP enabled, and with `--api-key` when it is reachable from the LAN. An `http://` page like this one can reach a plain `http://` llama-server on the LAN, which an `https://` page cannot.

 ## Self-hosting

 The app is static and uses relative paths and a hash router, so any static host can serve it at any path. `npx @ggml-org/llama-chat build --out <dir>` writes the files (as does `npm run build` here, to `dist`); serve them with any static file server, for example `npx http-server llama-chat -p 3000`. Send the headers listed above with `index.html` and the PWA files, so the app behaves as it does under llama-server (see [Cross-origin isolation](#cross-origin-isolation)).

-The app reaches the llama-server on its own origin, if there is one (llama-server serves it with `--path`, or your reverse proxy puts the API next to the files), and any other llama-server you add by URL, which needs `--cors-origins` for the app's address.
+The app reaches the llama-server on its own origin by default (llama-server serves it with `--path`, or your reverse proxy puts the API next to the files). To host it apart from llama-server, name the server in `config.json`, the file next to `index.html`:
+
+```json
+{ "server": "http://localhost:8080" }
+```
+
+`npx llama-chat build --server <url>` writes that file, and `npx llama-chat --server <url>` answers it without one. The app reads it on every start, past its caches, so a host can change it without a new build. That llama-server needs `--cors-origins` for the app's address when it restricts origins.

 ## Features

diff --git a/ui/apps/chat/alias/package.json b/ui/apps/chat/alias/package.json
index 8de00aa8c..086623973 100644
--- a/ui/apps/chat/alias/package.json
+++ b/ui/apps/chat/alias/package.json
@@ -1,6 +1,6 @@
 {
 	"name": "llama-chat",
-	"version": "0.1.0",
+	"version": "0.2.0",
 	"description": "npx llama-chat: runs Llama Chat, the chat app for llama.cpp. Same as npx @ggml-org/llama-chat.",
 	"keywords": [
 		"llama.cpp",
@@ -28,6 +28,6 @@
 		"node": ">=20"
 	},
 	"dependencies": {
-		"@ggml-org/llama-chat": "0.1.0"
+		"@ggml-org/llama-chat": "0.2.0"
 	}
 }
diff --git a/ui/apps/chat/cli/server.js b/ui/apps/chat/cli/server.js
index 8ef0f557c..95aa60373 100644
--- a/ui/apps/chat/cli/server.js
+++ b/ui/apps/chat/cli/server.js
@@ -11,7 +11,7 @@

 import { spawn } from 'node:child_process';
 import { createReadStream, readFileSync } from 'node:fs';
-import { cp, readdir, stat } from 'node:fs/promises';
+import { cp, readdir, stat, writeFile } from 'node:fs/promises';
 import http from 'node:http';
 import { extname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
 import { fileURLToPath } from 'node:url';
@@ -36,8 +36,11 @@ const NO_CACHE = new Set([
 	'/sw.js',
 	'/manifest.webmanifest',
 	'/_app/version.json',
-	'/build.json'
+	'/build.json',
+	'/config.json'
 ]);
+// the file next to index.html that tells the app where llama-server is
+const CONFIG_PATH = '/config.json';
 const CACHE_IMMUTABLE = 'public, max-age=31536000, immutable';
 const CACHE_REVALIDATE = 'no-cache';
 /** @type {Record<string, string>} */
@@ -68,10 +71,13 @@ export const USAGE = `Usage: llama-chat [options]
        llama-chat build [--out <dir>] [--force]

 Serves Llama Chat on localhost as static files, or, with build, writes them to
-a folder for any HTTP server. The browser talks to llama-server directly: start
-it with --cors-origins set to this page's address when it restricts origins.
+a folder for any HTTP server. The browser talks to llama-server directly: name
+it with --server, and start it with --cors-origins set to this page's address
+when it restricts origins.

 Options:
+  --server <url>   the llama-server the app talks to, e.g. http://localhost:8080
+                   (also for build; default: the address the app is served on)
   --port <n>       port to listen on (default: ${DEFAULTS.port})
   --host <addr>    address to listen on, 0.0.0.0 for the LAN (default: ${DEFAULTS.host})
   --open           open the browser once it listens (default)
@@ -84,9 +90,9 @@ Build options:
   --force          write into a folder that is not empty

 Examples:
-  npx @ggml-org/llama-chat
+  npx @ggml-org/llama-chat --server http://localhost:8080
   npx @ggml-org/llama-chat --host 0.0.0.0 --port 3000 --no-open
-  npx @ggml-org/llama-chat build --out ./public`;
+  npx @ggml-org/llama-chat build --out ./public --server https://llm.example.com`;

 /** The version in this package's package.json. */
 export function packageVersion() {
@@ -97,7 +103,7 @@ export function packageVersion() {
  * Reads the command line. No verb serves the app, `start` means the same, and `build` writes it
  * to a folder.
  * @param {string[]} argv the arguments after the command
- * @returns {{ command: 'build' | 'serve', force: boolean, help: boolean, host: string, open: boolean, out: string, port: number, version: boolean }}
+ * @returns {{ command: 'build' | 'serve', force: boolean, help: boolean, host: string, open: boolean, out: string, port: number, server: string, version: boolean }}
  */
 export function parseCliArgs(argv) {
 	const { positionals, values } = parseArgs({
@@ -111,6 +117,7 @@ export function parseCliArgs(argv) {
 			open: { type: 'boolean' },
 			out: { type: 'string' },
 			port: { type: 'string' },
+			server: { type: 'string' },
 			version: { short: 'v', type: 'boolean' }
 		},
 		strict: true
@@ -138,6 +145,24 @@ export function parseCliArgs(argv) {
 		throw new Error(`invalid --port: ${values.port}`);
 	}

+	let server = '';
+
+	if (values.server !== undefined) {
+		let parsed;
+
+		try {
+			parsed = new URL(values.server);
+		} catch {
+			parsed = null;
+		}
+
+		if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
+			throw new Error(`invalid --server, expected an http(s) URL: ${values.server}`);
+		}
+
+		server = `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
+	}
+
 	return {
 		command,
 		force: values.force ?? false,
@@ -146,6 +171,7 @@ export function parseCliArgs(argv) {
 		open: values.open ?? true,
 		out: values.out ?? DEFAULTS.out,
 		port,
+		server,
 		version: values.version ?? false
 	};
 }
@@ -224,10 +250,19 @@ function sendError(res, status, message) {
 }

 /**
- * The HTTP server: the files of `dist`, read-only.
- * @param {{ distDir?: string }} [options]
+ * The app's config.json for a llama-server at `server`.
+ * @param {string} server
  */
-export function createChatServer({ distDir = DIST_DIR } = {}) {
+function configJson(server) {
+	return `${JSON.stringify({ server })}\n`;
+}
+
+/**
+ * The HTTP server: the files of `dist`, read-only. With `server`, it answers config.json
+ * itself, so the app talks to that llama-server instead of this address.
+ * @param {{ distDir?: string, server?: string }} [options]
+ */
+export function createChatServer({ distDir = DIST_DIR, server = '' } = {}) {
 	const root = normalize(distDir);

 	return http.createServer(async (req, res) => {
@@ -240,6 +275,19 @@ export function createChatServer({ distDir = DIST_DIR } = {}) {
 			return;
 		}

+		if (server && pathname === CONFIG_PATH) {
+			const body = configJson(server);
+
+			res.writeHead(200, {
+				'Cache-Control': CACHE_REVALIDATE,
+				'Content-Length': Buffer.byteLength(body),
+				'Content-Type': MIME_TYPES['.json']
+			});
+			res.end(req.method === 'HEAD' ? undefined : body);
+
+			return;
+		}
+
 		const file = resolveStatic(root, pathname);
 		const stats = file ? await stat(file).catch(() => null) : null;

@@ -256,10 +304,11 @@ export function createChatServer({ distDir = DIST_DIR } = {}) {
 /**
  * Writes the app to a folder: the files of `dist` without source maps, ready for any static
  * file server. Refuses a folder that is not empty unless `force` is set, and a folder in `dist`.
- * @param {{ distDir?: string, force?: boolean, out: string }} options
+ * With `server`, its config.json names that llama-server.
+ * @param {{ distDir?: string, force?: boolean, out: string, server?: string }} options
  * @returns {Promise<string>} the absolute path of the folder
  */
-export async function buildStatic({ distDir = DIST_DIR, force = false, out }) {
+export async function buildStatic({ distDir = DIST_DIR, force = false, out, server = '' }) {
 	const source = resolve(distDir);
 	const target = resolve(out);
 	const inside = relative(source, target);
@@ -276,6 +325,8 @@ export async function buildStatic({ distDir = DIST_DIR, force = false, out }) {

 	await cp(source, target, { filter: (file) => !file.endsWith('.map'), recursive: true });

+	if (server) await writeFile(join(target, CONFIG_PATH), configJson(server));
+
 	return target;
 }

@@ -339,7 +390,11 @@ export async function main(argv) {

 	if (options.command === 'build') {
 		try {
-			const target = await buildStatic({ force: options.force, out: options.out });
+			const target = await buildStatic({
+				force: options.force,
+				out: options.out,
+				server: options.server
+			});
 			const shown = relative(process.cwd(), target) || '.';

 			console.log(`Llama Chat ${packageVersion()} written to ${target}`);
@@ -352,7 +407,7 @@ export async function main(argv) {
 		return;
 	}

-	const server = createChatServer();
+	const server = createChatServer({ server: options.server });

 	return new Promise((resolve) => {
 		server.on('error', (error) => {
@@ -373,6 +428,9 @@ export async function main(argv) {
 			const url = `http://${shown.includes(':') ? `[${shown}]` : shown}:${address.port}/`;

 			console.log(`Llama Chat ${packageVersion()} on ${url}`);
+
+			if (options.server) console.log(`Talking to llama-server on ${options.server}`);
+
 			console.log(
 				`If llama-server restricts origins (tools or MCP on), start it with --cors-origins ${url.slice(0, -1)}`
 			);
diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json
index ef7891ba3..5009e3ac3 100644
--- a/ui/apps/chat/package-lock.json
+++ b/ui/apps/chat/package-lock.json
@@ -1,12 +1,12 @@
 {
 	"name": "@ggml-org/llama-chat",
-	"version": "0.1.0",
+	"version": "0.2.0",
 	"lockfileVersion": 3,
 	"requires": true,
 	"packages": {
 		"": {
 			"name": "@ggml-org/llama-chat",
-			"version": "0.1.0",
+			"version": "0.2.0",
 			"license": "MIT",
 			"bin": {
 				"llama-chat": "bin/cli.js"
diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json
index 76146f41e..5273e2497 100644
--- a/ui/apps/chat/package.json
+++ b/ui/apps/chat/package.json
@@ -1,6 +1,6 @@
 {
 	"name": "@ggml-org/llama-chat",
-	"version": "0.1.0",
+	"version": "0.2.0",
 	"description": "Llama Chat, the chat app for llama.cpp. Run it with npx @ggml-org/llama-chat against any llama-server.",
 	"keywords": [
 		"llama.cpp",
diff --git a/ui/apps/chat/src/hooks.client.ts b/ui/apps/chat/src/hooks.client.ts
new file mode 100644
index 000000000..656ce58d2
--- /dev/null
+++ b/ui/apps/chat/src/hooks.client.ts
@@ -0,0 +1,4 @@
+import { loadServerConfig } from '#lib/utils/server-config.ts';
+
+/** Runs once before the app starts: the server's address has to be known before the first request. */
+export const init = () => loadServerConfig();
diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte
index a527bcd23..620c2bff8 100644
--- a/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte
+++ b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte
@@ -6,7 +6,7 @@
 	import { HEADERS, ICON_CLASS_DEFAULT, ROUTES, SETTINGS_KEYS } from '#lib/constants/index.ts';
 	import { KeyboardKey } from '#lib/enums/index.ts';
 	import { serverStore, settingsStore } from '#lib/stores/index.ts';
-	import { withBase } from '#lib/utils/base-path.ts';
+	import { serverUrl } from '#lib/utils/server-config.ts';
 	import { goto } from '$app/navigation';
 	import { fade, fly, scale } from 'svelte/transition';

@@ -67,7 +67,7 @@
 			settingsStore.updateConfig(SETTINGS_KEYS.API_KEY, apiKeyInput.trim());

 			// Test the API key by making a real request to the server
-			const response = await fetch(withBase('/props'), {
+			const response = await fetch(serverUrl('/props'), {
 				headers: {
 					'Content-Type': 'application/json',
 					[HEADERS.AUTHORIZATION]: `${HEADERS.BEARER}${apiKeyInput.trim()}`
diff --git a/ui/apps/chat/src/lib/services/models.service.ts b/ui/apps/chat/src/lib/services/models.service.ts
index 87abe1a94..f3396d53c 100644
--- a/ui/apps/chat/src/lib/services/models.service.ts
+++ b/ui/apps/chat/src/lib/services/models.service.ts
@@ -10,7 +10,6 @@ import { API_MODELS, MODEL_ID, type ModelSidecar } from '#lib/constants/index.ts
 import { ServerModelStatus } from '#lib/enums/index.ts';
 import type { ModelSidecarBadge, ParsedModelId } from '#lib/types/models.js';
 import { getAuthHeaders } from '#lib/utils/api-headers.ts';
-import { withBase } from '#lib/utils/base-path.ts';
 import {
 	apiDelete,
 	apiFetch,
@@ -22,6 +21,7 @@ import {
 	sidecarFromFileToken,
 	splitSseRecords
 } from '#lib/utils/index.ts';
+import { serverUrl } from '#lib/utils/server-config.ts';

 export class ModelsService {
 	private static readonly SSE_RECONNECT_MS = 1000;
@@ -360,7 +360,7 @@ export class ModelsService {

 		while (!signal.aborted) {
 			try {
-				const response = await fetch(withBase(API_MODELS.SSE), {
+				const response = await fetch(serverUrl(API_MODELS.SSE), {
 					headers: getAuthHeaders(),
 					signal
 				});
diff --git a/ui/apps/chat/src/lib/services/tools.service.ts b/ui/apps/chat/src/lib/services/tools.service.ts
index dd401f79d..2f0dd8fa8 100644
--- a/ui/apps/chat/src/lib/services/tools.service.ts
+++ b/ui/apps/chat/src/lib/services/tools.service.ts
@@ -9,8 +9,8 @@ import { API_TOOLS, HEADERS, HOME_TILDE, SEARCH } from '#lib/constants/index.ts'
 import { BuiltInTool, GlobSearchType, ToolResponseField } from '#lib/enums/index.ts';
 import type { GlobEntry, ServerToolInfo, ToolExecutionResult } from '#lib/types/index.ts';
 import { getJsonHeaders } from '#lib/utils/api-headers.ts';
-import { withBase } from '#lib/utils/base-path.ts';
 import { apiFetch, buildCaseInsensitiveGlob, joinPath, lastPathSegment } from '#lib/utils/index.ts';
+import { serverUrl } from '#lib/utils/server-config.ts';
 import { parseSseJsonStream, type SseJsonEvent } from '#lib/utils/sse.ts';

 export class ToolsService {
@@ -137,7 +137,7 @@ export class ToolsService {

 		if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;

-		const response = await fetch(withBase(API_TOOLS.EXECUTE), {
+		const response = await fetch(serverUrl(API_TOOLS.EXECUTE), {
 			body: JSON.stringify({ params, stream: true, tool: toolName }),
 			headers,
 			method: 'POST',
diff --git a/ui/apps/chat/src/lib/services/voice.service.ts b/ui/apps/chat/src/lib/services/voice.service.ts
index c794b1b64..2b55288b1 100644
--- a/ui/apps/chat/src/lib/services/voice.service.ts
+++ b/ui/apps/chat/src/lib/services/voice.service.ts
@@ -15,7 +15,7 @@ import {
 } from '#lib/constants/index.ts';
 import type { SettingsConfigType } from '#lib/types/index.ts';
 import { getAuthHeaders } from '#lib/utils/api-headers.ts';
-import { withBase } from '#lib/utils/base-path.ts';
+import { serverUrl } from '#lib/utils/server-config.ts';

 /** What a feature asks of the voice wiring, besides the settings. */
 export interface VoiceSessionRequest {
@@ -97,7 +97,7 @@ export class VoiceService {
 		return {
 			context: {
 				getHeaders: () => getAuthHeaders(),
-				resolveUrl: (path) => withBase(path.replace(VOICE_RELATIVE_PATH_PATTERN, ''))
+				resolveUrl: (path) => serverUrl(path.replace(VOICE_RELATIVE_PATH_PATTERN, ''))
 			},
 			realtime: !hasAuth
 		};
diff --git a/ui/apps/chat/src/lib/utils/api-fetch.ts b/ui/apps/chat/src/lib/utils/api-fetch.ts
index 85534558a..e4950669c 100644
--- a/ui/apps/chat/src/lib/utils/api-fetch.ts
+++ b/ui/apps/chat/src/lib/utils/api-fetch.ts
@@ -1,5 +1,5 @@
 import { getAuthHeaders, getJsonHeaders } from './api-headers';
-import { withBase } from './base-path';
+import { getServerBase, serverUrl } from './server-config';
 import {
 	API_ABSOLUTE_URL_PROTOCOLS,
 	ERROR_MESSAGES,
@@ -66,8 +66,8 @@ export async function apiFetch<T>(path: string, options: ApiFetchOptions = {}):
 	const { authOnly = false, headers: customHeaders, ...fetchOptions } = options;
 	const baseHeaders = authOnly ? getAuthHeaders() : getJsonHeaders();
 	const headers = { ...baseHeaders, ...customHeaders };
-	// absolute URLs with an allowed protocol pass through untouched; relative paths get the base prefix
-	const url = API_ABSOLUTE_URL_PROTOCOLS.some((p) => path.startsWith(p)) ? path : withBase(path);
+	// absolute URLs with an allowed protocol pass through untouched; relative paths go to the server
+	const url = API_ABSOLUTE_URL_PROTOCOLS.some((p) => path.startsWith(p)) ? path : serverUrl(path);

 	let response;

@@ -110,7 +110,8 @@ export async function apiFetchWithParams<T>(
 	params: Record<string, string>,
 	options: ApiFetchOptions = {}
 ): Promise<T> {
-	const url = new URL(basePath, window.location.href);
+	// on the configured server when there is one, else relative to the page as before
+	const url = new URL(getServerBase() ? serverUrl(basePath) : basePath, window.location.href);

 	for (const [key, value] of Object.entries(params)) {
 		if (value !== undefined && value !== null) {
diff --git a/ui/apps/chat/src/lib/utils/api-key-validation.ts b/ui/apps/chat/src/lib/utils/api-key-validation.ts
index 2783b3241..f86e64c18 100644
--- a/ui/apps/chat/src/lib/utils/api-key-validation.ts
+++ b/ui/apps/chat/src/lib/utils/api-key-validation.ts
@@ -1,4 +1,4 @@
-import { withBase } from './base-path';
+import { serverUrl } from './server-config';
 import { error } from '@sveltejs/kit';
 import { HEADERS } from '#lib/constants/index.ts';
 import { MimeTypeApplication } from '#lib/enums/index.ts';
@@ -28,7 +28,7 @@ export async function validateApiKey(fetch: typeof globalThis.fetch): Promise<vo
 			headers[HEADERS.AUTHORIZATION] = `${HEADERS.BEARER}${apiKey}`;
 		}

-		const response = await fetch(withBase('/props'), { headers });
+		const response = await fetch(serverUrl('/props'), { headers });

 		if (!response.ok) {
 			if (response.status === 401 || response.status === 403) {
diff --git a/ui/apps/chat/src/lib/utils/cors-proxy.ts b/ui/apps/chat/src/lib/utils/cors-proxy.ts
index c5875482b..fe9af9046 100644
--- a/ui/apps/chat/src/lib/utils/cors-proxy.ts
+++ b/ui/apps/chat/src/lib/utils/cors-proxy.ts
@@ -2,7 +2,7 @@
  * CORS Proxy utility for routing requests through llama-server's CORS proxy.
  */

-import { withBase } from './base-path';
+import { serverUrl } from './server-config';
 import { CORS_PROXY, CORS_PROXY_ENDPOINT } from '#lib/constants/index.ts';
 import { UrlProtocol } from '#lib/enums/index.ts';

@@ -12,7 +12,7 @@ import { UrlProtocol } from '#lib/enums/index.ts';
  * @returns URL pointing to the CORS proxy with target encoded
  */
 export function buildProxiedUrl(targetUrl: string): URL {
-	const proxyPath = withBase(CORS_PROXY_ENDPOINT);
+	const proxyPath = serverUrl(CORS_PROXY_ENDPOINT);
 	const proxyUrl = new URL(proxyPath, window.location.origin);

 	proxyUrl.searchParams.set(CORS_PROXY.URL_PARAM, targetUrl);
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index 4476ac63f..2dae4a575 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -11,6 +11,7 @@
 export { getAuthHeaders, getJsonHeaders, sanitizeHeaders } from './api-headers';
 export { ApiError, apiDelete, apiFetch, apiFetchWithParams, apiPost } from './api-fetch';
 export { withBase } from './base-path';
+export { getServerBase, loadServerConfig, serverUrl, setServerBase } from './server-config';
 export { validateApiKey } from './api-key-validation';

 // Attachment utilities
diff --git a/ui/apps/chat/src/lib/utils/server-config.ts b/ui/apps/chat/src/lib/utils/server-config.ts
new file mode 100644
index 000000000..24e5b1e99
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/server-config.ts
@@ -0,0 +1,63 @@
+import { withBase } from './base-path';
+
+/**
+ * Where the llama-server is. By default it serves the app, so its API is on the app's own
+ * origin. An app hosted apart from it (a static host, `npx llama-chat --server`) names it in
+ * `config.json`, a file next to index.html: `{ "server": "http://localhost:9931" }`.
+ */
+
+/** The file next to index.html that holds the settings a host gives the app. */
+export const SERVER_CONFIG_FILE = '/config.json';
+
+let serverBase = '';
+
+/**
+ * The server's address as a prefix for an API path: its origin and any path it is served
+ * under, without a trailing slash. Empty for anything but an http(s) URL.
+ */
+export function normalizeServerBase(value: unknown): string {
+	if (typeof value !== 'string' || !value.trim()) return '';
+
+	try {
+		const url = new URL(value.trim());
+
+		if (url.protocol !== 'http:' && url.protocol !== 'https:') return '';
+
+		return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
+	} catch {
+		return '';
+	}
+}
+
+/** Names the server, as `config.json` does. Empty puts it back on the app's own origin. */
+export function setServerBase(value: unknown): void {
+	serverBase = normalizeServerBase(value);
+}
+
+/** The server named by `config.json`, or an empty string when it is on the app's own origin. */
+export function getServerBase(): string {
+	return serverBase;
+}
+
+/**
+ * Reads `config.json` once, before the app starts. A missing or broken file leaves the server
+ * on the app's own origin, as does a host that is offline.
+ */
+export async function loadServerConfig(): Promise<void> {
+	try {
+		const response = await fetch(withBase(SERVER_CONFIG_FILE), { cache: 'no-store' });
+
+		if (!response.ok) return;
+
+		const config: unknown = await response.json();
+
+		if (config && typeof config === 'object' && 'server' in config) setServerBase(config.server);
+	} catch {
+		// no config.json: the server is the one that serves the app
+	}
+}
+
+/** The URL of a server path (`/props`, `./props`): on the configured server, else on the app's origin. */
+export function serverUrl(path: string): string {
+	return serverBase ? `${serverBase}/${path.replace(/^\.?\//, '')}` : withBase(path);
+}
diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte
index 8fcef551b..b66a3ecfc 100644
--- a/ui/apps/chat/src/routes/+layout.svelte
+++ b/ui/apps/chat/src/routes/+layout.svelte
@@ -32,8 +32,8 @@
 		versionStore
 	} from '#lib/stores/index.ts';
 	import { initStores } from '#lib/stores/init.ts';
-	import { withBase } from '#lib/utils/base-path.ts';
 	import { hapticTap } from '#lib/utils/index.ts';
+	import { serverUrl } from '#lib/utils/server-config.ts';
 	import { browser } from '$app/env';
 	import { afterNavigate, goto } from '$app/navigation';
 	import { page } from '$app/state';
@@ -184,7 +184,7 @@
 					[HEADERS.AUTHORIZATION]: `${HEADERS.BEARER}${apiKey.trim()}`
 				};

-				fetch(withBase('/props'), { headers })
+				fetch(serverUrl('/props'), { headers })
 					.then((response) => {
 						if (response.status === 401 || response.status === 403) {
 							window.location.reload();
diff --git a/ui/apps/chat/src/service-worker/index.ts b/ui/apps/chat/src/service-worker/index.ts
index fd5f735a1..4dad9f55f 100644
--- a/ui/apps/chat/src/service-worker/index.ts
+++ b/ui/apps/chat/src/service-worker/index.ts
@@ -4,13 +4,14 @@ import { assets, immutable } from '$app/manifest';
 import { self } from '$app/service-worker';

 const CACHE = `llama-ui-${version}`;
-// sw.js is the legacy worker path; it must always come from the network
+// sw.js is the legacy worker path; it must always come from the network, as must config.json,
+// which a host may change between two loads of the same build
 const PRECACHE = [
 	'./',
 	'manifest.webmanifest',
 	'_app/version.json',
 	...immutable.map(({ path }) => path),
-	...assets.map(({ path }) => path).filter((path) => path !== 'sw.js')
+	...assets.map(({ path }) => path).filter((path) => path !== 'sw.js' && path !== 'config.json')
 ].map((path) => new URL(withBase(path), self.location.href).href);
 const PRECACHE_PATHS = new Set(PRECACHE.map((href) => new URL(href).pathname));

diff --git a/ui/apps/chat/static/config.json b/ui/apps/chat/static/config.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/ui/apps/chat/static/config.json
@@ -0,0 +1 @@
+{}
diff --git a/ui/apps/chat/tests/unit/cli.test.ts b/ui/apps/chat/tests/unit/cli.test.ts
index d55be9a8f..be0b9e37a 100644
--- a/ui/apps/chat/tests/unit/cli.test.ts
+++ b/ui/apps/chat/tests/unit/cli.test.ts
@@ -33,6 +33,18 @@ describe('llama-chat CLI arguments', () => {
 		expect(options).toMatchObject({ host: '0.0.0.0', open: false, port: 3001 });
 	});

+	it('reads --server for serving and for build, without a trailing slash', () => {
+		expect(parseCliArgs([]).server).toBe('');
+		expect(parseCliArgs(['--server', 'http://localhost:8080/']).server).toBe(
+			'http://localhost:8080'
+		);
+		expect(parseCliArgs(['build', '--server', 'https://llm.example.com/llama/']).server).toBe(
+			'https://llm.example.com/llama'
+		);
+		expect(() => parseCliArgs(['--server', 'localhost:8080'])).toThrow(/invalid --server/);
+		expect(() => parseCliArgs(['--server', 'not a url'])).toThrow(/invalid --server/);
+	});
+
 	it('accepts start as a verb that changes nothing', () => {
 		expect(parseCliArgs(['start', '--no-open']).open).toBe(false);
 	});
@@ -42,8 +54,6 @@ describe('llama-chat CLI arguments', () => {
 		expect(() => parseCliArgs(['--nope'])).toThrow();
 		expect(() => parseCliArgs(['--port', 'abc'])).toThrow(/invalid --port/);
 		expect(() => parseCliArgs(['--port', '70000'])).toThrow(/invalid --port/);
-		// it forwards nothing, so there is no llama-server to name
-		expect(() => parseCliArgs(['--server', 'http://127.0.0.1:9931'])).toThrow();
 	});

 	it('reads build with its own flags, and keeps serving flags out of it', () => {
@@ -105,6 +115,18 @@ describe('llama-chat build', () => {
 		]);
 	});

+	it('names the llama-server in config.json when given one', async () => {
+		const out = await buildStatic({
+			distDir: dist,
+			out: join(work, 'pointed'),
+			server: 'http://localhost:8080'
+		});
+
+		expect(JSON.parse(await readFile(join(out, 'config.json'), 'utf8'))).toEqual({
+			server: 'http://localhost:8080'
+		});
+	});
+
 	it('refuses a folder that is not empty unless forced', async () => {
 		const out = join(work, 'busy');

@@ -181,6 +203,26 @@ describe('llama-chat server', () => {
 		expect(worker.headers.get('cache-control')).toBe('no-cache');
 	});

+	it('answers config.json with the llama-server it was given, revalidated', async () => {
+		expect((await fetch(`${chatUrl}/config.json`)).status).toBe(404);
+
+		const pointed = createChatServer({ distDir: dist, server: 'http://localhost:8080' });
+		const pointedUrl = await listen(pointed);
+
+		try {
+			const response = await fetch(`${pointedUrl}/config.json`);
+
+			expect(response.headers.get('cache-control')).toBe('no-cache');
+			expect(await response.json()).toEqual({ server: 'http://localhost:8080' });
+
+			// naming a llama-server must not turn this into a proxy for it
+			expect((await fetch(`${pointedUrl}/tools`)).status).toBe(404);
+			expect((await fetch(`${pointedUrl}/props`, { method: 'POST' })).status).toBe(405);
+		} finally {
+			await close(pointed);
+		}
+	});
+
 	it('forwards nothing: API paths are not found and other methods are refused', async () => {
 		const props = await fetch(`${chatUrl}/props`);

diff --git a/ui/apps/chat/tests/unit/server-config.test.ts b/ui/apps/chat/tests/unit/server-config.test.ts
new file mode 100644
index 000000000..3d27d37c2
--- /dev/null
+++ b/ui/apps/chat/tests/unit/server-config.test.ts
@@ -0,0 +1,79 @@
+import {
+	getServerBase,
+	loadServerConfig,
+	normalizeServerBase,
+	serverUrl,
+	setServerBase
+} from '#lib/utils/server-config.ts';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('$app/paths', () => ({ asset: (path: string) => `./${path}` }));
+
+afterEach(() => {
+	setServerBase('');
+	vi.unstubAllGlobals();
+});
+
+describe('normalizeServerBase', () => {
+	it('keeps the origin and a path, without a trailing slash', () => {
+		expect(normalizeServerBase('http://localhost:9931')).toBe('http://localhost:9931');
+		expect(normalizeServerBase(' http://localhost:9931/ ')).toBe('http://localhost:9931');
+		expect(normalizeServerBase('https://llm.example.com/llama/')).toBe(
+			'https://llm.example.com/llama'
+		);
+	});
+
+	it('is empty for anything but an http(s) URL', () => {
+		for (const value of ['', '   ', 'localhost:9931', 'ftp://host', 'javascript:alert(1)', 7, null])
+			expect(normalizeServerBase(value)).toBe('');
+	});
+});
+
+describe('serverUrl', () => {
+	it("stays on the app's own origin by default", () => {
+		expect(serverUrl('/props')).toBe('./props');
+	});
+
+	it('goes to the configured server', () => {
+		setServerBase('http://localhost:9931/');
+
+		expect(serverUrl('/props')).toBe('http://localhost:9931/props');
+		expect(serverUrl('v1/chat/completions')).toBe('http://localhost:9931/v1/chat/completions');
+		expect(serverUrl('./props')).toBe('http://localhost:9931/props');
+	});
+});
+
+describe('loadServerConfig', () => {
+	const respond = (body: unknown, ok = true) =>
+		vi.stubGlobal(
+			'fetch',
+			vi.fn(async () => ({ json: async () => body, ok }))
+		);
+
+	it('reads the server from config.json, past the HTTP cache', async () => {
+		respond({ server: 'http://localhost:9931' });
+		await loadServerConfig();
+
+		expect(fetch).toHaveBeenCalledWith('./config.json', { cache: 'no-store' });
+		expect(getServerBase()).toBe('http://localhost:9931');
+	});
+
+	it("leaves the server on the app's origin for an empty, missing or broken file", async () => {
+		respond({});
+		await loadServerConfig();
+		expect(getServerBase()).toBe('');
+
+		respond({ server: 'http://localhost:9931' }, false);
+		await loadServerConfig();
+		expect(getServerBase()).toBe('');
+
+		vi.stubGlobal(
+			'fetch',
+			vi.fn(async () => {
+				throw new Error('offline');
+			})
+		);
+		await loadServerConfig();
+		expect(getServerBase()).toBe('');
+	});
+});