277 lines
13 KiB
Markdown
277 lines
13 KiB
Markdown
# 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.
|
|
|
|
## AFFiNE managed trial counter versus provider limits
|
|
|
|
`currentUser.copilot.quota { limit used }` describes AFFiNE's managed AI trial,
|
|
not the connected ChatGPT account's remaining usage. It must not be presented as
|
|
an OpenAI allowance or an invoice. BYOK execution is authorized independently
|
|
from quota-backed managed routes and records usage as `byok_server`.
|
|
|
|
The pinned release has a legacy accounting edge case: deleted sessions retain
|
|
`messageCost`, while the BYOK exemption query joins usage billing units to live
|
|
message rows. Removing test conversations can therefore leave a misleading
|
|
managed-trial cost after their BYOK message rows disappear. The observed `8/10`
|
|
was explained by eight such retained units; the connected provider's request
|
|
history was tagged BYOK, not AFFiNE-managed usage.
|
|
|
|
Do not fix this by resetting usage, promoting a plan, granting unlimited quota,
|
|
or weakening server enforcement. The raw quota and all provider/quota errors
|
|
remain unchanged. A self-hosted UI should instead identify AI as self-hosted
|
|
and explain that provider and server limits may apply, without a managed-trial
|
|
progress bar, Free badge or AFFiNE upgrade action. Cloud quota presentation
|
|
continues to use the original managed allowance.
|
|
|
|
ChatGPT subscription access is already paid for by the account owner; it is not
|
|
unlimited. OpenAI still enforces the account's model, usage-window and app-access
|
|
limits. This connector does not add an API-key billing fallback.
|
|
|
|
### Verified self-hosted usage rollout
|
|
|
|
On 2026-11-06, frontend static package
|
|
`3s22k6a5p9731xmlr6x33icilcsfkzv2-affine-frontend-static-0.27.4` was copied to
|
|
`hectic-lab` and mounted over the unchanged backend's static directory. This
|
|
was a bounded systemd override, **not** a NixOS generation switch: the active
|
|
and boot generation remain `6rb81fr95gngs99x1dvjw9vzzd7snkn5`. A whole-host
|
|
build was interrupted rather than activating unrelated package updates.
|
|
|
|
The root-owned persistent drop-in is
|
|
`/etc/systemd/system.control/affine-native.service.d/99-frontend-static-rollout.conf`.
|
|
It resets `BindReadOnlyPaths` and supplies only the new static bind. This
|
|
control directory is used because NixOS's `/etc/systemd/system` points into
|
|
the immutable store. GC roots `affine-frontend-static-rollout` and
|
|
`affine-frontend-static-rollback` under `/nix/var/nix/gcroots` retain the new
|
|
bundle and the previous `hrg3dkcacg5drizifiinjx481k6k33d5` bundle.
|
|
|
|
Only `affine-native.service` restarted. The migration unit's active timestamp,
|
|
PostgreSQL, Redis and ChatGPT gateway process IDs and active timestamps stayed
|
|
unchanged. The running application's mount namespace was checked against the
|
|
new package's `index.html`; HTTPS `/info` remained healthy. An authenticated
|
|
headless browser verified the sidebar and account settings on desktop and a
|
|
Pixel 5 viewport: neutral self-hosted text, no trial count, progress bar or
|
|
billing action, in both English and Russian. This stable release serves the
|
|
responsive web application to mobile browsers; upstream's separate mobile shell
|
|
is canary-only. The separate
|
|
mobile component is covered by the source-level rendering check.
|
|
|
|
A real BYOK text probe succeeded after deployment. AFFiNE's raw managed quota
|
|
remained `{ limit: 10, used: 8 }` before and after; no accounting records or
|
|
provider limits were altered. Existing browser sessions need a hard refresh.
|
|
|
|
The drop-in survives reboots and NixOS generation rollbacks, and masks future
|
|
declarative frontend changes until removed. During the next reviewed NixOS
|
|
switch containing the desired `frontendPackage`, remove this exact drop-in,
|
|
run `systemctl daemon-reload`, and restart only `affine-native.service` so the
|
|
declared bind takes effect. Remove the temporary GC roots only after checking
|
|
that the active generation retains the desired package and rollback retention
|
|
is no longer needed. Do not use a broad `systemctl revert` operation.
|
|
|
|
To roll back this bounded rollout while the original generation remains active,
|
|
remove that exact drop-in, daemon-reload and restart `affine-native.service`.
|
|
Its declared unit still binds the previous `hrg3dkcacg5drizifiinjx481k6k33d5`
|
|
bundle. Confirm health and the effective bind before removing any GC root.
|