gpt in affine
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s

This commit is contained in:
2026-11-01 11:21:28 +00:00
parent e935abd0c3
commit 50c4efc09b
30 changed files with 4280 additions and 336 deletions
+2
View File
@@ -5,6 +5,8 @@
- [Project Zomboid backups](./project-zomboid-backups.md)
- [Gitea Kanban CLI](./gitea-kanban-cli.md)
- [AFFiNE document typography](./affine-typography.md)
- [Native AFFiNE deployment and migration](./affine-native.md)
- [ChatGPT subscription connector for AFFiNE](./affine-chatgpt.md)
## Gitea runner labels
+206
View File
@@ -0,0 +1,206 @@
# AFFiNE ChatGPT subscription connector
`affine-chatgpt` uses the official Sign in with ChatGPT preview flow. It does not
use browser cookies, another application's OAuth client, or an API-billing
fallback. Account eligibility and usage limits are controlled by OpenAI.
## Native service
The reusable NixOS module is `hectic.services.affine-chatgpt`. The hectic-lab
host enables it in `nixos/system/hectic-lab/affine-chatgpt.nix`.
- Unit: `affine-chatgpt.service`, running as `affine-chatgpt`.
- Listener: `127.0.0.1:3012`; no public port or Docker dependency.
- OAuth state: `/var/lib/affine-chatgpt/session`, mode `0700`.
- Credentials and stable gateway key: owner-only files, mode `0600`.
- Gateway key: `/var/lib/affine-chatgpt/gateway-key`.
Do not put credentials or key contents in Nix expressions, the Nix store,
environment variables, command arguments, logs, screenshots, or Git. The
service receives only the protected key's path. Keep the key stable: AFFiNE
stores its value as an encrypted workspace BYOK credential.
The service is deliberately not started when the OAuth credential file is
absent. Provision the state before starting it, using the service account's
ownership. Preserve the original private directory/file permissions.
## Authorize and move a session
On the computer running the user's regular browser:
```sh
nix run .#affine-chatgpt -- login
nix run .#affine-chatgpt -- status
nix run .#affine-chatgpt -- models
```
Open the printed OpenAI authorization URL in the normal browser, not a
temporary automation browser. Complete login, any passkey challenge, and app
consent. The loopback callback is `http://127.0.0.1:1455/auth/callback`; the
listener expires after 15 minutes unless `login --timeout` is specified.
For a self-hosted VM, securely transfer the complete credential record over
SSH. Create and persist a distinct VM host ID in `session/host.json`; do not
overwrite it with the laptop's host ID. Associate the imported credential's
`host_id` with that VM. Use the same issued client registration, not the
`dynamic_agent_client` registration entrypoint, for subsequent token exchanges.
After a successful remote model and inference test, remove the local active
credential record. Only the VM should rotate the imported refresh token.
Never copy a different application's credential record or session cookies.
Login and model-list success prove enrollment and catalog access, not working
inference. Require a streamed request ending with `response.completed` before
claiming that the subscription works.
## AFFiNE configuration
Configure these settings through AFFiNE's supported administrator API/UI, not
direct SQL or source-embedded secrets:
```json
{
"copilot.enabled": true,
"copilot.byok.enabled": true,
"copilot.byok.allowedProviders": ["openai"],
"copilot.byok.allowCustomEndpoint": true,
"copilot.byok.allowPrivateEndpoint": true
}
```
The native AFFiNE wrapper sets `DEPLOYMENT_TYPE=selfhosted`, required for custom
endpoints. The stable AFFiNE `private.key` must be preserved so stored BYOK
credentials remain decryptable.
Add a workspace BYOK provider:
- Provider: `openai`.
- Endpoint kind: `openai_compatible`.
- URL: `http://127.0.0.1:3012/v1`.
- Dialect: `responses`, not Chat Completions.
- Credential: the protected gateway key, not an OpenAI token.
- Model: a slug returned by the authorized account's catalog.
- Initial capabilities: text input/output and `tool_calling`, no attachments.
Persistent AFFiNE BYOK is workspace-wide. All authorized workspace members can
consume the connected account's limits and send document context/tool results
to OpenAI. User consent to shared access does not replace OpenAI's account and
subscription terms.
## Supported transport
The gateway authenticates requests before reading their bodies. It supports
`GET /v1/models` and `POST /v1/responses`, text history, function/custom tools,
and function-call results. AFFiNE executes tools; the gateway never executes
shell commands or document tools itself.
Upstream requests always use `store:false` and `stream:true`. Non-streaming
AFFiNE probes are assembled from completed SSE output items and the final
completion event. An explicitly non-SSE Content-Type is rejected; a missing
Content-Type is accepted only through the same strict SSE parser. Failed,
incomplete, malformed, or interrupted streams are not reported as successful.
Image generation, image/file/audio attachments, hosted MCP, Code Interpreter,
and persistent Responses conversation IDs are not supported. Do not declare
those capabilities in AFFiNE.
## Verification and development
```sh
nix build .#affine-chatgpt
nix build .#checks.x86_64-linux.affine-chatgpt-enrollment
nix build .#checks.x86_64-linux.affine-chatgpt-module
nix build .#checks.x86_64-linux.affine-model-picker
nix build .#affine-chatgpt.pythonEnv --out-link package/affine-chatgpt/.venv
pyright --project package/affine-chatgpt/pyrightconfig.json \
--pythonpath package/affine-chatgpt/.venv/bin/python3
```
Package checks use fake credentials and local HTTP fixtures only. Real smoke
tests should verify unauthenticated `401`, model filtering, text response,
function-call output, streamed completion, restart, and token refresh without
printing credentials. A successful direct gateway test is not proof that
AFFiNE's workspace provider and chat UI have been configured.
References:
- <https://developers.openai.com/siwc/token-sharing-open-source>
- <https://developers.openai.com/siwc/token-sharing-open-source/self-hosted-vms>
- <https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations>
## hectic-lab deployment
The native service is active and the shared AFFiNE workspace has an enabled
`ChatGPT subscription` BYOK profile pointing at `http://127.0.0.1:3012/v1`.
The profile offers these account-catalog models, each with text input/output
and tool calling:
- `gpt-5.6-luna`
- `gpt-5.6-terra`
- `gpt-5.6-sol`
- `gpt-6-luna`
- `gpt-6-sol`
- `gpt-6-astra`
- `gpt-6.1-terra`
- `gpt-6.1-sol`
The existing first/default model remains `gpt-5.6-luna`. All eight models passed
AFFiNE's chat and tool-calling probes. A two-turn chat switched from
`gpt-5.6-luna` to `gpt-6.1-sol`; the second model recovered a random marker from
the first turn, confirming conversation history is retained across the switch.
The temporary test conversation was removed through AFFiNE's API. Model changes
use the existing workspace profile and do not replace its encrypted credential
or require another OAuth login. Reload an already-open client to refresh its
model catalog.
The pinned AFFiNE frontend originally exposed only managed route choices, which
are empty on self-hosted servers. `package/affine/byok-model-picker.patch` adds
workspace BYOK models to the existing Model menu and forwards the selected
profile/model separately from managed route IDs. Auto and managed selections
remain supported; retries retain the last request selection in memory.
BYOK discovery uses the existing owner/admin settings API. Owners and workspace
admins can choose these models in the patched selector; ordinary members retain
Auto and can use the shared default profile without gaining settings access.
No backend permission or Enterprise source code is changed.
The native module's optional `frontendPackage` mounts matching source-built
static assets read-only into the application service. Backend binaries and
migration units stay unchanged during this frontend-only rollout. Compatibility
checks require matching release and source revision. The host explicitly enables
this override; a standalone module with no override keeps its bundled frontend.
For a frontend-only rollout, build the static artifact and picker check, inspect
the host activation plan, then activate the host configuration normally:
```sh
nix build .#affine-frontend-static .#checks.x86_64-linux.affine-model-picker
nixos-rebuild switch --flake '.#hectic-lab|x86_64-linux'
```
Only `affine-native.service` should restart for a static-only change. Its
migration unit, dedicated PostgreSQL and Redis must keep their existing package
and restart triggers. Reload the client with a hard refresh after deployment to
discard cached frontend chunks.
### Verified picker rollout
The patched selector is deployed in NixOS generation
`1mvb1nb5xqhaj8xfskxi00lj39lmbpzl`. It binds frontend static package
`hrg3dkcacg5drizifiinjx481k6k33d5` over the unchanged native backend's static
directory. The activation restarted only AFFiNE; PostgreSQL, Redis and migration
unit process/state timestamps remained unchanged.
An authenticated headless browser verified all eight menu choices and selected
`gpt-6.1-sol`. The real selector returned the expected `profileId` and `modelId`
with no managed `routeTargetId`; the trigger displayed the selected model.
Open the AI input's Auto/current-model control, then its Model submenu. Use a
hard refresh (`Ctrl+F5`) if the old interface is still cached.
Account OAuth enrollment, remote catalog access, text generation, function
calls and streamed tool results were tested. AFFiNE's own provider probes and
chat SSE endpoint also passed, including automatic profile routing.
Only the server now owns the imported rotating session; the local active
credential copy was removed after remote verification. Images and attachments
remain unsupported and are not advertised by the profile.
+142
View File
@@ -144,3 +144,145 @@ before upgrades. Production migration remains a separate, explicit operation.
AFFiNE backend source has its own license; review it before production use.
This module does not grant production authorization or alter upstream license
terms.
## hectic-lab host configuration
`nixos/system/hectic-lab/affine.nix` stages the reusable native module alongside
the original deployment. `hectic.affineDeployment.nativeActive` defaults to
`false`: the legacy Docker units and nginx port 3010 remain selected. The old
configuration is preserved in `affine-docker.nix` for staging and rollback.
Set `nativeActive = true` only after the final frozen-state restore and native
verification; this removes the legacy unit declarations and selects nginx port
3011. Source declarations alone are not evidence that production has migrated.
The host configuration intentionally uses isolated dependencies:
| Component | Unit | Endpoint/state |
| --- | --- | --- |
| AFFiNE | `affine-native.service` | `127.0.0.1:3011`, `/var/lib/affine-native` |
| Migration | `affine-native-migrate.service` | Same user, environment and state |
| PostgreSQL 16 | `affine-postgresql.service` | Unix socket `/run/affine-postgresql`, port 5433, `/var/lib/affine-postgresql` |
| Redis | `redis-affine.service` | `127.0.0.1:6388` |
| ChatGPT connector | `affine-chatgpt.service` | `127.0.0.1:3012`, separate protected state |
The database cluster does not listen on TCP and does not replace the host's
shared `postgresql.service`. It uses peer authentication, a non-superuser role
and database named `affine-native`, and pgvector `0.8.7` from the pinned
official release. PostgreSQL pre-creates `vector` and `pgcrypto` as its cluster
administrator. The cluster locale matches the existing Docker database's
`en_US.utf8`; do not silently substitute a different collation.
Both AFFiNE units are gated by `/var/lib/affine-native/environment`. Create that
file only after staging the correct database/config/storage. It must be
protected outside Git and the Nix store. Its required connection settings are:
```text
DATABASE_URL=postgresql://affine-native@localhost:5433/affine-native?host=/run/affine-postgresql
AFFINE_INDEXER_ENABLED=false
```
The database URL contains no password because the Unix socket uses peer auth.
The environment file may also carry secrets; treat the entire file as private.
## Docker-to-native migration procedure
1. Build the source package, exact pgvector version, native service units and
targeted checks before scheduling an outage. Inspect the activation plan;
do not restart the shared PostgreSQL cluster or unrelated Redis instances.
2. Inventory the running AFFiNE revision, database extensions/locale, workspace
and user counts, config/private key, storage file manifest and nginx route.
Never print secret values or document contents.
3. Make an owner-only custom-format PostgreSQL backup and config/storage
snapshot. Verify `pg_restore --list`, archive readability and checksums.
A listed archive is not a tested restore or an offsite backup.
4. Start only the dedicated PostgreSQL and Redis units. Restore a rehearsal
dump into their isolated database, preserving role ownership. Pre-created
extensions avoid giving the application superuser privileges. Use
`pg_restore --exit-on-error --no-owner --no-acl --no-comments
--role=affine-native`; investigate any error instead of ignoring it.
5. Copy the complete Docker config and storage to
`/var/lib/affine-native/.affine/{config,storage}`. Preserve `private.key`
byte-for-byte. Give the native account ownership and private permissions.
Update copied server/listen/port and Redis settings for native paths;
preserve authentication, external URL and all encryption material.
6. Run migration/startup against the rehearsal database and copied storage
only. Never point staging workers at the live Docker database/storage.
Verify `/info` reports `selfhosted` and compatibility `0.27.4`, then test
authenticated workspaces, representative documents and stored attachments.
7. Announce the write freeze. Stop all Docker AFFiNE application/worker writers
without deleting its PostgreSQL volume. Take a fresh final dump and final
config/storage snapshot after the freeze. Restore that final snapshot into
a clean native database; stop staging units before replacing state.
8. Start native migration and application units. Verify entity counts,
checksums, login, documents, attachments and readiness before switching
`hectic.affineDeployment.nativeActive` to `true` and nginx from port 3010 to
3011. Inspect the activation plan and test nginx configuration first.
9. Confirm the public HTTPS route, WebSockets/live editing and signup policy.
Confirm the cutover removed/disabled the old Docker `affine.service` and
`affine-frontend.service`. Retain their image/config/data and final snapshot;
do not delete old state as part of cutover.
10. Configure the [native ChatGPT connector](./affine-chatgpt.md) through AFFiNE's
administrator API/UI and verify an actual AFFiNE AI request, not only a
direct upstream probe.
Before native production writes, rollback can return nginx/application to the
frozen Docker state. After native writes begin, that state is stale: rollback
requires a new consistent export and compatible restore, not a proxy flip to
an old database. NixOS generation rollback alone does not restore application
data.
If SSH, package copying, extension build, rehearsal restore or verification is
blocked, leave the Docker production route intact. Do not create the runtime
environment marker or activate a half-prepared native application.
## Completed hectic-lab cutover: 2026-10-31
Production now explicitly sets `hectic.affineDeployment.nativeActive = true`.
The activated persistent NixOS generation is:
```text
/nix/store/6vp7qb6id8krb9l5ff1dkdi7nzxifhwd-nixos-system-hectic-lab-26.05.20261006.b253099
```
Final write-frozen backup:
```text
/var/backups/affine/native-cutover-20261031T231824Z
```
The backup directory is `0700`; database/config/storage archives are `0600`.
It includes the final database dump, verified archive listings, config and
storage snapshots, previous generation references, and matching before/after
data fingerprints. Keep it private. It is local recovery material, not an
offsite backup.
Cutover verification matched all rows/fingerprints in `users`, `workspaces`,
`workspace_members`, `workspace_pages`, `snapshots`, `updates`, and `blobs`:
5 users, 2 workspaces, 5 memberships, 44 pages, 53 snapshots, 0 pending update
rows, and 49 blob records. All 98 storage files (19,341,496 bytes) and the
original `private.key` were preserved. Rehearsal authenticated document bytes
and a 3,049,505-byte attachment matched the Docker source; final HTTPS login,
document reads, attachment retrieval and frontend assets passed.
The final `switch-to-configuration switch` completed successfully. The Docker
AFFiNE application/PostgreSQL/Redis containers are gone; their original
`/var/lib/affine` state remains retained. The host Docker daemon still serves
unrelated applications and was not removed.
The staging `test` activation encountered a pre-existing D-Bus reload timeout
(the journal also records it on 2026-10-10); the bus remained active and was
not restarted. The final cutover activation did not reload D-Bus and completed
successfully. Shared `postgresql.service` remained active throughout.
The native [ChatGPT connector](./affine-chatgpt.md) is enabled through the
workspace's persistent BYOK profile `ChatGPT subscription`. Text and function
probes were verified, and an actual AFFiNE SSE chat returned the expected
response with both explicit and automatic provider selection. Two authenticated
WebSocket connections joined the workspace and read identical document state
without writing documents.
After restarting both native AFFiNE and the connector, public login, document
and attachment reads, two-client WebSocket reads, and an automatic-routed AI
chat associated with an existing document passed again. Local validation also
passed 61 connector tests, Pyright with its Nix Python environment, and the
runtime, typography, native-module, production and connector Nix checks.
+14
View File
@@ -36,6 +36,20 @@ The backend used by that check still requires explicit unfree evaluation.
## Current hectic-lab rollout
Since 2026-10-31, hectic-lab runs the source-built backend and patched frontend
together through `hectic.services.affine` and `affine-native.service`. Its
dedicated PostgreSQL, Redis and ChatGPT connector are native services as well.
There is no production AFFiNE container or `affine-frontend.service` mount.
See [native deployment and migration](./affine-native.md) for the cutover,
verification and backup record. The frontend patch remains part of the same
pinned AFFiNE source package; a read-only browser check after migration confirmed
the real document's H2 blocks retain the 24px scale.
## Historical Docker rollout
The following describes the earlier frontend-only rollout, retained for the
staging/rollback configuration. It is not the current production topology.
`affine-frontend-static` contains regular, copied web assets, including admin
and mobile directories and upstream license notices. It does not contain
symlinks into store paths that would be unavailable inside a container.