Commit graph

125 commits

Author SHA1 Message Date
RainbowBird
3b4bea32a4
refactor(server): consolidate backend shared packages and fix RESP3 stream read (#3667)
Some checks are pending
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Plugin Entrypoints / Native ESM (macos-latest) (push) Waiting to run
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Plugin Entrypoints / Native ESM (ubuntu-latest) (push) Waiting to run
Plugin Entrypoints / Native ESM (windows-latest) (push) Waiting to run
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
## Summary

1. Consolidate three backend-only packages (`http-shared`,
`internal-auth-shared`, and `redis-stream-shared`) into one workspace
package: `server/packages/backend-shared` (`@proj-airi/backend-shared`).
2. Expose three subpath exports (`./http`, `./internal-auth`, and
`./redis-stream`) so callers keep clean module boundaries without
duplicating package manifests, tsconfig files, and Dockerfile copy
entries.
3. Fix a live `XREADGROUP` decoding bug against Redis 7 with `ioredis`
v6 RESP3 replies.

## Why

- Every small backend package previously required its own
`package.json`, `tsconfig.json`, `vitest.config.ts`, `README.md`, and
copies across three server Dockerfiles (`server/apps/api/Dockerfile`,
`server/apps/api/production/railway/Dockerfile`, and
`server/apps/auth/Dockerfile`).
- During live dev acceptance on Railway Redis 7, `ioredis` v6 returned
flattened RESP3 `[streamKey, entries]` replies for `XREADGROUP` instead
of nested RESP2 `[[streamKey, entries]]`. That triggered a `ValiError`
in `readNew` and delayed delivery until `XAUTOCLAIM` ran 30 seconds
later.

## Architecture Changes

- Create `server/packages/backend-shared` (`@proj-airi/backend-shared`)
with subpath exports:
  - `@proj-airi/backend-shared/http`
  - `@proj-airi/backend-shared/internal-auth`
  - `@proj-airi/backend-shared/redis-stream`
- Update imports in `server/apps/api`, `server/apps/auth`,
`eslint.config.ts`, server docs, and all three server Dockerfiles.
- Update `readGroupReplySchema` and `normalizeReadGroupReply` in
`server/packages/backend-shared/src/redis-stream/stream-consumer.ts` to
decode both RESP2 nested and RESP3 flattened replies, and add a unit
regression test.
- Keep `server/AGENTS.md` and `server/apps/api/AGENTS.md` updates in a
separate commit.
- Companion deployment watch-path update is in
`proj-airi/airi-deploy#10`.

## Visual Changes

None. Backend packages, Dockerfiles, and documentation only.

## Verification

Ran in rc (`luoling-dev/airi-checks`, `node3`):

- `pnpm -F @proj-airi/backend-shared typecheck` — passed
- `pnpm -F @proj-airi/auth typecheck` — passed
- `pnpm -F @proj-airi/api typecheck` — passed
- `pnpm -F @proj-airi/backend-shared exec vitest run` — 6 files passed,
43 tests passed (1 skipped)
- `pnpm -F @proj-airi/auth exec vitest run` — 19 files passed, 184 tests
passed
- `pnpm -F @proj-airi/api exec vitest run` — 4 files passed, 37 tests
passed
- `pnpm exec eslint` on `eslint.config.ts`,
`server/packages/backend-shared`, `server/apps/api`, `server/apps/auth`,
and updated `AGENTS.md` files — passed
2026-12-02 15:11:08 +00:00
RainbowBird
9f57d77d87
fix(api-server): copy internal-auth-shared and redis-stream-shared in Railway Dockerfile (#3665)
## Summary

Follow-up to #3662 and #3663. Railway builds `ts-api` from
`server/apps/api/production/railway/Dockerfile`, which missed the new
`server/packages/internal-auth-shared` and
`server/packages/redis-stream-shared` workspace packages added in #3662.

## Changes

- Copy `server/packages/internal-auth-shared/package.json` and
`server/packages/redis-stream-shared/package.json` before `pnpm
install`.
- Copy `server/packages/internal-auth-shared` and
`server/packages/redis-stream-shared` sources before `pnpm -F
@proj-airi/api-server run build`.

## Visual Changes

None.

## Verification

- Matches `server/apps/api/Dockerfile` line for line for the shared
workspace packages.
- CI checks validate the branch and Railway builds `ts-api` directly
from this Dockerfile after merge.
2026-12-02 21:54:48 +08:00
RainbowBird
1624a34a26
refactor(server): invert account deletion orchestration and enforce unidirectional API-to-Auth S2S (#3663)
## Summary

Follow-up to #3662. Inverts account deletion control so Resource API
orchestrates the business flow and Auth acts as a pure bottom-layer
identity provider. All internal S2S HTTP calls now flow strictly in one
direction (`API -> Auth`) under Ed25519 request-bound authentication.

```mermaid
flowchart LR
  Client["Stage Web / Desktop / Pocket"] -->|"POST /api/v1/account/delete"| API["server/apps/api\n(Orchestrator & Signer)"]
  API -->|"Local check"| RC["RevenueCat Subscriber Client"]
  API -->|"GET /internal/auth/session\nEd25519 JWT (no jti write)"| Auth["server/apps/auth\n(Bottom-Layer IdP & Verifier)"]
  API -->|"POST /internal/auth/delete-account\nEd25519 JWT + Redis jti replay check"| Auth
  Auth -->|"XADD user.deleted"| Redis[("Redis Streams\naccount-events")]
  Redis -->|"XREADGROUP"| API
  Redis -->|"XREADGROUP"| Cloud["AIRI Cloud"]
```

## Key Changes

- **ADR**: Added
`server/docs/ai/adr/2026-12-02-account-deletion-orchestration.md`.
- **`@proj-airi/internal-auth-shared`**:
- Replaced `AUTH_USER_DELETION_CHECK` with `AUTH_SESSION_READ`
(`internal:auth:session:read`) and `AUTH_ACCOUNT_DELETE`
(`internal:auth:account:delete`).
- Added optional `skipReplayCheck` (`false` by default) so read-only
`GET /internal/auth/session` skips Redis `jti` writes while keeping
Ed25519 signature, 30s TTL, request binding, and scope checks.
- **`server/apps/auth` (Bottom-Layer IdP)**:
- Swapped `INTERNAL_AUTH_PRIVATE_KEY` to `INTERNAL_AUTH_PUBLIC_JWKS` and
removed `RESOURCE_SERVER_URL`, `src/resource-api.ts`,
`src/plugins/account-deletion.ts`, and Better Auth `user.deleteUser`.
- Protected `GET /internal/auth/session` with Ed25519 S2S auth
(`skipReplayCheck: true`).
- Added `POST /internal/auth/delete-account` with Ed25519 S2S auth +
Redis `jti` replay protection, authoritative fresh user session
verification (< 5 minutes for cookie or OIDC JWT with active `sid`),
`userId` ownership check, social OAuth grant revocation, `user.deleted`
stream publish, user/session deletion, and `Max-Age=0` cookie clearing.
- **`server/apps/api` (Orchestrator & Signer)**:
- Swapped `INTERNAL_AUTH_PUBLIC_JWKS` to `INTERNAL_AUTH_PRIVATE_KEY` and
removed `POST /internal/auth/user-deletion/check` plus the `/internal/*`
bypass.
- Signed outbound `GET /internal/auth/session` calls in
`resolveRequestAuth`.
- Added `POST /api/v1/account/delete` (`authGuard`, `strictObject({
confirm: literal(true) })`, local RevenueCat `409 SUBSCRIPTION_ACTIVE`
pre-check, signed `POST /internal/auth/delete-account` call forwarding
user credentials/CSRF headers and relaying expired `Set-Cookie`
headers).
- **`packages/stage-pages`**:
- Switched `account-settings-page.vue` deletion request from
`/delete-account` to `POST /api/v1/account/delete` via direct `fetch`
(preserving the no-refresh-on-401 invariant).
- **Local Infra & Docs**:
- Updated `server/docker-compose.yaml`, `server/README.md`,
`server/apps/api/README.md`, `server/apps/auth/README.md`, and
`server/apps/api/AGENTS.md` (in its own commit).

## Visual Changes

None. The account deletion confirmation dialog UI, copy, and
interactions are unchanged; only its backend endpoint changed.

## Operational Rollout Notes

Before deploying to Railway:
1. Set `INTERNAL_AUTH_PRIVATE_KEY` on `ts-api` and
`INTERNAL_AUTH_PUBLIC_JWKS` on `auth-server` (for `service:airi-api`).
2. Remove `RESOURCE_SERVER_URL` and `INTERNAL_AUTH_PRIVATE_KEY` from
`auth-server`, and remove `INTERNAL_AUTH_PUBLIC_JWKS` from `ts-api`.
3. Deploy `auth-server` and `ts-api` together so signed `GET
/internal/auth/session` and `POST /internal/auth/delete-account` match
immediately.
4. Older desktop or mobile binaries calling `/api/auth/delete-account`
receive `404` after deployment and must update.

## Verification

All checks ran in rc (`luoling-dev/airi-checks`):
- ESLint on all 41 changed files: passed (`0` errors)
- `pnpm -F @proj-airi/internal-auth-shared typecheck` & Vitest: `9/9`
passed
- `pnpm -F @proj-airi/api-server typecheck` & Vitest (`--changed`):
`320/320` passed
- `pnpm -F @proj-airi/auth-server typecheck` & full Vitest suite:
`19/19` files, `184/184` passed
- `pnpm -F @proj-airi/stage-pages typecheck` & browser Vitest
(`account-settings-page.browser.test.ts`): `15/15` passed
2026-12-02 21:38:30 +08:00
RainbowBird
989f383b16
refactor(server): add Ed25519 internal S2S auth and move Auth events to Redis Streams (#3662)
## Summary

Add zero-trust service-to-service authentication to the resource API
`/internal/*` boundary and move asynchronous Auth-to-API handoffs onto
Redis Streams.

- Protect `POST /internal/auth/user-deletion/check` with short-lived,
request-bound Ed25519 JWTs (`@proj-airi/internal-auth-shared`), explicit
`typ: "airi-internal+jwt"`, scope enforcement, and Redis `jti` replay
protection.
- Extract shared Redis Streams infrastructure and `account-events` /
`auth-events` contracts into `@proj-airi/redis-stream-shared`.
- Publish `user.deleted` (`account-events`) and `user.signed_up`
(`auth-events`) directly from Auth, consume both in API in-process
stream consumers with graceful shutdown, and remove `POST
/internal/auth/user-deletion` and `POST /internal/auth/events`.
- This PR is independent and based on `origin/main`
(`705f48059...ad0b2a8b5`).

## Context

- Request: The user asked to harden unauthenticated `/internal/*` routes
that previously relied only on edge path blocking, decouple unnecessary
synchronous Auth-to-API calls onto Redis Streams without splitting a
separate Railway worker, and split this server-only refactor from a
later orchestration-inversion PR.
- Scenario: In the hosted Railway deployment, Caddy blocks `/internal/*`
at the edge, while Auth called `/internal/auth/*` over the private
network without application credentials. Any edge misconfiguration or
compromised private service can invoke `/internal/auth/user-deletion`
without proving caller identity.
- Scope: Keep `POST /internal/auth/user-deletion/check` protected by
Ed25519 S2S auth in this PR. Leave account-deletion orchestration
inversion (eliminating the last Auth-to-API call and updating web,
desktop, and mobile clients) for a separate follow-up PR.

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| `@proj-airi/internal-auth-shared` | Absent | Signs and verifies
request-bound Ed25519 S2S JWTs with Redis `jti` replay protection |
Eliminates edge-only trust on `/internal/*` and isolates S2S keys from
user OIDC keys |
| `@proj-airi/redis-stream-shared` | Stream primitives and
`account-events` lived inside `server/apps/api` | Shared stream
producer, consumer, `account-events`, and `auth-events` contracts | Lets
Auth and API share typed stream contracts while preserving Go Cloud
compatibility |
| `server/apps/api` internal routes and middleware | Three
unauthenticated routes under `/internal/auth/*`; user
`sessionMiddleware` ran on all paths | Only `POST
/internal/auth/user-deletion/check`, protected by Ed25519 S2S
middleware; `sessionMiddleware` skips `/internal/*` | Removes two
unnecessary synchronous endpoints and prevents user/service auth context
mixing |
| `server/apps/api` stream consumers and shutdown | No background stream
consumer; `server.ts` did not handle `SIGTERM`/`SIGINT` | HTTP-free
`src/consumers/index.ts` runs `api-user-deletion` and `api-auth-events`
under `injeca` lifecycle with graceful shutdown | Handles Auth deletion
cleanup and signup analytics asynchronously with `XAUTOCLAIM` retries
and DLQ |
| `server/apps/auth` outbound boundary | Sent unsigned HTTP calls for
check, deletion cleanup, and signup events | Signs
`/user-deletion/check` with Ed25519 JWT; publishes `user.deleted` and
`user.signed_up` directly to Redis Streams | Keeps Auth decoupled from
API business cleanup and analytics providers |

## Architecture and behavior

### Module flow

```mermaid
flowchart LR
  Auth[server/apps/auth] -->|signed POST /internal/auth/user-deletion/check| InternalRoute[api/routes/internal-auth]
  Auth -->|signInternalRequest| InternalAuth[packages/internal-auth-shared]
  InternalRoute -->|requireInternalAuth| InternalAuth
  InternalRoute --> ReplayStore[(Redis internal:jti)]
  InternalRoute --> RevenueCat[RevenueCat Subscriber]

  Auth -->|XADD user.deleted| AccountStream[(Redis account-events)]
  Auth -->|XADD user.signed_up| AuthStream[(Redis auth-events)]
  Auth --> StreamPkg[packages/redis-stream-shared]

  ApiConsumers[api/consumers] --> StreamPkg
  ApiConsumers -->|XREADGROUP api-user-deletion| AccountStream
  ApiConsumers -->|XREADGROUP api-auth-events| AuthStream
  ApiConsumers --> Deletion[UserDeletionService]
  ApiConsumers --> ProductEvents[ProductEventService]

  Cloud[Cloud proj-airi/backend] -->|XREADGROUP cloud-inbox| AccountStream
```

### Signed deletion pre-check

```mermaid
sequenceDiagram
  participant A as Auth service
  participant S as internal-auth-shared
  participant API as API /internal/auth
  participant R as Redis
  participant RC as RevenueCat

  A->>S: Sign POST + path + raw body SHA-256
  A->>API: POST /internal/auth/user-deletion/check + X-Internal-Authorization
  API->>S: Verify EdDSA signature, typ, aud, scope, htm, htu, bsh
  API->>R: SET internal:jti:<jti> 1 EX 60 NX
  alt invalid token, wrong scope, tampered body, or replay
    API-->>A: 401 or 403 ApiError
  else valid
    API->>RC: hasRenewingSubscription(userId)
    alt renewing subscription active
      API-->>A: 409 SUBSCRIPTION_ACTIVE
    else deletable
      API-->>A: 200 { deletable: true }
    end
  end
```

### Event-driven deletion and signup

```mermaid
sequenceDiagram
  participant A as Auth service
  participant R as Redis Streams
  participant C as API consumers
  participant Cloud as Cloud inbox consumer

  A->>R: XADD account-events user.deleted (id = user-deletion:<userId>)
  A->>A: Delete user and sessions
  par API cleanup
    C->>R: XREADGROUP api-user-deletion
    C->>C: userDeletionService.softDeleteAll(userId)
    C->>R: XACK
  and Cloud cleanup
    Cloud->>R: XREADGROUP cloud-inbox
    Cloud->>Cloud: Delete inbox notifications
    Cloud->>R: XACK
  end
```

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| User OIDC JWT cannot authenticate `/internal/*` | Token confusion if
S2S verifier accepts user keys or generic `JWT` type | Separate Ed25519
keys, explicit `typ: "airi-internal+jwt"`, `aud`, `iss`, and
`sessionMiddleware` bypass on `/internal/*` | Covered by
`internal-auth.test.ts` and `app.test.ts` |
| Request integrity and replay on `/internal/*` | Captured token reused
or body `userId` modified within TTL | 30s TTL, signed
`htm`/`htu`/`bsh`, Redis `SET ... EX ... NX` `jti` store | Covered by
`internal-auth.test.ts` and `internal-auth.test.ts` in API |
| Deletion event durability | Redis write fails before Auth deletes user
row | `beforeDelete` throws on `XADD` failure so Better Auth keeps the
user row for retry | Covered by `confirmed-account-deletion.test.ts` |
| Cross-repo compatibility with Go Cloud | Payload or stream key change
breaks `cloud-inbox` | `account-events` keeps `user.deleted` v1 `{
userId }` and `id: user-deletion:<userId>`; `user.signed_up` uses
dedicated `auth-events` | Covered by `streams.test.ts`; live Go Cloud
consumer not exercised in this PR |
| Railway rollout order | Auth deploys before API creates consumer
groups or loads `INTERNAL_AUTH_PUBLIC_JWKS` |
`INTERNAL_AUTH_PUBLIC_JWKS` and `INTERNAL_AUTH_PRIVATE_KEY` fail fast at
boot; deploy `ts-api` before `auth-server` | Documented in ADR and
README; live Railway deploy pending merge |

## Verification

Focused package and service checks run locally:

```text
pnpm -F @proj-airi/internal-auth-shared typecheck     # pass
pnpm -F @proj-airi/internal-auth-shared test:run      # pass (9/9)
pnpm -F @proj-airi/redis-stream-shared typecheck      # pass
pnpm -F @proj-airi/redis-stream-shared test:run       # pass (24/24, 1 skipped real-Redis test)
pnpm -F @proj-airi/auth-server typecheck              # pass
pnpm -F @proj-airi/auth-server build                  # pass
pnpm -F @proj-airi/auth-server test:run               # pass (21 files, 199/199)
pnpm -F @proj-airi/api-server typecheck               # pass
pnpm -F @proj-airi/api-server build                   # pass
pnpm -F @proj-airi/api-server test:run                # 94 passed, 2 skipped, 2 PGlite timeout failures under parallel ESLint load
pnpm -F @proj-airi/api-server exec vitest run src/libs/mock-db.test.ts src/services/domain/billing/tests/flux-usage-migration.test.ts src/app.test.ts  # pass (3 files, 17/17)
pnpm exec eslint server/packages/internal-auth-shared server/packages/redis-stream-shared server/apps/api/src/app.ts server/apps/api/src/app.test.ts server/apps/api/src/server.ts server/apps/api/src/consumers server/apps/api/src/routes/internal-auth.ts server/apps/api/src/routes/internal-auth.test.ts server/apps/auth/src/resource-api.ts server/apps/auth/src/tests/resource-api.test.ts server/apps/auth/src/server.ts server/apps/auth/src/env.ts  # pass (0 errors, 0 warnings)
```

Not verified locally:

- Real Redis consumer group integration test (`TEST_REDIS_URL` unset).
- Live Railway multi-service deployment and Go Cloud consumer
integration.

## Rollout and follow-up

1. Generate a production Ed25519 key pair with
`generateInternalKeyPair('auth-2026-12')`.
2. Configure `INTERNAL_AUTH_PUBLIC_JWKS` on Railway `ts-api` and deploy
`ts-api` first so it creates the `api-user-deletion` and
`api-auth-events` consumer groups.
3. Configure `INTERNAL_AUTH_PRIVATE_KEY` on Railway `auth-server` and
deploy `auth-server`.
4. Follow-up PR: invert account-deletion orchestration from Auth to API
and migrate clients to eliminate the remaining Auth-to-API call.

## Agent

- Harness: Antigravity
- Model: Gemini 4 Neon (High)
2026-12-02 19:06:16 +08:00
RainbowBird
b2fd492af0
feat(server): support cookie sessions in api-server and cookie-only session-jwt in auth-server (#3657)
Some checks are pending
CI / Unit Test (others) (push) Blocked by required conditions
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
## Summary

This is **PR 1 of 4** for migrating Web authentication to a same-origin
BFF with Better Auth `HttpOnly` session cookies and moving Electron
token management to the main process.

This PR adds two strictly additive backend boundaries without changing
any existing Bearer JWT or OIDC flows:

1. **`server/apps/auth`**:
- Adds private `GET /internal/auth/session` (outside `/api/auth/*` rate
limiting and blocked at the public edge by `/internal/* -> 404`) so
`server/apps/api` can resolve Better Auth session cookies over
`AUTH_SERVER_INTERNAL_URL` without importing Better Auth or holding
`BETTER_AUTH_SECRET`.
- Adds cookie-only `POST /api/auth/session-jwt` to mint a 5-minute
stateless JWT (using Better Auth's `auth.api.signJWT` and existing JWKS
key set, matching `iss`, `aud`, `sub`, and `sid`) for Bearer-only
upstreams such as `cloud.airi.build`.
2. **`server/apps/api`**:
- Extends `resolveRequestAuth` to resolve `better-auth.session_token`
(and `__Secure-better-auth.session_token`) cookies via
`AUTH_SERVER_INTERNAL_URL/internal/auth/session` when no `Authorization:
Bearer` header is present.
- Enforces CSRF origin checks on cookie-authenticated mutations and
CSWSH trusted-origin checks on cookie-authenticated WebSocket upgrades
(`/ws/chat`, `/ws/v2/chat`, `/api/v1/audio/speech/ws`).
- Supports pre-authenticated `/ws/v2/chat` upgrades on open while
preserving anonymous upgrade + `chat:authenticate` for native clients.
3. **ADR**: Adds
`server/docs/ai/adr/2026-12-02-cookie-session-and-session-jwt-boundary.md`.

This PR is independent and based on `origin/main` (`4554c786a`).

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| Auth routes (`server/apps/auth/src/routes.ts`, `auth.ts`) | Only
public `/api/auth/*` routes and OIDC token exchange exist. | Adds
private `GET /internal/auth/session` and cookie-only `POST
/api/auth/session-jwt` backed by `auth.api.signJWT`. | Keeps Better Auth
and its secret inside `server/apps/auth` while enabling same-origin
cookie BFFs. |
| API request auth (`server/apps/api/src/libs/request-auth.ts`,
`middlewares/auth.ts`, `audio-transcription-stream/route.ts`) | Accepts
`Authorization: Bearer` JWTs only. | Keeps Bearer priority, adds
internal cookie session resolution with CSRF/CSWSH origin validation and
ban re-checks. | Enables cookie-authenticated HTTP and streaming ASR
requests without duplicating Better Auth in `api-server`. |
| API WebSocket auth (`server/apps/api/src/app.ts`, `libs/ws-auth.ts`,
`routes/chat-ws/v2/index.ts`) | `/ws/chat` and `/api/v1/audio/speech/ws`
require `?token=`. `/ws/v2/chat` always requires `chat:authenticate`. |
Accepts trusted-origin session cookies on upgrade and pre-authenticates
`/ws/v2/chat` on open while keeping `?token=` and `chat:authenticate`
unchanged. | Removes browser URL query tokens when Web moves behind a
same-origin BFF. |

## Architecture and behavior

```mermaid
sequenceDiagram
  participant B as Browser / Web BFF
  participant API as server/apps/api
  participant AUTH as server/apps/auth
  participant DB as PostgreSQL

  B->>API: HTTP / WS upgrade with Cookie + trusted Origin
  API->>API: Validate CSRF / CSWSH origin rules
  API->>AUTH: GET /internal/auth/session (Cookie only)
  AUTH->>DB: Verify active session and ban state
  AUTH-->>API: 200 { userId, sessionId, expiresAt, ... }
  API->>DB: Load user row and re-check ban state
  API-->>B: Authenticated response or pre-authenticated WS peer
```

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Better Auth isolation | `api-server` leaks `BETTER_AUTH_SECRET` or
imports Better Auth | Cookie validation stays in `auth-server` behind
private `GET /internal/auth/session` | Covered by
`routes-cookie-session.test.ts` and `request-auth.test.ts` |
| Public edge isolation for `/internal/auth/session` | Public caller
reaches internal route | Edge proxy blocks `/internal/*` with `404`
(same contract as `api-server`'s `/internal/auth/*`) | Existing Caddy
edge rule in `server/dev/caddy/Caddyfile`; Railway edge config not
modified in this PR |
| Cookie-only isolation on `/session-jwt` and `/internal/auth/session` |
Bearer JWT tries to mint new JWTs or resolve internal session |
`copyCookieHeaderOnly` strips `Authorization` before calling
`auth.api.getSession` | Covered by `routes-cookie-session.test.ts` |
| CSRF on cookie mutations and `/session-jwt` | Cross-site form or
script triggers state-changing call | Rejects `Sec-Fetch-Site:
cross-site` and untrusted `Origin` / `Referer` headers | Covered by
`routes-cookie-session.test.ts` and `request-auth.test.ts` |
| CSWSH on cookie WebSocket upgrades | Cross-site page opens WS using
browser cookie | `requireTrustedOriginForCookie: true` requires a
present, trusted `Origin` header | Covered by `request-auth.test.ts` |
| Transient internal auth failure on WS upgrade | Temporary 5xx closes
WS as permanent 4001 | `resolveCookieSession` throws on non-401
failures; WS upgrades close with retryable `1011`
(`createRetryableWsEvents`) | Covered by `request-auth.test.ts` |
| Existing Bearer / OIDC clients | Regression on Electron, Capacitor, or
current Web | Bearer path runs first and never invokes cookie lookup |
Covered by existing `request-auth.test.ts` and
`routes-oidc-token-auth.test.ts` |

## Verification

### Static checks

```text
pnpm exec eslint server/docs/ai/adr/2026-12-02-cookie-session-and-session-jwt-boundary.md server/apps/auth/src/auth.ts server/apps/auth/src/routes.ts server/apps/auth/src/tests/routes-cookie-session.test.ts server/apps/api/src/app.ts server/apps/api/src/middlewares/auth.ts server/apps/api/src/libs/request-auth.ts server/apps/api/src/libs/ws-auth.ts server/apps/api/src/libs/tests/request-auth.test.ts server/apps/api/src/routes/audio-transcription-stream/route.ts server/apps/api/src/routes/chat-ws/v2/index.ts server/apps/api/src/routes/chat-ws/v2/index.test.ts
# Passed (0 errors)

pnpm -F @proj-airi/auth-server typecheck
pnpm -F @proj-airi/api-server typecheck
# Passed (0 errors)
```

### Focused tests

```text
pnpm -F @proj-airi/auth-server exec vitest run src/tests/routes-cookie-session.test.ts src/tests/routes-oidc-token-auth.test.ts
# Passed: 2 files, 13 tests (plus 196 existing auth-server tests passed on the preceding full run)

pnpm -F @proj-airi/api-server exec vitest run src/libs/tests/request-auth.test.ts src/libs/tests/ws-auth.test.ts src/routes/chat-ws/v2/ src/routes/audio-transcription-stream/route.test.ts
# Passed: 7 files, 33 tests
```

### Not verified locally

- Full monorepo `pnpm typecheck` and `pnpm test:run` (left for GitHub
Actions CI).
- Live Railway private-network (`AUTH_SERVER_INTERNAL_URL`) deployment
verification (verified after merge).
2026-12-02 07:52:44 +00:00
RainbowBird
4554c786a1
feat(api-server): add ASR metrics, fix TTS status reporting, and set second-scale histogram buckets (#3650)
## Summary

Production alerts for AI services had three backend telemetry gaps.
First, GenAI and email duration histograms had unit `s` without explicit
bucket boundaries, so OpenTelemetry applied default millisecond buckets
(`0, 5, 10, 25, ...`) and distorted Prometheus P95 queries. Second,
aborted HTTP TTS requests reported `502` instead of `499`, and streaming
TTS error paths recorded no metrics. Third, realtime ASR emitted no
metrics and returned HTTP `200` before requesting the Aliyun NLS token.

This independent PR fixes all three telemetry surfaces in
`@proj-airi/api-server`.

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| OTel meter setup (`otel/index.ts`) | Histograms used SDK default
millisecond bucket boundaries. | Histograms configure explicit
second-scale `advice.explicitBucketBoundaries`. | Makes sub-5s
Prometheus P95 interpolation accurate for TTFC, LLM, TTS, ASR, and email
latency. |
| HTTP speech service (`services/domain/openai-speech`) |
`routerFailure` mapped caller `AbortError` to `502`. | `routerFailure`
maps `abortSignal.aborted` to `499` and sets `error.type` on status `>=
400`. | Stops client cancellations from inflating TTS 5xx failure
counts. |
| Streaming speech WebSocket (`routes/audio-speech-ws`) | Only
successful billed sessions recorded `operationDuration`. | Every
terminal path records `operationDuration` once with status (`200`,
`400`, `402`, `499`, `500`, `502`, `503`), `gen_ai.provider.name`, and
`error.type`. | Exposes streaming TTS outages and configuration errors
in Prometheus. |
| Realtime ASR stream (`routes/audio-transcription-stream`) | No OTel
metrics or spans. Aliyun NLS acquired its token inside the HTTP `200`
SSE body. | Both Aliyun NLS and DashScope Fun-ASR record
`operationDuration` (`airi.gen_ai.operation.kind="asr"`) and spans.
Aliyun NLS acquires its token before returning HTTP `200` and throws
`502` on failure. | Enables HTTP 5xx and ASR failure-rate alerting for
both providers. |

## Architecture and behavior

### Before and After for Aliyun NLS token failures

#### Before

```mermaid
sequenceDiagram
  participant C as Client
  participant R as Transcription route
  participant S as SSE stream
  participant A as Aliyun NLS

  C->>R: POST /api/v1/audio/transcriptions/stream
  R-->>C: HTTP 200 text/event-stream
  S->>A: CreateToken
  A-->>S: error
  S-->>C: stream aborts (HTTP status stays 200, no metric)
```

#### After

```mermaid
sequenceDiagram
  participant C as Client
  participant R as Transcription route
  participant T as ASR telemetry
  participant A as Aliyun NLS

  C->>R: POST /api/v1/audio/transcriptions/stream
  R->>A: CreateToken
  alt token request fails
    R->>T: record status 502 (token_error)
    R-->>C: HTTP 502 BAD_GATEWAY
  else token request succeeds
    R-->>C: HTTP 200 text/event-stream
    R->>T: track session until complete, cancel (499), or fail (502)
  end
```

The route now acquires the Aliyun NLS token before it sends the HTTP
`200` response header, and every ASR session records one terminal status
on `gen_ai.client.operation.duration`.

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Histogram bucket boundaries in seconds | Default SDK boundaries
collapse all sub-5s values into one bucket. | Explicit
`advice.explicitBucketBoundaries` in `initOtel`. | Verified with real
`MeterProvider` and `MetricReader` in `src/otel/index.test.ts`. |
| Single metric sample per streaming TTS or ASR session | Multiple
socket events (`error` then `close`) double-count one session. |
Idempotent `metricsRecorded` / `settled` boolean guard in session
telemetry. | Verified in `audio-speech-ws/route.test.ts`,
`session.test.ts`, and `dashscope-fun-asr-session.test.ts`. |
| Client abort classification in HTTP TTS | Caller disconnect triggers
false `502` alerts. | `routerFailure` checks `abortSignal.aborted` and
records `499`. | Verified in
`services/domain/openai-speech/index.test.ts`. |
| Aliyun NLS upstream `TaskFailed` and early WS drop | Silent truncation
or missed failure alerts. | `TaskFailed` and premature non-1000/1001
close record `502` and error the stream. | Verified in `session.test.ts`
and `dashscope-fun-asr-session.test.ts`. |
| Grafana Cloud alert rule rollout | Live Grafana alert rules still need
PromQL updates after deployment. | Follow-up Grafana Cloud update after
operator approval. | Not verified in production until deployed. |

## Verification

Ran in `rc` (`luoling-dev/airi-checks`, commit `b05f63d43` over merge
base `a94f86b70`):

```text
/root/agent-docs/scripts/airi-rc.sh check
- ESLint (14 changed files): exit 0
- pnpm -F @proj-airi/api-server typecheck: exit 0
- pnpm -F @proj-airi/api-server exec vitest run --changed a94f86b704 --passWithNoTests: exit 0 (208 passed, 0 failed)
```

- Focused tests verify bucket boundaries, HTTP TTS `499` vs `502`,
streaming TTS error metrics, and ASR token/stream metrics.
- Typecheck and lint verify static checks on `@proj-airi/api-server`.
- Live Grafana Cloud ingestion and alert evaluation are not yet verified
because this PR is not deployed.
2026-12-02 05:59:33 +00:00
RainbowBird
689f36d6a4
feat(auth): upgrade Better Auth to ^1.7.28 and enable refresh token reuse window (#3648)
## Summary

Unpin and upgrade `better-auth`, `@better-auth/drizzle-adapter`, and
`@better-auth/oauth-provider` from `1.6.25` to `^1.7.28`, and replace
the deprecated `@better-auth/cli` (`^1.4.22`) with `auth` (`^1.7.28`).
Extend the shared Drizzle auth schema with the tables and columns
required by Better Auth 1.7 (`0037_better_auth_1_7.sql`), enable a
30-second `refreshTokenReuseInterval` on `oauthProvider`, and adapt
breaking API changes in `steam`, `oidcJwtBearer`, and
`useLinkedAccounts`.

- Base / head: `a94f86b70...c28c6ada0`
- ADR: `server/docs/ai/adr/2026-12-01-better-auth-1-7-schema.md`

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| Dependency catalog (`pnpm-workspace.yaml`,
`server/apps/auth/package.json`) | Exact `1.6.25` pins on Better Auth
packages, deprecated `@better-auth/cli@^1.4.22`, `zod@^4.4.3`,
`jose@^6.2.10` | Caret `^1.7.28` on Better Auth packages and
`auth@^1.7.28`, `zod@^4.6.7`, `jose@^6.2.18` | Allows Renovate updates
and resolves one shared `@better-auth/core@1.7.28` instance across
`better-auth` and `@better-auth/oauth-provider` |
| Auth schema and migrations (`server/packages/auth-shared`,
`server/apps/api/drizzle`) | Better Auth 1.6 schema without JWKS
algorithm columns, OAuth resource tables, or refresh rotation replay
columns | Adds 3 tables (`oauth_resource`, `oauth_client_resource`,
`oauth_client_assertion`), new 1.7 columns and indexes, and backfills
`oauth_client.application_type` from `type` | Satisfies Better Auth 1.7
strict Drizzle schema checks while keeping `oauth_client.public` and
`type` nullable for rolling deployments |
| OAuth provider config (`server/apps/auth/src/auth.ts`) | Default
`refreshTokenReuseInterval: 0` (immediate family revocation on any
concurrent retry), seeds `type` and `public` only | Sets
`refreshTokenReuseInterval: 30` and seeds `applicationType` alongside
`type` and `public` | Absorbs concurrent or retried refresh token
requests within 30 seconds instead of revoking the active token family |
| OIDC JWT bearer plugin
(`server/apps/auth/src/plugins/oidc-jwt-bearer.ts`) |
`StoredJwkRowSchema` expects `optional(string())` for `alg` and `crv` |
`StoredJwkRowSchema` accepts `optional(nullable(string()))` | Prevents
`ValiError` 500 responses when PostgreSQL returns `null` for the new
`jwks.alg` and `jwks.crv` columns |
| Steam auth plugin (`server/apps/auth/src/plugins/steam.ts`) | Calls
3-argument `generateState` and removed
`internalAdapter.findAccountByProviderId` | Calls `generateState(ctx,
options?)` and `internalAdapter.findAccountByKey` | Matches Better Auth
1.7 OAuth2 state and internal adapter signatures |
| Linked accounts composable
(`packages/stage-ui/src/composables/use-linked-accounts.ts`) | Sends `{
providerId }` to `/unlink-account` | Sends `{ accountId:
linkedAccount.id }` (the Better Auth account row `id`) | Matches Better
Auth 1.7 `/unlink-account`, which requires the Better Auth row `id` |

## Architecture and behavior

### Concurrent refresh token retry

Before (`@better-auth/oauth-provider@1.6.25`):

```mermaid
sequenceDiagram
  participant C1 as Client request 1
  participant C2 as Client request 2
  participant Auth as Auth server
  participant DB as PostgreSQL
  C1->>Auth: POST /oauth2/token (R1)
  Auth->>DB: Revoke R1 and insert R2
  Auth-->>C1: Return access token and R2
  C2->>Auth: Concurrent retry (R1)
  Auth->>DB: Detect revoked R1 and delete token family
  Auth-->>C2: 400 invalid_grant
```

After (`@better-auth/oauth-provider@1.7.28` with
`refreshTokenReuseInterval: 30`):

```mermaid
sequenceDiagram
  participant C1 as Client request 1
  participant C2 as Client request 2
  participant Auth as Auth server
  participant DB as PostgreSQL
  C1->>Auth: POST /oauth2/token (R1)
  Auth->>DB: Mark R1 rotated (30s replay window) and insert R2
  Auth->>DB: Save encrypted replay payload on R1
  Auth-->>C1: Return access token and R2
  C2->>Auth: Concurrent retry (R1 within 30s)
  Auth->>DB: Verify R1 replay window and request match
  Auth-->>C2: Return cached rotation response without revoking R2
```

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Zero-downtime rolling deploy from 1.6.25 to 1.7.28 | Old 1.6.25 pods
crash if migration drops `oauth_client.public` or `type` |
`0037_better_auth_1_7.sql` keeps both columns nullable and backfills
`application_type` from `type`. `seedTrustedClients` writes all three
fields | Verified by generated SQL inspection and `seedTrustedClients`
unit tests. Follow-up migration removes legacy columns after rollout |
| PostgreSQL `jwks` rows with `null` `alg` or `crv` | `loadJwks` throws
`ValiError` and breaks JWT-authenticated account routes |
`StoredJwkRowSchema` uses `optional(nullable(string()))` | Verified by
`confirmed-account-deletion.test.ts` (22 tests) and
`oidc-jwt-bearer.test.ts` against PGlite and `memoryAdapter` |
| Better Auth 1.7 `/unlink-account` request contract | Sending `{
providerId }` or the external provider `accountId` fails with 400
`ACCOUNT_NOT_FOUND` | `useLinkedAccounts.unlink` resolves
`accountsByProvider.value.get(providerId)` and sends `{ accountId:
linkedAccount.id }` | Verified by `use-linked-accounts.test.ts`,
`use-linked-accounts.browser.test.ts`, and
`account-settings-page.browser.test.ts` |
| Ban revocation with replay window enabled | Banned users keep
replaying a rotated refresh token | `databaseHooks.user.update.after`
deletes all `oauth_refresh_token` and `oauth_access_token` rows for the
banned user | Verified by existing `auth.ts` ban hook and
`ban-guard.test.ts`. Live production migration execution is unverified
until deployment |

## Verification

All checks ran in `rc` (`luoling-dev/airi-checks`) against the exact
lockfile and code in this PR:

- `pnpm exec eslint` on all 12 changed source, config, test, and ADR
files: passed (0 errors)
- `pnpm -F <pkg> typecheck` on `@proj-airi/auth-shared`,
`@proj-airi/auth-server`, `@proj-airi/api-server`,
`@proj-airi/ui-server-auth`, `@proj-airi/stage-ui`,
`@proj-airi/stage-pages`, `@proj-airi/stage-web`: all 7 passed
- `pnpm -F @proj-airi/auth-server exec vitest run`: 18/18 files, 185/185
tests passed
- `pnpm -F @proj-airi/api-server exec vitest run
src/schemas/auth-schema-contract.test.ts
src/libs/tests/request-auth.test.ts`: 2/2 files, 10/10 tests passed
- `pnpm -F @proj-airi/ui-server-auth exec vitest run`: 7/7 files, 38/38
tests passed
- `pnpm -F @proj-airi/stage-ui exec vitest run
src/composables/use-linked-accounts.test.ts
src/composables/use-linked-accounts.browser.test.ts
src/stores/auth.test.ts`: 3/3 files, 28/28 tests passed (node +
Chromium)
- `pnpm -F @proj-airi/stage-pages exec vitest run
src/pages/settings/account/account-settings-page.browser.test.ts`: 1/1
file, 15/15 tests passed (Chromium)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-12-01 13:12:15 +00:00
Lulu
77b8ef8e1f
feat(flux): separate usage and payment receipts (#3373)
Some checks failed
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Has been cancelled
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-25 22:19:06 +08:00
Lulu
6ca5beaa6c
feat(chat): sync image attachments through S3 (#3614) 2026-11-25 11:16:53 +00:00
RainbowBird
1892e9e070
feat(api-server,stage-ui): price TTS by the catalog model (#3595) 2026-11-24 13:54:08 +00:00
RainbowBird
c87461ea5c
feat(http-shared): type success responses and forbid c.json in server routes (#3582) 2026-11-23 19:55:29 +08:00
Lulu
042eb5e3bb
feat(api,stage-pages): add animated account usage and separate history (#3173)
Some checks are pending
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Cloudflare Workers / Build - docs (push) Waiting to run
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
Co-authored-by: Neko Ayaka <neko@ayaka.moe>
Co-authored-by: RainbowBird <git@luoling.moe>
2026-11-22 23:25:46 +08:00
RainbowBird
f95c0a18bb
feat(api-server): add the Fish Audio TTS provider (#3570) 2026-11-22 18:13:21 +08:00
RainbowBird
51172c6589
feat(api-server): route official ASR to Model Studio Fun-ASR in Singapore (#3569) 2026-11-22 17:50:20 +08:00
RainbowBird
b3a6d60718
feat(api-server): add a script to rotate the LLM router master key (#3545)
Some checks failed
CI / Detect changes (push) Has been cancelled
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Has been cancelled
Cloudflare Workers / Build - docs (push) Has been cancelled
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Has been cancelled
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Has been cancelled
CI / Build Test (stage-tamagotchi) (push) Has been cancelled
CI / Unit Test (stage-tamagotchi) (push) Has been cancelled
CI / Unit Test (stage-ui-1) (push) Has been cancelled
CI / Lint (push) Has been cancelled
CI / Build Test (stage-web) (push) Has been cancelled
CI / Build Test (ui-playgrounds) (push) Has been cancelled
CI / Build Test (stage-tamagotchi-godot) (push) Has been cancelled
CI / Unit Test (others) (push) Has been cancelled
CI / Unit Test (api-server-1) (push) Has been cancelled
CI / Unit Test (api-server-2) (push) Has been cancelled
CI / Unit Test (stage-ui-2) (push) Has been cancelled
CI / Unit Test (push) Has been cancelled
CI / Type Check (others) (push) Has been cancelled
CI / Type Check (desktop) (push) Has been cancelled
CI / Type Check (web) (push) Has been cancelled
CI / Type Check (push) Has been cancelled
CI / Check Provenance (push) Has been cancelled
Cloudflare Workers / Deploy - stage-web (push) Has been cancelled
## Summary

- Add `server/apps/api/src/scripts/rotate-llm-router-master-key`. It
re-encrypts stored provider keys from `LLM_ROUTER_MASTER_KEY_PREVIOUS`
to `LLM_ROUTER_MASTER_KEY`.
- Document the `LLM_ROUTER_MASTER_KEY` rotation in the API README.
- Document the `BETTER_AUTH_SECRET` rotation in the Auth README. It
needs no code: Better Auth reads `BETTER_AUTH_SECRETS` itself, and
expiring the old JWKS keys makes the jwt plugin create a key under the
new secret.

## Context

The maintainer asked for a script to rotate `LLM_ROUTER_MASTER_KEY` and
`BETTER_AUTH_SECRET`, plus a rotation plan.

Replacing `BETTER_AUTH_SECRET` alone breaks OIDC. The jwt plugin
encrypts the JWKS private keys with the secret, so token signing fails
after the change. Better Auth 1.6.25 supports versioned `secrets` for
this case.

This PR does not change any deployed variable. The rotation itself is a
separate operator step.

## Change map

| Module | Before | After |
| --- | --- | --- |
| API envelope crypto users | AAD helpers were private |
`providerConfigAad` and `STREAM_MODEL_LABEL_FALLBACK` are exported for
the script |
| API rotation script | none | Re-encrypts `config_kv`
`LLM_ROUTER_CONFIG`, `UNSPEECH_UPSTREAM`, and
`user_provider_configs.config` |
| Auth README | no rotation steps | `BETTER_AUTH_SECRETS` plus JWKS key
expiry, no code change |

## Architecture and behavior

```mermaid
sequenceDiagram
  participant Op as Operator
  participant API as API container
  participant PG as Postgres
  participant R as Redis
  Op->>API: rotate-llm-router-master-key --apply
  API->>PG: SELECT config_kv ... FOR UPDATE
  API->>API: decrypt with previous key, encrypt with current key (same AAD)
  API->>PG: UPDATE config_kv
  API->>R: DEL config:<key>, PUBLISH configkv:invalidate
  API->>PG: UPDATE user_provider_configs WHERE id = ? AND config = <old>
  API->>PG: second read-only pass
  API-->>Op: exit 0 / 1 / 2
```

Exit codes of the script: `0` means the old key can be removed. `1`
means some values open with no configured key. `2` means some values
still need the old key.

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| AAD must match each reader | Re-encrypted key cannot be read | Uses
the model map key, `streaming-tts`, and `providerConfigAad`, the same as
the readers | Unit tests in `rotation.test.ts` |
| Concurrent admin write to ConfigKV | Script overwrites a new config |
Row lock in one transaction | Not run against a real database |
| Concurrent user edit of a provider config | Script overwrites the edit
| Update matches the old ciphertext. A miss counts as a conflict | Not
run against a real database |
| Other ConfigKV fields | Rewrite drops or adds fields | `looseObject`
schemas keep unknown fields and add no defaults | Unit tests check
`headers`, `provider`, and `defaults` |
| Wrong old key | Data is lost | Values that neither key opens stay
unchanged and give exit code 1 | Unit tests |
| JWKS keys after an auth secret rotation | Removing
`BETTER_AUTH_SECRETS` later breaks decryption of new keys | README says
to keep `BETTER_AUTH_SECRETS` | Documented only |

Rotating the auth secret signs out every cookie and bearer session. This
is Better Auth behavior: it signs cookies with the current secret only.
OIDC refresh tokens are stored as SHA-256 hashes and stay valid.

## Verification

Run in an rc Workspace on the first commit of this branch. The second
commit removes the auth script and only changes the Auth README.

- `pnpm -F @proj-airi/api-server typecheck`: pass
- `pnpm -F @proj-airi/api-server exec vitest run`: 995 pass, 5 fail. The
failures are PGlite 5 s timeouts in `mock-db.test.ts` and
`flux-usage-migration.test.ts`. They fail the same way on the merge base
in the same Workspace. `audio-speech-ws/route.test.ts` failed once in
the full run and passed alone.
- `pnpm exec eslint` on the changed files: no errors

Not verified: running the script against a real Postgres and Redis.

## Agent

- Harness: Claude Code
- Model: claude-opus-5-5

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-18 13:49:09 +08:00
RainbowBird
7786a0228d
feat(analytics): send product events to OpenPanel and PostHog in parallel (#3454) 2026-11-15 03:13:12 +08:00
RainbowBird
69d60cf95f release: v0.15.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:53:10 +07:00
RainbowBird
51b6b498d5 release: v0.15.3 2026-11-13 03:07:42 +07:00
RainbowBird
e18a9a5b87
feat(api): grant the Capacitor of a promotional RevenueCat entitlement (#3226)
Some checks are pending
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
CI / Unit Test (others) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
## Summary

An operator gives Go or Plus by granting the `airi_go` or `airi_plus`
entitlement in RevenueCat. RevenueCat lists the grant as a subscription
with `product_id: null`. The reconciliation looked the Capacitor quota
up by product, so it skipped the grant. The user got the entitlement in
the client but no Capacitor Flux.

A promotional entitlement now uses the one quota that the
`REVENUECAT_CAPACITORS` products of that entitlement share.

The skip came from the parse fix in
[airi#2910](https://github.com/moeru-ai/airi/pull/2910). The review
comment there only asked that a null product parse. It did not ask for
the skip.

- [airi#2910](https://github.com/moeru-ai/airi/pull/2910)
fix(api,auth,stage-ui): close the Capacitor follow-ups of #2813 ·
2026-10-10 · @luoling8192

## Behavior

- `fetchEntitlements` returns a promotional entitlement with `productId:
null` and reads no product.
- `capacitorQuota` gives a store subscription the quota of its product,
as before. A promotional entitlement gets the quota of its products when
they all have one quota.
- Products with different quotas, or no product for the entitlement: no
Capacitor. The admin dashboard is to show this case with a reason.
- A grant without an end date grants no Capacitor, as before.
- The latest period start wins, so a grant after a paid subscription
replaces its Capacitor until the grant ends.
- The webhook needs no change. It reconciles every event type except
`TEST`, including the `NON_RENEWING_PURCHASE` event of a grant.

ADR: `server/docs/ai/adr/2026-10-29-promotional-capacitors.md`.
`2026-10-04-subscription-credits.md` and the API README point to it.

## Follow-up

The admin API in `proj-airi/backend` will grant and revoke the
entitlement through RevenueCat API v2. It will also list each user's
RevenueCat subscriptions with a mark for those that grant no Capacitor.
That work depends on this PR, so it will not be deployed before this PR
merges.

## Verification

- `pnpm exec vitest run src/services/adapters/revenuecat-subscri
src/routes/revenuecat src/services/domain/billing` in `server/apps/api`:
9 files pass, 1 skipped; 127 tests pass, 1 skipped.
- `pnpm -F @proj-airi/api-server typecheck`: pass, after building
`@proj-airi/server-sdk-shared`.
- `eslint` on the changed source and the new ADR: pass.
- Not run: the full workspace test suite and `pnpm lint` over the
repository.
- Not verified: a real promotional grant. I have no RevenueCat account
with a grant to read.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 00:54:28 +08:00
RainbowBird
a1a5692726
feat(stage-ui,stage-pages,stage-layouts): put the subscription first and show Flux by account state (#3486)
## Summary

AIRI sells Flux in two ways: one-time Flux packs and the Capacitor
subscription, which refills Flux on a schedule. The subscription was
hard to find and hard to understand. It had its own page that most
entries did not link to, and entries used different names.

This PR makes the subscription the main way to get Flux, and one-time
packs a top-up.

- Every entry and the page title say **Subscription** (zh-Hans: **订阅**).
Users did not know what a Capacitor is, so "Capacitor" and "Flux" are
product names inside the page only.
- One rule decides what every entry shows:
- Signed out: nothing, so users who do not use the cloud see no Flux UI.
  - Signed in without a subscription: the Flux balance.
  - Subscribed: the Capacitor percent.
- Every entry opens one page. It opens on one card for the Capacitor:
- Subscribed: the card shows the percent that is left, the refill time,
the renewal date, and the manage link. The fill of the card is the
Capacitor. The top edge of the fill is the usage of the current refill
window, with a forecast at the average pace. The forecast text follows
the dot of the current percent, and the tier of the Capacitor is a chip.
- Not subscribed: the card says what a subscription gives. It has no
curve.
- Below the card come the fallback switch, the Capacitor cards in three
columns, the Flux top-up packs in a grid with the balance, and the
history.
- The separate Capacitor page and the Flux rows of the account page are
removed.
- The subscription now sends the client funnel events that the one-time
packs already send.
- The fallback to the Flux balance stays off by default. This PR does
not turn it on.

The curve needs one new read: `GET /api/v1/flux/capacitor/usage`. It
returns percents only, the same as the balance read. The other changes
are UI. Desktop checkout moved to
[airi#3494](https://github.com/moeru-ai/airi/pull/3494), so desktop
builds keep `main`'s behavior here: without a RevenueCat web key, they
show no subscription UI.

This PR is independent. It is based on `main`.
[airi#3484](https://github.com/moeru-ai/airi/pull/3484) also changes the
desktop Island. The second PR to merge must rebase over the other.

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| Flux status (`stage-ui/composables/use-flux-status.ts`, new) | Each
entry read the auth store itself | One composable returns visibility,
value, and icon | All entries follow the same rule. All entries link to
`AIRI_FLUX_URL`. |
| Flux page (`stage-pages/pages/settings/flux.vue`) | A large filled
card for the Flux balance, packs, and history | One page: the
subscription (`CapacitorSection`), the top-up packs with the balance,
and the history | The title is "Subscription" with a star icon. A
signed-out visitor sees only the packs. The pack grid takes any number
of packs. |
| Capacitor section (`stage-pages/components/capacitor-section.vue`) |
The `/settings/capacitor` page with a thin meter | A component inside
the Flux page. It opens on the Capacitor card, then the fallback switch
and the Capacitor cards. | Without a Capacitor, the card explains the
subscription. If the usage read fails, the card shows the percent as a
plain fill. The route is removed. Nothing in the app links to it. |
| Usage curve (`stage-pages/components/capacitor-usage.ts`, new) | Not
present | Pure functions that turn the usage of a window into the curve,
the fill, and the forecast | The level holds until a debit, then eases
down. A full Capacitor is below the top edge of the card. The forecast
uses the average pace of the window. It is not shown in the first 5% of
a window, for a full Capacitor, or for an empty one. |
| Capacitor usage read (`server/apps/api` `flux.ts`, `routes/flux`) |
Not present | `GET /api/v1/flux/capacitor/usage` returns `startedAt`,
`endsAt`, and `records` of `{ at, percent }` | It reads the `debit` rows
of the Capacitor pool since the last refill, at most the latest 500. It
needs no migration. The ADR `2026-10-04-subscription-credits.md`
describes it. |
| Account page | Flux balance and Capacitor rows | No Flux rows | The
account page holds only account items. |
| Web header (`stage-layouts` `Header.vue`, `header-flux.vue`) | The
avatar menu showed the balance | One Flux entry next to the avatar | The
settings layout uses the same header without the character switcher. The
desktop settings window header is unchanged. |
| Mobile settings drawer | No Flux row | A Flux row after Notifications
| The top row of the mobile stage is unchanged. |
| Desktop Island account area | A small "{credits} Flux" pill | A Flux
row with the same rule | Opens the Flux page in the settings window. |
| Analytics | Only the one-time packs sent `pricing_page_viewed`,
`plan_selected`, and `checkout_started` | The Capacitor section sends
them too, with `plan_period: monthly` and the RevenueCat product id |
The packs keep their `pricing_page_viewed` on page open. |
| i18n (`en`, `zh-Hans`) | Mixed names | Entries and the page title say
Subscription. The page names the Capacitor and does not call it a plan.
Unused keys removed. | Other locales come from Crowdin. |

The Flux page keeps its URL. Stripe's `success_url` and `cancel_url`
(`server/apps/api/src/routes/stripe/operations/checkout.ts`),
onboarding, the provider pages, and the promo banner already point to
it, so the checkout routes do not change.

## Architecture and behavior

```mermaid
flowchart LR
  Auth[auth store: isAuthenticated, credits, capacitorPercent] --> Status[useFluxStatus]
  Status -->|hidden| None[No entry]
  Status -->|balance or percent| Entries[Header, mobile drawer, desktop Island]
  Entries -->|AIRI_FLUX_URL| Page[Flux page]
  Page --> Cap[CapacitorSection]
  Page --> Balance[Balance, packs, history]
```

```mermaid
sequenceDiagram
  participant U as User
  participant P as Flux page
  participant A as OpenPanel
  participant RC as RevenueCat
  participant API as AIRI API
  P->>A: pricing_page_viewed (monthly)
  U->>P: Subscribe on a plan
  P->>A: plan_selected (product id)
  P->>A: checkout_started (product id)
  P->>RC: purchase in the page (web SDK modal)
  P->>API: revenuecat sync, then GET /api/v1/flux
  API-->>P: capacitorPercent
  P->>API: GET /api/v1/flux/capacitor/usage
  API-->>P: window times and percent records
```

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Signed-out users see no Flux UI | Cloud UI intrudes on local-only
users | `useFluxStatus().visible` is `isAuthenticated` |
`use-flux-status.browser.test.ts` |
| Users see the subscription first | Packs keep the attention | The
subscription section comes before the packs | `flux.browser.test.ts`:
`opens on the subscription offer, then the packs with the balance, then
the history` |
| The card shows the usage of the window | The curve or the forecast is
wrong | `capacitorCurve` builds both from the usage read and the current
percent | `capacitor-usage.browser.test.ts`, and `flux.browser.test.ts`:
`draws the usage of the window as the fill of the Capacitor card` |
| A failed usage read does not hide the percent | The card is empty |
The card falls back to a plain fill of the percent |
`flux.browser.test.ts`: `keeps the percent as a plain fill when the
usage read fails` |
| The usage read shows only the current window | Debits of an earlier
window, refills, or wallet debits appear | The query takes `debit` rows
of the Capacitor pool since the last refill. A due refill gives no
records. | `flux.test.ts`: three usage tests. `route.test.ts`: the route
and its auth guard. |
| An empty Capacitor with the switch off stops chat | The user does not
know how to continue | A warning under the card points at the switch |
`capacitor-section.browser.test.ts`: `warns about an empty Capacitor
only when Flux cannot pay` |
| A Stripe return shows its result | The result is missed | The banner
shows at the top of the page | `flux.browser.test.ts`: `shows the result
after a Stripe checkout returns` |
| Signed-out visitors can still buy packs | Public page loses its packs
| `showCapacitor` needs a signed-in user | `flux.browser.test.ts`:
`keeps the original package cards public` |
| The subscription funnel is recorded | No client events for the
subscription | `CapacitorSection` sends the three events |
`capacitor-section.browser.test.ts` checks the events and their order |
| Builds that cannot sell the Capacitor, such as Steam and desktop |
Subscription UI appears without a checkout | `isCapacitorAvailable()`
needs the web key and enabled Flux purchases | Code review. **Not
verified** in a Steam or desktop build. |

## Verification

All commands ran in rc on the PR head before this push (97f863e0f) with
the two new commits applied.

```text
pnpm -F @proj-airi/api-server typecheck                          # exit 0
pnpm -F @proj-airi/api-server exec vitest run src/routes/flux/route.test.ts src/services/domain/flux.test.ts
                                                                 # 2 files, 23 tests passed
pnpm -F @proj-airi/stage-pages typecheck                         # exit 0
pnpm -F @proj-airi/stage-pages exec vitest run src/pages/settings/flux.browser.test.ts src/components/capacitor-usage.browser.test.ts
                                                                 # 2 files, 14 tests passed
pnpm -F @proj-airi/stage-ui exec vitest run src/composables/capacitor-section.browser.test.ts
                                                                 # 1 file, 7 tests passed
eslint <changed files>                                           # 0 errors, 1 warning
pnpm i18n:check                                                  # no errors
```

The lint warning is on `formatNumber` in `flux.vue`, which this PR does
not add.

Not verified:

- The root `pnpm typecheck`. The rc node went down while it ran. CI runs
it on this push.
- The other `stage-pages`, `stage-ui`, and `stage-tamagotchi` tests on
the two new commits. CI runs them.
- One zh-Hans wording change came after the rc run: the empty warning
says "Flux 余额" in place of "Flux 电量".
- The new entry label in the running app. The header, drawer, and Island
captures below are from before the rename.
- A Steam build.
- The server-side purchase event for the subscription. See the follow-up
below.

## Visual changes

The five "After" captures of the Subscription page are new. They render
the page component in a Vitest browser harness in rc, with mocked auth,
Flux, usage, and RevenueCat responses, in English and the light theme at
1100px wide. The harness does not load the app fonts or the settings
layout, so the font and the page header differ from the app. The
captures are from commit `95849f076`. The curve draws once when the card
opens, and the captures show the state after that animation. The other
captures are from the earlier state of this PR: Playwright against a
Vite dev server, and a Vitest browser harness at 520x640 for the desktop
Island. Their header, drawer, and Island rows show the old label "Flux".
The label is now "Subscription".

Scenarios: `none` has 1,200 Flux and no subscription, `active` has
Capacitor Pro at 62%, `empty` has Capacitor Pro at 0%.

| Before | After |
| --- | --- |
|
![](https://github.com/user-attachments/assets/1ee2cebc-61a5-478c-96e6-8f4cebff2ffe)
|
![](https://github.com/user-attachments/assets/c0bcb7a0-cce6-45f0-8622-b8fdba8c8d05)
|
| Flux page / no subscription / 1280x1500 | Subscription / no
subscription / 1100 wide |
|
![](https://github.com/user-attachments/assets/d78494a2-9ee5-42e4-a0a6-cad6c76ab132)
|
![](https://github.com/user-attachments/assets/5adee602-aca6-4891-bdeb-24eb815c2b23)
|
| Flux page / subscribed / 1280x1500 | Subscription / subscribed / 1100
wide |
|
![](https://github.com/user-attachments/assets/2b2263b7-c947-491d-9ec5-53c9098fd1ea)
|
![](https://github.com/user-attachments/assets/879df923-82ff-446b-b510-f96d4afe6e98)
|
| Flux page / Capacitor empty / 1280x1500 | Subscription / Capacitor
empty / 1100 wide |
| Absent |
![](https://github.com/user-attachments/assets/692a3506-cca0-4e3d-ad8d-4600f23931b6)
|
| Absent | Subscription / no subscription / mobile 390 wide |
| Absent |
![](https://github.com/user-attachments/assets/fbe78c96-5fc0-4bbe-8ea4-0b27f7d7ca00)
|
| Absent | Subscription / subscribed / mobile 390 wide. A narrow card
hides the forecast and the icon. |
|
![](https://github.com/user-attachments/assets/05821824-411f-4851-9e02-b28e3e811ec4)
| Removed |
| Capacitor page / no subscription / 1280x1500 | Removed: the content is
on the Flux page |
|
![](https://github.com/user-attachments/assets/98de26d3-78d5-4e29-bba1-418e24013869)
|
![](https://github.com/user-attachments/assets/7a2461f6-e626-4cb4-a223-79ab58a7cb91)
|
| Account / subscribed / 1280x1500 | Account / subscribed / 1280x1500 |
|
![](https://github.com/user-attachments/assets/bcd8da19-d923-4208-af5e-efee5e2e792a)
|
![](https://github.com/user-attachments/assets/ac2fb147-e93b-4dca-83ae-e38699294e27)
|
| Web stage header / no subscription / 1280x860 | Web stage header / no
subscription / 1280x860 |
|
![](https://github.com/user-attachments/assets/cf150f26-2976-40d4-9e01-67a65e7a267a)
|
![](https://github.com/user-attachments/assets/e61f9aca-7965-4d31-be2b-d3d13fb74ea5)
|
| Web stage header / subscribed / 1280x860 | Web stage header /
subscribed / 1280x860 |
|
![](https://github.com/user-attachments/assets/43386177-5f17-4f32-9d27-fb6250f1047d)
|
![](https://github.com/user-attachments/assets/882aef97-fc2e-46ce-887f-d62adc8d4328)
|
| Mobile settings drawer / subscribed / 390x844 | Mobile settings drawer
/ subscribed / 390x844 |
|
![](https://github.com/user-attachments/assets/7ab4e370-0429-4760-aeb4-e3ee09318436)
|
![](https://github.com/user-attachments/assets/e8a972f3-7fae-48b4-b005-dc9a26bbdf00)
|
| Desktop Island menu / no subscription | Desktop Island menu / no
subscription |
|
![](https://github.com/user-attachments/assets/c3943074-f332-45b2-972e-19b278a2c01f)
|
![](https://github.com/user-attachments/assets/dc6c8954-1fa9-4362-b146-062a8640b785)
|
| Desktop Island menu / subscribed | Desktop Island menu / subscribed |

## Rollout and follow-up

- Desktop checkout is in
[airi#3494](https://github.com/moeru-ai/airi/pull/3494).
- The server does not record a subscription purchase in OpenPanel. The
Stripe webhook sends `payment_completed`, but the RevenueCat webhook
does not. A separate server PR can send it for `INITIAL_PURCHASE`, so
the subscription funnel has an end.
- Desktop subscribers cannot manage the subscription in the app yet.
- The Capacitor cards have no "recommended" mark. The RevenueCat catalog
does not say which Capacitor to recommend.
- A build that cannot sell the Capacitor, such as Steam, still labels
the entry "Subscription", while its page shows only the Flux balance.
- The history keeps its table. The legacy attributify classes in that
part of `flux.vue` are not refactored here.

## Follow-ups from review

These four review findings are open. This pull request does not change
them. None of them is verified against the code.

- The subscription pricing view is recorded while the subscription tab
is hidden.
- A build without a RevenueCat web key, or with purchases off, hides the
Flux fallback switch from a subscriber.
- The usage curve omits a debit that the refill transaction posts.
- A wallet refresh on window focus does not refresh the usage of the
curve.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Lulu <anlulu.dev@yahoo.com>
2026-11-12 21:47:15 +08:00
Neko Ayaka
528a31de63 release: v0.15.2
Some checks are pending
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Update Nix pnpmDeps Hash / update (push) Waiting to run
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Cloudflare Workers / Build - docs (push) Waiting to run
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
2026-11-09 21:14:10 +08:00
RainbowBird
fe0b8fa73f
feat(api-server): index llm_request_log by created_at (#3457)
## Summary

Add the index `llm_request_log_created_idx` on
`llm_request_log(created_at)`.

The admin API reads the request log by time window across all users:
request statistics, and since
[proj-airi/backend#68](https://github.com/proj-airi/backend/pull/68) the
provider health query and minute/hour windows. The table has indexes
only for `(user_id, created_at)`, `(user_id, request_id)`, `(state,
started_at)` and `(gateway, generation_id)`. Without a user filter,
those queries scan the whole table. The Go Ent mirror in
proj-airi/backend already declares this index, but no migration created
it.

## Change map

- `server/apps/api/src/schemas/llm-request-log.ts`: the new index.
- `server/apps/api/drizzle/0034_llm_request_log_created_index.sql` and
`meta/`: generated by `drizzle-kit generate --name
llm_request_log_created_index`. The only statement is the new index. I
changed it to `CREATE INDEX IF NOT EXISTS`.

## Boundaries and risks

- The migrator runs pending migrations in one transaction, so the
migration cannot use `CONCURRENTLY`. A plain `CREATE INDEX` blocks
writes to `llm_request_log` while it builds. Request log rows are
written after the response is sent, so a short block delays log writes,
not user requests.
- To avoid the block, run this on production before the deploy. The
migration then skips the existing index:

  ```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS "llm_request_log_created_idx" ON
"llm_request_log" USING btree ("created_at");
  ```

- Rollback: `DROP INDEX IF EXISTS "llm_request_log_created_idx";`. No
data changes.

## Verification

In rc, on a clone at a0d1b2ce0:

- `drizzle-kit generate`: no change other than the new index.
- `pnpm -F @proj-airi/api-server typecheck`: pass.
- `server/apps/api` Vitest: 88 files passed, 2 skipped; 975 tests
passed, 4 skipped.
- `eslint` on the changed schema file: no errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:28:46 +08:00
RainbowBird
a0d1b2ce03
feat(api-server): report GenAI metrics with the OTel semantic convention names (#3450)
Some checks failed
CI / Type Check (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
Crowdin upload changed translations / upload-translations-to-crowdin (push) Has been cancelled
## Summary

The API gateway reported GenAI metrics with names that are not in the
OpenTelemetry GenAI semantic conventions. It also did not report cache
tokens, reasoning tokens, or cost. Postgres already had this data, but
Prometheus did not. This PR uses the convention names from
[`open-telemetry/semantic-conventions-genai`](https://github.com/open-telemetry/semantic-conventions-genai)
and adds the missing values. Then an OpenRouter-style usage dashboard
can use only Prometheus. Top users stay in Postgres, because `user_id`
is a high-cardinality label.

The GenAI constants now live only in `@proj-airi/trace-kit`. trace-kit
already had 17 hand-copied GenAI attribute names. The GenAI conventions
moved to a new repository that has no release and no npm package. The
GenAI exports of `@opentelemetry/semantic-conventions` are deprecated
and use the old names. So a script in trace-kit generates
`src/conventions/semconv.ts` from a pinned commit (`e6658f1`,
2026-11-06) of the registry YAML. The 17 old copies have the same
values. An upgrade changes the commit and runs `pnpm -F
@proj-airi/trace-kit generate:semconv`. The diff of the generated file
then shows each renamed name. The API imports the names from the new
`@proj-airi/trace-kit/semconv` entry. That entry has only constants, so
the server does not load the trace runtime.

The dashboards change in a paired PR. Apply it to Grafana after this PR
deploys:

- [airi-deploy#5](https://github.com/proj-airi/airi-deploy/pull/5)
feat(grafana): read the GenAI semantic convention metrics and add spend
panels · 2026-11-08 · @luoling8192

## Change map

| Metric or attribute | Before | After | Description |
| --- | --- | --- | --- |
| Chat and Responses duration | `gen_ai.client.operation.duration` |
`gen_ai.client.inference.duration` | The conventions say that inference
must not use `operation.duration` |
| Request count | `gen_ai.client.operation.count` | Removed | Use the
`_count` series of the duration histograms |
| Input and output tokens | `gen_ai.client.token.usage.input/output` |
`gen_ai.client.inference.usage.input_tokens/output_tokens` | Convention
names, with `gen_ai.token.modality=unknown` |
| Cache and reasoning tokens | Not reported |
`gen_ai.client.inference.usage.cache_read.input_tokens`,
`cache_write.input_tokens`, `reasoning.output_tokens` | Values from
`extractUsageFromBody` |
| First chunk latency | `gen_ai.client.first_token.duration` |
`gen_ai.client.inference.time_to_first_chunk` | Chat, Responses, and the
TTS WebSocket |
| Cost | Not reported | `airi.gen_ai.client.cost` (USD) | The
conventions have no cost metric. The value is the upstream cost that the
provider reports, not the Flux charge |
| Provider label | `provider` | `gen_ai.provider.name` | Gateway
`airi.gen_ai.gateway.*` counters keep `provider` |
| Other labels | None | `gen_ai.response.model`, and `error.type` when
the status is 400 or more | `http.response.status_code` stays |
| TTS duration | `gen_ai.client.operation.duration` | Same | TTS is not
an inference operation |
| GenAI constants | Strings in `utils/observability.ts`, and 17 hand
copies in trace-kit | Generated once in trace-kit, imported from
`@proj-airi/trace-kit/semconv` | `error.type` comes from
`@opentelemetry/semantic-conventions`. The trace-kit test that compared
copies with the deprecated npm exports is removed |
| Span attributes | Input and output tokens | Also
`gen_ai.usage.cache_read.input_tokens`, `cache_write.input_tokens`,
`reasoning.output_tokens` | |

Token and cost counters record only positive values, as the conventions
require. A missing or zero value records nothing.

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| Dashboards in `proj-airi/airi-deploy` read the old names | Panels go
empty after deploy |
[airi-deploy#5](https://github.com/proj-airi/airi-deploy/pull/5) moves
them | Apply that PR to Grafana right after this deploy |
| Grafana alert rules read the old names | Alerts stop firing | None. No
repository has the rules | Unverified. Check the rules in Grafana |
| Generated constants match the pinned registry | A hand edit or a stale
file gives wrong names | The file is generated, and the generator throws
on duplicate names | `render.test.ts`. Regenerating in rc gave no diff |
| trace-kit consumers | Removing `SEMCONV_VERSION` or changing the root
exports breaks a consumer | Nothing read `SEMCONV_VERSION`. The 17 names
keep their values | Typecheck of trace-kit dependents in rc, see
Verification |
| Docker build of the API | The image misses trace-kit | Both API
Dockerfiles copy and build `packages/stream-kit` and
`packages/trace-kit` | No Docker build ran. Checked by reading the
Dockerfiles |
| Cost matches the provider receipt | Cost is recorded as the Flux
charge, or is lost when the wallet cannot pay | `costUsd` comes from
`price.costReceipt.usage.costUsd`, before settlement | `route.test.ts`:
a drained wallet still records `0.038` USD |
| Label cardinality | High-cardinality labels | Only model, provider,
operation, status, and error type. No user ID | Code review |
| The conventions are at `development` stability | Names can change
again | None | Accepted risk |

## Verification

All checks ran in an rc Workspace, on a clean clone with this diff
applied.


- `pnpm -F @proj-airi/api-server typecheck`: passed.
- `pnpm -F @proj-airi/api-server exec vitest run`: 88 files passed and 2
skipped. 975 tests passed and 4 skipped.
- `pnpm exec eslint <changed files>`: 0 errors. The warnings that remain
were there before this change.
- `pnpm install --frozen-lockfile` (full workspace): passed. The
lockfile change is the API link to trace-kit and the trace-kit
devDependencies.
- `pnpm -F @proj-airi/trace-kit build`: passed, with `dist/semconv.mjs`.
- `turbo run test:run` for trace-kit, ui-trace, and testing-audio: 28
tasks passed. trace-kit 73 tests, ui-trace 17 tests.
- `turbo run typecheck --filter=...@proj-airi/trace-kit
--filter=@proj-airi/api-server --continue`: 10 of 13 passed.
`airi-plugin-game-chess`, `stage-tamagotchi`, and
`stage-tamagotchi-kirie` failed on errors in `electron-vueuse` and Vue
pages. The same three fail on the merge base `b51672dc8` in the same
Workspace.
- Full API suite on the final head: 974 passed, 1 failed. The failure is
a 5 s timeout in `mock-db.test.ts` under node load. The file passed
alone. Earlier runs had the same timeouts in PGlite tests.
- New tests in `telemetry.test.ts` cover each new counter, its
attributes, the skip of zero values, and `error.type`.

I did not check the exported names on a live Prometheus. With the OTLP
translation, I expect `airi_gen_ai_client_cost_total` and
`gen_ai_client_inference_usage_input_tokens_total`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:32:21 +00:00
Neko
d16d54417d
chore: upgrade injeca to 0.5.1 (#3436) 2026-11-08 06:41:31 +08:00
Neko
9746435252
chore: upgrade injeca to 0.3 and move lifecycle hooks into build (#3412) 2026-11-06 14:53:50 +08:00
RainbowBird
89ec1e953f release: v0.15.1 2026-11-04 16:00:30 +07:00
RainbowBird
4f0cb5cc31 release: v0.15.0
Some checks are pending
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
2026-11-04 00:41:45 +07:00
RainbowBird
e2dc1f491f
test: make the slowest test suites faster (#3362)
## Summary

This change makes the slowest test suites faster. It removes no test
case and no assertion. Each change has a measurement before and after in
rc, and the CI result follows below.

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| `api-server` test database | Each `mockDB` call creates PGlite and
pushes the full schema, about 2.7 s. | The first call per schema saves
the database file. Each later call loads a copy, about 0.5 s. | Each
call still gets an empty database. The key is the schema snapshot, so a
changed table gets a new push. |
| `api-server` Vitest | `fileParallelism: false`, `maxWorkers: 1` |
Default parallel workers | Each file has its own in-memory database. |
| `stage-ui` node tests | `fileParallelism: false`, `maxWorkers: 1` |
Two workers, in a group before the browser group | Vitest needs a
separate group for a project with its own worker limit. |
| VRM view test (Issue #1806) | Downloads `AvatarSample_A.vrm` and loads
it five times. | Builds a small VRM 1.0 file in the test and loads it
five times. | The test checks model identity and offsets. Model content
does not change them. |
| Inlay return-home test | Waits 5.5 s, then polls for up to 7 s. | Fake
timers move the clock. | The same two checks stay: no return while
speech shows, then one return. |
| Controls Island timer tests | Three real waits of 1.7 s, then a wait
for the 1.5 s collapse interval. | A clock that runs with real time and
that the test moves forward. | The clock starts before mount, so the
timers that mount creates are fake too. |

## Measurements in rc

Each run used `taskset -c 0-3` on one rc machine, to match a 4 vCPU CI
runner.

| Test | Before | After |
| --- | --- | --- |
| `field-sync/store.test.ts` and `character-cards.test.ts` | 43.0 s |
14.1 s and 15.0 s |
| `api-server`, all files | 143.8 s | 57 s, three runs |
| `stage-ui` node project | 81 s to 89 s | 36 s to 39 s with four
workers, three runs |
| `stage-ui`, all projects | 168 s | 127 s |
| VRM view test, test time | 19.0 s and 20.0 s | 2.0 s and 2.7 s |
| `controls-island-overflow.browser.test.ts` | 47.1 s | 37.3 s and 38.0
s |
| Inlay return-home test | 10.5 s | under 0.3 s, three runs |

The before run of the VRM test also failed once in rc. The download of
`AvatarSample_A.vrm` stopped with `ResponseContentLengthMismatchError`.
The new test does not need that download.

## Measurements in CI

Before is main run
[41602759203](https://github.com/moeru-ai/airi/actions/runs/41602759203).
After is this pull request, run
[41649791029](https://github.com/moeru-ai/airi/actions/runs/41649791029).
Each value is one run.

| Test or shard | Before | After |
| --- | --- | --- |
| `field-sync/store.test.ts` | 49.4 s | 21.1 s |
| `api-server-1` Vitest duration | 134.8 s | 37.9 s |
| `api-server-2` Vitest duration | 115.2 s | 46.2 s |
| `stage-ui-1` Vitest duration | 134.2 s | 83.7 s |
| `stage-ui-2` Vitest duration | 116.8 s | 96.2 s |
| VRM view test file | 34.7 s | 6.0 s |
| `voice-inlay.browser.test.ts` | 16.9 s | 6.7 s |
| `controls-island-overflow.browser.test.ts` | 38.1 s | 35.4 s |
| Slowest Unit Test shard, job time | 254 s (`stage-ui-1`) | 238 s
(`others`) |

The shard job times are not a direct comparison. The `others` shard of
this pull request ran 35 of 72 packages, and the main run ran 3 of 72.
The `stage-tamagotchi` shard took 96.1 s before and 111.6 s after, with
two packages run in each.

## Boundaries and risks

| Invariant | Failure mode | Protection | Evidence |
| --- | --- | --- | --- |
| Each `mockDB` call gets an empty database | A copy keeps rows from an
earlier test | The copy is taken right after the schema push | New test
`gives each call an empty database when the schema repeats` |
| A changed schema gets a new push | Two tables with one name share a
wrong copy | The key is the full Drizzle Kit snapshot, without its
random ids | New test `pushes a new schema when a table with the same
name changes its columns` |
| Parallel files do not share state | Tests interfere | Each file has
its own PGlite and Pinia | `api-server` and `stage-ui` passed three
times each in rc |
| Slow store imports do not time out | Too many workers starve
`hearing.analytics.test.ts`, which has a 10 s limit | Two workers for
the `stage-ui` node project | It failed with default workers under Turbo
concurrency 2, and passed with two workers |

## Verification

All commands ran in rc.

- `pnpm -F <package> typecheck` for `api-server`, `stage-web`,
`stage-tamagotchi`, and `stage-ui`: all passed.
- `TURBO_SCM_BASE=<merge base> pnpm exec turbo run test:run --affected
--concurrency=2 --force`, two runs. Run 1 passed 44 of 44 tasks. Run 2
failed one case in `InteractiveArea.browser.test.ts` (`expected 250.0625
to be 238`). This change does not touch that file, and it also failed on
main before this change.
- `vitest run` for the VRM, inlay, and Controls Island files: passed in
each run listed above.
- `pnpm run lint`: 0 errors.
- CI on `69ec14634`: all checks passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:44:03 +00:00
Younsang Na
4746803ac3
refactor: remove five any types from api-server, ui-loading-screens, and ui-transitions (#3333) 2026-11-03 16:22:07 +08:00
RainbowBird
6e9cb7c436
fix(stage-ui): make display model sync recover like character cards (#3343)
Some checks are pending
CI / Unit Test (api-server-1) (push) Blocked by required conditions
CI / Unit Test (api-server-2) (push) Blocked by required conditions
CI / Unit Test (stage-tamagotchi) (push) Blocked by required conditions
CI / Unit Test (stage-ui-1) (push) Blocked by required conditions
CI / Unit Test (stage-ui-2) (push) Blocked by required conditions
CI / Unit Test (push) Blocked by required conditions
CI / Type Check (others) (push) Blocked by required conditions
CI / Type Check (desktop) (push) Blocked by required conditions
CI / Type Check (web) (push) Blocked by required conditions
CI / Type Check (push) Blocked by required conditions
CI / Check Provenance (push) Blocked by required conditions
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Cloudflare Workers / Build - docs (push) Waiting to run
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
## Summary

Display model cloud sync can stop for good after one failed step, and it
does not reach a running device. Character card sync does not have these
problems, because each run compares the current state and the runs start
often. This PR gives display models the same design, and moves the
shared scheduling to `libs/sync-runner`.

The feature stays behind the `display-model-sync` flag. The server code
does not change. This PR is independent.

The display model sync comes from this pull request:

- [airi#2869](https://github.com/moeru-ai/airi/pull/2869)
feat(api,stage-ui): sync Live2D and VRM models to private storage ·
2026-10-08 · @luoling8192

## Change map

| Module | Before | After | Description |
| --- | --- | --- | --- |
| `libs/sync-runner` | Did not exist. The card store owned its
scheduling. | Runs one synchronization at a time, retries a failed run,
and requests runs on events. | Later sync features reuse this code. |
| `stores/display-model-cloud` | Did not exist. Each window ran the
queue and held the directory. | A synced store. The leader owns the
queue and the comparison. Each window reads the state. | One window
uploads, and all windows show one state. |
| `stores/display-models` | Local files, downloads, uploads, and the
directory. | Local files and downloads. It reads the rest from the cloud
store. | Downloads stay in the caller window, because a leader-routed
call rejects after 30 seconds. |
| `stores/modules/airi-card` | Its own run loop and watchers. | Uses
`SyncRunner` and `watchSyncTriggers`. | Cards also get a timed retry and
the focus and network triggers. |
| `stores/settings/stage-model` | Loaded the selection only when the
selection changed. | Also retries after the available models change. | A
sign-in or a reconnection can repair an empty Stage. |
| `libs/file-transfer` | A failed task waited for a manual retry. |
`retryFailed` runs it again, except after a permanent refusal. | A full
quota does not upload the same file again and again. |

## Architecture and behavior

### S1: an upload attempt fails after the PUT

Before, a retry could never finish:

```mermaid
sequenceDiagram
  participant Q as TransferQueue
  participant A as API
  participant S as Object store
  Q->>A: reserve(requestId R)
  A-->>Q: session 1
  Q->>S: PUT key 1
  Q->>A: complete(session 1)
  A--xQ: network failure
  Q->>A: retry: reserve(requestId R)
  A-->>Q: session 1 again
  Q->>S: PUT key 1
  S-->>Q: 412, the key already exists
  Note over Q: failed, and each later retry repeats this
```

After, each attempt reserves a new session:

```mermaid
sequenceDiagram
  participant Q as TransferQueue
  participant A as API
  participant S as Object store
  Q->>A: reserve(requestId R1)
  A-->>Q: session 1
  Q->>S: PUT key 1
  Q->>A: complete(session 1)
  A--xQ: network failure
  Q->>A: next run: reserve(requestId R2)
  A-->>Q: session 2
  Q->>S: PUT key 2
  Q->>A: complete(session 2)
  A-->>Q: ready
```

An expired session (410) or an aborted session (409) recovers in the
same way.

### S2: runs in several windows

```mermaid
flowchart LR
  F[Follower window] -->|synchronize action| L[Leader window]
  M[Leader window triggers] -->|synchronize action| L
  L --> R[SyncRunner]
  R -->|list, rename, delete| API
  R --> Q[TransferQueue]
  R -->|localRevision and directory state| F
  F -->|reads the files again| IDB[(IndexedDB)]
```

### Other scenarios

- S3: a new leader starts its queue and resumes the persisted uploads.
- S4: a name follows the side that changed it. `syncedName` is the
common base. The account name wins if both sides changed it.
- S5: a failed directory read retries after 30 seconds, 2 minutes, and
then 10 minutes. The Stage then loads a selection that it could not
load.
- S6: an account switch reloads the list, and a direct lookup checks the
account. A private copy of the previous account stays hidden.
- S7: removing a copy that came from the account does not report a
deletion. Cards keep their references when sync is off or after
sign-out.
- S8: a session change stops uploads and downloads in the same task. The
account stays unknown until `user` matches the new token.

## Boundaries and risks

| Invariant or boundary | Failure mode | Protection | Evidence or gap |
| --- | --- | --- | --- |
| One upload for each persisted task | Two windows upload one file | The
leader owns the queue | `display-model-cloud.browser.test.ts`, with real
leader and follower runtimes |
| A transfer stays in its account | `authedFetch` sends the current
token, so an active upload can write into a new account. During a
sign-in, the token changes before `user`. | `isSessionVerified` in the
auth store, and a sync watcher that stops the queue and downloads in the
task of the change | `display-models.test.ts`. Both cases fail without
the guard. |
| A queued file stays in its account | The queue action waits for a run,
and the session changes during the wait | The caller names the account,
and the action compares it after the wait. `enqueue` drops a task if the
account changes during its write. | `display-models.test.ts` fails
without the guard. `transfer-queue.test.ts` |
| Card sync stays in its account | More triggers can start a run during
a sign-in, while `userId` names the previous account |
`runCardSynchronization` waits for `isSessionVerified`, and `isCurrent`
checks the session version | `airi-card-sync.browser.test.ts`. The case
fails without the guard. |
| A session failure can recover | A 410, or a 409 from completion, stops
the background retry | `TransferRequestError.permanent`. Only a refusal
of the file or the account is final. | `display-model-sync.test.ts` |
| The directory follows the account | After a sign-out, the models of
the previous account stay listed | A run compares both owners |
`display-models.test.ts` |
| A new leader takes over | Replicated `ownerId` hides the switch, so
the queue never starts | `queueOwnerId` is local to the window |
`display-model-cloud.browser.test.ts` |
| Retries stop on a permanent refusal | A full quota repeats a large
upload | `isPermanentTransferFailure` | `display-models.test.ts` |
| Follower calls can time out | A leader-routed call rejects after 30
seconds | Long work reports through state. Downloads stay in the caller
window. | Read from `pinia-plugin-synced`. No test runs a 30-second
call. |
| Storage cost | Each attempt can leave an unused object and a session
row | The external cleanup in the ADR | Unverified. This PR does not
check that the cleanup job exists. |
| Repeated large uploads | An unstable network restarts the PUT on each
retry | A PUT cannot resume | Known limit, not changed here |
| Storage CORS | Electron or Capacitor origins can be missing from the
production bucket | None in code | Unverified. The repository has only
`server/dev/s3/cors.json`. |

## Verification

No UI structure changes, so this PR has no visual evidence. The model
selector and the mobile strip only refresh the directory when they
mount. No run used real devices or real object storage.

| Command | Result |
| --- | --- |
| `pnpm -F @proj-airi/stage-ui exec vitest run` | 1987 passed, 2 failed.
See below. |
| `pnpm -F @proj-airi/stage-pages exec vitest run` | 67 passed |
| `pnpm -F @proj-airi/api-server exec vitest run
src/services/domain/display-models.test.ts` | 13 passed |
| `TURBO_SCM_BASE=<merge base> pnpm exec turbo run test:run --affected
--continue --concurrency=2` | 43 of 44 tasks passed. `stage-ui` failed.
See below. |
| `pnpm -F @proj-airi/stage-ui typecheck` | Passed |
| `pnpm -F @proj-airi/api-server typecheck` | Passed |
| `pnpm -F @proj-airi/stage-web typecheck` and `stage-pocket typecheck`
| Passed |
| `pnpm typecheck` | Failed in `stage-tamagotchi-kirie`, with the same
44 errors on the base commit. The local install did not build some
packages. |
| `pnpm -F @proj-airi/stage-tamagotchi typecheck` | Failed with 185
errors. None touch a changed file. The common cause is unbuilt packages.
CI is the check for this. |
| `pnpm lint` | 0 errors, 683 warnings |

Failures in the local test runs:

- `markdown-renderer` tilde highlight failed in earlier runs, also
without this change. It passed in the last full run.
- `silero-vad` failed under load. It passed alone with this change, and
one case failed alone on the base commit.
- `speech` voice catalog routing failed once in the full run. It passed
twice alone.
- CI failed `airi-card.test.ts` twice with a stale selection. A store
lookup after an await returned the store of another Pinia, because the
only writer writes an empty value in this state. The tests now pass
their own Pinia. The late work that changes the active Pinia is not
identified, and the failure did not reproduce locally. Production has
one Pinia, so this affects only tests.
- A Node worker exits after all Node tests pass, on this ARM64 machine,
with a native `std::vector` assertion. Clean `main` does the same. CI
does not show it.
- `live2d` settings and `polaroid` timed out under load. Both passed
alone.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:47:05 +00:00
RainbowBird
8d27dcffcb
ci: reduce CI time without removing checks (#3330)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:52:33 +08:00
Aleytia Fairlight
f7106e3d6b
test(api): keep the capacitor test periods relative to the clock (#3320) 2026-11-02 13:46:30 +08:00
Neko Ayaka
349ecfeda2 release: v0.14.1 2026-10-30 23:42:06 +08:00
Neko Ayaka
c32506cd2b release: v0.14.0
Some checks are pending
CI / Build Test (ui-loading-screens) (push) Waiting to run
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Build Test (stage-web) (push) Waiting to run
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
Release Tamagotchi / Build-4 (push) Blocked by required conditions
Release Tamagotchi / Publish Bundle (push) Blocked by required conditions
Release Tamagotchi / Promote Canary to Stable (push) Blocked by required conditions
Release Tamagotchi / Plan Updates (push) Waiting to run
Release Tamagotchi / Build (push) Blocked by required conditions
Release Tamagotchi / Build-1 (push) Blocked by required conditions
Release Tamagotchi / Build-2 (push) Blocked by required conditions
Release Tamagotchi / Build-3 (push) Blocked by required conditions
Release Tamagotchi / Publish GitCode Release Mirror (push) Blocked by required conditions
Update Nix pnpmDeps Hash / update (push) Waiting to run
Release Tamagotchi / Publish Distribution (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-1 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-2 (push) Blocked by required conditions
Release Tamagotchi / Publish Distribution-3 (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
2026-10-30 02:27:22 +08:00
Neko Ayaka
5d97ac41b7 release: v0.13.1 2026-10-29 07:19:40 +08:00
RainbowBird
215cfc3e64
feat(api-server): send configured headers to LLM upstreams (#3200)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Neko <neko@ayaka.moe>
2026-10-29 02:48:37 +08:00
jim139129
32054c07cf
fix(security): update runtimes for CVE-2026-111497 (#3184) 2026-10-28 20:45:56 +08:00
Neko Ayaka
3c4aca2093 release: v0.13.0 2026-10-28 05:26:59 +08:00
Neko Ayaka
3b0672e366 release: v0.12.0
Some checks are pending
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Build Test (stage-web) (push) Waiting to run
CI / Build Test (ui-loading-screens) (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
Crowdin upload changed translations / upload-translations-to-crowdin (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
2026-10-23 18:58:29 +08:00
Neko Ayaka
c7c9c91791 release: v0.12.0-beta.6
Some checks failed
CI / Build Test (ui-loading-screens) (push) Waiting to run
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Build Test (stage-web) (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix assets Hash / update (push) Has been cancelled
2026-10-23 14:31:31 +08:00
Younsang Na
de5844c3fa
test: run workspace tests through Turbo (#3048)
Some checks are pending
CI / Build Test (stage-web) (push) Waiting to run
CI / Build Test (ui-loading-screens) (push) Waiting to run
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Lint (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
2026-10-21 20:44:37 +08:00
RainbowBird
7a0f5bc391
fix(api,stage-ui): keep the character of synchronized chats (#2874)
Some checks are pending
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Build Test (stage-web) (push) Waiting to run
CI / Build Test (ui-loading-screens) (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Update Nix pnpmDeps Hash / update (push) Waiting to run
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 01:56:16 +08:00
RainbowBird
b7ca814039
feat: show account Notifications from AIRI Cloud (#3022)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:53:40 +00:00
Neko
8781d10cd9
refactor(server): use valibot format actions instead of regexes (#3045) 2026-10-20 00:27:40 +08:00
Neko
80cf17f344
fix(server): match trusted origins by their parsed URL (#3043) 2026-10-19 23:54:52 +08:00
Neko
06103df976
feat(api-server): pass the language of speech text to StepFun (#3042) 2026-10-19 23:54:22 +08:00
RainbowBird
c0f961e234
docs(server): define HTTP response conventions (#3028)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:15:33 +08:00
RainbowBird
4608dea156
feat(api): add Redis Streams infrastructure and publish account events (#3025)
Some checks are pending
CI / Build Test (ui-transitions) (push) Waiting to run
CI / Unit Test (push) Waiting to run
CI / Type Check (push) Waiting to run
CI / Check Provenance (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build Test (stage-tamagotchi) (push) Waiting to run
CI / Build Test (stage-tamagotchi-godot) (push) Waiting to run
CI / Build Test (stage-web) (push) Waiting to run
CI / Build Test (ui-loading-screens) (push) Waiting to run
Cloudflare Pages (Auth UI) / Deploy - ui-server-auth (push) Waiting to run
Cloudflare Workers / Build - docs (push) Waiting to run
Cloudflare Workers / Deploy - stage-web (push) Blocked by required conditions
E2E Test - Tamagotchi (Linux) / X11 window render (Xvfb) (push) Waiting to run
E2E Test - Tamagotchi (Linux) / Wayland window render (weston headless) (push) Waiting to run
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 02:05:06 +08:00
RainbowBird
7c6bb0df93
feat(capacitor): show quota and refill details (#3004) 2026-10-17 10:33:25 +00:00
railway-app[bot]
6b1cb3b257
fix: import errors from http-error-shared (#3005) 2026-10-17 18:16:59 +08:00