2026年11月23日星期一

The three hidden switches: wiring AFFiNE Self‑hosted to your own LLM

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:

baseURL: https://magpie.example.ts.net
api key: sk-…
model: group/local (an OpenAI-compatible gateway, vision + tool calls)

Supposedly this is a config‑file job. The generated config.json schema even has the fields:

{
  "copilot": {
    "enabled": true,
    "byok": {
      "enabled": true,
      "allowCustomEndpoint": true,
      "allowPrivateEndpoint": true
    }
  }
}

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:

  1. copilot_disabled
  2. BYOK target is unavailable / customEndpointMode: "unavailable"
  3. invalid BYOK endpoint
  4. credential_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:

HalfLanguageReads config from
API / GraphQL / frontend glueTypeScript (/app/dist/main.js)$PROJECT_ROOT/config.json → fallback ~/.affine/config/config.json
Copilot runtime, BYOK, encryption, routingRust (/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:

// packages/backend/native/src/runtime/config.rs (0.27.4)
#[derive(Default, Deserialize)]
struct AppConfigFile {
  db: Option<DbConfigFile>,
  crypto: Option<CryptoConfigFile>,
  copilot: Option<CopilotRuntimeConfigFile>,
}

No file → copilot.enabled stays false → the first chat request dies with:

// packages/backend/native/src/runtime/backend_runtime/copilot/mod.rs
if !config.copilot.enabled {
  return Err(RuntimeError::invalid_state("copilot_disabled"));
}

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.

- AFFINE_BACKEND_RUNTIME_CONFIG_PATH=/root/.affine/config/config.json

(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:

policy: {"enabled":true,"allowedProviders":["anthropic","fal","gemini","openai"],
         "customEndpointMode":"unavailable","privateEndpointSupported":false}

customEndpointMode isn't read from allowCustomEndpoint. It's computed from deployment:

// packages/backend/native/src/llm/byok/policy.rs
let custom_endpoint_mode = match deployment {
  Deployment::Cloud => ByokCustomEndpointMode::Unavailable,
  Deployment::SelfHosted if config.allow_custom_endpoint => ByokCustomEndpointMode::Enabled,
  Deployment::SelfHosted => ByokCustomEndpointMode::Disabled,
};
allow_private_endpoint: custom_endpoint_mode == Enabled && config.allow_private_endpoint

And deployment — in 0.27.4 — comes from an environment variable only:

// packages/backend/native/src/runtime/config.rs
fn deployment_from_env() -> Deployment {
  if env::var("DEPLOYMENT_TYPE").as_deref() == Ok("selfhosted") {
    Deployment::SelfHosted
  } else {
    Deployment::Cloud // ← the default, even in a self-hosted image
  }
}

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:

- DEPLOYMENT_TYPE=selfhosted

Two env vars and the policy flips:

{"enabled":true,"customEndpointMode":"enabled","privateEndpointSupported":true}

Why this is "hidden": the TypeScript layer defaults the same variable to self-hosted for you —

// packages/backend/server/src/env.ts:90
DEPLOYMENT_TYPE = readEnv(
  'DEPLOYMENT_TYPE',
  this.dev ? DeploymentType.Affine : DeploymentType.Selfhosted,
  Object.values(DeploymentType)
);

— 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):

// packages/backend/native/src/llm/byok/contract.rs — validate_definition()
("openai_compatible", Some(url), Some(dialect)) if provider == "openai" => OpenAiCompatible {
  url: canonicalize_endpoint(&url).map_err(|_| ByokContractError::Endpoint)?,
  dialect: match dialect {
    "responses" => OpenAiDialect::Responses,
    "chat_completions" => OpenAiDialect::ChatCompletions,
    _ => return Err(ByokContractError::Endpoint),
  },
}

(b) The stored serde form (what is read back):

// same file, ByokEndpoint enum
#[serde(rename_all = "snake_case")]
enum ByokEndpoint { ProviderDefault, OpenAiCompatible { url, dialect } }

The tag is open_ai_compatible on disk, openai_compatible on the wire. Feed the storage the wire spelling and you get:

unknown variant `openai_compatible`, expected `provider_default` or `open_ai_compatible`

…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):

