# OmniChat

[![Latest release](https://gitlab.com/geekaholic/omni-chat/-/badges/release.svg?value_width=124)](https://gitlab.com/geekaholic/omni-chat/-/releases)

OmniChat is a lightweight, local-first, multi-user AI chat app. The core is a Go server with SQLite storage, and it talks to any OpenAI-compatible endpoint such as LiteLLM, vLLM, llama.cpp, or another compatible local/proxy server.

Tool-capable models can also call a native `web_search` function. Search is provider-based and off by default. Configure Tavily with your own API key, then enable Search for a chat. Desktop and standalone web
also offer SearXNG and DuckDuckGo. iOS search Settings offer Tavily and Off only; the DuckDuckGo
HTML adapter is excluded from iOS builds. A companion
`fetch_url` tool lets the model fetch and summarize a specific URL (a web page, article, or — via a
capable reader — a YouTube transcript); it is off by default and enabled with `CHAT_WEB_FETCH=true`.
A native `generate_image` tool turns "generate an image of…" requests into pictures rendered inline
in the chat; it is enabled by pointing `CHAT_IMAGE_GEN_URL` at any OpenAI-Images-compatible backend,
such as the bundled Z-Image-Turbo sidecar (see [Image generation](#image-generation)). Responses
can also be read out loud in configurable voices by pointing `CHAT_TTS_URL` at any
OpenAI-compatible speech backend, such as the bundled OmniVoice sidecar (native Apple-Silicon MPS or Docker CUDA; see
[Read aloud](#read-aloud-text-to-speech)). The composer's mic button turns speech back into text —
dictate a message instead of typing it — via `CHAT_STT_URL` and any OpenAI-compatible transcription
backend, such as the bundled whisper sidecar (native Apple-Silicon MLX or Docker CUDA/CPU; see
[Voice input](#voice-input-dictation)), or the browser's own on-device speech recognition with no
backend configured at all.

The product goal is one Go core shared by both a web app and native Tauri shells. The macOS shell
bundles the core as a sidecar; the iPadOS shell links that exact core as a Go C archive because
iPadOS cannot launch sidecar processes. See [Desktop app](#desktop-app-macos) and
[Native iPad app](#native-ipad-app-ipados-26).

Normal message drafts are saved in the core for the current sign-in session, including ready
attachments (subject to the pending-upload expiry). During a valid session, reloading or relaunching restores the draft
and its conversation. Draft recovery also works when a hosted/Docker instance is opened over
plain HTTP on your network. Send keeps the draft until the core accepts the message; rejected sends
show an error beside the composer. Returning from the background refreshes the conversation
and reconnects an interrupted response without cancelling generation. On iPad the core reconnects
itself if iPadOS dropped its local connection while the app was in the background; if it still
can't be reached, the error beside the composer offers **Reconnect**, so there's no need to close
the app. Native Apple shells also restore the main view if WebKit terminates its content process. Off-the-record mode removes any
previous saved draft and never saves temporary-chat text.

**Request size limits.** JSON API requests are limited to 4 MiB by default. Off-the-record
requests allow 16 MiB for the full transcript and settings; skill preview/import keeps its
9 MiB body limit. Smaller endpoint limits still apply. Oversized bodies decoded by these
JSON handlers return HTTP 413 with error code `payload_too_large`. File/audio uploads and
the agent model proxy retain their separate limits.

If the core rejects your sign-in session, OmniChat closes account dialogs and returns to sign-in
with a clear message. Normal unsent text is held only in memory and restored if the same account
signs back in without reloading the app; attachments need reattaching. Off-the-record text and
message edits are cleared. Provider errors and network interruptions do not sign you out.

Wide tables and code blocks scroll horizontally within the response. On phones and other touch
screens, a visible bar below overflowing content lets you drag to view the hidden columns or text;
you can also swipe the content sideways.

Chat messages retain their avatars on phone-sized screens, including oMNI's dinosaur on replies.

New chats get an immediate first-message title, then the Go core makes one best-effort pass after
the first answer to replace it with a short summary title. Later turns never auto-rename the chat;
use Chat Details to edit the title manually. The title wand prefers the auxiliary model and
uses the chat's model if auxiliary generation is unavailable or fails. Both servers retain
their sharing permission checks. Chat-model title calls reserve up to 256 output tokens for
answer framing, within the server's limits; the visible title remains short. If the title wand fails, you can retry or close
the editor and keep the current title. Closing cancels an unfinished title request; unsaved
metadata errors offer a choice to keep editing or discard the unsaved edits. Touch controls
avoid double-tap zoom while retaining pinch zoom.
The title subtitle shows tags or project membership when present; it makes no
privacy claim about the selected inference backend.

## User manual

Read the [published user and configuration manual](https://geekaholic.gitlab.io/omni-chat/docs/manual.html).
In a downloaded or cloned copy, open [`docs/manual.html`](docs/manual.html) directly in a browser
(double-click it, or run `open docs/manual.html` on macOS or `xdg-open docs/manual.html` on Linux).

For the full product spec, see [docs/prd.html](docs/prd.html). For agent/development rules, see [AGENTS.md](AGENTS.md).

## Installing build dependencies

To build OmniChat from a clean machine you need the following. All commands go through the
[Makefile](Makefile), so `make` is required as well.

| Tool | Minimum | Why |
| --- | --- | --- |
| Go | 1.27.4+ | Builds the core (matches `core/go.mod`) **and** compiles the sandbox Go runtime for the web build. |
| Node.js | 20 or 22 LTS | Builds the Svelte/Vite web SPA. |
| npm | bundled with Node | Installs and runs the web build. |
| make | any recent | Runs every documented command. |
| git | any recent | Clones the repo. |

No C compiler is needed — storage uses the pure-Go `github.com/ncruces/go-sqlite3` (no CGO).

Rust and the Tauri CLI are needed **only** to build the desktop app; the core and the web app build
without them (see [Desktop app](#desktop-app-macos)).

Building the web app provisions the WebAssembly runtime assets for the code-block **Run** feature: it
compiles the sandbox Go runtime (`tools/gorunner`, emitted to `web/public/runtimes/go-<version>/`, so
the Go toolchain is needed for the web build too) and downloads pinned, checksum-verified Python
(Pyodide) and bash (Wasmer/WASIX) assets (see `web/runtimes.json`) on the first build — network is
needed once for the download; afterwards builds reuse the cached files under `web/public/runtimes/`
and run offline. Network errors, HTTP 5xx and 429 responses are retried up to four times; a 404 or a
checksum mismatch fails at once. For a fully offline build, pre-populate `web/public/runtimes/` from a mirror.

You also need an **OpenAI-compatible endpoint** (LiteLLM, vLLM, llama.cpp, etc.) with
`/v1/models` and `/v1/chat/completions` to actually run the app — that is a runtime dependency,
not a build dependency.

### macOS (Homebrew)

```bash
brew install go node make git
```

macOS already ships `make` and `git` with the Xcode Command Line Tools (`xcode-select --install`);
Homebrew simply provides newer versions.
If Go is already installed, run `brew upgrade go` to meet the 1.27.4 security minimum.

### Ubuntu / Debian

The `apt` packages for Go and Node are often too old, so install those from upstream:

```bash
# make, a compiler toolchain, and git
sudo apt update && sudo apt install -y build-essential git

# Go (official tarball — 1.27.4 or newer is required)
curl -fsSL https://go.dev/dl/go1.27.4.linux-amd64.tar.gz | sudo tar -C /usr/local -xz
echo 'export PATH=/usr/local/go/bin:$PATH' >> ~/.profile && source ~/.profile
# or: sudo snap install go --classic

# Node.js 22 LTS via NodeSource
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs
# or use nvm: https://github.com/nvm-sh/nvm
```

### Verify

```bash
go version && node -v && npm -v && make --version
```

Then build everything with `make build` (or run the full gate with `make check`).

Both Go modules require **Go 1.27.4 or newer** for the
[HTTP/1 MaxBytesReader header-race fix (GO-2026-6859)](https://pkg.go.dev/vuln/GO-2026-6859).
This also retains the earlier [compromised-certificate distrust fix (CVE-2026-111943)](https://go.dev/issue/82345).
With automatic toolchain selection enabled, an older Go installation downloads a suitable
toolchain; with `GOTOOLCHAIN=local`, an older compiler refuses the build. Docker server and
Linux package builders pin Go 1.27.4. CI retains Node 22 and selects `go1.27.4+auto`, logging
the effective version for both modules. Rebuild apps and container images after upgrading:
existing binaries retain their compiled standard library.

## Quick Start

If Ollama, LM Studio, llama.cpp, or another keyless OpenAI-compatible server is already
running on this machine (or your LAN), start OmniChat and the model picker fills in on
its own. To pin a specific URL instead:

```bash
# Ollama defaults to port 11434, LM Studio to 1234, llama.cpp/vLLM commonly to 8000/8080
CHAT_ENDPOINT_URL=http://localhost:11434 make dev
```

`make dev` serves the app on port `8080`, so open <http://127.0.0.1:8080>. On first run, create
the owner account; after that, login is required for protected routes. New passwords (the owner,
members an admin adds, `reset-password`) need at least 8 characters; passwords set before this rule
keep working. Password fields have an eye button to show what you typed instead of a confirm field.

Set `CHAT_PORT` to use a different port, `CHAT_API_KEY` if your endpoint needs a token, and
`CHAT_DB_PATH` to choose where the SQLite file lives. See [Configuration](#configuration) for the
full list.

The SQLite pool allows up to eight open connections and retains up to four idle
connections to bound the memory used by the driver’s WASM instances. Additional
database work waits for a connection. A literal `:memory:` database uses one open
and one idle connection so its schema and data survive between calls.

Memory and chat-summary embedding vectors are stored as little-endian float32 BLOBs
with model and dimension tags; cosine ranking runs in Go, without a SQLite vector
extension. Changing the configured model or dimension makes mismatched vectors stale;
they are re-embedded in bounded batches when accessed.

`GET /api/health` reports the linked build version and database probe result, for
example `{"version":"dev","db":{"ok":true}}`. Packaged builds report their CalVer
instead of `dev`; the response has no SQLite-extension capability field.

### Sign-in security

Sessions expire 30 days after sign-in; activity does not extend that expiry. The
core records session activity at most once every five minutes instead of writing
on every authenticated request. Expired sessions and their saved composer drafts
are removed when the core opens the database and after each successful sign-in.
Live sessions and their drafts are preserved.

Failed logins are counted for each username/IP pair (username case-insensitive for
throttling), with a separate counter across all usernames from the same IP. A pair allows
five failures before delaying further attempts; the IP allows 20. Failures for a username
from one IP do not block that username from other IPs. A blocked request receives HTTP 429
`too_many_attempts` and a `Retry-After` header. The delay starts at one second, doubles after
further failures, and is capped at 60 seconds. Counters expire 15 minutes after their last
failure; checking them or logging in successfully does not extend expiry. A successful
login clears only its pair counter. Counters live in memory and reset on core restart.
The sign-in form displays the server's wait message.

Usernames longer than 256 bytes skip the account lookup and username key. They still
perform dummy password verification, return the normal `invalid_credentials` 401, and
count against the IP only; an existing IP backoff still returns 429.

The client IP comes from the connection by default. With `CHAT_TRUST_PROXY=true`, login
uses the validated right-most `X-Forwarded-For` address; client-controlled left-most
addresses are ignored, and a missing or invalid right-most value falls back to the peer.
Login and first-run setup share a
four-operation password hashing limit. Unknown or disabled accounts also perform password
verification and return the same `invalid_credentials` response as a wrong password.
The host `reset-password` command is unaffected.

### Required upgrade for reverse-proxy deployments

Proxy trust now defaults **off for every bind address**, including `0.0.0.0`.
**Existing reverse-proxy deployments must set `CHAT_TRUST_PROXY=true` (or `1`) in the
core environment and restart.** For Compose, uncomment the example in `.env`; the base
Compose file loads it automatically. No bundled Compose setup includes an incoming
reverse proxy, so none enables trust by default.

**Behind a TLS-terminating proxy, `CHAT_TRUST_PROXY=true` is now required for the
browser app to work at all.** Without it, the core sees HTTP while the browser's
Origin is HTTPS: every browser write, including sign-in, returns **403 `cross_origin`**.
Set the variable on the core and restart it; changing only the proxy is not enough.

When trust is off, `X-Forwarded-Proto` and `X-Forwarded-Host` are ignored. Their presence
logs one warning per core process naming `CHAT_TRUST_PROXY`. With trust enabled, they
determine the external HTTPS origin for API checks, OAuth and voice, and HTTPS session cookies get
`Secure`. Direct TLS also sets `Secure` without proxy trust. Plain loopback HTTP used by
desktop/iPad and standalone web mode keeps working.

Enable trust only when the core is reached through a trusted proxy. The proxy must
send `X-Forwarded-Proto` with the public scheme, and either preserve the public `Host`
or send `X-Forwarded-Host` with the public host (including any non-default port).
Overwrite forwarded scheme/host headers rather than passing client-supplied values
through. Append the observed client address to `X-Forwarded-For`; only the right-most
address is used for login throttling.

Minimal nginx example inside an existing HTTPS `server` block on public port 443,
with the core listening on `127.0.0.1:8080`:

```nginx
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_buffering off;
}
```

On a non-default public port, use `$http_host` instead of `$host` for both `Host`
and `X-Forwarded-Host`, because `$host` drops the port.

### API origin checks

State-changing `/api/` requests (methods other than GET, HEAD and OPTIONS) return
403 `cross_origin` when an `Origin` header does not match the core's scheme, host
and port. Empty, `null`, malformed and multiple origins are rejected too. If Origin
is absent, `Sec-Fetch-Site: cross-site` or `same-site` is rejected; `same-origin`,
`none` and requests without either header keep working. CLI clients need no new header.
The `/agent-proxy/v1/` routes retain their scoped bearer-token authentication.

Serve the SPA and API from the same origin. Behind a reverse proxy, configure
`CHAT_TRUST_PROXY` as described above so checks use the public origin. The desktop
and iPad shells load the core's loopback origin. The Vite `make dev-web` proxy
preserves the browser's Host header so dev requests pass the same check without
rewriting a foreign Origin into a trusted one.

### Browser response headers and caching

The core's SPA responses include `X-Content-Type-Options: nosniff`,
`Referrer-Policy: no-referrer`, and an enforced `Content-Security-Policy` of
`object-src 'none'; frame-ancestors 'self'; form-action 'self'`. This blocks object
embeds, permits only same-origin ancestors and form submissions, and sends no
referrer. Existing cross-origin isolation headers remain in place.

A second header, `Content-Security-Policy-Report-Only`, inventories a full strict
policy in the browser console, including `script-src 'self' 'wasm-unsafe-eval'`,
worker, connection, image and style restrictions. It has no reporting endpoint.
**Script restrictions are not yet enforced:** `srcdoc`, `blob:` and `data:` previews
inherit their embedder's policy and currently need inline scripts. `base-uri 'self'`
also remains report-only because HTML previews install a non-app base URL. Preview
isolation and strict script enforcement require the owner-approved S5b design.

Existing content-hashed files under `/assets/` use
`Cache-Control: public, max-age=31536000, immutable` (one year). `index.html`, the app
root, and client-side route fallbacks use `Cache-Control: no-store` so a reload can
load the current build. Versioned sandbox runtime assets retain their immutable cache policy.

To repeat the CSP browser check, use an existing Playwright installation with its
Chromium browser available (no application dependency is added):

```sh
make build
mkdir -p .cache/s5-2
(cd core && go build -o ../.cache/s5-2/fixture ./internal/api/testdata/csp)
PLAYWRIGHT_MODULE=/absolute/path/to/playwright/index.mjs node web/scripts/probeCSP.mjs
```

The fixture uses an isolated database, mock inference, and a fake microphone/voice
backend. It checks chat, math, images, HTML/SVG/Markdown previews, the browser popout,
all five code languages, voice and Settings. Expect `passed: true` and
`counts.enforcedSPA: 0`. The printed report is also saved under `.cache/s5-2/browser-*/`;
report-only and existing preview-policy violations remain visible in the inventory.

### Add to iPhone Home Screen

When the web app is reachable from your phone, open it in Safari, tap **Share**, then tap
**Add to Home Screen**. iOS uses the bundled Omni app icon (`apple-touch-icon`) and launches the app
in a standalone browser window from that Home Screen icon.

## Docker

Docker is an alternative to installing Go and Node.js locally. The Compose setup pulls the
published multi-platform image from GitLab, publishes the app only on host loopback by default,
and keeps the SQLite database in the Docker-managed `omni-chat-data` volume.

```bash
# Optional: copy this if you want to change ports, endpoint settings, or secrets.
cp .env.example .env

docker compose up -d
docker compose ps
```

To start OmniChat with the optional self-hosted SearXNG provider:

```bash
printf 'SEARXNG_SECRET=%s\n' "$(openssl rand -hex 32)" >> .env
docker compose -f compose.yaml -f compose.search.yaml up -d
```

The overlay enables SearXNG JSON results, configures OmniChat to use the internal
`http://searxng:8080` address, and publishes its UI only on
<http://127.0.0.1:8888> by default. Generate the secret once and keep it in the ignored
`.env` file; Compose fails with setup guidance when it is missing. The overlay is not part of the
normal Compose stack.

For a host-run core (`make dev`) instead of the full Compose stack, start just SearXNG and point
the core at its published port:

```bash
printf 'SEARXNG_SECRET=%s\n' "$(openssl rand -hex 32)" >> .env
docker compose -f compose.search-only.yaml up -d
CHAT_WEB_SEARCH_URL=http://localhost:8888 make dev
```

To start OmniChat with the optional llama.cpp auxiliary-model sidecar (see [Auxiliary
model](#auxiliary-model-chat-titles-memory-jobs-smart-routing)):

```bash
docker compose -f compose.yaml -f compose.aux.yaml up -d
```

The overlay wires `CHAT_AUX_URL` / `CHAT_AUX_MODEL` to an internal `aux-model` service running
`ghcr.io/ggml-org/llama.cpp`, which downloads the configured Hugging Face GGUF (default
[`LiquidAI/LFM2.5-1.2B-Instruct-GGUF`](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-GGUF),
~731 MiB) into a named volume on first run — allow a moment before the sidecar reports healthy and
OmniChat starts. This one model handles chat titles, memory jobs, **and** smart-router
classification, so on its own it needs no separate router sidecar. It is stackable with the other
overlays, e.g. `docker compose -f compose.yaml -f compose.search.yaml -f compose.aux.yaml up -d`.

For a host-run core (`make dev`) instead of the full Compose stack, start just the sidecar and
point the core at its published port:

```bash
docker compose -f compose.aux-only.yaml up -d
CHAT_AUX_URL=http://localhost:8091 \
CHAT_AUX_MODEL=lfm2.5-1.2b-instruct make dev
```

To run the `fetch_url` tool through a self-hosted reader sidecar instead of the in-core `direct`
provider (see [Web/URL fetch](#weburl-fetch)):

```bash
docker compose -f compose.yaml -f compose.fetch.yaml up -d
```

The overlay enables the tool (`CHAT_WEB_FETCH=true`), switches it to the `reader` provider, and points
OmniChat at an internal `reader` service on `http://reader:8081` (its port is also published on
<http://127.0.0.1:3001> for debugging). The service is
[`ghcr.io/jina-ai/reader:oss`](https://github.com/jina-ai/reader), Jina AI's official self-host image
(multi-platform: `linux/amd64` and `linux/arm64`, so it runs unmodified on Apple Silicon) that renders
JavaScript in a bundled headless browser; override `READER_IMAGE`/`READER_VERSION` in `.env` to pin or
replace it. It is a large image and needs more memory than the other sidecars, so allow a moment on
first pull. Stackable with the other overlays, e.g.
`docker compose -f compose.yaml -f compose.search.yaml -f compose.fetch.yaml up -d`.

**When to use it.** The default `direct` provider needs no extra container and handles most static or
server-rendered pages, but it only does a plain HTTP GET: it cannot run JavaScript, is blocked by
anti-bot defenses such as Cloudflare, and cannot read YouTube transcripts. The reader sidecar runs a
real browser, so it renders JS-heavy pages, gets past many anti-bot walls, and returns a YouTube watch
URL's transcript — at the cost of a much larger image, more RAM/CPU, slower fetches (you may want to
raise `CHAT_WEB_FETCH_TIMEOUT`, up to `60s`), and sending target URLs to that container. Prefer
`direct` and switch to the reader overlay only when you need one of those capabilities.

For a host-run core (`make dev`) instead of the full Compose stack, start just the reader and point the
core at its published port:

```bash
docker compose -f compose.fetch-only.yaml up -d
CHAT_WEB_FETCH=true CHAT_WEB_FETCH_PROVIDER=reader \
CHAT_WEB_FETCH_URL=http://localhost:3001 make dev
```

To use the default in-core `direct` provider under the base Compose stack (no sidecar), just add
`CHAT_WEB_FETCH=true` to `.env` — no overlay needed:

```bash
echo 'CHAT_WEB_FETCH=true' >> .env
docker compose up -d
```

### Image generation under Compose

To offer the [`generate_image`](#image-generation) tool from the Compose stack, use the
`compose.imagegen.yaml` overlay. It builds and runs the bundled **Z-Image-Turbo** sidecar
(`docker/imagegen/` — FastAPI + [diffusers](https://github.com/huggingface/diffusers) exposing the
OpenAI Images API) and points OmniChat at it:

```bash
docker compose -f compose.yaml -f compose.imagegen.yaml up --build -d
```

The sidecar **requires an NVIDIA GPU** (install the
[NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html);
Z-Image-Turbo wants roughly 16 GB of VRAM in bf16) and downloads ~12 GB of weights into the
`imagegen-models` volume on first start — watch `docker compose logs -f imagegen` and expect the
healthcheck to stay `starting` until the model is loaded. Stackable with the other overlays.

**On Jetson/L4T or arm64 CUDA hosts**, the default x86-64 base image won't run. Override
`IMAGEGEN_BASE_IMAGE` with a CUDA-enabled PyTorch image that matches your host's driver stack (torch
is **not** reinstalled by the build — it must come from the base) and set `IMAGEGEN_RUNTIME=nvidia`
so the GPU is exposed. For example, in `.env`:

```bash
# NVIDIA Jetson (aarch64 / L4T) — match your JetPack
IMAGEGEN_BASE_IMAGE=dustynv/pytorch:2.7-r36.4.0
# or arm64 CUDA (DGX Spark / Grace-Hopper) — GB10 (sm_121) needs a CUDA >= 12.9 base,
# or edit-model JIT kernels fail with "nvrtc: invalid value for --gpu-architecture"
# IMAGEGEN_BASE_IMAGE=nvcr.io/nvidia/pytorch:25.09-py3
IMAGEGEN_RUNTIME=nvidia
```

On a GPU-less host (for example macOS, where containers cannot use the GPU), run just the sidecar on
a GPU machine and point the core at it:

```bash
# on the GPU box
IMAGEGEN_PUBLISH_ADDRESS=0.0.0.0 docker compose -f compose.imagegen-only.yaml up --build -d
# where the core runs
CHAT_IMAGE_GEN_URL=http://<gpu-host>:8001 make dev   # or add it to .env for Compose
```

**On Apple Silicon**, skip Docker for the sidecar entirely and run it natively so it uses the Mac's
GPU via PyTorch MPS (containers on macOS get no GPU — the compose overlay's NVIDIA reservation
fails outright, and CPU diffusion is unusably slow):

```bash
cd docker/imagegen
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt torch
uvicorn app:app --port 8001          # auto-detects MPS; first run downloads ~12 GB to ~/.cache/huggingface
```

Then point the core at it (`CHAT_IMAGE_GEN_URL=http://localhost:8001 make dev`, or in `.env` for a
Compose-run core use `http://host.docker.internal:8001`). Wait for `model ready` in the sidecar log
before the first request, and note the app-side `CHAT_IMAGE_GEN_TIMEOUT` may need raising while MPS
warms up. When running natively, all the `IMAGEGEN_*` knobs documented in `.env.example` apply as
plain process environment variables (`.env` only feeds Docker Compose) — e.g.
`IMAGEGEN_EDIT_MODEL_ID=Qwen/Qwen-Image-Edit-2509 uvicorn app:app --port 8001`.

Set `IMAGEGEN_API_KEY` on the sidecar and `CHAT_IMAGE_GEN_API_KEY` on the core when that port is
reachable by others. Any other OpenAI-Images-compatible server also works — set
`CHAT_IMAGE_GEN_URL` (and optionally `CHAT_IMAGE_GEN_MODEL`/`CHAT_IMAGE_GEN_API_KEY`) and skip the
sidecar entirely. The sidecar has its own quick-reference
[docker/imagegen/README.md](docker/imagegen/README.md) (Mac-native vs Docker, all knobs).

**Multiple image backends.** `CHAT_IMAGE_GEN_URL` accepts a comma-separated list (one backend per
URL, named by host, first = default), and for richer setups `endpoints.json` may declare a named
`images[]` array + `default_image_endpoint` (see `docs/endpoints.example.jsonc`): each entry
references a `connection` (which carries the base URL and, via `protocol: "responses"`, the OpenAI
Responses API's native `image_generation` tool instead of the default OpenAI Images API — a
connection's API key is the credential) and keeps optional `model`/`carrier_model`/`timeout`/`stream`.
Responses image generation requires a provider that supports the native tool and a `carrier_model`.
Each chat picks its image backend in the Options sidebar; new chats start on `default_image_endpoint`.

**ChatGPT plan usage is chat-only in the current OpenAI preview.** It does not support image
generation. Existing ChatGPT image definitions remain visible for removal but are not registered
as working image backends. Configure a separate image server or an eligible API-key provider.


The same file may declare **named speech backends** in a top-level `tts[]` array +
`default_tts_endpoint`: each entry references a `connection` and keeps a required `model`, an
optional pinned `voices` list with a `default_voice`, and a `timeout`. Users pick their voice
(across all configured backends) under **Voice Engine** in the Options sidebar's
default-collapsed **Voice & Dictation** section. Without a `tts[]` section the `CHAT_TTS_*` env
vars apply.

The file may likewise declare **named transcription backends** in a top-level `stt[]` array +
`default_stt_endpoint`: each entry references a `connection` and keeps a required `model`, an
optional default `language` (ISO-639-1), and a `timeout`. Without an `stt[]` section the
`CHAT_STT_*` env vars apply; with neither configured, the browser's own speech recognition still
covers dictation where supported.

### Text-to-speech under Compose

To offer [read-aloud](#read-aloud-text-to-speech) from the Compose stack, use the
`compose.tts.yaml` overlay. It builds and runs the bundled **OmniVoice** sidecar
(`docker/tts/` — FastAPI wrapping the [k2-fsa OmniVoice](https://github.com/k2-fsa/OmniVoice)
zero-shot TTS model, Apache-2.0, behind the OpenAI speech API) and points OmniChat at it:

```bash
docker compose -f compose.yaml -f compose.tts.yaml up --build -d
```

**CPU works out of the box** (no GPU required): the sidecar auto-detects its device and drops to
8 inference steps on CPU — usable, though slower than real-time. A CUDA GPU auto-selects full
32-step quality much faster than real-time; in `.env` set `TTS_BASE_IMAGE` to a torch-CUDA image
that also ships `torchaudio` (omnivoice needs it) and set `TTS_RUNTIME=nvidia` — the same switch
on **every** CUDA host, since the overlay passes `NVIDIA_VISIBLE_DEVICES` through to expose the
GPU on Jetson/L4T, arm64 NGC (DGX Spark / Grace-Hopper), and x86-64 alike:

| Host | `TTS_BASE_IMAGE` |
| --- | --- |
| x86-64 CUDA | `pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime` |
| Jetson / L4T | `dustynv/pytorch:2.7-r36.4.0` (match your JetPack) |
| arm64 NGC (DGX Spark) | `nvcr.io/nvidia/pytorch:25.09-py3` (GB10 / sm_121 needs CUDA ≥ 12.9) |

The first start downloads the OmniVoice weights (~2.5 GB) into the `tts-models` volume — watch
`docker compose logs -f tts`.

**On Apple Silicon, skip Docker for the sidecar entirely** and run it natively on the **MLX
engine** (mlx-audio's OmniVoice port on Apple's ML framework — no torch involved). Measured on an
M-series Mac: full 32-step quality at ~0.25× real-time — an 80-second reply renders in ~22 s,
short replies in under a second, with working speed control and consistent voices on long
replies (a torch/MPS fallback at ~0.8× real-time exists, see `docker/tts/README.md`):

```bash
cd docker/tts
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt mlx-audio
uvicorn app:app --port 8880       # auto-picks MLX; first run downloads ~2.5 GB to ~/.cache/huggingface
```

Then point the core at it (`CHAT_TTS_URL=http://localhost:8880 CHAT_TTS_MODEL=omnivoice make dev`,
or `http://host.docker.internal:8880` in `.env` for a Compose-run core). Wait for `model ready`
in the sidecar log before the first request.

**Voices:** the sidecar lists four curated preset names (nova, fable, coral, ash — first is the
default), each an OmniVoice attribute persona — and since OmniVoice
designs voices from attribute descriptions, **any other string you save as your voice is used
verbatim as the description** (e.g. `male, elderly, low pitch, british accent`; attributes:
gender, age, pitch, accent, and the `whisper` style). Voice cloning is not exposed. The sidecar
has its own quick-reference [docker/tts/README.md](docker/tts/README.md) (Mac-native vs Docker,
all knobs).

For a host-run core, or to run the sidecar on a different box, use `compose.tts-only.yaml`:

```bash
# on the box running the sidecar
docker compose -f compose.tts-only.yaml up --build -d
# where the core runs
CHAT_TTS_URL=http://localhost:8880 CHAT_TTS_MODEL=omnivoice make dev
```

Set `TTS_API_KEY` on the sidecar and `CHAT_TTS_API_KEY` on the core when the port is reachable by
others (`TTS_PUBLISH_ADDRESS=0.0.0.0`). Any other OpenAI-compatible speech server works the same
way — including the hosted OpenAI API:

```bash
CHAT_TTS_URL=https://api.openai.com CHAT_TTS_MODEL=gpt-4o-mini-tts CHAT_TTS_API_KEY=sk-… make dev
```

### Local Kokoro read-aloud

In **Settings → Models → Read aloud**, click **Download** on the **Kokoro 82M** pill.
Once downloaded, Kokoro is available immediately; there is no enable toggle or restart required.
Choose **Kokoro (local)** in the Read aloud selector to make it the instance default, then save
that preference. An admin can manage downloads on desktop, iPad/iPhone or a compatible standalone server.
On iPad and iPhone with 8 GB or more, Kokoro downloads (about 338 MB) and runs on the device;
keep OmniChat in the foreground while it speaks. Smaller devices keep using external speech
servers and browser voices.
The Go core downloads an isolated Python runtime, pinned dependencies and model files;
no Python commands or separate server are needed. The pill shows progress, model size and
**Retry**, **Download** or **Remove** actions. Removing the model asks for confirmation, removes
Kokoro from voice choices immediately, and keeps the runtime/packages cached. It stays removed
across restarts until you click **Download**; removal waits until speech and setup are idle.
Downloads require Internet access; cached speech
works offline afterward. The small helper ships inside the Go binary (and therefore the
DMG/AppImage); the runtime and weights are downloaded, not bundled.

Expand **Voice & Dictation → Voice Engine**, choose **Server** if needed, and select
`af_heart`, `af_bella` or `am_adam` under **Kokoro (local)**. **Preview voice** uses the same
authenticated Go `/api/tts` path as the speaker button. These presets use American English.
Hosted speech servers remain available alongside it. Separate Kokoro backends (including MLX)
and OmniVoice are hidden from the UI to avoid duplicate choices, but remain supported through
manual `tts[]` or `CHAT_TTS_*` configuration and named `/api/tts` requests.
This includes repository-qualified model names such as `mlx-community/Kokoro-82M-bf16`.
These duplicate servers are also omitted from service alerts; their status is independent
of the built-in **Kokoro (local)** model.

| Host | Inference engine |
| --- | --- |
| Apple-Silicon macOS | MLX, using the Mac GPU |
| Native Linux x86_64 / ARM64 (glibc) | Kokoro ONNX; CUDA on NVIDIA x86_64, CPU fallback everywhere |
| Optional Kokoro Docker image | Same ONNX CPU engine inside the core container |

The model loads on the first speech request. Voice listing and health checks do not load
it. After five idle minutes the native worker exits and releases inference memory; the
next request starts it again. It survives core restarts so saving unrelated settings
doesn't unload a warm model. Desktop Quit stops the recorded private worker. The worker
uses a random loopback port and a private token, not a public speech port. One synthesis
runs at a time with four queued requests. Text and audio are never persisted.

Runtime/cache/model files live under `kokoro/` beside the core's database, shared across
helper updates. The ONNX model and voices total about 115 MiB; MLX weights are about
355 MB. Python and package dependencies need additional disk space. Model artifacts and
the optional uv bootstrap download are pinned; uv itself is downloaded automatically if
absent. Kokoro weights are [Apache-2.0 licensed](https://huggingface.co/hexgrad/Kokoro-82M).

For a headless native server, merge `"local_tts": {"enabled": true, "default": true}`
into `endpoints.json`, or set `CHAT_LOCAL_TTS=true` before starting the core. The environment
switch overrides the file's enabled flag. Advanced testing can select
`CHAT_LOCAL_TTS_ENGINE=auto|mlx|onnx`; auto picks MLX only on Apple Silicon.

For Docker, use the optional image target through this overlay:

```bash
docker compose -f compose.yaml -f compose.kokoro.yaml up --build -d
```

This adds Python/ONNX dependencies to one Debian-based core container. Models persist in
the existing `/data` volume and load only on demand; no Docker socket, GPU, extra published
port, or separate speech container is needed. The default small Alpine image remains
unchanged and can still use external speech servers. Its settings explain that built-in
Kokoro requires the optional image. The optional target is also available with
`docker build --target with-kokoro -t omni-chat-kokoro .`.

For development comparisons only, `make dev-kokoro` still starts the independent MLX-Audio
API at `http://127.0.0.1:8882` using `.cache/kokoro/`. That manual service is separate from
the built-in on-demand worker; it may be configured as a normal AI Server with model
`mlx-community/Kokoro-82M-bf16`, voices `af_heart,af_bella,am_adam` and default `af_heart`.

### Speech-to-text under Compose

To offer [voice input](#voice-input-dictation) from the Compose stack, use the `compose.stt.yaml`
overlay. It builds and runs the bundled **whisper** sidecar (`docker/stt/` — FastAPI wrapping
OpenAI's Whisper model behind the OpenAI transcription API) and points OmniChat at it:

```bash
docker compose -f compose.yaml -f compose.stt.yaml up --build -d
```

**CPU works out of the box** (no GPU required): the sidecar runs the **faster-whisper** engine
(CTranslate2) and auto-detects int8 CPU compute. A CUDA GPU is much faster than real-time; in
`.env` set `STT_BASE_IMAGE` to a CUDA-capable image and `STT_DEVICE=cuda` (x86 hosts also add a
GPU `deploy.devices` reservation like `compose.imagegen.yaml`'s; Jetson/L4T also sets
`STT_RUNTIME=nvidia`). The first start downloads the whisper weights into the `stt-models` volume
— watch `docker compose logs -f stt`.

**On Apple Silicon, skip Docker for the sidecar entirely** and run it natively on the **MLX
engine** ([mlx-whisper](https://github.com/ml-explore/mlx-examples/tree/main/whisper), Apple's MLX
port of Whisper — no torch involved; containers on macOS never see the GPU):

```bash
cd docker/stt
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt mlx-whisper
uvicorn app:app --port 8881       # auto-picks MLX; "model ready" in the log = good to go
```

Then point the core at it (`CHAT_STT_URL=http://localhost:8881 CHAT_STT_MODEL=large-v3-turbo make dev`,
or `http://host.docker.internal:8881` in `.env` for a Compose-run core).

For a host-run core, or to run the sidecar on a different box, use `compose.stt-only.yaml`:

```bash
# on the box running the sidecar
docker compose -f compose.stt-only.yaml up --build -d
# where the core runs
CHAT_STT_URL=http://localhost:8881 CHAT_STT_MODEL=large-v3-turbo make dev
```

Set `STT_API_KEY` on the sidecar and `CHAT_STT_API_KEY` on the core when the port is reachable by
others (`STT_PUBLISH_ADDRESS=0.0.0.0`). Any other OpenAI-compatible transcription server works the
same way — including the hosted OpenAI API:

```bash
CHAT_STT_URL=https://api.openai.com CHAT_STT_MODEL=whisper-1 CHAT_STT_API_KEY=sk-… make dev
```

With no `CHAT_STT_URL` (or `stt[]`) configured at all, dictation still works in browsers that
support on-device `SpeechRecognition` (Chrome, Safari) — see [Voice input](#voice-input-dictation).
The sidecar has its own quick-reference [docker/stt/README.md](docker/stt/README.md) (Mac-native
vs Docker, all knobs).

### Agent handoff + SFTP under Compose

To offer the [Agent handoff](#agent-handoff-delegate-a-task-to-pi) (`delegate_task`) tool and SFTP
workspace access from the Compose stack, use the `compose.agents.yaml` overlay. The core launches
each approved delegation as a **sibling container** through the host's Docker socket, so the overlay
mounts the socket, adds the workspace tree at an identical path on both sides (the host daemon
resolves the sibling's bind mounts against *host* paths), and publishes the SFTP port. One-time
setup:

```bash
make agent-image                                              # the agent image
sudo mkdir -p /srv/omni-agent-work
sudo chown 10001:10001 /srv/omni-agent-work                   # the core's container uid
cp docs/agents.compose-example.json config/agents.json        # managed mode + docker runtime + sftp
ssh-keygen -t ed25519 -f config/sftp_host_key -N ""           # the core runs as uid 10001,
sudo chown 10001 config/sftp_host_key                         # so it must own this key
```

Then bring the stack up with the overlay (stackable with the others):

```bash
DOCKER_GID=$(getent group docker | cut -d: -f3) \
  docker compose -f compose.yaml -f compose.agents.yaml up --build -d
```

`DOCKER_GID` is the group that owns `/var/run/docker.sock` so the non-root core may use it. Change
the workspace location with `OMNI_AGENT_WORK_DIR` in `.env` — it must match `managed_root` in
`agents.json` exactly, as a literal absolute path (no `~`; the container cannot expand your home).
SFTP publishes on `127.0.0.1:2222` by default; set `OMNI_SFTP_PUBLISH_ADDRESS=0.0.0.0` to reach it
from the LAN. If you change `OMNI_SFTP_PUBLISH_PORT`, also set `"public_port"` in the config's
`sftp` block to the same value so the SFTP address the UI offers to copy points at the published
port, not the container-internal one. The example config uses `"docker_network": "bridge"`, so agent containers reach your
`host.docker.internal` model endpoint through the same host-gateway alias the core uses.

**On macOS (Docker Desktop)** the paths and permissions differ: `/srv` is on the sealed read-only
system volume, so put the workspace under your home instead — `mkdir -p ~/omni-agent-work` (no
`sudo`), then set `OMNI_AGENT_WORK_DIR=/Users/<you>/omni-agent-work` in `.env` and the same path as
`managed_root` in `agents.json`. Skip every `chown` and the `DOCKER_GID` prefix — Desktop's VirtioFS
maps file ownership automatically and its socket needs no extra group.

If you built the published `latest` image before `fetch_url` existed (or before another `CHAT_*`
feature you're testing landed), `docker compose up -d` alone will keep running that stale image.
Rebuild from your checked-out source with `docker compose up --build -d` to pick up local changes.

Open <http://127.0.0.1:8080> and create the owner account. The default endpoint is
`http://host.docker.internal:8000`; change `CHAT_ENDPOINT_URL` in `.env` for a different local
OpenAI-compatible port (for example `11434` for Ollama). Compose passes every variable in `.env`
to the container, so it can also hold `CHAT_API_KEY`, an environment variable referenced by
`api_key_env`, and any supported `CHAT_*` capability overrides. Keep `.env` private; it is ignored
by Git.

The default image is `registry.gitlab.com/geekaholic/omni-chat:latest`, built for both AMD64 and
ARM64. GitLab publishes an immutable full-commit-SHA tag alongside `latest` after every successful
main-branch pipeline. Pin a deployment by setting this in `.env`:

```bash
OMNI_CHAT_IMAGE=registry.gitlab.com/geekaholic/omni-chat:<full-commit-sha>
```

Public registries can be pulled anonymously. If the GitLab project or registry is private, run
`docker login registry.gitlab.com` before pulling. To build from the checked-out source instead of
pulling the published image, run `docker compose up --build -d`.

After publishing the multi-platform image, CI's `cleanup-images` job requests
[GitLab tag cleanup](https://docs.gitlab.com/api/container_registry/#delete-registry-repository-tags-in-bulk)
for this exact app repository. It retains `latest`, this pipeline's SHA, five other recent
full-commit-SHA tags, and images less than 24 hours old (GitLab orders and ages tags by manifest
creation time). Explicitly keeping this pipeline's SHA also protects cached builds with old manifests.
Only lowercase 40-character SHA tags are eligible for removal; named release tags and sidecar
repositories are untouched. SHA pins can therefore expire; use a named release tag for a
long-lived pin. Running containers continue to work, but a removed SHA tag cannot be pulled again.
Override `CONTAINER_KEEP_TAGS` (default `5`) and `CONTAINER_MIN_AGE_HOURS` (default `24`) in
CI/CD variables; both must be positive integers.

The job uses `CI_JOB_TOKEN`. If permission is refused, run the pipeline as a Maintainer or
provide a masked, protected `GITLAB_CLEANUP_TOKEN` with `api` scope and Maintainer role on a
protected default branch. It serializes requests with `publish-image`, never deletes manifests
by digest, and fails on API errors. GitLab's once-per-hour bulk-cleanup limit is logged as a
deferral to a later pipeline. Cleanup runs asynchronously and large backlogs can take several
runs. On GitLab.com, unreferenced layers are garbage-collected after 24 hours; storage usage
may take time to fall. Self-managed registries need their own garbage collection setup.

With an `api`-scoped `GITLAB_TOKEN` in the environment, preview the repository and cleanup policy:

```bash
GITLAB_PROJECT=geekaholic/omni-chat \
GITLAB_REGISTRY_IMAGE=registry.gitlab.com/geekaholic/omni-chat \
node tools/cleanup-gitlab-images.mjs --dry-run
```

Use `--delete` to queue cleanup; GitLab selects the eligible tags when its worker runs.
The dry run makes no changes and displays the policy rather than a list of individual tags.
`GITLAB_API_URL` supports self-managed instances. CI applies this policy after successful
publication; it does not change the project's separate scheduled expiration-policy settings.

Container `localhost` refers to the OmniChat container, not the host. Compose maps
`host.docker.internal` to the host gateway on Docker Desktop and native Linux. On native Linux,
the AI server must listen on an address reachable from Docker's bridge, not only `127.0.0.1`;
bind it to an appropriate host interface and restrict that port with host firewall rules.

### Persistent configuration

Compose mounts the repository's `./config` directory read-write at `/config` (the rest of the
container stays read-only). Admins save Settings into `endpoints.json` there; append `:ro` to
that volume to lock saving off and edit files only on the host. The process runs as uid 10001,
so on Linux a directory you created is still not writable by it, even when the mount has no
`:ro`. Settings tells the two apart: "cannot write to the config directory" means ownership,
fixed once with:

```bash
sudo chown 10001:"$(id -g)" ./config
sudo chmod 775 ./config
```

while "the config directory is read-only" means the mount itself carries `:ro`.

Files that Settings saves (`endpoints.json` and its `.bak`) are written mode `0600` and owned by
uid 10001, because they can hold API keys. After the first save from Settings, edit them on the
host with `sudo` (or save from Settings only).

Put persistent `endpoints.json`, `profiles.json`, `SOUL.md`, and optional `skills/*.md` files there:

```bash
cp docs/endpoints.docker.example.jsonc config/endpoints.json   # then delete the // comments
cp docs/profiles.example.json config/profiles.json
cp docs/SOUL.example.md config/SOUL.md
mkdir -p config/skills && cp docs/skills.example/*.md config/skills/
cp docs/mcp.docker.example.json config/mcp.json          # optional; enables MCP tools
# Edit those files, then reload startup configuration:
docker compose restart
```

`docs/endpoints.docker.example.jsonc` is an annotated example (schema 2, `connections[]`) that the
app never loads — it is written for a human or agent to copy from and edit, so its comments must
go before the result is valid JSON. Like it, `mcp.docker.example.json` uses `host.docker.internal:PORT` for
MCP servers running on the host. It also differs in one Docker-specific way: the core's
container has no Node and a read-only rootfs, so it cannot spawn `npx …` **stdio** MCP servers.
Run those as sidecars with the `compose.mcp.yaml` overlay and point at them over HTTP by their
Compose service name (e.g. `http://mcp-files:8000/mcp`) — see [running npx MCP plugins as sidecars](#docker-running-npx-mcp-plugins-sidecar-overlay).

The Docker endpoint example uses `host.docker.internal`, which is required for an AI server
running on the host. As with native runs, the presence of `config/endpoints.json` takes precedence
over `CHAT_ENDPOINT_URL`. The database remains in the named volume when the image or container is
recreated:

```bash
git pull
docker compose pull
docker compose up -d
```

`docker compose down` preserves the database. `docker compose down -v` permanently removes it.
To expose OmniChat to other machines intentionally, set `OMNI_CHAT_PUBLISH_ADDRESS=0.0.0.0` in
`.env` and apply appropriate network controls.

For a consistent backup, stop database writes and archive the named volume:

```bash
docker compose stop
mkdir -p backups
docker run --rm \
  -v omni-chat-data:/data:ro \
  -v "$PWD/backups:/backup" \
  alpine:3.22 tar -czf /backup/omni-chat-data.tar.gz -C /data .
docker compose start
```

### Docker without Compose

```bash
docker volume create omni-chat-data
docker run -d --name omni-chat --restart unless-stopped \
  --add-host host.docker.internal:host-gateway \
  -p 127.0.0.1:8080:8080 \
  -e CHAT_ENDPOINT_URL=http://host.docker.internal:8000 \
  -v omni-chat-data:/data \
  -v "$PWD/config:/config" \
  registry.gitlab.com/geekaholic/omni-chat:latest
```

The image runs as uid 10001 and includes a health check against `/api/health`. The database
lives under `/data`. `./config` is where Settings writes `endpoints.json`; on Linux it must be
writable by that user (`sudo chown 10001:"$(id -g)" ./config && sudo chmod 775 ./config`). Add
`:ro` to the config mount to forbid saving from Settings. To build the image locally instead, run
`docker build -t omni-chat:local .` and replace the final image name with `omni-chat:local`.

## Commands

```bash
make dev          # run the Go core and served web app
make check        # fmt + lint + test + build
make lint         # go vet + pinned Staticcheck + svelte-check + iOS license input check
make fmt          # gofmt + prettier
make audit        # fail on known vulnerabilities in npm, Go and Rust dependencies (needs network)
make test         # go test ./...
make test-race    # Go race detector on the core (slow; separate CI job, outside make check)
make build-core   # build the Go core binary
make build-cli    # build the standalone omni-chat wrapper CLI
make build        # build the web app, core, and wrapper CLI
make dev-desktop  # run the Tauri desktop shell against a freshly built core
make build-desktop # bundle the macOS .app and .dmg (includes the omni-chat CLI)
make check-linux-prereqs # verify the native Linux AppImage toolchain
make build-linux  # build an AppImage for this native x86_64/aarch64 Linux host
make build-linux-docker # build the AppImage in Ubuntu 24.04 Docker on other Linux distros or macOS
make check-ipad-prereqs # verify Xcode, rustup target, CMake, CocoaPods, and Tauri CLI
make check-ipad-simulator-prereqs # additionally verify the ARM64 Simulator toolchain
make init-ios     # intentionally regenerate the tracked Tauri Xcode project
make dev-ipad     # build native archives and install/run on an attached iPad
make build-ipad   # make a signed device build and open the Xcode project
make dev-ipad-simulator # build and run on a selected iPad Simulator
make build-ipad-simulator # create an unsigned ARM64 Simulator bundle
make build-cli-sidecar # the omni-chat CLI copied into the desktop app bundle
make publish-macos # build/publish a fresh CalVer DMG and prepare the matching TestFlight version
make publish-linux # publish the newest same-version x86_64 + aarch64 AppImage pair
make release      # build and publish macOS + both Linux architectures with one version
```

`make check` and `make build` never touch Rust, so CI and the web workflow stay Rust-free.
`make lint` runs Go vet and Staticcheck `v0.8.2` on the core, strict Svelte check on the
SPA, and the iOS license input check. Staticcheck is pinned in the Makefile and runs
through `go run` with repository-local caches; the first download needs network access.
Its configuration disables ST1005 (error capitalization), because messages may start
with product names such as Hola and Pi.
`make fmt` runs gofmt and Prettier. ESLint is not part of the gate.
`make test-race` runs `go test -race -count=1 -timeout 25m ./...` in `core/`. It stays out of `make check`
because it is slow and needs cgo. CI runs it as the `race` job on the Debian `golang:1.27.4`
image with a 30-minute job timeout. The 25-minute limit is per package, above `go test`'s
10-minute default.

After `make build`, the optional chat-library browser check uses an existing Playwright
installation (no added dependency):

```sh
PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs node web/scripts/probeChatPagination.mjs
```

It seeds 250 chats in a fresh repository-local test database, checks scrolling and search,
and writes its report/screenshot under `.cache/q1/`. It never uses the normal app database.

`make audit` checks dependencies for known vulnerabilities: `npm audit` on the web app's shipped
packages (high or critical fails), `govulncheck` on the Go modules, and `cargo audit` on the
desktop shell (installed into `.cache/cargo-tools` the first time). CI runs the npm and Go checks
on every pipeline, and `build-desktop`, `build-linux`, `build-linux-docker`, `publish-macos` and
`publish-linux` run all three before building, so a release can't ship a known vulnerability. To
fix a failure, update the lockfile (`cd web && npm audit fix`, `go get <module>@<fixed version>`,
or `cargo update -p <crate>`) and commit it. `SKIP_AUDIT=1` skips the check for an offline local
`build-*`; publishing always runs it.

Changing dependencies also means refreshing the iOS app's bundled license notices: `make check`
fails until they match the lockfiles. Run `python3 tools/collect-ios-notices.py`, review the change
to `web/public/licenses/third-party-notices.txt`, then
`node tools/check-ios-license-inputs.mjs --write`, and commit all three together.

## Native iPad app (iPadOS 26)

The iPad target is a real Tauri 2 application, not Add to Home Screen. Its WKWebView talks to the
same Go API on device over loopback. The Go core is linked into the app as a `c-archive`; SQLite and
all business logic remain in Go. On iPadOS 26 and later the on-device model is Qwen 3.5 2B in MLX
format, with a 16,384-token context, enough for a system prompt, tool schemas and several
web-search results. The helper loads the snapshot's text model only and prefills in 512-token
chunks, so a 15.6K-token prompt peaks at about 2.4 GB. Apple Silicon Macs on macOS 26 and later run the
same MLX helper with a 32,768-token context: Qwen 3.5 4B on Macs with 16 GB or more, Qwen 3.5 2B
on 8 GB Macs. Both platforms need at least 8 GB RAM.
Go downloads and verifies the files; Swift handles inference behind authenticated loopback.
The output budget scales with the device — 4,096 tokens under 12 GB of memory, 5,120 up to 24 GB,
6,144 above — and is capped by whatever the prompt leaves of the context. The core splits the output budget between thinking and the answer,
so a model that thinks too long is stopped and re-asked with thinking off rather than running
out of room mid-reply. Text, thinking and tools are supported, and answers stream as they are
written even when tools are offered. After a tool call, the helper reuses the prompt it already
processed and reads only the call and its result, so a web-search answer starts in a fraction of
the time a full re-read takes. The 2B's thinking is capped at 768 tokens: when it keeps
second-guessing itself, the core stops it within seconds and answers with thinking off.
Weights from earlier versions (the GGUF download, or the Mac's retired Core AI bundle) are
listed as old weights and can be removed from the model controls.

Simulator supports remote chat only.
On iPhone and iPad, **Options → Background generation** (on by default) keeps a reply going after you leave OmniChat or lock the screen. iOS shows progress and a cancel control. Remote models continue with ordinary network access. On-device Metal continues in the background when the App ID has Background GPU Access; read aloud still stops when you leave. Downloads are pinned MLX snapshots from Hugging Face: about
1.75 GB for the 2B and 3.06 GB for the 4B. Models load in seconds; nothing is compiled on the
device.
Manage the model under **Settings → Models → On-device model**, including after
closing the main-window notice with its **×** button. Download, pause/resume, and removal apply
immediately. See [On-device models](docs/coreai.md).

### Build and self-sign with a free Apple ID

Install full Xcode 27+ (not only Command Line Tools), open it once, and add your Apple ID under
**Xcode → Settings → Accounts**. Select the automatically created **Personal Team**. Then:

```bash
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
brew install go node make cmake rustup cocoapods
export PATH="$(brew --prefix rustup)/bin:$PATH"
rustup default stable
rustup target add --toolchain stable aarch64-apple-ios aarch64-apple-ios-sim
rustup component add --toolchain stable llvm-tools
cargo install tauri-cli --version "^2" --locked

make check-ipad-prereqs
make build-ipad               # downloads/verifies pinned llama.cpp, builds, opens Xcode
```

The iPad build explicitly enables Go modules, even if your global Go configuration has
`GO111MODULE=off`.
The iPhone, iPad, Mac, Linux, and browser icons are generated from
`desktop/app-icon.png` during `make init-ios` and each iPad build, and the
desktop and browser sizes are the exported copies of that same file. After changing
the artwork, rebuild and install over the existing app to update the icon while keeping its data.

The generated Apple project under `desktop/gen/apple` is committed so Xcode Cloud can select the
shared iOS scheme immediately after cloning the repository. Its executable
`ci_scripts/ci_post_clone.sh` hook installs any missing command-line tools and builds the web
bundle, pinned llama.cpp archive, and embedded Go core before Xcode Cloud invokes `xcodebuild`.
Rust components (`llvm-tools` and `rust-src`) are installed serially in that hook. The iOS
wrapper puts the real stable compiler ahead of rustup proxies and propagates the stable
toolchain to child commands, preventing dependency-local toolchain files from starting
competing downloads during parallel compilation.
Keep the project and hook tracked; only its `build/`, `Externals/`, and `xcuserdata/` products
remain ignored.

Homebrew installs `rustup` keg-only because it conflicts with the standalone `rust` formula. Add
`export PATH="$(brew --prefix rustup)/bin:$PATH"` to `~/.zshrc` so new zsh sessions can find it.
CocoaPods must come from the Homebrew formula (`brew install cocoapods`); do not use Tauri's
system-Ruby `sudo gem install` fallback.

The `llvm-tools` component is required by `swift-rs`'s Xcode 27 export fix (1.0.9, plus a
vendored release-export patch). The generated Xcode build phase uses the repository's Rust wrapper, so builds launched from
Xcode work even though GUI applications do not inherit Homebrew or Cargo's shell `PATH`.

iOS 27 also requires a static scene-lifecycle declaration. The repository supplies it through
`desktop/Info.ios.plist`, uses tao 0.37 with its scene-configuration lifetime fix, and mirrors the
declaration into generated Xcode files. If Xcode stops at `UIApplicationMain` with
`EXC_BREAKPOINT`, rerun `make build-ipad` so those generated files and dependencies are refreshed.

The first native llama.cpp compile is large and may take several minutes. Warnings about a missing
llama.cpp Git repository or OpenMP are expected for the pinned source archive; Metal and Accelerate
are the iPad backends. The build deliberately omits llama.cpp's executable and web UI, retaining
only the static API server linked into OmniChat.

In the generated Xcode project, select the OmniChat application target, open **Signing &
Capabilities**, enable **Automatically manage signing**, and select your Personal Team. Keep the
bundle identifier `org.geekaholic.omni-chat`. Connect the iPad, accept **Trust This Computer**, select
it as the run destination, and press Run. If prompted on the iPad, enable **Developer Mode** under
**Settings → Privacy & Security**, restart, then run again. After the first install, approve the
Personal Team certificate under **Settings → General → VPN & Device Management → Developer App →
Trust**, then run or open OmniChat again. You can also set
`APPLE_DEVELOPMENT_TEAM=<your 10-character team id>` and use `make dev-ipad` for later installs.

For a cable-free smoke test, install an iOS Simulator runtime matching the selected Xcode SDK
in **Xcode → Settings → Components**, then run `make dev-ipad-simulator`. The launcher prompts for a destination; set an exact one
when desired, for example `make dev-ipad-simulator IPAD_SIMULATOR="iPad Air 11-inch (M4)"`.
The simulator target builds an unsigned ARM64 simulator bundle, boots the selected device with
`simctl`, and opens Device Hub (Xcode 27) or the legacy Simulator app from the active Xcode.
An already booted simulator is supported. `IPAD_SIMULATOR` accepts an exact name or UDID; use
`xcrun simctl list devices available` to list them. iPhones work too, for example
`make dev-ipad-simulator IPAD_SIMULATOR="iPhone 18 Pro"` when that device is installed.
The command returns after launching; rerun it after code changes to rebuild and relaunch the app.
`make check-ipad-simulator-prereqs` checks the UI, SDK and available iOS runtime before building
web/Go assets. Xcode includes the SDK, while Simulator runtimes are separate installations.
Tauri's “Xcode Simulator SDK … is not installed” message can mean its runtime check failed.
Check `xcrun --sdk iphonesimulator --show-sdk-version` and `xcrun simctl list runtimes`;
install the matching runtime in Components, or use `xcodebuild -downloadPlatform iOS -buildVersion <version>`.
If the runtime is installed but temporarily unavailable, open Xcode or Device Hub and retry.
The iPhone Duo simulator requires Xcode 27.1 and its iOS runtime. You can keep that Xcode
alongside another installation and select it for one command:

```bash
DEVELOPER_DIR=/Applications/Xcode-27.1.app/Contents/Developer make dev-ipad-simulator IPAD_SIMULATOR="iPhone Duo"
```

This selects the SDK for the build as well as the simulator tools, without changing the global Xcode selection.
Use Device Hub’s fold/unfold control to check both displays without restarting the app.
Building with the 27.1 SDK enables the full inner display; see
[Apple’s Duo preparation guide](https://developer.apple.com/iphone-duo/prepare/).
To check the seated split, turn the simulated Duo sideways and partly fold it in Device Hub so the
fold runs across the screen. The shell passes the fold position to the app as `native-fold`
events; debug builds also log each report as `omni-chat: fold …` (Xcode console, or the
simulator log as `[stderr]`). iOS device release builds (archives and Xcode Cloud) stop when
the iOS SDK is older than 27.1, because the app would run letterboxed on the Duo's inner display:
set the Xcode Cloud workflow's Xcode version to 27.1 (Workflow → Environment → Xcode). Debug and
simulator builds only warn.

Simulator builds need neither Developer Mode nor a Personal Team. `make build-ipad-simulator`
performs the same ARM64 compile/link without launching it. Metal is available in the Apple-Silicon
simulator, but its memory pressure and inference speed do not predict behavior on a physical iPad.

Xcode 26.6 supports iPadOS devices only through 26.5. An iPad on iPadOS 27 beta therefore needs a
current Xcode 27 beta (and a macOS version that Xcode beta supports); Developer Mode alone cannot
make Xcode 26.6 recognize that device. See Apple's
[Xcode SDK and device-support table](https://developer.apple.com/xcode/system-requirements/).

Free Personal Team profiles normally expire after seven days. Reconnect the iPad and press Run
again to reprovision; this is development signing, not an App Store or redistributable IPA. Keep the
same bundle identifier and do not delete the app if you want its database and downloaded model to
remain in its sandbox. Detailed troubleshooting is in
[`docs/ipad-self-signing.md`](docs/ipad-self-signing.md).

TestFlight builds come from Xcode Cloud instead. `make publish-macos` prepares the matching
date-based iOS release version; commit and push those metadata changes to the branch Cloud watches.
Cloud supplies its own increasing build counter. The procedure and failure modes are in
[`docs/ipad-testflight.md`](docs/ipad-testflight.md). `desktop/Info.ios.plist` declares
`ITSAppUsesNonExemptEncryption = NO`, so builds skip the export compliance prompt.

If the archive succeeds but Cloud export exits 70, download **Artifacts → Logs** and inspect
`app-store-export-archive-logs/xcodebuild-export-archive.log`. HTTP 502 from `listTeams.action`
with `Session Proxy Provider` authentication errors points to Cloud's signing service; retry
before changing project signing or revoking certificates. See the troubleshooting section in
[`docs/ipad-testflight.md`](docs/ipad-testflight.md).

## Desktop app (macOS)

The desktop shell is a thin Tauri 2 window. It picks a free loopback port, starts the same Go core
binary as a sidecar, waits for the core's `READY port=<n>` handshake, and points the webview at it.
All logic stays in the core — the Rust layer only supervises the process.

On macOS and Linux, right-click browser menus (Back, Reload, Inspect Element) and the
web inspector are disabled in the app and preview windows. Use the app's navigation
and copy buttons or keyboard shortcuts for copying and pasting text.

### Install a prebuilt app

Apple Silicon, macOS 26+. One command downloads the latest DMG, copies
`OmniChat.app` into `/Applications`, clears Gatekeeper quarantine, and
puts the `omni-chat` CLI on your `PATH` (symlink into `~/.local/bin`, plus
Homebrew's bin when that directory is writable):

```bash
curl -fsSL https://geekaholic.gitlab.io/omni-chat/install-macos.sh | bash
```

Then, with the app running: `omni-chat launch pi` or `omni-chat launch hola-coder -i`.

Or download the [latest DMG](https://geekaholic.gitlab.io/omni-chat/downloads/macos/)
and drag the app to Applications yourself. A manual install still needs
`xattr -dr com.apple.quarantine "/Applications/OmniChat.app"` (or System
Settings → Privacy & Security → **Open Anyway**) because the build is ad-hoc
signed, and it does not put the CLI on `PATH` — either re-run the installer
or:

```bash
ln -sfn "/Applications/OmniChat.app/Contents/Resources/omni-chat" ~/.local/bin/omni-chat
```

To build and publish a new DMG with a fresh UTC date-based version:

```bash
GITLAB_DEPLOY_TOKEN=your-deploy-token make publish-macos
# Include the release metadata in a commit:
GITLAB_DEPLOY_TOKEN=your-deploy-token make publish-macos PUBLISH_FLAGS='--commit'
# Reuse an existing DMG without rebuilding or changing its version:
DMG='/path/to/OmniChat_<version>_aarch64.dmg' GITLAB_DEPLOY_TOKEN=your-deploy-token make publish-macos
```

That uploads the DMG and its SHA-256 to GitLab's generic package registry
(`omni-chat-macos/<version>/Omni-Chat-aarch64.dmg`), points the macOS section of
`downloads/latest.json` at it, and rewrites `downloads/macos/index.html`, the
stable download page that forwards to the current DMG. The DMG itself is no
longer committed to Git. Windows packages are not published yet.

After a successful upload, the publisher also synchronizes the iOS overlay, Info.plist, Xcode
project and project.yml to the DMG's `YYYY.M.DHHMMSS` release version. Commit and push these files
for the next Xcode Cloud build to use it; publishing macOS does not itself upload an iOS build.
Cloud uses `CI_BUILD_NUMBER` for the separate Apple build number and embeds the release version
in the Go core. Existing TestFlight builds keep their old versions. `BUILD_VERSION` can still pin
a reproducible build; Cargo's crate version and the base Tauri source version remain independent.

Both publish targets authenticate the same way. A project deploy token with the
`write_package_registry` scope in `GITLAB_DEPLOY_TOKEN` is preferred; `GITLAB_TOKEN` (a personal,
project or group access token with the `api` scope) and GitLab CI's `CI_JOB_TOKEN` also work, in
that order. Provide the token only for the publish command; it is passed to curl on stdin, never
on its command line.

Both `make publish-macos` and `make publish-linux` also
prepend a release section to `CHANGE.log` built from the conventional-commit subjects since the
previous release (a commit that changed `downloads/latest.json`), grouped as New / Improvements /
Fixes; `docs:`, `chore:`, `test:`, `ci:` and `style:` commits are left out. Hand-written narrative
entries can still go above it. To backfill a past release:
`node tools/update-changelog.mjs --file CHANGE.log --version <ver> --platform macOS --release-commit <sha>`.
`PUBLISH_FLAGS='--commit'` stages `CHANGE.log` with the release.

`make release` builds and publishes macOS and both Linux architectures with **one** version
(the Linux AppImages build in Docker Desktop on the Mac), so a single GitLab Release carries all
three downloads; `PUBLISH_FLAGS` passes through to both publish scripts. `publish-macos` and
`publish-linux` remain for single-platform releases.

GitLab Releases are created by CI, not by the publish scripts. On every default-branch pipeline,
the `sync-releases` job (`tools/sync-gitlab-releases.mjs`, after `cleanup-packages`) walks the
first-parent history of `downloads/latest.json` and gives each version that still has packages in
the registry one Release: tag `v<version>` on its newest publish commit (created through the
Releases API, so nothing pushes tags and no tag pipeline runs), the version's `CHANGE.log`
section as notes, the install commands, and download links for every platform that shipped it.
A second platform publishing the same version is added to the same Release. When cleanup removes
a version's packages, its Release is deleted and the tag is kept. The job uses `CI_JOB_TOKEN`; if
that is refused, add a masked `GITLAB_RELEASE_TOKEN` CI/CD variable (`api` scope, Maintainer
role). To preview or apply by hand: `node tools/sync-gitlab-releases.mjs [--apply] [--ref origin/main]`
with `GITLAB_RELEASE_TOKEN` or `GITLAB_TOKEN` (Developer role or higher). The project's release badge
shows the newest one.

GitLab CI runs `cleanup-packages` after Pages deploys on the default branch. It keeps the
five newest CalVer versions of **each** desktop package (`omni-chat-macos` and
`omni-chat-linux`), plus installer-linked versions and uploads less than 24 hours old.
Older versions are deleted as whole packages, including checksums and both Linux architectures.
Other package names and Docker images are outside this job's scope. Override
`PACKAGE_KEEP_VERSIONS` (default `5`) and `PACKAGE_MIN_AGE_HOURS` (default `24`) in CI/CD variables
to change retention; both must be positive integers. GitLab's built-in
[package cleanup policy](https://docs.gitlab.com/user/packages/package_registry/reduce_package_registry_storage/)
only removes duplicate assets within a version, so it does not replace this job.

Cleanup uses `CI_JOB_TOKEN` and needs a pipeline triggered by a Maintainer or Owner. If that
token is refused, add a masked, protected `GITLAB_CLEANUP_TOKEN` CI/CD variable with `api` scope
and the Maintainer role, and protect the default branch. Upload-only deploy tokens cannot delete
packages. The job protects both its deployed `downloads/latest.json` and the current default-branch
manifest read through the API, so queued pipelines preserve both sets of installer links. It lists
all package pages before deleting anything and fails if the manifest or API cannot be read.

After merging, the next successful default-branch Pages deployment also cleans the existing
backlog. To preview the same policy locally, provide `GITLAB_TOKEN` with `api` scope in your
environment and run:

```bash
GITLAB_PROJECT=geekaholic/omni-chat node tools/cleanup-gitlab-packages.mjs --dry-run
```

Use `--delete` to apply it. `GITLAB_API_URL` supports a self-managed instance and `GITLAB_REF`
selects its default branch (local default: `main`). Docker images are handled separately by
`cleanup-images` after successful publication, as described in the Docker instructions above.

Extra prerequisites, on top of the table above:

| Tool | Version | Why |
| --- | --- | --- |
| Rust | 1.82+ | Compiles the Tauri shell. |
| Tauri CLI | 2.x | Runs and bundles the app: `cargo install tauri-cli --version "^2" --locked` |
| Xcode | 27 | Links against the macOS SDK and compiles the AppleFoundation helper for macOS 26. |
| Build host | Apple Silicon | The app ships `arm64` only; `make build-desktop` runs `check-macos-prereqs` first and refuses anything else. |

```bash
make dev-desktop     # build the SPA + core sidecar, then run the shell
make build-desktop   # produce desktop/target/release/bundle/macos/OmniChat.app
```

To sign a local build with an Apple Development certificate installed through Xcode,
set `APPLE_SIGNING_IDENTITY` to its exact name from `security find-identity -v -p codesigning`:

```bash
APPLE_SIGNING_IDENTITY='Apple Development: Your Name (IDENTIFIER)' make build-desktop
```

The macOS signing config includes `desktop/Entitlements.macos.plist` for bundled
executables, including the Go core. Its `allow-unsigned-executable-memory` entitlement
is required by the pinned SQLite/wazero compiler, which generates executable memory
without `MAP_JIT`; `allow-jit` alone is insufficient. Keep Hardened Runtime enabled.
Without this entitlement, a signed core can verify successfully on disk but die at
startup with signal 9 (`CODESIGNING: Invalid Page`). Verify signed releases by actually
starting the bundled core with a temporary database and waiting for `READY`, not just
by checking its signature or `--version`.

Packaged builds receive one UTC CalVer for the whole make invocation in the form
`YYYY.M.DHHMMSS` (for example, `2026.8.16180542`). The Go core, standalone CLI,
Tauri bundle metadata, DMG filename, and footer all use that same value; development
runs identify themselves as `dev`. Set `BUILD_VERSION` to reproduce an exact artifact,
for example `make build-desktop BUILD_VERSION=2026.8.16180542`. The standalone wrapper
prints its embedded value with `omni-chat --version`. Cargo's `Compiling omni-chat-desktop v0.1.1`
line identifies the Rust shell crate, whose source version is independent of the release.
It does not identify the AppImage version. Each new `make build-linux` or
`make build-linux-docker` invocation generates a fresh UTC release version; all architectures
in one invocation share it. An explicit command-line or exported `BUILD_VERSION` pins that value
until removed (use `unset BUILD_VERSION` to clear an exported pin).

Both targets first run `make llama-sidecar`, which downloads the `llama.cpp` release pinned in
`desktop/llama.json`, verifies its SHA256 and keeps `llama-server` plus the libraries it actually
links in `desktop/vendor/llama/` (git-ignored, ~23 MB). It needs the network once, then no-ops until
the pinned tag changes — the same discipline `web/runtimes.json` uses for the Pyodide assets. To bump
the version, edit the tag, run the target, and paste the checksum it reports.

The bundle targets are `app` and `dmg`, so a build produces both:

```
desktop/target/release/bundle/macos/OmniChat.app              # ~89 MB
desktop/target/release/bundle/dmg/OmniChat_<UTC-CalVer>_aarch64.dmg  # ~54 MB
```

**The DMG bundler needs macOS Automation permission the first time.** It drives Finder over
AppleScript to lay out the disk-image window, and on a machine that has never granted that it
*hangs* rather than failing — including on CI and in an SSH session with no desktop. `make check`
and `make build` never touch Rust, so this only affects `make build-desktop`. If it stalls at
`Running bundle_dmg.sh`, grant Terminal (or your IDE) control of Finder under System Settings →
Privacy & Security → Automation. Desktop builds enable verbose output so a failed
`bundle_dmg.sh` reports the underlying command error.

If compilation succeeded but packaging failed, retry just packaging from `desktop/`,
using the **same version printed by the build** and the same `APPLE_SIGNING_IDENTITY`:

```sh
cd desktop
cargo tauri bundle --bundles app,dmg --verbose --config \
  '{"version":"2026.9.20220039","bundle":{"macOS":{"bundleVersion":"2026.9.20220039"}}}'
```

If the error is in Finder/AppleScript, prefix that command with `CI=true` to skip
the Finder window layout (the app and Applications shortcut are still included).
This does not fix disk-image creation, mounting, or signing errors; use the verbose
error to diagnose those. Notarization being skipped is a separate warning.

### Sharing a build with someone else

Send the `.dmg` — it is self-contained. It carries the shell, the Go core (with the SPA embedded),
the `omni-chat` launch CLI, and the bundled `llama-server`; the recipient needs no repo, no
toolchain and no config file. The core starts with an empty config directory, so they create the
owner account and add endpoints from **Settings** inside the app. The one-line installer also
symlinks the CLI onto `PATH`; a drag-install of the DMG does not.

Three things to tell them, or it will look broken:

- **Apple Silicon, macOS 26+.** The app binaries are `arm64`-thin and the bundle declares a
  minimum system version of 26.0, so an Intel Mac or an older macOS cannot run it.
- **Gatekeeper will block it.** The build is ad-hoc signed (see below), so first launch needs
  System Settings → Privacy & Security → **Open Anyway**, or
  `xattr -dr com.apple.quarantine "/Applications/OmniChat.app"`.
- **macOS may ask for keychain access.** API keys live in the OS keychain, and an ad-hoc signature
  is regenerated on every build — so each new build looks like a different app and asks again.

Docker (for SearXNG and the agent's `docker` runtime) and Pi (for the agent's host runtime) are
*not* bundled and stay optional; the features that need them report themselves unavailable rather
than breaking the app. Background models work out of the box.

Where the app keeps things:

| What | Path | Notes |
| --- | --- | --- |
| Config | `~/.config/omni-chat/` | The same directory the core uses in web mode, so one machine has one config. |
| Database | `~/Library/Application Support/omni-chat/app.db` | Separate from the repo's `data/app.db`, so the desktop app has its own accounts and chats. |

Because the database is separate, the first launch shows the **Create the owner** setup screen even
if you already have an account in a web-mode instance.

Builds are **ad-hoc signed by default**. Set `APPLE_SIGNING_IDENTITY` as above to sign
with an installed certificate. Apple Development signing is for local development;
normal distribution outside the App Store requires Developer ID signing and notarization.
The auto-updater is not set up yet.

## Desktop app (Linux AppImage)

OmniChat is published for native `x86_64` and `aarch64` Linux desktops as a single AppImage per
architecture. The package carries the Tauri shell, Go core with embedded SPA, and the `omni-chat`
launch CLI. Models, inference servers and Docker remain external and optional; unlike macOS, Linux
does not bundle `llama-server`, because the existing PATH/Docker fallback can match the host's GPU
drivers.

At first use, the shell materializes its embedded Go core and CLI as private, content-addressed
executables under `${XDG_CACHE_HOME:-~/.cache}/omni-chat/appimage-runtime`; they remain part of the
one downloaded and verified AppImage and require no system-wide installation.

Run the one-line installer to verify the SHA-256, install the AppImage as
`~/.local/bin/omni-chat-app`, add a desktop-menu entry, and point
`~/.local/bin/omni-chat` at the same file:

```bash
curl -fsSL https://geekaholic.gitlab.io/omni-chat/install-linux.sh | bash
omni-chat-app       # GUI
omni-chat launch pi # bundled CLI, while the app is running
```

You can also find immutable, versioned AppImages in the project's
[GitLab package registry](https://gitlab.com/geekaholic/omni-chat/-/packages). A direct portable
download opens the GUI; create an `omni-chat` symlink to the file if you also want its multi-call
CLI.

Published compatibility starts at Ubuntu 24.04 and is smoke-tested on Debian 13, current Fedora,
and a current rolling distribution. The desktop session must provide a Secret Service
implementation such as GNOME Keyring or KWallet for endpoint keys; OmniChat never falls back to
plaintext storage.

WebKitGTK, its matching helper processes and injected library are bundled. They resolve inside
the AppImage on Arch/CachyOS as well as Debian/Ubuntu; installing a host WebKit package is not
required and cannot repair an incomplete bundle. The final packaging step relocates WebKit's
compiled-in Ubuntu paths after all linuxdeploy passes and rejects missing helpers.

The host supplies the Wayland, xkbcommon and XCB display libraries, along with Mesa/EGL and
the graphics driver. Final packaging removes build-host copies of those display libraries:
older bundled Wayland libraries can cause an `EGL_BAD_PARAMETER` abort and a black window
on rolling distributions such as CachyOS ([upstream report](https://github.com/tauri-apps/tauri/issues/15976)).
GTK/WebKit and their matching helpers stay bundled. Hardware acceleration and the desktop's
Wayland/X11 selection are retained.

On Raspberry Pi 4, 400 and 5, WebKit's default DMA-BUF path draws a garbled window on the
Broadcom V3D driver, so the launcher sets `WEBKIT_DMABUF_RENDERER_FORCE_SHM=1` when it detects
that driver. Other graphics drivers are unaffected. To try the default path, for example after
an update, launch with `WEBKIT_DMABUF_RENDERER_FORCE_SHM=0 omni-chat-app`.

For an older affected AppImage on Arch/CachyOS, this temporary per-launch workaround uses
the host's Wayland client library:

```bash
LD_PRELOAD=/usr/lib/libwayland-client.so.0 omni-chat-app
```

Updated packages do not need that override. Messages about optional
`colorreload-gtk-module` or `window-decorations-gtk-module` integrations are separate from
the fatal EGL error; installing a second WebKit runtime is not the fix.

Before opening the GUI, the launcher checks the bundled files and their shared-library
dependencies; desktop-menu failures also show a KDE/GNOME dialog when kdialog or Zenity is available.
The installer performs the same check without FUSE or a display before replacing
an existing installation. For manual diagnostics or an explicit native-package-manager repair:

```bash
omni-chat-app --check-dependencies
omni-chat-app --install-dependencies
```

Known missing host graphics libraries produce commands for Arch/CachyOS (`pacman -Syu --needed`),
Debian/Ubuntu (`apt-get`) or Fedora (`dnf`). Installation happens only with
`--install-dependencies`, uses sudo when necessary, and retains the package manager's normal
confirmation prompt. The download installer also accepts that flag:
`curl -fsSL https://geekaholic.gitlab.io/omni-chat/install-linux.sh | bash -s -- --install-dependencies`.
Unknown libraries are reported by name; missing bundled files require reinstalling OmniChat.
An older glibc requires a distribution update (these builds need glibc 2.39+).
If the AppImage runtime itself reports missing FUSE, run
`omni-chat-app --appimage-extract-and-run --check-dependencies` (or use that runtime option to
launch the GUI). That failure occurs before the bundled launcher can run.

### Building and publishing Linux packages

Build each architecture with Ubuntu 24.04 target-architecture tools and the same explicit CalVer.
Use native hardware or the Docker/QEMU workflow below; building on a newer glibc silently drops
older distro compatibility.

```bash
cargo install tauri-cli --version "^2" --locked
make check-linux-prereqs
make build-linux BUILD_VERSION=2026.9.1120000
```

Native packaging also requires Python 3 and `squashfs-tools` for final relocation, validation
and assembly; the Docker builder includes both. The packaging regression tests in `make check`
also use Python 3. Python is not required on installed desktops.

The AppImage bundles the GStreamer audio plugins listed in `tools/linux-gstreamer-plugins.txt`
(without them, WebKit crashes the window the first time it plays sound). Native builds need
`gstreamer1.0-plugins-base`, `gstreamer1.0-plugins-good` and `gstreamer1.0-alsa`;
`make check-linux-prereqs` names any missing plugin, and the Docker builder installs them.

On other Linux distributions, including Omarchy, or on macOS with Docker Desktop, use the bundled
Ubuntu 24.04 builder:

```bash
make build-linux-docker
# Optional: use the same version for both architecture builds.
make build-linux-docker BUILD_VERSION=2026.9.1120000
```

This requires Make and a working local Docker daemon accessible by your user (on macOS, Docker
Desktop with at least ~10 GB free in its disk image; Settings > Resources). The target checks
Docker access and the daemon's Linux disk space first, builds/reuses `docker/build-linux/Dockerfile`, and supplies Go, Node, Rust, Tauri,
and the native libraries inside the container. The first run downloads and compiles the tools;
later runs reuse Docker layers and dependency caches. The build containers need no FUSE device or
privileged mode. Builds run with your UID/GID and use separate Rust/npm caches, preserving the host's
`desktop/target` and `web/node_modules` directories. Generated Go sidecars and web assets still
use their normal checkout paths; do not run native and Docker builds concurrently in one checkout.
The builder refuses to start with less than 4 GiB free on Docker's Linux filesystem; keep
about 10 GB or more available for cold builds and `LINUX_ARCH=all`. Host filesystem free space
is separate from Docker Desktop's disk limit. If apt reports invalid repository signatures,
check Docker disk space first: a full disk can prevent signature verification. Free unused
build cache or increase Docker Desktop's disk limit, then retry; keep apt signature checks enabled.
The build script never prunes caches, images or volumes automatically.
Temporary registry connection failures while resolving base-image metadata (such as `EOF` or
timeouts) get up to three attempts, with 2- and 4-second delays. Other build failures stop
immediately. If registry access still fails, check Docker Desktop's network/proxy/VPN settings
and Docker Hub connectivity, then rerun the same command; existing build caches are reused.

On macOS, Docker Desktop's file sharing enforces host permission bits, which breaks linuxdeploy's
library copies, so the Rust target and AppDir live in the Docker volume
`omni-chat-linux-target-<arch>` and only the finished AppImage is written back to the checkout
(`docker volume rm omni-chat-linux-target-amd64 omni-chat-linux-target-arm64` reclaims the space).

The default target is the host's native architecture. To build x86_64 on ARM64, or ARM64 on
x86_64, select `LINUX_ARCH=amd64` or `LINUX_ARCH=arm64` (`x86_64` and `aarch64` aliases also work).
`LINUX_ARCH=all` builds both sequentially with one `BUILD_VERSION`.
The frontend builds in a native Node/Go Docker stage, which also cross-compiles the pure-Go
sidecars for the selected architecture. Rust compilation and linuxdeploy's ELF dependency step run
in the target Ubuntu userspace under QEMU. The native stage then creates the target AppImage from
linuxdeploy's completed AppDir and target runtime, avoiding the target AppImage plugin on
large-page ARM64 hosts. npm caches live in `.cache/linux-docker/assets-<host-arch>/`; Rust caches
and AppImages remain in `.cache/linux-docker/<target-arch>/`.
Before building, the wrapper checks that Docker can execute the target Ubuntu image.
The packager uses Ubuntu's versioned Rust 1.91 packages to avoid the rustup compiler's allocator
crashes under x86_64 emulation, and runs a compile/link/run smoke test before installing Tauri.
No special QEMU or Node environment settings are required. If QEMU/binfmt is missing, register
the handlers on the host once:

```bash
docker run --privileged --rm tonistiigi/binfmt --install amd64,arm64
```

That setup command changes host executable handlers and is never run automatically by Make.
Docker Desktop for macOS already ships amd64 emulation, so no binfmt setup is needed there.
Enable Settings > General > Use Rosetta for x86_64/amd64 emulation (Apple Virtualization
framework only): an incremental amd64 rebuild dropped from about 13 minutes under QEMU to about 2.
See [Docker's QEMU documentation](https://docs.docker.com/build/building/multi-platform/#qemu).
Emulation can be much slower for compilation and compression. Build both targets with the same
version, then publish. Without explicit paths, the publisher picks the newest x86_64 AppImage
and the aarch64 AppImage of the same version:

```bash
make build-linux-docker LINUX_ARCH=all
GITLAB_DEPLOY_TOKEN=your-deploy-token make publish-linux
```

The resulting AppImage is in `.cache/linux-docker/<amd64|arm64>/target/release/bundle/appimage/`,
according to the selected target. If the Docker access check fails, start the daemon and check
your Docker context and socket permissions, then rerun the target.

For native builds on two machines, collect the resulting `amd64` and `aarch64` files, then
publish the pair atomically:

```bash
GITLAB_DEPLOY_TOKEN=your-deploy-token make publish-linux \
  APPIMAGE_X86_64='/path/OmniChat_2026.9.1120000_amd64.AppImage' \
  APPIMAGE_AARCH64='/path/OmniChat_2026.9.1120000_aarch64.AppImage'
```

Tokens work as for `make publish-macos`: `GITLAB_DEPLOY_TOKEN` with `write_package_registry` is
preferred, then `GITLAB_TOKEN` with the `api` scope, then CI's `CI_JOB_TOKEN`.
The publisher uploads immutable AppImages and checksums to GitLab's generic package registry, then
updates only the Linux section of `downloads/latest.json`; GitLab Pages serves that small manifest to
the installer. Linux and macOS releases may therefore advance independently. Signing, auto-update and
automatic release builds are not yet configured.

### Starting local services from inside the app

The desktop **Settings → Local services** page can start two optional sidecars
for you, so a fresh install is not stuck with search and background intelligence switched off:

| Service | What it needs | What it unlocks |
| --- | --- | --- |
| **Web search (SearXNG)** | Docker | `web_search` and `search_images` |
| **Background models (llama.cpp)** | Nothing on macOS — `llama-server` is bundled | Chat titles, memory extraction, rolling summaries, semantic routing |

Starting a service also writes the config that points the core at it, so it asks for a restart
afterwards — the core reads its configuration once at startup.

The background service hosts one ~700 MB model (`LiquidAI/LFM2.5-1.2B-Instruct`).
It handles chat titles, memory and semantic routing by default, with no separate router model.

Weights download into `~/Library/Application Support/omni-chat/models/` with visible progress, and
are resumable.

**Test background models** runs one real request per configured model and reports each as ready in
green or not ready in red, with a timing. It is the only honest readiness signal, because **Running
does not mean loaded**: router mode loads a model only when a request names it, and the service
probe uses `/health`, which answers 200 with nothing resident. The first test is therefore slow — it
includes reading the weights off disk, a few seconds on a cold machine — while later tests come back
in milliseconds. The test never downloads anything; that is what Start does. With a dedicated router
classifier configured you get a row per model, so a failure tells you which of the two is wrong.

The macOS app **ships its own `llama-server`** (23 MB, in `Contents/Resources/llama/`), so background
models work on a Mac with neither Docker nor Homebrew installed. A native binary is always preferred
over a container because containers on macOS never see the GPU, and the bundled build is
Metal-enabled. Resolution order is the bundled binary, then `llama-server` on `PATH`, then Docker —
so a Linux build with no bundled binary still works through a container.

Managed services can create an optional-service-only `endpoints.json`; no remote chat endpoint is
required first. This matches the iPad configuration, where `@on-device` is injected at runtime and
is deliberately absent from the file.

Managed services **survive config saves but stop when you quit the app**. The core restarts on
every config save, so a loaded model deliberately survives those restarts rather than reloading
several hundred megabytes each time you edit something. Quitting is different: everything the app
started — the model server and its `omni-managed-*` containers — is stopped with it, so nothing
keeps eating memory after the app is gone. State is still discovered by probing, so a SearXNG you
started yourself with `compose.search-only.yaml` shows here as running — but quitting leaves it
alone: only what the app launched is stopped, and a leftover from a force-killed session is picked
up and stopped at the next session's quit. This applies to dev runs too: `Ctrl-C` on
`make dev-desktop` stops the services it started.

On macOS, an off-by-default **Keep running in background** setting (under **Settings →
Desktop**) changes what closing the window means: the window hides, the app stays visibly in the
Dock, and the services keep running — useful when a model server should stay warm. A Dock click
brings the window back; quitting from the Dock or with `⌘Q` still stops everything. iPhone and
iPad use **Options → Background generation** for a different job: keeping the current reply
scheduled after you leave the app.

The GPU-bound sidecars — image generation, TTS, STT — are deliberately **not** managed. A container
cannot reach the GPU on macOS, so a one-click container there would be unusably slow while looking
supported; those keep their documented native and remote-host paths.

### Editing endpoints from inside the app

OmniChat can edit `endpoints.json` itself — in the desktop app and, for admins, in the web app —
so getting running doesn't mean copying `docs/endpoints.example.jsonc` and hand-editing JSON. Open
the user menu → **Settings** (every user can open it). **Admins** (the owner, plus anyone an admin
grants it to with the **Admin** switch in Members) edit everything; everyone else gets
**Integrations** and a read-only view of the servers, model assignments and web tools — never
their URLs or keys. On the web, saving restarts the server in place and typed API keys are stored
in the server's `endpoints.json` (there is no Keychain); under Docker the `./config` mount must be
writable by the container user, uid 10001 (the default `compose.yaml` mounts it read-write — on
Linux run `sudo chown 10001:"$(id -g)" ./config && sudo chmod 775 ./config` once; add `:ro` to
lock web saving off).
**Settings → Integrations → Enable third-party integrations** is off until you approve its
shared disclosure. ChatGPT and MCP settings remain visible but disabled until approval, including
adding/editing servers, account controls and usage management. Cancelling the notice keeps them
disabled; turning the switch off disables them again. One approval per account covers ChatGPT (OpenAI) and the MCP connections you
choose to use, including later additions. It lists chat content, relevant history, enabled
profile/location/memories only when opted in, attachments and MCP tool arguments; tool results may go to the selected chat
provider. Configured MCP recipients are listed by name and host (or local process). The notice
asks **Send chats to OpenAI?** when no MCP servers are configured, otherwise
**Send data to OpenAI and your MCP servers?**. Without configured MCP servers, it explains
that later MCP additions are covered and omits the MCP request category from the sharing list.
Approval persists across restarts and connection toggles. Turning it off immediately blocks future
ChatGPT requests and MCP tool calls while keeping configurations and sign-ins. Provider OAuth
and MCP tool-action confirmations still apply. On-device chat and manual AI Server approvals
remain separate.

The sharing API records a separate `personal_context` choice for each approved AI Server
destination and for Integrations. Existing approvals retain an on choice; new approvals start
off. Sharing PUT requests accept optional `personal_context`; omitting it preserves the current
choice. Revoking then approving again, or approving a changed server destination, resets it off.
Config saves can opt in with `sharing_personal_context: ["connection-name"]`; each name must also
be in `sharing_approvals`, or the save returns `400 invalid_sharing_approval`. These choices belong
to the signed-in account and are stored in SQLite, separately from `endpoints.json`.
When a destination's choice is off, the core withholds the account profile, location, memories
and cross-chat recall from its turns, including turns resolved by Auto. A flag-read error also
withholds that context while allowing the approved chat to continue. Auxiliary consolidation
at a manual server's or ChatGPT connection's URL follows that destination's choice. Discovered network, on-device and voice
endpoints retain their existing personalization.
Sharing notices name known providers, such as OpenAI, and identify other server recipients as
“the operator of &lt;host&gt;”. An empty or invalid address asks you to enter the server address.
**Also share my profile, location and memories** starts unchecked for new approvals. Change an
approved server's choice in Settings → AI Servers with **Share profile, location and memories**;
the ChatGPT card in Settings → Integrations has the same switch, disabled while integrations are off.
Allowing the network search only lets OmniChat look; scanning sends no chats. Each server it finds
on another machine must then be approved by name, like a server you add, before its models appear
or it receives anything, with the same unchecked **Also share my profile, location and memories**
option. Approve found servers right after the first search, or later under **Approve servers** in
Settings → AI Servers, where an approved found server also has the **Share profile, location and
memories** switch. Servers on this device, such as Ollama on the same Mac, need no approval.
When no model is available, the composer's model picker offers a way forward (owners and admins
only): **Configure an AI server** opens Settings → AI Servers with the Add server form ready when
no server is saved, and **Check AI servers** opens that page when a saved server isn't answering. The voice weather tool has been removed; voice Search
uses web search and page fetching.

**Settings → Integrations** offers **Continue with ChatGPT**, an account picker, explicit plan-usage
consent, sign-out and a **Plan usage** card with **Manage usage** for the signed-in account.
Usage management appears only in Settings → Integrations → ChatGPT. It opens ChatGPT; sign in
there with the same connected account. Turn on *Use for Chat*, then Save & restart. Models come from
the selected account's live catalog; installing the Codex CLI is not required. It also manages MCP servers. Local services, Agent
handoff and Desktop stay desktop-app-only. Settings splits into **Models** ("Defaults for each job", listed first) and **AI Servers**
("Discover and manage servers"), followed by **Web & tools**, **Local services**, **Agent handoff**, and
**Desktop**. It opens on AI Servers when you have no saved servers yet, else on Models. On a
phone-width screen (820 px or narrower, e.g. an iPhone in portrait) the page list is a slide-in menu:
Settings opens with it showing, its × button closes it, and the ☰ button beside the page title brings it back.
The dialog stays inside the screen's safe areas in portrait and landscape; the page list and page content scroll independently on short screens. Server rows
there fold their status into a dot on the server-type tile plus a word on the address line.

**AI Servers** is where the servers themselves live. **Connections** lists what you've saved — each
row shows a status (Connected / Needs key / Unreachable / Unsaved), the label, URL, its "Used for"
chips, and a model count, with **Manage** expanding the full editor in place and a trash icon to **Remove**
retiring it — plus an **Add server** button for typing one in by hand. Below that (above it, when
you have no servers yet) is **Network discovery**: an auto toggle (servers on this machine are
always used, whatever the toggle says) and a **Scan now** button for an on-demand full pass — this
machine, named local hosts, and the attached network — regardless of the toggle. Scan now lists
every open server it finds with its model count, and a key-locked one as **Locked · needs API key**. Each server shows a lettermark tile for its detected **server type** (llama.cpp, vLLM, Ollama, LM Studio, oMLX, LiteLLM, SGLang, Kapitsa, OpenAI; a generic server glyph when unknown) next to its model count. A status dot on each result says where it stands: green **In use** (auto-discovery already offers its models in the picker) or **Saved**, orange **Needs key**, grey **Available**;
each result gets its own **Add connection** button, which opens the editor with the URL and a
suggested label already filled in — and, for a locked one, the key field focused so you can type it
straight in. The connection editor itself (Add server / Manage / add-from-scan) has a **Label** (an
internal id is derived once behind the scenes and never shown again — rename the label as often as
you like), **Base URL**, **Server type** (set by detection, or pick it yourself), **Authentication** (None / API key — ChatGPT sign-in lives in Integrations), and **Used for** switches —
Chat, Embeddings, Image generation, Read aloud, Voice input, at least one required. A server that
uses ChatGPT sign-in can only be used for Chat; other `protocol: "responses"` servers may also support Image generation —
the Embeddings, Read aloud, Voice input and Auxiliary clients send just a URL and key, so the core
refuses such a connection there and the editor hides unsupported uses. An already-selected
unsupported use remains visible so you can turn it off when correcting a draft.
Add server opens an isolated draft; dismissing an untouched form adds nothing and produces no warning. **Allow & Save** validates the details and keeps the server in Settings; **Save & restart** applies it. Base URL errors appear below that field after an attempted save; other required settings are validated inside the editor. **X** and **Not Now** discard the draft, asking for confirmation when entered details would be lost. Manage uses the same draft and discard behavior.

Immediately above **Test connection** and **Allow & Save**, a sharing card asks **Send chats to {recipient}?**, naming a known provider or **the operator of &lt;host&gt;**, and lists the selected features' data: messages/history, attachments, image prompts or audio as applicable. Profile, location and memories appear in the list only while **Also share my profile, location and memories** is checked; new approvals start unchecked. It explains recipient-controlled handling and links to the privacy policy.

Adding a chat, image-generation, read-aloud or voice-input server and choosing
**Save & restart** approves sharing with that destination
for your account. Existing unapproved servers have a one-time **Finish server setup** card in
**Settings → AI Servers**; review it and choose **Use this server**. Other users approve
separately. **Services → Chat backends** switches only show or hide models in your picker and
Auto routing; toggling them off/on never changes or repeats approval. Until setup is complete,
that server's models are unavailable. Changing its URL or protocol requires fresh approval;
labels, keys and model tuning do not. Model and health checks can still run.
The same approval covers image generation/editing, read-aloud text and submitted audio on that
saved connection, including media-only servers. The core checks before sending content and on
content-bearing HTTP retries; redirects cannot forward it to another server. Read aloud checks
again for every chunk, so revocation prevents later chunks. Already-approved chat destinations
reuse their approval. On-device speech needs no remote-server approval. Existing media-only
servers use the same Finish server setup card; no extra popup appears during use. Network
scanning and ChatGPT/MCP have their own saved approvals. Separate embedding and web-service
recipients still require review.

The built-in ChatGPT connection keeps its URL, server type, protocol and model identifiers managed:
URL, type and model fields are read-only, and the protocol editor is hidden. Its display name,
Chat switch and token/context limits remain
editable. Sign-in is managed in Integrations. Other API-key servers keep their editable connection fields.
Turning a use on reveals that job's settings inline (Chat: context window, max output, sampling, thinking, model
overrides; Image: model, carrier model, stream, timeout; Read aloud: model, voices, timeout; Voice
input: model, language, timeout), with an **Advanced** disclosure for `protocol`. **Test
connection** runs one check per enabled use and shows a row per use: Chat/Embeddings list models and
fill the model dropdowns; Image checks credential and reach *without* generating — the smallest
image the API offers is 1024×1024, which costs real money hosted and a GPU slot locally, so a
button that spent one on every press would be a trap; Read aloud synthesizes a short phrase and
*plays it*, because hearing it is the only way to know the voice is the one you wanted; Voice input
sends a half-second clip of generated silence and passes on a successful request, which proves the
route, key, and model id without needing anything to actually be heard. Saving works even when a
test fails or was never run, with a warning.

**Models** holds the *default* for each job — each select lists only connections tagged with that
chip on AI Servers. **Default chat server** picks a server only (no model; the model you used last
still wins on a new chat). **Auxiliary** is On-device / Managed (the Local services llama.cpp) / a
connection + model for chat titles, background memory work and long-chat summaries. Selecting a
remote auxiliary server automatically loads its models into a compact model picker. The adjacent
refresh icon reloads the list and has a **Refresh models** tooltip.
Assigning a remote model to Aux also keeps it in that server's normal chat list (when the server
is enabled for Chat), available for manual selection and Auto routing. The **Show in model picker**
switch controls only the extra Auxiliary group entry.
Saved model selections are preserved if the server is unavailable or no longer lists
them. On-device and Managed selections work as before. Auxiliary also has the
default-on **Use for Smart Router** and **Show in model picker** switches — **Test** sends one real
completion against the unsaved values, so a bad key or model id is caught before Save and restart,
and never starts a service or downloads weights. **Embeddings** is a connection + model + dimension,
with a warning about replacing memory embeddings; stale memory and summary vectors are refreshed in bounded batches on access. **Image generation**, **Read aloud** (plus
a default voice), and **Voice input** each pick a default connection the same way. A job with no
tagged connection shows "No servers are set up for this — add one in AI Servers" instead of an empty
select. Removing on AI Servers a connection that a Models default still points at is blocked at
Save, and the problem message names — and clicking it opens — whichever page fixes it.

The same app also configures **web search** and **web fetch** (under Web & tools), which were
previously environment-only and therefore unreachable in a bundled app:

- **Web search** — Tavily (hosted, paste a free API key, nothing to run) or SearXNG (self-hosted,
  give it a URL). **Test search** runs one real query so a bad key or a SearXNG without JSON output
  enabled surfaces immediately. SearXNG also enables `search_images`; Tavily has no image search.
  On iPad, Tavily can be saved with an empty remote-endpoint list and used by the injected
  `@on-device` model.
- **Web fetch** — a single switch enabling `fetch_url` and `fetch_image`. The default provider runs
  inside the core, so nothing else has to be running.

A ChatGPT connection is managed in Integrations. The admin selects the active ChatGPT account;
that credential is still shared by this OmniChat instance, like an instance API key. Use it only for
your own local or privately self-hosted runtime, not as a public subscription pool. iOS uses a local
single-person instance. Other API-key connections retain their own credentials.

This is native-shell-only by design. `GET`/`PUT /api/config` return `501 not_implemented` unless the
core was started with `CHAT_DESKTOP=1`, which only the Linux, macOS and iPad Tauri shells set. A shared web
instance therefore never exposes instance config, connection keys, or the ability to repoint the app
at another backend.

Saving is authoritative only over the sections the form sends: `connections` (like `endpoints`,
search and fetch) always moves, because every client that speaks schema 2 renders it, while
`images`/`tts`/`stt`/`aux`/`embeddings`/`discovery` move only when the client actually sent them.
Older clients that omit `aux` leave the background-model section untouched; the Models form can
replace it or explicitly turn it off. The advanced `router_model` is preserved for user-configured remote services.
Managed background services clear that field and use their one instruct model for routing. A connection's key never round-trips to the client — `GET` redacts
it to `api_key_set`, and saving without touching it keeps what's on disk.

Saving does three things in order: writes any new API key to the **OS secure store**, writes the
config file, then restarts the core. The restart is the whole apply mechanism — the core reads its
configuration once at startup — and it ends any answer in progress.

**Keys go to the platform secure store, not the file.** `endpoints.json` stores only `api_key_env`, the name of an
environment variable; the shell reads the value from Apple Keychain or Linux Secret Service and injects it when it spawns the
core. That satisfies the "endpoint API keys live in the OS keychain" rule with no change to the core,
which has always supported `api_key_env`. Two consequences worth knowing:

- The **first** launch after storing a key raises a macOS permission prompt, because the app's
  signature is unfamiliar — and an ad-hoc build gets a new signature every time it is rebuilt, so
  during development this recurs. The launch is not blocked: the shell waits ten seconds, then starts
  the core without the stored keys, and the affected endpoint shows as degraded until the next launch.
- A core started **outside** the shell (web mode, Docker) reading the same `endpoints.json` will not
  have those variables set, so those endpoints have no key there. Keys already inline in the file keep
  working everywhere; the UI shows them as "Stored in this file, in plain text" and offers to move
  them.

`endpoints.json.bak` keeps the last known good config. It updates only after an admin successfully
loads the authenticated app; saving repeatedly or failing to start leaves it untouched. A config
the core would refuse to boot on is rejected before the file is touched — the real config decoder
validates it, not a copy.

If the core fails to start — most often an invalid file in `~/.config/omni-chat/` — the window stays
on the shell's own splash page and shows the core's output instead of a blank screen, with
**Try again** and **Restore previous config** buttons.

Three things work differently from a browser, because the webview does not implement them:

- **Confirmations are drawn by the app**, not the OS. `window.confirm`/`prompt` never appear in the
  desktop webview, so Archive, Delete chat, New project and discarding a temporary chat use an
  in-app dialog — the browser now uses the same one, so both shells behave identically.
- **Saving a file opens the macOS save panel.** The webview ignores the browser download mechanism,
  so chat exports and code-block downloads go through the shell. The webview cannot
  print either, so **Save as PDF** (share menu) and **Export PDF** (a response's `⋯` menu) are
  rendered by the core instead and saved through the same panel. On iPhone and iPad the same
  exports open the system share sheet (Save to Files, Mail, AirDrop and the rest) with the
  finished file.
- **Links open in your default browser.** The webview cannot open a tab, so citations, source cards
  and links in a reply are handed to the OS instead — which is also how OAuth sign-in works. Only
  `http`/`https` are ever opened, and only to another origin: the app's own links (an attachment, for
  instance) stay inside, because the browser has no session for the local core.

Archiving a chat hides it rather than deleting it. Turn on **Show archived** in the sidebar filters
to see archived chats and unarchive them from Chat Details.

## Importing from ChatGPT

Bring your ChatGPT history into OmniChat with the `core import chatgpt` CLI subcommand. In
ChatGPT, go to **Settings → Data controls → Export data**; a download link arrives by email with a
zip file.

```bash
./.cache/bin/omni-chat-core import chatgpt ~/Downloads/chatgpt-export.zip --user alice
```

`<export>` accepts the export zip as downloaded, an already-unzipped export directory, or a bare
`conversations.json`. A bare JSON file has no attachments to pull from, so the importer prints a
note to stderr and continues without them. Both the classic single-`conversations.json` layout and
the newer sharded layout (`conversations-000.json`, `conversations-001.json`, … plus `.dat` assets
with a `conversation_asset_file_names.json` restoring their original names) are supported.

Flags:

| Flag | Effect |
| --- | --- |
| `--user <username>` | target omni-chat username (required) |
| `--db <path>` | SQLite database path (defaults to `$CHAT_DB_PATH` or `data/app.db`) |
| `--skip-attachments` | opt out of importing images/files referenced by messages |
| `--skip-memories` | opt out of importing ChatGPT memories |
| `--skip-archived` | opt out of importing conversations archived in ChatGPT |
| `--dry-run` | parse the export and print the report without writing anything |

For each conversation the importer takes the **active branch only** — exactly what you last saw in
ChatGPT, not every edited-away alternative. It imports the title, timestamps, user/assistant
messages, reasoning ("thoughts") folded into the following assistant message, images/files as
attachments, and archived state; every imported chat gets a `chatgpt` tag. ChatGPT memories (bio-tool
writes) are harvested into your user-scope memories, deduplicated against what's already there.
Tool-call plumbing (code execution, browsing traces, canvas) is not imported and is counted in the
summary.

Re-running the import against a newer export is incremental: conversations that haven't changed are
skipped, conversations that grew in ChatGPT get only their new messages appended, and conversations
whose active branch changed (an edit that switched branches) are skipped with a warning — existing
messages are never rewritten or deleted. It's safe to import while the server is running (SQLite
WAL). Imported chats have no model/endpoint set, so they pick your default model the next time you
use them.

### Importing under Docker Compose

When OmniChat runs via `docker compose`, the same binary is the container's entrypoint, so the
import runs as a one-off container that shares the service's database volume and env:

```bash
docker compose run --rm \
  -v "$PWD/chatgpt-export.zip:/import/export.zip:ro" \
  omni-chat import chatgpt /import/export.zip --user alice
```

`docker compose run` reuses the service's `CHAT_DB_PATH=/data/app.db` and the `omni-chat-data`
volume, so no `--db` flag is needed and the import lands in the same database the server uses —
safe to run while the service is up. Bind-mount the export read-only at a fresh path such as
`/import/…` (avoid `/tmp`, which the service config covers with a small tmpfs). All the flags above
work the same way; add `--dry-run` first if you want a report before writing anything. If the image
predates the import feature, rebuild it with `docker compose build`.

## Resetting a forgotten password

OmniChat has no email or self-service reset; passwords are stored only as argon2id hashes. Reset a
forgotten password on the machine that holds the database, with the `reset-password` command. It
needs the database file, which already grants full control of the instance, so it adds no new way
in. It asks for the new password (at least 8 characters) twice, writes the new hash and signs that account out everywhere.
It is safe while OmniChat is running.

```bash
omni-chat reset-password --user alice                               # desktop app (macOS or Linux)
docker compose run --rm omni-chat reset-password --user alice      # Docker Compose
./.cache/bin/omni-chat-core reset-password --user alice --db core/data/app.db   # server or source build
```

- **Desktop app:** the `omni-chat` command that the macOS and Linux installers put on `PATH` hands
  off to the core inside the app. On macOS without that command, run
  `"/Applications/OmniChat.app/Contents/MacOS/core" reset-password --user alice`.
- **Database:** the first of `--db`, `$CHAT_DB_PATH`, `data/app.db` in the current folder, then
  the desktop app's database (`~/Library/Application Support/omni-chat/app.db` on macOS,
  `${XDG_DATA_HOME:-~/.local/share}/omni-chat/app.db` on Linux). It never creates a database, and
  prints the file it is changing before asking for the password.
- **Username:** must match exactly, as at sign-in. A wrong name lists the accounts in that
  database.
- **Disabled accounts:** still can't sign in until an admin enables them again under Members.
- **Scripts:** without a terminal, the new password is the first line of stdin, e.g.
  `printf '%s\n' "$NEW_PASSWORD" | docker compose run --rm -T omni-chat reset-password --user alice`.
- **iPad and iPhone:** the built-in core has no terminal. For an account on a server the device
  signs in to, run the command on that server.

## Backing up and restoring

`backup` writes one file holding the whole instance: every account's chats, attachments, memories,
projects, skills and settings, plus OmniChat's own config files (`endpoints.json`, `profiles.json`,
`router.json`, `agents.json`, `mcp.json`, `SOUL.md`, `skills/`, `token.key`, `sftp_host_key`). It is
safe while OmniChat runs.

```bash
omni-chat backup --out ~/Backups                                                    # desktop app
docker compose run --rm -v "$PWD/backups:/backups" omni-chat backup --out /backups  # Docker Compose
./.cache/bin/omni-chat-core backup --out /var/backups/omni-chat                     # server or source build
```

- **Not included:** login sessions (everyone signs in again), agent workspace folders, downloaded
  models (they download again), and secret values. The summary lists the secret names
  (`api_key_env`, `token_env`, MCP `env:NAME`) to re-enter after a restore.
- **Config allowlist:** only those files are read. Anything else in the config folder (`.bak`
  copies, unrelated files) is reported as skipped. Symlinks are never followed.
- **File:** `omni-chat-backup-<UTC time>.tar.gz`, written owner-only. It never overwrites an existing
  file. `manifest.json` inside lists every file's size and SHA-256.
- **`--encrypt`:** asks for a passphrase (or reads the first line of stdin) and writes
  `….tar.gz.age`. `age -d` can open it without OmniChat. A forgotten passphrase cannot be
  recovered.
- **Docker on Linux:** the container runs as uid 10001, so create the host folder writable by it
  first: `mkdir -p backups && sudo chown 10001 backups`. Docker Desktop on macOS needs nothing.

To restore, quit OmniChat. On macOS with **Keep running in background** on, closing the window
leaves it running, so use ⌘Q or Dock → Quit. Then:

```bash
omni-chat restore ~/Backups/omni-chat-backup-20261017T183000Z.tar.gz
docker compose stop omni-chat   # Docker: stop the service first, then restore, then start it again
docker compose run --rm -v "$PWD/backups:/backups" omni-chat restore /backups/omni-chat-backup-….tar.gz
docker compose start omni-chat
omni-chat-core restore backup.tar.gz --db /srv/omni-chat/app.db
```

- **Checks first:** restore verifies the whole file (checksums, database integrity, schema) before
  changing anything. It refuses a backup from a newer OmniChat.
- **OmniChat must be stopped:** every running core holds a shared lock on `<database>.lock`, and
  restore refuses while one is held.
- **Existing data:** restore stops if OmniChat data already exists. `--force` renames each existing
  file to `<name>.before-restore-<UTC time>`; nothing is deleted.
- **Database location:** the first of `--db`, `$CHAT_DB_PATH`, an existing `data/app.db`, then the
  desktop app's location. A fresh server needs `--db`.

## Configuration

Core runtime config:

Native apps (desktop and iPad) default to network discovery, but wait for your first approval before scanning. Under
**Settings → AI Servers → Network discovery**, the auto toggle applies through **Save & Restart**.
Turning it off keeps same-device discovery and manually configured connections. The optional
`endpoints.json` section `"discovery": {"mode": "lan"}` accepts `lan`, `local`, or `off`;
`off` disables all automatic discovery. A saved `off` survives unrelated settings edits.
`CHAT_ENDPOINT_DISCOVERY` overrides the file and disables the toggle with an explanation.
Standalone servers now default to `local`: operators can set `discovery.mode` or
`CHAT_ENDPOINT_DISCOVERY=lan|local|off`, then restart. No settings UI is exposed on servers.
The same AI Servers page also has a **Scan now** button for an on-demand full pass (this machine,
named local hosts, and the attached network) regardless of the auto toggle, which also surfaces
servers locked behind an API key — see [Editing endpoints from inside the app](#editing-endpoints-from-inside-the-app).
A file with only `"schema_version": 2, "discovery": {...}` and no `connections`/`endpoints` is
valid; discoveries stay ephemeral either way.

Both auto discovery and Scan now sweep only the machine's own private-network interfaces
(RFC 1918/4193) and mDNS-named `.local` hosts — a server reachable only over an overlay network
such as Tailscale (its 100.64.0.0/10 range doesn't count as "private" here, and it isn't
mDNS-advertised) will not show up in either. Add it by its reachable address with **Add server**
instead.

A fresh desktop or iPad install doesn't search the network while you create the owner account, so
the system's Local Network prompt never appears before setup. Right after setup, a card explains the
search and what chat data may be shared: **Allow & scan** turns on network discovery and searches right away (on macOS and iPad
the OS may ask for Local Network access first). The card shows the search and what it found, or
offers **Search again** when nothing answered; **Continue** is always available. The result is
recorded as the Settings → AI Servers scan, so that page shows "Last scanned …" and the same servers.
**Not now** saves `"discovery": {"mode": "local"}` — turn it on later under Network discovery or
use Scan now. Onboarding, the first later enable of automatic discovery, and the first **Scan now**
share the Add Server data-sharing notice, titled **Find and use AI servers on your network?**.
Approval is stored as `discovery.network_approved: true` in `endpoints.json`, independently of
`discovery.mode`, and survives restarts and off/on changes. Not now, X and Escape leave scanning
off. Settings approval alone does not enable background discovery; **Save & restart** applies
the toggle. Native installations without recorded approval hold automatic LAN discovery until
answered, including older installations. An explicit operator environment override keeps precedence.
Scan now probes servers it already knows before sweeping the network, so a server
that answers slowly during the sweep is still listed.

On iPad, Allow the Local Network prompt to discover LAN model servers. After a denial,
open **Settings → Privacy & Security → Local Network → OmniChat**, enable access, and return.
Taking a photo opens the camera on that tap, and iOS asks for Camera access as part of opening it.
Denying it leaves OmniChat open and offers an existing photo or file instead. Dictation asks for Microphone and Speech Recognition.
Those prompts are the permission dialogs; without the usage strings in the iOS app, iOS quits
OmniChat instead of asking.
The core retries without a restart, pauses LAN work while inactive, and refreshes interfaces on
resume. Initial active scans retry every five seconds for a minute, then every 60 seconds;
scans never overlap. Bonjour names use Apple's DNS-SD APIs; servers without advertisements
remain discoverable by IP through the bounded IPv4 scan. No multicast entitlement is required.

Model discovery groups verified aliases of the same host and port when their complete model
catalogs match, keeping all models under one endpoint. This covers native interfaces and DNS
aliases such as Docker's `host.docker.internal`; the container and Docker host stay distinct.
Configured chat backends take precedence, saved interface selections continue to resolve, and
an auxiliary entry does not hide the server's full catalog. Identical model IDs on different
machines remain selectable. Addresses without a discoverable host relationship remain separate.
The picker refreshes every 2s while the first LAN scan is still running so newly found servers
appear without a reload. Hostname labels come from Go mDNS reverse-PTR (not `/usr/bin/dig`).

| Variable | Default | Notes |
| --- | --- | --- |
| `CHAT_BIND` | `127.0.0.1` | Bind address. Use `0.0.0.0` only when intentionally sharing the instance. |
| `CHAT_TRUST_PROXY` | `false` | **Required upgrade behind a reverse proxy:** set `true` or `1` and restart to honor forwarded scheme/host and the validated right-most client IP. Off for every bind address; direct TLS sets secure cookies independently. See [the upgrade step](#required-upgrade-for-reverse-proxy-deployments). |
| `CHAT_PORT` | `0` | `0` chooses an ephemeral port and prints it in the `READY` line. |
| `CHAT_DB_PATH` | `core/data/app.db` when run via `make dev` | SQLite database path. |
| `CHAT_LOG_FILE` | unset in web mode; desktop sets its app log path | Optional core log file, alongside stderr. Keeps three files total: active plus `.1` and `.2`, each up to 5 MiB. |
| `CHAT_ENDPOINT_URL` | unset | OpenAI-compatible endpoint base URL. Accepts a comma-separated list to combine multiple backends (each shares `CHAT_API_KEY`). Ignored when `endpoints.json` is present. When unset, OmniChat also scans loopback and the local network for keyless OpenAI-compatible servers (Ollama, LM Studio, llama.cpp, vLLM, …) and offers their models in the picker. |
| `CHAT_ENDPOINT_DISCOVERY` | native: `lan`; server: `local` | `lan` (loopback + mDNS `.local` names + each attached IPv4 `/24`), `local` (this machine + `host.docker.internal`), or `off`. Skips host:port pairs already configured as **chat** backends. An auxiliary model on the same URL (e.g. oMLX `:8000`) does not hide the rest of that server's models. Native apps default to `lan`; standalone servers default to `local`. The environment overrides `endpoints.json` → `discovery.mode`, which overrides the platform default. |
| `CHAT_ENDPOINT_DISCOVERY_PORTS` | built-in popular list | Optional comma-separated port list (max 32) replacing the defaults (`11434`, `1234`, `8000`, `8080`, `8888`, …). |
| `CHAT_API_KEY` | unset | Optional bearer token. Keep secrets in env/keychain, not SQLite plaintext. |
| `CHAT_CONFIG_DIR` | OS config dir | App config directory. Defaults to `~/.config/omni-chat` on macOS/Linux unless Linux `XDG_CONFIG_HOME` is set; Windows uses the user config directory. |
| `CHAT_PROFILES_PATH` | `<config-dir>/profiles.json` | Optional file-specific override for additional or overriding profile definitions loaded at startup. |
| `CHAT_SOUL_PATH` | `<config-dir>/SOUL.md` | Optional file-specific override for the assistant personality Markdown loaded at startup. |
| `CHAT_SKILLS_PATH` | `<config-dir>/skills` | Optional overlay directory of `*.md` skills. Missing default dir is fine; an explicit path must exist. See [Skills](#skills). |
| `CHAT_ENDPOINTS_PATH` | `<config-dir>/endpoints.json` | Optional file-specific override for the multi-backend definitions loaded at startup. See [Multiple backends](#multiple-backends). |
| `CHAT_ROUTER_PATH` | `<config-dir>/router.json` | Optional file-specific override for the Auto (Smart Router) policy loaded at startup. See [Auto (Smart Router)](#auto-smart-router). |
| `CHAT_AGENTS_PATH` | `<config-dir>/agents.json` | Optional file-specific override for the external-agent definitions that enable the `delegate_task` tool. See [Agent handoff](#agent-handoff-delegate-a-task-to-pi-or-hola). |
| `CHAT_MCP_PATH` | `<config-dir>/mcp.json` | Optional file-specific override for the MCP-server definitions that enable MCP tools. See [MCP tools](#mcp-tools). |
| `CHAT_OAUTH_CALLBACK_BIND` | `127.0.0.1` | Bind host for the temporary OAuth callback listener used by subscription sign-ins (ChatGPT prefers 1455, falling back to a free port). Containers set `0.0.0.0` so the published port can reach it — compose.yaml does this. Publishing the host side is opt-in: set `OMNI_OAUTH_PUBLISH_PORT=1455` in `.env` (default: an ephemeral port, i.e. the automatic callback is off and sign-in uses the paste fallback). |
| `CHAT_ROUTER_CLASSIFIER_URL` | unset | OpenAI-compatible endpoint of a **dedicated** router-classifier model (a general-purpose instruct model). Unset falls back to the auxiliary model (`CHAT_AUX_*`) when configured, else heuristics only. See [Semantic router classifier](#semantic-router-classifier). |
| `CHAT_ROUTER_CLASSIFIER_MODEL` | unset | Required when the URL is set; the one explicit classifier model id. |
| `CHAT_ROUTER_CLASSIFIER_FORMAT` | `auto` | `auto` and `schema` both use JSON-schema classification with a general instruct model. |
| `CHAT_ROUTER_CLASSIFIER_API_KEY` | unset | Optional bearer token for the classifier endpoint. |
| `CHAT_ROUTER_CLASSIFIER_TIMEOUT` | `3000ms` | Race deadline; accepts `100ms`–`10s`. Requires a Go duration unit, e.g. `3000ms` — a bare number like `3000` fails to parse and is fatal at startup. |
| `CHAT_WEB_SEARCH_PROVIDER` | `off` | Opt into `searxng` or `tavily`; `duckduckgo` is available outside iOS only. |
| `CHAT_WEB_SEARCH_URL` | unset | SearXNG base URL (or Tavily proxy). An existing URL-only setup still selects SearXNG. |
| `CHAT_WEB_SEARCH_TIMEOUT` | `10s` | Search request timeout; maximum `1m`. |
| `CHAT_WEB_SEARCH_MAX_RESULTS` | `5` | Results returned to the model, from 1 to 10. |
| `CHAT_TOOL_CALLING` | `true` | Set `false` to suppress tools for an environment-backed endpoint. |
| `CHAT_PROMPT_PROFILE` | `auto` | How much tool surface a model is given: `auto` derives it from the resolved parameter size, `full` keeps the complete surface, `terse`/`minimal` force the small-model behavior. Per-endpoint/per-model equivalent: `prompt_profile` in `endpoints.json`. |
| `CHAT_VISION_BUDGET` | `balanced` | Automatic image-input budget for an environment-backed endpoint: `low`, `balanced`, or `high`. Per-endpoint/per-model equivalent: `vision_budget` in `endpoints.json`. |
| `CHAT_WEB_FETCH` | `false` | Set `true` to enable the `fetch_url` tool. |
| `CHAT_WEB_FETCH_PROVIDER` | `direct` | `direct` (in-core, SSRF-guarded) or `reader` (external reader endpoint). |
| `CHAT_WEB_FETCH_URL` | unset | Reader endpoint base URL; required when the provider is `reader` (e.g. `https://r.jina.ai`). |
| `CHAT_WEB_FETCH_TIMEOUT` | `15s` | Per-fetch deadline, from `1s` to `60s`. |
| `CHAT_WEB_FETCH_MAX_BYTES` | `2097152` | Per-page download cap in bytes before truncation. |
| `CHAT_WEB_FETCH_USER_AGENT` | realistic browser UA | Overrides the User-Agent sent by the `direct` provider. |
| `CHAT_WEB_FETCH_ALLOW_PRIVATE` | `false` | Local dev only: relax the SSRF guard so private/loopback hosts can be fetched. |
| `CHAT_IMAGE_GEN_URL` | unset | Image backend base URL — a single URL or a comma-separated list (one backend per URL, like `CHAT_ENDPOINT_URL`; first = default). Setting it enables the `generate_image` tool. Ignored when `endpoints.json` declares `images[]`. See [Image generation](#image-generation). |
| `CHAT_IMAGE_GEN_PROVIDER` | `openai` | Backend protocol: `openai` (the OpenAI Images API, `POST /v1/images/generations`) or `responses` (the Responses API's `image_generation` tool — needs `carrier_model`, so configure it via `endpoints.json` `images[]` in practice). |
| `CHAT_IMAGE_GEN_MODEL` | unset | Optional model id passed through to the backend (the bundled sidecar serves one model and ignores it). |
| `CHAT_IMAGE_GEN_API_KEY` | unset | Optional bearer token for the image backend. Env-only, never stored in SQLite. |
| `CHAT_IMAGE_GEN_TIMEOUT` | `120s` | Idle deadline per image, from `10s` to `10m` (Go duration or bare seconds). With a streaming backend every progress event resets it, so only a stalled backend trips it; against a non-streaming backend it is the total deadline. |
| `CHAT_IMAGE_GEN_STREAM` | `true` | Ask the backend for streamed progress + partial previews (OpenAI Images `stream`/`partial_images`). Backends that ignore it degrade gracefully; set `false` to force plain JSON requests. |
| `CHAT_TTS_URL` | unset | Speech backend base URL — a single URL or a comma-separated list (one backend per URL; first = default). Setting it enables [read-aloud](#read-aloud-text-to-speech). Ignored when `endpoints.json` declares `tts[]`. |
| `CHAT_TTS_MODEL` | `tts-1` | Speech model id passed through to the backend (`omnivoice` for the bundled sidecar, `gpt-4o-mini-tts` on the OpenAI API). |
| `CHAT_TTS_API_KEY` | unset | Optional bearer token for the speech backend. Env-only, never stored in SQLite. |
| `CHAT_TTS_VOICES` | unset | Optional comma-separated voice list, pinning the picker instead of asking the backend. |
| `CHAT_TTS_DEFAULT_VOICE` | unset | Voice used when an account has no preference. |
| `CHAT_TTS_TIMEOUT` | `300s` | Per-synthesis-call deadline, from `1s` to `10m` (Go duration or bare seconds). Long replies are chunked, so this bounds each chunk, not the whole message. Sized for CPU backends — synthesis can legitimately take minutes there. |
| `CHAT_STT_URL` | unset | Transcription backend base URL — a single URL or a comma-separated list (one backend per URL; first = default). Setting it enables [voice input](#voice-input-dictation)'s server engine. Ignored when `endpoints.json` declares `stt[]`. |
| `CHAT_STT_MODEL` | `whisper-1` | Transcription model id passed through to the backend (`large-v3-turbo` for the bundled sidecar, `whisper-1` on the OpenAI API). |
| `CHAT_STT_API_KEY` | unset | Optional bearer token for the transcription backend. Env-only, never stored in SQLite. |
| `CHAT_STT_TIMEOUT` | `120s` | Per-transcription-call deadline, from `1s` to `10m` (Go duration or bare seconds). |

iOS search Settings offer **Tavily** and **Off** only. DuckDuckGo and SearXNG remain available in desktop and standalone web installations. Saved desktop-only choices display as Off on iOS and are cleared when settings are saved. The iOS help text and read-only summary omit those provider names.

The search settings name the selected provider that receives search queries and explain that pages you ask OmniChat to open are requested directly from those websites. Settings → Models → On-device model identifies Hugging Face (huggingface.co) as the model download service; no chat content is sent for the download, and on-device answers stay on your device. Privacy links in Legal and sharing notices open the iOS privacy policy on iOS and the general policy on other platforms.

The welcome screen only offers the on-device model on a device that can run it. A device with less than 8 GB of memory, or a download that stopped because storage ran out, is explained in Settings → Models instead.

Model/request config:

| Variable | Default | Notes |
| --- | --- | --- |
| `CHAT_MAX_TOKENS_FIELD` | `max_tokens` | Set to `max_completion_tokens` for endpoints/models that require it. |
| `CHAT_CONTEXT_WINDOW` | `8192` | Approximate input+output context window used for preflight budgeting. |
| `CHAT_MAX_OUTPUT_TOKENS` | unset | Optional hard cap for generated tokens; response-length presets and model metadata are clamped to this. |
| `CHAT_CONTEXT_SAFETY_MARGIN` | `512` | Reserved tokens subtracted from the input budget. |
| `CHAT_RESPONSE_HEADER_TIMEOUT` | `2m` | How long to wait for the endpoint's first response headers. On streaming backends these arrive with the first token, so this is effectively a time-to-first-token limit — raise it (e.g. `5m`) for slow self-hosted routers that cold-load large models, or a turn errors with a `timeout` while the model is still loading. Accepts a Go duration (`5m`, `90s`) or a bare number of seconds (`300`). |
| `CHAT_STREAM_IDLE_TIMEOUT` | `5m`; tool turns: longer | Maximum silence *between* streamed tokens before a turn is treated as a stalled upstream and ended (`finish_reason=error`, retryable) — the streaming body has no read deadline otherwise, so a backend that wedges mid-response without closing the socket would hang the turn. Unset, a turn that offers tools allows the time to write its whole output budget at 15 tok/s when that is longer (32k tokens ≈ 36 min), because some servers (TensorFold) send nothing until a tool call is complete; setting the variable applies that value to every turn. A healthy stream never trips it; raise it only for extremely slow token generators. Accepts a Go duration or a bare number of seconds. Interrupted responses can be resumed in place with **Continue**. |
| `CHAT_STREAM_DETACH_GRACE` | `5m` | How long a generation keeps running with **no browser attached** before it is cancelled. Generation is detached from the connection: navigating around the app, reloading the page, or briefly closing the laptop never kills a turn — the client re-attaches and replays what it missed, and the generating chat pulses in the sidebar. The flip side is that a genuinely closed browser keeps the backend busy for up to this grace, so tune it to taste. Accepts a Go duration or a bare number of seconds; `0` restores the old behaviour (cancel the instant the last client disconnects). Stopping a turn is always immediate via the Stop button. |
| `CHAT_HONORS_SAMPLING` | `false` | When `true`, Creativity sends `temperature` and `top_p`. |
| `CHAT_EXTRA_BODY` | unset | JSON object merged into the top-level chat request body for static endpoint params. |
| `CHAT_THINKING_ON_BODY` | unset | Advanced adapter override: JSON object merged into the top-level chat request body when the per-chat Thinking switch is on/auto. |
| `CHAT_THINKING_OFF_BODY` | unset | Advanced adapter override: JSON object merged into the top-level chat request body when the per-chat Thinking switch is off. |
| `CHAT_THINKING_BUDGET_TOKENS` | unset | Reasoning-guard token cap per response. A reasoning model that thinks past this budget — or starts repeating itself — is stopped gracefully with a "got stuck thinking" note offering **Retry without thinking** and **Regenerate**, instead of burning the whole output window. The budget is added on top of the response-length preset rather than taken out of it, so thinking never starves the reply. When a model overruns it, the turn is retried once with thinking off and seeded with the model's own notes, so you still get an answer; the "got stuck thinking" note appears only when that is impossible (a repetition loop, or a model whose thinking cannot be turned off). Unset applies the framing profile's default — 1024 for sub-2B models, 2048 up to 10B; above that and for models of unknown size, 1/16 of the context window (never below 16384), halved at low Thinking effort and doubled at high on models with an effort control, doubled again for Write Code turns, at most 131072 — so a 262k-window model gets 16384 for a plain turn and 32768 for a coding one. Also settable per endpoint (`thinking.budget_tokens`) or per model (`thinking_overrides[].budget_tokens`) in `endpoints.json`. OmniChat also learns from each response: a server that stops a response short of what was asked reveals its real output limit, which later turns are sized to (thinking then gets at most half, so the answer keeps room), and the model's reported thinking tokens tune how the guard counts dense reasoning such as code. |
| `CHAT_PARSE_THINK_TAGS` | `false` | Advanced adapter override: parse streamed `<think>...</think>` content into the reasoning channel and strip it from the answer. |

Embeddings are optional and, when configured, power **semantic memory** — relevance-ranked recall and meaning-based deduplication (see the Memory section). Memory also works without them through lexical, entity and acronym matching. Document RAG will reuse the same client in a later phase.

| Variable | Default | Notes |
| --- | --- | --- |
| `CHAT_EMBEDDINGS_URL` | unset | OpenAI-compatible embeddings endpoint (`/v1/embeddings`). Unset disables semantic memory. |
| `CHAT_EMBEDDINGS_MODEL` | unset | Embedding model name. Required when the URL is set. |
| `CHAT_EMBEDDINGS_DIM` | unset | Embedding dimension; must match the model. Required when the URL is set. |
| `CHAT_EMBEDDINGS_API_KEY` | unset | Optional bearer token for the embeddings endpoint. |
| `CHAT_EMBEDDINGS_TIMEOUT` | `30s` | Per-request timeout (1s–2m). |

Stored memory and summary vectors carry their model and dimension. Mismatches or invalid vectors are treated as missing and re-embedded in bounded batches on access; no table recreation or manual migration is needed.

### Auxiliary model (chat titles, memory jobs, smart routing)

Native Apple apps default to **AppleFoundation** on iOS 26 / macOS 26 and later,
including OS 27. Enable Apple Intelligence in system Settings and let its model download.
This is independent of the optional Qwen chat-model download. In **Settings →
Models → Auxiliary**, AppleFoundation is selected automatically; choose Managed (the Local
services llama.cpp), a connection + model, or **Disabled** to turn background inference off. The Test button
reports availability and checks a completion. Existing custom endpoints and explicit disabled
settings are preserved. A dedicated router classifier still takes precedence.

On-device Qwen 3.5 2B places reasoning in the Thinking block and supports the opt-in
**Code execution** tool (Python/JavaScript in the existing client sandbox).


One optional small, fast, **non-thinking** model powers OmniChat's background intelligence. Configure `CHAT_AUX_*` to enable it. Everything it does runs off the response path (never adding turn latency), and it never uses your main chat model, so it won't compete with generation on a single local endpoint. A 1–2B non-reasoning instruct model is ideal — the recommended default is [`LFM2.5-1.2B-Instruct`](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-GGUF) (~731 MB at Q4_K_M), e.g. `llama-server -hf LiquidAI/LFM2.5-1.2B-Instruct-GGUF:Q4_K_M --port 8091 --alias lfm2.5-1.2b-instruct`; see `.env.example` for smaller/larger alternatives.

| Variable | Default | Notes |
| --- | --- | --- |
| `CHAT_AUX_URL` | unset | OpenAI-compatible chat endpoint for the auxiliary model. Unset disables these features on standalone servers; native Apple apps use AppleFoundation by default. |
| `CHAT_AUX_MODEL` | unset | Model name (a small, fast, non-thinking instruct model is ideal). Required when the URL is set. |
| `CHAT_AUX_API_KEY` | unset | Optional bearer token for the endpoint. |
| `CHAT_AUX_ROUTER` | `true` | Set `false` (or `0`) to stop the aux model from serving as the smart-router classifier when no dedicated one is configured. |
| `CHAT_AUX_SHOW_IN_MODEL_DROPDOWN` | `true` | Set `false` (or `0`) to hide the auxiliary model from manual chat selection without disabling its background jobs. |

When visible, the configured model appears under an **Auxiliary model** group in the chat picker and
uses the ordinary chat prompt, budgeting, streaming, and persistence path when selected. This extra
entry remains manual-only. A remote model also listed on a Chat-enabled server keeps its normal
chat entry, which Auto (Smart Router) and `omni-chat launch` can use under their usual filters. In
`endpoints.json`, use `aux.show_in_model_dropdown: false` for the same opt-out. Existing chats that
already selected the auxiliary model continue working when it is hidden. OmniChat still reads the
configured model's live `/v1/models` metadata, so small endpoints retain their real context limit.
Apple's `apple-foundationmodel` (served by apfel) is recognized as a tool-capable ~3B model; an opaque,
retryable FoundationModels stream failure is retried once only when it occurred before any answer or
tool call was emitted. Apfel's textual JSON tool-call fallback is also recognized, but only for complete
envelopes naming tools actually offered on that round; it enters the normal validation and tool-budget
loop instead of appearing as a JSON code block in the chat.

> **Migration from `CHAT_MEMORY_*`:** the auxiliary model replaces the former `CHAT_MEMORY_URL`/`CHAT_MEMORY_MODEL`/`CHAT_MEMORY_API_KEY` variables, which are no longer read. Point `CHAT_AUX_URL`/`CHAT_AUX_MODEL` at the same small model to restore the memory jobs — setting `CHAT_MEMORY_*` now only logs a startup warning.

What it powers:

- **Chat titles** — after the first exchange, the aux model replaces the truncated first message with a concise 2–6 word title summarizing the conversation. Without an aux model, the derived truncated title stands.
- **Automatic extraction** quietly saves durable facts you mention. It is conservative: only clearly-stated, lasting facts, skips sensitive data (passwords, card/account numbers, secrets), honors the chat's `save_policy` (`off`/`explicit_only` disable it) and `min_confidence_to_save`, and de-duplicates against what you already have. A brief "Memory · Remembered" notification in the top-right corner announces each background save a few seconds after the reply, with **Undo** and **View** buttons. Everything it saves is inspectable, editable, and deletable in the Memories panel.
- **Rolling chat summaries (automatic context compaction)** keep a long conversation coherent past the model's context window. Once a chat grows long enough, a compact running recap of the earlier messages is maintained in the background — each refresh merges the previous recap with the new turns, so early context is never lost — and when the input budget would otherwise drop old turns, the assistant sees an "Earlier in this conversation…" recap in their place instead of losing the thread. Unlike the other jobs here, this one works **even without an aux model** (summarization then quietly uses the chat's own model between turns) and regardless of the Memory toggle. Your transcript is never altered: when compaction was active on the last response, a subtle divider marks the boundary ("messages above are sent to the model as a summary") with a **View summary** control that shows exactly what the model is told, and the response's info popup gains a "Context: Compacted" row. Editing, regenerating, or deleting a message inside the summarized span simply discards the stale summary and rebuilds it in the background — nothing is ever locked.
- **Cross-chat recall** brings relevant history from your *other* conversations into the current one. When you ask about something you discussed in a previous chat, the assistant is shown a short "From earlier conversations…" recap of the most relevant past chats, so a brand-new chat isn't a blank slate. This needs embeddings configured (it ranks summaries by meaning), only ever draws on your own chats, and respects the per-chat Memory toggle (off = no recall).
- **Consolidation** tidies your accumulated memories over time. An idle-time, per-user pass (rate-limited, in the background) merges duplicates, resolves contradictions (the newer memory wins; the older is retired), and distills recurring patterns into higher-level "insight" memories. Nothing is hard-deleted — retired memories keep a link to what replaced them and can be inspected via `GET /api/memories?include_deleted=true`. Pinned memories are never touched.
- **Smart-router classification** — when you pick "Auto (Smart Router)" and no dedicated classifier is configured, the aux model classifies each turn (code / reasoning / creative / etc.) so routing can pick a fitting model. This runs on the turn path under a short raced deadline (default 3s, falling back to heuristics), separate from the background jobs above. See [Semantic router classifier](#semantic-router-classifier); disable with `CHAT_AUX_ROUTER=0`.

## Message Actions

- **Edit your message** changes an earlier user prompt and regenerates from that point.
- **Edit an assistant response** asks the model to revise that response from a short instruction while the original stays visible. Revision thinking can be expanded during the stream; the answer is replaced with a dissolve effect only after the edit succeeds. The edit instruction is prompt context only and is not saved as a chat message. The model is always told to return the whole revised response — never just a patch or the changed lines — so you don't need to ask for an inline edit. If an edit makes things worse, **Undo edit** (the back-arrow next to Edit) brings back the version it replaced: one undo, no redo. It is offered only while that response is the last message in the chat and the chat has no images; sending a follow-up counts as accepting the edit.
- **Regenerate** re-runs an assistant response from the prior user turn.
- **Delete** removes a message from the visible chat and future prompt context with a short undo window.
- **Generation details** opens from the info icon beside an assistant response. Hover or focus it for a quick view, or click to pin it. The panel shows the response's saved profile, resolved model/endpoint (after Edits by different models, every model that worked on the response, listed once each), thinking and web-search status, token counts, TTFT, speeds, and total time.
- **`⋯` (more)** — on assistant responses in the Mac, Linux, iPhone and iPad apps. A browser does not show it:
  - **Summarize** (responses of about 150 words or more) adds a *Summarize this response* turn at the end of the chat, as if you had typed it, and stays in the history. It runs the built-in **Summarize** skill whatever Profile the chat uses: bottom line first, then the key points, keeping numbers, commands, settings paths and every warning, adding nothing and never repeating code blocks. The turn uses no tools and neither reads nor saves memories. Summarizing an earlier response shows a chip under the request that jumps back to it. Regenerate re-summarizes the same response; it fails clearly if that response was deleted. Editing the request turns it into an ordinary message.
  - **Export PDF** saves just that response — chat title, date, the response with its images, and its sources; not your question, thinking or tool details — for following steps away from the chat or sending a clean answer to someone. On iPhone and iPad this opens the system share sheet.

## Sharing & export

The **share** icon at the top of the chat exports the current conversation as a standalone
document. The HTML and Markdown downloads render what's already on screen, with no server
round-trip:

- **Download HTML** saves a single `.html` file (title, messages, rendered markdown, code-run
  outputs, and web-source citations). Images are inlined as data URLs so the page opens fully
  offline; other attachments are listed by filename. A chat containing math carries the KaTeX
  stylesheet and fonts inside the file too. Assistant thinking is not included.
- **Save as PDF** — in the desktop app (macOS, Linux, iPhone and iPad) the core renders the PDF
  (pure Go: goldmark + fpdf with the Go fonts, no print dialog or browser): title, who exported it
  and when, tags, each turn with its speaker and time, your messages as plain text and the replies
  formatted with their images, code-run results and sources. Letter paper for US/Canada locales, A4
  elsewhere. Limits of the lightweight renderer: math is shown as its LaTeX source, code has no
  syntax colours, emoji are left out and characters outside the Go fonts (CJK, Sinhala, …) print as
  boxes. Hidden for off-the-record chats, which have no server-side copy. Mac and Linux store it
  with the save panel. iPhone and iPad open the system share sheet, where the menu items are
  **Share Markdown**, **Share HTML** and **Share PDF** — Save to Files (including iCloud), Mail,
  AirDrop and the other share actions. In a browser, Save as PDF still opens the print view
  (choose *Save as PDF* there).
- **Download Markdown** saves a `.md` file with assistant answers kept as Markdown, code-run
  outputs as fenced blocks, and citations as links. Images are referenced by filename (not
  embedded), keeping the file small and portable. On iPhone and iPad this is **Share Markdown**.

## Attachments

Attach images and documents to a message with the composer's paperclip button, by dropping files
onto the conversation (including from Finder in the desktop app), or by clipboard paste. Supported: PNG/JPEG/WebP/GIF images and PDF/TXT/MD/HTML documents, up to 20 MB per
file and 8 files per message.

Chat images display inline without a clickable link or iOS long-press preview. Document
attachments keep their links; generated images retain their explicit Download and Edit actions.

- **Images** are sent to the model as vision content on that turn (OpenAI-compatible `image_url`
  parts, so local VLMs like Qwen2.5-VL behind llama.cpp or Ollama just work). Source pixels are
  preserved, then resized once for the resolved endpoint/model under its Low VRAM, Balanced, or
  High detail pixel budget. The composer's **image size** dropdown selects 100%, 75%, 50%, or 25%
  of the original width and height, with every choice capped by that budget. Smaller choices may
  save context, but percentages do not specify token savings; existing caps and a conservative
  per-image token floor can keep the estimate unchanged. The choice resets to 100% after sending.
  Its short tooltip reads “Use less than 100% to resize image & save context” and hides while
  the dropdown is open.
  Follow-up turns retain up to eight recent user-uploaded images (counting scanned PDF pages)
  with their original messages, using the saved size and the resolved model's shared pixel budget.
  Older turns and their images are trimmed together when context fills; generated images keep
  their textual references. Editing a user message shows its existing attachments and restores
  its image size; saving keeps those files and allows new uploads alongside them. The composer
  warns when the selected model cannot view images; Auto (Smart Router) requires vision for
  retained image context as well as new image uploads.
  With Search on and a tool-capable model, explicit requests such as “Where can I buy this?”
  start with a seller search and ask for clickable product links from the results. For an image,
  the model first identifies search terms from visible features or branding; the core runs the
  search before requesting an answer from the actual results. Uncertain matches are labeled. Broad retailer
  search pages are labeled as browsing links; they do not prove an exact match or availability.
  Vision support is detected from (strongest first) `model_overrides` in `endpoints.json`, the
  endpoint's own reported modalities (llama.cpp's router exposes `input_modalities` — note a
  llama-server started **without `--mmproj`** reports and is treated as text-only), and a
  built-in catalog (Gemma 3/4, Qwen 3.5/3.6, Qwen-VL, LLaVA, Pixtral, GLM-4.5V/4.1V, GPT-4o/5,
  Claude, Gemini, …). If a model is misdetected, set `{"model_pattern": "...", "vision": true}` in
  that endpoint's `model_overrides`. This is also how you handle a model whose vision support
  depends on the build rather than the name — GLM-5.2, for instance, ships as both a text-only
  and an image-capable deployment under the same model id, so the catalog claims no vision for it
  and you opt in on the endpoint serving the multimodal build.
- **Documents** get their text extracted server-side and injected as source context, on the
  attaching turn and on follow-up questions in the same chat (token-budgeted).
- **Scanned PDFs** with no text layer fall back to extracting their embedded page images, which
  ride the same vision path.

Uploads are stored per-user in SQLite; unsent uploads expire after 24 hours.

## Math rendering

Assistant answers render LaTeX with KaTeX, which is bundled into the app — nothing is fetched from
a CDN, so formulas work offline and in the desktop app exactly as they do in the browser.

- `$$…$$` and `\[…\]` render as a centred display equation. A long one scrolls inside the message
  instead of stretching it.
- `$…$` and `\(…\)` render inline, on the text baseline.
- **Money in ordinary prose is left alone.** "it costs $5, so $10 total" stays plain text. A bare
  `$…$` is only treated as math when it follows the strict rules TeX itself uses: no space after the
  opening `$`, no space before the closing one, no digit straight after it, and no line break in
  between. Anything money-shaped fails at least one of those.
- Models often emit slightly invalid LaTeX, so the renderer is deliberately forgiving: a literal
  `%` (as in `\mathbf{77.18%}`, which would otherwise be read as a comment and silently swallow the
  rest of the line) and a literal `$` (as in `\frac{$140}{$860}`, which would otherwise be a parse
  error) both render as written. The trade is that TeX comments can't be used inside math.
- Genuinely broken LaTeX shows the source in red rather than failing the whole message, and math
  inside code spans or fenced code blocks is never rendered.

Math is included in exports: a downloaded HTML chat carries the stylesheet and font faces inside the
file, so it looks the same opened offline.

## Composer Code Blocks

Type three backticks on an otherwise empty composer line to open a monospace code block. Paste or
type code without input-time syntax highlighting; Enter and Shift+Enter both add a new line and
never submit. Use Arrow Down at the end of the block, or click the blank line below it, to continue
with normal text. A populated code block stays structured until all of its contents are deleted or
cut; Backspace dismisses a newly opened empty block. Sent user messages show these sections as
visual code blocks. Wrap a word or phrase in single backticks, such as \`back_tick\`,
for inline code: closing the pair formats it immediately in the composer, and the sent
message keeps the same monospace style. Continue typing normally after the closing backtick;
Backspace immediately after conversion restores the literal backticks. Editing or restoring a
draft preserves the formatting. Inline pairs stay within one line; unmatched or escaped
backticks remain literal. Other user text stays literal.

## Code Previews

Assistant code blocks can be copied or saved from their toolbar. The save action opens a Save As
picker when the browser supports it, otherwise it falls back to a normal local download. On iPhone
and iPad it opens the system share sheet. A block is
saved under its name: the fence's (```` ```html index.html ````) or a filename line just above it, else
one the reply gives it — the one fitting filename the sentence before the block mentions ("Save this as
`index.html`:"), or a first-line comment such as `<!-- index.html -->`. A complete HTML page with no
name is saved under its `<title>` — "Pac-Man Clone" becomes `pacman_clone.html` (lowercase, words
joined by `_`, no spaces) — and as `index.html` only when the title is missing or generic. Only unnamed blocks (`snippet.*`) and a name two blocks share get an ordering suffix such as
`snippet-02.js`. HTML code blocks can be rendered as
sandboxed previews with inline CSS and JavaScript. Adjacent `css` and `js` blocks are bundled into
the same preview. Dynamically evaluated JavaScript, including `eval()` and `new Function()`, is
allowed inside the isolated preview so interactive apps such as calculators work. HTML previews can
also be popped out — into a new browser tab in the web app, a separate app window in the desktop
app — so keyboard driven demos such as games can capture arrow keys without scrolling the chat. The iframe does not receive same-origin access, cannot access
authenticated `/api/*` endpoints, and may load external resources only over HTTPS.

## Running code blocks

JavaScript, TypeScript, Python, Go, and bash code blocks show a **Run** button that executes the
snippet locally, in a sandboxed WebAssembly runtime (QuickJS for JS/TS, Pyodide/CPython for Python, a
Yaegi interpreter for Go, WASIX GNU bash for bash/sh) inside a dedicated Web Worker — nothing is sent
to a server. The iOS app does not include Bash or offer Run on shell code blocks. The sandbox has
**no network, no DOM, and no filesystem** access to your machine:
`fetch`, `XMLHttpRequest`, and storage are unavailable, so untrusted AI-generated code can't reach
your session or the network. Each run is capped at **30 seconds** of wall-clock time and **1 MiB** of
output, and nothing runs until you click Run. Output (stdout/stderr, exit code, duration) streams into
a panel below the code; **Stop**, **Re-run**, and **Close** controls manage the run. Runtimes download
once on first use and are then cached (Python is ~6 MB, Go ~8 MB, bash ~4 MB). Python covers the
standard library plus a curated set of bundled offline packages — **numpy and pandas** load
automatically when imported (a one-time ~8 MB download). Anything else fails with an honest
`ModuleNotFoundError` note: packages can't be installed because the sandbox has no network —
`pip`/`micropip` don't work by design. Go runs a standard-library subset via
an interpreter — no third-party modules, and networking/`os-exec`/`syscall`/`unsafe` are withheld as a
security boundary. **Multi-file programs work:** code blocks that carry a filename — either on the
fence (` ```python main.py `) or as a bold/heading line right above the block (`**utils.py**`) — form
a workspace within one answer. Running a named block mounts its named siblings into the sandbox's
in-memory filesystem, so `import utils` or a multi-file Go package just works; the files exist only
for that run and are discarded with it. **Interactive programs work:** a JS/TS program that reads
input with Node `readline` or `process.stdin`, a Python program that calls `input()`, or a bash block
runs in a terminal below the block — type into it and the run keeps going. JS/TS interactivity needs
no special browser support; **Python `input()` and bash need cross-origin isolation** (a
`SharedArrayBuffer`), so they work in **Chrome and Firefox** and degrade to a "not supported" notice
in Safari. bash runs your block as a real script (`bash -c`) with `coreutils` (`ls`, `cat`, and
friends); if the script calls `read`, the terminal stays live for input. There is no `pip`, `python`,
`node`, or package manager in the shell — a `command not found` is followed by a one-line note saying
only bash + coreutils are available. Because bash runs in
WebAssembly without full POSIX signals, a filter reading an *unbounded* stream and piped into another
command (e.g. `tr < /dev/urandom | head -c 16`) produces no output — bound the source first
(`head -c 64 /dev/urandom | …`).

To make cross-origin isolation possible the app sends `Cross-Origin-Opener-Policy: same-origin` and
`Cross-Origin-Embedder-Policy: credentialless` on its own responses; `credentialless` keeps
cross-origin images in chat loading (without credentials).

## Appearance

- **Light / dark theme** toggles from the sun/moon button in the top bar, next to the switch-user button. It defaults to your operating system's preference and remembers your choice per user (stored in the browser), so each account keeps its own theme on that device.
- **Interface zoom** uses `Cmd`+`+` / `Cmd`+`-` on macOS and `Ctrl`+`+` / `Ctrl`+`-` elsewhere; `Cmd`/`Ctrl`+`0` returns to 100%. The desktop app steps through 80%, 90%, 100%, 110%, 125%, 150%, 175%, and 200%, remembers the choice per user on that device, and reflows the whole interface rather than enlarging text into fixed controls. The standalone web app leaves these shortcuts and their limits to the browser, including user-controlled pinch zoom.
- **Focus the composer** with `Cmd`+`Shift`+`L` on macOS and `Ctrl`+`Shift`+`L` on Windows/Linux. If the composer was tucked into its peek bar (it auto-collapses when an answer starts streaming), the shortcut expands it and puts the cursor in the input so you can type a follow-up. A second press does not re-collapse it. The chord is ignored while a modal dialog is open.
- **Find in the current chat** with `Cmd`+`F` on macOS and `Ctrl`+`F` on Windows/Linux. A find bar searches visible message text (not thinking traces or other chats); `Enter` / `Cmd`+`G` (or `F3`) steps to the next hit and `Escape` closes it. The standalone web app takes this chord from the browser find-in-page while you are in the app — use the browser menu if you want the native finder.
- **Search chats or tags** with `Cmd`+`Shift`+`P` on macOS and `Ctrl`+`Shift`+`P` on Windows/Linux. That expands a collapsed library sidebar (or opens the mobile drawer) and focuses the existing search box. Unshifted `Cmd`/`Ctrl`+`P` is left for print. Firefox's private-window chord is the same as the Windows/Linux binding.
- **Live-turn activity hint** — while a response is generating, a thin orange glow sweeps around the composer border and the collapse chevron gently breathes. It shows on the collapsed peek bar too, so an in-flight turn stays visible even with the composer tucked away, and it stops the moment the turn finishes. With the OS reduced-motion preference set, the sweep is replaced by a static accent ring.

The Library fetches 50 recent chats at a time and loads older pages as you scroll;
**Load more recents** is also available. Project folders fetch their own pages: **Load more
chats** finds older conversations even when they are outside Recents’ loaded pages.
Search checks titles and tag names across the saved library after a short typing pause
(about 250 ms), while already-loaded matches appear immediately. Use a bare tag name in
search, or choose its hashtag chip for an exact tag filter. `%`, `_` and `\` are literal;
SQLite’s default case folding is ASCII. Clearing search or changing tag/archive filters
starts again at the first page. Message bodies are not searched.

After a reply, the Library refreshes quietly without clearing open project folders or
reducing an expanded folder to five chats. Each collection refreshes at most its newest
200 loaded rows; older loaded rows remain visible as cached data with their existing
continuation. Changing filters resets those caches. Loading indicators appear on initial
loads, filter changes and Load more, rather than background refreshes.

## Background generation

A response keeps generating even if you click into another chat or reload the page: generation
runs in the core, detached from the browser connection. On a computer the core process stays
scheduled when you switch apps, so the reply continues there too. The generating chat pulses
gently in the sidebar so you can find your way back; opening it shows everything streamed so
far — thinking trace included — and continues live. On reload the app re-attaches automatically.
Only pressing **Stop** (or leaving no browser attached for longer than `CHAT_STREAM_DETACH_GRACE`,
default 5 minutes) ends a turn early — so a genuinely closed browser stops burning GPU after the
grace, while a quick reload costs nothing. While a turn runs, other chats are read-only; their
Send button explains which chat the model is busy in. Off-the-record chats are the exception:
their transcript only lives in the browser, so their streams remain tied to the connection.

**Pause and resume.** Next to **Stop**, a **Pause** button (‖) appears once a saved chat's reply
has started. Pausing stops the model but keeps everything written so far, so you can close the
laptop or quit the app and come back later: the paused reply is saved, survives sleep and
restarts, and shows on your other devices too. While a chat is paused, its composer shows the
prompt you sent, read-only, with **Play** (▶) and **Stop** in place of Send, and the chat carries a
small ⏸ in the sidebar. Other chats work normally in the meantime. **Play** clears the composer
and continues the same reply where it stopped; if you paused while the model was still thinking,
it gets its own notes back and carries on from them. You can pause and resume as many times as
you like. **Stop** while paused ends the reply like a normal Stop, keeping the partial answer.
Resuming sends the conversation to the model again, so on a large local model the reply may take
a moment to pick up. Pausing is always something you choose: closing the lid mid-reply without
pausing works as before. Off-the-record chats and assistant Edit offer Stop only.

Each saved chat allows one generation at a time, including Send, Summarize, Regenerate,
Continue, and edits of user or assistant messages. If another tab or device starts one first,
the app shows **“A reply is already in progress.”** and joins that reply where available.
The refused action leaves the chat unchanged and keeps your unsent composer text and uploads.
Assistant revisions stay tied to their original connection and cannot be joined; their reservation
still prevents another generation from changing that chat until the revision ends.
Saved-chat voice calls hold the same slot from model loading until the call ends; end
voice mode before changing that chat. Unsaved voice calls have no chat to reserve.

On iPhone and iPad the core lives inside the app, and iOS suspends that process when you leave.
**Options → Background generation**, below Services, is a single **Keep generating** switch with
no show/hide control. It is on by default. While it is on, each Send asks iOS to keep the reply
generating and to show progress with a cancel control. Turning it off during a reply dismisses
that progress and leaves the reply running only while OmniChat stays open. If iOS cancels the
work, the composer says so and the reply stops. Read aloud still stops when you leave. On-device
Metal needs Background GPU Access on the App ID; remote models continue with the app's network
access. The Simulator has no continued-processing tasks, so a reply there runs in the foreground.

## Settings Behavior

The Options panel starts collapsed by default to give the conversation more room — open it from the sliders button on its rail. Your expand/collapse choice for each side panel is remembered per user (stored in the browser), like the theme. Model, Profile, and Thinking stay available in the composer toolbar while it is collapsed. Inside the panel, expand Profile to reach its style controls, nested Session Instructions, and the selected profile's Skill when one is attached; both managed-text viewers have their own eye icons and start collapsed.

The Options panel is intentionally single-purpose:

- **Model** is populated from `/api/models`, persists per chat, and is selected from the compact composer picker. A status LED sits beside each real model inside the picker (and next to the selected model on the closed picker): green when the selected backend confirms that model is loaded, amber while it is loading, and neutral when unloaded, sleeping, or unsupported. It refreshes while the app is visible. Typing with an unloaded or sleeping model selected starts loading it in the background, so the first reply doesn't wait for the whole load. The load uses the llama.cpp router's load call, Ollama's preload, or a one-token request elsewhere, and nothing is added to the chat. The LED turns green when the model is ready, and amber while it loads if the server reports a loading state (the llama.cpp router does; Ollama and oMLX go straight from grey to green). The picker checks every 2 seconds until then. Each model is warmed at most once every 2 minutes. The picker is disabled while a response is streaming; stop first, then switch models and regenerate.
- **Tone** is single-select and only changes `style.tone`. `Default` adds no tone instruction.
- **Response Length** changes the desired output token cap; the backend clamps it to model/context limits and may reduce it to preserve recent chat history.
- **Creativity** changes style prompt text. It sends `temperature` and `top_p` only when `CHAT_HONORS_SAMPLING=true`.
- **Format** changes output-shape prompt text.
- **Thinking** persists per chat. The synchronized switches in the composer toolbar and Settings both update the same state. On (`auto`) asks capable endpoints for thinking; Off disables upstream thinking when OmniChat knows the model/server adapter, otherwise it suppresses reasoning display/storage for that turn. Completed reasoning panels show how long the leading thinking phase took, measured from the first reasoning token to the first visible answer token. Reasoning models are detected by model family on any self-hosted server (see Reasoning models). Models with no known reasoning channel or adapter show the switch as unavailable.
- **Thinking effort** is an account-wide Low / Balanced / High control in Settings (default Balanced). It changes how thoroughly supporting models reason — it is not the reasoning-token budget, and it is not a per-chat toggle. Qwen 3.8 defaults to its maximum (`xhigh`) unless this is set; OmniChat maps Balanced → `medium` and High → `xhigh` (the template rejects the name `high`). The same preference is applied to `omni-chat launch`; agent handoff (`delegate_task`) has its own **Agent thinking** setting (Low / Same as chat / Off, default Low). Models that do not honor a native effort knob are left unchanged. For a hosted provider that accepts the standard Chat Completions `reasoning_effort` field, opt the model in with `thinking_overrides[].effort: "reasoning_effort"` (Low / Balanced / High → `low` / `medium` / `high`), and add `"off_body": {"reasoning_effort": "none"}` where the provider can switch reasoning off so Thinking off and the out-of-room recovery work — for example `{"model_pattern": "qwen-3.8-27b", "effort": "reasoning_effort", "on_body": {"reasoning_effort": "medium"}, "off_body": {"reasoning_effort": "none"}}`. Some providers run their maximum effort when the field is absent.
- **ChatGPT thinking**: a Responses connection with no `thinking` settings of its own sends `reasoning: {effort, summary: "auto"}` when Thinking is on, so the thinking streams, with effort Low → `low`, Balanced → `medium`, High → `high`. Thinking off sends `reasoning: {effort: "low"}` (these models have no `none`).
- **`omni-chat launch` Thinking** follows **New chat defaults → Thinking** (on/off) plus the account effort above. The composer Thinking switch is per-chat only and does not change a launch. Restart `omni-chat launch` after changing the default so a new lease is minted.
- **Off the record** (the privacy-shield toggle next to the theme switch in the top bar) starts a **temporary chat**. While it is on, nothing about the conversation is saved anywhere — no chat appears in History, no messages are stored, and no memory, summaries, or chat title are generated. The transcript lives only in your browser for that session and is gone when you reload the page or open another chat (you'll be asked to confirm before leaving). Memory is forced off (and its toggle is locked), and attachments, image generation, and the Agent tool are unavailable in this mode; web search, URL fetch, code execution, and MCP tools still work. It can only be turned on for a brand-new, empty chat — once you've sent a message it stays on until you start or open a different chat.
- **Profile** is a collapsible section with an always-visible dropdown. Its expanded controls contain Tone / Response Length / Creativity / Format, the nested Session Instructions editor, and a read-only Skill viewer when the selected concrete profile attaches a procedure. `Default` restores default tone, medium length, balanced creativity, and structured format; Brainstorm Ideas, Draft Content, Write Code, Learn Topic, Write a How-to, and Write a Mini-book set a session-only persona plus style bundle, and each attaches a matching bundled skill (a procedure, not extra persona text). How-to and Mini-book are the writing skills: the assistant authors teaching documents page-by-page instead of dumping a book into an agent. Selecting a value expands the Profile controls. Each assistant response records the profile ID and label used for that turn and shows it in the response's Generation details panel. Reopening a chat selects the profile from its newest visible assistant response; if that profile was removed from configuration, the historical label remains visible and the selector falls back to `No profile`. If that response was Auto-routed (label `Auto → <Profile Label>`, or a bare `Auto`), reopening restores the **Auto** profile selection instead of the concrete persona it happened to route to that turn.
- **Session Instructions** is nested under the expanded Profile controls and keeps its own show/hide and reset buttons. It contains only the editable per-session instructions generated from project/profile/style settings; app safety, hidden realtime context, SOUL, and an attached skill are managed by the core and are not shown in the textarea. Edits are session-only and are not saved to SQLite. Reloading discards edits and regenerates the default instructions for the restored current profile.
- **Skill** appears after Session Instructions only when the core resolves one for the selected profile. Its independent eye control reveals the exact managed Markdown in a read-only panel. The viewer starts hidden after reload and keeps its disclosure state while switching profiles; Default and Auto show no Skill row because neither has one stable attached procedure.

The top-right user menu contains **Edit Profile**, **Manage Memories**, **Settings**, and **Sign off**. In Settings, a **Legal** section below **You** contains **Privacy policy**, **Terms**, **Support**, and **Acknowledgements**. These links also appear on the first-run and sign-in screens. These open the public website in your browser, including in native apps. Edit Profile updates your username, display name, and a small local avatar image. Memory persists per chat: On lets the assistant save durable facts about you and recall the relevant ones on later turns; Off neither reads nor writes memory for that chat (history is still stored). See the Memory section below.

**Members** is under **Profile → Settings → You**, immediately above Delete Account, for owners and admins. It provides the existing add, enable/disable and admin controls; changes apply immediately. Member management no longer appears in the Options sidebar.

**Delete Account** is under **Profile → Settings → You**, with a red warning-triangle icon. The page explains the permanent loss of your account, chat history, uploaded files, memories, personal settings, connected-service sign-ins, personal/published skills, and app-managed agent workspaces. Type **DELETE ACCOUNT** exactly and submit to confirm; deletion cannot be undone. All sessions are revoked and you are signed out. A single-account installation returns to first-time setup so you can create a new account. On shared instances, other users keep their data and the owner role passes to another account when necessary. Downloaded models and instance-wide settings remain; external files, provider-held data and subscriptions are unaffected.

On iOS, the deletion warning says “Export functionality is currently not available on this device.” Other platforms retain the desktop-only export reminder. The shared-instance explanation appears only outside iOS; the details about retained models, instance settings, external files and provider data remain visible on every platform.

The optional **Help oMNI know you** form starts with your display name (or username), your device
timezone, and a clearly marked city suggestion from that timezone. All are editable and nothing
is saved until **Save profile**; **Skip for now** leaves the private context empty. Onboarding and
**Edit Profile** keep field labels with friendly question placeholders and use a timezone dropdown
instead of free text. Username fields disable automatic capitalization and correction. Mobile
dialogs stay within safe areas and the visible viewport when the keyboard opens, with clearance
for iOS input controls; long forms scroll inside the dialog.

The layout follows the current window size, including folding, rotation, and split windows.
Compact windows show one chat pane with overlay sidebars. Medium windows (720–1199 CSS pixels
wide and taller than 500 pixels) dock History and open Options as an overlay; wide windows
(1200 pixels or more) dock both panels. Shorter windows below 1200 pixels use the compact layout.
Desktop windows start at 1296×860. Controls can still wrap depending on sidebar space, zoom and picker labels. The composer expands up to 1100 CSS pixels. Send/Stop stays beside the last row of tools as controls wrap in narrower windows, avoiding a separate send-only row on desktop. Narrow phones use extra rows to keep tools, live meters and actions accessible. Resizing preserves your draft, active response, reading position, and saved sidebar preferences. Rotation settles the new viewport before restoring scroll; the welcome screen keeps its scroll position instead of following the bottom.

On iPhone Duo with iOS 27.1, partly folding the phone with the fold running across the screen
(laptop style, bottom half on the table) splits OmniChat at the fold: the conversation and the
streaming answer stay on the top half, and the composer fills the bottom half, where the keyboard
opens. Nothing is drawn across the fold. In this position the composer cannot be minimized, both
sidebars open as drawers, and dialogs stay on the top half; if the keyboard leaves too little room
below the fold, the composer moves just above it. Unfolding or closing the phone brings back the
normal layout with your draft and reading position. Chrome on Android foldables gets the same
split in the browser through the Device Posture and Viewport Segments web APIs.

Turn the Duo sideways and partly fold it so the crease runs from top to bottom (book style).
The chat library fills the left half, stopping at the fold, and the conversation fills the right
half. Options still opens over the conversation. iPhone Duo keeps the clock and Wi-Fi in a
column at the screen edge; Options, account, off-the-record, and theme
stack there as equal square buttons, starting just below the clock and Wi-Fi, so the chat title
keeps the pane. History sits before Edit on the left of the title, and Share is left out of the column. Other screens
keep account, off-the-record, theme, and Options in their normal top-bar order.
Hiding the library gives the conversation the whole screen, and the history control brings it
back. A desktop browser book split keeps those controls in the top bar.

The composer follows the width available inside the chat pane, including sidebar and safe-area
space. Narrow panes put Model and Profile together above a single row of actions, with tool
switches available in Tools. Wider panes fit those controls on one row. Short windows use a
smaller initial input that still grows while typing, leaving more room for the conversation.
Short landscape screens also compact the header and hide its subtitle and the disclaimer.
On short portrait screens, the composer extends beneath a top-side status area, keeping
rounded-corner clearance instead of leaving an unused strip beside the input.

On touch screens, drag inward from almost anywhere along either side edge to reveal its sidebar.
The start zones are at least 56px wide, with small corner margins. Swipe outward across an open
sidebar to close it, including from its buttons; ordinary taps still work. The Duo status column
accepts these swipes too. Both sidebars settle after the same short swipe (96 CSS pixels, or
half their travel when shorter), even when one is a wider overlay drawer. Drag down from the
full-width strip above the composer or its empty space to minimize it, or up from the strip or
collapsed bar to restore it. Tapping the grip also toggles it. Panels follow your finger. The composer settles
open past halfway, otherwise closed. Cancelling restores the starting state. Text editing,
conversation scrolling, horizontally scrollable content and pinch zoom retain their normal behavior.
The off-the-record banner stays fully visible at the conversation's top edge as you scroll,
rotate or fold; its text wraps within the available width and safe areas.

The response Info card pairs Profile with Task skill, groups tool activity together, and keeps
token counts and timings easy to scan. Expand **Generation logs** below the stats for routing,
memory, identity provenance, and per-round diagnostics.

A small circular **Context** meter sits immediately to the right of **Tools**, moving into
the restore bar when the composer is minimized. Hover, focus, or tap it for a compact orange
tooltip such as `Context 12k/262k · 249k left`. It shows one model call's input plus generated
output against its usable window (the model window minus the safety margin). Counts update about once per second as the model streams data; `≈` marks
estimates, which are replaced by provider-reported counts when available. A silent or buffering
backend cannot supply live counts, so the meter holds its last reading rather than inventing
progress. Amber starts at 80% and red at 95%; this is context capacity, not task progress or a research
allowance. Tool follow-ups reset to their newly prepared context after trimming, so usage can
decrease. During an agent handoff, the composer ring follows the active agent call and labels
its tooltip **Agent context**, using that call's own window. It returns to the chat call when
the parent resumes. Agent and plan-task cards retain their own meters; counts are never added
across calls. Final snapshots survive reloads. Older messages
without a snapshot show unknown usage until a new call supplies one.

A small orange **generation speedometer** beside the context ring updates about once per
second. Hover, focus, or tap it for tok/s and the current activity. Its needle follows a
three-second rolling estimate including thinking and tool arguments, and follows the active
agent model during handoffs. Between agent model calls it retains the measured average labelled
**Agent · Last model call**. If a provider buffers its output but reports final token counts,
an approximate full-call rate is labelled **includes wait**; live progress is never invented.
During tool execution, orchestration, or a silent backend, the hub pulses while the tooltip
describes the activity; an unavailable speed parks the needle.
Approval waits pause the pulse. The dial spans 0–200 tok/s; the tooltip shows the full speed.
`≈` marks estimates. When generation ends it shows the last chat call's average using reported
tokens when available, excluding time waiting for the first output or trailing usage reports.
A buffered chat response cannot establish streaming speed. Reduced-motion settings disable animation.

Power users can customize the default assistant personality by creating `<config-dir>/SOUL.md`. The built-in SOUL makes OmniChat warm, thoughtful, conversational, and lightly playful by default. `CHAT_CONFIG_DIR=/path/to/omni-chat-config` overrides the directory for all app config, and `CHAT_SOUL_PATH=/path/to/SOUL.md` overrides only the soul file. SOUL controls personality and tone only; app safety remains a separate hard-coded invariant that the core always injects before sending upstream. A missing default `SOUL.md` is fine and uses the built-in personality; an explicit `CHAT_SOUL_PATH` must exist and must not be empty.

```bash
mkdir -p ~/.config/omni-chat
cp docs/SOUL.example.md ~/.config/omni-chat/SOUL.md
```

Power users can extend profiles by creating `<config-dir>/profiles.json`, where the default config dir is `~/.config/omni-chat` on macOS and Linux-style systems. `CHAT_PROFILES_PATH=/path/to/profiles.json` overrides only the profiles file.

## Memory

With the **Memory** toggle on, the assistant remembers durable facts, preferences, decisions, and constraints about you across chats — separate from raw message history.

- **Ask it to remember.** Say something like "Remember that I'm vegetarian" and the assistant saves a durable memory; a "Memory · Saved" notification in the top-right corner confirms it for about 15 seconds, with **Undo** if it saved something you didn't want kept. In a later chat it recalls the relevant memories automatically. Say "Forget that I'm vegetarian" to remove one.
- **Manage your memories.** Choose **Manage Memories** from the top-right user menu to list everything remembered about you. Filter by scope, edit a memory's text or kind, pin the ones that should always stay in context, add one manually, delete any, and see each memory's provenance (the chat it came from). Memories are private to your account.
- **Scopes.** `user` memories follow you across all your projects; `project` memories apply only within that project's chats. (Shared `workspace` memory arrives with the sharing phase.)
- **Kinds.** `preference`, `fact`, `decision`, `constraint`.

- **Smarter recall (optional).** When an embeddings endpoint is configured (`CHAT_EMBEDDINGS_*`), the assistant recalls memories by *relevance* to what you're currently asking rather than by recency, and saving something you already told it in different words updates the existing memory instead of adding a duplicate. Without embeddings, recall is recency-based and dedup is exact-text — everything still works.

Memories are stored in the local SQLite database and are also available via the `/api/memories` REST endpoints. Automatic extraction from conversations and rolling chat summaries are planned in later memory phases; see the PRD and `docs/superpowers/specs/` for the design.

Built-in profiles load first; matching IDs in the JSON file override built-ins in place, and new IDs append to the list. The welcome page shows at most 8 cards total; the synthetic **✨ Auto** entry (see below) is shown first when present and uses one of those slots. The profile dropdowns still include every configured profile. A missing default `profiles.json` is fine and uses built-ins. An explicit `CHAT_PROFILES_PATH` must exist. Any existing profile file is validated at startup and must use lower snake case IDs plus valid style option keys. `icon` is optional and must name a bundled icon in lower kebab case; unknown names fall back to the generic custom-profile icon in the UI.

A ready-to-copy starter lives at [docs/profiles.example.json](docs/profiles.example.json):

```bash
mkdir -p ~/.config/omni-chat
cp docs/profiles.example.json ~/.config/omni-chat/profiles.json
```

You can also point directly at it for a one-off run:

```bash
CHAT_PROFILES_PATH=docs/profiles.example.json make dev
```

```json
{
  "schema_version": 1,
  "profiles": [
    {
      "id": "review_docs",
      "label": "Review Docs",
      "description": "Review documentation for gaps.",
      "persona_prompt": "Review documentation for missing context and unclear claims.",
      "icon": "file-text",
      "style": {
        "tone": "direct",
        "response_length": "detailed",
        "creativity": "precise",
        "format": "structured"
      }
    }
  ]
}
```

### Skills

A **profile** is who the assistant is this session (persona + style). A **skill** is a procedure it should follow (how to review code, how to write a mini-book). Skills are managed Markdown, injected as a `Skill:` block that is not shown in the session-instructions textarea. The selected profile's resolved skill is separately visible, but not editable, in the expanded Profile controls. Keep `persona_prompt` short; put process in a skill.

**Manage your library in Settings → You → Skills.** Every signed-in user can import a public skills.sh or GitHub skill/repository URL, or upload a standard `SKILL.md`/ZIP package. Preview the instructions, files, license, and compatibility before importing. Remote packages are pinned to a commit; installation preserves the reviewed bytes, original files, and content hash. Imports and Profile assignments are private and save immediately in either desktop or web.

Use **Profile skills** on that page to choose each Profile’s procedure for your account, including No skill or Use instance default. **Remove** clears an imported skill’s personal assignments; **Undo removal** restores them unless you saved a newer assignment. Built-in and instance skills use **Disable for me / Enable for me**. Past responses retain the skill name and provenance in their generation details after removal.

The composer keeps one **Profile** selector. Its assigned skill is used automatically, with no second skill choice. Manage personal assignments in Settings → You → Skills; inspect the resolved instructions in the expanded Profile controls. Auto resolves personal assignments after choosing its concrete Profile. Session Instructions remain separately editable. Responses record the procedure used in generation details. MCP companion guidance and direct Auto task-skill selection are planned separately; see [the contextual skills design](docs/superpowers/specs/2026-10-12-contextual-skills-design.md).

The same library labels **Built-in**, **Instance**, and **Personal** skills. Built-ins ship with the app and cannot be deleted; startup overlays are labelled Instance rather than Built-in. Administrators can open **Manage shared skills** or **Settings → This instance → Shared skills** to review and explicitly publish their own imported package as an independent instance copy. Everyone can inspect/use that copy, but only administrators can remove it for everyone. Removal clears its personal Profile assignments without changing historical responses. Private imports never become shared automatically. File-managed overlays remain operator-maintained startup configuration.

**OmniChat Help** is built-in app guidance. It activates for app questions and short follow-ups, independently of the selected Profile and model; unrelated questions do not load it. Disable it for your account in the library. It receives only the running version, core shell, your instance-management authority, off-the-record state, and offered tool families. It walks through everyday actions (new chats, rename, archive, delete, and where each setting lives) and host password reset, backup and restore. It guides configuration through settings; it does not grant the model configuration-write powers. Its instructions and live facts share the normal budgeted system message with any task skill. Generation details retain which skills were used and why. **View → Export SKILL.md** exports bundled instructions with the app version, without live account facts or credentials.

Imported skills use standard YAML `name` and `description` metadata and a Markdown procedure. Instruction-only skills up to 8 KiB can run in chat. Scripts/assets, resource references, declared tool/environment requirements, and larger procedures are marked **Needs adaptation**: they can be imported for inspection but cannot be activated. Compatibility checks cannot verify every prose requirement. Importing never executes code, installs dependencies, grants tools, or transfers packages to external agents. No automatic updates or private-repository credentials are supported in this version. For GitHub refs containing slashes, use a commit URL or local upload.

Limits: 8 MiB upload, 16 MiB expanded/downloaded, 1 MiB and 128 files per package, 64 candidates per source, and 100 imports per account including reversibly removed packages. Import previews expire after ten minutes. Shared instance overlays below retain their existing format and startup lifecycle.

Instance administrators can supply a shared profile default in two ways:

1. Explicit `"skill": "write_howto"` on the profile.
2. Same id: a profile `id: "review_code"` loads a skill named `review_code` if one exists.

An explicit skill id that is not in the catalog fails startup before `READY`. An empty `skill` field is fine — same-id match is optional.

Built-in skills match the six welcome-card profiles: `brainstorm_ideas`, `draft_content`, `write_code`, `learn_topic`, `write_howto`, and `write_minibook`. Overlay more as `*.md` files under `<config-dir>/skills/` (or `CHAT_SKILLS_PATH`). A missing default directory is fine. An explicit `CHAT_SKILLS_PATH` must exist and be a directory. Each file is at most 8 KiB. Same id replaces a bundled skill.

A ready-to-copy overlay lives at [docs/skills.example/](docs/skills.example/) and uses the **same ids** as [docs/profiles.example.json](docs/profiles.example.json) (`review_code`, `debug_issue`, `plan_project`, `summarize_notes`, `write_tests`, `decision_memo`, `polish_writing`, `analyze_data`). Those example profiles leave `skill` empty so `CHAT_PROFILES_PATH=docs/profiles.example.json` still starts without a skills directory. Copy both to attach the procedures:

```bash
cp docs/profiles.example.json ~/.config/omni-chat/profiles.json
mkdir -p ~/.config/omni-chat/skills
cp docs/skills.example/*.md ~/.config/omni-chat/skills/
```

You can also point at both example files for a one-off run:

```bash
CHAT_PROFILES_PATH=docs/profiles.example.json CHAT_SKILLS_PATH=docs/skills.example make dev
```

Front matter on an instance overlay file is `id` and `name` only. The rest is the procedure. Do not put a `README.md` in the skills directory — every `.md` file is loaded as a skill.

Typst templates for how-tos and mini-books seed only when the resolved skill id is `write_howto` or `write_minibook`. A custom skill gets prompt injection; it does not get those templates. PDF-in-chat and `chat-assets/` still run after every `delegate_task`.

Reasoning models often have endpoint-specific parameters. OmniChat infers common adapters such as Qwen served by llama.cpp and DeepSeek V4 served by `ds4.c`. For OMLX, it reads the optional `/v1/models/status` metadata and enables the switch whenever `thinking_default` is a boolean; both `true` and `false` indicate that the model's chat template supports `enable_thinking`. This keeps new OMLX model families working without name-based allowlists.

Thinking control, thinking effort and anti-loop sampling follow the **model family** — hybrid Qwen3.x, GLM-4.5+, Gemma 4+, DeepSeek (R1 always-thinking), gpt-oss (always-thinking), Nemotron, Meta Muse Glimmer, Inkling 2 (always-thinking, effort dial) — on any self-hosted server: one with a known `owned_by` (llama.cpp, vLLM, SGLang, oMLX, Ollama, LM Studio, ds4.c, Kapitsa), or any server on loopback, the LAN, a tailnet or found by discovery, unless its `owned_by` names a cloud vendor (`openai`, `system`, `anthropic`, `google`, `azure`, `openrouter` — e.g. a LiteLLM proxy). A LAN relay for another hosted API that reports some other owner is treated as self-hosted: give that endpoint `thinking_overrides` and `sampling_defaults: "off"`. Newer generations inherit the newest known behaviour (a future `qwen3.9`, `glm-6` or `gemma-5` gets its family's switch on day one); Instruct/Coder variants stay non-thinking and Thinking variants always-thinking. Ollama gets `reasoning_effort: "none"` as its off switch; oMLX's `thinking_default` metadata enables the switch for families OmniChat does not know. Muse Glimmer reasons at strength "high" by default and has no template on/off key: on Ollama, `reasoning_effort: "none"` turns its reasoning off and Thinking effort Low / Balanced / High sends `low` / `medium` / `high` (measured on Ollama 0.40); elsewhere effort goes to the template as `reasoning_strength` (Meta's documented argument) and there is no off switch. Hosted Muse Spark (Meta Model API) is a cloud model and gets no family behaviour. If a single-model self-hosted server's `/v1/models` omits the context window, OmniChat reads it from `/health` (`context_length`, …) instead of assuming 8192. Ollama's `/v1/models` never carries one: a model Ollama has loaded gets its runner's context from `/api/ps`, and an unloaded one its maximum from `/api/tags` (Ollama 0.40+) capped at the context Ollama was last seen loading models with — 32768 until one is seen, since Ollama silently truncates a longer prompt.

Bonsai models, including `bonsai-2:9b` and namespaced `Ternary-Bonsai` ids, support the Thinking toggle on Ollama: Off sends `reasoning_effort: "none"`; On restores Ollama’s default thinking. This was verified against Bonsai 2 9B. Other self-hosted runtimes show reasoning but need a configured adapter until their switch is verified (oMLX can still enable it through its live template metadata). See [Ollama’s thinking controls](https://docs.ollama.com/api/openai-compatibility) and the [Bonsai model card](https://huggingface.co/prism-ml/Ternary-Bonsai-2-9B-gguf).

Inkling 2 models (for example `inkling2-mini`) always reason. Their template's `reasoning_effort` is a dial, not a switch: `none` still thinks. Thinking effort Low / Balanced / High sends `low` / `medium` / `high` through `chat_template_kwargs` (top-level `reasoning_effort` on Ollama); the template's own default is 0.9, which is `high`. On llama.cpp the Thinking toggle works: Off sends `reasoning_effort: "none"` with `thinking_budget_tokens: 1`, and every thinking turn sends `thinking_budget_tokens` at 90% of the turn's reasoning ceiling. llama.cpp then ends a long think itself and the model writes its answer, instead of thinking until the context runs out. That cap only ends the first thinking block: at High effort Inkling can open a new one. On these turns the stream guard therefore counts every reasoning delta as a token (llama.cpp streams one token per delta). A re-opened think trips the guard at the real ceiling, and the turn finishes with thinking off from the model's own notes. Other runtimes get the effort dial but no toggle. This was verified on llama.cpp b12624.

A llama.cpp router's `/v1/models` can list the model's trained maximum as `context_length` (1048576 for Inkling 2 Mini) beside the window it actually serves. OmniChat sizes the turn by the smaller of the two. For a loaded model that is `meta.n_ctx`. For an unloaded one it is the `--ctx-size` / `-c` launch argument in `status.args`.

Kapitsa (`owned_by` `nace`) publishes `context_length` and `context_fit`. `context_fit` is how many tokens one conversation can hold once the memory budget is spent, and OmniChat sizes the turn to the smaller of the two. A row with `downloaded: false` stays out of the picker until that model is installed. `active: true` is loaded and `active: false` is unloaded. Flint writes its tool calls in GLM markup, and Kapitsa's tool-call grammar refuses that shape: for Flint, OmniChat sends `tool_choice` `"auto"` and non-strict tools. Qwen and Nemotron on the same server keep strict tools. Flint has no thinking on/off switch; its trace still arrives on `reasoning_content`.

GLM-4.5 and later (GLM-4.5, GLM-4.6, GLM-5.x) are hybrid reasoners toggled through the chat template, so a self-hosted GLM — vLLM, SGLang, llama.cpp — gets a fully controllable Thinking switch backed by `chat_template_kwargs.enable_thinking`. Serve it with `--reasoning-parser glm45` and the trace arrives on the native reasoning channel; serve it without and OmniChat sniffs the leading `<think>` tag and routes the trace anyway. The inference is deliberately limited to self-hosted backends: Z.ai's hosted API toggles the same models with a different shape (`thinking: {"type": "enabled"}`), so point an endpoint at it and configure `thinking` explicitly. GLM-4 and older have no thinking mode and correctly show no switch.

For custom endpoints, configure per-endpoint thinking request bodies in `endpoints.json`:

```json
{
  "thinking": {
    "on_body": { "reasoning_effort": "medium" },
    "off_body": { "reasoning_effort": "none" },
    "parse_think_tags": true
  }
}
```

`CHAT_EXTRA_BODY` remains available for static top-level request parameters. Do not use it for per-turn thinking state; the Thinking switch owns that and chooses the inferred/configured adapter body at request time.

Do not force sampling on reasoning models unless your endpoint explicitly supports it.

## Web search

OmniChat starts with web search off. After a provider is configured and Search is explicitly
enabled for a chat, it advertises a strict `web_search` function to tool-capable models. The Go core validates the call, queries the
configured provider, returns structured title/URL/snippet results to the model, and persists the
results as source cards. Search snippets are treated as untrusted data and are not full-page
content. The function takes an optional `recency` (`day`, `week`, `month` or `year`) that the model
sets for time-sensitive questions: it maps to DuckDuckGo's date filter or SearXNG's `time_range`, and on Tavily a `day` or
`week` search also switches to its news index, so "today's headlines" returns that day's articles
rather than evergreen "news today" pages and last week's roundups.

Choose a provider under **Settings → Web & tools → Web search**:

| Provider | Setup | Notes |
| --- | --- | --- |
| `off` (default) | None | No search provider. |
| `duckduckgo` | None | Opt-in on desktop and web/Docker. Excluded from iOS builds. Text search only. |
| `searxng` | Self-hosted; run it and point the core at its URL | Also provides `search_images`. |
| `tavily` | Hosted; needs an API key | No extra process at all. Free tier at [tavily.com](https://tavily.com) — 1,000 searches a month, no card. No image search. |

Configure a provider in the `search` section of `endpoints.json`, which wins over the environment the
same way `images[]`/`tts[]`/`stt[]` already do:

```json
{
  "schema_version": 2,
  "connections": [{ "name": "local", "base_url": "http://127.0.0.1:8000" }],
  "endpoints": [{ "connection": "local" }],
  "search": { "provider": "tavily", "api_key_env": "TAVILY_API_KEY" },
  "fetch": { "enabled": true }
}
```

`api_key_env` names an environment variable rather than holding the secret — the same mechanism the
endpoints use, which is how the native app keeps the key in the OS Keychain. An inline
`"api_key"` also works. With no `search` section the `CHAT_WEB_SEARCH_*` variables apply, leaving search
off when unset. Existing URL-only environment setups still use SearXNG, and existing
SearXNG/Tavily file settings are preserved. Legacy empty search sections remain explicitly off.
`CHAT_WEB_SEARCH_API_KEY` sets Tavily's key when `CHAT_WEB_SEARCH_PROVIDER=tavily`.

On iOS, use **Settings → Web & tools → Tavily**, enter your own key, and **Save & Restart**.
Then enable **Search** for the chat (or opt in through **New chat defaults**). Queries can include
conversation-derived context and go to Tavily, including with an on-device model; usage is billed
to your Tavily account. Keys are loaded from the device Keychain at runtime. No publisher key or
personal configuration is bundled. Legacy DuckDuckGo settings stay disabled on iOS without
blocking startup; choosing Tavily never falls back to DuckDuckGo. Existing explicit chat/account
Search choices are preserved. Unspecified chat settings and temporary requests default off.

Every web build scans the embedded assets for Tavily credentials; iOS core builds also scan the
compiled archive. A detected credential fails the build without printing the value. Private `.env`
and `config/` files are ignored, and the iOS bundle has no personal configuration resources.

Built-in search needs no Python, Docker, helper process or model weights. It makes ordinary HTTPS
POST requests for DuckDuckGo's HTML results, keeping queries out of URLs/access logs. It validates and deduplicates destination links, and bounds
response size and snippet length. Requests are serialized with at least one second between starts;
status polling never performs a search. Queries are cached only within the existing turn, never in
a shared or persistent provider cache. DuckDuckGo receives the query and the public IP of the
device/server running the core. Internet access is required. CAPTCHAs, rate limits and changed result
pages produce an explicit search error; there is no automatic switch to another provider.

Choose **Off** to disable instance search (`"search": {"provider":"off"}` or
`CHAT_WEB_SEARCH_PROVIDER=off`). The per-chat **Search** switch still gates all OmniChat web tools,
including URL/image fetch, so turning it off sends no searches.

### Self-hosting SearXNG

`search` is a single object, so a config file names one provider at a time. The SearXNG form is:

```json
{ "search": { "provider": "searxng", "base_url": "http://localhost:8888", "max_results": 5 } }
```

`docs/endpoints.docker.example.jsonc` shows it wired for Compose (`http://searxng:8080`);
`docs/endpoints.example.jsonc` shows the built-in default and alternatives. Bring the sidecar up on its own — it is not
part of the normal Compose stack:

```bash
printf 'SEARXNG_SECRET=%s\n' "$(openssl rand -hex 32)" >> .env
docker compose -f compose.search-only.yaml up -d
```

That publishes SearXNG on `127.0.0.1:8888`. Point the app at it — **Settings → Web & tools → Web search →
SearXNG** in the desktop app, or `CHAT_WEB_SEARCH_URL=http://localhost:8888` for web mode — and use
**Test search** to confirm it answers.

The one setting that matters is JSON output. `deploy/searxng/settings.yml` (mounted read-only by the
overlay) must list `json` under `search.formats`, or SearXNG returns 403 and the core reports
*"SearXNG rejected JSON output; enable the json search format."* Running the app and the sidecar in
the same Compose project instead? Use `-f compose.yaml -f compose.search.yaml`, which sets the URL
for you.

The desktop app exposes both under **Settings → Web & tools** in the user menu, so neither needs a text
editor. Adding another provider (Serper, Exa) is a small implementation behind the same Go
`search.Provider` interface. A configured endpoint that does not support OpenAI-compatible tool calls can
set `"tool_calling": false` in `endpoints.json`; `CHAT_TOOL_CALLING=false` provides the equivalent
fallback for environment-backed endpoints. The composer's **Search** toggle (off by default) is a
per-chat privacy switch: turning it off withholds every web tool — `web_search`, `search_images`,
`fetch_url`, and `fetch_image` — for that chat, and the model is told web access is off. Delegated
agents and MCP tools are separate toggles and are not covered. Set its starting value for new chats
under **New chat defaults** in the right Options panel. Source cards are no longer a toggle: any
answer that used sources shows a collapsed **Sources · N** section below it that expands to the
cards. The Search toggle only appears when search or fetch is configured.

The right sidebar's **Services → Chat backends** shows a switch beside each backend name.
Turn it off to hide that backend's models from **your** picker and exclude them from Auto routing,
including routed agent tasks and new interactive agent launches. The preference is stored in SQLite
for your account and applies across devices without a restart. Disabled rows stay visible so you
can turn them back on, even if the server is offline. Other users, shared configuration, credentials,
background services, running requests, and existing chats pinned to a specific model are unaffected.

## Web/URL fetch

Enable it with `{"fetch": {"enabled": true}}` in `endpoints.json` or `CHAT_WEB_FETCH=true`. The
default `direct` provider runs inside the core behind an SSRF guard, so this needs nothing else
running — it is the cheapest capability to turn on.

When fetch is enabled, OmniChat additionally advertises a strict `fetch_url` function so a
tool-capable model can retrieve a specific URL the user gave it (or that appeared in search results),
extract its readable text, and summarize or quote it. The result is persisted as a source card, and
each response snapshots a `web_fetch_status` (`used`/`empty`/`failed`/`not_used`) shown in the
response info control. `web_search` and `fetch_url` share one bounded tool-call budget per turn.

Two providers are available:

The iOS Settings UI offers only the built-in `direct` provider. The Reader service choice is
available in desktop Settings; an iOS Settings save converts an older Reader selection to `direct`.

- **`direct`** (default) fetches in-core with a realistic browser User-Agent and extracts the main
  content with a readability parser. A built-in SSRF guard refuses private, loopback, link-local, and
  cloud-metadata addresses (checked at dial time, so redirects and DNS rebinding are covered too);
  only `text/html`/`text/plain` responses are extracted and the body is size-capped. It needs no
  external service but may be blocked by JS-heavy or anti-bot sites.
- **`reader`** delegates to an external or self-hosted reader endpoint (`CHAT_WEB_FETCH_URL`, e.g.
  `https://r.jina.ai`) that renders JS and returns clean text. This handles anti-bot sites and, with
  a capable reader, YouTube transcripts. URLs are sent to that endpoint, so point it at a service you
  trust. The `compose.fetch.yaml` overlay (see [Docker](#docker)) is the easy way to run a self-hosted
  reader for this provider.

When the fetch tool is enabled and your message contains a URL, the core fetches it automatically
before the model runs (up to the first two URLs) and hands the model the content, so summarizing a
pasted link works reliably even on models that would otherwise reach for web search. Fetched content
is treated as untrusted: the model is instructed not to follow instructions embedded in a page and to
cite the URL.

### Showing images from the web

The same setting also enables **`fetch_image`**, so the model can show you a picture that already
exists rather than drawing one:

> **Show me a 3-month candlestick chart of TSLA.**

The core downloads the image and puts it in the reply. No image backend is required — an instance
that cannot *generate* images can still *show* them.

The model gets image URLs three ways, and is told never to invent one:

- **`search_images`** looks pictures up by keywords and returns direct image URLs. It needs a search
  provider with image support (SearXNG's `images` category) and has its own small per-turn budget,
  so hunting for a picture never eats the `web_search`/`fetch_url` allowance.
- **`fetch_url`** reports any image URLs it finds on a page it read, under `images`.
- **Live stock charts** come from chart endpoints that render on demand from a ticker (StockCharts,
  Finviz) when your current request asks for a chart and names its ticker. Company-name-only
  requests need an image URL found on a fetched page first. Charts cannot be invented as
  placeholders for coding tasks or inferred from your name or profile.

The image is **downloaded and stored**, not hotlinked: it survives the source going away, travels
with an exported chat, never leaks your IP to the origin host, and can be handed to `edit_image`
afterwards. What the URL claims does not decide what gets stored — the bytes are sniffed and only
real png/jpeg/webp/gif images are kept, so a rate-limit page served as `image.png` is refused
instead of rendered. The same SSRF guard as `fetch_url` applies, redirects and all.

A fetched image is never dressed up as a generated one: its caption reads *Fetched · … from
`<host>`* and links to the source, and the response info control credits your image backend only for
images it actually made. There is a budget of three fetches per turn, and it is unavailable off the
record (it would leave an attachment behind).

Every turn also carries a hidden, system-injected context block (not the editable Session Instructions):
the current date and time in your browser's timezone, best-effort details about the client device's
OS/version/CPU architecture, and a short directive. When `web_search` is
available it tells the model to search for current or possibly-changed facts and trust fresh
results over its own memory; when the tool is unavailable it instead tells the model it has no web
access and should flag that its knowledge may be out of date. The wording is kept plain so smaller
local models follow it reliably. The browser sends its IANA timezone name (e.g.
`America/Chicago`) plus structured OS metadata from Client Hints or coarse user-agent fallbacks; it
never sends the raw user-agent string. The server keeps the authoritative clock, treats the device
version/architecture as approximate (and distinct from a remote core host), and does not persist
either value. The prompt explicitly tells the model to use the detected OS for commands,
installation, and debugging unless you name a different target.

## Code execution as a tool

Beyond the manual Run button, a tool-capable model can execute code itself: turn on the **Code
Execution** toggle in the composer (the `</>` tray button, or its switch in the Tools menu — it
outlines orange when active) and the model is
offered a `run_code` function (Python or JavaScript). Ask something like *"sort these numbers and
give me the median — use a tool"* and the model writes a program, your **browser** runs it in the
same sandboxed WASM runtime as the Run button (fresh Web Worker, no network/DOM/filesystem/stdin,
30-second timeout, capped output), and the printed result feeds back into the model's answer — the
code never runs on the server. While it executes, the response shows a "Running Python…" chip that
becomes a collapsed card; expand it to audit the exact code and its stdout/stderr, and the card is
stored with the message so it survives reload. Runs are budgeted (three per response, independent of
the web-tool budget), arguments are validated before anything executes, and if the browser can't
produce a result the model is told execution was unavailable and answers without it. Go and bash are
deliberately not offered to the model (slow first load / browser-gated); they remain Run-button-only.
Enabling the toggle is the explicit opt-in for auto-running model-written code in the sandbox — with
it off (the default), nothing ever runs without your click.

Per-chat tools live in the composer as a **tray of up to four icon toggles** plus a **Tools menu**
(the grid button) listing every tool with an on/off switch (hover a row for its description). Tools whose
backing service was never configured on the instance don't appear at all — a bare core shows only
Code Execution, Thinking, Memory, and (when your browser supports speech) Read aloud. A tool whose
service is configured but currently down stays in the menu dimmed with the reason and recovers by
itself when the service returns. Enabled tools claim the tray slots first, so what you switched on
is always one click away; everything else is in the menu. All of these apply to the *current chat*
(this session). To choose what *new* chats start with, use the **New chat defaults** switches in
the right Options sidebar. This section starts collapsed; its eye button shows or hides the
switches. Defaults are saved to your account (synced across devices) and never change a chat
you've already started. (Agent handoff is deliberately not a new-chat default — it's
situational and off unless you turn it on for a chat.) The per-chat **Memory** switch also lives in
the Tools menu, and a new **Image tools** switch (on by default) can turn image generation off for
a chat.

## Launch Pi or Hola against OmniChat

The standalone `omni-chat` binary can open your normal interactive Pi or Hola (`hola-coder`)
installation with every text model currently available to OmniChat. The macOS one-line installer
puts it on your `PATH`; from source, build it first:

```bash
make build-cli
.cache/bin/omni-chat launch pi
.cache/bin/omni-chat launch hola-coder -i
```

Name the agent (`pi`, or `hola-coder` / `hola`), then give it its own options as usual — they go to
the agent unchanged, so `omni-chat launch hola-coder -i` opens Hola's interactive REPL and
`omni-chat launch pi --continue` resumes Pi.

A packaged desktop app already contains the same binary at
`OmniChat.app/Contents/Resources/omni-chat`.

The wrapper first checks that the core and database are healthy, prompts for your OmniChat username
and password, and then starts the agent. Use Pi's `/model` picker, or Hola's `/model ls` and
`/model ENDPOINT/MODEL`, to switch between the available models; models with the same ID on
different endpoints remain separate. Every model request goes back through the OmniChat core,
including endpoints that need OAuth or the Responses protocol. The wrapper never writes an endpoint
key or your password to disk. It keeps a short-lived launch token in the agent's process environment,
renews it while the agent runs, and revokes it and logs out when the agent exits.
If an endpoint connection drops before producing any model output, the core retries it twice with a
short bounded backoff. Once any model event has arrived, the request is never replayed.
When a model does not report an output cap, the temporary Pi provider and Hola profiles use the
proxy's 32,768-token file-writing fallback; an explicit endpoint/model cap still wins (Hola's is also
capped at that fallback, as in agent handoff), and the proxy clamps the request to the context room
remaining after the agent's transcript and tool schemas. Reasoning may use that entire
resolved output allowance: the proxy does not apply its smaller chat-response thinking budget or
depend on recognizing the model/backend. Repetition-loop protection stays active, and if a backend
streams past the full allowance the proxy closes the completion normally with `finish_reason:
"length"` instead of breaking the agent's stream.

Server discovery checks `--server`, then `OMNI_CHAT_URL`, the desktop app's remembered port, and
finally `http://127.0.0.1:8080`. An explicitly supplied server must be healthy; it is never silently
replaced by another instance. Plain HTTP is accepted on loopback only unless you deliberately pass
`--allow-insecure-http`. Examples:

```bash
omni-chat launch pi --server https://chat.example.com --username alice
omni-chat launch pi --model local/qwen3-coder --continue
omni-chat launch hola-coder --model local/qwen3-coder -i
```

The wrapper takes its own options (`--server`, `--username`, `--model ENDPOINT/MODEL`,
`--allow-insecure-http`) from anywhere on the command line, before or after the agent name; every
other argument goes to the agent in order. Everything after `--` goes to the agent untouched, which
is how to pass the agent an argument that looks like one of the wrapper's options.

**Pi.** The wrapper owns Pi's `--provider`, `--model`, `--models`, and `--api-key` flags so they
cannot bypass the scoped route; your usual Pi sessions, skills, themes, and extensions otherwise
remain available. Pi extensions are trusted local code and can still make their own unrelated network
calls.

**Hola.** Hola reads its models only from `~/.hola/profiles.json`, so the wrapper runs it with a
private, temporary `HOME` whose `profiles.json` has one profile per launch model, named
`ENDPOINT/MODEL` (the selected model is the default). Everything else in your home and `~/.hola` —
plugins, skills, `mcp.json`, `SOUL.md`, git and ssh config — is linked in, so it works as usual, and
sessions stay in the project's `.hola/hola-coder.db`. While Hola runs, `$HOME` for Hola and the
commands it runs is that temporary folder (`cd ~` lands there; files you already have are reached
through the links). When Hola exits, anything it created there for the first time, such as a new
`~/.hola/skills/…` entry, is moved into your real home, and the temporary folder is deleted; an entry
that cannot be moved is kept and its path printed. The launch token is in Hola's `OPENAI_API_KEY`, so
commands Hola runs see it instead of your own OpenAI key. The wrapper owns `-p`/`--profile` (use
`--model`), removes `HOLA_PROFILE` and `OPENAI_BASE_URL` from Hola's environment, and sets
`HOLA_ADAPTIVE_REASONING=0` unless you set it yourself, since the launch already applies your
Thinking settings. Hola prefers the `.hola/profiles.json` of the folder's project — the nearest
parent folder with `.git` or `.hola` — over the generated one, so the wrapper refuses to start when
that file exists. From a folder outside any git repository, the search can reach your own
`~/.hola/profiles.json`: launch from a repository, or `mkdir .hola` first. Hola's built-in `codex`
and `claude` profiles stay reachable with `/model` and use your own logins, not OmniChat.

The v1 launch catalog is text-only and excludes OmniChat's virtual Auto Router and image-generation
endpoints. This interactive wrapper is independent of the chat feature below: it does not require
`agents.json`, does not run the agent on the core host, and does not use a managed agent workspace.

## Agent handoff (delegate a task to Pi or Hola)

`run_code` is a sealed sandbox — no filesystem, no network. When a task needs the real thing (edit a
repository, run its test suite, make git commits, longer-running work), a tool-capable model can hand
it to an **external coding agent** running on the machine hosting the core. The built-in adapters are
[Pi](https://pi.dev) and [Hola](https://cloudgpu.io/agent/hola-ai-agent/usage) (the
`hola-coder` tail from Hola 0.6 or newer).

The delegation follows the account's **Agent thinking** setting (below), applied to the chat's
effective Thinking choice. When it resolves to off, the endpoint/model's inferred or configured
off-body and non-thinking sampling settings apply to every model call Pi or Hola makes during that
run; reasoning that a backend still emits is not relayed to the agent.

**Agent handoff resilience.** Delegated agents get the bound model's real context window and output budget (Pi's own default of 16,384 output tokens no longer applies). The agent model proxy budgets each call as the agent's answer budget plus the model's reasoning ceiling on top, holds tool calls until a model turn completes, and retries a reasoning overrun or a cut-off tool call once with thinking off — the agent never receives a half-written file — and asks once more for a call the model server dropped (a turn that ends normally with nothing shown while usage counts hidden answer tokens: TensorFold drops a tool call whose arguments it cannot parse, and the agent would take the empty reply as the model finishing), or one a short reply only announced ("I'll read the existing files first." — agents take a reply without a tool call as the end of the run). Each run is pinned to the endpoint it started on, so a busy discovered server or a config reload cannot break it, and discovery keeps a server through two missed scans. A run whose last model call was cut off, failed, or looped is reported **Incomplete** with the reason, never as finished. The proxy also watches the agent's own tool use: once the same tool call has returned the same result 3 times since the agent last changed a file (a job id, process id or run time in a command's output does not make it different), the model is told that repeating will not change anything, and at 6 the run is stopped as looping instead of burning its time limit; after 25 tool calls without changing a file (40 before its first change) the model is told to make its edit or finish with its report (an edit that failed to apply does not count as a change, and the note says how to redo it); in the last third of a run's time limit the model is told how many minutes remain and asked to finish its files and checks rather than start anything new (each such note is added once and then kept in the same place in the transcript, so the server's prompt cache — which on hybrid-attention models like Qwen 3.8 Next resumes only from an exact prefix — keeps working); in a plan, a task's agent that tries to write a file a task which has not run yet will write (say, the final assembly script while building one app) is asked again with a note naming that task — files of finished tasks stay open to it; an edit call with no text to replace (meant to append, it would put the new code at the very start of the file) is asked for again with a note on how to add code; a command tool that offers an optional timeout in seconds (Pi's `bash`) gets 120 s when the model leaves it out, so one never-ending command cannot hang the run, the running card shows what the agent's model is doing right now — "Writing index.html · 14.2 KB so far · 1m 20s" on servers that stream tool-call arguments (vLLM, llama.cpp, oMLX), "Model working · 1m 20s" on servers that only send a tool call once it is complete (TensorFold) — and after each model call its tokens and speed ("Model call: 6,341 tokens in 1m 19s (80 tok/s) → write index.html"), and an argument the model sends as a JSON string where the tool's schema expects an array or object is decoded before the agent sees it — mending the two slips measured in long model-written JSON, a key that lost its colon (`"produces "First…`) and a semicolon after the closing bracket. In a plan, a task whose run ended badly but whose declared files all pass its checks gets one continuation to finish anything left, and counts as done if that ends badly too — the checks are the acceptance test; a declared file that still holds a placeholder for code the agent meant to add later (such as `/* PART-2-BELOW */`) is never done. A chat turn that ends without a reply is retried once, including before its first tool call; when it produced only reasoning, the recovery keeps its bounded notes and available tools, switches Thinking off when supported, and asks for the next concrete action without treating plans as completed work, and a tool call cut off by the output limit when Thinking is already off is retried once with up to double the output room (within the endpoint's `max_output_tokens` and the context) instead of ending the turn — including a call the server swallowed (some servers parse tool calls themselves and drop one the cap cut off, so the stream shows a sentence while usage reports the whole budget). A call the model itself ended partway is handled the same way: the server drops it and the turn ends normally after a sentence, but usage counts far more answer tokens than were shown, so the call is asked for again (with Thinking off, the model's own notes handed back, when Thinking was on) — and so is a round that offered tools and then went silent past the stream idle bound, since such a server shows nothing while it composes a call. An empty reply whose usage still counts answer tokens (a call to a tool that is not offered, dropped whole) is asked for again with the list of tools that exist, and tool-call markup a model writes when no tools are offered is kept out of its answer. A stream that has been silent for a minute while the server reports nothing running (TensorFold's `requests_running` on `/health`) is ended then and there instead of being waited out to the idle bound. **Agent thinking** (Settings → Agent thinking: Low (default) / Same as chat / Off) sets how agents reason; Low runs agents at the lowest thinking effort under a 4096-token reasoning ceiling (a turn whose Thinking is off stays off; a run whose model thinks into that ceiling three times goes on with thinking off, and so do a plan's later tasks on that model once its earlier tasks tripped it three times, since each such call is minutes of reasoning thrown away before the same call is made without it), because an agent takes dozens of model steps — but only on models that have an effort control (for example Qwen 3.8, or OpenAI-style `reasoning_effort`). A model with only an on/off switch, such as GLM, cannot think less, so Low is ignored for it: it keeps the chat's Thinking and its own reasoning room, rather than being cut off mid-thought (pick Off to make it faster); Same as chat uses the turn's Thinking and Thinking effort.

**Plans.** For anything with several features or more than a few hundred lines — judged by scope, not file count — the assistant hands off a **plan** (`delegate_plan`) instead of one long brief (a deliverable that must be a single file is still built in parts, with a final task that combines them): a goal and up to 12 small tasks, each creating or modifying at most 3 files, naming what it reads and depends on, and listing acceptance checks (plain commands such as `node --check app.js`). Before you see it, OmniChat strips a `timeout N` prefix from a check (checks already time out after 120 s, and macOS has no `timeout`), drops a `node --check` on a file that is not a script (it can never pass), turns a folder given to `node --test` (such as `node --test tests/`) into a quoted pattern of the test files in it (Node 22 and newer take patterns there and fail on a folder; Node 20 is no longer supported for such checks), adds a test script a check runs but no task writes to that task's files (when it has room), moves a check that uses a file a later task creates onto that task (which then waits for the tasks the check needs — tasks run in plan order, and an earlier task is never made to wait for a later one), makes a task wait for the earlier task that writes a file it reads, lets the shared context run up to a quarter over its 8 KB budget and a task's instructions up to twice their 4 KB one (a retry's fix guidance runs long) rather than sending the plan back for a few bytes, keeps the goal and context of an earlier attempt when a corrected plan leaves them out, and, if the plan's JSON is broken, tells the assistant exactly where. You approve the plan once — edit a task's instructions or checks, or remove tasks, first. The request waits 30 minutes for your answer; if it expires, the dialog closes and the assistant carries on without the handoff. OmniChat then runs the tasks in order, one agent call each with a brief scoped to that task (the folders its new files go in are created first — some agents' write tools fail on a missing folder); a task cut off before it wrote its files is re-briefed once, and OmniChat runs each task's checks itself before starting the next. A job card under the message shows the workspace folder (copy its path; in the desktop app, open it in Finder or your file manager to watch files appear), and every task's status, running time, model, files and check results — plus the plan's total running time, ticking live (paused time doesn't count) — with **Stop** while it runs. Each task's latest step sits on one line; expand it, like the Thinking fold, to follow everything the agent did for that task (kept until you reload). Asked to start a new plan while one in the chat is paused, the assistant is first pointed back at the paused job (its finished tasks are kept). A failed task pauses the job and the assistant decides — retry with revised instructions, skip (the tasks after it then run without it; a task that has not run yet cannot be skipped; after four failed runs a retry must change the task's checks), add a fix-up task, or stop — and asks you again only if that touches files outside the plan you approved. If the app restarts mid-job, the job comes back paused; **Resume** (or asking the assistant to continue) picks up from the first unfinished task and never redoes finished ones. The job's ledger is also written to `.omni/handoff/<job>.json` in the workspace. The response info panel shows the name of each successfully used agent (for example, Hola or Pi), including plan and resumed tasks; the ledger records each task's model and endpoint, including when you choose the chat model explicitly.

**Choosing models for plan tasks.** When the chat is on **Auto**, each task is routed to its own model: one that can call tools and has at least a 32k context (and vision if the task reads images), the smallest one adequate for the task's effort (light, standard or heavy), preferring the previous task's model and models that are already loaded, so a job does not swap models needlessly. A task that failed or was cut off is retried on the next stronger model when there is one (a task you stopped is not). The job card shows which model ran each task (hover for why). With a model picked explicitly, every task uses that model. A cut-off task continues in the agent's own session (Pi reopens it with `--continue`) rather than starting over. Agents that run in Docker can use plans too: OmniChat runs each task's checks inside the agent's image, with the workspace mounted, no network and the image's entrypoint bypassed, so the image needs whatever the checks call (for example `node`). Checks are plain commands — no shell interpreters such as `sh -c`, and no description of the expected result (a check passes when it exits 0; "`node test.mjs` exits 0 and prints PASS" is rejected, and so is `grep -c`, which fails when the count is 0, or a grep with several `-e` patterns, which passes when any of them is found — a list of text that must not appear fails on clean files). OmniChat reads a check's quotes and backslash escapes the way a shell does (so `node -e "…'type=\"module\"'…"` means what it means to the agent that runs it), and before you see a plan it parses the code of each `node -e`/`-p` check with `node --check` (nothing runs) and sends back one that is not valid JavaScript, naming the spot — such a check fails however right the task's files are. Plans have size limits (goal 2000 bytes, shared context 8192, task titles 200, `produces` 500, up to 8 checks of 1200 bytes each); a JSON string sent where the tool expects an array or object (such as `tasks`) is decoded; an invalid plan gets up to five fix rounds per turn before the user is asked; `plan_limits` in `agents.json` (`max_tasks`, `max_files_per_task`, `max_instruction_bytes`) adjusts them per agent. Note that `node --check` does not syntax-check a `.js` file containing `export`, so prefer `node --test` or importing the module for ES-module checks. Adapter maintainers can run the conformance kit with `OMNI_AGENT_CONFORMANCE=1 go test ./internal/agent/conformance` (needs the agent CLI installed).

This is off unless the operator enables it. Create `<config-dir>/agents.json` (default
`~/.config/omni-chat/agents.json`; `CHAT_AGENTS_PATH` overrides only this file) declaring which
directories agents may touch and which agents exist. A ready-to-copy starter lives at
[docs/agents.example.json](docs/agents.example.json):

```bash
cp docs/agents.example.json ~/.config/omni-chat/agents.json
# or for a one-off run:
CHAT_AGENTS_PATH=docs/agents.example.json make dev
```

```json
{
  "schema_version": 1,
  "workspace_roots": ["~/Work"],
  "agents": [
    { "id": "pi", "label": "Pi", "type": "pi", "command": "pi", "timeout_minutes": 30 }
  ]
}
```

Install the agent first ([Pi](https://pi.dev), or
[Hola](https://cloudgpu.io/agent/hola-ai-agent/usage) 0.6+). A Hola entry is
`{"id":"hola","label":"Hola","type":"hola","command":"hola-coder","timeout_minutes":30}`
(`timeout_minutes` is each run's time limit; 30 when omitted).
`command` is resolved against `PATH` and then the usual install directories
(`/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`, …) — your `PATH` always wins, and an absolute
path always works. That fallback matters most in the desktop app and under systemd/launchd, where
the core inherits a minimal `PATH` that has none of those directories.
`workspace_roots` is the safety boundary: the agent can only ever run in a directory that resolves
under one of these roots.

**In the desktop app** you do not edit this file by hand. Open **Settings → Agent handoff**
to turn Pi and Hola on independently, pick each runtime, and choose where the agents work. The default
is **a fresh folder per chat**: you pick one workspace folder, and every chat gets its own new
subfolder inside it, created on the first handoff and reused by follow-ups in the same chat — the
agent never touches your existing files or the folder itself. Switch to **directly in folders I
choose** to let them work inside real repositories instead. Each agent shows the version its installed command reports (`--version`). Each enabled agent has its own **Test**
button, which resolves its command/image, checks the shared workspace, and actually starts that
adapter using the current form values, **before saving**, including first setup. Every test runs in the
shared workspace, so **Test** stays disabled until a workspace folder is chosen; the card says so and
offers **Choose Workspace folder…** (or **Add a folder…**) right beside it. Testing does not save
settings or restart the core; editing the form clears previous results. Saving asks for a restart,
because the core reads `agents.json` once at startup.
**Turn off** removes the file (a `.bak` is kept next to it).

For Hola, OmniChat uses the documented 0.6 profile feature rather than consuming ambient user
configuration. Every delegation writes a private temporary `omni-chat` profile containing the
selected model, proxy URL, OpenAI tool-call parser, coding toolsets (`fs`, `edit`, `search`, `exec`, `git` — Hola 1.12+ keeps `write_file`/`edit_file`/`search_replace`/`apply_patch` in `edit`, and without it the model could write only through shell heredocs, which Hola's convergence guard counts as read-only and stops as stuck), balanced convergence policy, and the model's `context_length` plus a `request_token_budget` of half the window (at most 64k tokens) — Hola 1.10+ otherwise caps every request's prompt at 16k tokens however large the model is, so Hola 1.10 or newer is recommended. To install Hola without sudo: `curl -fsSL https://cloudgpu.io/install.sh | HOLA_INSTALL_PREFIX=~/.local/hola HOLA_BIN_DIR=~/.local/bin sh` (set `HOLA_VERSION` to pin a release that has a build for your platform).
The profile deliberately omits `api_key`, so Hola reads the run-scoped token supplied through the
child process's `OPENAI_API_KEY` environment variable; the token never enters the profile or command
line. Every delegation also uses `--new`: workspace files persist between handoffs, but Hola never
auto-resumes model history from a previous run's `hola-coder.db` — except that a plan task cut off mid-way continues its own Hola session (`-c <session>`). Hola 1.10+ keeps that database in the workspace (`.hola/`), and OmniChat reads it (read-only) for the run's real outcome: a reply cut off at the output limit, or the tool-turn limit (or Hola's convergence guard) stopping a run after real work, is reported `incomplete` rather than ok or failed. Hola's adaptive reasoning is switched off for delegations (`HOLA_ADAPTIVE_REASONING=0`) because OmniChat already applies the agent thinking policy. Agent bookkeeping folders (`.hola/`, `.omni/`) are left out of the change summary a run reports. The temporary HOME excludes the
user's `~/.hola` so personal plugins/settings cannot
reroute a delegation. Because a repository's `.hola/profiles.json` takes precedence over the global
profile, the adapter refuses that workspace with an actionable error instead of claiming it can
guarantee the selected OmniChat route. See Hola's
[profile guide](https://cloudgpu.io/blog/using-hola-profiles) and
[0.6 options](https://cloudgpu.io/blog/new-config-options-in-hola-0-6).

For a **multi-user server** use *managed* workspaces instead: set `"workspace_mode": "managed"` with
a `"managed_root"` (starter: [docs/agents.server-example.json](docs/agents.server-example.json)). The
core then gives every conversation its own private directory `<managed_root>/<user>/<project>` — named
after what is being built (`browser-os`, `stocks-simulator`; the assistant names it, and `-2`, `-3`… keep
names unique), created on first delegation, reused for follow-ups in the same chat (even if you rename
the folder), and invisible to other users. Chats from before this keep their `<chat id>` folders. The model
no longer picks a folder; the consent modal shows the assigned one. In the desktop app you can
**change** it from that modal with a native folder picker (or create a subfolder there), and the
choice sticks for the rest of the conversation; the picker is confined to your own workspace area
(`<managed_root>/<your user folder>`, or the configured roots in `roots` mode), so it can never reach
another user's folders. Your user folder is named from your username (`bud`, or `bud-2` if that name is
taken) the first time it is needed and then stays put, even if you rename yourself; a folder from an
older version named after your user id (`usr_…`) is moved to the new name once, with a link left at
the old name so saved paths keep working. SFTP logins land in the same folder.

Instead of installing the agent on the server, you can run it in a **Docker container**: build the
bundled Pi image and point its entry at it —

```bash
make agent-image        # docker build -t omni-agent-pi:latest docker/agent-pi
```

```json
{ "id": "pi", "type": "pi", "command": "pi", "runtime": "docker", "image": "omni-agent-pi:latest" }
```

Hola has no bundled image in this repository. Supply your own image containing Hola 0.6+ and
`hola-coder`, for example
`{"id":"hola","type":"hola","command":"hola-coder","runtime":"docker","image":"your-hola-image:tag"}`.

Per delegation the core runs either image with the workspace mounted at `/workspace`, as your own
uid/gid, with all capabilities dropped; the host only needs the `docker` CLI (plus `git` for the
run card's change summary). `docker_network` defaults to `host` so `localhost` model endpoints just
work on Linux; on macOS/Windows Docker Desktop set `"docker_network": "bridge"` — the core then
rewrites `localhost` endpoint URLs to `host.docker.internal` automatically. This is not optional on
macOS: Docker Desktop's host networking does not give the container this machine's loopback, so with
`host` the agent cannot reach the model and the run ends with no output. The desktop app's Agent
handoff form defaults to `bridge` for that reason.

**Getting at the files.** With managed workspaces, add `"sftp": { "enabled": true, "addr": ":2222" }`
and the core embeds an SFTP server over the workspace tree. Users sign in with their omni-chat
username and password and see only their own chats' folders (read-write — copy results out, or drop
input files in for the next delegation):

```bash
sftp -P 2222 alice@your-server          # CLI
# VS Code: install the "SSH FS" extension and add sftp://alice@your-server:2222
#   (SSH FS, not Remote-SSH — Remote-SSH must exec a server on the remote and
#   this port is sftp-subsystem-only, no shell/exec)
# FileZilla/Cyberduck: sftp, host your-server, port 2222, password login
```

There is no shell access — only the SFTP subsystem, jailed per user. The server's host key is
generated on first start at `<config-dir>/sftp_host_key`. Each agent-run card in the chat shows a
copy button with a ready-to-paste `sftp://you@host:port/<chat folder>` address; if the externally
reachable port differs from the listen port (e.g. a compose port mapping), set
`"public_port": <port>` in the `sftp` block so the advertised address is right.

Once configured, turn on the **Agent** toggle (the robot tray button or its Tools-menu switch) in the composer and ask for
something that needs a real workspace — *"in ~/Work/myproj, add a failing test for the parser and
make it pass — delegate it."* The model writes a self-contained brief and a **consent modal** appears
showing the target folder and the editable brief; nothing runs until you approve, and the agent sees
exactly what you approve. The subagent runs on the same model your chat is using — its model calls
are relayed through the core, so every configured endpoint works (including subscription backends
like the ChatGPT Codex endpoint) and the agent process never receives your endpoint's API key, only
a token valid for that one run. While it works you see a live activity card with an animated
working indicator, a live elapsed timer, and a **Stop task** button — so even a quiet agent still
looks active. When it finishes, a collapsed run card records
the brief, what it did, its summary, and a `git diff --stat` of the changes — stored with the message
so it survives reload. Denying, stopping, or a timeout all leave the model to answer gracefully; the
turn never fails on an agent error. Each turn allows an initial delegation plus one corrective
handoff, with fresh approval for each, and only one agent runs per user at a time. Denying or
stopping a task ends further handoffs for that turn. A finished run is not proof the task succeeded;
the summary and validation results describe what actually happened.

When existing code is in the conversation, the assistant can pass its saved code blocks directly
to the agent as input files. The consent modal lists the selected blocks; after approval, the core
copies their exact bytes into a separate `.omni-handoff-*` folder without overwriting project
files. Up to eight blocks (1 MiB total) are allowed, separately from the 32 KiB task brief.
The agent reads those files instead of receiving a retyped copy of the code.
This includes code in your current message or edited message, and the original answer when
revising an assistant response. A folder picked or reset during approval also applies to
the corrective handoff within that same turn.

Omni stops tool attempts after three consecutive failures and asks for an honest blocker report.
Revising an answer does not make image links invented by the assistant trusted user links;
URLs in your actual edit request remain eligible.
Image downloads require a user-supplied URL, an image URL returned by image search or a fetched
page, or a supported live-chart endpoint matching a ticker in your current chart request.
Invented placeholder image URLs and unrelated chart shortcuts are rejected before
any download; image tools cannot retrieve code from the conversation.

Adding support for another agent is a small, documented Go integration — see
[docs/dev/agent-integrations.md](docs/dev/agent-integrations.md).

## MCP tools

**Settings → Integrations → MCP servers** shows each server once, with its connection status,
sign-in controls, and account switch. Admins use **Manage** to edit a server or the trash icon
to remove it after confirmation. **Add server** opens a form; Cancel discards it without adding
a row. With no servers, an introductory card offers one **Add server** action. Once a server
has been added, the compact **Tools per turn** control and Add server sit below the full-width
heading, wrapping on smaller screens. Server edits apply with
**Save & restart**. HTTP servers can be managed in web and native
apps; local command (stdio) editing requires the desktop app and is unavailable on iPad.
Saved server names stay fixed. Existing stdio environment settings are preserved without exposing
their values in Settings. Removing every server disables MCP after restart.

On each server row, each user can still connect, disconnect, or enable the server
immediately for their own account. Changing a server URL requires a new OAuth sign-in; replacing
a URL, command, or authentication setting also requires fresh tool approvals in existing chats.
The editor writes the same `mcp.json` described below and honors `CHAT_MCP_PATH`. A read-only
configuration directory prevents saving; concurrent changes are reported instead of overwritten.

Tool-capable models can also call tools from **MCP servers** (Model Context Protocol) — remote
services over Streamable HTTP or local commands the operator whitelists (spawned over stdio). This
is off unless an admin configures it in Settings or creates `<config-dir>/mcp.json` (default
`~/.config/omni-chat/mcp.json`; `CHAT_MCP_PATH` overrides only this file). A ready-to-copy starter
lives at [docs/mcp.example.json](docs/mcp.example.json):

```bash
cp docs/mcp.example.json ~/.config/omni-chat/mcp.json
# or for a one-off run:
CHAT_MCP_PATH=docs/mcp.example.json make dev
```

```json
{
  "schema_version": 1,
  "servers": [
    { "name": "files", "transport": "stdio",
      "command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/data"] },
    { "name": "notes", "transport": "http", "url": "http://localhost:9000/mcp",
      "auth": "bearer_env", "token_env": "NOTES_MCP_TOKEN" }
  ]
}
```

Each server's tools appear to the model as `mcp_<server>_<tool>` functions. Turn on the **MCP
Tools** toggle (the server button) in the composer to enable them for the current chat (off by
default). Every call shows a **consent modal** before anything runs: it names the tool and server in plain
language, explains what the tool does in the server's own words (its schema description), and lists
each argument on a labelled row — with the argument's schema description behind an ⓘ, long values
clamped to a readable preview you can expand, and the exact JSON payload one click away under
*"View raw JSON"*. The rows are built from the arguments the model actually sent, so an argument the
tool never declared still shows up. An *"always allow this tool in this chat"* checkbox stops repeat
prompts for tools you trust. Per-response outcomes land in the message's info popover, and each call (server,
tool, status, duration — no payloads) is stored with the message. Optional per-server fields:
`tool_allowlist` (offer only the listed tools), `always_confirm` (see below), `timeout_seconds`
(default 30), and `env` for stdio servers (a value of `"env:NAME"` reads NAME from the core's
environment so secrets stay out of the file). A dead or unreachable server just contributes
nothing — the turn never fails on it.

One top-level field tunes the whole file: `max_offered_tools` (default 128, max 512) caps how many
tools are offered to the model per turn across **all** servers. Servers are consumed in `mcp.json`
order, so if you run several large servers whose combined tools exceed the cap, later ones get
starved — raise `max_offered_tools`, reorder, or narrow a big server with `tool_allowlist`. The core
logs `mcp: offered tool cap reached` when it truncates.

Set `"always_confirm": true` on a server whose tools take **real-world action you never want
repeated unattended** — placing a trade, moving money. Every call on that server then asks, no
matter how many times you approve: the "always allow" checkbox is not offered, and a grant saved
before you set the flag stops being honored. The core enforces this itself, so it holds regardless
of which client is rendering the prompt.

Each configured server has an on/off **toggle** in the Options sidebar's **Services** section. It's
per-user and account-wide: switching a server off means it offers **no tools** in any of your chats
(and its live session is dropped) until you switch it back on — a quick way to silence one server
without editing `mcp.json` or disabling the rest. This is distinct from the per-chat **MCP Tools**
composer toggle, which turns *all* MCP on or off for a single chat.

Servers declaring `"auth": "oauth"` need a per-user sign-in: the Options sidebar's **Services**
section shows a **Connect** button that opens the provider's authorization page (OAuth
2.1 with PKCE; the server's authorization endpoints and client registration are discovered
automatically). In the desktop app that is your **default browser**, not a tab inside the app — many
identity providers refuse to sign in inside an embedded webview, and the webview cannot open tabs.
The Services list then polls for a couple of minutes, so the row flips to connected on its own once
you finish. Each user connects their own account — one user's tools never ride another's
credentials — and **Disconnect** revokes the stored connection. Tokens are stored encrypted at rest
(AES-GCM) in the app database; the data key lives at `<config-dir>/token.key` (created on first
use, `0600`), falling back to a `token.key` beside the database when the config dir is read-only
(e.g. an `:ro` Docker bind mount) — an existing key wins wherever it lives.

### Robinhood agentic trading

Robinhood publishes an official MCP server, so a tool-capable model can read your portfolio and
place orders from a chat. It needs no special support beyond the `oauth` + `always_confirm` fields
above — add it to `mcp.json`:

```json
{ "name": "robinhood", "transport": "http",
  "url": "https://agent.robinhood.com/mcp/trading",
  "auth": "oauth", "always_confirm": true, "timeout_seconds": 30 }
```

Then open the Options sidebar's **Services** section and hit **Connect** next to `robinhood`. This
opens Robinhood's authorization page; sign in there (a **desktop** browser is required — Robinhood
creates your *Agentic* account as part of the first authorization). Once connected, turn on **MCP
Tools** in the composer for the chat you want to trade from.

Two boundaries are worth knowing:

- Robinhood confines order placement to your **Agentic account** — a separate, separately funded
  account. Reads (positions, balances, order history, watchlists) span your accounts; writes do
  not. Your exposure is bounded by what you fund there.
- Every single call asks for your approval, because the entry sets `always_confirm`. The consent
  modal shows the symbol, side, and quantity as labelled rows before anything is sent. Approving one
  order never pre-approves the next.

Order placement is real. An LLM can misread a request, act on a stale quote, or size a position
wrongly — read each consent prompt before approving it, and treat a denied call as the safe default.

### Docker: running npx MCP plugins (sidecar overlay)

The Docker image deliberately ships without Node, so `stdio` servers launched with `npx` cannot run
inside the omni-chat container. The `compose.mcp.yaml` overlay provides that capability as
**sidecars**: each npx-installed plugin runs in a stock Node container, wrapped by
[supergateway](https://www.npmjs.com/package/supergateway), which bridges the plugin's stdio to
Streamable HTTP — and the core connects to it with an ordinary `http` entry in `config/mcp.json`.
The overlay ships two ready-made sidecars, `mcp-figma`
([figma-developer-mcp](https://www.npmjs.com/package/figma-developer-mcp); set `FIGMA_API_KEY` in
`.env`) and `mcp-files` (the filesystem server over the host directory named by `MCP_FILES_DIR`,
default `./mcp-demo`):

```bash
docker compose -f compose.yaml -f compose.mcp.yaml up -d
```

```json
{
  "schema_version": 1,
  "servers": [
    { "name": "files", "transport": "http", "url": "http://mcp-files:8000/mcp" },
    { "name": "figma", "transport": "http", "url": "http://mcp-figma:8000/mcp" }
  ]
}
```

To add another plugin, copy a service block in the overlay, change the inner `npx -y <package> …`
command and the published host port, and add the matching one-line `http` entry to
`config/mcp.json`. The first start downloads the packages into a shared npm-cache volume; restarts
are fast. Secrets stay in the sidecar's environment (from `.env`) and never reach the core or the
config file. For a host-run core (`make dev`), `compose.mcp-only.yaml` starts just the sidecars —
point `~/.config/omni-chat/mcp.json` at the published ports instead
(`http://127.0.0.1:8807/mcp` for figma, `http://127.0.0.1:8808/mcp` for files).

## Image generation

With an image backend configured (`CHAT_IMAGE_GEN_URL`), a tool-capable model can create pictures:
ask *"Generate an image of a cyberpunk cat riding a skateboard"* and the model calls a
`generate_image` function with a detailed prompt (and an optional shape — square, portrait, or
landscape). The core generates the image server-side against the backend, stores it with the
conversation, and shows an **animated placeholder inline the moment generation starts**; with a
streaming backend (the bundled sidecar, or anything speaking OpenAI's `partial_images` streaming)
the placeholder becomes a **blurred preview of the actual image that sharpens as generation
progresses**, with a live percentage — then the finished image replaces it in place, with the
prompt as a
caption, a **Download** button, and a **Variation** button that prefills the composer with a
variation request you can edit before sending (the model then re-generates with a fresh seed).
Images are private to your account like any attachment, survive reload, and are included in chat
exports. Each response is budgeted to two images; if the backend is down or slow the model is told
generation failed and answers gracefully — the turn never errors on it.

The bundled image server renders **one image at a time** (concurrent diffusions on one GPU are
slower than running back-to-back). When someone else's generation is in flight, yours waits its
turn and the placeholder says *"Waiting for the image server… (N ahead)"* — queued jobs never time
out while visibly waiting. The queue is bounded (`IMAGEGEN_MAX_QUEUE`, default 4 waiters); beyond
that the server reports busy and the assistant tells you to try again shortly.

**Editing and image-to-image.** The model can also transform an existing image with a companion
`edit_image` tool: attach a photo and say *"make this look like a watercolor"*, click the **Edit**
button on any generated image (it prefills the composer with the image's reference), or just say
*"now make it night time"* about the image it produced a moment ago. **This works with any
tool-capable chat model — no vision support required**: the model passes an image *reference* (an
id the app provides in text) plus your instruction, and the image backend does the pixel work. A
vision model can describe the image to itself for richer edit prompts, but it's optional. Edited
results show an "Edited ·" caption and count against the same two-images-per-response budget, and
the placeholder starts from a blurred copy of the source image so you see what's being transformed.

The tools are offered whenever the backend is configured and the model supports tool calling — there
is no per-chat toggle. The backend speaks the **OpenAI Images API** (`POST /v1/images/generations`
and multipart `POST /v1/images/edits`), so you can point `CHAT_IMAGE_GEN_URL` at the bundled
[Z-Image-Turbo sidecar](#image-generation-under-compose) (`docker/imagegen/`, GPU required) or at
any other compatible server. The sidecar's edit quality has two levels: leave `IMAGEGEN_EDIT_MODEL_ID` unset for classic
img2img re-imagining using the already-loaded base model (no extra download — the right default
for most machines), or set it to a dedicated
instruction-edit model for true "change X to Y" edits:
[`Qwen/Qwen-Image-Edit-2509`](https://huggingface.co/Qwen/Qwen-Image-Edit-2509) (Apache-2.0, the
reference open editor — but ~20B, so plan for ~40–60 GB) or
`black-forest-labs/FLUX.1-Kontext-dev` (12B; gated + non-commercial license — accept it on HF and
set `HF_TOKEN`). Tongyi announced a same-family Z-Image-Edit, but no public weights exist as of
July 2026.

**Tuning fallback edits** (no `IMAGEGEN_EDIT_MODEL_ID`): the bundled Z-Image-Turbo base is
guidance-free, so a style prompt only steers weakly and edits keep the composition while lightly
re-imagining it. Two levers make restyles land: raise `IMAGEGEN_EDIT_STRENGTH` (default 0.7)
toward ~0.8 for a stronger change (lower toward 0.6 if the subject drifts), and rely on the full
descriptive prompt the model now writes (e.g. "the same photo as a soft watercolor painting")
rather than a terse instruction. `IMAGEGEN_EDIT_GUIDANCE` (default 1.0) only helps if your model
responds to CFG — the distilled base can burn/over-saturate above 1, so leave it unless you swap
in a CFG-capable model. True "add a hat / change X to Y" edits need a dedicated
`IMAGEGEN_EDIT_MODEL_ID`, which is impractical under ~32 GB of memory.

Generation can take a while on local hardware — raise
`CHAT_IMAGE_GEN_TIMEOUT` if your backend cold-loads the model.

In the right Options sidebar, **New chat defaults** sets Search, Code Execution,
Thinking, Agent, MCP tools, Read aloud, Image tools, and Memory for future chats.
Thinking, Image tools, and Memory start on; Search and the others start off. Composer
switches override these choices for the current chat. Memory on enables reading and
saving memories; off-the-record chats always keep memory off. Read aloud also works
with browser speech. **Thinking effort** groups the model effort and Agent thinking
controls; use its eye button to show or hide them.

## Read aloud (text-to-speech)

With a speech backend configured (`CHAT_TTS_URL`, or `tts[]` in `endpoints.json`), assistant
responses can be read out loud:

- **Speaker button** — every assistant message grows a speaker icon in its action row. Click to
  hear it. While the audio is prepared, a ring around a timer fills from gray to orange and gently
  pulses — an estimate from the reply's length that eases toward full and holds until the audio
  arrives; while it speaks, click the pause icon to pause. Click the play icon to resume from
  the same position. Clicking during preparation cancels it. Starting another message replaces
  the current playback. Replaying
  the same message in the same session reuses the audio without re-synthesizing.
- **Read aloud toggle** — a per-chat toggle (in the composer tray or Tools menu) that reads each
  response aloud automatically when it finishes streaming. Errored or stopped turns are never
  spoken. A "New chat defaults" switch in the Options sidebar makes it the default for new chats.
- **Voice preference** — expand the default-collapsed **Voice & Dictation** section in Settings;
  its **Voice Engine** group picks your account's engine, voice, and speed (0.5×–2×), with a
  **Preview** button. The preference is account-synced and applies everywhere you sign in.
- **Device fallback** — with no speech backend configured (or every configured one down), read-aloud
  automatically falls back to **your device's own OS voice** via the browser's built-in speech
  synthesis: instant, free, offline. A **Voice engine** setting (Auto / Server / This device) can
  also force it outright. The device engine uses the voice configured at the OS level (macOS:
  System Settings → Spoken Content) — no in-app voice list — and honors your speed preference.

The core converts the message's markdown to speakable text (code blocks become a short "code block
omitted" note, links read their label, each table row is read with its column names, symbols, units
and shortcuts such as ≈, ±, °C, tok/s and e.g. are said in words, math is read aloud, and emoji are
skipped; names and acronyms stay as written), splits long replies on sentence boundaries, and streams the audio through — nothing is stored, and off-the-record chats can speak
too. Visible backends appear under **Speech** in the Services panel with the usual health LED.

The backend contract is the **OpenAI speech API** (`POST /v1/audio/speech`), so the bundled
[OmniVoice sidecar](#text-to-speech-under-compose) (`docker/tts/` — runs natively on Apple
Silicon via MPS, or in Docker with CUDA/CPU elsewhere) and any hosted OpenAI-compatible endpoint
(e.g. api.openai.com with `gpt-4o-mini-tts`) are interchangeable. Named backends with per-backend
voices live in `endpoints.json` `tts[]` (see [Multiple backends](#multiple-backends)). With the
bundled sidecar, a voice that isn't one of the listed presets is treated as a raw OmniVoice
attribute description — type your own (e.g. `female, teenager, high pitch, australian accent`).

## Hands-free voice mode

In **Settings → Models**, download **Gemma 4 E2B** (5.52 GB, Apache-2.0), the
fast default. **Gemma 4 E4B** (8.59 GB, Apache-2.0, needs about 10 GB of free
memory) is an optional second download for comparing knowledge against latency;
pick it from the **Voice model** menu in Settings and in the voice overlay (the
overlay remembers the choice in this browser). On an Apple-Silicon test Mac, E4B
took about 560 ms to start speaking versus about 320 ms for E2B, and followed the
tool rules less reliably. Only one model is loaded at a time. Each download
also sets up local **Kokoro** speech (MLX on Apple Silicon, ONNX on
Linux; watch Read aloud for its progress). Gemma hears each utterance directly
through its own audio encoder and answers in text with thinking off; Kokoro
speaks the answer sentence by sentence while Gemma is still writing, so the first
words usually play a few hundred milliseconds after you stop talking. A second
runtime slot transcribes the same audio for the saved transcript, off the reply
path. Voice needs local Kokoro: with Read aloud's Kokoro turned off on the host,
voice mode is unavailable.

Choose the composer’s **Voice** button and **Start voice**. An amber glass orb,
with oMNI inside, listens, thinks and speaks; its eye follows the pointer. Pause
to finish a turn, or mute/end using the overlay. A pause mid-question is fine:
if you carry on within about a second and a half, before any reply has finished
playing, the two parts become one question. While oMNI is speaking, short
acknowledgements such as "mhm" or "go on" do not interrupt; keep talking for
about half a second to cut in. A single turn can last up to 30 seconds.

Search, Memory and Wake word use the same icon-only toggle buttons as the chat
panel, with descriptions available on hover or keyboard focus.

**Wake word.** Turn on **Wake word** (the ear toggle) to use voice mode like a
voice assistant: after Start voice, oMNI waits for "Hey Omni" (the status says
so) and answers nothing until then. A rising chime marks that it is listening;
keep chatting as long as you like, and after 30 seconds of quiet a falling
chime marks that it stopped and is waiting for "Hey Omni" again. Say
**"Hey Omni, stop"** (or "go to sleep", "that's all") to send it back to sleep
at any point, even over a reply; the screen shows "30 sec silence or say “Hey
Omni, stop”" while it is listening. "Hey Omni,
what's the capital of France?" in one breath wakes it and answers. While waiting, the
model transcribes only the first seconds of each utterance to look for the wake
phrase; nothing said before it is answered, saved or logged. The toggle can be
switched during a call and is remembered in this browser. A waiting call ends
after an hour without "Hey Omni".

The model loads when you press Start voice and unloads as soon as you leave
voice mode, unless a typed chat is using the same model at that moment.

Voice conversations currently use English. A new voice chat starts as
**Voice chat**. When the call ends, the auxiliary model renames it
**Voice chat about** the subject of the transcript. An existing chat keeps its
title. The current chat keeps a text transcript and its selected text model;
raw audio is discarded. Off-the-record voice keeps the transcript only in RAM.
Each saved reply records how long it took from the end of your speech to the
first audio and to the end of the reply. Voice uses basic identity, location and
home time zone, device OS information, current date/time, persona, instructions,
and the last few exchanges of the chat. In US time zones it also gets the next
seven holidays and clock changes (including Black Friday and Cyber Monday) with
their weekdays, computed by the core. **Memory** in the voice overlay (on by
default when your new-chat default for Memory is on; unavailable off the record)
lets oMNI read your saved memories as context: the ones relevant to the last
exchanges, topped up with pinned and recent ones. Voice only reads them. It
never saves, updates or forgets a memory, so there is no "Remembered" notice
or undo during a call. Stored summaries and extended profile
interests/goals/background are excluded. Voice does not run memory extraction,
consolidation or summary jobs.

**Search** in the voice overlay starts from the chat's Search setting and gates
every voice tool, all of which reach the network: **web_search** and **fetch_url**,
when the host has them configured (at most two web calls per spoken turn).
While a tool runs, oMNI says "Let me check.", the orb shows a
comet circling the glass, and a soft two-note cue pulses until the answer
starts. Web sources a reply used are saved with it and appear on the message;
they stay in the call's context so "what are the steps for the first one?" can
read that page. If oMNI says it will check something but doesn't, the core
makes it run the lookup, and a lookup written out as text is run, not read
aloud. Before any tool has run in a turn, speech stops at a promise to check
("Let me take another look.") and a claim of having checked ("I've re-checked
the prices…") is never spoken, so a made-up result is not heard; the turn
calls the tool instead, or says it couldn't check. Each tool call is listed
with the reply's generation details. Only the tool's query (search words or a URL)
leaves the host; your voice never does. With Search off, oMNI answers from what it
knows and says when something
needs Search. Code execution, agents, MCP and image tools are not part of a call.
Voice aims to answer first, give concrete suggestions, and ask only for essential
missing details.

The optional runtime is a stock `llama-server` from pinned llama.cpp, with Metal
acceleration on Apple-Silicon Macs. Linux x86_64/ARM64 defaults to CPU; build
with `VOICE_BACKEND=cuda` on an NVIDIA CUDA development host for GPU
acceleration. Desktop packages bundle the runtime; an administrator downloads
the model once for all accounts. Only one voice conversation runs per core at a
time. The model unloads after five idle minutes. CPU latency depends on the host.
Voice mode is not available on iPhone or iPad.

Standalone web operators install the runtime separately (Git, CMake and a C++17
compiler are build prerequisites; Linux Vulkan builds also need `libvulkan-dev`,
`glslc` and `spirv-headers` on Ubuntu; CUDA builds need a compatible CUDA toolkit):

```sh
make voice-runtime                       # Metal on macOS; Vulkan + CPU fallback on Linux
# Or: VOICE_BACKEND=cuda make voice-runtime  # CUDA + CPU fallback
# Or: VOICE_BACKEND=auto make voice-runtime  # CUDA + Vulkan + CPU (both toolkits)
# Or: VOICE_BACKEND=cpu make voice-runtime
export CHAT_VOICE_RUNTIME="$PWD/desktop/vendor/voice/omni-voice-runtime"
make dev
```

Linux packages include Vulkan acceleration for compatible NVIDIA, AMD and Intel
GPUs plus an independent CPU fallback. Install your GPU's Vulkan driver and host
Vulkan loader; end users do not need a development toolkit. The core probes GPUs
only when a model is requested, prefers CUDA when included, then Vulkan, then CPU,
and retries another runtime if GPU loading fails. Settings reports the selected
backend/device and fallback explanation; selection does not mean every operation
runs on the GPU. Keep the complete `desktop/vendor/voice/` directory together when
deploying a standalone server. Kokoro uses CUDA on NVIDIA Linux x86_64 hosts, with an INT8 CPU fallback.
On other Linux hosts it uses CPU ONNX. Its next explicit Download installs the
CUDA packages and an additional pinned FP32 model (about 326 MB) when the NVIDIA
driver is present; packages need additional disk space. No CUDA toolkit install
is needed. `CHAT_KOKORO_ACCELERATION=auto` is the default; operators can force
`cpu` or request `cuda` (Linux x86_64 only). Settings reports the selected backend
after speech loads it, plus any CPU fallback explanation. This describes provider
selection, not execution of every operation on the GPU. An existing CPU install
needs Download again after this update; model and package caches are reused.

Voice build caches are separated by backend and source checkout. Switching
`VOICE_SOURCE_DIR` needs no manual CMake cache cleanup. An existing build
checkout that still carries the patch earlier releases applied for the retired
LFM3 model is restored to the pinned source automatically.

`make build` remains independent of C++/Rust and does not require voice support.
The model runs on the core host; a remote browser needs HTTPS for microphone
access.

**The voice models are also chat models.** Once downloaded, Gemma 4 E2B and E4B
appear in the composer's model picker under **On this device** (with the
on-device MLX model on Macs that have one), served by the same local runtime on
macOS and Linux. Text chats with them get everything voice mode leaves off:
thinking (the Thinking toggle), image attachments, web search and page reading,
code execution, agents, MCP and image tools, memory, the full profile, and
32K-token conversations. A chat and a voice call can share the loaded model; a
chat or call that needs the other model while one is in use gets a busy
message. Listing never loads a model; the first message does, and it unloads
after five idle minutes. Text chat needs no Kokoro.

Voice weights live in `voice/gemma-4-e2b/model/` (and
`voice/gemma-4-e4b/model/`) beside the database.
Removing them does not delete chat transcripts. Failed loads are retried by
starting voice again, without downloading the weights again. On first start, the
core deletes downloads of the retired LFM3-Audio-2B (`voice/model/`) and
Qwen2.5-Omni-7B (`voice/qwen2.5-omni-7b/`) models.

To check conversation quality and latency against a running core in web mode
(macOS; `say` voices the questions):

```sh
cd core && go run ./cmd/voice-eval -url http://127.0.0.1:PORT -setup
# Compare models: add -model Gemma-4-E4B (default Gemma-4-E2B)
```

It replays scripted spoken questions over the voice WebSocket, then reports the
time to first audio and flags repeated or cut-off answers, needless clarifying
questions, missing tool use and links read aloud.
Add `-wake` to run the wake-word checks; a listening error stops that script
immediately and exits with the error.

## Voice input (dictation)

A mic button in the composer, before Send, turns speech into text:

- **Mic button / `Ctrl+Shift+D`** — click (or press the shortcut) to start recording; click again
  (or press it again) to stop and transcribe. The transcribed text lands at the cursor. `Escape`
  cancels an in-progress recording and discards the audio. Recording auto-stops after 3 minutes.
- **Two engines** — the **server** engine uploads the recording to a configured transcription
  backend (`CHAT_STT_URL`, or `stt[]` in `endpoints.json`); the **browser** engine uses the
  device's own on-device `SpeechRecognition` (Chrome, Safari — no upload, no server needed).
  The **Dictation** group in the Options sidebar's **Voice & Dictation** section picks the engine
  (Auto / Server / This device) and dictation language; Auto prefers the server backend when
  configured and reachable, else falls back to the browser engine.
- **Privacy** — the core holds audio in memory, forwards it to the transcription backend, and
  discards it; it is never written to disk or stored in the database on the core's side. The
  bundled whisper sidecar uses a transient temp file it deletes right after transcription.

The backend contract is the **OpenAI transcription API** (`POST /v1/audio/transcriptions`), so the
bundled [whisper sidecar](#speech-to-text-under-compose) (`docker/stt/` — runs natively on Apple
Silicon via MLX, or in Docker with CUDA/CPU elsewhere) and any hosted OpenAI-compatible endpoint
(e.g. api.openai.com with `whisper-1`) are interchangeable. Each backend appears under
**Dictation** in the Services panel with the usual health LED:

```bash
CHAT_STT_URL=https://api.openai.com CHAT_STT_MODEL=whisper-1 CHAT_STT_API_KEY=sk-… make dev
```

Named backends live in `endpoints.json` `stt[]` (see [Multiple backends](#multiple-backends)). With
no server backend configured at all, the mic button still works wherever the browser engine is
supported.

## Multiple backends

To combine models from several OpenAI-compatible backends (e.g. a local vLLM/LiteLLM proxy alongside a hosted provider) in one model picker, create `<config-dir>/endpoints.json` (default `~/.config/omni-chat/endpoints.json`; `CHAT_ENDPOINTS_PATH` overrides only this file). Servers are described once in a top-level `connections[]` array (`name`, `label`, `base_url`, `api_key`/`api_key_env`/`auth`, `protocol`, and an optional `runtime` server type — `llamacpp`, `vllm`, `ollama`, `lmstudio`, `omlx`, `litellm`, `sglang`, `openai` or `other` — that Scan now and Test connection fill in and Settings lets you correct); the `endpoints[]` array then names one `connection` per chat backend and keeps only the chat-capability fields below. **`schema_version` must be `2`** — this is the only format the core reads, and an older per-endpoint-URL file fails startup with a message pointing at `docs/endpoints.example.jsonc` and the manual's Configuration Reference chapter (see [Editing endpoints from inside the app](#editing-endpoints-from-inside-the-app) for the desktop UI, which does this typing for you). Per-connection/per-endpoint capability fields mirror the `CHAT_*` model/request settings and apply only to that backend. An optional `model_overrides` array declares per-model capability metadata (matched by a `model_pattern` glob on the model id) — `vision`, `tool_calling`, `params_b`, `vendor`, `family` — that the Auto router uses; overrides win over the built-in model catalog and over id inference. A `model_overrides` entry may also carry `extra_body` — request params sent only for matching models, overriding the endpoint-wide `extra_body` per key — and `prompt_profile` (see below). Mode-specific per-model request parameters belong in `thinking_overrides[].on_body` and `.off_body`; partial bodies merge over inferred adapters, so a sampling override does not need to repeat `chat_template_kwargs.enable_thinking`. `params_b` is also read from the backend when it reports one (llama.cpp's `meta.n_params`), which matters for aliases like `lfm2-tool` whose id carries no size.

Vision preprocessing is configured independently with `vision_budget`: `low` (1024 px, 1 MP per
image, 2 MP per turn), `balanced` (default: 1568 px, 2.5 MP/image, 5 MP/turn), or `high` (2560 px,
6 MP/image, 12 MP/turn). The same field in a matching `model_overrides` entry wins over the endpoint.

### Small models on modest hardware

Tool schemas are not free. A very small model shown a wide tool surface stops answering and starts routing:
asked to extract some fields as JSON, `LFM2-1.2B-Tool` replies *"I don't have a tool that can do that — would
you like me to search?"*, even though it answers the same question correctly when no tools are attached.
Measurement showed this is caused by the *presence* of tool schemas, not by prompt length or tool count —
shortening the prompt, adding a "just answer directly" instruction, and cutting ten tools to two all failed.

So OmniChat sizes the tool surface to the model. Below 2B parameters, a tool family is offered on the first
round only when the turn actually implicates it (you pasted a URL, asked for a picture, told it to remember
something, or asked about something current); below 10B, only `delegate_task` is withheld. Once the model
calls a tool the full surface returns, so multi-step work like search-then-read still chains. Models of
unknown size are treated as large and behave exactly as before — nothing is narrowed on a guess.

Parameter size comes from the backend when it reports one, otherwise from the model id or the built-in
catalog. Override it per endpoint or per model with `prompt_profile`:

```json
{
  "connections": [{ "name": "llamacpp-local", "base_url": "http://localhost:8000" }],
  "endpoints": [{
    "connection": "llamacpp-local",
    "prompt_profile": "auto",
    "model_overrides": [
      { "model_pattern": "lfm2-*", "params_b": 1.2 },
      { "model_pattern": "phi-4-mini*", "prompt_profile": "full" }
    ]
  }]
}
```

`auto` (the default) derives the profile from size; `full` restores the complete tool surface; `terse` and
`minimal` force the small-model behavior. `CHAT_PROMPT_PROFILE` does the same without a config file. Tools a
model is too small to use are dimmed in the composer's Tools menu with the reason.

To check how a model behaves under this framing, run `make probe ENDPOINT=http://localhost:8000 MODEL=<id>`.
It replays a fixed set of prompts twice — at the resolved profile and forced to `full` — and prints a
pass/fail table. It needs a live backend and is not part of `make check`.

Under **Settings → Web & tools → Web search**, below **Web fetch**, set **Search & fetch
calls per turn** from **1 to 32** (default **8**). It saves immediately for the
current chat; on a fresh or temporary chat, it applies when you send. The allowance
is also shared with explicit memory tools. Turning Search off and back on retains
the limit. Once it is exhausted, the core asks the model to
answer from the retrieved results and state any gaps. Code, agents, image tools,
and MCP keep their separate budgets. Available context does not extend this
research allowance. The context meter uses the latest model round's input;
turn-wide token totals count repeated prompts and are not context occupancy.

The response's Info panel includes **Generation limits & recovery**: the effective
context window and its source, each model round's output and thinking budgets,
reported token usage, remaining shared tool calls, tool outcomes, and the precise recovery trigger. A tool call
that was cut off or dropped is distinguished from a thinking-budget overrun.
Older recovered responses say the cause was not recorded. When a tool-using round
reaches the output limit without answer text, the core preserves its actual tool
results and retries once to write the answer; models with an off switch use it on
that retry. Endpoint caps and context budgeting still apply. Remote models use
the same core policy on Mac and iPad; the client device's memory does not size a
remote model's budgets.

Thinking-budget and empty-reply recovery can produce requested writing or code
directly; they do not require a web lookup or agent handoff. Tools remain available
when the request needs them, with the same consent and call limits. A model that
still returns no answer after the bounded retry reports `empty_response` instead
of saving a successful blank reply; regenerate or choose another model.

For a single-model local server whose catalog omits context limits, `/health`
supplies the serving window. A cold turn retries a failed background probe;
transient metadata failures retain the exact model's last verified limits and
label the source as cached. Explicit endpoint limits still win. When serving metadata
is absent, the core uses a known model's catalog default before the conservative
8192-token fallback. The [sourced context catalog](core/internal/modelcaps/context_windows.json)
covers concrete versions and sizes across the recognized model families, including
OpenAI, Claude, Qwen, DeepSeek, Llama, Gemma/Gemini, GLM, Mistral, Phi, Grok,
Liquid, SmolLM, Granite, MiniCPM, Nemotron, and Apple Foundation Models. It includes
short windows too (TinyLlama: 2048; Apple: 4096). Qwen3.8-Flash-Next defaults to
262144. See the [coverage and maintenance notes](docs/dev/model-context-defaults.md).
Diagnostics and `/api/models` mark this assumption as `catalog`, not a verified
server reading; later server metadata wins even when smaller. Unknown models keep
8192; limits are never guessed from hardware or a future model's family name.
Common GGUF/MLX quantization suffixes retain the known base default; unverified
fine-tunes, ambiguous aliases, and optional context extensions need metadata or
configuration. Published shorter quantized variants have their own entries.
If a server runs with a different limit and omits metadata, configure its actual
`context_window` in the matching `endpoints.json` chat entry (Settings → AI Servers).
Catalog defaults also apply to automatically discovered servers without adding a
saved connection.

Local reasoning models get two guardrails out of the box. First, known families (hybrid Qwen3.x, Gemma, gpt-oss, DeepSeek-R1, Nemotron, GLM-4.5+) automatically receive their publishers' recommended anti-repetition sampling on self-hosted servers (by `owned_by` or by a local/LAN/tailnet URL — see Reasoning models). Qwen3.5/3.6 and Qwen3.8 use their newer mode-specific recommendations instead of the original Qwen3 profile. Tune this with `sampling_defaults` (`"auto"`/`"on"`/`"off"`) per endpoint, override values shared by both modes via `extra_body`, or set per-model mode values with `thinking_overrides[].on_body`/`.off_body`. Explicit Qwen Instruct/Coder and Thinking-only variants remain fixed-mode; unqualified Qwen3.x models and fine-tunes inherit the hybrid switch on runtimes that expose it. Second, a reasoning guard bounds the thinking channel (`thinking.budget_tokens`, defaulting to 1024/2048 for small models and, for larger ones, a share of the context window scaled by Thinking effort and doubled for coding — see `CHAT_THINKING_BUDGET_TOKENS`). The budget rides on top of the response-length preset rather than eating into it, so a hard-thinking model never starves its own reply. Overrunning it is not a failure: the turn is re-asked once with thinking off, seeded by the model's own notes, and finishes normally. Only a repetition loop — or an overrun on a model whose thinking cannot be switched off — ends the turn with the "got stuck thinking" note offering **Retry without thinking** and **Regenerate**. A response the server cut off with nothing but thinking takes the same thinking-off retry when the model can switch thinking off. OmniChat also learns from each response: a server that stops a response short of what was asked reveals its real output limit, which later turns are sized to (thinking then gets at most half, so the answer keeps room), and the model's reported thinking tokens tune how the guard counts dense reasoning such as code. The Thinking label shows a live elapsed timer while a model reasons.

Beyond `api_key`/`api_key_env`, a connection may authenticate through **OAuth** (a subscription
sign-in instead of a key) and speak the **Responses API** instead of `/v1/chat/completions`. The
built-in provider is **ChatGPT / “Continue with ChatGPT”**:

```json
{
  "schema_version": 2,
  "connections": [{
    "name": "chatgpt",
    "base_url": "https://api.openai.com",
    "protocol": "responses",
    "auth": { "type": "oauth", "provider": "openai-codex" }
  }],
  "endpoints": [{ "connection": "chatgpt" }]
}
```

The saved provider identifier stays `openai-codex` for compatibility. The core migrates old
ChatGPT backend URLs to the public API and ignores old static/CLI model lists. Existing chats
retain their selected model; choose an available model if it is no longer offered. Existing Codex
CLI credentials require a one-time reconnect in **Settings → Integrations**.

OmniChat uses OpenAI's [official OSS sign-in flow](https://developers.openai.com/siwc/token-sharing-open-source/sign-in):
its own dynamic registration, PKCE, nonce and a verified ID token. Allow ChatGPT plan usage on the
OpenAI consent screen. A valid sign-in without the plan grant stays signed in but cannot perform
inference; **Enable ChatGPT plan usage** explicitly requests consent again. Eligibility and limits
are controlled by OpenAI. Requests consume the selected account's ChatGPT allowance;
**Settings → Integrations → ChatGPT → Manage usage** opens
[ChatGPT usage settings](https://chatgpt.com/settings/usage).

Accounts, issued client IDs, rotating tokens, scopes and verified identities are stored separately
and encrypted. Switching accounts refreshes the live `/v1/models` catalog. The core sends full
history to `/v1/responses` with `store:false` and `stream:true`, and requires `response.completed`.
The preview does not accept output/sampling parameters, so these are omitted upstream while local
input budgeting remains enforced. Image generation is not supported through ChatGPT plan usage.

A temporary callback listener starts before opening the system browser, preferring port 1455 and
falling back to a free port at `http://127.0.0.1:<port>/auth/callback`. For Compose on the browser's
host, `OMNI_OAUTH_PUBLISH_PORT=1455` forwards the preferred port (`CHAT_OAUTH_CALLBACK_BIND=0.0.0.0`
inside the container). Publishing is off by default. If the browser cannot reach the listener,
paste its complete callback URL into Integrations. Sign-out attempts remote session revocation,
then clears local access, refresh and ID tokens; if revocation cannot be confirmed the UI tells
you to disconnect OmniChat in ChatGPT settings. Saved account registrations and the host ID remain
for later sign-in. No developer API key or Codex CLI client ID is bundled.

A ready-to-copy, annotated starter lives at
[docs/endpoints.example.jsonc](docs/endpoints.example.jsonc) (the app never loads the `.jsonc`
file itself — copy the parts you need and delete the comments; a Docker-flavored variant is
[docs/endpoints.docker.example.jsonc](docs/endpoints.docker.example.jsonc)):

```bash
cp docs/endpoints.example.jsonc ~/.config/omni-chat/endpoints.json
# then delete the // comments, or start from the desktop app's AI Servers page instead
```

```json
{
  "schema_version": 2,
  "connections": [
    { "name": "local-litellm", "label": "Local LiteLLM", "base_url": "http://localhost:4000" },
    { "name": "openai", "label": "OpenAI", "base_url": "https://api.openai.com", "api_key_env": "OPENAI_API_KEY" }
  ],
  "default_endpoint": "local-litellm",
  "endpoints": [
    { "connection": "local-litellm" },
    { "connection": "openai", "max_tokens_field": "max_completion_tokens", "context_window": 128000 }
  ]
}
```

**Existing `endpoints.json` files from before this change must be recreated** — schema 1 (per-job
`name`/`base_url`/`api_key*`) fails startup with a pointer to the example above; there is no
automatic migration.

The model dropdown combines every backend's models under a selectable divider per backend (choosing the divider picks that backend's first model). A backend that fails to load at startup is shown as offline and skipped — the others still work. Each chat remembers both its model and backend. Endpoint API keys in this file are never written to SQLite, but note this owner-managed file is the one place a plaintext key may live; prefer `api_key_env` if you'd rather not store the secret in the file. When no `endpoints.json` exists, `CHAT_ENDPOINT_URL` is used and may be a single URL or a comma-separated list.

For local inference servers, `/api/models` also reports a normalized model residency state when the backend exposes one. OmniChat auto-detects Ollama (`/api/ps`), LM Studio (native v1, with v0 fallback), llama.cpp router mode (`/models`) and single-server mode (`/health`), vLLM (`/health` plus its served model list), and oMLX (`/v1/models/status`). The composer model picker shows this as a small status LED beside each real model (and next to the selected model on the closed picker); the Auto router and backend divider rows carry none. These probes are optional: unsupported or temporarily failing status endpoints leave the LED neutral without removing the model from the picker. The residency state also steers the default selection: a fresh session prefers your last-used model when it is online (loaded/loading/no-signal), else the next online model on the same backend, else an online model from another backend — and a selection whose backend vanishes self-heals the same way while you're on the welcome screen, returning to the remembered model when its backend comes back.

## Service availability & self-healing

Status detection validates provider-specific fields. A plain model catalog at
`/api/v0/models` (as TensorFold returns) is not LM Studio residency data: missing
or unrecognized `state` values remain unknown. For a single-model server, a
successful `/health` probe then supplies the loaded signal and green picker dot.

Optional integrations (agent runner, image-generation sidecar, web search, web fetch, embeddings, MCP servers) are tracked at runtime via `GET /api/status`. The core probes each configured service lazily while the app is visible — the image sidecar's `/health`, `docker version` for containerized agents, the SearXNG/reader base URL, the embeddings server's `/v1/models` — with results cached ~20 s, and every real tool call feeds the same status passively. There are no background probes when no client is watching.

This extends to startup: a **valid config the environment cannot satisfy never blocks the app**. If the agent workspace directory can't be created (not mounted into the container, read-only, wrong owner), the docker daemon is down, an agent's command or image is missing, or the SFTP host key can't be written to a read-only config dir, the core logs a warning naming the reason and disables just that feature — chat, search, and routing keep serving. (The OAuth token key first falls back to living beside the database; it only degrades when neither the config dir nor the data dir is writable.) Only an *invalid config file* (bad JSON, a missing explicit `CHAT_AGENTS_PATH`) still fails before `READY`. The agent workspace is provisioned on first use and re-checked by each status poll, so fixing the environment restores agents without a restart.

> **Note:** `config/agents.json` is what enables agents — not the `compose.agents.yaml` overlay. The base compose always mounts `./config`, so if that file exists while the overlay is absent (which is what mounts the workspace), agents come up unavailable with a warning explaining why.

When a configured service is down, the UI degrades gracefully instead of showing dead controls: the composer's **Agent** toggle dims with the reason as its tooltip (and the MCP toggle dims when every configured server is down), and an alert triangle appears in the composer row. Clicking it lists what needs attention — failed enabled chat backends and servers whose models **Need approval**, including model names when their catalog is available — plus the recent offline/online event history. **Review server** opens Settings → AI Servers for the existing sharing review; it grants no permission by itself. Approval warnings remain visible when no approved models are available. Backends disabled under Services → Chat backends are omitted. The Options sidebar's **Integrations** section shows every tracked service with the same status dots as Backends and a manual refresh button. Recovery is automatic: within one status poll (~15 s) of the service coming back, toggles re-enable and the alert clears. The core logs every transition (`service down` / `service recovered`, with downtime) for debugging.

## Auto (Smart Router)

The model picker also offers a virtual **✨ Auto (Smart Router)** entry whenever at least one real model is available. Selecting it classifies each turn (task type, complexity, required capabilities, input size) with fast, deterministic heuristics and routes it to the single best available real model/endpoint, falling back to the default endpoint's first model if nothing else is routable. It works out of the box with a built-in policy — no configuration required — and after a response the composer shows `Auto → <routed-model>`; the response's Generation details panel shows which model handled it and why.

Selection also considers each model's resolved capabilities — vision, tool-calling, parameter size, and vendor/family — drawn from a built-in catalog of common model ids, from id inference, or from a per-endpoint `model_overrides` array in `endpoints.json` (strongest first). Policy selectors can target the derived tags (`vision`, `size_tiny`/`size_small`/`size_medium`/`size_large`, `reasoning`, `vendor_<v>`/`family_<f>`), and a turn with an image attachment hard-requires a vision-capable model (relaxed only if none is available).

**Loaded models first.** On servers that report which models are in memory — Ollama, LM Studio, the llama.cpp router, oMLX (the same residency the picker's LEDs show) — Auto only picks among the models that are already loaded, so it never makes the server swap models just to answer a quick question. It loads another model only when no loaded one can handle the turn (an image with no loaded vision model, a prompt too long for their context, or web search with no loaded tool-calling model); the routing reason then says `no loaded model fits; loads <model>`. Models on a self-hosted server that reports no residency count as not loaded; hosted cloud APIs always count as ready.

**Jev by TypeSafe AI (optional).** For better judgement of each message, turn on **Settings → Models → Smart Router → Use Jev** and paste a [TypeSafe](https://typesafe.ai/) API key (**Test Jev** makes one tiny call to confirm the key and connection; the desktop stores the key in the Keychain as `OMNI_KEY_ROUTING`, a web install keeps it in `endpoints.json`). Jev is a non-generative decision model: one call per turn (about 0.2 s) rates the latest message's task and difficulty on five levels, whether it needs domain expertise, and whether you asked for a stronger model — so the local GPU isn't spent on classification. Auto then picks the model. Your message and a little recent context are sent to TypeSafe. Any Jev error or timeout (default 1500 ms) falls back to the built-in router silently; `router:jev` in the status panel shows whether Jev is answering.

**Cloud models in Auto.** With both local and cloud models (for example a ChatGPT subscription), **Settings → Models → Cloud models in Auto** decides when Auto may use the cloud: *Only for expert requests* (default — expert-level difficulty, an explicit "use your strongest model", or a follow-up in a thread a cloud model already answered), *Always*, or *Never*. In `endpoints.json`:

```jsonc
"routing": { "provider": "jev", "api_key_env": "TYPESAFE_API_KEY", "cloud": "expert", "timeout": "1500ms" }
```

**Fastest model that is good enough.** Every model gets a capability band — tiny, small, medium, large, frontier — from a `capability` in `model_overrides`, its parameter count (tiny < 2B ≤ small < 10B ≤ medium < 40B ≤ large), the built-in catalog for hosted models whose size isn't published, or a fallback (large for a cloud API, medium for your own server). A true reasoning model (R1, QwQ, gpt-oss, the o-series — not one that merely can switch thinking on), and a coder on a coding turn, rank one band higher. Each turn gets a target from its difficulty (simple → small+, moderate → medium+, hard → large+; Jev's five levels add trivial → tiny and expert → frontier; a moderate-or-harder request needing domain expertise → large+; "use your strongest model" → frontier), and Auto keeps the models that reach it and prefers the smallest of them. A substantive follow-up stays within one band of the model that answered the thread and prefers that same model; a simple one ("sum that up") drops to the fastest able model — unless it continues the previous request ("the code is above", "yes, do that"), which stays with the model that was handling it. Mixture-of-experts models rank by total parameters but count as fast by their active ones (`active_params_b`, inferred from ids like `qwen3-30b-a3b`). Difficulty alone never loads a model — except when Jev is confident a request is hard and nothing loaded is able enough. The full reasoning is in [the design record](docs/superpowers/specs/2026-09-27-auto-routing-capability-matching-design.md).

Power users can customize model tagging and per-task preferences with `<config-dir>/router.json` (default `~/.config/omni-chat/router.json`; `CHAT_ROUTER_PATH` overrides only this file). A ready-to-copy starter lives at [docs/router.example.json](docs/router.example.json):

```bash
cp docs/router.example.json ~/.config/omni-chat/router.json
# or for a one-off run:
CHAT_ROUTER_PATH=docs/router.example.json make dev
```

See PRD §11 "Router definitions" for the full schema.

### Semantic router classifier

By default the router classifies each turn with fast, deterministic heuristics only. To classify
turns semantically instead, you have two options:

- **Zero-config:** if the [auxiliary model](#auxiliary-model-chat-titles-memory-jobs-smart-routing)
  (`CHAT_AUX_*`) is configured, it automatically doubles as the classifier via the JSON-schema
  adapter — no extra setup. Disable this role with `CHAT_AUX_ROUTER=0`.
- **Dedicated model:** point the router at a purpose-built classifier with
  `CHAT_ROUTER_CLASSIFIER_URL` and `CHAT_ROUTER_CLASSIFIER_MODEL` (and optionally
  `CHAT_ROUTER_CLASSIFIER_API_KEY` / `CHAT_ROUTER_CLASSIFIER_TIMEOUT` / `CHAT_ROUTER_CLASSIFIER_FORMAT`),
  or add an equivalent `classifier` section to `router.json` (see the commented example in
  [docs/router.example.json](docs/router.example.json)) — env vars override the file per field. A
  dedicated classifier always takes precedence over the auxiliary model.

Semantic classification uses structured JSON with a general instruct model. The auxiliary
model provides this by default; an explicitly configured dedicated classifier uses the same
format. `CHAT_ROUTER_CLASSIFIER_FORMAT` accepts `auto` or `schema`, which are equivalent.
The classifier can suggest an Auto-profile persona; when it is disabled or too slow, a
deterministic task-affinity heuristic picks from the profile catalog.

On every routed turn the classifier races the heuristics against a deadline (default `3000ms`,
sized for a CPU-only sidecar classifying a fresh, full-context turn — see
[docs/router.example.json](docs/router.example.json) to tune it for your hardware).
Whichever finishes first within the deadline wins; a classifier error, timeout, or unset
config falls back to heuristics, so a turn never fails or blocks on it. The persisted
`routing_reason` records which one won, prefixed `semantic: ` or `heuristic: `, and the
per-message stats hover's decision time includes any time spent waiting on the classifier.

Use the existing `compose.aux.yaml` or `compose.aux-only.yaml` overlay to host the background
model for semantic classification as well as titles and memory.

### Auto profile

The profile dropdown also offers a synthetic **✨ Auto** entry alongside the built-in and any
custom profiles. `auto` is reserved — it is never a real profile you can define in
`profiles.json`. Picking Auto is an autopilot: it also switches the chat to the **✨ Auto (Smart
Router)** model (when that model is available), so a single choice hands both the backend model
and the per-turn persona to the router. Auto only picks a persona on an Auto (Smart Router) chat.
On such a turn the profile catalog is offered to the router: the `schema` semantic classifier, when
enabled, picks the best-fitting profile from it; otherwise (the classifier disabled
or too slow) a deterministic task-affinity heuristic matches the turn's task to a profile whose
description reads like that kind of work. Either way the chosen profile's persona is used and the
response shows `Auto → <Profile Label>` beside the response metadata, exactly like a manually-picked
profile would. When no profile fits (e.g. a trivial greeting) or the chat uses a manually-selected
model, Auto behaves like `No profile` and the response is simply labeled `Auto`. Reopening such a
chat restores the **Auto** profile selection rather than whatever persona it happened to route to on
the last turn.

## Manual Verification

To confirm settings are reaching the model:

1. Start your OpenAI-compatible endpoint.
2. Start OmniChat with `CHAT_ENDPOINT_URL` and, if needed, `CHAT_MAX_TOKENS_FIELD`.
3. Create/login in the browser.
4. Create or select a chat, choose a model, optionally edit Session Instructions or select a Profile, change Tone / Response Length / Creativity / Format, and send a message.
5. Check your endpoint or proxy logs. The upstream request should include exactly one `system` message, the selected model, and the configured max-token field.

If `CHAT_HONORS_SAMPLING=false`, `temperature` and `top_p` are intentionally omitted even when Creativity changes. If `CHAT_HONORS_SAMPLING=true`, Creativity maps to sampling parameters.

Token usage stats are shown when the backend reports them. The core normalizes OpenAI-compatible `usage` chunks and Ollama final-stream `prompt_eval_count` / `eval_count` metrics into the same message stats. Open the info icon beneath an assistant response for labeled token counts, prefill/generation speed, TTFT, thinking time when present, and total request-to-completion time formatted in seconds, minutes, or hours. Each new assistant message also snapshots its resolved model/endpoint, thinking mode, and whether web search was unavailable, unused, successful, empty, or failed, so later chat-setting changes do not rewrite history.

## Troubleshooting

### Finding core logs after a restart or crash

The desktop app writes `core.log` in its app log directory: on macOS,
`~/Library/Logs/org.geekaholic.omni-chat/`; on Linux,
`${XDG_DATA_HOME:-~/.local/share}/org.geekaholic.omni-chat/logs/`.
The core keeps the active file and two archives (`core.log.1`, `core.log.2`), each
up to 5 MiB, and appends across restarts. Files are owner-readable/writable only.
The splash/recovery view still shows the latest 400 lines from memory.

For a standalone web server, opt in with `CHAT_LOG_FILE=/path/to/core.log` and
restart. Use a dedicated writable path. If the file cannot be opened, the core
warns and continues on stderr; a later file-write failure warns once, and stderr
continues. The logger creates missing parent directories. Startup and chat-turn
records include diagnostic metadata (IDs, timing and byte counts), not transcripts.
Error messages are kept on one line, scrubbed for Authorization/Bearer values,
API keys, credential assignments and URL userinfo/query strings, then truncated
to 500 bytes. Provider errors retain their code, HTTP-status/retryable metadata,
optional request ID, and a scrubbed transport/decode cause (also one line, up to
500 bytes). Raw response bodies are excluded. Panic values remain type-only, with stack
locations available. URL fields retain only their scheme and host, and
credential/prompt/content fields are redacted. Review the files before sharing.

### Every write, including sign-in, returns 403 `cross_origin` behind a TLS proxy

Set `CHAT_TRUST_PROXY=true` on the core and restart it. The proxy must send
`X-Forwarded-Proto: https` and either preserve the public `Host` or send
`X-Forwarded-Host` with that public host (including any non-default port).
See [the reverse-proxy upgrade and nginx example](#required-upgrade-for-reverse-proxy-deployments).

### A response says “Something went wrong while generating this reply.”

If a background generation panics, OmniChat keeps the partial answer and marks the
turn with a non-retryable `internal_error`; other chats remain available.
The core logs `background job panicked` with the job name, panic type, and stack
trace. Include that log when reporting the failure.

### SearXNG exits because `server.secret_key` is unchanged

Recent SearXNG releases reject the bundled `ultrasecretkey`. Generate a unique installation secret
and recreate the overlay:

```bash
printf 'SEARXNG_SECRET=%s\n' "$(openssl rand -hex 32)" >> .env
docker compose -f compose.yaml -f compose.search.yaml up -d
```

Do not commit `.env` or place this secret in `settings.yml`.

### Empty model picker with a LAN endpoint on macOS

If `CHAT_ENDPOINT_URL` points to a machine on your local network (e.g.
`http://192.168.x.x:8000` or `http://<hostname>.local:port`) and the model
picker stays empty even though `curl`ing the same `/v1/models` URL works, the
cause is usually **macOS Local Network privacy**. Recent macOS releases block a
process from reaching local-network addresses until you grant it Local Network
access, which surfaces here as a "no route to host" error and an offline
endpoint. Public/internet endpoints are unaffected. The same grant is required
for automatic local-endpoint discovery (scanning Ollama/LM Studio/llama.cpp on
the LAN) in both `make dev` and the desktop app.

Fix: **System Settings → Privacy & Security → Local Network**, enable the toggle
for the terminal app you launch `make dev` from (Terminal, iTerm2, Ghostty,
VS Code, …) **and** for **OmniChat** when using the desktop build, then **quit
and reopen** that app. Loopback servers (oMLX/Ollama on `127.0.0.1`) do not
need this; `.local` names and `192.168.x` addresses do. On macOS Sequoia the
grant applies to that exact binary, so an ad-hoc `go run` / unsigned sidecar
can stay blocked even after OmniChat or Terminal is allowed. The Local Network
entry only appears after the app has attempted a LAN connection — open it once,
approve the system prompt, then restart. Ad-hoc desktop rebuilds are a new
signature and may ask again. If you launch through tmux/screen/ssh, start from
a plain terminal window so the permission is attributed correctly.

## Licensing and acknowledgements

OmniChat is released under [Apache 2.0](LICENSE). The manual's
[Acknowledgements](docs/manual.html#acknowledgements) credits the on-device Qwen and Kokoro
models, native Swift and Tauri components, Go core libraries, frontend and sandbox runtimes,
optional sidecars, integrations, and fonts. It distinguishes bundled software from optional
downloads and independently operated services; their individual licenses and terms still apply.

The public chapter is at
https://manual.omni-chat.work/docs/manual.html#acknowledgements and is linked from the
marketing website. This credits overview does not replace the full license texts, notices,
or source-availability obligations required for a particular distribution.

The app's **Third-party licenses** view is available before sign-in and in Settings → Legal.
See [`docs/dev/ios-license-inventory.md`](docs/dev/ios-license-inventory.md) for the iOS
dependency inventory and instructions for updating its notices.
