Skip to content

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.

feat(v0.16.3): admin Logs view, per-slot provider diagnostics, AI failure reasons (A3) (#41)

Ashiq Hussain Mirbaf9f6d7f386
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97c178d..3479067 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,49 @@
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.3] — 2026-11-07
+
+### Added
+
+- **Admin Logs view (`/admin/logs`) — "why did the AI feature fail?"
+ finally answerable from the console.** Every AI request through
+ `withProvider` now writes a durable telemetry row (AIUsage, extended
+ by migration `0010_ai_request_log`): feature, provider, model,
+ outcome status, round-trip duration and a scrubbed failure reason —
+ every outcome recorded, not just successes: provider failures carry
+ the provider's HTTP status, and the guard exits are logged with
+ their codes (403 rejected · 429 rate-limited · 503 disabled or
+ unconfigured, slot named). The page leads with a slot-status strip
+ (what each of the five capability slots resolves to right now), then
+ the request log with live tail (5 s, pauses on hidden tabs), window /
+ feature / outcome filters and per-feature call/error counters. Rows
+ are swept after 90 days like TrafficStat.
+- **Per-slot "Test" buttons on the AI & models page.** The A2 test
+ connection only proved chat worked — a chat-only provider (NVIDIA NIM
+ et al.) passed every test while image generation 404'd in production,
+ which is exactly the incident that prompted this release. Each slot
+ is now probed through the endpoint it actually uses: text/vision via
+ a minimal chat completion, image via a real minimal generation,
+ imageEdit via a deliberately image-less probe (a 400-class "must
+ provide images" answer PROVES the endpoint exists, costlessly),
+ imageSearch via a one-result search. Verdicts explain themselves —
+ a 404 says "this provider does not serve image generation; pin those
+ slots to a provider that does". Every slot row also shows the
+ endpoint path it exercises.
+
+### Fixed
+
+- **AI failure responses now carry the reason.** The 502 body from AI
+ routes includes `code: "PROVIDER_ERROR"` and a scrubbed `detail`
+ ("404 page not found (HTTP 404)") — the same string the Logs view
+ shows, so end users and the admin see one truth. Credential-shaped
+ tokens (nvapi-/sk-/Bearer…) are masked before anything is logged or
+ returned.
+- **OpenAI-style `b64_json` image responses work.** The SDK passes
+ non-URL items through untouched, and the image/image-edit routes only
+ read `data[0].base64` — providers answering `b64_json` (the OpenAI
+ shape) returned "no image". Both routes now accept either field.
+
## [0.16.2] — 2026-11-07
### Fixed
diff --git a/docs/ADMIN.md b/docs/ADMIN.md
index 8e869f6..1fdf92b 100644
--- a/docs/ADMIN.md
+++ b/docs/ADMIN.md
@@ -1,4 +1,4 @@
-# Admin console (v0.16 A1 · v0.16.2 A2)
+# Admin console (v0.16 A1 · v0.16.2 A2 · v0.16.3 A3)
> **TL;DR** — set `CANVIX_ADMIN_USERS="your-username"`, restart, sign in:
> the shield icon on the dashboard opens `/admin`. Everything below is
@@ -130,6 +130,34 @@ 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).
+### Logs
+
+`/admin/logs` (v0.16.3 A3) answers "why isn't the AI feature working"
+without an SSH session. Two surfaces:
+
+- **AI slot status** — what each of the five capability slots (`text`,
+ `vision`, `image`, `imageEdit`, `imageSearch`) resolves to right now:
+ provider label, base URL, model id and which config layer answered
+ (providers table / legacy override / env / file). Never the key. A
+ slot wired to a chat-only provider is the classic silent breakage —
+ text features work, image generation 404s on the same key — and the
+ strip makes the wiring visible before anything is even tried.
+- **AI request log** — one row per AI request (the AIUsage table, see
+ §3): feature, provider · model, outcome chip (200-299 green;
+ 403 rejected · 429 rate-limited · 503 unconfigured · provider HTTP
+ code red), round-trip duration and the scrubbed failure reason — the
+ same string the client's 502 body carries (one truth, two audiences).
+ Live tail (5 s poll, pauses when the tab is hidden), window (15 m …
+ 7 d), feature and outcome filters, per-feature call/error counters.
+
+The per-slot **Test** buttons on the AI & models page probe the real
+endpoint each slot uses (chat completion for text/vision, a real
+minimal generation for image, a deliberately image-less probe for
+imageEdit — a 400-class rejection proves the endpoint exists — and a
+one-result search for imageSearch). A 404 verdict states the fix:
+chat-only providers cannot run image slots; pin them to a provider
+that serves image endpoints.
+
### Settings
- **Allow new sign-ups** — off means `POST /api/auth/register` answers
@@ -280,7 +308,28 @@ probes that provider; `model` overrides the model for the probe.
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`)
+
+- **D14 (A3) — the AI request log lives IN AIUsage, not a new table.**
+ One row per AI request was already being written; the Logs view only
+ needed the columns (model/status/durationMs/error, all nullable,
+ migration `0010_ai_request_log`). No second write path, no join, no
+ new retention policy — 90 days, swept lazily like TrafficStat.
+- **D15 (A3) — provider error text is scrubbed, capped and shared.**
+ `describeProviderError()` extracts the HTTP status, masks
+ credential-shaped tokens (nvapi-/sk-/Bearer…), collapses whitespace
+ and caps at 240 chars. The same string flows to AIUsage (`error`),
+ the client 502 body (`detail`) and the console — no place shows a
+ raw provider body, and no place shows different truths.
+- **D16 (A3) — slot tests probe real endpoints, classified by verdict.**
+ A chat-only provider passing the old test while image generation
+ 404'd was the diagnostic gap; now a 404/405 verdict says "not
+ served — pin image slots to a provider that serves image endpoints",
+ a 401/403 says "check the key", and a 400-class answer to the
+ deliberately-empty imageEdit probe says "reachable". The image slot
+ does a REAL minimal generation — the only full proof; on providers
+ without the endpoint it 404s instantly and costs nothing.
+
+## 6. Database changes (migration `0009_admin_console`, extended by `0010_ai_request_log`)
```sql
ALTER TABLE "User" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'user';
@@ -292,3 +341,11 @@ CREATE TABLE "DailyActive" (… UNIQUE(day, actor));
`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.
+
+### `0010_ai_request_log` (v0.16.3 A3)
+
+Four nullable columns on `AIUsage` — `model`, `status`, `durationMs`,
+`error` — written by `withProvider` for every outcome. Existing rows
+stay valid (nulls read as "not recorded"); rows are swept after 90
+days. Instances that never open `/admin/logs` accumulate exactly what
+they always did.
diff --git a/package-lock.json b/package-lock.json
index c448e63..f251b07 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "canvix",
- "version": "0.16.1",
+ "version": "0.16.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "canvix",
- "version": "0.16.1",
+ "version": "0.16.3",
"hasInstallScript": true,
"dependencies": {
"@imgly/background-removal": "^1.7.0",
diff --git a/package.json b/package.json
index 276581f..8648745 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "canvix",
- "version": "0.16.2",
+ "version": "0.16.3",
"private": false,
- "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
+ "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "node scripts/build.mjs",
diff --git a/prisma/migrations/0010_ai_request_log/migration.sql b/prisma/migrations/0010_ai_request_log/migration.sql
new file mode 100644
index 0000000..d962b16
--- /dev/null
+++ b/prisma/migrations/0010_ai_request_log/migration.sql
@@ -0,0 +1,13 @@
+-- v0.16.3 (A3): AI request log — the durable record behind /admin/logs.
+-- AIUsage gains the columns the Logs view reads: the model id the slot
+-- requested, the outcome status (HTTP code from the provider on
+-- failures, or the guard-exit code: 403 rejected / 429 rate-limited /
+-- 503 disabled-or-unconfigured), the provider round-trip duration and
+-- a short scrubbed error reason. All nullable — existing rows stay
+-- valid, and instances that never open /admin simply accumulate the
+-- same telemetry they already did (swept after 90 days like TrafficStat).
+
+ALTER TABLE "AIUsage" ADD COLUMN "model" TEXT;
+ALTER TABLE "AIUsage" ADD COLUMN "status" INTEGER;
+ALTER TABLE "AIUsage" ADD COLUMN "durationMs" INTEGER;
+ALTER TABLE "AIUsage" ADD COLUMN "error" TEXT;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 655a16f..ec00c64 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -241,13 +241,22 @@ model Media {
@@index([ownerId, keepInLibrary])
}
-// Provider accounting + abuse telemetry for AI routes.
+// Provider accounting + request telemetry for AI routes (v0.16.3 A3
+// extends it into the admin Logs view). One row per AI request through
+// withProvider, every outcome recorded — success, provider failure
+// (with the scrubbed reason), no-provider, feature-disabled, rate-
+// limited and rejected. `error` carries a short, key-scrubbed
+// provider message; credentials never reach this table.
model AIUsage {
- id String @id @default(cuid())
- feature String // write | image | image-edit | translate | assistant | magic-layers | search
- provider String // zai | local
- ok Boolean @default(true)
- createdAt DateTime @default(now())
+ id String @id @default(cuid())
+ feature String // write | image | image-edit | translate | assistant | magic-layers | search
+ provider String // multi-table label | db | env | file
+ ok Boolean @default(true)
+ model String? // model id the slot requested (null = provider default)
+ status Int? // outcome: 200-299 ok · 403/429/503 guard exits · provider HTTP code on failure
+ durationMs Int? // provider round-trip
+ error String? // scrubbed, capped failure reason
+ createdAt DateTime @default(now())
@@index([createdAt])
}
diff --git a/src/app/admin/logs/page.tsx b/src/app/admin/logs/page.tsx
new file mode 100644
index 0000000..ae04270
--- /dev/null
+++ b/src/app/admin/logs/page.tsx
@@ -0,0 +1,9 @@
+import { AdminLogs } from '@/components/admin/logs'
+
+// /admin/logs (v0.16.3 A3) — AI request log + slot status. The layout
+// already gated this path to admins server-side; the API re-checks.
+export const dynamic = 'force-dynamic'
+
+export default function AdminLogsPage() {
+ return <AdminLogs />
+}
diff --git a/src/app/api/admin/config/ai-test/route.ts b/src/app/api/admin/config/ai-test/route.ts
index 20ad2cb..5d80b86 100644
--- a/src/app/api/admin/config/ai-test/route.ts
+++ b/src/app/api/admin/config/ai-test/route.ts
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/admin/guard'
import { getProviders, AI_SLOTS } from '@/lib/admin/config'
import { resolveSlot, makeClient, rateLimit, type ResolvedSlot } from '@/lib/ai/provider'
+import { probeSlot, classifyProbeError, SLOT_ENDPOINT } from '@/lib/ai/probe'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { withLogging } from '@/lib/observability'
@@ -20,10 +21,27 @@ export const dynamic = 'force-dynamic'
// { 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).
+// v0.16.3 (A3) adds per-SLOT probing — the diagnostic gap behind "test
+// says OK but the feature is broken": a chat-only provider (NVIDIA NIM
+// et al.) passes every text test yet cannot serve image generation,
+// because it simply has no POST /v1/images/generations route. Body:
+// { slot: "image" | "imageEdit" | "imageSearch" | "text" | "vision" }
+//
+// text / vision → one minimal chat completion (the existing probe).
+// image → a REAL minimal generation — the only full proof;
+// on providers without the endpoint it 404s instantly
+// and costs nothing.
+// imageEdit → minimal probe against /images/generations/edit with
+// no input image — a 400-class "must provide images"
+// answer PROVES the endpoint exists (zero cost); 404
+// means the provider cannot run this slot.
+// imageSearch → one tiny search (count 1); 404 = not served.
+//
+// Verdicts classify the provider's answer so the console can say WHY,
+// not just "failed". 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
@@ -100,6 +118,58 @@ async function __canvix_post(req: NextRequest) {
}
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>
+
+ // v0.16.3 (A3): per-slot probe — test the ENDPOINT the slot uses,
+ // not just chat. { slot } resolves that slot's provider+model
+ // through the full chain (multi table → legacy → env → file).
+ const slotProbe = typeof body.slot === 'string' ? body.slot.trim() : null
+ if (slotProbe) {
+ if (!(slotProbe in SLOT_ENDPOINT)) {
+ return NextResponse.json({ ok: false, error: 'Unknown slot — use text, vision, image, imageEdit or imageSearch.' }, { status: 400 })
+ }
+ const resolved = await resolveSlot(slotProbe as 'text' | 'vision' | 'image' | 'imageEdit' | 'imageSearch')
+ if (!resolved) {
+ return NextResponse.json(
+ { ok: false, error: `The ${slotProbe} slot has no provider — pin one on the AI & models page.` },
+ { status: 503 }
+ )
+ }
+ const modelOverride = typeof body.model === 'string' && body.model.trim() ? body.model.trim() : null
+ const target: TestTarget = {
+ baseUrl: resolved.baseUrl,
+ apiKey: resolved.apiKey,
+ model: modelOverride ?? resolved.model,
+ label: resolved.label ?? resolved.source,
+ source: resolved.source,
+ }
+ try {
+ const out = await probeSlot(slotProbe, target)
+ return NextResponse.json({
+ ok: out.verdict.ok,
+ slot: out.verdict.slot,
+ endpoint: out.verdict.endpoint,
+ providerLabel: target.label,
+ model: target.model ?? 'sdk-default',
+ httpStatus: out.verdict.httpStatus,
+ message: out.verdict.message,
+ ...(out.reply ? { reply: out.reply } : {}),
+ })
+ } catch (error) {
+ // probeSlot catches provider errors itself; this is only for the
+ // unexpected (client construction, timeouts before the race)
+ const verdict = classifyProbeError(slotProbe, error)
+ return NextResponse.json({
+ ok: false,
+ slot: verdict.slot,
+ endpoint: verdict.endpoint,
+ providerLabel: target.label,
+ model: target.model ?? 'sdk-default',
+ httpStatus: verdict.httpStatus,
+ message: verdict.message,
+ })
+ }
+ }
+
const target = await resolveTarget(body)
if (!target.ok) return target.res
diff --git a/src/app/api/admin/logs/route.ts b/src/app/api/admin/logs/route.ts
new file mode 100644
index 0000000..61e946b
--- /dev/null
+++ b/src/app/api/admin/logs/route.ts
@@ -0,0 +1,60 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { requireAdmin } from '@/lib/admin/guard'
+import { resolveSlot } from '@/lib/ai/provider'
+import { parseLogWindow, parseOutcome, parseLimit, queryAiLogs } from '@/lib/admin/logs'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET /api/admin/logs — the console's Logs view (v0.16.3 A3).
+//
+// Two payloads in one response:
+// slots — what each of the five capability slots currently resolves
+// to (provider label, base URL, model, config source) or
+// null when unconfigured. Never the key — resolveSlot's
+// apiKey is dropped before serialization.
+// log — recent AI request rows from AIUsage with filters:
+// ?window=15m|1h|6h|24h|7d (default 24h)
+// ?feature=assistant|write|translate|image|image-edit|magic-layers|search
+// ?outcome=all|errors|ok (default all)
+// ?limit=20..400 (default 150)
+//
+// The Logs page polls this every few seconds when live-tailing; the
+// poll itself is a plain admin GET, excluded from nothing — it is
+// cheap (indexed createdAt range + groupBy) and admin-only.
+
+const SLOT_ORDER = ['text', 'vision', 'image', 'imageEdit', 'imageSearch'] as const
+
+async function __canvix_get(req: NextRequest) {
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ const q = req.nextUrl.searchParams
+ const log = await queryAiLogs({
+ window: parseLogWindow(q.get('window')),
+ feature: q.get('feature'),
+ outcome: parseOutcome(q.get('outcome')),
+ limit: parseLimit(q.get('limit')),
+ })
+
+ const slots = await Promise.all(
+ SLOT_ORDER.map(async (slot) => {
+ const r = await resolveSlot(slot)
+ if (!r) return { slot, configured: false as const }
+ return {
+ slot,
+ configured: true as const,
+ providerId: r.providerId ?? null,
+ label: r.label ?? null,
+ baseUrl: r.baseUrl,
+ model: r.model ?? null,
+ source: r.source,
+ }
+ })
+ )
+
+ return NextResponse.json({ log, slots })
+}
+
+export const GET = withLogging('GET /api/admin/logs', __canvix_get)
diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.ts
index c206d80..74900b9 100644
--- a/src/app/api/ai/image-edit/route.ts
+++ b/src/app/api/ai/image-edit/route.ts
@@ -81,7 +81,10 @@ async function __canvix_post(req: NextRequest) {
size,
} as unknown as Parameters<typeof ctx.zai.images.generations.edit>[0])
- const base64 = response.data[0]?.base64
+ // v0.16.3 (A3): OpenAI-compatible providers return b64_json; the SDK
+ // passes such items through untouched (it only converts url items).
+ const item = response.data[0] as { base64?: string; b64_json?: string } | undefined
+ const base64 = item?.base64 ?? item?.b64_json
if (!base64) {
return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })
}
diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.ts
index 9ba031f..3bad465 100644
--- a/src/app/api/ai/image/route.ts
+++ b/src/app/api/ai/image/route.ts
@@ -32,7 +32,10 @@ async function __canvix_post(req: NextRequest) {
size,
})
- const base64 = response.data[0]?.base64
+ // v0.16.3 (A3): OpenAI-compatible providers return b64_json; the SDK
+ // passes such items through untouched (it only converts url items).
+ const item = response.data[0] as { base64?: string; b64_json?: string } | undefined
+ const base64 = item?.base64 ?? item?.b64_json
if (!base64) {
return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })
}
diff --git a/src/components/admin/AdminShell.tsx b/src/components/admin/AdminShell.tsx
index 1db2868..b679545 100644
--- a/src/components/admin/AdminShell.tsx
+++ b/src/components/admin/AdminShell.tsx
@@ -3,7 +3,7 @@
import { usePathname } from 'next/navigation'
import Link from 'next/link'
import type { ReactNode } from 'react'
-import { LayoutDashboard, Users, Sparkles, Settings, ArrowLeft } from 'lucide-react'
+import { LayoutDashboard, Users, Sparkles, Settings, ScrollText, ArrowLeft } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Logo } from '@/components/logo'
@@ -11,6 +11,7 @@ const NAV = [
{ href: '/admin', label: 'Overview', icon: LayoutDashboard, exact: true },
{ href: '/admin/users', label: 'Users', icon: Users, exact: false },
{ href: '/admin/ai', label: 'AI & models', icon: Sparkles, exact: false },
+ { href: '/admin/logs', label: 'Logs', icon: ScrollText, exact: false },
{ href: '/admin/settings', label: 'Settings', icon: Settings, exact: false },
] as const
diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsx
index c0b1c5a..b15e232 100644
--- a/src/components/admin/ai-config.tsx
+++ b/src/components/admin/ai-config.tsx
@@ -100,6 +100,24 @@ interface TestState {
message: string
}
+/** Per-slot probe result (A3) — the verdict says WHY, not just pass/fail. */
+interface SlotTestState {
+ slot: string
+ ok: boolean
+ message: string
+ busy?: boolean
+}
+
+/** The endpoint each slot exercises — shown next to the slot so the
+ * provider-fit question ("can NVIDIA generate images?") answers itself. */
+const SLOT_ENDPOINT: Record<string, string> = {
+ text: 'chat/completions',
+ vision: 'chat/completions',
+ image: 'images/generations',
+ imageEdit: 'images/generations/edit',
+ imageSearch: 'images/search',
+}
+
export function AdminAiConfig() {
const [view, setView] = useState<ConfigView | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -195,6 +213,28 @@ export function AdminAiConfig() {
}
}
+ const [slotTest, setSlotTest] = useState<SlotTestState | null>(null)
+
+ /** Probe the ENDPOINT the slot actually uses (A3) — a chat-only
+ * provider passes the text test but cannot generate images. */
+ async function testSlot(slot: string) {
+ setSlotTest({ slot, ok: true, busy: true, message: 'probing…' })
+ const res = await sendJson<{ ok: boolean; endpoint?: string; providerLabel?: string; message?: string; reply?: string; error?: string }>(
+ '/api/admin/config/ai-test',
+ 'POST',
+ { slot }
+ )
+ if (res.ok && res.data.ok) {
+ setSlotTest({
+ slot,
+ ok: true,
+ message: `${res.data.providerLabel ?? 'Provider'} · ${res.data.message}${res.data.reply ? ` “${res.data.reply.slice(0, 60)}”` : ''}`,
+ })
+ } else {
+ setSlotTest({ slot, ok: false, message: res.data.message ?? res.data.error ?? `Test failed (${res.status})` })
+ }
+ }
+
useEffect(() => {
getJson<ConfigView>('/api/admin/config').then((res) => {
if (res.ok) {
@@ -375,6 +415,7 @@ export function AdminAiConfig() {
<div>
<p className="text-sm font-medium">{s.label}</p>
<p className="text-xs text-muted-foreground">{s.hint}</p>
+ <p className="mt-0.5 font-mono text-[11px] text-muted-foreground">uses {SLOT_ENDPOINT[s.key]}</p>
</div>
<label className="text-xs">
<span className="mb-1 block font-medium">Provider</span>
@@ -405,6 +446,21 @@ export function AdminAiConfig() {
: '→ not configured (feature reports unavailable)'}
</span>
</label>
+ <div className="flex items-end sm:col-start-3">
+ <button
+ onClick={() => void testSlot(s.key)}
+ disabled={busy || slotTest?.busy === true}
+ title={`Probe the real ${SLOT_ENDPOINT[s.key]} endpoint this slot uses`}
+ 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 {s.label.toLowerCase()}
+ </button>
+ </div>
+ {slotTest && slotTest.slot === s.key && !slotTest.busy && (
+ <p className={`sm:col-span-3 text-sm ${slotTest.ok ? 'text-emerald-600' : 'text-destructive'}`}>
+ {slotTest.message}
+ </p>
+ )}
</div>
)
})}
diff --git a/src/components/admin/logs.tsx b/src/components/admin/logs.tsx
new file mode 100644
index 0000000..d87a170
--- /dev/null
+++ b/src/components/admin/logs.tsx
@@ -0,0 +1,371 @@
+'use client'
+
+// Logs view (v0.16.3 A3) — the "why did the AI feature fail" page.
+//
+// Two surfaces:
+// Slot status — what each of the five AI capability slots resolves
+// to right now (provider, model, config source). A slot wired to a
+// chat-only provider is the classic silent breakage: text features
+// work, image generation 404s. The strip makes the wiring visible
+// before anything is even tried.
+//
+// Request log — one row per AI request (AIUsage via
+// /api/admin/logs): feature, provider, model, outcome status,
+// round-trip duration and — the point of the page — the scrubbed
+// error reason, the same string the client's 502 body carries.
+// Live tail (5 s, pauses when the tab hides), window / feature /
+// outcome filters, and per-feature call/error counters.
+
+import { useEffect, useRef, useState } from 'react'
+import { RefreshCw } from 'lucide-react'
+import { getJson } from './fetch'
+import { Card, Chip } from './bits'
+
+interface AiLogRow {
+ id: string
+ createdAt: string
+ feature: string
+ provider: string
+ model: string | null
+ ok: boolean
+ status: number | null
+ durationMs: number | null
+ error: string | null
+}
+interface AiLogCounts {
+ total: number
+ errors: number
+ byFeature: Record<string, { calls: number; errors: number }>
+}
+interface SlotView {
+ slot: string
+ configured: boolean
+ providerId?: string | null
+ label?: string | null
+ baseUrl?: string
+ model?: string | null
+ source?: string
+}
+interface LogsView {
+ log: { window: string; rows: AiLogRow[]; counts: AiLogCounts }
+ slots: SlotView[]
+}
+
+const POLL_MS = 5000
+
+const SLOT_LABEL: Record<string, string> = {
+ text: 'Text',
+ vision: 'Vision',
+ image: 'Image generation',
+ imageEdit: 'Image editing',
+ imageSearch: 'Photo search',
+}
+const SLOT_FEATURES: Record<string, string> = {
+ text: 'Magic Write · Translate · Assistant',
+ vision: 'Magic Layers',
+ image: 'Photos panel → Generate',
+ imageEdit: 'Magic Eraser · Enhance · BG remove',
+ imageSearch: 'Photos panel → Search',
+}
+const SOURCE_LABEL: Record<string, string> = {
+ multi: 'providers table',
+ db: 'legacy override',
+ env: 'environment variables',
+ file: '.z-ai-config file',
+}
+const WINDOWS = ['15m', '1h', '6h', '24h', '7d'] as const
+const FEATURES = ['assistant', 'write', 'translate', 'image', 'image-edit', 'magic-layers', 'search'] as const
+
+function fmtTime(iso: string): string {
+ const d = new Date(iso)
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
+}
+function fmtDay(iso: string): string {
+ const d = new Date(iso)
+ return d.toLocaleDateString([], { month: 'short', day: 'numeric' })
+}
+function fmtMs(ms: number | null): string {
+ if (ms === null || ms === undefined) return '—'
+ if (ms < 1000) return `${ms} ms`
+ return `${(ms / 1000).toFixed(1)} s`
+}
+
+/** Status chip: 2xx green, 4xx amber, 5xx/none red for AI rows. */
+function StatusChip({ ok, status }: { ok: boolean; status: number | null }) {
+ if (ok) return <Chip tone="good">{status ?? 'ok'}</Chip>
+ if (status === 429) return <Chip tone="bad">429 · rate limit</Chip>
+ if (status === 403) return <Chip tone="bad">403 · rejected</Chip>
+ if (status === 503) return <Chip tone="bad">503 · unconfigured</Chip>
+ return <Chip tone="bad">{status ?? 'failed'}</Chip>
+}
+
+export function AdminLogs() {
+ const [data, setData] = useState<LogsView | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [stale, setStale] = useState(false)
+ const [paused, setPaused] = useState(false)
+ const [live, setLive] = useState(true)
+ const [busy, setBusy] = useState(false)
+
+ const [window, setWindow] = useState<(typeof WINDOWS)[number]>('24h')
+ const [feature, setFeature] = useState<string>('')
+ const [outcome, setOutcome] = useState<'all' | 'errors' | 'ok'>('all')
+
+ const liveRef = useRef(true)
+ const aliveRef = useRef(true)
+
+ async function fetchOnce(): Promise<boolean> {
+ const params = new URLSearchParams({ window, outcome, limit: '150' })
+ if (feature) params.set('feature', feature)
+ const res = await getJson<LogsView>(`/api/admin/logs?${params.toString()}`)
+ if (!aliveRef.current) return false
+ if (res.ok) {
+ setData(res.data)
+ setError(null)
+ setStale(false)
+ return true
+ }
+ setError(res.data?.error ?? `Request failed (${res.status})`)
+ setStale(true)
+ return false
+ }
+
+ // refetch on filter change (silently — the live loop keeps the data warm;
+ // deferred a tick so no setState runs synchronously inside the effect)
+ useEffect(() => {
+ aliveRef.current = true
+ liveRef.current = live
+ const t = setTimeout(() => void fetchOnce(), 0)
+ return () => {
+ aliveRef.current = false
+ clearTimeout(t)
+ }
+ }, [window, feature, outcome])
+
+ // live tail loop
+ 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)
+ if (liveRef.current) {
+ await fetchOnce()
+ }
+ 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)
+ }
+ }, [])
+
+ async function refreshNow() {
+ setBusy(true)
+ await fetchOnce()
+ setBusy(false)
+ }
+
+ const counts = data?.log.counts
+ const rows = data?.log.rows ?? []
+ const errorRate = counts && counts.total > 0 ? Math.round((counts.errors / counts.total) * 100) : 0
+
+ return (
+ <>
+ {/* ── slot status ── */}
+ <Card
+ title="AI slot status"
+ right={<Chip tone={data && data.slots.some((s) => s.configured) ? 'good' : 'bad'}>{data ? `${data.slots.filter((s) => s.configured).length}/5 wired` : '…'}</Chip>}
+ >
+ <p className="mb-4 text-sm text-muted-foreground">
+ What each AI capability resolves to right now. A slot on a provider that does not serve its endpoint is the
+ usual reason a feature &ldquo;silently&rdquo; fails — text can work on a chat-only provider while image
+ generation 404s on the very same key. Configure providers and slots on the{' '}
+ <a href="/admin/ai" className="underline underline-offset-2">
+ AI &amp; models
+ </a>{' '}
+ page.
+ </p>
+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {(data?.slots ?? []).map((s) => (
+ <div key={s.slot} className="rounded-xl border p-3">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm font-medium">{SLOT_LABEL[s.slot] ?? s.slot}</p>
+ {s.configured ? <Chip tone="good">wired</Chip> : <Chip tone="bad">not configured</Chip>}
+ </div>
+ <p className="mt-1 text-xs text-muted-foreground">{SLOT_FEATURES[s.slot] ?? ''}</p>
+ {s.configured ? (
+ <p className="mt-2 break-all font-mono text-xs">
+ {s.label ?? s.baseUrl}
+ <br />
+ <span className="text-muted-foreground">
+ {s.model ?? 'provider default'} · {SOURCE_LABEL[s.source ?? ''] ?? s.source}
+ </span>
+ </p>
+ ) : (
+ <p className="mt-2 text-xs text-muted-foreground">feature reports unavailable</p>
+ )}
+ </div>
+ ))}
+ {!data && <div className="h-20 animate-pulse rounded-xl bg-muted" />}
+ </div>
+ </Card>
+
+ {/* ── request log ── */}
+ <Card
+ title={
+ <span className="inline-flex items-center gap-2">
+ AI request log
+ {live && (
+ <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={
+ counts ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <Chip>{counts.total} calls</Chip>
+ <Chip tone={counts.errors > 0 ? 'bad' : 'good'}>
+ {counts.errors} errors · {errorRate}%
+ </Chip>
+ </div>
+ ) : undefined
+ }
+ >
+ <div className="mb-4 flex flex-wrap items-center gap-2">
+ <label className="text-xs">
+ <span className="sr-only">Window</span>
+ <select
+ value={window}
+ onChange={(e) => setWindow(e.target.value as (typeof WINDOWS)[number])}
+ className="h-9 rounded-lg border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring"
+ >
+ {WINDOWS.map((w) => (
+ <option key={w} value={w}>
+ last {w}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="text-xs">
+ <span className="sr-only">Feature</span>
+ <select
+ value={feature}
+ onChange={(e) => setFeature(e.target.value)}
+ className="h-9 rounded-lg border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring"
+ >
+ <option value="">all features</option>
+ {FEATURES.map((f) => (
+ <option key={f} value={f}>
+ {f} {counts && counts.byFeature[f] ? `(${counts.byFeature[f].calls})` : ''}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="text-xs">
+ <span className="sr-only">Outcome</span>
+ <select
+ value={outcome}
+ onChange={(e) => setOutcome(e.target.value as 'all' | 'errors' | 'ok')}
+ className="h-9 rounded-lg border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring"
+ >
+ <option value="all">all outcomes</option>
+ <option value="errors">errors only</option>
+ <option value="ok">successes only</option>
+ </select>
+ </label>
+ <button
+ onClick={() => setLive((v) => !v)}
+ className={`h-9 rounded-lg border px-3 text-sm font-medium transition-colors ${live ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
+ aria-pressed={live}
+ >
+ {live ? 'Live · 5s' : 'Live off'}
+ </button>
+ <button
+ onClick={() => void refreshNow()}
+ disabled={busy}
+ 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"
+ >
+ <RefreshCw size={14} className={busy ? 'animate-spin' : ''} /> Refresh
+ </button>
+ {paused && <Chip>paused — tab hidden</Chip>}
+ {stale && <Chip tone="bad">reconnecting</Chip>}
+ </div>
+
+ {error && <p className="mb-3 text-sm text-destructive">{error}</p>}
+
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[680px] text-left text-sm">
+ <thead>
+ <tr className="border-b text-xs uppercase tracking-wide text-muted-foreground">
+ <th className="py-2 pr-3 font-medium">When</th>
+ <th className="py-2 pr-3 font-medium">Feature</th>
+ <th className="py-2 pr-3 font-medium">Provider · model</th>
+ <th className="py-2 pr-3 font-medium">Status</th>
+ <th className="py-2 pr-3 font-medium">Took</th>
+ <th className="py-2 font-medium">Reason</th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r) => (
+ <tr key={r.id} className="border-b align-top last:border-0">
+ <td className="whitespace-nowrap py-2 pr-3 text-xs tabular-nums text-muted-foreground">
+ {fmtDay(r.createdAt)} {fmtTime(r.createdAt)}
+ </td>
+ <td className="py-2 pr-3 font-medium">{r.feature}</td>
+ <td className="max-w-[220px] break-all py-2 pr-3 font-mono text-xs">
+ {r.provider}
+ {r.model ? <span className="text-muted-foreground"> · {r.model}</span> : null}
+ </td>
+ <td className="py-2 pr-3">
+ <StatusChip ok={r.ok} status={r.status} />
+ </td>
+ <td className="whitespace-nowrap py-2 pr-3 text-xs tabular-nums text-muted-foreground">
+ {fmtMs(r.durationMs)}
+ </td>
+ <td className="py-2 text-xs">
+ {r.error ? (
+ <span className="text-destructive" title={r.error}>
+ {r.error}
+ </span>
+ ) : (
+ <span className="text-muted-foreground">{r.ok ? '—' : '(no reason recorded)'}</span>
+ )}
+ </td>
+ </tr>
+ ))}
+ {rows.length === 0 && (
+ <tr>
+ <td colSpan={6} className="py-6 text-center text-sm text-muted-foreground">
+ {data ? 'No AI requests in this window yet.' : 'Loading…'}
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ {data && rows.length >= 150 && (
+ <p className="mt-2 text-xs text-muted-foreground">Showing the newest 150 — narrow the window or filters for older rows.</p>
+ )}
+ </Card>
+ </>
+ )
+}
diff --git a/src/lib/admin/logs.test.ts b/src/lib/admin/logs.test.ts
new file mode 100644
index 0000000..f790711
--- /dev/null
+++ b/src/lib/admin/logs.test.ts
@@ -0,0 +1,126 @@
+// Unit tests for the AI request log query layer (v0.16.3 A3) — the
+// parsers are pure; queryAiLogs runs against a mocked db, verifying
+// the where-clauses the Logs view depends on and the row shaping.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ aIUsage: {
+ findMany: vi.fn().mockResolvedValue([]),
+ groupBy: vi.fn().mockResolvedValue([]),
+ deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
+ },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { parseLogWindow, parseOutcome, parseLimit, LOG_WINDOWS, queryAiLogs } from './logs'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ dbMock.aIUsage.findMany.mockResolvedValue([])
+ dbMock.aIUsage.groupBy.mockResolvedValue([])
+ dbMock.aIUsage.deleteMany.mockResolvedValue({ count: 0 })
+})
+
+describe('log query parsers (A3)', () => {
+ it('defaults the window to 24h and accepts known values only', () => {
+ expect(parseLogWindow(null)).toBe('24h')
+ expect(parseLogWindow('15m')).toBe('15m')
+ expect(parseLogWindow('7d')).toBe('7d')
+ expect(parseLogWindow('bogus')).toBe('24h')
+ expect(LOG_WINDOWS['15m']).toBe(15 * 60 * 1000)
+ })
+
+ it('parses outcome conservatively', () => {
+ expect(parseOutcome(null)).toBe('all')
+ expect(parseOutcome('errors')).toBe('errors')
+ expect(parseOutcome('ok')).toBe('ok')
+ expect(parseOutcome('everything')).toBe('all')
+ })
+
+ it('clamps the limit', () => {
+ expect(parseLimit(null)).toBe(150)
+ expect(parseLimit('10')).toBe(20)
+ expect(parseLimit('9999')).toBe(400)
+ expect(parseLimit('abc')).toBe(150)
+ })
+})
+
+describe('queryAiLogs (A3)', () => {
+ it('passes window, feature and outcome filters into the where clause', async () => {
+ const rand = vi.spyOn(Math, 'random').mockReturnValue(0.5) // never sweeps
+ await queryAiLogs({ window: '1h', feature: 'image', outcome: 'errors', limit: 50 })
+ const where = dbMock.aIUsage.findMany.mock.calls[0][0].where
+ expect(where.feature).toBe('image')
+ expect(where.ok).toBe(false)
+ expect(where.createdAt.gte).toBeInstanceOf(Date)
+ expect(Date.now() - where.createdAt.gte.getTime()).toBeLessThanOrEqual(LOG_WINDOWS['1h'] + 100)
+ expect(dbMock.aIUsage.findMany.mock.calls[0][0].take).toBe(50)
+ expect(dbMock.aIUsage.groupBy).toHaveBeenCalled()
+ expect(dbMock.aIUsage.deleteMany).not.toHaveBeenCalled()
+ rand.mockRestore()
+ })
+
+ it('drops unknown features instead of erroring', async () => {
+ const rand = vi.spyOn(Math, 'random').mockReturnValue(0.5)
+ await queryAiLogs({ window: '24h', feature: "'; DROP TABLE", outcome: 'all', limit: 150 })
+ expect(dbMock.aIUsage.findMany.mock.calls[0][0].where.feature).toBeUndefined()
+ rand.mockRestore()
+ })
+
+ it('shapes rows and aggregates per-feature counts', async () => {
+ const rand = vi.spyOn(Math, 'random').mockReturnValue(0.5)
+ dbMock.aIUsage.findMany.mockResolvedValue([
+ {
+ id: 'c1',
+ createdAt: new Date('2026-11-07T10:00:00Z'),
+ feature: 'image',
+ provider: 'NVIDIA NIM',
+ model: 'qwen/qwen-image',
+ ok: false,
+ status: 404,
+ durationMs: null,
+ error: '404 page not found (HTTP 404)',
+ },
+ ])
+ dbMock.aIUsage.groupBy.mockResolvedValue([
+ { feature: 'image', ok: false, _count: { _all: 3 } },
+ { feature: 'write', ok: true, _count: { _all: 4 } },
+ { feature: 'write', ok: false, _count: { _all: 1 } },
+ ])
+ const out = await queryAiLogs({ window: '24h', outcome: 'all', limit: 150 })
+ expect(out.rows).toHaveLength(1)
+ expect(out.rows[0]).toEqual({
+ id: 'c1',
+ createdAt: '2026-11-07T10:00:00.000Z',
+ feature: 'image',
+ provider: 'NVIDIA NIM',
+ model: 'qwen/qwen-image',
+ ok: false,
+ status: 404,
+ durationMs: null,
+ error: '404 page not found (HTTP 404)',
+ })
+ expect(out.counts.total).toBe(8)
+ expect(out.counts.errors).toBe(4)
+ expect(out.counts.byFeature.image).toEqual({ calls: 3, errors: 3 })
+ expect(out.counts.byFeature.write).toEqual({ calls: 5, errors: 1 })
+ // every known feature has an entry even with zero rows
+ expect(out.counts.byFeature.assistant).toEqual({ calls: 0, errors: 0 })
+ rand.mockRestore()
+ })
+
+ it('sweeps rows past retention when the 1% dice come up', async () => {
+ const rand = vi.spyOn(Math, 'random').mockReturnValue(0)
+ dbMock.aIUsage.deleteMany.mockResolvedValue({ count: 12 })
+ const out = await queryAiLogs({ window: '15m', outcome: 'all', limit: 150 })
+ expect(dbMock.aIUsage.deleteMany).toHaveBeenCalled()
+ expect(out.swept).toBe(true)
+ const where = dbMock.aIUsage.deleteMany.mock.calls[0][0].where
+ // 90-day retention
+ const days = (Date.now() - where.createdAt.lt.getTime()) / (24 * 60 * 60 * 1000)
+ expect(days).toBeGreaterThan(89.9)
+ expect(days).toBeLessThan(90.1)
+ rand.mockRestore()
+ })
+})
diff --git a/src/lib/admin/logs.ts b/src/lib/admin/logs.ts
new file mode 100644
index 0000000..eb6a092
--- /dev/null
+++ b/src/lib/admin/logs.ts
@@ -0,0 +1,147 @@
+// ─────────────────────────────────────────────────────────────
+// AI request log query layer (v0.16.3 A3) — the data behind
+// /admin/logs.
+//
+// AIUsage (extended by migration 0010) is one row per AI request
+// through withProvider: feature, provider, model, outcome status,
+// round-trip duration and a scrubbed error reason. This module
+// shapes the admin-facing view: window parsing, filter parsing and
+// the row/summary projection. Pure logic is separate from the route
+// so it is unit-testable without a server.
+//
+// CONTRACT: server-only (the route imports the db layer through
+// queryAiLogs); every entry point swallows its own errors.
+// ─────────────────────────────────────────────────────────────
+
+/** Retention for AI request rows — mirrors TrafficStat's 90 days. */
+export const AI_LOG_RETENTION_DAYS = 90
+
+/** Supported ?window= values → milliseconds. */
+export const LOG_WINDOWS = {
+ '15m': 15 * 60 * 1000,
+ '1h': 60 * 60 * 1000,
+ '6h': 6 * 60 * 60 * 1000,
+ '24h': 24 * 60 * 60 * 1000,
+ '7d': 7 * 24 * 60 * 60 * 1000,
+} as const
+
+export type LogWindow = keyof typeof LOG_WINDOWS
+
+export function parseLogWindow(value: string | null): LogWindow {
+ return value && value in LOG_WINDOWS ? (value as LogWindow) : '24h'
+}
+
+/** Parse ?outcome= — anything but "errors"/"ok" means "all". */
+export function parseOutcome(value: string | null): 'all' | 'errors' | 'ok' {
+ return value === 'errors' || value === 'ok' ? value : 'all'
+}
+
+/** Parse ?limit= — clamped 20..400, default 150. */
+export function parseLimit(value: string | null): number {
+ if (value === null || value.trim() === '') return 150
+ const n = Number(value)
+ if (!Number.isFinite(n) || n <= 0) return 150
+ return Math.min(400, Math.max(20, Math.round(n)))
+}
+
+/** Feature names the log can filter by (kept in a stable order for UIs). */
+export const LOG_FEATURES = [
+ 'assistant',
+ 'write',
+ 'translate',
+ 'image',
+ 'image-edit',
+ 'magic-layers',
+ 'search',
+] as const
+
+export interface AiLogRow {
+ id: string
+ createdAt: string
+ feature: string
+ provider: string
+ model: string | null
+ ok: boolean
+ status: number | null
+ durationMs: number | null
+ error: string | null
+}
+
+export interface AiLogCounts {
+ total: number
+ errors: number
+ /** Calls + errors per feature, every known feature present. */
+ byFeature: Record<string, { calls: number; errors: number }>
+}
+
+export interface AiLogResult {
+ window: LogWindow
+ rows: AiLogRow[]
+ counts: AiLogCounts
+ swept?: boolean
+}
+
+/**
+ * Query the AI request log. Server-only: imports the db lazily so the
+ * pure helpers above stay importable from unit tests and (potentially)
+ * edge-ish contexts. Also lazily sweeps rows past retention (1% of
+ * queries — the same amortization recordTraffic uses).
+ */
+export async function queryAiLogs(opts: {
+ window: LogWindow
+ feature?: string | null
+ outcome: 'all' | 'errors' | 'ok'
+ limit: number
+}): Promise<AiLogResult> {
+ const since = new Date(Date.now() - LOG_WINDOWS[opts.window])
+ const feature =
+ opts.feature && LOG_FEATURES.includes(opts.feature as (typeof LOG_FEATURES)[number]) ? opts.feature : null
+ const where = {
+ createdAt: { gte: since },
+ ...(feature ? { feature } : {}),
+ ...(opts.outcome === 'errors' ? { ok: false } : {}),
+ ...(opts.outcome === 'ok' ? { ok: true } : {}),
+ }
+ const { db } = await import('@/lib/db')
+ const [raw, grouped] = await Promise.all([
+ db.aIUsage.findMany({ where, orderBy: { createdAt: 'desc' }, take: opts.limit }),
+ db.aIUsage.groupBy({
+ by: ['feature', 'ok'],
+ where: { createdAt: { gte: since } },
+ _count: { _all: true },
+ }),
+ ])
+ const counts: AiLogCounts = { total: 0, errors: 0, byFeature: {} }
+ for (const f of LOG_FEATURES) counts.byFeature[f] = { calls: 0, errors: 0 }
+ for (const g of grouped) {
+ const calls = g._count._all
+ counts.total += calls
+ if (g.ok === false) counts.errors += calls
+ const slot = counts.byFeature[g.feature] ?? { calls: 0, errors: 0 }
+ slot.calls += calls
+ if (g.ok === false) slot.errors += calls
+ counts.byFeature[g.feature] = slot
+ }
+ let swept = false
+ if (Math.random() < 0.01) {
+ const cutoff = new Date(Date.now() - AI_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1000)
+ const r = await db.aIUsage.deleteMany({ where: { createdAt: { lt: cutoff } } })
+ swept = r.count > 0
+ }
+ return {
+ window: opts.window,
+ rows: raw.map((r) => ({
+ id: r.id,
+ createdAt: r.createdAt.toISOString(),
+ feature: r.feature,
+ provider: r.provider,
+ model: r.model,
+ ok: r.ok,
+ status: r.status,
+ durationMs: r.durationMs,
+ error: r.error,
+ })),
+ counts,
+ swept,
+ }
+}
diff --git a/src/lib/ai/probe.test.ts b/src/lib/ai/probe.test.ts
new file mode 100644
index 0000000..6f7bcfe
--- /dev/null
+++ b/src/lib/ai/probe.test.ts
@@ -0,0 +1,109 @@
+// Unit tests for per-slot provider probing (v0.16.3 A3) — the
+// classification that turns a provider's answer into the verdict the
+// admin acts on. The production incident this encodes: NVIDIA NIM
+// (chat-only) pinned to every slot — text tests passed while image
+// generation 404'd with no explanation anywhere the admin could see.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const chatCreate = vi.fn(async () => ({ choices: [{ message: { content: 'ok' } }] }))
+const generationsCreate = vi.fn(async () => ({ data: [{ base64: 'aGk=' }] }))
+const generationsEdit = vi.fn(async () => ({ data: [{ base64: 'aGk=' }] }))
+const searchCreate = vi.fn(async () => ({ results: [{ original_url: 'https://x/y.jpg' }] }))
+
+vi.mock('z-ai-web-dev-sdk', () => ({
+ default: class MockZAI {
+ chat: unknown
+ images: unknown
+ constructor(_config: { baseUrl?: string; apiKey?: string }) {
+ this.chat = { completions: { create: chatCreate } }
+ this.images = {
+ generations: { create: generationsCreate, edit: generationsEdit },
+ search: { create: searchCreate },
+ }
+ }
+ },
+}))
+
+import { classifyProbeError, probeSlot, SLOT_ENDPOINT } from './probe'
+
+const TARGET = { baseUrl: 'https://provider.test/v1', apiKey: 'k', label: 'Test Provider', source: 'multi' }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ chatCreate.mockResolvedValue({ choices: [{ message: { content: 'ok' } }] })
+ generationsCreate.mockResolvedValue({ data: [{ base64: 'aGk=' }] })
+ generationsEdit.mockResolvedValue({ data: [{ base64: 'aGk=' }] })
+ searchCreate.mockResolvedValue({ results: [{ original_url: 'https://x/y.jpg' }] })
+})
+
+describe('classifyProbeError (A3)', () => {
+ it('a 404 from the image endpoint is a NOT-SERVED verdict that names the fix', () => {
+ const v = classifyProbeError('image', new Error('API request failed with status 404: 404 page not found'))
+ expect(v.ok).toBe(false)
+ expect(v.httpStatus).toBe(404)
+ expect(v.endpoint).toBe(SLOT_ENDPOINT.image)
+ expect(v.message).toContain('does not serve this endpoint')
+ expect(v.message).toContain('cannot generate images')
+ })
+
+ it('a 401 is a credentials verdict', () => {
+ const v = classifyProbeError('text', new Error('API request failed with status 401: bad key'))
+ expect(v.ok).toBe(false)
+ expect(v.httpStatus).toBe(401)
+ expect(v.message).toContain('credentials')
+ })
+
+ it('a 400-class answer to a deliberately-empty probe PROVES the endpoint exists', () => {
+ const v = classifyProbeError('imageEdit', new Error('API request failed with status 400: must provide images'))
+ expect(v.ok).toBe(true) // reachable — that is the signal
+ expect(v.httpStatus).toBe(400)
+ expect(v.message).toContain('reachable')
+ })
+
+ it('5xx and unknown errors are failures with the scrubbed reason', () => {
+ const v = classifyProbeError('image', new Error('API request failed with status 502: upstream nvapi-SecretSecret99 blew up'))
+ expect(v.ok).toBe(false)
+ expect(v.httpStatus).toBe(502)
+ expect(v.message).toContain('nvapi-***')
+ expect(v.message).not.toContain('SecretSecret99')
+ })
+})
+
+describe('probeSlot (A3)', () => {
+ it('image success is a full end-to-end verdict', async () => {
+ const out = await probeSlot('image', TARGET)
+ expect(out.verdict.ok).toBe(true)
+ expect(out.verdict.httpStatus).toBe(200)
+ expect(out.verdict.message).toContain('end-to-end')
+ expect(generationsCreate).toHaveBeenCalledWith(expect.objectContaining({ prompt: expect.any(String) }))
+ })
+
+ it('image 404 becomes a classified verdict, never a thrown error', async () => {
+ generationsCreate.mockRejectedValueOnce(new Error('API request failed with status 404: 404 page not found'))
+ const out = await probeSlot('image', TARGET)
+ expect(out.verdict.ok).toBe(false)
+ expect(out.verdict.httpStatus).toBe(404)
+ })
+
+ it('imageEdit probe sends no image (400-class = exists) and classifies the rejection', async () => {
+ generationsEdit.mockRejectedValueOnce(new Error('API request failed with status 422: images required'))
+ const out = await probeSlot('imageEdit', TARGET)
+ expect(generationsEdit).toHaveBeenCalledWith(expect.not.objectContaining({ images: expect.anything() }))
+ expect(out.verdict.ok).toBe(true) // endpoint reachable
+ expect(out.verdict.message).toContain('reachable')
+ })
+
+ it('imageSearch reports the result count', async () => {
+ const out = await probeSlot('imageSearch', TARGET)
+ expect(out.verdict.ok).toBe(true)
+ expect(out.verdict.message).toContain('1 result')
+ })
+
+ it('text slot goes through chat completions and returns the reply', async () => {
+ const out = await probeSlot('text', TARGET)
+ expect(out.verdict.ok).toBe(true)
+ expect(out.reply).toBe('ok')
+ expect(chatCreate).toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/ai/probe.ts b/src/lib/ai/probe.ts
new file mode 100644
index 0000000..4d66fa2
--- /dev/null
+++ b/src/lib/ai/probe.ts
@@ -0,0 +1,199 @@
+// ─────────────────────────────────────────────────────────────
+// Per-slot provider probing (v0.16.3 A3) — the machinery behind
+// the AI & models page's per-slot "Test" buttons.
+//
+// The A2 test connection only ever proved chat worked, so a
+// chat-only provider (NVIDIA NIM and friends) passed every test
+// while image generation 404'd in production — the exact incident
+// this module exists to prevent. Each slot is probed through the
+// ENDPOINT it actually uses, and failures are classified into an
+// admin-actionable verdict ("this provider does not serve image
+// generation"), never a bare status code.
+//
+// CONTRACT: server-only (constructs SDK clients); never logs or
+// returns credentials — error text is scrubbed before shaping.
+// ─────────────────────────────────────────────────────────────
+
+import { makeClient } from '@/lib/ai/provider'
+
+/** Probe timeout — generous: image generation legitimately takes seconds. */
+export const PROBE_TIMEOUT_MS = 25_000
+
+/** Which SDK endpoint each slot exercises (shown in verdicts + docs). */
+export const SLOT_ENDPOINT: Record<string, string> = {
+ text: 'POST {base}/chat/completions',
+ vision: 'POST {base}/chat/completions',
+ image: 'POST {base}/images/generations',
+ imageEdit: 'POST {base}/images/generations/edit',
+ imageSearch: 'POST {base}/images/search',
+}
+
+export interface ProbeVerdict {
+ ok: boolean
+ slot: string
+ endpoint: string
+ httpStatus: number | null
+ message: string
+}
+
+/** Classify a thrown probe error into an admin-actionable verdict. */
+export function classifyProbeError(slot: string, err: unknown): ProbeVerdict {
+ const raw = err instanceof Error ? err.message : String(err)
+ const m = raw.match(/status (\d{3})/i)
+ const status = m ? Number(m[1]) : null
+ const endpoint = SLOT_ENDPOINT[slot] ?? 'provider endpoint'
+ const clean = raw
+ .replace(/(nvapi-|sk-|gsk_|pk-|rk-|ak-|xai-|hf_|Bearer\s+)[A-Za-z0-9_\-]{8,}/gi, '$1***')
+ .replace(/[\r\n\t]+/g, ' ')
+ .trim()
+ .slice(0, 220)
+
+ if (status === 404 || status === 405) {
+ return {
+ ok: false,
+ slot,
+ endpoint,
+ httpStatus: status,
+ message:
+ `The provider answered ${status} for ${endpoint.replace('{base}', 'its base URL')} — it does not serve this ` +
+ `endpoint, so the ${slot === 'text' || slot === 'vision' ? 'chat' : slot} capability cannot run on it. ` +
+ `Chat-only providers (e.g. NVIDIA NIM) work for text and vision but cannot generate images or edit them — ` +
+ `pin those slots to a provider that serves image endpoints (e.g. Z.ai, OpenAI).`,
+ }
+ }
+ if (status === 401 || status === 403) {
+ return {
+ ok: false,
+ slot,
+ endpoint,
+ httpStatus: status,
+ message: `The provider rejected the credentials (HTTP ${status}) — check the API key for this provider.`,
+ }
+ }
+ if (status !== null && status >= 400 && status < 500) {
+ return {
+ ok: true, // endpoint exists and answered — request shape rejected, expected for empty probes
+ slot,
+ endpoint,
+ httpStatus: status,
+ message: `Endpoint is reachable (HTTP ${status} rejecting the minimal probe — expected for this test shape). ` +
+ `The provider serves ${endpoint.replace('{base}', 'this route')}; ${clean}`,
+ }
+ }
+ return {
+ ok: false,
+ slot,
+ endpoint,
+ httpStatus: status,
+ message: clean || 'The provider did not answer in time.',
+ }
+}
+
+/** What a probe needs to reach the provider (never logged verbatim —
+ * the apiKey rides in the SDK client only). */
+export interface ProbeTarget {
+ baseUrl: string
+ apiKey: string
+ model?: string
+ label: string
+ source: string
+}
+
+/** Probe ONE capability slot through its real endpoint (A3). Provider
+ * errors are CAUGHT and classified — a rejection is a verdict, not an
+ * exception; only unexpected throws (client construction) propagate. */
+export async function probeSlot(slot: string, target: ProbeTarget): Promise<{ verdict: ProbeVerdict; reply?: string }> {
+ const zai = await makeClient(target.baseUrl, target.apiKey)
+ const model = target.model
+ const withTimeout = <T,>(p: Promise<T>): Promise<T> => {
+ return Promise.race([
+ p,
+ new Promise<T>((_, reject) => {
+ setTimeout(() => reject(new Error('provider timed out')), PROBE_TIMEOUT_MS)
+ }),
+ ])
+ }
+
+ if (slot === 'image') {
+ try {
+ const r = await withTimeout(
+ zai.images.generations.create({
+ ...(model ? { model } : {}),
+ prompt: 'a small solid red circle on a white background',
+ size: '1024x1024',
+ })
+ )
+ const has = Boolean((r as { data?: { base64?: string }[] }).data?.[0]?.base64)
+ return {
+ verdict: {
+ ok: true,
+ slot,
+ endpoint: SLOT_ENDPOINT.image,
+ httpStatus: 200,
+ message: has
+ ? 'Generated a test image end-to-end — the full path works.'
+ : 'The provider answered but returned no image data.',
+ },
+ }
+ } catch (err) {
+ return { verdict: classifyProbeError(slot, err) }
+ }
+ }
+ if (slot === 'imageEdit') {
+ try {
+ // deliberately image-less: a 400-class rejection proves the route
+ // exists without spending an edit
+ await withTimeout(
+ zai.images.generations.edit({
+ ...(model ? { model } : {}),
+ prompt: 'probe',
+ } as unknown as Parameters<typeof zai.images.generations.edit>[0])
+ )
+ return {
+ verdict: {
+ ok: true,
+ slot,
+ endpoint: SLOT_ENDPOINT.imageEdit,
+ httpStatus: 200,
+ message: 'The edit endpoint accepted the probe.',
+ },
+ }
+ } catch (err) {
+ return { verdict: classifyProbeError(slot, err) }
+ }
+ }
+ if (slot === 'imageSearch') {
+ try {
+ const r = await withTimeout(zai.images.search.create({ query: 'red circle', count: 1 }))
+ const n = (r as { results?: unknown[] }).results?.length ?? 0
+ return {
+ verdict: {
+ ok: true,
+ slot,
+ endpoint: SLOT_ENDPOINT.imageSearch,
+ httpStatus: 200,
+ message: n
+ ? `Search answered with ${n} result${n === 1 ? '' : 's'} — the full path works.`
+ : 'Search answered but returned no results.',
+ },
+ }
+ } catch (err) {
+ return { verdict: classifyProbeError(slot, err) }
+ }
+ }
+ // text / vision — the existing minimal chat completion
+ const completion = await withTimeout(
+ zai.chat.completions.create({
+ ...(model ? { model } : {}),
+ messages: [{ role: 'user', content: 'Reply with the single word: ok' }],
+ thinking: { type: 'disabled' },
+ })
+ )
+ const reply = String(
+ (completion as { choices?: { message?: { content?: string } }[] }).choices?.[0]?.message?.content ?? ''
+ ).slice(0, 120)
+ return {
+ verdict: { ok: true, slot, endpoint: SLOT_ENDPOINT[slot] ?? 'chat', httpStatus: 200, message: 'Chat completion answered.' },
+ reply,
+ }
+}
diff --git a/src/lib/ai/provider-logging.test.ts b/src/lib/ai/provider-logging.test.ts
new file mode 100644
index 0000000..5dcd06d
--- /dev/null
+++ b/src/lib/ai/provider-logging.test.ts
@@ -0,0 +1,170 @@
+// Unit tests for v0.16.3 (A3): provider error normalization + full-outcome
+// request logging in withProvider. The AIUsage row is what /admin/logs
+// reads, so these invariants ARE the Logs view's contract:
+//
+// 1. describeProviderError turns SDK-shaped messages into {status,
+// message} with credentials scrubbed and length capped.
+// 2. withProvider records EVERY outcome: success (status + duration
+// + model), provider failure (HTTP status + scrubbed reason — and
+// the client 502 body carries the same reason), and the unconfigured
+// 503 with the slot named.
+// 3. The failure reason in the row is the same string the client
+// sees — one truth, two audiences.
+//
+// Hermeticity: /etc/.z-ai-config can exist on dev machines (it does on
+// the build sandbox) — the fs mock below forces the file layer absent
+// so the unconfigured case is deterministic everywhere.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ aIUsage: { create: vi.fn().mockResolvedValue({}) },
+ appConfig: { findUnique: vi.fn().mockResolvedValue(null) },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+vi.mock('fs', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('fs')>()
+ return { ...actual, existsSync: () => false }
+})
+
+// SDK mock — the class mirrors the real constructor surface (A2)
+const chatCreate = vi.fn(async () => ({
+ choices: [{ message: { content: 'ok' } }],
+}))
+vi.mock('z-ai-web-dev-sdk', () => ({
+ default: class MockZAI {
+ chat: { completions: { create: typeof chatCreate } }
+ constructor(_config: { baseUrl?: string; apiKey?: string }) {
+ this.chat = { completions: { create: chatCreate } }
+ }
+ },
+}))
+
+import { NextRequest, NextResponse } from 'next/server'
+import { describeProviderError, scrubErrorText, withProvider } from './provider'
+
+function sameOriginPost(url: string): NextRequest {
+ return new NextRequest(`http://canvix.test${url}`, {
+ method: 'POST',
+ headers: { host: 'canvix.test', origin: 'http://canvix.test', 'content-type': 'application/json' },
+ body: '{}',
+ })
+}
+
+/** recordUsage is fire-and-forget on the success/failure paths — let the
+ * voided promise settle before asserting on the row. */
+function flush(): Promise<void> {
+ return new Promise((r) => setTimeout(r, 20))
+}
+
+beforeEach(() => {
+ vi.stubEnv('ZAI_BASE_URL', 'http://provider.test')
+ vi.stubEnv('ZAI_API_KEY', 'test-key')
+ vi.clearAllMocks()
+ dbMock.aIUsage.create.mockResolvedValue({})
+ chatCreate.mockResolvedValue({ choices: [{ message: { content: 'ok' } }] })
+})
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+})
+
+describe('describeProviderError (A3)', () => {
+ it('extracts the HTTP status from the SDK-shaped message', () => {
+ const out = describeProviderError(new Error('API request failed with status 404: 404 page not found'))
+ expect(out.status).toBe(404)
+ expect(out.message).toContain('404 page not found')
+ expect(out.message).toContain('(HTTP 404)')
+ // the SDK prefix must not survive verbatim
+ expect(out.message).not.toMatch(/^API request failed/)
+ })
+
+ it('scrubs key-shaped tokens from the reason', () => {
+ const out = describeProviderError(
+ new Error('API request failed with status 401: invalid key nvapi-AbCdEfGh12345678 rejected')
+ )
+ expect(out.status).toBe(401)
+ expect(out.message).not.toContain('nvapi-AbCdEfGh12345678')
+ expect(out.message).toContain('nvapi-***')
+ })
+
+ it('caps the message length', () => {
+ const long = 'x'.repeat(500)
+ const out = describeProviderError(new Error(long))
+ expect(out.message.length).toBeLessThanOrEqual(240)
+ })
+
+ it('handles non-Error throwables and collapses whitespace', () => {
+ const out = describeProviderError('boom\n\twith\nnewlines')
+ expect(out.status).toBeNull()
+ expect(out.message).toBe('boom with newlines')
+ })
+})
+
+describe('scrubErrorText (A3)', () => {
+ it('masks every known key prefix', () => {
+ const out = scrubErrorText('sk-abcdefgh1234 gsk_xxxx1234 Bearer tokentoken123')
+ expect(out).not.toMatch(/(abcdefgh1234|xxxx1234|tokentoken123)/)
+ })
+ it('leaves ordinary text intact', () => {
+ expect(scrubErrorText('provider answered 429 too many requests')).toBe('provider answered 429 too many requests')
+ })
+})
+
+describe('withProvider request logging (A3)', () => {
+ it('records a success row with model, status and duration', async () => {
+ const res = await withProvider('write', sameOriginPost('/api/ai/write'), { limit: 5, windowSec: 60 }, async (ctx) => {
+ await ctx.zai.chat.completions.create({ messages: [{ role: 'user', content: 'hi' }] })
+ return NextResponse.json({ ok: true })
+ })
+ expect(res.status).toBe(200)
+ await flush()
+ expect(dbMock.aIUsage.create).toHaveBeenCalledTimes(1)
+ const row = dbMock.aIUsage.create.mock.calls[0][0].data
+ expect(row.feature).toBe('write')
+ expect(row.ok).toBe(true)
+ expect(row.status).toBe(200)
+ expect(typeof row.durationMs).toBe('number')
+ expect(row.provider).toBe('env') // fallback-chain label = config source
+ })
+
+ it('records the provider failure with its HTTP status and reason, and the client 502 carries the same reason', async () => {
+ chatCreate.mockRejectedValueOnce(new Error('API request failed with status 404: 404 page not found'))
+ const res = await withProvider('image', sameOriginPost('/api/ai/image'), { limit: 5, windowSec: 60 }, async (ctx) => {
+ // image slot resolves through the same env chain in this test —
+ // calling ANY provider method stands in for the generation call
+ await ctx.zai.chat.completions.create({ messages: [{ role: 'user', content: 'hi' }] })
+ return NextResponse.json({})
+ })
+ expect(res.status).toBe(502)
+ const body = await res.json()
+ expect(body.code).toBe('PROVIDER_ERROR')
+ expect(body.detail).toContain('404 page not found')
+ await flush()
+ expect(dbMock.aIUsage.create).toHaveBeenCalledTimes(1)
+ const row = dbMock.aIUsage.create.mock.calls[0][0].data
+ expect(row.ok).toBe(false)
+ expect(row.status).toBe(404)
+ expect(row.error).toContain('404 page not found')
+ expect(row.provider).toBe('env')
+ })
+
+ it('records the unconfigured 503 with the slot named', async () => {
+ vi.stubEnv('ZAI_BASE_URL', '')
+ vi.stubEnv('ZAI_API_KEY', '')
+ const res = await withProvider(
+ 'image',
+ sameOriginPost('/api/ai/image'),
+ { limit: 5, windowSec: 60 },
+ async () => NextResponse.json({})
+ )
+ expect(res.status).toBe(503)
+ expect(dbMock.aIUsage.create).toHaveBeenCalledTimes(1)
+ const row = dbMock.aIUsage.create.mock.calls[0][0].data
+ expect(row.ok).toBe(false)
+ expect(row.status).toBe(503)
+ expect(row.provider).toBe('no-provider (image)')
+ expect(row.error).toContain('image')
+ })
+})
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 4c3b1eb..0ce5340 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -265,6 +265,9 @@ export interface ProviderContext {
model?: string
/** Which provider answered (multi table only) — for accounting labels. */
label?: string
+ /** Which config layer answered (multi/db/env/file) — the Logs view's
+ * provider column when no table label applies (v0.16.3 A3). */
+ source?: SlotSource
}
/** Resolve a slot and construct its client. Null when unconfigured. */
@@ -273,7 +276,7 @@ export async function getClientForSlot(slot: AiSlot): Promise<ProviderContext |
if (!resolved) return null
try {
const zai = await makeClient(resolved.baseUrl, resolved.apiKey)
- return { zai, model: resolved.model, label: resolved.label }
+ return { zai, model: resolved.model, label: resolved.label, source: resolved.source }
} catch (err) {
console.error(`[ai] provider initialization failed (${slot})`, err)
return null
@@ -331,17 +334,78 @@ 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> {
+/** Telemetry detail attached to one AI request row (v0.16.3 A3). */
+export interface UsageDetail {
+ model?: string
+ status?: number
+ durationMs?: number
+ error?: string
+}
+
+export async function recordUsage(
+ feature: string,
+ provider: string,
+ ok: boolean,
+ detail: UsageDetail = {}
+): 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 } })
+ await db.aIUsage.create({
+ data: {
+ feature,
+ provider,
+ ok,
+ ...(detail.model !== undefined ? { model: detail.model } : {}),
+ ...(detail.status !== undefined ? { status: detail.status } : {}),
+ ...(detail.durationMs !== undefined ? { durationMs: detail.durationMs } : {}),
+ ...(detail.error !== undefined ? { error: detail.error } : {}),
+ },
+ })
} catch {
/* accounting must never break the request */
}
}
+// ── provider error normalization (v0.16.3 A3) ────────────────
+//
+// The SDK throws `Error("API request failed with status 404: 404 page
+// not found")` — the raw string ends up in server logs and nowhere
+// else, which is exactly why "why is image generation broken" needed
+// an SSH session to answer. These helpers turn any thrown value into
+// a short, scrubbed, admin-safe reason that flows into BOTH the
+// AIUsage log (→ /admin/logs) and the client's 502 body, so the
+// failure explains itself wherever it is seen.
+
+/** Never let a credential (or anything key-shaped) reach a log or client. */
+export function scrubErrorText(text: string): string {
+ return text
+ .replace(/(nvapi-|sk-|gsk_|pk-|rk-|ak-|xai-|hf_|Bearer\s+)[A-Za-z0-9_\-]{8,}/gi, '$1***')
+ .replace(/[\r\n\t]+/g, ' ')
+ .replace(/\s{2,}/g, ' ')
+ .trim()
+ .slice(0, 240)
+}
+
+export interface ProviderErrorInfo {
+ /** HTTP status the provider answered, when the error carries one. */
+ status: number | null
+ /** Short scrubbed human reason, safe for logs, admin UI and clients. */
+ message: string
+}
+
+/** Turn any thrown value into { status?, message } — scrubbed and capped. */
+export function describeProviderError(err: unknown): ProviderErrorInfo {
+ const raw = err instanceof Error ? err.message : String(err)
+ const m = raw.match(/status (\d{3})/i)
+ const status = m ? Number(m[1]) : null
+ // drop the SDK prefix — "API request failed with status 404: X" → "X (HTTP 404)"
+ const body = raw.replace(/^API request failed with status \d{3}:?\s*/i, '').trim()
+ const suffix = status ? ` (HTTP ${status})` : ''
+ return { status, message: scrubErrorText(body ? `${body}${suffix}` : raw) }
+}
+
// ── shared error responses ──
export const NO_PROVIDER_RESPONSE = {
@@ -423,16 +487,40 @@ export async function withProvider(
const slot = FEATURE_SLOTS[feature] ?? 'text'
const ctx = await getClientForSlot(slot)
if (!ctx) {
- await recordUsage(feature, 'zai', false)
+ await recordUsage(feature, `no-provider (${slot})`, false, {
+ status: 503,
+ error: `no provider configured for the ${slot} slot`,
+ })
return providerUnavailable(NextResponse.json({}))
}
try {
+ const started = Date.now()
const out = await fn(ctx)
- void recordUsage(feature, 'zai', true)
+ void recordUsage(feature, ctx.label ?? ctx.source ?? slot, true, {
+ model: ctx.model,
+ status: out.status,
+ durationMs: Date.now() - started,
+ })
return out
} catch (err) {
console.error(`[ai/${feature}]`, err)
- void recordUsage(feature, 'zai', false)
- return NextResponse.json({ error: 'The AI service is unavailable right now. Please try again.' }, { status: 502 })
+ const info = describeProviderError(err)
+ void recordUsage(feature, ctx.label ?? ctx.source ?? slot, false, {
+ model: ctx.model,
+ status: info.status ?? 502,
+ durationMs: undefined,
+ error: info.message,
+ })
+ // v0.16.3 (A3): the 502 body now carries the scrubbed reason — the
+ // admin Logs view shows the same string, and end users finally see
+ // "provider answered 404" instead of a generic unavailable.
+ return NextResponse.json(
+ {
+ error: 'The AI service is unavailable right now. Please try again.',
+ code: 'PROVIDER_ERROR',
+ ...(info.message ? { detail: info.message } : {}),
+ },
+ { status: 502 }
+ )
}
}