{
  "endpoint": {
    "kind": "open_ai_compatible",
    "url": "https://magpie.example.ts.net",
    "dialect": "chat_completions"
  },
  "models": [
    {
      "modelId": "group/local",
      "enabled": true,
      "capabilities": [
        {
          "input": ["text", "image"],
          "output": ["text", "object", "structured"],
          "features": ["tool_calling"],
          "attachmentKinds": ["image"],
          "attachmentSources": ["url", "data"]
        }
      ]
    }
  ]
}

Gotchas buried in there:

  • capabilities is an array of capability objects, not one object — the singular name is a lie.
  • models must be non-empty (Required("models")) and every modelId must 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. Declare output: ["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) — with openai_compatible endpoints 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:

// packages/backend/native/src/runtime/backend_runtime/byok/profile.rs
let key = envelope_key(root_secret)?; // root_secret = private.key PEM bytes, verbatim
let aad = server_aad(&workspace_id, &profile_id, &provider, definition.endpoint_identity());
let encrypted = key.encrypt(&SensitiveCredential::new(credential.into_bytes()), &aad);

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:

Error: credential_unavailable

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:

// packages/backend/server/src/plugins/copilot/runtime/turn-orchestrator.ts
const { profileId, modelId, routeTargetId, reasoning, webSearch, byokLeaseId } = ChatQuerySchema.parse(query);

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

services:
  affine:
    image: ghcr.io/toeverything/affine:stable
    environment:
      - DATABASE_URL=postgresql://affine@postgres:5432/affine
      - REDIS_SERVER_HOST=redis
      # 1. without this the native runtime thinks it is Affine Cloud
      - DEPLOYMENT_TYPE=selfhosted
      # 2. without this the native runtime never sees your config.json
      - AFFINE_BACKEND_RUNTIME_CONFIG_PATH=/root/.affine/config/config.json
    volumes:
      - ./config:/root/.affine/config
      - ./data/storage:/root/.affine/storage
{
  "copilot": {
    "enabled": true,
    "byok": {
      "enabled": true,
      "allowCustomEndpoint": true,
      "allowPrivateEndpoint": true
    }
  }
}

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:

{ workspace(id: "<workspace-id>") {
    byokSettings {
      serverEntitled
      policy { enabled allowedProviders customEndpointMode privateEndpointSupported }
      profiles { profileId name provider enabled revision
                 definition { endpoint { kind url dialect } models { modelId enabled } } }
    } } }

Expected when healthy:

{ "policy": { "enabled": true, "customEndpointMode": "enabled", "privateEndpointSupported": true } }

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

SymptomCauseFix
copilot_disabled on every message, UI shows Copilot onnative runtime never loaded the config fileAFFINE_BACKEND_RUNTIME_CONFIG_PATH
customEndpointMode: "unavailable"deployment defaulted to CloudDEPLOYMENT_TYPE=selfhosted
private BYOK endpoints are disabled for a LAN/Tailscale hostallowPrivateEndpoint false, or deployment gateboth env vars + allowPrivateEndpoint: true
BYOK target is unavailableprovider not in allowedProviders, or endpoint kind mismatchadd openai to copilot.byok.allowedProviders
profile missing from UI though the row existsdefinition fails native serde → silently filtereduse open_ai_compatible on disk, capabilities as an array
credential_unavailablehand-written ciphertext, or endpoint URL edited after encryptionrecreate via the runtime API
invalid BYOK endpoint on createkind: "open_ai_compatible" in the create payloadthe contract wants openai_compatible

Lessons

  1. 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.
  2. Silent filtering is the expensive bug. listByokProfiles swallowing invalid rows cost more time than every error message combined. If a storage layer can drop rows, it must log why.
  3. 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.
  4. When docs run out, read the sourcemap. main.js.map still contains the original TypeScript (sourcesContent), and --filter=blob:none --sparse cloning 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.
  5. 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.