The three hidden switches: wiring AFFiNE Self‑hosted to your own LLM
A field report from the 0.27.4 release — where the docs stop and the Rust starts.
The goal
Self‑hosted AFFiNE (Docker, ghcr.io/toeverything/affine:stable), one extra LLM endpoint on the LAN:
Supposedly this is a config‑file job. The generated config.json schema even has the fields:
And the UI agrees with you: Settings → AI → BYOK shows the profile, the model, even the green "entitled" badge. Then you send a message and get, in order:
copilot_disabledBYOK target is unavailable/customEndpointMode: "unavailable"invalid BYOK endpointcredential_unavailable
Four errors, four different layers. None of them is the one the docs describe. Here's the map.
Layer 0: where the config actually comes from
AFFiNE 0.27 split itself in two:
| Half | Language | Reads config from |
|---|---|---|
| API / GraphQL / frontend glue | TypeScript (/app/dist/main.js) | $PROJECT_ROOT/config.json → fallback ~/.affine/config/config.json |
| Copilot runtime, BYOK, encryption, routing | Rust (/app/dist/server-native.x64.node) | dirname(process.execPath)/config.json, cwd/config.json, plus $AFFINE_BACKEND_RUNTIME_CONFIG_PATH |
Same file, two independent readers, disjoint search paths. In the standard Docker image the mount is ./config:/root/.affine/config, so only the TypeScript side ever sees your file. The Rust side looks in /app/ and /usr/local/bin/, finds nothing, and falls back to compiled defaults:
No file → copilot.enabled stays false → the first chat request dies with:
The TypeScript side happily reports serverEntitled: true, entitled: true the whole time, because it read your file. That mismatch is the single most confusing part of the whole affair: the UI is lying to you, and it isn't wrong — it's just reading a different file.
Fix: point the native runtime at the mounted file.
(Alternatively, bind‑mount the config to /app/config.json. The env var is less fragile and doesn't shadow anything.)
Layer 1: the switch that isn't in any config file
With the config finally visible, copilot_enabled was true — and the endpoint was still refused:
customEndpointMode isn't read from allowCustomEndpoint. It's computed from deployment:
And deployment — in 0.27.4 — comes from an environment variable only:
Note what this means: on a fresh docker-compose install with the official image, the native runtime believes it is running in Affine's cloud. Custom endpoints are structurally impossible. allowCustomEndpoint: true in config.json is not ignored carelessly — it's evaluated in a branch that is never reached.
There's a second, subtler consequence: allow_private_endpoint can only ever be true if custom_endpoint_mode == Enabled, so private/LAN endpoints are doubly gated. A Tailscale (100.64.0.0/10) or RFC1918 address fails the public-address check in ByokPolicy::admit unless the deployment type is correct and allowPrivateEndpoint is on.
Fix:
Two env vars and the policy flips:
Why this is "hidden": the TypeScript layer defaults the same variable to self-hosted for you —
— so nobody notices it's unset. The Rust layer has no such fallback, and
deployment_from_env()is a five-line function with no comment. It is the one piece of self-host identity the native runtime never infers, and the only way to set it.
Layer 2: two schemas for one JSON blob
Write a row straight into ai_workspace_byok_configs and listByokProfiles returns [] — silently. No error, no warning. The profile simply vanishes from the UI.
The reason is that the definition JSON is validated in two different shapes:
(a) The create/update contract (what the API accepts):
(b) The stored serde form (what is read back):
The tag is open_ai_compatible on disk, openai_compatible on the wire. Feed the storage the wire spelling and you get:
…if you go through a code path that surfaces errors. listByokProfiles doesn't — it filters invalid rows out. The only reliable oracle was probeByokProfile({ workspaceId, profileId }), whose error message names the offending field one layer at a time.
The full validated shape (this is the one that survives a round‑trip):
Gotchas buried in there:
capabilitiesis an array of capability objects, not one object — the singular name is a lie.modelsmust be non-empty (Required("models")) and everymodelIdmust be declared, even if the upstream serves fifty of them.Capabilities are not decorative: they're the routing contract. Declare attachmentKinds: []and the attach button refuses images. Declareoutput: ["text"]and structured‑output requests are rejected before a single token is generated.Declared capabilities are bounded by the built‑in registry ( declared capability exceeds provider or model upper bound) — withopenai_compatibleendpoints you get the generic OpenAI ceiling, which is generous, but you cannot claim more than it.
Layer 3: the credential is not just AES‑GCM
If you hand‑write the row, you must also produce encrypted_api_key in the native envelope format — which is not the base64(iv‖tag‖ciphertext) produced by CryptoHelper on the TypeScript side (packages/backend/server/src/base/helpers/crypto.ts:67, AES-256-GCM keyed by sha256(privateKey PEM)). The BYOK store uses an AEAD envelope with associated data:
The AAD binds the ciphertext to workspace + profile id + provider + endpoint URL. A row copied between workspaces, or a profile whose endpoint.url you later hand‑edit in SQL, decrypts to nothing:
Which is exactly the error you get for a byte‑perfect hand‑crafted AES‑GCM blob. The only sane way to create a profile is through the runtime itself — createByokProfile(...) / replaceByokProfile(...), which the GraphQL mutation calls for you.
Bonus trap: the wire form is generated client‑side
There is no server‑side "default profile". The chat submission carries profileId + modelId:
So a profile created out‑of‑band shows up in settings and is never selected until the client picks it. Seeding the only enabled profile works, because the UI auto‑selects it — but two profiles means the user must choose.
The working recipe
Then, and only then, create the BYOK profile through the app (Settings → AI → add OpenAI‑compatible provider) so the credential gets a valid envelope.
Verifying from the outside
The byokSettings field is on the workspace type, not on Query:
Expected when healthy:
If customEndpointMode reads unavailable, the deployment flag is still wrong (it can only be disabled when DEPLOYMENT_TYPE is right but allowCustomEndpoint isn't). If profiles is [] while rows exist in ai_workspace_byok_configs, the stored definition is failing serde — check the enum spelling first.
Symptom → cause
| Symptom | Cause | Fix |
|---|---|---|
copilot_disabled on every message, UI shows Copilot on | native runtime never loaded the config file | AFFINE_BACKEND_RUNTIME_CONFIG_PATH |
customEndpointMode: "unavailable" | deployment defaulted to Cloud | DEPLOYMENT_TYPE=selfhosted |
private BYOK endpoints are disabled for a LAN/Tailscale host | allowPrivateEndpoint false, or deployment gate | both env vars + allowPrivateEndpoint: true |
BYOK target is unavailable | provider not in allowedProviders, or endpoint kind mismatch | add openai to copilot.byok.allowedProviders |
| profile missing from UI though the row exists | definition fails native serde → silently filtered | use open_ai_compatible on disk, capabilities as an array |
credential_unavailable | hand-written ciphertext, or endpoint URL edited after encryption | recreate via the runtime API |
invalid BYOK endpoint on create | kind: "open_ai_compatible" in the create payload | the contract wants openai_compatible |
Lessons
Two runtimes, two config loaders. In any hybrid TS/Rust service, "the config file is correct" is not a statement about reality until you know which loader you mean. Silent filtering is the expensive bug. listByokProfilesswallowing invalid rows cost more time than every error message combined. If a storage layer can drop rows, it must log why.Default to cloud, fall back to nothing. A defaults decision ( else Deployment::Cloud) turned a self-hosted install into a system that silently cannot use its own feature.When docs run out, read the sourcemap. main.js.mapstill contains the original TypeScript (sourcesContent), and--filter=blob:none --sparsecloning of the upstream repo turns binary string‑archaeology into a five‑minute grep. Every answer in this post came from source, not from guessing at API behaviour.Wire format ≠ storage format. An enum alias, an array‑wrapped singular, or an AAD that binds four fields will each produce an error that names none of them.
Ship the two env vars. The rest is table stakes.