Dialogue drafting hung on "Drafting..." forever against OpenRouter, with the provider having received and completed the request. Two independent faults, both found by running the app's own code against the live endpoint. The hang: streamObject is lazy. Awaiting result.object alone does not pump the stream in this SDK version, so the promise waited for a parse that never started and the call sat until its ten minute ceiling. One identical request, measured twice: object-only never returned in 60s, draining textStream first returned a valid draft in 6.9s. generateStructured now drains the stream before reading the object. The endpoint: provider(modelId) resolves to OpenAI's Responses API, which only OpenAI implements. OpenRouter answered 200 and never completed. Every OpenAI-compatible service the app targets serves /chat/completions, which the plain path already used, so chatModelFor reaches the model through .chat(). The instrumented request now goes to /chat/completions and Compose's structured branch uses the same call. Defences, since a provider can still answer and then go quiet: an idle watchdog aborts a body that delivers no bytes for 60s on both paths, transport retries are off so one stall is one wait, a draft is capped at four minutes, and the dialog has a UI watchdog plus a catch that shows the failure instead of spinning. Against the live endpoint the real function now returns a five node draft in 6.2s. 246 tests across 24 files pass, including a regression test that fails if the stream drain is ever removed.
7.4 KiB
AI model connections
Every AI surface in the app talks to an OpenAI-compatible chat-completions
endpoint. By default that is the Unsloth Studio box on the LAN, configured by
environment variables. A stored connection lets a different provider or model be
chosen from the admin panel without editing .env or redeploying.
The three surfaces
Each surface has its own selector, because they want different things from a model:
| Surface | What it asks for | Bean counter note |
|---|---|---|
| AI Compose | prose, wrapped into the field's JSON shape | runs on every allowlisted field, so the cheapest capable model wins |
| Dialogue draft | a whole conversation as one strict JSON object | needs the strongest schema adherence |
| Dialogue rewrite | one rewritten line | prose only, a small model is fine |
Settings → AI Settings (ai-settings, a global) holds the three selectors.
Blank means the environment defaults, so an empty global changes nothing.
Creating a connection
Server → AI Connections (ai-connections).
| Field | Notes |
|---|---|
| Label | shown in the selectors and recorded in draft provenance; say which provider and model |
| Base URL | includes the API prefix, e.g. http://192.168.1.7:8888/v1 or https://api.deepseek.com/v1. /chat/completions is appended |
| Model id | exactly what the provider expects, e.g. deepseek-v4.1-flash |
| API key | write-only (see below). Blank leaves the stored key alone |
| Structured mode | json_schema, json_object, or prompt |
| Send reasoning off | sends reasoning_effort: "none", off for strict providers |
The key is write-only
The apiKey field's read access denies everyone, so it never appears in the admin
form, REST, GraphQL, or a populated relationship. The server reads it with
overrideAccess: true when it makes a request.
That design makes a blank submission ambiguous, so the rule is: blank means
unchanged. Replacing the key means typing a new one. Deleting it means ticking
Clear API key and saving. hasApiKey shows whether one is stored without
revealing it. The clearApiKey checkbox resets itself after each save so a later
edit cannot silently delete a key that was just set.
The key is stored as plain text in the database (there is no at-rest encryption
here), so database backups contain it. If that is
unacceptable for a provider, keep using the UNSLOTH_API_KEY env var and leave the
connection's key blank: a blank connection key falls back to the env var.
Structured output modes
json_schema is the default and the best option: the provider enforces the schema,
so a malformed draft is rejected before it reaches the app.
Some OpenAI-compatible providers reject a json_schema request. For those:
json_objectasks for JSON mode and puts the schema in the system prompt.promptasks for nothing and relies on the prompt, then parses the reply.
Both weaker modes serialise the schema into the prompt and parse the reply, so a model that does not follow instructions still fails, but through the app's existing validate-and-retry loop rather than a provider 400.
Test the connection before trusting it
The Test connection button on the edit view runs two probes against the saved values:
- a plain completion, which validates URL, key and model id;
- a tiny structured object, which validates the configured mode.
Both must pass. Every request carries a ten minute ceiling, so a host that accepts
the connection and never answers fails visibly instead of hanging the button.
The second one is the important one: a provider that rejects
json_schema looks perfectly healthy on a plain completion and fails every draft.
The result is stored on the record (lastTestOk, lastTestedAt,
lastTestMessage) and cleared whenever the base URL, model id, structured mode,
reasoning flag or key changes, because a passing test only describes the
configuration that was tested. The clearing happens in beforeChange, not
afterChange: an after-change return value is only the response of the operation,
so the stored row would keep showing a stale pass while the API looked correct.
Only fields actually submitted count as changed, otherwise the Test button's own
result write would invalidate itself.
What changes when a connection is active
- Requests go to
baseUrlwithmodelIdand the stored key instead of theUNSLOTH_*values. reasoning_effort: "none"is sent only when the connection allows it.- A draft's provenance records the connection label and model id, so a stored conversation still says which provider produced it.
- Compose's model dropdown has a single fixed entry ("Active AI connection"). The plugin's config is built once at boot and cannot list database rows, so the label names the routing rule; the handler resolves the actual connection per request.
Failure messages worth recognising
… API error: 401 … Invalid API key: the key is wrong or expired. Note that the Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually meansUNSLOTH_API_KEYis stale, not that a connection is misconfigured.The provider stopped sending data (60s with no response).: the provider answered and then went quiet mid-response. The idle watchdog abandons the call rather than waiting for the total ceiling. Try again: the request is likely to route to a different upstream, and the connection's Test button tells you whether the endpoint itself is healthy.… API error: 400 … response_format: the provider rejects the structured mode. Switch tojson_objectorprompt, or turn off the reasoning toggle if the error namesreasoning_effort.- Drafts fail twice with
before blaming the model: the prompt voice is suspect, not the provider. The message names which voice was in use.
Sending the request
Two things about the request are easy to get wrong, and both produced silent hangs rather than errors:
- The chat-completions endpoint, always.
chatModelForreaches the model throughprovider.chat(modelId). Calling the provider as a function (provider(modelId)) resolves to OpenAI's Responses API, which only OpenAI implements: OpenRouter, DeepSeek, Unsloth Studio and Ollama serve/chat/completionsand nothing else. There the request still returned 200 and the draft never arrived. - The stream must be drained.
streamObjectis lazy:result.objectdoes not resolve unless something reads the stream, so awaiting that promise alone waits for a parse that never starts.generateStructureddrainstextStreamfirst. Measured against OpenRouter with one identical request: object-only never returned in 60s, draining returned a draft in 6.9s. - Transport retries are off (
maxRetries: 0) so one stall is one wait. The draft runner already retries for a better reason: validator complaints.
Tests
tests/int/ai-connections.int.spec.ts: key write-only contract, blank-means-keep, clear, per-surface resolution, half-filled fallback, test-result invalidation.tests/int/ai-structured-stream.int.spec.ts: the lazy-stream guard. Fails if the drain is ever removed, which is the bug that made every draft hang.tests/int/ai-idle-watchdog.int.spec.ts: healthy body passes through, a silent body fails in the silence window, a body-less response is left alone.tests/int/ai-generate-modes.int.spec.ts: request shape against a local stub server (URL, model, key header, reasoning toggle), all three structured modes, and provider-error surfacing.