Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.16.2): multi-provider AI + real-time traffic, SDK construction fix (A2)
Ashiq Hussain Mir1cebd1215e51
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 35525a6..97c178d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,59 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.16.2] — 2026-11-07++### Fixed++- **Every console/env-configured AI provider failed with "Configuration+ file not found or invalid" (A2 root-cause fix).** A1 injected the+ resolved provider into `process.env.ZAI_BASE_URL`/`ZAI_API_KEY` before+ calling `ZAI.create()`, on the belief that the SDK resolved env vars.+ It does not — the SDK's `loadConfig()` only ever reads+ `.z-ai-config` files (cwd → ~ → /etc). On any host without that file+ (the canvix.app VPS included) every "Test connection" answered+ 502 "Provider initialization failed" and every AI feature answered+ 503, no matter what was saved in the console. `makeClient()`+ (src/lib/ai/provider.ts) now constructs the SDK directly with the+ resolved `{ baseUrl, apiKey }` — the constructor takes exactly that+ shape, and any OpenAI-compatible endpoint works through it.++### Added++- **Multi-provider AI configuration (A2).** `/admin`'s AI page now has+ a providers table — up to eight OpenAI-compatible endpoints (NVIDIA+ NIM, OpenRouter, Z.ai, Groq, OpenAI…), one write-only key each — and+ five capability slots (`text`, `vision`, `image`, `imageEdit`,+ `imageSearch`) that can each be pinned to a different provider ++ model, so Magic Write can run on one vendor while image generation+ runs on another. Per-slot precedence: providers table → legacy+ single override → env vars → `.z-ai-config` → unconfigured.+ `/api/ai/capabilities` probes per slot; keys are preserved on edit+ (empty field = keep the stored credential); one click imports the+ A1 single-provider override into the table. Storage is one more+ `AppConfig` JSON row (`ai.providers`) — no schema change. Per-row+ Test buttons probe a specific provider (`{ providerId }` body on+ `/api/admin/config/ai-test`).+- **Real-time traffic panel (A2).** `/admin`'s overview now leads with+ a live panel fed by `GET /api/admin/realtime` (2 s polling,+ self-excluded from its own counters): requests/errors per second+ over the last 60 s, 5-minute request/error/active-visitor/AI-call+ totals, p50/p95 latency and the window's top routes. Counters live+ in `src/lib/admin/realtime.ts` — a zero-import, hard-capped,+ in-memory module statically linked into the observability wrapper+ (cannot repeat the v0.16.1 edge-bundle regression); visitors are+ per-boot salted hashes, never raw IPs; `CANVIX_TRAFFIC=0` disables+ live recording together with the durable counters. Process-local by+ design — TrafficStat/AIUsage remain the durable record.++### Changed++- `withProvider()` handlers now receive one `{ zai, model }` context+ instead of a bare client — a slot's provider and model can no longer+ drift apart between resolution and the request.+- MCP `generate_design` uses the text slot's provider + model (was:+ SDK default on whatever `getZAI()` resolved).+## [0.16.1] — 2026-11-07### Fixeddiff --git a/docs/ADMIN.md b/docs/ADMIN.mdindex 910915b..8e869f6 100644--- a/docs/ADMIN.md+++ b/docs/ADMIN.md@@ -1,4 +1,4 @@-# Admin console (v0.16 A1)+# Admin console (v0.16 A1 · v0.16.2 A2)> **TL;DR** — set `CANVIX_ADMIN_USERS="your-username"`, restart, sign in:> the shield icon on the dashboard opens `/admin`. Everything below is@@ -69,7 +69,29 @@ is changed; the env always wins, and the badge says so.### AI & models-**Provider precedence** (highest wins):+**Providers (the multi-provider table, v0.16.2 A2).** Add up to+8 providers — any OpenAI-compatible endpoint works (NVIDIA NIM,+OpenRouter, Z.ai, Groq, OpenAI…): a label, a base URL and a+write-only API key each. Every capability **slot** can then be pinned+to a different provider + model:++| Slot | What answers through it |+| --- | --- |+| `text` | Magic Write · Translate · Assistant (chat completions) |+| `vision` | Magic Layers (image understanding) |+| `image` | text-to-image |+| `imageEdit` | Magic Eraser / Enhance |+| `imageSearch` | stock photo search |++A slot left on “— fall back —” ignores the table and walks the legacy+chain below. `/api/ai/capabilities` now probes **per slot**, so wiring+text to NVIDIA and images to Z.ai reports exactly those features as+available. Editing a provider (label/URL) never demands the key again:+an empty key field keeps the stored credential (matched by id);+deleting the row and re-adding needs it. One click imports the old+single-provider override into the table and clears the legacy row.++**Fallback chain** for unpinned slots (highest wins):1. the **console override** stored in `AppConfig` (`ai.provider`),2. `ZAI_BASE_URL` + `ZAI_API_KEY` environment variables,@@ -78,15 +100,17 @@ is changed; the env always wins, and the badge says so.The override needs **both** fields; sending `provider: null` clears itand restores the env/file fallback. The page always shows which layer is-currently answering (`console / environment / config file`) and the-effective base URL — but **never the key**: it is stored once and echoed-back only as a mask (`sk-1…wxyz`). Same posture as the env var it-overrides.--**Models** — `text` (Magic Write, Translate, Assistant), `vision`-(Magic Layers, default `glm-4.5v`) and `image` ids. Empty = the SDK-default, exactly the pre-console behaviour. Ids are validated-(`[A-Za-z0-9._:+-]{1,120}`) before they can reach the provider.+currently answering per slot (`providers table / legacy override /+environment / config file`) and the effective base URLs — but **never a+key**: keys are stored once and echoed back only as masks+(`sk-1…wxyz`). Same posture as the env vars they override.++**Models** — per-slot model ids in the providers table; the fallback+chain still reads the legacy `text` / `vision` / `image` ids (`vision`+defaults to `glm-4.5v`). Empty = the provider's default, exactly the+pre-console behaviour. Ids are validated (`[A-Za-z0-9._:+/@-]{1,120}` — `/`+for NVIDIA NIM namespaces, `@` for OpenRouter prefixes)+before they can reach a provider.**Feature switches** — seven kill switches (Magic Write, imagegeneration, image editing, Magic Layers, translation, Assistant, photo@@ -100,7 +124,11 @@ search). A switched-off feature:**Test connection** — one minimal chat completion (thinking disabled,one-word reply, 15 s circuit breaker), rate-limited to one probe per-10 s. It is the only console action that spends provider quota.+10 s. It is the only console action that spends provider quota. Each+provider row has its own Test button; the fallback card tests the+resolved text slot. The probe goes through the SDK constructor with the+resolved `{ baseUrl, apiKey }` — never `ZAI.create()`, whose file-only+lookup ignored env vars and broke every test since A1 (see D3).### Settings@@ -115,6 +143,8 @@ one-word reply, 15 s circuit breaker), rate-limited to one probe per## 3. Traffic & activity recording — the model+**Durable** (the charts):+- One `TrafficStat` row per **(UTC day, route template, method,status)**, incremented fire-and-forget by the `withLogging` wrapper.**Counts only** — no ids, no IPs, no query strings (the same stance as@@ -132,12 +162,30 @@ one-word reply, 15 s circuit breaker), rate-limited to one probe pertarget) is exact. Improving this needs `waitUntil` plumbing throughevery route — deliberately out of scope for A1.-Config reads (feature switches, settings, provider) are cached+Config reads (feature switches, settings, provider table) are cachedin-process for **10 s** and invalidated on write — one tiny indexed`findMany` per window per instance. A failed config read falls back todefaults (= pre-A1 behaviour): these toggles are additive restrictionsand a flapping read must not brick design autosave.+**Live** (v0.16.2 A2, the “Live traffic” panel): an in-memory rolling+window recorded by the same `withLogging` wrapper — per-second+request/error buckets (last 60 s shown), per-route per-minute hits,+hashed visitor keys and a latency ring, all capped and swept (see+`src/lib/admin/realtime.ts`). Semantics worth knowing:++- **process-local** — counters reset on restart; TrafficStat/AIUsage+ remain the durable record,+- **single process** — each Node process counts its own requests (the+ self-hosted standalone deploy is one process),+- the panel polls `GET /api/admin/realtime` every 2 s and **that poll+ is excluded** from the live counters (the dashboard must not become+ its own top route); it is still counted in the durable tables,+- visitors are counted through a per-boot salted hash of the client IP+ — a count key, not an identity; raw IPs are never stored anywhere,+- `CANVIX_TRAFFIC=0` disables live recording together with the durable+ counters.+## 4. API surface (for scripts)All `/api/admin/*` routes re-check the session independently of the UI@@ -145,16 +193,37 @@ All `/api/admin/*` routes re-check the session independently of the UI```GET /api/admin/overview — everything the Overview page shows+GET /api/admin/realtime — live counters (polled every 2 s)GET /api/admin/users?q=&page= — directory + per-user aggregatesPOST /api/admin/users/<id>/role — { role: "admin" | "user" }POST /api/admin/users/<id>/sessions — revoke all sessions of one user-GET /api/admin/config — sanitized config (masked key)-PUT /api/admin/config — { provider?|models?|features?|settings? }+GET /api/admin/config — sanitized config (masked keys)+PUT /api/admin/config — { provider? | providers? | models? | features? | settings? | importLegacyProvider? }POST /api/admin/config/ai-test — live provider probe (1 / 10 s)```-`PUT` accepts any subset of the four sections; `features` and `settings`-merge over current values, `models` replaces, `provider` follows §2.+`PUT` accepts any subset of the sections; `features` and `settings`+merge over current values, `models` replaces, `provider` follows §2,+`providers` full-replaces the table:++```jsonc+{+ "providers": {+ "list": [+ { "id": "pnvidia", "label": "NVIDIA NIM", "baseUrl": "https://integrate.api.nvidia.com/v1" },+ { "label": "Z.ai", "baseUrl": "https://api.z.ai/v1", "apiKey": "sk-…" }+ ],+ "slots": { "text": { "providerId": "pnvidia", "model": "meta/llama-3.1-70b-instruct" }, "image": null }+ }+}+```++Ids are optional on input (generated server-side); an omitted `apiKey`+keeps the stored key for that id; `providers: null` clears the table.+`importLegacyProvider: true` folds the A1 single override into the table.++`ai-test` body: `{}` probes the resolved text slot; `{ providerId }`+probes that provider; `model` overrides the model for the probe.## 5. Dependency & design decisions — on record@@ -166,12 +235,16 @@ merge over current values, `models` replaces, `provider` follows §2.- **D2 — admin resolution is DB role OR env list.** Fail-closed bothways; no implicit first-user admin; the env list doubles as thelockout recovery path.-- **D3 — provider injection via `process.env`.** `ZAI.create()` takes- no arguments and resolves its own config from env/file (verified- against the SDK typings). A console-set provider is therefore- injected into `process.env.ZAI_BASE_URL`/`ZAI_API_KEY` before- instantiation — server-side, in-memory, the exact variables the- documented env setup uses.+- **D3 — provider clients are constructed directly (A2 correction).**+ A1 injected console providers into `process.env.ZAI_*` before+ `ZAI.create()`, believing the SDK resolved env vars. It does not —+ `loadConfig()` only reads `.z-ai-config` files, so every+ console/env-configured provider failed instantiation with+ "Configuration file not found or invalid" (the root cause behind+ every failed Test connection on canvix.app). The SDK class+ constructor takes exactly `{ baseUrl, apiKey }`; `makeClient()`+ (src/lib/ai/provider.ts) now constructs it directly with the resolved+ config. The env-injection path is gone.- **D4 — API keys are write-only.** Stored in `AppConfig`, returnedonly as `maskApiKey()` output; GET responses never contain a fullkey (unit-tested).@@ -192,6 +265,20 @@ merge over current values, `models` replaces, `provider` follows §2.other specs honor.- **D10 — self-role-change is refused** (`SELF_ROLE_CHANGE`), so theconsole cannot be used to lock out its only operator.+- **D11 — per-slot provider resolution (A2).** The multi-provider+ table lives in the existing `AppConfig` JSON store (`ai.providers`) —+ **no schema change, no new migration**. Slots that reference a+ deleted provider fall through to the legacy chain instead of failing+ the feature (fail-open, the same stance as D6).+- **D12 — real-time counters are a zero-import in-memory module (A2).**+ `src/lib/admin/realtime.ts` imports nothing — so linking it statically+ into the stdlib-only observability module cannot repeat the v0.16.1+ edge-bundle regression — and every structure is hard-capped and+ swept (bounded memory by construction).+- **D13 — the live panel's own poll is not counted live (A2).** The+ 2-second `/api/admin/realtime` poll is excluded from the in-memory+ counters so the dashboard's refresh never dominates the “top routes”+ view; it is still recorded in the durable tables.## 6. Database changes (migration `0009_admin_console`)@@ -202,4 +289,6 @@ CREATE TABLE "TrafficStat" (… UNIQUE(day, route, method, status));CREATE TABLE "DailyActive" (… UNIQUE(day, actor));```-`npm run db:setup` applies it; nothing else changes.+`npm run db:setup` applies it; nothing else changes. **A2 adds no+migration** — the multi-provider table is one more `AppConfig` row+(`ai.providers`), and live traffic keeps no database state at all.diff --git a/package.json b/package.jsonindex 7cf0a95..276581f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.16.1",+ "version": "0.16.2","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/app/api/admin/config/ai-test/route.ts b/src/app/api/admin/config/ai-test/route.tsindex 3558c9d..20ad2cb 100644--- a/src/app/api/admin/config/ai-test/route.ts+++ b/src/app/api/admin/config/ai-test/route.ts@@ -1,6 +1,7 @@import { NextRequest, NextResponse } from 'next/server'import { requireAdmin } from '@/lib/admin/guard'-import { resolveProvider, getZAI, getTextModel, rateLimit } from '@/lib/ai/provider'+import { getProviders, AI_SLOTS } from '@/lib/admin/config'+import { resolveSlot, makeClient, rateLimit, type ResolvedSlot } from '@/lib/ai/provider'import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'import { withLogging } from '@/lib/observability'@@ -12,9 +13,79 @@ export const dynamic = 'force-dynamic'// 15 s circuit breaker. Admin-only and rate-limited to one probe per 10 s// — it is the one console action that spends real provider quota, and it// must never become a proxy for chatty automation.+//+// v0.16.2 (A2) body:+// {} — test the resolved TEXT slot+// (multi table → legacy → env → file)+// { providerId: "p1…" } — test that provider of the table+// { providerId?, model: "some-model" } — override the model for this probe+//+// The test always goes through the SDK constructor with the resolved+// { baseUrl, apiKey } — never ZAI.create(), whose file-only config+// lookup was the bug behind every failed test since A1 (see+// src/lib/ai/provider.ts, makeClient).const TEST_TIMEOUT_MS = 15_000+interface TestTarget {+ baseUrl: string+ apiKey: string+ model?: string+ label: string+ source: string+}++async function resolveTarget(body: Record<string, unknown>): Promise<+ { ok: true; target: TestTarget } | { ok: false; res: NextResponse }+> {+ const modelOverride = typeof body.model === 'string' && body.model.trim() ? body.model.trim() : null+ const providerId = typeof body.providerId === 'string' && body.providerId.trim() ? body.providerId.trim() : null++ if (providerId) {+ const table = await getProviders()+ const entry = table?.providers.find((p) => p.id === providerId)+ if (!entry) {+ return {+ ok: false,+ res: NextResponse.json({ ok: false, error: 'Unknown provider id — save the provider first.' }, { status: 400 }),+ }+ }+ // default the probe to the model some slot already pins to this provider+ let model = modelOverride ?? undefined+ if (!model && table) {+ for (const slot of AI_SLOTS) {+ const s = table.slots[slot]+ if (s && s.providerId === providerId && s.model) {+ model = s.model+ break+ }+ }+ }+ return { ok: true, target: { baseUrl: entry.baseUrl, apiKey: entry.apiKey, model, label: entry.label, source: 'multi' } }+ }++ const resolved: ResolvedSlot | null = await resolveSlot('text')+ if (!resolved) {+ return {+ ok: false,+ res: NextResponse.json(+ { ok: false, error: 'No AI provider is configured — add one on this page or set ZAI_BASE_URL/ZAI_API_KEY.' },+ { status: 503 }+ ),+ }+ }+ return {+ ok: true,+ target: {+ baseUrl: resolved.baseUrl,+ apiKey: resolved.apiKey,+ model: modelOverride ?? resolved.model,+ label: resolved.label ?? resolved.source,+ source: resolved.source,+ },+ }+}+async function __canvix_post(req: NextRequest) {if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })const guard = await requireAdmin(req)@@ -28,18 +99,13 @@ async function __canvix_post(req: NextRequest) {)}- const provider = await resolveProvider()- if (!provider) {- return NextResponse.json(- { ok: false, error: 'No AI provider is configured — set one on this page or via ZAI_BASE_URL/ZAI_API_KEY.' },- { status: 503 }- )- }+ const body = (await req.json().catch(() => ({}))) as Record<string, unknown>+ const target = await resolveTarget(body)+ if (!target.ok) return target.restry {- const zai = await getZAI()- if (!zai) return NextResponse.json({ ok: false, error: 'Provider initialization failed.' }, { status: 502 })- const model = await getTextModel()+ const zai = await makeClient(target.target.baseUrl, target.target.apiKey)+ const model = target.target.modelconst completion = await Promise.race([zai.chat.completions.create({...(model ? { model } : {}),@@ -55,7 +121,8 @@ async function __canvix_post(req: NextRequest) {).slice(0, 120)return NextResponse.json({ok: true,- source: provider.source,+ source: target.target.source,+ providerLabel: target.target.label,model: model ?? 'sdk-default',reply: reply || '(empty reply)',})diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.tsindex 579ff0d..86e7e7e 100644--- a/src/app/api/admin/config/route.ts+++ b/src/app/api/admin/config/route.ts@@ -5,18 +5,26 @@ import {getFeatures,getSettings,getProviderOverride,+ getProviders,setProvider,clearProvider,setModels,setFeatures,setSettings,+ setProviders,+ clearProviders,+ importLegacyProvider,validateProvider,validateModels,validateFeatures,validateSettings,+ validateProviderList,+ validateSlots,maskApiKey,+ type StoredProviderEntry,+ type AiSlot,} from '@/lib/admin/config'-import { resolveProvider } from '@/lib/ai/provider'+import { resolveProvider, resolveSlot, type ResolvedSlot } from '@/lib/ai/provider'import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'import { withLogging } from '@/lib/observability'@@ -25,20 +33,50 @@ export const dynamic = 'force-dynamic'// GET/PUT /api/admin/config — the console's configuration surface.//-// GET is sanitized by construction: the stored API key only ever comes-// back as a mask, env vars as presence booleans, and the effective base-// URL (whatever layer it came from) — enough to operate on, never a-// credential. PUT validates section by section and returns the same+// GET is sanitized by construction: stored API keys only ever come+// back as masks, env vars as presence booleans, and effective base+// URLs (whatever layer they came from) — enough to operate on, never+// a credential. PUT validates section by section and returns the same// sanitized shape back.+//+// v0.16.2 (A2) adds the multi-provider sections:+// providers { list: […], slots: {…} } | null — full replace /+// clear of the ai.providers table+// importLegacyProvider: true — fold the A1 single override into the+// table and clear the legacy row++const SLOT_ORDER: AiSlot[] = ['text', 'vision', 'image', 'imageEdit', 'imageSearch']++function slotView(resolved: ResolvedSlot | null) {+ if (!resolved) return null+ return {+ providerId: resolved.providerId ?? null,+ label: resolved.label ?? null,+ baseUrl: resolved.baseUrl,+ model: resolved.model ?? null,+ source: resolved.source,+ }+}async function sanitizedView() {- const [provider, stored, models, features, settings] = await Promise.all([+ const [provider, stored, providers, models, features, settings] = await Promise.all([resolveProvider(),getProviderOverride(),+ getProviders(),getModels(),getFeatures(),getSettings(),])+ // per-slot resolution (multi table → legacy chain) for the slots card+ const resolved = {} as Record<AiSlot, ReturnType<typeof slotView>>+ await Promise.all(+ SLOT_ORDER.map(async (slot) => {+ resolved[slot] = slotView(await resolveSlot(slot))+ })+ )+ const list: { id: string; label: string; baseUrl: string; keyMasked: string }[] = (providers?.providers ?? []).map(+ (p: StoredProviderEntry) => ({ id: p.id, label: p.label, baseUrl: p.baseUrl, keyMasked: maskApiKey(p.apiKey) })+ )return {provider: {configured: provider !== null,@@ -50,6 +88,13 @@ async function sanitizedView() {keySet: Boolean(process.env.ZAI_API_KEY?.trim()),},},+ providers: {+ // the multi-provider table — null when nothing is stored yet+ set: providers !== null,+ list,+ slots: providers?.slots ?? {},+ resolved,+ },models,features,settings,@@ -75,11 +120,12 @@ async function __canvix_put(req: NextRequest) {try {const body = (await req.json().catch(() => ({}))) as Record<string, unknown>- // ── provider section ────────────────────────────────────────+ // ── provider section (legacy single override, v0.16 A1) ────// null clears the override (fall back to env/file). An object sets// it: both fields together activate, both empty clears, half-empty// is a 400 — the operator always gets an explicit error instead of- // a silently half-configured provider.+ // a silently half-configured provider. Superseded per-slot by the+ // providers table below, kept for compat and env/file management.if (body.provider !== undefined) {if (body.provider === null) {await clearProvider()@@ -104,6 +150,36 @@ async function __canvix_put(req: NextRequest) {}}+ // ── providers section (multi-provider table, v0.16.2 A2) ───+ // Full replace: { list: [{id?, label, baseUrl, apiKey?}], slots:+ // { slot: {providerId, model?} | null } }. Keys are write-only —+ // an entry whose apiKey is empty keeps its stored key (matched by+ // id). null clears the whole table (slots fall back to the legacy+ // chain above).+ if (body.providers !== undefined) {+ if (body.providers === null) {+ await clearProviders()+ } else if (typeof body.providers === 'object' && body.providers !== null && !Array.isArray(body.providers)) {+ const raw = body.providers as Record<string, unknown>+ const current = await getProviders()+ const existing = new Map<string, StoredProviderEntry>((current?.providers ?? []).map((p) => [p.id, p]))+ const listCheck = validateProviderList(raw.list, { existing })+ if (!listCheck.ok) return NextResponse.json({ error: listCheck.error }, { status: 400 })+ const ids = new Set(listCheck.value.map((p) => p.id))+ const slotsCheck = validateSlots(raw.slots, ids)+ if (!slotsCheck.ok) return NextResponse.json({ error: slotsCheck.error }, { status: 400 })+ await setProviders({ providers: listCheck.value, slots: slotsCheck.value })+ } else {+ return NextResponse.json({ error: 'providers must be an object ({ list, slots }) or null.' }, { status: 400 })+ }+ }++ // ── importLegacyProvider (one-click migration, A2) ─────────+ if (body.importLegacyProvider === true) {+ const result = await importLegacyProvider()+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: 400 })+ }+// ── models section (full replace) ───────────────────────────if (body.models !== undefined) {const check = validateModels(body.models)diff --git a/src/app/api/admin/overview/route.ts b/src/app/api/admin/overview/route.tsindex 022f96a..9ac0e15 100644--- a/src/app/api/admin/overview/route.ts+++ b/src/app/api/admin/overview/route.ts@@ -1,7 +1,7 @@import { NextRequest, NextResponse } from 'next/server'import { db } from '@/lib/db'import { requireAdmin, isAdminUser, adminSource } from '@/lib/admin/guard'-import { resolveProvider } from '@/lib/ai/provider'+import { providersSummary } from '@/lib/ai/provider'import { fillDays, sumSeries, dayKey, type DayPoint } from '@/lib/admin/series'import { APP_VERSION, withLogging } from '@/lib/observability'@@ -86,7 +86,7 @@ async function __canvix_get(req: NextRequest) {take: 10,select: { id: true, username: true, role: true, createdAt: true },}),- resolveProvider(),+ providersSummary(),])const dbLatencyMs = Date.now() - probeStart@@ -131,7 +131,12 @@ async function __canvix_get(req: NextRequest) {admin: isAdminUser(u),adminSource: adminSource(u),})),- provider: { configured: provider !== null, source: provider?.source ?? null },+ provider: {+ configured: provider.configured,+ source: provider.source,+ providerCount: provider.providerCount,+ slotsSet: provider.slotsSet,+ },})} catch (error) {console.error('GET /api/admin/overview failed', error)diff --git a/src/app/api/admin/realtime/route.ts b/src/app/api/admin/realtime/route.tsnew file mode 100644index 0000000..8c63075--- /dev/null+++ b/src/app/api/admin/realtime/route.ts@@ -0,0 +1,29 @@+import { NextRequest, NextResponse } from 'next/server'+import { requireAdmin } from '@/lib/admin/guard'+import { liveSnapshot } from '@/lib/admin/realtime'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++// GET /api/admin/realtime — the console's live traffic panel (v0.16.2 A2).+//+// Reads the in-memory rolling counters recorded by withLogging on every+// API request: per-second request/error buckets (last 60 s), 5-minute+// request/error/visitor/AI totals, a latency ring (p50/p95) and the+// top routes of the window. Aggregate counts only — the same no-ids/+// no-IPs/no-query-strings stance as /api/health?v=2; visitors are+// counted through per-boot salted hashes, never the IP itself.+//+// The panel polls this every 2 s; the poll is excluded from the live+// counters themselves (see observability.ts) so the dashboard never+// becomes its own top route. Counters are process-local and reset on+// restart — TrafficStat/AIUsage remain the durable record.++async function __canvix_get(req: NextRequest) {+ const guard = await requireAdmin(req)+ if (!guard.ok) return guard.res+ return NextResponse.json(liveSnapshot())+}++export const GET = withLogging('GET /api/admin/realtime', __canvix_get)diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.tsindex 8e71d67..e682417 100644--- a/src/app/api/ai/assistant/route.ts+++ b/src/app/api/ai/assistant/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getTextModel } from '@/lib/ai/provider'+import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -229,7 +229,7 @@ async function __canvix_post(req: NextRequest) {const message = (body.message ?? '').trim().slice(0, 1500)if (!message) return NextResponse.json({ error: 'A message is required.' }, { status: 400 })- return withProvider('assistant', req, { limit: 20, windowSec: 60 }, async (zai) => {+ return withProvider('assistant', req, { limit: 20, windowSec: 60 }, async (ctx) => {const d = body.design ?? {}const els = (d.elements ?? []).slice(0, 80)const elementSummary = els@@ -294,8 +294,8 @@ async function __canvix_post(req: NextRequest) {.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string').map((m) => ({ role: m.role, content: m.content.slice(0, 1000) }))- const completion = await zai.chat.completions.create({- model: await getTextModel(),+ const completion = await ctx.zai.chat.completions.create({+ model: ctx.model,messages: [{ role: 'assistant', content: system },{ role: 'assistant', content: `Current design context:\n${designContext}` },diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsindex 97e1966..030848b 100644--- a/src/app/api/ai/capabilities/route.ts+++ b/src/app/api/ai/capabilities/route.ts@@ -1,5 +1,5 @@import { NextResponse } from 'next/server'-import { hasProvider } from '@/lib/ai/provider'+import { hasProviderForSlot } from '@/lib/ai/provider'import { getFeatures } from '@/lib/admin/config'import { withLogging } from '@/lib/observability'@@ -14,20 +14,30 @@ export const dynamic = 'force-dynamic'*/async function __canvix_get() {// v0.16 (A1): a capability is available when a provider answers AND- // the admin console has not switched the feature off. Still booleans+ // the admin console has not switched the feature off. v0.16.2 (A2):+ // the provider check is per capability SLOT — with the multi-provider+ // table you can wire text to one vendor and images to another, so+ // "a provider exists" is no longer a single boolean. Still booleans// only — never config, never keys, never which layer answered.- const configured = await hasProvider()+ const [text, vision, image, imageEdit, imageSearch] = await Promise.all([+ hasProviderForSlot('text'),+ hasProviderForSlot('vision'),+ hasProviderForSlot('image'),+ hasProviderForSlot('imageEdit'),+ hasProviderForSlot('imageSearch'),+ ])+ const configured = text || vision || image || imageEdit || imageSearchconst flags = await getFeatures()return NextResponse.json({configured,capabilities: {- magicWrite: configured && flags.magicWrite,- imageGeneration: configured && flags.imageGeneration,- imageEditing: configured && flags.imageEditing,- vision: configured && flags.vision, // Magic Layers- translation: configured && flags.translation,- assistant: configured && flags.assistant,- photoSearch: configured && flags.photoSearch,+ magicWrite: text && flags.magicWrite,+ imageGeneration: image && flags.imageGeneration,+ imageEditing: imageEdit && flags.imageEditing,+ vision: vision && flags.vision, // Magic Layers+ translation: text && flags.translation,+ assistant: text && flags.assistant,+ photoSearch: imageSearch && flags.photoSearch,backgroundRemoval: true, // local ONNX — always availablecolorPalette: true, // local deterministiclayoutSuggestions: true, // local deterministicdiff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.tsindex 421982c..c206d80 100644--- a/src/app/api/ai/image-edit/route.ts+++ b/src/app/api/ai/image-edit/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getImageModel } from '@/lib/ai/provider'+import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -71,15 +71,15 @@ async function __canvix_post(req: NextRequest) {const h = Number(body.naturalHeight) || 0const size: ImgSize = w && h ? bestSize(w, h) : '1024x1024'- return withProvider('image-edit', req, { limit: 5, windowSec: 60 }, async (zai) => {+ return withProvider('image-edit', req, { limit: 5, windowSec: 60 }, async (ctx) => {// NOTE: the SDK's TS type declares `image`, but the backend API requires// `images: [{ url }]` (verified — API error 1210 "must provide images").// The SDK forwards the body verbatim, so we send the correct runtime shape.- const response = await zai.images.generations.edit({+ const response = await ctx.zai.images.generations.edit({prompt,images: [{ url: image }],size,- } as unknown as Parameters<typeof zai.images.generations.edit>[0])+ } as unknown as Parameters<typeof ctx.zai.images.generations.edit>[0])const base64 = response.data[0]?.base64if (!base64) {diff --git a/src/app/api/ai/image/image-guard.test.ts b/src/app/api/ai/image/image-guard.test.tsindex a827d1d..94923c8 100644--- a/src/app/api/ai/image/image-guard.test.ts+++ b/src/app/api/ai/image/image-guard.test.ts@@ -19,14 +19,20 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'// This sandbox (and dev machines) can carry a real /etc/.z-ai-config, which-// would make getZAI() hit the live gateway from unit tests. Mock the SDK-// module itself so the route's full happy path runs hermetically.+// would make the provider path hit the live gateway from unit tests. Mock+// the SDK module itself so the route's full happy path runs hermetically.+//+// v0.16.2 (A2): the app constructs the SDK directly (new ZAI({ baseUrl,+// apiKey }) — see makeClient in provider.ts), because ZAI.create() only+// reads a .z-ai-config file and ignores env vars. The mock is therefore+// a CLASS now, mirroring the real constructor surface.const generationsCreate = vi.fn(async () => ({ data: [{ base64: 'aGVsbG8=' }] }))vi.mock('z-ai-web-dev-sdk', () => ({- default: {- create: vi.fn(async () => ({- images: { generations: { create: generationsCreate } },- })),+ default: class MockZAI {+ images: { generations: { create: typeof generationsCreate } }+ constructor(_config: { baseUrl?: string; apiKey?: string }) {+ this.images = { generations: { create: generationsCreate } }+ }},}))diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.tsindex 5133a0d..9ba031f 100644--- a/src/app/api/ai/image/route.ts+++ b/src/app/api/ai/image/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getImageModel } from '@/lib/ai/provider'+import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -25,9 +25,9 @@ async function __canvix_post(req: NextRequest) {return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })}- return withProvider('image', req, { limit: 5, windowSec: 60 }, async (zai) => {- const response = await zai.images.generations.create({- model: await getImageModel(),+ return withProvider('image', req, { limit: 5, windowSec: 60 }, async (ctx) => {+ const response = await ctx.zai.images.generations.create({+ model: ctx.model,prompt,size,})diff --git a/src/app/api/ai/magic-layers/route.ts b/src/app/api/ai/magic-layers/route.tsindex cd34c3e..de248fa 100644--- a/src/app/api/ai/magic-layers/route.ts+++ b/src/app/api/ai/magic-layers/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getVisionModel } from '@/lib/ai/provider'+import { withProvider, DEFAULT_VISION_MODEL } from '@/lib/ai/provider'import { validateAnalysis } from '@/lib/magic-layers/validate'import { withLogging } from '@/lib/observability'@@ -30,7 +30,7 @@ async function __canvix_post(req: NextRequest) {return NextResponse.json({ error: 'Image too large — max ~6 MB after normalization.' }, { status: 413 })}- return withProvider('magic-layers', req, { limit: 10, windowSec: 60 }, async (zai) => {+ return withProvider('magic-layers', req, { limit: 10, windowSec: 60 }, async (ctx) => {const system ='You are a precise design-image analyzer for a graphic-design editor. You look at a FLAT (raster) design ' +'image and decompose it into an editable layer structure: background, text regions, photo regions, shapes ' +@@ -55,8 +55,8 @@ async function __canvix_post(req: NextRequest) {'9. If the background is a photo/illustration, use kind=photo and still list visible foreground regions.\n' +'10. notes = one short sentence about what the reconstruction will approximate (e.g. "illustration left of title will become a cropped image region").'- const completion = await zai.chat.completions.createVision({- model: await getVisionModel(),+ const completion = await ctx.zai.chat.completions.createVision({+ model: ctx.model ?? DEFAULT_VISION_MODEL,messages: [{ role: 'system', content: system },{diff --git a/src/app/api/ai/translate/route.ts b/src/app/api/ai/translate/route.tsindex 7a4cfee..b217319 100644--- a/src/app/api/ai/translate/route.ts+++ b/src/app/api/ai/translate/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getTextModel } from '@/lib/ai/provider'+import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -55,9 +55,9 @@ async function __canvix_post(req: NextRequest) {const user = `Target language: ${language}\n\nTexts:\n${numbered}\n\nRespond with a JSON array of ${texts.length} translated strings, same order.`- return withProvider('translate', req, { limit: 15, windowSec: 60 }, async (zai) => {- const completion = await zai.chat.completions.create({- model: await getTextModel(),+ return withProvider('translate', req, { limit: 15, windowSec: 60 }, async (ctx) => {+ const completion = await ctx.zai.chat.completions.create({+ model: ctx.model,messages: [{ role: 'assistant', content: system },{ role: 'user', content: user },diff --git a/src/app/api/ai/write/route.ts b/src/app/api/ai/write/route.tsindex 6db883c..7c94170 100644--- a/src/app/api/ai/write/route.ts+++ b/src/app/api/ai/write/route.ts@@ -1,5 +1,5 @@import { NextRequest, NextResponse } from 'next/server'-import { withProvider, getTextModel } from '@/lib/ai/provider'+import { withProvider } from '@/lib/ai/provider'import { withLogging } from '@/lib/observability'export const runtime = 'nodejs'@@ -31,9 +31,9 @@ async function __canvix_post(req: NextRequest) {return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })}- return withProvider('write', req, { limit: 20, windowSec: 60 }, async (zai) => {- const completion = await zai.chat.completions.create({- model: await getTextModel(),+ return withProvider('write', req, { limit: 20, windowSec: 60 }, async (ctx) => {+ const completion = await ctx.zai.chat.completions.create({+ model: ctx.model,messages: [{role: 'assistant',diff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.tsindex 3e9b577..a94b805 100644--- a/src/app/api/photos/search/route.ts+++ b/src/app/api/photos/search/route.ts@@ -17,8 +17,8 @@ async function __canvix_post(req: NextRequest) {if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)- return withProvider('search', req, { limit: 12, windowSec: 60 }, async (zai) => {- const response = await zai.images.search.create({ query, count })+ return withProvider('search', req, { limit: 12, windowSec: 60 }, async (ctx) => {+ const response = await ctx.zai.images.search.create({ query, count })const results = (response.results ?? []).map((r) => ({url: r.original_url,diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsxindex 7499d5a..c0b1c5a 100644--- a/src/components/admin/ai-config.tsx+++ b/src/components/admin/ai-config.tsx@@ -1,10 +1,40 @@'use client'+// AI configuration (v0.16 A1 → v0.16.2 A2 rework).+//+// Four surfaces:+// 1. Providers — the multi-provider table: add any OpenAI-compatible+// endpoint (NVIDIA NIM, OpenRouter, Z.ai, Groq, …), one key each,+// write-only credentials, per-provider Test button.+// 2. Model slots — pin each capability (text / vision / image /+// imageEdit / imageSearch) to a provider + model id, so different+// features can run on different vendors.+// 3. Legacy fallback — the v0.16 A1 single-provider override and model+// ids, used only by slots that don't resolve through the table.+// 4. Feature kill switches.+import { useEffect, useState } from 'react'-import { Zap } from 'lucide-react'+import { Zap, Plus, Trash2, Import } from 'lucide-react'import { getJson, sendJson } from './fetch'import { Card, Toggle, Chip } from './bits'+interface ProviderEntryView {+ id: string+ label: string+ baseUrl: string+ keyMasked: string+}+interface SlotEntryView {+ providerId: string+ model?: string+}+interface SlotResolved {+ providerId: string | null+ label: string | null+ baseUrl: string+ model: string | null+ source: string+}interface ConfigView {provider: {configured: boolean@@ -13,11 +43,40 @@ interface ConfigView {stored: { baseUrl: string; keyMasked: string } | nullenv: { urlSet: boolean; keySet: boolean }}+ providers: {+ set: boolean+ list: ProviderEntryView[]+ slots: Record<string, SlotEntryView | undefined>+ resolved: Record<string, SlotResolved | null>+ }models: { text?: string; vision?: string; image?: string }features: Record<string, boolean>settings: { signupsOpen: boolean; anonymousEditing: boolean }}+/** Local editing state for one provider row. New rows get a client-generated+ * id so slots can reference them in the same save (the server accepts any+ * `p`-prefixed id and keeps it). */+interface ProviderRow {+ id: string | null // null = new, unsaved+ label: string+ baseUrl: string+ apiKey: string // empty = keep stored key on save+}++/** `p` + 10 base36 chars — same shape the server generates. */+function newProviderId(): string {+ return 'p' + Array.from({ length: 10 }, () => Math.floor(Math.random() * 36).toString(36)).join('')+}++const SLOT_INFO: { key: string; label: string; hint: string; placeholder: string }[] = [+ { key: 'text', label: 'Text', hint: 'Magic Write · Translate · Assistant', placeholder: 'e.g. meta/llama-3.1-70b-instruct' },+ { key: 'vision', label: 'Vision', hint: 'Magic Layers — image understanding', placeholder: 'e.g. meta/llama-3.2-90b-vision-instruct' },+ { key: 'image', label: 'Image generation', hint: 'Text-to-image in the Photos panel', placeholder: 'provider default' },+ { key: 'imageEdit', label: 'Image editing', hint: 'Magic Eraser / Enhance', placeholder: 'provider default' },+ { key: 'imageSearch', label: 'Photo search', hint: 'Stock photo search', placeholder: 'provider default' },+]+const FEATURE_INFO: { key: string; label: string; hint: string }[] = [{ key: 'magicWrite', label: 'Magic Write', hint: 'AI copy suggestions in the text toolbar' },{ key: 'imageGeneration', label: 'Image generation', hint: 'Text-to-image in the Photos panel' },@@ -28,37 +87,57 @@ const FEATURE_INFO: { key: string; label: string; hint: string }[] = [{ key: 'photoSearch', label: 'Photo search', hint: 'Stock photo search in the Photos panel' },]-const SOURCE_LABEL: Record<string, string> = { db: 'console override', env: 'environment variables', file: '.z-ai-config file' }+const SOURCE_LABEL: Record<string, string> = {+ multi: 'providers table',+ db: 'legacy override',+ env: 'environment variables',+ file: '.z-ai-config file',+}++interface TestState {+ providerId: string | 'default'+ ok: boolean+ message: string+}export function AdminAiConfig() {const [view, setView] = useState<ConfigView | null>(null)const [error, setError] = useState<string | null>(null)const [notice, setNotice] = useState<string | null>(null)+ const [rows, setRows] = useState<ProviderRow[]>([])+ const [slots, setSlots] = useState<Record<string, { providerId: string; model: string }>>({})const [baseUrl, setBaseUrl] = useState('')const [apiKey, setApiKey] = useState('')const [models, setModels] = useState<{ text: string; vision: string; image: string }>({ text: '', vision: '', image: '' })const [features, setFeatures] = useState<Record<string, boolean>>({})const [busy, setBusy] = useState(false)- const [test, setTest] = useState<{ ok: boolean; message: string } | null>(null)+ const [test, setTest] = useState<TestState | null>(null)- useEffect(() => {- getJson<ConfigView>('/api/admin/config').then((res) => {- if (res.ok) {- setView(res.data)- setBaseUrl(res.data.provider.stored?.baseUrl ?? '')- setModels({- text: res.data.models.text ?? '',- vision: res.data.models.vision ?? '',- image: res.data.models.image ?? '',- })- setFeatures(res.data.features)- setError(null)- } else {- setError(res.data?.error ?? `Request failed (${res.status})`)- }+ function applyView(data: ConfigView) {+ setView(data)+ setRows(+ data.providers.list.map((p) => ({+ id: p.id,+ label: p.label,+ baseUrl: p.baseUrl,+ apiKey: '', // write-only: never prefilled+ }))+ )+ const slotState: Record<string, { providerId: string; model: string }> = {}+ for (const s of SLOT_INFO) {+ const stored = data.providers.slots[s.key]+ slotState[s.key] = { providerId: stored?.providerId ?? '', model: stored?.model ?? '' }+ }+ setSlots(slotState)+ setBaseUrl(data.provider.stored?.baseUrl ?? '')+ setModels({+ text: data.models.text ?? '',+ vision: data.models.vision ?? '',+ image: data.models.image ?? '',})- }, [])+ setFeatures(data.features)+ }async function put(body: unknown, message: string) {setBusy(true)@@ -71,23 +150,62 @@ export function AdminAiConfig() {}setError(null)setNotice(message)- setView(res.data)+ applyView(res.data)setApiKey('')setTimeout(() => setNotice(null), 4000)}- async function testProvider() {+ /** Save the providers table (list full-replace + slots full-replace). */+ async function saveProviders() {+ const list = rows.map((r) => ({+ ...(r.id ? { id: r.id } : {}),+ label: r.label,+ baseUrl: r.baseUrl,+ ...(r.apiKey ? { apiKey: r.apiKey } : {}),+ }))+ const slotBody: Record<string, { providerId: string; model?: string } | null> = {}+ for (const s of SLOT_INFO) {+ const cur = slots[s.key]+ slotBody[s.key] = cur.providerId ? { providerId: cur.providerId, ...(cur.model ? { model: cur.model } : {}) } : null+ }+ await put({ providers: { list, slots: slotBody } }, 'Providers and slots saved.')+ }++ async function importLegacy() {+ await put({ importLegacyProvider: true }, 'Legacy override imported into the providers table.')+ }++ async function testProvider(providerId: string | null) {setBusy(true)setTest(null)- const res = await sendJson<{ ok: boolean; model?: string; reply?: string; error?: string }>('/api/admin/config/ai-test', 'POST', {})+ const res = await sendJson<{ ok: boolean; providerLabel?: string; model?: string; reply?: string; error?: string }>(+ '/api/admin/config/ai-test',+ 'POST',+ providerId ? { providerId } : {}+ )setBusy(false)if (res.ok && res.data.ok) {- setTest({ ok: true, message: `Provider answered (model ${res.data.model}): “${res.data.reply}”` })+ setTest({+ providerId: providerId ?? 'default',+ ok: true,+ message: `${res.data.providerLabel ?? 'Provider'} answered (model ${res.data.model}): “${res.data.reply}”`,+ })} else {- setTest({ ok: false, message: (res.data.error as string) ?? `Test failed (${res.status})` })+ setTest({ providerId: providerId ?? 'default', ok: false, message: (res.data.error as string) ?? `Test failed (${res.status})` })}}+ useEffect(() => {+ getJson<ConfigView>('/api/admin/config').then((res) => {+ if (res.ok) {+ applyView(res.data)+ setError(null)+ } else {+ setError(res.data?.error ?? `Request failed (${res.status})`)+ }+ })+ }, [])+if (error && !view) {return (<Card title="AI configuration">@@ -100,6 +218,8 @@ export function AdminAiConfig() {}const providerSectionReady = Boolean(baseUrl.trim()) === Boolean(apiKey.trim()) || (!baseUrl && !apiKey)+ const legacyStored = view.provider.stored !== null+ const tableEmpty = rows.length === 0return (<>@@ -107,20 +227,214 @@ export function AdminAiConfig() {{notice && <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-700">{notice}</div>}<Card- title="AI provider"+ title="AI providers"+ right={+ view.providers.set && rows.length > 0 ? (+ <Chip tone="good">{rows.length} stored</Chip>+ ) : (+ <Chip tone={tableEmpty && !legacyStored && !view.provider.configured ? 'bad' : 'neutral'}>empty</Chip>+ )+ }+ >+ <p className="mb-4 text-sm text-muted-foreground">+ Add any OpenAI-compatible endpoint — NVIDIA NIM, OpenRouter, Z.ai, Groq, OpenAI… Each provider keeps its own+ write-only key, and every capability below can run on a different vendor. The key is stored, never displayed+ again; leave the field empty when editing to keep the stored one.+ </p>++ {legacyStored && (+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm">+ <span>+ A legacy single-provider override is stored ({view.provider.stored?.baseUrl}). It only answers slots that+ have no provider above — import it to manage it here.+ </span>+ <button+ onClick={() => void importLegacy()}+ disabled={busy}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-amber-600/40 bg-amber-500/20 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-500/30 disabled:opacity-50"+ >+ <Import size={14} /> Import into providers+ </button>+ </div>+ )}++ {rows.length === 0 && (+ <p className="mb-4 rounded-xl border border-dashed p-4 text-sm text-muted-foreground">+ No providers yet. Add one below — you need its base URL (ending in <code className="rounded bg-muted px-1">/v1</code>{' '}+ for most vendors) and an API key.+ </p>+ )}++ <div className="space-y-3">+ {rows.map((row, i) => {+ const usedBy = SLOT_INFO.filter((s) => slots[s.key]?.providerId === row.id).map((s) => s.label)+ const saved = view.providers.list.some((p) => p.id === row.id)+ return (+ <div key={row.id ?? `new-${i}`} className="rounded-xl border p-3">+ <div className="grid gap-2 sm:grid-cols-[1fr_2fr_1fr_auto]">+ <label className="text-xs">+ <span className="mb-1 block font-medium">Label</span>+ <input+ value={row.label}+ onChange={(e) => setRows((rs) => rs.map((r, j) => (j === i ? { ...r, label: e.target.value } : r)))}+ placeholder="NVIDIA NIM"+ className="h-9 w-full rounded-lg border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring"+ />+ </label>+ <label className="text-xs">+ <span className="mb-1 block font-medium">Base URL</span>+ <input+ value={row.baseUrl}+ onChange={(e) => setRows((rs) => rs.map((r, j) => (j === i ? { ...r, baseUrl: e.target.value } : r)))}+ placeholder="https://integrate.api.nvidia.com/v1"+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"+ />+ </label>+ <label className="text-xs">+ <span className="mb-1 block font-medium">API key</span>+ <input+ type="password"+ value={row.apiKey}+ onChange={(e) => setRows((rs) => rs.map((r, j) => (j === i ? { ...r, apiKey: e.target.value } : r)))}+ placeholder={saved ? `stored: ${view.providers.list.find((p) => p.id === row.id)?.keyMasked ?? '—'}` : 'new key — required'}+ autoComplete="off"+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"+ />+ </label>+ <div className="flex items-end gap-1.5">+ <button+ onClick={() => void testProvider(row.id)}+ disabled={busy || !saved}+ title={saved ? 'Send a minimal chat completion through this provider' : 'Save first, then test'}+ className="inline-flex h-9 items-center gap-1.5 rounded-lg border px-3 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50"+ >+ <Zap size={14} /> Test+ </button>+ <button+ onClick={() => setRows((rs) => rs.filter((_, j) => j !== i))}+ disabled={busy}+ title="Remove this provider (saved on Save)"+ className="inline-flex h-9 items-center rounded-lg border px-2.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-50"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ {row.id && usedBy.length > 0 && (+ <p className="mt-2 text-xs text-muted-foreground">+ {saved ? `serves: ${usedBy.join(' · ')}` : 'unsaved — press “Save providers & slots” to activate'}+ </p>+ )}+ {test && (test.providerId === row.id) && (+ <p className={`mt-2 text-sm ${test.ok ? 'text-emerald-600' : 'text-destructive'}`}>{test.message}</p>+ )}+ </div>+ )+ })}+ </div>++ <div className="mt-3 flex flex-wrap gap-2">+ <button+ onClick={() => setRows((rs) => [...rs, { id: newProviderId(), label: '', baseUrl: '', apiKey: '' }])}+ disabled={busy || rows.length >= 8}+ className="inline-flex items-center gap-1.5 rounded-lg border px-3.5 py-1.5 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50"+ >+ <Plus size={14} /> Add provider+ </button>+ <button+ onClick={() => void saveProviders()}+ disabled={busy || rows.length === 0}+ className="rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"+ >+ Save providers & slots+ </button>+ </div>+ {test && test.providerId === 'default' && (+ <p className={`mt-3 text-sm ${test.ok ? 'text-emerald-600' : 'text-destructive'}`}>{test.message}</p>+ )}+ </Card>++ <Card+ title="Model slots"+ right={+ <Chip tone={Object.values(view.providers.resolved).some((r) => r !== null) ? 'good' : 'neutral'}>+ {Object.values(view.providers.resolved).filter((r) => r !== null).length}/5 wired+ </Chip>+ }+ >+ <p className="mb-4 text-sm text-muted-foreground">+ Pin each capability to a provider and model. A slot with no provider falls back to the legacy chain below —+ every feature can run on a different vendor.+ </p>+ <div className="space-y-3">+ {SLOT_INFO.map((s) => {+ const resolved = view.providers.resolved[s.key]+ const current = slots[s.key] ?? { providerId: '', model: '' }+ return (+ <div key={s.key} className="grid gap-2 rounded-xl border p-3 sm:grid-cols-[1.4fr_1fr_1.4fr]">+ <div>+ <p className="text-sm font-medium">{s.label}</p>+ <p className="text-xs text-muted-foreground">{s.hint}</p>+ </div>+ <label className="text-xs">+ <span className="mb-1 block font-medium">Provider</span>+ <select+ value={current.providerId}+ onChange={(e) => setSlots((sl) => ({ ...sl, [s.key]: { ...current, providerId: e.target.value } }))}+ className="h-9 w-full rounded-lg border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring"+ >+ <option value="">— fall back —</option>+ {rows.map((r) => (+ <option key={r.id ?? r.label} value={r.id ?? ''} disabled={!r.id}>+ {r.label || r.baseUrl || 'unsaved provider'}+ </option>+ ))}+ </select>+ </label>+ <label className="text-xs">+ <span className="mb-1 block font-medium">Model id</span>+ <input+ value={current.model}+ onChange={(e) => setSlots((sl) => ({ ...sl, [s.key]: { ...current, model: e.target.value } }))}+ placeholder={s.placeholder}+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"+ />+ <span className="mt-1 block text-[11px] text-muted-foreground">+ {resolved+ ? `→ ${resolved.label ?? resolved.baseUrl} · ${resolved.model ?? 'provider default'} (${SOURCE_LABEL[resolved.source] ?? resolved.source})`+ : '→ not configured (feature reports unavailable)'}+ </span>+ </label>+ </div>+ )+ })}+ </div>+ <button+ onClick={() => void saveProviders()}+ disabled={busy || rows.length === 0}+ className="mt-4 rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"+ >+ Save providers & slots+ </button>+ </Card>++ <Card+ title="Fallback — single provider & default models"right={view.provider.configured ? (- <Chip tone="good">configured · {SOURCE_LABEL[view.provider.source ?? ''] ?? view.provider.source}</Chip>+ <Chip tone={view.provider.source === 'db' ? 'good' : 'neutral'}>+ fallback active · {SOURCE_LABEL[view.provider.source ?? ''] ?? view.provider.source}+ </Chip>) : (- <Chip tone="bad">not configured</Chip>+ <Chip tone="bad">no fallback</Chip>)}><p className="mb-4 text-sm text-muted-foreground">- Canvix runs its AI features through one provider. An override set here wins over the{' '}+ Only used by slots set to “— fall back —” above. The single override wins over the{' '}<code className="rounded bg-muted px-1">ZAI_BASE_URL</code> /{' '}- <code className="rounded bg-muted px-1">ZAI_API_KEY</code> environment variables; clear it to fall back. The key- is write-only — it is stored, never displayed again.+ <code className="rounded bg-muted px-1">ZAI_API_KEY</code> environment variables; model ids apply to the+ matching fallback slot. Keys are write-only — stored, never displayed again.</p><div className="grid gap-3 sm:grid-cols-2"><label className="text-sm">@@ -144,71 +458,58 @@ export function AdminAiConfig() {/></label></div>+ <div className="mt-3 grid gap-3 sm:grid-cols-3">+ {(['text', 'vision', 'image'] as const).map((key) => (+ <label key={key} className="text-sm">+ <span className="mb-1 block font-medium capitalize">{key} model</span>+ <input+ value={models[key]}+ onChange={(e) => setModels((m) => ({ ...m, [key]: e.target.value }))}+ placeholder={key === 'vision' ? 'glm-4.5v (default)' : 'SDK default'}+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"+ />+ </label>+ ))}+ </div><div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><span>env: {view.provider.env.urlSet ? 'base URL set' : 'no base URL'} · {view.provider.env.keySet ? 'key set' : 'no key'}</span>- {view.provider.activeBaseUrl && <span className="break-all">active: {view.provider.activeBaseUrl}</span>}+ {view.provider.activeBaseUrl && <span className="break-all">active fallback: {view.provider.activeBaseUrl}</span>}</div><div className="mt-4 flex flex-wrap gap-2"><buttononClick={() =>baseUrl.trim() && apiKey.trim()- ? void put({ provider: { baseUrl, apiKey } }, 'Provider override saved.')- : void put({ provider: null }, 'Provider override cleared — env/file fallback restored.')+ ? void put({ provider: { baseUrl, apiKey } }, 'Fallback override saved.')+ : void put({ provider: null }, 'Fallback override cleared — env/file fallback restored.')}disabled={busy || !providerSectionReady}className="rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50">- {baseUrl.trim() && apiKey.trim() ? 'Save override' : 'Clear override'}+ {baseUrl.trim() && apiKey.trim() ? 'Save fallback override' : 'Clear fallback override'}+ </button>+ <button+ onClick={() => void put({ models }, 'Fallback models saved.')}+ disabled={busy}+ className="rounded-lg border px-3.5 py-1.5 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50"+ >+ Save fallback models</button><button- onClick={() => void testProvider()}- disabled={busy || !view.provider.configured}+ onClick={() => void testProvider(null)}+ disabled={busy}className="inline-flex items-center gap-1.5 rounded-lg border px-3.5 py-1.5 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50">- <Zap size={14} /> Test connection+ <Zap size={14} /> Test fallback (text slot)</button></div>- {test && (- <p className={`mt-3 text-sm ${test.ok ? 'text-emerald-600' : 'text-destructive'}`}>{test.message}</p>- )}- </Card>-- <Card title="Models">- <p className="mb-4 text-sm text-muted-foreground">- Which model ids the AI features request. Leave a field empty to use the SDK default — exactly the pre-console- behaviour.- </p>- <div className="grid gap-3 sm:grid-cols-3">- {(['text', 'vision', 'image'] as const).map((key) => (- <label key={key} className="text-sm">- <span className="mb-1 block font-medium capitalize">- {key} {key === 'text' && <span className="text-muted-foreground">(write · translate · assistant)</span>}- {key === 'vision' && <span className="text-muted-foreground">(Magic Layers)</span>}- </span>- <input- value={models[key]}- onChange={(e) => setModels((m) => ({ ...m, [key]: e.target.value }))}- placeholder={key === 'vision' ? 'glm-4.5v (default)' : 'SDK default'}- className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"- />- </label>- ))}- </div>- <button- onClick={() => void put({ models }, 'Models saved.')}- disabled={busy}- className="mt-4 rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"- >- Save models- </button></Card><Card title="AI features"><p className="mb-4 text-sm text-muted-foreground">Kill switches per feature. A switched-off feature reports as unavailable everywhere (panels grey out, the- capabilities endpoint says no) and its API route refuses work — even with a provider configured.+ capabilities endpoint says no) and its API route refuses work — even with providers configured.</p><ul className="divide-y">{FEATURE_INFO.map((f) => (diff --git a/src/components/admin/overview.tsx b/src/components/admin/overview.tsxindex 894f547..f10fcba 100644--- a/src/components/admin/overview.tsx+++ b/src/components/admin/overview.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'import { getJson } from './fetch'import { StatCard, Card, Chip } from './bits'import { BarChart, LineChart, HBars, fmt, fmtBytes } from './charts'+import { AdminRealtime } from './realtime'interface DayPoint {day: string@@ -30,11 +31,12 @@ interface Overview {topRoutes: { route: string; method: string; hits: number }[]aiByFeature: { feature: string; calls: number; ok: number }[]recentUsers: { id: string; username: string; role: string; createdAt: string; admin: boolean }[]- provider: { configured: boolean; source: string | null }+ provider: { configured: boolean; source: string | null; providerCount: number; slotsSet: number }}const SOURCE_LABEL: Record<string, string> = {- db: 'console',+ multi: 'providers table',+ db: 'console override',env: 'environment',file: 'config file',}@@ -79,6 +81,8 @@ export function AdminOverview() {return (<>+ <AdminRealtime />+<div className="grid grid-cols-2 gap-4 md:grid-cols-4"><StatCard label="Users" value={fmt(data.totals.users)} sub={`${data.windows.dauToday} active today`} /><StatCard label="Designs" value={fmt(data.totals.designs)} sub={`${fmt(data.totals.templates)} templates`} />@@ -92,9 +96,15 @@ export function AdminOverview() {<StatCard label="Media stored" value={fmtBytes(data.totals.mediaBytes)} sub={`${fmt(data.totals.mediaCount)} files`} /><StatCard label="Comments" value={fmt(data.totals.comments)} sub="all designs" /><StatCard- label="AI provider"- value={data.provider.configured ? 'configured' : 'none'}- sub={data.provider.configured ? `via ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}` : 'local features only'}+ label="AI providers"+ value={data.provider.configured ? (data.provider.source === 'multi' ? String(data.provider.providerCount) : 'configured') : 'none'}+ sub={+ data.provider.configured+ ? data.provider.source === 'multi'+ ? `${data.provider.slotsSet}/5 slots wired · via ${SOURCE_LABEL[data.provider.source] ?? data.provider.source}`+ : `via ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}`+ : 'local features only'+ }/></div>@@ -165,13 +175,18 @@ export function AdminOverview() {<dd className="text-right font-medium tabular-nums">{data.version}</dd><dt className="text-muted-foreground">Database latency</dt><dd className="text-right font-medium tabular-nums">{data.dbLatencyMs} ms</dd>- <dt className="text-muted-foreground">AI provider</dt>+ <dt className="text-muted-foreground">AI providers</dt><dd className="text-right font-medium">- {data.provider.configured ? `configured · ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}` : 'not configured'}+ {data.provider.configured+ ? data.provider.source === 'multi'+ ? `${data.provider.providerCount} in table · ${data.provider.slotsSet}/5 slots wired`+ : `configured · ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}`+ : 'not configured'}</dd></dl><p className="mt-4 text-xs text-muted-foreground">- Traffic counters are aggregate counts only — no ids, no IPs, no query strings. 90-day retention. Disable with{' '}+ Live counters are in-memory (reset on restart); the charts above are the durable record. Traffic counters are aggregate+ counts only — no ids, no IPs, no query strings. 90-day retention. Disable with{' '}<code className="rounded bg-muted px-1">CANVIX_TRAFFIC=0</code>.</p></Card>diff --git a/src/components/admin/realtime.tsx b/src/components/admin/realtime.tsxnew file mode 100644index 0000000..937fce6--- /dev/null+++ b/src/components/admin/realtime.tsx@@ -0,0 +1,242 @@+'use client'++// Live traffic panel (v0.16.2 A2) — polls GET /api/admin/realtime every+// 2 s and renders the in-memory rolling counters: a per-second request+// sparkline (last 60 s), 5-minute request/error/visitor/AI totals, a+// latency ring (p50/p95) and the window's top routes. Pauses itself+// when the tab is hidden (visibilitychange) so an idle dashboard stops+// polling; the panel's own poll is excluded from the counters server-+// side (see observability.ts), so the numbers shown are site traffic,+// not dashboard noise.++import { useEffect, useRef, useState } from 'react'+import { getJson } from './fetch'+import { Card, Chip } from './bits'+import { fmt } from './charts'++interface SecondPoint {+ t: number+ req: number+ err: number+}+interface RealtimeView {+ now: string+ uptimeSec: number+ seconds: SecondPoint[]+ window5m: {+ requests: number+ errors: number+ visitors: number+ p50Ms: number | null+ p95Ms: number | null+ aiCalls: number+ aiOk: number+ }+ topRoutes: { route: string; hits: number }[]+}++const POLL_MS = 2000++function fmtUptime(sec: number): string {+ if (sec < 60) return `${sec}s`+ if (sec < 3600) return `${Math.floor(sec / 60)}m ${sec % 60}s`+ const h = Math.floor(sec / 3600)+ const m = Math.floor((sec % 3600) / 60)+ return `${h}h ${m}m`+}++/** Hand-rolled per-second area sparkline — zero new dependencies. */+function Sparkline({ points }: { points: SecondPoint[] }) {+ const W = 600+ const H = 72+ const max = Math.max(1, ...points.map((p) => p.req))+ const step = W / Math.max(points.length - 1, 1)+ const y = (v: number) => H - 2 - (v / max) * (H - 6)+ const line = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)},${y(p.req).toFixed(1)}`).join(' ')+ const area = `${line} L${W},${H} L0,${H} Z`+ const errLine = points.some((p) => p.err > 0)+ ? points.map((p, i) => `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)},${y(p.err).toFixed(1)}`).join(' ')+ : null+ const last = points[points.length - 1]+ return (+ <svg+ viewBox={`0 0 ${W} ${H}`}+ preserveAspectRatio="none"+ className="w-full"+ style={{ height: H }}+ role="img"+ aria-label="requests per second, last 60 seconds"+ >+ <path d={area} fill="var(--cv-teal)" opacity={0.15} />+ <path d={line} fill="none" stroke="var(--cv-teal)" strokeWidth={1.6} vectorEffect="non-scaling-stroke" />+ {errLine && (+ <path+ d={errLine}+ fill="none"+ stroke="var(--destructive)"+ strokeWidth={1.2}+ vectorEffect="non-scaling-stroke"+ opacity={0.8}+ />+ )}+ {last && <circle cx={W} cy={y(last.req)} r={2.5} fill="var(--cv-teal)" />}+ </svg>+ )+}++export function AdminRealtime() {+ const [data, setData] = useState<RealtimeView | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [paused, setPaused] = useState(false)+ const [stale, setStale] = useState(false)+ const aliveRef = useRef(true)++ useEffect(() => {+ aliveRef.current = true+ let timer: ReturnType<typeof setTimeout>++ const tick = async () => {+ if (!aliveRef.current) return+ if (typeof document !== 'undefined' && document.hidden) {+ setPaused(true)+ timer = setTimeout(tick, POLL_MS)+ return+ }+ setPaused(false)+ try {+ const res = await getJson<RealtimeView>('/api/admin/realtime')+ if (!aliveRef.current) return+ if (res.ok) {+ setData(res.data)+ setError(null)+ setStale(false)+ } else {+ setError(res.data?.error ?? `Request failed (${res.status})`)+ setStale(true)+ }+ } catch {+ if (aliveRef.current) {+ setError('Live endpoint unreachable — retrying.')+ setStale(true)+ }+ }+ if (aliveRef.current) timer = setTimeout(tick, POLL_MS)+ }++ void tick()+ const onVisibility = () => {+ /* next tick picks the state up */+ }+ document.addEventListener('visibilitychange', onVisibility)+ return () => {+ aliveRef.current = false+ clearTimeout(timer)+ document.removeEventListener('visibilitychange', onVisibility)+ }+ }, [])++ const reqPerMin = data ? data.seconds.reduce((a, p) => a + p.req, 0) : 0+ const errPerMin = data ? data.seconds.reduce((a, p) => a + p.err, 0) : 0++ return (+ <Card+ title={+ <span className="inline-flex items-center gap-2">+ Live traffic+ <span className="relative flex h-2.5 w-2.5" aria-hidden>+ <span+ className={`absolute inline-flex h-full w-full rounded-full ${paused || stale || error ? 'bg-muted-foreground/40' : 'animate-ping bg-emerald-500/60'}`}+ />+ <span+ className={`relative inline-flex h-2.5 w-2.5 rounded-full ${paused || stale || error ? 'bg-muted-foreground/50' : 'bg-emerald-500'}`}+ />+ </span>+ </span>+ }+ right={+ data ? (+ <div className="flex items-center gap-2">+ {paused && <Chip>paused — tab hidden</Chip>}+ {stale && <Chip tone="bad">reconnecting</Chip>}+ <Chip>up {fmtUptime(data.uptimeSec)}</Chip>+ </div>+ ) : undefined+ }+ >+ {error && !data ? (+ <p className="text-sm text-destructive">{error}</p>+ ) : !data ? (+ <div className="h-24 animate-pulse rounded-xl bg-muted" />+ ) : (+ <>+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Requests / min</p>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums text-card-foreground">{fmt(reqPerMin)}</p>+ <p className="text-xs text-muted-foreground">last 60 s</p>+ </div>+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Errors / min</p>+ <p className={`mt-0.5 text-2xl font-semibold tabular-nums ${errPerMin > 0 ? 'text-destructive' : 'text-card-foreground'}`}>+ {fmt(errPerMin)}+ </p>+ <p className="text-xs text-muted-foreground">4xx + 5xx</p>+ </div>+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Active visitors</p>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums text-card-foreground">{fmt(data.window5m.visitors)}</p>+ <p className="text-xs text-muted-foreground">last 5 min</p>+ </div>+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Requests (5 min)</p>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums text-card-foreground">{fmt(data.window5m.requests)}</p>+ <p className="text-xs text-muted-foreground">+ {data.window5m.errors > 0 ? `${fmt(data.window5m.errors)} errors` : 'no errors'}+ </p>+ </div>+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Latency p50 / p95</p>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums text-card-foreground">+ {data.window5m.p50Ms !== null ? `${data.window5m.p50Ms}ms` : '—'}+ </p>+ <p className="text-xs text-muted-foreground">+ p95 {data.window5m.p95Ms !== null ? `${data.window5m.p95Ms}ms` : '—'}+ </p>+ </div>+ <div>+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">AI calls (5 min)</p>+ <p className="mt-0.5 text-2xl font-semibold tabular-nums text-card-foreground">{fmt(data.window5m.aiCalls)}</p>+ <p className="text-xs text-muted-foreground">+ {data.window5m.aiCalls > 0+ ? `${fmt(data.window5m.aiOk)} ok · ${fmt(Math.max(0, data.window5m.aiCalls - data.window5m.aiOk))} failed`+ : 'recent requests'}+ </p>+ </div>+ </div>++ <div className="mt-4">+ <Sparkline points={data.seconds} />+ <p className="mt-1 text-xs text-muted-foreground">+ requests per second — teal = requests, red = errors (peak {fmt(Math.max(1, ...data.seconds.map((p) => p.req)))}/s)+ </p>+ </div>++ {data.topRoutes.length > 0 && (+ <div className="mt-4">+ <p className="mb-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">Top routes — last 5 min</p>+ <ul className="divide-y">+ {data.topRoutes.map((r) => (+ <li key={r.route} className="flex items-center justify-between gap-4 py-1.5 text-sm">+ <code className="truncate font-mono text-xs">{r.route}</code>+ <span className="shrink-0 tabular-nums text-muted-foreground">{fmt(r.hits)}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ {error && <p className="mt-3 text-xs text-destructive">{error}</p>}+ </>+ )}+ </Card>+ )+}diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.tsindex 471cf65..1c8f810 100644--- a/src/lib/admin/config.test.ts+++ b/src/lib/admin/config.test.ts@@ -13,14 +13,22 @@ import {validateModels,validateFeatures,validateSettings,+ validateProviderList,+ validateSlots,maskApiKey,getFeatures,getSettings,getProviderOverride,+ getProviders,getModels,setFeatures,+ setProviders,+ clearProviders,clearProvider,+ importLegacyProvider,+ invalidateAdminConfig,DEFAULT_FEATURES,+ type StoredProviderEntry,} from './config'beforeEach(() => {@@ -65,7 +73,10 @@ describe('validateModels (v0.16 A1)', () => {it('rejects garbage model ids and unknown junk only warns by ignoring', () => {expect(validateModels({ text: 'bad model!' }).ok).toBe(false)- expect(validateModels({ text: '../etc/passwd' }).ok).toBe(false)+ expect(validateModels({ text: 'model;rm -rf /' }).ok).toBe(false) // ; and spaces are never legal+ // "/" IS legal since v0.16.2 — NVIDIA NIM / HuggingFace namespaces+ expect(validateModels({ text: 'meta/llama-3.1-70b-instruct' }).ok).toBe(true)+ expect(validateModels({ text: 'openrouter/auto' }).ok).toBe(true)const out = validateModels({ evil: 'x', text: 'glm-4.6' })expect(out.ok).toBe(true)if (out.ok) expect(out.value).toEqual({ text: 'glm-4.6' })@@ -165,3 +176,177 @@ describe('writers (v0.16 A1)', () => {)})})++describe('validateProviderList (v0.16.2 A2)', () => {+ const existing = new Map<string, StoredProviderEntry>([+ ['pkeep', { id: 'pkeep', label: 'Old label', baseUrl: 'https://old.example/v1', apiKey: 'sk-stored' }],+ ])++ it('validates a clean list and normalizes base URLs', () => {+ const out = validateProviderList([{ id: 'pa', label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k-a' }])+ expect(out.ok).toBe(true)+ if (out.ok) expect(out.value[0]).toEqual({ id: 'pa', label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k-a' })+ })++ it('keeps the stored key when apiKey is omitted (write-only credential)', () => {+ const out = validateProviderList([{ id: 'pkeep', label: 'Renamed', baseUrl: 'https://old.example/v1' }], { existing })+ expect(out.ok).toBe(true)+ if (out.ok) {+ expect(out.value[0].apiKey).toBe('sk-stored')+ expect(out.value[0].label).toBe('Renamed')+ }+ })++ it('demands a key for a NEW provider (unknown id, no key)', () => {+ const out = validateProviderList([{ label: 'New', baseUrl: 'https://n.example/v1' }], { existing })+ expect(out.ok).toBe(false)+ })++ it('generates ids for new entries (injectable makeId) and enforces uniqueness', () => {+ let n = 0+ const out = validateProviderList(+ [+ { label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k' },+ { label: 'B', baseUrl: 'https://b.example/v1', apiKey: 'k' },+ ],+ { makeId: () => 'p' + n++ }+ )+ expect(out.ok).toBe(true)+ if (out.ok) {+ expect(out.value.map((p) => p.id)).toEqual(['p0', 'p1'])+ expect(out.value[0].id).toMatch(/^p[a-z0-9]+$/)+ }+ const dup = validateProviderList(+ [+ { id: 'psame', label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k' },+ { id: 'psame', label: 'B', baseUrl: 'https://b.example/v1', apiKey: 'k' },+ ],+ { makeId: () => 'px' }+ )+ expect(dup.ok).toBe(false)+ })++ it('rejects malformed entries: label, URL, scheme, embedded credentials, cap', () => {+ expect(validateProviderList('nope').ok).toBe(false)+ expect(validateProviderList([{ label: '', baseUrl: 'https://x.io', apiKey: 'k' }]).ok).toBe(false)+ expect(validateProviderList([{ label: 'A', baseUrl: 'not a url', apiKey: 'k' }]).ok).toBe(false)+ expect(validateProviderList([{ label: 'A', baseUrl: 'ftp://x', apiKey: 'k' }]).ok).toBe(false)+ expect(validateProviderList([{ label: 'A', baseUrl: 'https://u:[email protected]', apiKey: 'k' }]).ok).toBe(false)+ expect(+ validateProviderList(+ Array.from({ length: 9 }, (_, i) => ({ label: `P${i}`, baseUrl: `https://p${i}.io`, apiKey: 'k' }))+ ).ok+ ).toBe(false)+ })++ it('an empty list is valid (clears the table)', () => {+ expect(validateProviderList([])).toEqual({ ok: true, value: [] })+ })+})++describe('validateSlots (v0.16.2 A2)', () => {+ const ids = new Set(['pa', 'pb'])++ it('keeps valid slots, drops unknown keys, omits empty models', () => {+ const out = validateSlots(+ { text: { providerId: 'pa', model: 'glm-4.6' }, vision: { providerId: 'pb', model: '' }, junk: { providerId: 'pa' } },+ ids+ )+ expect(out.ok).toBe(true)+ if (out.ok) {+ expect(out.value).toEqual({ text: { providerId: 'pa', model: 'glm-4.6' }, vision: { providerId: 'pb' } })+ }+ })++ it('null clears a slot; unknown providerId and bad models are rejected', () => {+ expect(validateSlots({ text: null }, ids)).toEqual({ ok: true, value: {} })+ expect(validateSlots({ text: { providerId: 'pgone' } }, ids).ok).toBe(false)+ expect(validateSlots({ text: { providerId: 'pa', model: 'bad model!' } }, ids).ok).toBe(false)+ expect(validateSlots([], ids).ok).toBe(false)+ })+})++describe('multi-provider table read/write (v0.16.2 A2)', () => {+ it('getProviders parses a stored table; absent/corrupt rows read as null', async () => {+ findMany.mockResolvedValue([+ {+ key: 'ai.providers',+ value: {+ providers: [{ id: 'pa', label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k' }],+ slots: { text: { providerId: 'pa', model: 'glm-4.6' } },+ },+ },+ ])+ const table = await getProviders()+ expect(table?.providers).toHaveLength(1)+ expect(table?.slots.text).toEqual({ providerId: 'pa', model: 'glm-4.6' })++ invalidateAdminConfig()+ findMany.mockResolvedValue([{ key: 'ai.providers', value: { providers: [{ label: 'no id' }] } }])+ expect(await getProviders()).toBeNull()++ invalidateAdminConfig()+ findMany.mockResolvedValue([])+ expect(await getProviders()).toBeNull()+ })++ it('setProviders upserts the table; clearProviders empties it', async () => {+ upsert.mockResolvedValue({})+ await setProviders({ providers: [{ id: 'pa', label: 'A', baseUrl: 'https://a.io', apiKey: 'k' }], slots: { text: { providerId: 'pa' } } })+ expect(upsert).toHaveBeenCalledWith(+ expect.objectContaining({ where: { key: 'ai.providers' } })+ )+ await clearProviders()+ expect(upsert).toHaveBeenCalledWith(+ expect.objectContaining({ where: { key: 'ai.providers' }, update: { value: {} } })+ )+ })+})++describe('importLegacyProvider (v0.16.2 A2)', () => {+ it('imports the legacy override, wires empty slots to it, clears the legacy row', async () => {+ findMany.mockResolvedValue([+ { key: 'ai.provider', value: { baseUrl: 'https://legacy.example/v1', apiKey: 'sk-leg' } },+ ])+ upsert.mockResolvedValue({})+ const out = await importLegacyProvider()+ expect(out.ok).toBe(true)+ if (out.ok) {+ expect(out.value.added).toBe(true)+ expect(out.value.list).toHaveLength(1)+ expect(out.value.list[0].baseUrl).toBe('https://legacy.example/v1')+ expect(out.value.list[0].apiKey).toBe('sk-leg')+ expect(Object.keys(out.value.slots)).toHaveLength(5) // all slots wired+ }+ const calls = upsert.mock.calls.map((c) => c[0].where.key)+ expect(calls).toContain('ai.providers')+ expect(calls).toContain('ai.provider') // cleared+ })++ it('does not duplicate a provider that is already in the table', async () => {+ findMany.mockResolvedValue([+ { key: 'ai.provider', value: { baseUrl: 'https://same.example/v1', apiKey: 'sk-leg' } },+ {+ key: 'ai.providers',+ value: {+ providers: [{ id: 'pa', label: 'Same', baseUrl: 'https://same.example/v1', apiKey: 'sk-x' }],+ slots: { text: { providerId: 'pa' } },+ },+ },+ ])+ upsert.mockResolvedValue({})+ const out = await importLegacyProvider()+ expect(out.ok).toBe(true)+ if (out.ok) {+ expect(out.value.added).toBe(false)+ expect(out.value.list).toHaveLength(1)+ expect(out.value.slots).toEqual({ text: { providerId: 'pa' } }) // existing slots kept+ }+ })++ it('fails cleanly when nothing is stored', async () => {+ findMany.mockResolvedValue([])+ const out = await importLegacyProvider()+ expect(out.ok).toBe(false)+ })+})diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.tsindex dee4a84..09948d6 100644--- a/src/lib/admin/config.ts+++ b/src/lib/admin/config.ts@@ -1,18 +1,23 @@// ─────────────────────────────────────────────────────────────-// Instance configuration (v0.16 A1) — the store behind /admin's-// AI + settings pages.+// Instance configuration (v0.16 A1, extended in v0.16.2 A2) —+// the store behind /admin's AI + settings pages.//-// Four small AppConfig rows (key → JSON):-// ai.provider { baseUrl, apiKey } — console-set provider, wins over env-// ai.models { text?, vision?, image? } — model ids passed to the SDK+// AppConfig rows (key → JSON):+// ai.provider { baseUrl, apiKey } — legacy single override (v0.16 A1)+// ai.providers { providers: […], slots: {…} } — multi-provider table (A2)+// ai.models { text?, vision?, image? } — legacy model ids (A1)// ai.features { magicWrite, … } — per-feature kill switches// app.settings { signupsOpen, anonymousEditing }//// Design decisions (documented in docs/ADMIN.md):-// • Precedence for the provider: DB (console) → env → .z-ai-config-// file → unconfigured. The console never shows a stored API key+// • Precedence per capability slot: multi-provider table (ai.providers)+// → legacy single override (ai.provider) → env → .z-ai-config file+// → unconfigured. The console never shows a stored API key// back — only a mask (write-only credential, same posture as the// env vars it overrides).+// • Multi-provider keys are write-only too: saving a provider without+// re-entering its key keeps the stored one (matched by id), so+// editing a label or model never demands the credential again.// • Reads are cached in-process for 10 s (config sits on every AI// request path; one tiny indexed findMany per 10 s per instance is// the whole cost). Writes invalidate immediately — the same server@@ -32,6 +37,7 @@ import type { Prisma } from '@/generated/prisma/client'export const CONFIG_KEYS = {provider: 'ai.provider',+ providers: 'ai.providers',models: 'ai.models',features: 'ai.features',settings: 'app.settings',@@ -48,6 +54,10 @@ export const AI_FEATURES = [] as constexport type AiFeature = (typeof AI_FEATURES)[number]+/** Capability slots (v0.16.2 A2) — what a provider can be assigned to. */+export const AI_SLOTS = ['text', 'vision', 'image', 'imageEdit', 'imageSearch'] as const+export type AiSlot = (typeof AI_SLOTS)[number]+export interface StoredProvider {baseUrl: stringapiKey: string@@ -57,6 +67,24 @@ export interface StoredModels {vision?: stringimage?: string}+/** One entry of the multi-provider table. */+export interface StoredProviderEntry {+ /** Stable client-visible id (`p` + alphanumerics) — slots reference it. */+ id: string+ label: string+ baseUrl: string+ apiKey: string+}+/** A capability slot pinned to one provider of the table. */+export interface StoredSlot {+ providerId: string+ model?: string+}+/** The whole multi-provider table (AppConfig `ai.providers`). */+export interface StoredProviders {+ providers: StoredProviderEntry[]+ slots: Partial<Record<AiSlot, StoredSlot>>+}export type StoredFeatures = Record<AiFeature, boolean>export interface StoredSettings {signupsOpen: boolean@@ -80,21 +108,27 @@ export const DEFAULT_SETTINGS: StoredSettings = {const BASEURL_MAX = 2048const APIKEY_MAX = 4096-const MODEL_RE = /^[A-Za-z0-9._:+-]{1,120}$/+// Model ids: letters, digits, ._:+- plus "/" (NVIDIA NIM + HuggingFace+// namespaces: meta/llama-3.1-70b-instruct) and "@" (OpenRouter vendor+// prefixes). No spaces, no path traversal (".." still passes the charset+// but can only ever name a model id at the provider, never a file).+const MODEL_RE = /^[A-Za-z0-9._:+/@-]{1,120}$/+const PROVIDER_ID_RE = /^p[a-z0-9]{1,23}$/+const LABEL_MAX = 60+/** Hard cap on table size — eight providers is far beyond any sane setup. */+const PROVIDERS_MAX = 8++/** Random id for a new provider entry (`p` + 10 base36 chars). */+function makeProviderId(): string {+ return 'p' + Array.from({ length: 10 }, () => Math.floor(Math.random() * 36).toString(36)).join('')+}// ── validation (pure, unit-tested) ────────────────────────────export type Check<T> = { ok: true; value: T } | { ok: false; error: string }-/** A usable provider override: an http(s) base URL without credentials + a non-empty key. */-export function validateProvider(input: unknown): Check<StoredProvider> {- if (typeof input !== 'object' || input === null) return { ok: false, error: 'provider must be an object.' }- const raw = input as Record<string, unknown>- if (typeof raw.baseUrl !== 'string' || !raw.baseUrl.trim()) return { ok: false, error: 'baseUrl is required.' }- if (typeof raw.apiKey !== 'string' || !raw.apiKey) return { ok: false, error: 'apiKey is required.' }- const baseUrl = raw.baseUrl.trim()- if (baseUrl.length > BASEURL_MAX) return { ok: false, error: `baseUrl must be at most ${BASEURL_MAX} characters.` }- if (raw.apiKey.length > APIKEY_MAX) return { ok: false, error: `apiKey must be at most ${APIKEY_MAX} characters.` }+/** Shared base-URL validation — returns the normalized URL or why it failed. */+function checkBaseUrl(baseUrl: string): Check<string> {let parsed: URLtry {parsed = new URL(baseUrl)@@ -107,7 +141,21 @@ export function validateProvider(input: unknown): Check<StoredProvider> {if (parsed.username || parsed.password) {return { ok: false, error: 'baseUrl must not embed credentials — put the key in the apiKey field.' }}- return { ok: true, value: { baseUrl: parsed.toString(), apiKey: raw.apiKey } }+ return { ok: true, value: parsed.toString() }+}++/** A usable provider override: an http(s) base URL without credentials + a non-empty key. */+export function validateProvider(input: unknown): Check<StoredProvider> {+ if (typeof input !== 'object' || input === null) return { ok: false, error: 'provider must be an object.' }+ const raw = input as Record<string, unknown>+ if (typeof raw.baseUrl !== 'string' || !raw.baseUrl.trim()) return { ok: false, error: 'baseUrl is required.' }+ if (typeof raw.apiKey !== 'string' || !raw.apiKey) return { ok: false, error: 'apiKey is required.' }+ const baseUrl = raw.baseUrl.trim()+ if (baseUrl.length > BASEURL_MAX) return { ok: false, error: `baseUrl must be at most ${BASEURL_MAX} characters.` }+ if (raw.apiKey.length > APIKEY_MAX) return { ok: false, error: `apiKey must be at most ${APIKEY_MAX} characters.` }+ const url = checkBaseUrl(baseUrl)+ if (!url.ok) return url+ return { ok: true, value: { baseUrl: url.value, apiKey: raw.apiKey } }}/** Optional model ids; unknown keys are dropped, each value must look like a model id. */@@ -154,6 +202,118 @@ export function validateSettings(input: unknown): Check<Partial<StoredSettings>>return { ok: true, value: out }}+// ── multi-provider table validation (v0.16.2 A2) ─────────────++/**+ * Validate the provider LIST half of `ai.providers` (full replace).+ *+ * Input shape: [{ id?, label, baseUrl, apiKey? }]. Keys are write-only:+ * an entry with an id whose apiKey is empty/missing keeps the stored key+ * (matched against `existing`), so editing a label or URL never demands+ * the credential again. New entries (no id, or an id not in `existing`)+ * MUST carry a key. Ids are validated for shape + uniqueness and+ * generated (via `makeId`, injectable for tests) when missing.+ */+export function validateProviderList(+ input: unknown,+ opts: { existing?: Map<string, StoredProviderEntry>; makeId?: () => string } = {}+): Check<StoredProviderEntry[]> {+ if (!Array.isArray(input)) return { ok: false, error: 'providers.list must be an array.' }+ if (input.length > PROVIDERS_MAX) {+ return { ok: false, error: `At most ${PROVIDERS_MAX} providers can be stored.` }+ }+ const existing = opts.existing ?? new Map()+ const makeId = opts.makeId ?? makeProviderId+ const seen = new Set<string>()+ const out: StoredProviderEntry[] = []+ for (let i = 0; i < input.length; i++) {+ const raw = input[i]+ if (typeof raw !== 'object' || raw === null) {+ return { ok: false, error: `providers.list[${i}] must be an object.` }+ }+ const entry = raw as Record<string, unknown>+ // label+ const label = typeof entry.label === 'string' ? entry.label.trim() : ''+ if (!label || label.length > LABEL_MAX) {+ return { ok: false, error: `providers.list[${i}].label must be 1-${LABEL_MAX} characters.` }+ }+ // baseUrl (shared rules with the legacy override)+ if (typeof entry.baseUrl !== 'string' || !entry.baseUrl.trim()) {+ return { ok: false, error: `providers.list[${i}].baseUrl is required.` }+ }+ const baseUrl = entry.baseUrl.trim()+ if (baseUrl.length > BASEURL_MAX) {+ return { ok: false, error: `providers.list[${i}].baseUrl must be at most ${BASEURL_MAX} characters.` }+ }+ const url = checkBaseUrl(baseUrl)+ if (!url.ok) return { ok: false, error: `providers.list[${i}]: ${url.error}` }+ // id — validate or generate, always unique within the list+ let id = typeof entry.id === 'string' && entry.id ? entry.id : ''+ if (id) {+ if (!PROVIDER_ID_RE.test(id)) {+ return { ok: false, error: `providers.list[${i}].id must look like "p" + lowercase alphanumerics.` }+ }+ } else {+ id = makeId()+ while (!PROVIDER_ID_RE.test(id) || seen.has(id)) id = makeId()+ }+ if (seen.has(id)) return { ok: false, error: `Duplicate provider id "${id}".` }+ seen.add(id)+ // apiKey — write-only: keep the stored one when omitted+ const stored = existing.get(id)+ let apiKey = typeof entry.apiKey === 'string' ? entry.apiKey : ''+ if (!apiKey && stored) apiKey = stored.apiKey+ if (!apiKey) {+ return {+ ok: false,+ error: `providers.list[${i}].apiKey is required for a new provider (leave it empty to keep a stored one).`,+ }+ }+ if (apiKey.length > APIKEY_MAX) {+ return { ok: false, error: `providers.list[${i}].apiKey must be at most ${APIKEY_MAX} characters.` }+ }+ out.push({ id, label, baseUrl: url.value, apiKey })+ }+ return { ok: true, value: out }+}++/**+ * Validate the SLOTS half of `ai.providers`: slot → { providerId, model? }+ * or null (clears the slot). providerId must reference a provider in the+ * list being saved. Unknown slot keys are dropped; model ids follow the+ * same MODEL_RE as the legacy models field (empty string = omit).+ */+export function validateSlots(input: unknown, providerIds: Set<string>): Check<Partial<Record<AiSlot, StoredSlot>>> {+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {+ return { ok: false, error: 'providers.slots must be an object.' }+ }+ const raw = input as Record<string, unknown>+ const out: Partial<Record<AiSlot, StoredSlot>> = {}+ for (const slot of AI_SLOTS) {+ const v = raw[slot]+ if (v === undefined) continue+ if (v === null) continue // explicit clear — omit the slot+ if (typeof v !== 'object' || Array.isArray(v)) {+ return { ok: false, error: `providers.slots.${slot} must be an object or null.` }+ }+ const entry = v as Record<string, unknown>+ const providerId = typeof entry.providerId === 'string' ? entry.providerId : ''+ if (!providerId || !providerIds.has(providerId)) {+ return { ok: false, error: `providers.slots.${slot}.providerId must reference a provider in the list.` }+ }+ let model: string | undefined+ const m = entry.model+ if (m !== undefined && m !== null && m !== '') {+ if (typeof m !== 'string' || !MODEL_RE.test(m)) {+ return { ok: false, error: `providers.slots.${slot}.model must be a model id (letters, digits, . _ : + -).` }+ }+ model = m+ }+ out[slot] = model ? { providerId, model } : { providerId }+ }+ return { ok: true, value: out }+}+/** Never echo a stored key — `sk-1…wxyz` shape with the length for a sanity check. */export function maskApiKey(key: string): string {if (key.length <= 8) return '••••••••'@@ -218,6 +378,23 @@ export async function getProviderOverride(): Promise<StoredProvider | null> {return check.ok ? check.value : null}+/**+ * The multi-provider table (v0.16.2 A2). Null when absent — slots then+ * fall back to the legacy chain (override → env → file). A table whose+ * list half fails validation is treated as absent (fail-open to the+ * legacy chain, the same stance as every other config read here).+ */+export async function getProviders(): Promise<StoredProviders | null> {+ const rows = await readRows()+ const raw = asRecord(rows.get(CONFIG_KEYS.providers))+ const list = Array.isArray(raw.providers) ? raw.providers : []+ const check = validateProviderList(list)+ if (!check.ok || !check.value.length) return null+ const ids = new Set(check.value.map((p) => p.id))+ const slots = validateSlots(raw.slots, ids)+ return { providers: check.value, slots: slots.ok ? slots.value : {} }+}+/** Model ids (empty strings omitted) — {} = SDK defaults. */export async function getModels(): Promise<StoredModels> {const rows = await readRows()@@ -258,6 +435,51 @@ export async function clearProvider(): Promise<void> {await writeRow(CONFIG_KEYS.provider, {})}+/** Write the full multi-provider table (list + slots together). */+export async function setProviders(value: StoredProviders): Promise<void> {+ await writeRow(CONFIG_KEYS.providers, value as unknown as Prisma.InputJsonValue)+}++/** Clear the multi-provider table — slots fall back to the legacy chain. */+export async function clearProviders(): Promise<void> {+ await writeRow(CONFIG_KEYS.providers, {})+}++/**+ * One-click migration (v0.16.2 A2): fold the legacy single-provider+ * override into the multi-provider table and clear the legacy row.+ *+ * • no legacy override stored → { ok: false } (the route answers 400)+ * • a provider with the same baseUrl already in the table → don't+ * duplicate, just clear the legacy row+ * • table has no slots yet → point all five at the imported provider+ * (preserves the A1 behaviour where the override answered everything)+ */+export async function importLegacyProvider(): Promise<+ | { ok: false; error: string }+ | { ok: true; value: { list: StoredProviderEntry[]; slots: Partial<Record<AiSlot, StoredSlot>>; added: boolean } }+> {+ const legacy = await getProviderOverride()+ if (!legacy) return { ok: false, error: 'No single-provider override is stored — nothing to import.' }+ const current = await getProviders()+ const list = current?.providers ? [...current.providers] : []+ const slots = current?.slots ? { ...current.slots } : {}+ const duplicate = list.some((p) => p.baseUrl === legacy.baseUrl)+ let added = false+ if (!duplicate) {+ let id = makeProviderId()+ while (list.some((p) => p.id === id)) id = makeProviderId()+ list.push({ id, label: 'Imported override', baseUrl: legacy.baseUrl, apiKey: legacy.apiKey })+ if (!Object.keys(slots).length) {+ for (const slot of AI_SLOTS) slots[slot] = { providerId: id }+ }+ added = true+ }+ await setProviders({ providers: list, slots })+ await clearProvider()+ return { ok: true, value: { list, slots, added } }+}+export async function setModels(value: StoredModels): Promise<void> {await writeRow(CONFIG_KEYS.models, value as unknown as Prisma.InputJsonValue)}diff --git a/src/lib/admin/realtime.test.ts b/src/lib/admin/realtime.test.tsnew file mode 100644index 0000000..28be7fc--- /dev/null+++ b/src/lib/admin/realtime.test.ts@@ -0,0 +1,127 @@+// Unit tests for the in-memory live traffic module (v0.16.2 A2) —+// bucketing, window expiry, gap-filled snapshot, latency percentiles+// and the bounded-eviction invariants. All timestamps are injected, so+// no fake timers are needed.++import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { recordLiveRequest, recordLiveAi, liveSnapshot, resetRealtime } from './realtime'++const T0 = 1_700_000_000_000 // an arbitrary epoch ms on a minute boundary+const min = (n: number) => T0 + n * 60_000+const sec = (n: number) => T0 + n * 1000++beforeEach(() => {+ resetRealtime()+ delete process.env.CANVIX_TRAFFIC+})++afterEach(() => {+ resetRealtime()+})++describe('recordLiveRequest + liveSnapshot (v0.16.2 A2)', () => {+ it('counts requests, errors, routes and visitors into the 5-minute window', () => {+ recordLiveRequest('GET /api/designs', 200, 12, 'v1', sec(0))+ recordLiveRequest('GET /api/designs', 200, 20, 'v1', sec(1))+ recordLiveRequest('POST /api/ai/write', 500, 90, 'v2', sec(1))+ recordLiveRequest('GET /api/health', 404, 5, null, sec(2))+ const snap = liveSnapshot(sec(3))+ expect(snap.window5m.requests).toBe(4)+ expect(snap.window5m.errors).toBe(2)+ expect(snap.window5m.visitors).toBe(2) // v1 + v2; null visitor not counted+ expect(snap.topRoutes[0]).toEqual({ route: 'GET /api/designs', hits: 2 })+ // the 60-second strip: 4 buckets with data, newest last+ expect(snap.seconds).toHaveLength(60)+ expect(snap.seconds[59]).toEqual({ t: Math.floor(sec(3) / 1000), req: 0, err: 0 })+ expect(snap.seconds[57].req).toBe(2) // second 1+ expect(snap.seconds[58].req).toBe(1) // second 2+ })++ it('gap-fills per-second buckets — the strip is always 60 long', () => {+ recordLiveRequest('GET /a', 200, 1, 'v1', sec(0))+ const snap = liveSnapshot(sec(30))+ expect(snap.seconds).toHaveLength(60)+ const withData = snap.seconds.filter((p) => p.req > 0)+ expect(withData).toHaveLength(1)+ })++ it('expires requests, routes and visitors past the 5-minute window', () => {+ recordLiveRequest('GET /old', 200, 5, 'v1', min(0))+ // still inside the window+ expect(liveSnapshot(min(4)).window5m.requests).toBe(1)+ expect(liveSnapshot(min(4)).window5m.visitors).toBe(1)+ // six minutes later everything has aged out (the read sweeps)+ const stale = liveSnapshot(min(6))+ expect(stale.window5m.requests).toBe(0)+ expect(stale.window5m.visitors).toBe(0)+ expect(stale.topRoutes).toEqual([])+ })++ it('drops per-second buckets older than 120 s from the strip', () => {+ recordLiveRequest('GET /a', 200, 1, 'v1', sec(0))+ const snap = liveSnapshot(sec(130))+ expect(snap.seconds.some((p) => p.req > 0)).toBe(false)+ })++ it('computes p50/p95 over the latency ring', () => {+ for (let i = 1; i <= 100; i++) recordLiveRequest('GET /x', 200, i, 'v1', sec(0)) // 1..100 ms+ const snap = liveSnapshot(sec(1))+ expect(snap.window5m.p50Ms).toBe(50)+ expect(snap.window5m.p95Ms).toBe(95)+ })++ it('caps the latency ring (last 720 requests only)', () => {+ for (let i = 1; i <= 1000; i++) recordLiveRequest('GET /x', 200, i, 'v1', sec(0))+ const snap = liveSnapshot(sec(1))+ // ring holds only the newest 720 of the 1..1000 ms requests (281..1000)+ expect(snap.window5m.requests).toBe(1000)+ expect(snap.window5m.p50Ms).toBe(640) // sorted[359] of 281..1000+ expect(snap.window5m.p95Ms).toBe(964) // sorted[683] of 281..1000+ })++ it('evicts the coldest route when the key cap is hit (bounded memory)', () => {+ for (let i = 0; i < 300; i++) recordLiveRequest(`GET /route-${i}`, 200, 1, 'v1', sec(0))+ recordLiveRequest('GET /hot', 200, 1, 'v1', sec(0))+ recordLiveRequest('GET /hot', 200, 1, 'v1', sec(0))+ const snap = liveSnapshot(sec(1))+ const routes = snap.topRoutes.map((r) => r.route)+ expect(routes).toContain('GET /hot')+ expect(routes.length).toBeLessThanOrEqual(8)+ // window totals are exact regardless of per-route eviction+ expect(snap.window5m.requests).toBe(302)+ })++ it('CANVIX_TRAFFIC=0 disables live recording entirely', () => {+ process.env.CANVIX_TRAFFIC = '0'+ recordLiveRequest('GET /a', 200, 1, 'v1', sec(0))+ recordLiveAi('write', true, sec(0))+ const snap = liveSnapshot(sec(1))+ expect(snap.window5m.requests).toBe(0)+ expect(snap.window5m.aiCalls).toBe(0)+ delete process.env.CANVIX_TRAFFIC+ })+})++describe('recordLiveAi (v0.16.2 A2)', () => {+ it('counts calls and successes per rolling minute', () => {+ recordLiveAi('write', true, min(0))+ recordLiveAi('write', true, min(0))+ recordLiveAi('image', false, min(1))+ const snap = liveSnapshot(min(2))+ expect(snap.window5m.aiCalls).toBe(3)+ expect(snap.window5m.aiOk).toBe(2)+ // aged out+ expect(liveSnapshot(min(6)).window5m.aiCalls).toBe(0)+ })+})++describe('liveSnapshot shape (v0.16.2 A2)', () => {+ it('reports uptime and an ISO timestamp', () => {+ // real clock here — uptime is measured from the actual module load+ const now = Date.now()+ const snap = liveSnapshot(now)+ expect(snap.now).toBe(new Date(now).toISOString())+ expect(snap.uptimeSec).toBeGreaterThanOrEqual(0)+ expect(snap.seconds).toHaveLength(60)+ })+})diff --git a/src/lib/admin/realtime.ts b/src/lib/admin/realtime.tsnew file mode 100644index 0000000..e32136c--- /dev/null+++ b/src/lib/admin/realtime.ts@@ -0,0 +1,265 @@+// ─────────────────────────────────────────────────────────────+// Real-time traffic (v0.16.2 A2) — the live counters behind the+// console's "Live traffic" panel (GET /api/admin/realtime).+//+// In-memory rolling windows over the same withLogging wrapper every+// API route already uses:+// • per-second request/error buckets — last 120 s+// • per-route per-minute hits — last 5 min+// • per-visitor (hashed, per-boot salt) last-seen — 5 min window+// • recent latency ring — last 720 requests (p50/p95)+// • AI calls per minute (ok + failed) — last 5 min+//+// CONTRACT (same as src/lib/observability.ts):+// • ZERO imports — stdlib-only, no Prisma, no db. This module is+// statically imported by observability.ts, so it must stay safe+// for every runtime Canvix supports (Node, Bun, workerd/edge).+// • Bounded memory: every structure has a hard cap and is swept+// lazily on write and on read.+// • Process-local: counters reset on restart. The TrafficStat /+// AIUsage tables remain the durable record (docs/ADMIN.md).+// • CANVIX_TRAFFIC=0 — the documented opt-out for traffic+// counting — disables live recording too (checked inline: this+// module deliberately imports nothing).+// • Privacy: visitors are counted through a salted, non-cryptographic+// hash of the client IP (see liveVisitorKey in observability.ts —+// per-boot salt, never the IP itself). Counts only, never ids,+// never query strings — the same stance as /api/health?v=2.+// ─────────────────────────────────────────────────────────────++/** Rolling window for routes / visitors / AI minutes. */+const WINDOW_MS = 5 * 60_000+/** Per-second buckets kept (snapshot shows the newest 60). */+const SECONDS_KEPT = 120+/** Hard cap on distinct route keys (misbehaving wrapper names). */+const ROUTES_MAX = 128+/** Hard cap on distinct visitor keys — far above any real audience. */+const VISITORS_MAX = 4096+/** Latency ring size (p50/p95 over the most recent requests). */+const LATENCY_RING = 720++interface SecondBucket {+ req: number+ err: number+}+interface AiMinute {+ calls: number+ ok: number+}++const bootAt = Date.now()++// module state (single-process by design — see header)+const seconds = new Map<number, SecondBucket>()+const minuteTotals = new Map<number, SecondBucket>() // 5-minute window totals+const routes = new Map<string, Map<number, number>>() // "METHOD /route" → minute → hits+const visitors = new Map<string, number>() // hash → last-seen ms+const latencies: number[] = []+const aiMinutes = new Map<number, AiMinute>()+let sweepTick = 0++function disabled(): boolean {+ return process.env.CANVIX_TRAFFIC === '0'+}++/** Drop everything outside the windows. Cheap, called on write + read. */+function sweep(now: number): void {+ const secondCutoff = Math.floor(now / 1000) - SECONDS_KEPT+ for (const key of seconds.keys()) {+ if (key <= secondCutoff) seconds.delete(key)+ }+ const minuteCutoff = Math.floor(now / 60_000) - Math.floor(WINDOW_MS / 60_000)+ for (const key of minuteTotals.keys()) {+ if (key <= minuteCutoff) minuteTotals.delete(key)+ }+ for (const [route, minutes] of routes) {+ for (const m of minutes.keys()) {+ if (m <= minuteCutoff) minutes.delete(m)+ }+ if (!minutes.size) routes.delete(route)+ }+ const msCutoff = now - WINDOW_MS+ for (const [visitor, seen] of visitors) {+ if (seen < msCutoff) visitors.delete(visitor)+ }+ for (const m of aiMinutes.keys()) {+ if (m <= minuteCutoff) aiMinutes.delete(m)+ }+}++/**+ * Record one API request (called from withLogging — fire-and-forget,+ * synchronous, cannot throw). `routeKey` is the wrapper name+ * ("METHOD /route"), `visitor` the hashed client key or null.+ */+export function recordLiveRequest(+ routeKey: string,+ status: number,+ durationMs: number,+ visitor: string | null,+ now: number = Date.now()+): void {+ if (disabled()) return+ // amortize the sweep — every 16th hit is enough at any real rps+ if ((sweepTick = (sweepTick + 1) & 15) === 0) sweep(now)+ const sec = Math.floor(now / 1000)+ let bucket = seconds.get(sec)+ if (!bucket) {+ bucket = { req: 0, err: 0 }+ seconds.set(sec, bucket)+ }+ bucket.req+++ if (status >= 400) bucket.err+++ const minute = Math.floor(now / 60_000)+ let totals = minuteTotals.get(minute)+ if (!totals) {+ totals = { req: 0, err: 0 }+ minuteTotals.set(minute, totals)+ }+ totals.req+++ if (status >= 400) totals.err+++ const route = routeKey.slice(0, 160)+ let minutes = routes.get(route)+ if (!minutes) {+ if (routes.size >= ROUTES_MAX) {+ // evict the route with the fewest total hits — bounded, keeps the hot ones+ let victim: string | null = null+ let victimHits = Number.POSITIVE_INFINITY+ for (const [r, m] of routes) {+ let total = 0+ for (const v of m.values()) total += v+ if (total < victimHits) {+ victimHits = total+ victim = r+ }+ }+ if (victim) routes.delete(victim)+ }+ minutes = new Map()+ routes.set(route, minutes)+ }+ minutes.set(minute, (minutes.get(minute) ?? 0) + 1)+ if (visitor) {+ if (visitors.size >= VISITORS_MAX && !visitors.has(visitor)) {+ // drop the stalest entry — the sweep will regenerate it if still active+ let victim: string | null = null+ let victimSeen = Number.POSITIVE_INFINITY+ for (const [v, seen] of visitors) {+ if (seen < victimSeen) {+ victimSeen = seen+ victim = v+ }+ }+ if (victim) visitors.delete(victim)+ }+ visitors.set(visitor, now)+ }+ if (latencies.length >= LATENCY_RING) latencies.shift()+ latencies.push(Math.max(0, Math.round(durationMs)))+}++/** Record one AI call outcome (called from recordUsage — sync, safe). */+export function recordLiveAi(feature: string, ok: boolean, now: number = Date.now()): void {+ if (disabled()) return+ const minute = Math.floor(now / 60_000)+ let bucket = aiMinutes.get(minute)+ if (!bucket) {+ bucket = { calls: 0, ok: 0 }+ aiMinutes.set(minute, bucket)+ }+ bucket.calls+++ if (ok) bucket.ok+++ void feature // feature-level live split is a future knob; totals for now+}++function percentile(sorted: number[], p: number): number | null {+ if (!sorted.length) return null+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.floor(p * (sorted.length - 1))))+ return sorted[idx]+}++/** Snapshot shape returned by GET /api/admin/realtime. */+export interface LiveSnapshot {+ now: string+ uptimeSec: number+ /** Newest-last per-second buckets, gap-filled to exactly 60 entries. */+ seconds: { t: number; req: number; err: number }[]+ window5m: {+ requests: number+ errors: number+ visitors: number+ p50Ms: number | null+ p95Ms: number | null+ aiCalls: number+ aiOk: number+ }+ topRoutes: { route: string; hits: number }[]+}++/**+ * The console's live view. Reads are cheap; the sweep keeps every map+ * bounded even on a burst of reads without writes.+ */+export function liveSnapshot(now: number = Date.now()): LiveSnapshot {+ sweep(now)+ // 60 gap-filled per-second buckets, oldest first+ const currentSec = Math.floor(now / 1000)+ const secondsOut: { t: number; req: number; err: number }[] = []+ for (let i = 59; i >= 0; i--) {+ const t = currentSec - i+ const b = seconds.get(t)+ secondsOut.push({ t, req: b?.req ?? 0, err: b?.err ?? 0 })+ }+ const minuteCutoff = Math.floor(now / 60_000) - Math.floor(WINDOW_MS / 60_000)+ let requests5m = 0+ let errors5m = 0+ for (const [m, b] of minuteTotals) {+ if (m <= minuteCutoff) continue+ requests5m += b.req+ errors5m += b.err+ }+ let aiCalls = 0+ let aiOk = 0+ for (const [m, b] of aiMinutes) {+ if (m <= minuteCutoff) continue+ aiCalls += b.calls+ aiOk += b.ok+ }+ const sorted = [...latencies].sort((a, b) => a - b)+ const topRoutes = [...routes.entries()]+ .map(([route, minutes]) => {+ let hits = 0+ for (const [m, n] of minutes) {+ if (m > minuteCutoff) hits += n+ }+ return { route, hits }+ })+ .filter((r) => r.hits > 0)+ .sort((a, b) => b.hits - a.hits)+ .slice(0, 8)+ return {+ now: new Date(now).toISOString(),+ uptimeSec: Math.floor((now - bootAt) / 1000),+ seconds: secondsOut,+ window5m: {+ requests: requests5m,+ errors: errors5m,+ visitors: visitors.size,+ p50Ms: percentile(sorted, 0.5),+ p95Ms: percentile(sorted, 0.95),+ aiCalls,+ aiOk,+ },+ topRoutes,+ }+}++/** Test hook — wipe every counter. */+export function resetRealtime(): void {+ seconds.clear()+ minuteTotals.clear()+ routes.clear()+ visitors.clear()+ latencies.length = 0+ aiMinutes.clear()+}diff --git a/src/lib/admin/routes.test.ts b/src/lib/admin/routes.test.tsindex e4b7407..952f3ac 100644--- a/src/lib/admin/routes.test.ts+++ b/src/lib/admin/routes.test.ts@@ -185,6 +185,110 @@ describe('GET/PUT /api/admin/config (v0.16 A1)', () => {})})+describe('PUT /api/admin/config × providers section (v0.16.2 A2)', () => {+ it('saves the multi-provider table and echoes it sanitized (masks, never keys)', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ // read #1: nothing stored; read #2 (post-write echo): the saved table+ dbMock.appConfig.findMany+ .mockResolvedValueOnce([])+ .mockResolvedValue([+ {+ key: 'ai.providers',+ value: {+ providers: [{ id: 'pnvidia', label: 'NVIDIA NIM', baseUrl: 'https://integrate.api.nvidia.com/v1', apiKey: 'nvapi-secret-abcdef-wxyz' }],+ slots: { text: { providerId: 'pnvidia', model: 'meta/llama-3.1-70b-instruct' } },+ },+ },+ ])+ const res = await configPut(+ req('http://localhost/api/admin/config', {+ method: 'PUT',+ body: {+ providers: {+ list: [{ id: 'pnvidia', label: 'NVIDIA NIM', baseUrl: 'https://integrate.api.nvidia.com/v1', apiKey: 'nvapi-secret-abcdef-wxyz' }],+ slots: { text: { providerId: 'pnvidia', model: 'meta/llama-3.1-70b-instruct' } },+ },+ },+ })+ )+ expect(res.status).toBe(200)+ const text = await res.text()+ expect(text).not.toContain('nvapi-secret-abcdef-wxyz')+ const body = JSON.parse(text) as {+ providers: { set: boolean; list: { id: string; keyMasked: string }[]; resolved: Record<string, { source: string; label: string | null } | null> }+ }+ expect(body.providers.set).toBe(true)+ expect(body.providers.list[0].keyMasked).toBe('nvap…wxyz')+ // the text slot resolves through the table; image (unpinned) may only+ // resolve via env/file on this machine — assert the table answer only+ expect(body.providers.resolved.text?.source).toBe('multi')+ expect(body.providers.resolved.text?.label).toBe('NVIDIA NIM')+ const upsertArg = dbMock.appConfig.upsert.mock.calls.find((c) => c[0].where.key === 'ai.providers')?.[0]+ expect(upsertArg).toBeDefined()+ })++ it('keeps a stored key when the payload omits it (write-only credential)', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ dbMock.appConfig.findMany.mockResolvedValue([+ {+ key: 'ai.providers',+ value: {+ providers: [{ id: 'pnvidia', label: 'NVIDIA NIM', baseUrl: 'https://integrate.api.nvidia.com/v1', apiKey: 'nvapi-stored' }],+ slots: {},+ },+ },+ ])+ const res = await configPut(+ req('http://localhost/api/admin/config', {+ method: 'PUT',+ body: {+ providers: {+ list: [{ id: 'pnvidia', label: 'NVIDIA NIM (renamed)', baseUrl: 'https://integrate.api.nvidia.com/v1' }],+ slots: {},+ },+ },+ })+ )+ expect(res.status).toBe(200)+ const upsertArg = dbMock.appConfig.upsert.mock.calls.find((c) => c[0].where.key === 'ai.providers')?.[0]+ expect(JSON.stringify(upsertArg)).toContain('nvapi-stored')+ expect(JSON.stringify(upsertArg)).toContain('renamed')+ })++ it('rejects slots that reference a provider not in the list', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ const res = await configPut(+ req('http://localhost/api/admin/config', {+ method: 'PUT',+ body: {+ providers: {+ list: [{ label: 'A', baseUrl: 'https://a.example/v1', apiKey: 'k' }],+ slots: { text: { providerId: 'pgone' } },+ },+ },+ })+ )+ expect(res.status).toBe(400)+ })++ it('providers: null clears the table', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { providers: null } }))+ expect(res.status).toBe(200)+ expect(dbMock.appConfig.upsert).toHaveBeenCalledWith(+ expect.objectContaining({ where: { key: 'ai.providers' }, update: { value: {} } })+ )+ })++ it('importLegacyProvider with nothing stored → 400 with a helpful error', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ dbMock.appConfig.findMany.mockResolvedValue([])+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { importLegacyProvider: true } }))+ expect(res.status).toBe(400)+ expect(((await res.json()) as { error: string }).error).toContain('nothing to import')+ })+})+describe('POST /api/auth/register × signups switch (v0.16 A1)', () => {it('closed signups → 503 SIGNUPS_CLOSED before validation or rate limiting', async () => {dbMock.appConfig.findMany.mockResolvedValue([{ key: 'app.settings', value: { signupsOpen: false } }])diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsindex 0c27202..4c3b1eb 100644--- a/src/lib/ai/provider.ts+++ b/src/lib/ai/provider.ts@@ -1,15 +1,29 @@import { NextResponse, type NextRequest } from 'next/server'import { existsSync, readFileSync } from 'fs'import { CSRF_REJECTED } from '@/lib/auth/csrf'-import { getProviderOverride, aiFeatureEnabled, getModels, type AiFeature } from '@/lib/admin/config'+import {+ getProviderOverride,+ getProviders,+ getModels,+ aiFeatureEnabled,+ type AiFeature,+ type AiSlot,+ type StoredProvider,+ type StoredProviders,+ type StoredModels,+} from '@/lib/admin/config'+import { recordLiveAi } from '@/lib/admin/realtime'/**- * Canvix AI provider abstraction (v0.5).+ * Canvix AI provider abstraction (v0.5, multi-provider since v0.16.2 A2).** Single server-side entry point for every AI capability. Centralizes:- * - provider configuration resolution (env override → .z-ai-config file → absent)+ * - provider configuration resolution, per capability slot:+ * multi-provider table (console) → legacy single override → env →+ * .z-ai-config file → absent+ * - SDK client construction* - capability probing (which features can run on this server)- * - rate limiting + AIUsage accounting+ * - rate limiting + AIUsage accounting + live traffic counters** CONTRACT: this module is SERVER-ONLY. It must never be imported from a* client component — the provider config contains credentials.@@ -30,9 +44,10 @@ export interface AIProviderConfig {/** Default multimodal model for Magic Layers analysis (v0.16 A1: overridable from /admin). */export const DEFAULT_VISION_MODEL = 'glm-4.5v'-// ── v0.16 (A1): model selection from the admin console ──────────-// Stored in AppConfig (ai.models), validated by src/lib/admin/config.ts.-// Undefined = let the SDK pick its own default — the pre-A1 behaviour.+// ── legacy model getters (v0.16 A1) ──────────────────────────+// Still used by the legacy fallback chain (ai.models feeds every slot+// that resolves via the single override / env / file). The multi-+// provider table carries its own per-slot model ids.export async function getTextModel(): Promise<string | undefined> {return (await getModels()).text@@ -47,16 +62,16 @@ export async function getImageModel(): Promise<string | undefined> {}/**- * Resolve the provider configuration.+ * Resolve the FILE-level provider config.* Priority: ZAI_BASE_URL/ZAI_API_KEY env vars → .z-ai-config file (cwd → ~ → /etc) → null.- * Returns null when no provider is configured (local-only mode).+ * Returns null when no provider is configured at this layer.*/export function resolveProviderConfig(): AIProviderConfig | null {const envUrl = process.env.ZAI_BASE_URL?.trim()const envKey = process.env.ZAI_API_KEY?.trim()if (envUrl && envKey) return { baseUrl: envUrl, apiKey: envKey }try {- // the SDK resolves the config file itself at ZAI.create(); mirror its lookup here+ // the SDK resolves the config file itself; mirror its lookup here//// PORTABILITY (v0.9.3): on Cloudflare Workers there is no real fs —// OpenNext's unenv layer stubs node:fs so these calls either return@@ -86,12 +101,100 @@ export function resolveProviderConfig(): AIProviderConfig | null {return null}+// ── per-slot resolution (v0.16.2 A2) ─────────────────────────++export type SlotSource = 'multi' | 'db' | 'env' | 'file'++/** What one capability slot resolved to — never the key, but enough to act. */+export interface ResolvedSlot {+ baseUrl: string+ apiKey: string+ /** Model id to request (undefined = provider default). */+ model?: string+ /** Which provider of the table answered (multi only). */+ providerId?: string+ /** Human label of the answering provider (multi only). */+ label?: string+ source: SlotSource+}++/**+ * Pure layer-picker (unit-tested): multi-provider table → legacy single+ * override → env vars → .z-ai-config file → null. Exported for tests;+ * runtime callers go through resolveSlot().+ */+export function pickSlot(+ slot: AiSlot,+ multi: StoredProviders | null,+ legacy: StoredProvider | null,+ models: StoredModels,+ env: { baseUrl?: string; apiKey?: string },+ file: StoredProvider | null+): ResolvedSlot | null {+ const tableSlot = multi?.slots[slot]+ if (multi && tableSlot) {+ const p = multi.providers.find((x) => x.id === tableSlot.providerId)+ if (p) {+ return {+ baseUrl: p.baseUrl,+ apiKey: p.apiKey,+ model: tableSlot.model,+ providerId: p.id,+ label: p.label,+ source: 'multi',+ }+ }+ // slot references a provider that no longer exists — fall through+ // to the legacy chain rather than failing the feature outright+ }+ // legacy chain: the single override / env / file answers every slot,+ // with the old ai.models ids still steering text/vision/image+ const legacyModel =+ slot === 'text' ? models.text : slot === 'vision' ? models.vision : slot === 'image' ? models.image : undefined+ if (legacy) return { baseUrl: legacy.baseUrl, apiKey: legacy.apiKey, model: legacyModel, source: 'db' }+ if (env.baseUrl && env.apiKey) {+ return { baseUrl: env.baseUrl, apiKey: env.apiKey, model: legacyModel, source: 'env' }+ }+ if (file) return { baseUrl: file.baseUrl, apiKey: file.apiKey, model: legacyModel, source: 'file' }+ return null+}++/** Resolve one capability slot through every config layer. */+export async function resolveSlot(slot: AiSlot): Promise<ResolvedSlot | null> {+ const [multi, legacy, models] = await Promise.all([getProviders(), getProviderOverride(), getModels()])+ return pickSlot(+ slot,+ multi,+ legacy,+ models,+ { baseUrl: process.env.ZAI_BASE_URL?.trim(), apiKey: process.env.ZAI_API_KEY?.trim() },+ resolveProviderConfig()+ )+}++/** Feature name (withProvider's first arg) → capability slot. */+const FEATURE_SLOTS: Record<string, AiSlot> = {+ write: 'text',+ translate: 'text',+ assistant: 'text',+ image: 'image',+ 'image-edit': 'imageEdit',+ 'magic-layers': 'vision',+ search: 'imageSearch',+}++/** Async probe — does THIS slot have a provider behind it? */+export async function hasProviderForSlot(slot: AiSlot): Promise<boolean> {+ return (await resolveSlot(slot)) !== null+}++// ── legacy single-chain resolution (v0.16 A1) ────────────────+// Kept for the console's legacy provider card and MCP capability text.+/*** Full resolution with provenance (v0.16 A1): console DB override → env- * vars → .z-ai-config file → null. The console-set override wins so an- * operator can point the instance at a different provider without a- * redeploy; `source` is surfaced in /admin (which layer answered —- * never the secret itself).+ * vars → .z-ai-config file → null. With the multi-provider table (A2)+ * this is the FALLBACK chain — resolveSlot() is what features use.*/export async function resolveProvider(): Promise<{ baseUrl: string; apiKey: string; source: 'db' | 'env' | 'file' } | null> {const fromDb = await getProviderOverride()@@ -104,38 +207,84 @@ export async function resolveProvider(): Promise<{ baseUrl: string; apiKey: strireturn null}-/** Async probe used by /api/ai/capabilities, MCP tools and route guards. */+/** Async probe used by MCP tools and route guards — any layer configured? */export async function hasProvider(): Promise<boolean> {- return (await resolveProvider()) !== null+ return (await resolveSlot('text')) !== null}-/**- * Create a ZAI SDK instance (server-side only). Lazy-imports the SDK so it- * never lands in a client bundle. Returns null when unconfigured.- */-export async function getZAI(): Promise<import('z-ai-web-dev-sdk').default | null> {- const cfg = await resolveProvider()- if (!cfg) return null- try {- // The SDK's ZAI.create() takes no arguments and resolves its own- // config from ZAI_BASE_URL/ZAI_API_KEY env or the .z-ai-config file- // (verified against the SDK's typings). A console-set (DB) provider- // is therefore injected through process.env before instantiation —- // server-side, in-memory, and exactly the variable the documented- // env setup uses, so the SDK keeps one consistent config surface.- // Decision recorded in docs/ADMIN.md.- if (cfg.source === 'db') {- process.env.ZAI_BASE_URL = cfg.baseUrl- process.env.ZAI_API_KEY = cfg.apiKey+/** What the console shows about the provider setup (never the key). */+export interface ProvidersSummary {+ configured: boolean+ source: SlotSource | null+ providerCount: number+ slotsSet: number+}+export async function providersSummary(): Promise<ProvidersSummary> {+ const multi = await getProviders()+ if (multi && multi.providers.length) {+ return {+ configured: true,+ source: 'multi',+ providerCount: multi.providers.length,+ slotsSet: Object.keys(multi.slots).length,}- const { default: ZAI } = await import('z-ai-web-dev-sdk')- return await ZAI.create()+ }+ const text = await resolveSlot('text')+ return { configured: text !== null, source: text?.source ?? null, providerCount: 0, slotsSet: 0 }+}++// ── SDK client construction ──────────────────────────────────++/** Construct an SDK client directly from resolved config (server-side only). */+export async function makeClient(baseUrl: string, apiKey: string): Promise<import('z-ai-web-dev-sdk').default> {+ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ // v0.16.2 (A2): construct the SDK DIRECTLY with the resolved config.+ //+ // ZAI.create() only ever reads a .z-ai-config file (cwd → ~ → /etc) —+ // it ignores ZAI_BASE_URL / ZAI_API_KEY entirely. Every console- or+ // env-configured provider therefore failed instantiation with+ // "Configuration file not found or invalid" — the bug behind every+ // failed "Test connection" (and every 503 AI feature) since A1 on+ // hosts that don't ship a config file. The class constructor takes+ // exactly the { baseUrl, apiKey } shape we already resolved, and any+ // OpenAI-compatible endpoint works through it. Decision recorded in+ // docs/ADMIN.md.+ //+ // The SDK's .d.ts marks the constructor private (it wants you on+ // create()), but the shipped dist/index.js declares a plain public+ // `constructor(config)` — verified against the installed package.+ // Cast to a constructor signature; the runtime shape matches.+ type ZAIConstructor = new (config: { baseUrl: string; apiKey: string }) => import('z-ai-web-dev-sdk').default+ const Ctor = ZAI as unknown as ZAIConstructor+ return new Ctor({ baseUrl, apiKey })+}++/** A usable client plus the model id its slot wants (undefined = default). */+export interface ProviderContext {+ zai: import('z-ai-web-dev-sdk').default+ model?: string+ /** Which provider answered (multi table only) — for accounting labels. */+ label?: string+}++/** Resolve a slot and construct its client. Null when unconfigured. */+export async function getClientForSlot(slot: AiSlot): Promise<ProviderContext | null> {+ const resolved = await resolveSlot(slot)+ if (!resolved) return null+ try {+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey)+ return { zai, model: resolved.model, label: resolved.label }} catch (err) {- console.error('[ai] provider initialization failed', err)+ console.error(`[ai] provider initialization failed (${slot})`, err)return null}}+/** Legacy helper — the text-slot client (MCP generate_design, older tests). */+export async function getZAI(): Promise<import('z-ai-web-dev-sdk').default | null> {+ return (await getClientForSlot('text'))?.zai ?? null+}+// ── rate limiting (in-memory sliding window; per feature+IP) ──interface Bucket {@@ -183,6 +332,8 @@ export function rateLimit(feature: string, req: Pick<NextRequest, 'headers'>, li// ── usage accounting (best-effort, never blocks a request) ──export async function recordUsage(feature: string, provider: 'zai' | 'local', ok: boolean): Promise<void> {+ // live console counters first — pure in-memory, synchronous, cannot throw+ recordLiveAi(feature, ok)try {const { db } = await import('@/lib/db')await db.aIUsage.create({ data: { feature, provider, ok } })@@ -203,18 +354,7 @@ export function providerUnavailable(res: NextResponse): NextResponse {return NextResponse.json(NO_PROVIDER_RESPONSE, { status: 503 })}-/** Helper: wrap a route's provider call with rate limit + usage accounting. */--/**- * v0.9.2 abuse guard — strict same-origin check for AI routes.- *- * Unlike the cookie-CSRF variant in lib/auth/csrf.ts (which lets- * Origin-less server-to-server calls through), AI generation is expensive- * metered compute that must ONLY be drivable from the app's own pages.- * Browsers always send Origin (or Referer) on POST — including same-origin- * fetch() — so anything without a matching Origin is a direct API bot and- * gets a flat 403 before any provider work happens.- */+/** v0.9.2 abuse guard — strict same-origin check for AI routes. */function isFromApp(req: NextRequest): boolean {const origin = req.headers.get('origin') ?? req.headers.get('referer')if (!origin) return false@@ -246,11 +386,18 @@ export const FEATURE_DISABLED = {code: 'FEATURE_DISABLED',} as const+/**+ * Wrap a route's provider work. Resolves the feature's capability slot,+ * constructs THAT provider's client and hands the handler a single+ * context: { zai, model } (v0.16.2 A2 — the handler no longer resolves+ * the model itself, so a per-slot provider+model pair can never drift+ * apart between the client and the model id).+ */export async function withProvider(feature: string,req: NextRequest,limits: { limit: number; windowSec: number },- fn: (zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>) => Promise<NextResponse>+ fn: (ctx: ProviderContext) => Promise<NextResponse>): Promise<NextResponse> {// v0.16 (A1): per-feature kill switch from the admin console. Checked// before the abuse guard, rate limiting and any provider work — a@@ -273,13 +420,14 @@ export async function withProvider({ status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } })}- const zai = await getZAI()- if (!zai) {+ const slot = FEATURE_SLOTS[feature] ?? 'text'+ const ctx = await getClientForSlot(slot)+ if (!ctx) {await recordUsage(feature, 'zai', false)return providerUnavailable(NextResponse.json({}))}try {- const out = await fn(zai)+ const out = await fn(ctx)void recordUsage(feature, 'zai', true)return out} catch (err) {diff --git a/src/lib/ai/slot-resolution.test.ts b/src/lib/ai/slot-resolution.test.tsnew file mode 100644index 0000000..0119b27--- /dev/null+++ b/src/lib/ai/slot-resolution.test.ts@@ -0,0 +1,94 @@+// Unit tests for per-slot provider resolution (v0.16.2 A2) — the pure+// pickSlot() layer-picker behind every AI feature. Precedence under+// test: multi-provider table → legacy single override → env vars →+// .z-ai-config file → null, with the legacy ai.models ids still+// steering the text/vision/image slots on the fallback chain.++import { describe, it, expect } from 'vitest'+import { pickSlot } from './provider'+import type { StoredProviders, StoredProvider } from '@/lib/admin/config'++const P1 = { id: 'pnvidia', label: 'NVIDIA NIM', baseUrl: 'https://integrate.api.nvidia.com/v1', apiKey: 'nvapi-1' }+const P2 = { id: 'pzai', label: 'Z.ai', baseUrl: 'https://api.z.ai/v1', apiKey: 'sk-2' }++function table(slots: StoredProviders['slots']): StoredProviders {+ return { providers: [P1, P2], slots }+}++describe('pickSlot (v0.16.2 A2)', () => {+ it('a slot pinned in the multi table resolves to that provider + model', () => {+ const out = pickSlot(+ 'text',+ table({ text: { providerId: 'pnvidia', model: 'meta/llama-3.1-70b-instruct' } }),+ null,+ {},+ {},+ null+ )+ expect(out).toEqual({+ baseUrl: P1.baseUrl,+ apiKey: P1.apiKey,+ model: 'meta/llama-3.1-70b-instruct',+ providerId: 'pnvidia',+ label: 'NVIDIA NIM',+ source: 'multi',+ })+ })++ it('different slots can point at different providers', () => {+ const t = table({+ text: { providerId: 'pnvidia', model: 'meta/llama-3.1-70b-instruct' },+ image: { providerId: 'pzai' },+ })+ const text = pickSlot('text', t, null, {}, {}, null)+ const image = pickSlot('image', t, null, {}, {}, null)+ expect(text?.baseUrl).toBe(P1.baseUrl)+ expect(text?.model).toBe('meta/llama-3.1-70b-instruct')+ expect(image?.baseUrl).toBe(P2.baseUrl)+ expect(image?.model).toBeUndefined() // no model = provider default+ })++ it('a slot whose providerId no longer exists falls back to the legacy chain', () => {+ const legacy: StoredProvider = { baseUrl: 'https://legacy.example/v1', apiKey: 'k' }+ const out = pickSlot('text', table({ text: { providerId: 'pgone' } }), legacy, { text: 'glm-4.6' }, {}, null)+ expect(out?.source).toBe('db')+ expect(out?.baseUrl).toBe('https://legacy.example/v1')+ expect(out?.model).toBe('glm-4.6')+ })++ it('unpinned slots fall back: legacy override wins over env and file', () => {+ const legacy: StoredProvider = { baseUrl: 'https://db.example/v1', apiKey: 'k' }+ const out = pickSlot('vision', table({ text: { providerId: 'pzai' } }), legacy, {}, { baseUrl: 'https://env.example', apiKey: 'e' }, { baseUrl: 'https://file.example', apiKey: 'f' })+ expect(out?.source).toBe('db')+ expect(out?.baseUrl).toBe('https://db.example/v1')+ })++ it('fallback chain: env beats file; file used when env incomplete', () => {+ const env = pickSlot('image', null, null, {}, { baseUrl: 'https://env.example', apiKey: 'e' }, { baseUrl: 'https://file.example', apiKey: 'f' })+ expect(env?.source).toBe('env')+ const file = pickSlot('image', null, null, {}, { baseUrl: 'https://env.example' }, { baseUrl: 'https://file.example', apiKey: 'f' })+ expect(file?.source).toBe('file')+ expect(file?.baseUrl).toBe('https://file.example')+ })++ it('legacy ai.models map onto matching slots of the fallback chain', () => {+ const models = { text: 'gpt-x', vision: 'glm-4.5v', image: 'cogview-3' }+ expect(pickSlot('text', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('gpt-x')+ expect(pickSlot('vision', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('glm-4.5v')+ expect(pickSlot('image', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBe('cogview-3')+ // imageEdit / imageSearch never had legacy model ids — provider default+ expect(pickSlot('imageEdit', null, { baseUrl: 'https://x', apiKey: 'k' }, models, {}, null)?.model).toBeUndefined()+ })++ it('nothing configured anywhere → null (feature reports unavailable)', () => {+ expect(pickSlot('text', null, null, {}, {}, null)).toBeNull()+ expect(pickSlot('imageSearch', table({}), null, {}, {}, null)).toBeNull()+ })++ it('the multi table does NOT rescue other slots — only pinned ones', () => {+ // text pinned, image not: with no legacy/env/file, image stays null+ const t = table({ text: { providerId: 'pzai' } })+ expect(pickSlot('text', t, null, {}, {}, null)).not.toBeNull()+ expect(pickSlot('image', t, null, {}, {}, null)).toBeNull()+ })+})diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.tsindex 422d8b3..1d61ae8 100644--- a/src/lib/mcp/tools.ts+++ b/src/lib/mcp/tools.ts@@ -11,7 +11,7 @@ import { FONTS } from '@/lib/editor-utils'import { isImageFilterId } from '@/lib/image-filters'import { exportPageToSVG } from '@/lib/svg-export'import { magicAnimatePage, clearPageAnimations } from '@/lib/animations'-import { hasProvider, getZAI, recordUsage, rateLimit } from '@/lib/ai/provider'+import { hasProvider, getClientForSlot, recordUsage, rateLimit } from '@/lib/ai/provider'import {createTextElement,createShapeElement,@@ -467,11 +467,11 @@ export function buildTools(deps: ToolDeps): ToolDef[] {handler: async (args) => {const query = asString(args.query).slice(0, 2000)if (query.length < 4) return fail('Provide a design brief ("query"), e.g. "Instagram post for a coffee shop launch — warm palette".')- const zai = await getZAI()- if (!zai) {+ const ctx = await getClientForSlot('text')+ if (!ctx) {await recordUsage('assistant', 'local', false).catch(() => undefined)return fail(- 'generate_design requires an AI provider configured on the server (set ZAI_API_KEY or a .z-ai-config file). ' ++ 'generate_design requires an AI provider configured on the server (add one in /admin, set ZAI_API_KEY, or ship a .z-ai-config file). ' +'Without a provider you can still create designs from templates: list_templates → create_design → add_text/add_shape.')}@@ -497,7 +497,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {].join('\n')try {- const raw = await completeGeneration(zai, system, `Design brief: ${query}\nPage size: ${width}x${height}px`)+ const raw = await completeGeneration(ctx, system, `Design brief: ${query}\nPage size: ${width}x${height}px`)if (!raw) return fail('The AI reply was not parseable JSON after one retry. Try rephrasing the brief.')const parsed = raw as Record<string, unknown>const spec = normalizeGeneratedDesign(parsed, width, height)@@ -1337,7 +1337,7 @@ function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: nu/** Ask the model for the design JSON; repair common JSON flaws and retry once. */async function completeGeneration(- zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>,+ ctx: NonNullable<Awaited<ReturnType<typeof getClientForSlot>>>,system: string,user: string): Promise<Record<string, unknown> | null> {@@ -1348,14 +1348,16 @@ async function completeGeneration(]// strict JSON mode (supported by the provider); fall back to plain text on errortry {- const completion = await zai.chat.completions.create({+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),messages,thinking: { type: 'disabled' },response_format: { type: 'json_object' },} as never)return completion.choices[0]?.message?.content ?? ''} catch {- const completion = await zai.chat.completions.create({+ const completion = await ctx.zai.chat.completions.create({+ ...(ctx.model ? { model: ctx.model } : {}),messages,thinking: { type: 'disabled' },})diff --git a/src/lib/observability.ts b/src/lib/observability.tsindex 54d2d96..b1ba986 100644--- a/src/lib/observability.ts+++ b/src/lib/observability.ts@@ -94,11 +94,50 @@ function countTraffic(name: string, method: string, status: number): void {.catch(() => {})}+// ── live traffic (v0.16.2 A2) ───────────────────────────+//+// src/lib/admin/realtime.ts is ZERO-import, db-free and edge-safe, so+// unlike the DB counters above it can be linked statically without+// dragging anything into the edge instrumentation bundle. It powers+// GET /api/admin/realtime (the console's live panel): per-second+// request/error buckets, per-route minutes, hashed visitors and a+// latency ring — all in-memory, all bounded (see that module's header).+import { recordLiveRequest } from '@/lib/admin/realtime'++/** Per-boot salt for visitor hashing — resets each restart, keeps the+ * hash non-guessable across boots without storing anything. */+const VISITOR_SALT = Math.random().toString(36).slice(2)++/**+ * Privacy-preserving visitor key for the live counters: the client IP+ * (first x-forwarded-for hop) hashed with the per-boot salt — djb2 is+ * not a privacy boundary, but the raw IP is never stored anywhere and+ * the key only ever feeds a COUNT. No IP → 'local' (on-host proxy).+ */+export function liveVisitorKey(req: Pick<NextRequest, 'headers'>): string {+ const ip =+ req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||+ req.headers.get('x-real-ip') ||+ ''+ if (!ip) return 'local'+ let h = 5381+ const mixed = VISITOR_SALT + ip+ for (let i = 0; i < mixed.length; i++) h = ((h << 5) + h + mixed.charCodeAt(i)) >>> 0+ return 'v' + h.toString(36)+}++/** The live panel's own poll — excluded from the live counters so the+ * dashboard's 2-second refresh never becomes the busiest "route". */+function isRealtimeSelfPoll(name: string): boolean {+ return name.includes('/api/admin/realtime')+}+/*** Wrap an API route handler with opt-in request logging AND always-on* aggregate traffic counters (v0.16 A1 — CANVIX_TRAFFIC=0 opts out;- * counts only, never ids/IPs/query strings). The stdout log side stays- * a zero-cost passthrough when CANVIX_LOG is unset (the default): the+ * counts only, never ids/IPs/query strings) plus the live in-memory+ * counters behind the console's real-time panel (v0.16.2 A2). The+ * stdout log side stays a zero-cost passthrough when CANVIX_LOG is unset (the default): the* wrapper checks once per call and never touches the response otherwise.* Never mutates the response — the handler's headers, streams and* status codes pass through untouched (the SSE route included).@@ -124,6 +163,9 @@ export function withLogging<A extends unknown[]>(})}countTraffic(name, req.method, res.status)+ if (!isRealtimeSelfPoll(name)) {+ recordLiveRequest(name, res.status, now() - start, liveVisitorKey(req))+ }return res} catch (error) {if (requestLoggingEnabled()) {@@ -135,6 +177,9 @@ export function withLogging<A extends unknown[]>(})}countTraffic(name, req.method, 500)+ if (!isRealtimeSelfPoll(name)) {+ recordLiveRequest(name, 500, now() - start, liveVisitorKey(req))+ }throw error}}