7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
P2 batch: routing traces, reasoning control, model-source guard, catalog-driven audio transcription + dashboard (#602)
Tashfeend9a0d772b4f6
diff --git a/client/src/App.tsx b/client/src/App.tsxindex 533594d3..679cdf17 100644--- a/client/src/App.tsx+++ b/client/src/App.tsx@@ -334,6 +334,7 @@ function App() {<Route path="/models/image/:id" element={<MediaDetailPage modality="image" />} /><Route path="/models/audio" element={<AudioPage />} /><Route path="/models/audio/:id" element={<MediaDetailPage modality="audio" />} />+ <Route path="/models/transcription/:id" element={<MediaDetailPage modality="transcription" />} /><Route path="/playground" element={<PlaygroundPage />} /><Route path="/keys" element={<KeysPage />} /><Route path="/fallback" element={<Navigate to="/models/chat" replace />} />diff --git a/client/src/components/command-palette.tsx b/client/src/components/command-palette.tsxindex 6749784c..07985563 100644--- a/client/src/components/command-palette.tsx+++ b/client/src/components/command-palette.tsx@@ -102,7 +102,7 @@ export function CommandPalette() {{ id: 'p-chat', group: 'pages', label: t('models.chatModelsTab'), keywords: 'models chat routing fallback', icon: MessageSquare, run: go('/models/chat') },{ id: 'p-embeddings', group: 'pages', label: t('models.embeddingsTab'), keywords: 'models embeddings vectors', icon: Layers, run: go('/models/embeddings') },{ id: 'p-image', group: 'pages', label: t('models.imageTab'), keywords: 'models image generation', icon: ImageIcon, run: go('/models/image') },- { id: 'p-audio', group: 'pages', label: t('models.audioTab'), keywords: 'models audio speech tts', icon: AudioLines, run: go('/models/audio') },+ { id: 'p-audio', group: 'pages', label: t('models.audioTab'), keywords: 'models audio speech tts stt transcription whisper', icon: AudioLines, run: go('/models/audio') },{ id: 'p-fusion', group: 'pages', label: t('models.fusionTab'), keywords: 'models fusion synthesis panel judge', icon: Zap, run: go('/models/fusion') },{ id: 'p-playground', group: 'pages', label: t('nav.playground'), keywords: 'playground test chat try', icon: SquareTerminal, run: go('/playground') },{ id: 'p-keys', group: 'pages', label: t('nav.keys'), keywords: 'keys providers api tokens', icon: KeyRound, run: go('/keys') },diff --git a/client/src/components/media-models.tsx b/client/src/components/media-models.tsxindex 32952355..e8f349b2 100644--- a/client/src/components/media-models.tsx+++ b/client/src/components/media-models.tsx@@ -1,6 +1,6 @@import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { Link } from 'react-router-dom'-import { AudioLines, Image as ImageIcon } from 'lucide-react'+import { AudioLines, Image as ImageIcon, Mic } from 'lucide-react'import { apiFetch } from '@/lib/api'import { Switch } from '@/components/ui/switch'import { ConfirmButton } from '@/components/confirm-button'@@ -15,7 +15,7 @@ export interface MediaModel {platform: stringmodelId: stringdisplayName: string- modality: 'image' | 'audio'+ modality: 'image' | 'audio' | 'transcription'enabled: booleanquotaLabel: stringkeyCount: number@@ -44,12 +44,83 @@ export function groupMedia(models: MediaModel[]): MediaGroup[] {.sort((a, b) => a.label.localeCompare(b.label))}+// One consolidated logical-model card: providers underneath in failover order+// (rows arrive from the API already sorted by priority), each with an enable+// toggle saved immediately.+function MediaGroupCard({+ group: g,+ detailBase,+ onToggle,+ onDeleteCustom,+ deletePending,+}: {+ group: MediaGroup+ detailBase: string+ onToggle: (id: number, enabled: boolean) => void+ onDeleteCustom: (id: number) => void+ deletePending: boolean+}) {+ const { t } = useI18n()+ const anyEnabled = g.members.some(m => m.enabled)+ const quota = g.members.map(m => m.quotaLabel).find(Boolean)+ return (+ <section className={`rounded-3xl border bg-card p-5 ${anyEnabled ? '' : 'opacity-60'}`}>+ <div className="mb-3 flex items-center gap-2 flex-wrap">+ <Link to={`${detailBase}/${g.slug}`} className="text-sm font-medium hover:underline">{g.label}</Link>+ {g.members.length > 1 ? (+ <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-muted text-muted-foreground">+ {t('models.providerCount', { count: g.members.length })}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground">{g.members[0].platform}</span>+ )}+ {quota && (+ <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-muted text-muted-foreground tabular-nums">{quota}</span>+ )}+ </div>++ <div className="divide-y">+ {g.members.map(m => (+ <div key={m.id} className={`flex items-center gap-3 py-2 ${m.enabled ? '' : 'opacity-50'}`}>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{m.platform}</span>+ {m.keyCount === 0 && (+ <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-amber-600/15 text-amber-700 dark:bg-amber-400/15 dark:text-amber-400">+ {t('models.noKey')}+ </span>+ )}+ </div>+ <div className="truncate font-mono text-[11px] text-muted-foreground">{m.modelId}</div>+ </div>+ <Switch+ checked={m.enabled}+ onCheckedChange={(c) => onToggle(m.id, c)}+ />+ {m.isCustom && (+ <ConfirmButton+ className="text-muted-foreground hover:text-destructive"+ onConfirm={() => onDeleteCustom(m.id)}+ disabled={deletePending}+ >+ {t('common.remove')}+ </ConfirmButton>+ )}+ </div>+ ))}+ </div>+ </section>+ )+}+// Shared list view for the Image and Audio dashboard tabs. Mirrors the chat// Models page: media models are consolidated into one logical-model group per// name (with a "N providers" badge), each linking to its own detail page, and a// per-provider enable toggle (saved immediately). Rows arrive from the signed// catalog via catalog-sync, so the list self-populates once a media catalog is-// applied.+// applied. The Audio tab carries both directions of the modality: audio out+// (text to speech, /v1/audio/speech) and audio in (speech to text,+// /v1/audio/transcriptions) as two sections of one page.export function MediaModelsView({ modality }: { modality: 'image' | 'audio' }) {const { t } = useI18n()const queryClient = useQueryClient()@@ -70,16 +141,30 @@ export function MediaModelsView({ modality }: { modality: 'image' | 'audio' }) {onSuccess: () => queryClient.invalidateQueries({ queryKey: ['media'] }),})- const groups = groupMedia((data?.models ?? []).filter(m => m.modality === modality))+ const models = data?.models ?? []+ const groups = groupMedia(models.filter(m => m.modality === modality))+ const sttGroups = groupMedia(models.filter(m => m.modality === 'transcription'))const title = modality === 'image' ? t('models.imageTitle') : t('models.audioTitle')const description = modality === 'image' ? t('models.imageDesc') : t('models.audioDesc')const endpoint = modality === 'image' ? '/v1/images/generations' : '/v1/audio/speech'+ const renderGroups = (gs: MediaGroup[], detailBase: string) => gs.map(g => (+ <MediaGroupCard+ key={g.slug}+ group={g}+ detailBase={detailBase}+ onToggle={(id, enabled) => toggle.mutate({ id, enabled })}+ onDeleteCustom={(id) => deleteCustom.mutate(id)}+ deletePending={deleteCustom.isPending}+ />+ ))+return (<div><PageHeader title={title} description={description} divider={false} actions={<ModelsTabs />} /><div className="space-y-4">+ {modality === 'audio' && <h2 className="text-sm font-medium">{t('models.ttsHeading')}</h2>}<p className="text-xs text-muted-foreground">{t('models.mediaHint')} <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">{endpoint}</code></p>@@ -95,60 +180,26 @@ export function MediaModelsView({ modality }: { modality: 'image' | 'audio' }) {title={t('models.mediaEmpty')}/>) : (- groups.map(g => {- const anyEnabled = g.members.some(m => m.enabled)- const quota = g.members.map(m => m.quotaLabel).find(Boolean)- return (- <section key={g.slug} className={`rounded-3xl border bg-card p-5 ${anyEnabled ? '' : 'opacity-60'}`}>- <div className="mb-3 flex items-center gap-2 flex-wrap">- <Link to={`/models/${modality}/${g.slug}`} className="text-sm font-medium hover:underline">{g.label}</Link>- {g.members.length > 1 ? (- <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-muted text-muted-foreground">- {t('models.providerCount', { count: g.members.length })}- </span>- ) : (- <span className="text-xs text-muted-foreground">{g.members[0].platform}</span>- )}- {quota && (- <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-muted text-muted-foreground tabular-nums">{quota}</span>- )}- </div>-- <div className="divide-y">- {g.members.map(m => (- <div key={m.id} className={`flex items-center gap-3 py-2 ${m.enabled ? '' : 'opacity-50'}`}>- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">{m.platform}</span>- {m.keyCount === 0 && (- <span className="text-[10px] rounded-full px-1.5 py-0.5 bg-amber-600/15 text-amber-700 dark:bg-amber-400/15 dark:text-amber-400">- {t('models.noKey')}- </span>- )}- </div>- <div className="truncate font-mono text-[11px] text-muted-foreground">{m.modelId}</div>- </div>- <Switch- checked={m.enabled}- onCheckedChange={(c) => toggle.mutate({ id: m.id, enabled: c })}- />- {m.isCustom && (- <ConfirmButton- className="text-muted-foreground hover:text-destructive"- onConfirm={() => deleteCustom.mutate(m.id)}- disabled={deleteCustom.isPending}- >- {t('common.remove')}- </ConfirmButton>- )}- </div>- ))}- </div>- </section>- )- })+ renderGroups(groups, `/models/${modality}`))}</div>++ {modality === 'audio' && (+ <div className="mt-10 space-y-4">+ <h2 className="text-sm font-medium">{t('models.sttHeading')}</h2>+ <p className="text-xs text-muted-foreground">+ {t('models.sttHint')} <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">/v1/audio/transcriptions</code>+ </p>++ {isLoading ? (+ <CardSkeleton />+ ) : sttGroups.length === 0 ? (+ <EmptyState icon={Mic} title={t('models.sttEmpty')} />+ ) : (+ renderGroups(sttGroups, '/models/transcription')+ )}+ </div>+ )}</div>)}diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex 6b72b361..5076013a 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -78,9 +78,13 @@"imageTitle": "Image models","audioTitle": "Audio models","imageDesc": "Text-to-image generation models.",- "audioDesc": "Text-to-speech generation models.",+ "audioDesc": "Text-to-speech and speech-to-text models.","mediaHint": "Generate via","mediaEmpty": "No models yet. They sync from the catalog.",+ "ttsHeading": "Text to speech",+ "sttHeading": "Speech to text",+ "sttHint": "Transcribe via",+ "sttEmpty": "No speech-to-text models yet. They sync from the catalog.","newBadge": "New","monthlyTokenBudget": "Monthly token budget","remaining": "remaining",diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex 5b0e94fe..6839c7bf 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -75,9 +75,13 @@"imageTitle": "Modelos de imagen","audioTitle": "Modelos de audio","imageDesc": "Modelos de generación de texto a imagen.",- "audioDesc": "Modelos de generación de texto a voz.",+ "audioDesc": "Modelos de texto a voz y de voz a texto.","mediaHint": "Generar mediante","mediaEmpty": "Aún no hay modelos. Se sincronizan desde el catálogo.",+ "ttsHeading": "Texto a voz",+ "sttHeading": "Voz a texto",+ "sttHint": "Transcribir mediante",+ "sttEmpty": "Aún no hay modelos de voz a texto. Se sincronizan desde el catálogo.","newBadge": "Nuevo","monthlyTokenBudget": "Presupuesto mensual de tokens","remaining": "restante",diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex 43a67eaa..49aa0fcf 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -75,9 +75,13 @@"imageTitle": "Modèles d'image","audioTitle": "Modèles audio","imageDesc": "Modèles de génération texte-image.",- "audioDesc": "Modèles de synthèse vocale.",+ "audioDesc": "Modèles de synthèse et de reconnaissance vocales.","mediaHint": "Générer via","mediaEmpty": "Aucun modèle pour l'instant. Ils se synchronisent depuis le catalogue.",+ "ttsHeading": "Synthèse vocale",+ "sttHeading": "Reconnaissance vocale",+ "sttHint": "Transcrire via",+ "sttEmpty": "Aucun modèle de reconnaissance vocale pour l'instant. Ils se synchronisent depuis le catalogue.","newBadge": "Nouveau","monthlyTokenBudget": "Budget mensuel de tokens","remaining": "restant",diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 1198c42e..98863ea7 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -75,9 +75,13 @@"imageTitle": "Modelli di immagini","audioTitle": "Modelli audio","imageDesc": "Modelli di generazione testo-immagine.",- "audioDesc": "Modelli di generazione testo-parlato.",+ "audioDesc": "Modelli di sintesi e riconoscimento vocale.","mediaHint": "Genera tramite","mediaEmpty": "Nessun modello ancora. Vengono sincronizzati dal catalogo.",+ "ttsHeading": "Sintesi vocale",+ "sttHeading": "Riconoscimento vocale",+ "sttHint": "Trascrivi tramite",+ "sttEmpty": "Nessun modello di riconoscimento vocale ancora. Vengono sincronizzati dal catalogo.","newBadge": "Nuovo","monthlyTokenBudget": "Budget mensile di token","remaining": "rimanenti",diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex fe103e39..8d39142a 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -75,9 +75,13 @@"imageTitle": "Modelos de imagem","audioTitle": "Modelos de áudio","imageDesc": "Modelos de geração de texto para imagem.",- "audioDesc": "Modelos de geração de texto para fala.",+ "audioDesc": "Modelos de texto para fala e de fala para texto.","mediaHint": "Gerar via","mediaEmpty": "Ainda sem modelos. Eles sincronizam do catálogo.",+ "ttsHeading": "Texto para fala",+ "sttHeading": "Fala para texto",+ "sttHint": "Transcrever via",+ "sttEmpty": "Ainda sem modelos de fala para texto. Eles sincronizam do catálogo.","newBadge": "Novo","monthlyTokenBudget": "Orçamento mensal de tokens","remaining": "restante",diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex d182cc96..7bae3ea8 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -75,9 +75,13 @@"imageTitle": "图像模型","audioTitle": "音频模型","imageDesc": "文本生成图像模型。",- "audioDesc": "文本转语音模型。",+ "audioDesc": "文本转语音与语音转文本模型。","mediaHint": "通过以下端点生成","mediaEmpty": "暂无模型,将从目录同步。",+ "ttsHeading": "文本转语音",+ "sttHeading": "语音转文本",+ "sttHint": "通过以下端点转录",+ "sttEmpty": "暂无语音转文本模型,将从目录同步。","newBadge": "新","monthlyTokenBudget": "每月令牌额度","remaining": "剩余",diff --git a/client/src/pages/MediaDetailPage.tsx b/client/src/pages/MediaDetailPage.tsxindex 9c60dbbd..1efa1484 100644--- a/client/src/pages/MediaDetailPage.tsx+++ b/client/src/pages/MediaDetailPage.tsx@@ -12,8 +12,10 @@ import type { MediaModel } from '@/components/media-models'// One generative-media model's page: every provider that serves this logical// model (failover routes across them), plus a ready-to-run snippet. Mirrors the-// chat ModelDetailPage for the image and audio modalities.-export default function MediaDetailPage({ modality }: { modality: 'image' | 'audio' }) {+// chat ModelDetailPage for the image, audio (TTS), and transcription (STT)+// modalities. Transcription models list on the Audio tab, so their back link+// points there.+export default function MediaDetailPage({ modality }: { modality: 'image' | 'audio' | 'transcription' }) {const { t } = useI18n()const { id } = useParams<{ id: string }>()const label = id ? decodeURIComponent(id) : ''@@ -50,7 +52,12 @@ export default function MediaDetailPage({ modality }: { modality: 'image' | 'aud"model": "${exampleModel}","prompt": "a red cat"}'`- : `curl ${base}/audio/speech \\+ : modality === 'transcription'+ ? `curl ${base}/audio/transcriptions \\+ -H "Authorization: Bearer ${key}" \\+ -F [email protected] \\+ -F model="${exampleModel}"`+ : `curl ${base}/audio/speech \\-H "Authorization: Bearer ${key}" \\-H "Content-Type: application/json" \\-d '{@@ -63,7 +70,7 @@ export default function MediaDetailPage({ modality }: { modality: 'image' | 'aud<PageHeader title={label || t('models.providersHeading')} description={t('models.providersHeading')} divider={false} actions={<ModelsTabs />} /><div className="space-y-6">- <Link to={`/models/${modality}`} className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">+ <Link to={modality === 'transcription' ? '/models/audio' : `/models/${modality}`} className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"><ChevronLeft className="size-4" />{t('models.backToModels')}</Link>diff --git a/server/src/__tests__/db/migrate/model-source-provenance.test.ts b/server/src/__tests__/db/migrate/model-source-provenance.test.tsnew file mode 100644index 00000000..b29f642e--- /dev/null+++ b/server/src/__tests__/db/migrate/model-source-provenance.test.ts@@ -0,0 +1,133 @@+import Database from 'better-sqlite3';+import { describe, expect, it } from 'vitest';+import { up as runLegacyBaseline } from '../../../db/migrations/20260101_000000_legacy_baseline.js';+import { down, up } from '../../../db/migrations/20260726_000003_model_source_provenance.js';++// The models.source backfill decides which pre-existing rows catalog-sync is+// allowed to prune. Getting it wrong in the 'catalog' direction deletes+// user-added models on the next sync, so these tests pin the heuristic:+// - custom platform / key-bound / 'User'/'Custom'-labelled rows -> 'user'+// - rows the applied catalog (settings.catalog_applied_json) lists -> 'catalog'+// - rows it does NOT list -> 'user' (sync would have pruned catalog leftovers)+// - no applied catalog at all -> remaining rows are baseline seeds -> 'catalog'++function seededDb(): Database.Database {+ const db = new Database(':memory:');+ runLegacyBaseline(db);+ return db;+}++function insertModel(+ db: Database.Database,+ platform: string,+ modelId: string,+ over: { keyId?: number | null; sizeLabel?: string } = {},+): void {+ db.prepare(`+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label, key_id, enabled)+ VALUES (?, ?, ?, 50, 50, ?, ?, 1)+ `).run(platform, modelId, modelId, over.sizeLabel ?? 'Large', over.keyId ?? null);+}++function sourceOf(db: Database.Database, platform: string, modelId: string): string {+ const row = db+ .prepare('SELECT source FROM models WHERE platform = ? AND model_id = ?')+ .get(platform, modelId) as { source: string };+ return row.source;+}++function setAppliedCatalog(db: Database.Database, value: string): void {+ db.prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)')+ .run('catalog_applied_json', value);+}++describe('20260726_000003_model_source_provenance backfill', () => {+ it('marks custom-platform, key-bound and User/Custom-labelled rows as user', () => {+ const db = seededDb();+ try {+ insertModel(db, 'custom', 'my-endpoint-model', { sizeLabel: 'Custom' });+ insertModel(db, 'groq', 'key-bound-model', { keyId: 42 });+ insertModel(db, 'groq', 'declarative-default-label', { sizeLabel: 'User' });++ up(db);++ expect(sourceOf(db, 'custom', 'my-endpoint-model')).toBe('user');+ expect(sourceOf(db, 'groq', 'key-bound-model')).toBe('user');+ expect(sourceOf(db, 'groq', 'declarative-default-label')).toBe('user');+ } finally {+ db.close();+ }+ });++ it('keeps baseline seeds as catalog when no catalog was ever applied', () => {+ const db = seededDb();+ try {+ up(db);+ const counts = db.prepare(`+ SELECT SUM(CASE WHEN source = 'user' THEN 1 ELSE 0 END) AS user_rows,+ SUM(CASE WHEN source = 'catalog' THEN 1 ELSE 0 END) AS catalog_rows+ FROM models+ `).get() as { user_rows: number; catalog_rows: number };+ // A fresh install has only bundled-baseline rows: all catalog-owned.+ expect(counts.user_rows).toBe(0);+ expect(counts.catalog_rows).toBeGreaterThan(0);+ } finally {+ db.close();+ }+ });++ it('marks rows absent from the applied catalog as user, listed rows as catalog', () => {+ const db = seededDb();+ try {+ // Hand-added native-platform model whose size_label does NOT follow the+ // 'User'/'Custom' convention — exactly the row the old prune guard lost.+ insertModel(db, 'groq', 'hand-added-model', { sizeLabel: 'Large' });++ // Applied catalog = every baseline row except the hand-added one.+ const models = db+ .prepare("SELECT platform, model_id FROM models WHERE model_id != 'hand-added-model'")+ .all() as { platform: string; model_id: string }[];+ setAppliedCatalog(db, JSON.stringify({+ version: '2099.01.01',+ tier: 'live',+ models: models.map((m) => ({ platform: m.platform, modelId: m.model_id })),+ quirks: [],+ }));++ up(db);++ expect(sourceOf(db, 'groq', 'hand-added-model')).toBe('user');+ const listed = models[0]!;+ expect(sourceOf(db, listed.platform, listed.model_id)).toBe('catalog');+ } finally {+ db.close();+ }+ });++ it('survives a corrupt cached catalog and still applies the heuristics', () => {+ const db = seededDb();+ try {+ insertModel(db, 'custom', 'corrupt-cache-model', { sizeLabel: 'Custom' });+ setAppliedCatalog(db, 'not json {');++ expect(() => up(db)).not.toThrow();+ expect(sourceOf(db, 'custom', 'corrupt-cache-model')).toBe('user');+ } finally {+ db.close();+ }+ });++ it('down drops the column and up is re-runnable', () => {+ const db = seededDb();+ try {+ up(db);+ down(db);+ const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];+ expect(columns.some((c) => c.name === 'source')).toBe(false);+ expect(() => up(db)).not.toThrow();+ expect(() => up(db)).not.toThrow();+ } finally {+ db.close();+ }+ });+});diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 292f45e8..990b6b15 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -14,6 +14,9 @@ const CUSTOM_MODEL_TOOL_SUPPORT_FILENAME = '20260706_000002_custom_model_tool_suconst PROFILE_CHAIN_BACKFILL_FILENAME = '20260714_000001_profile_chain_backfill.ts';const KEY_HEALTH_ERROR_FILENAME = '20260720_000001_key_health_error.ts';const COOLDOWN_PROBE_PROVENANCE_FILENAME = '20260726_000001_cooldown_probe_provenance.ts';+const REQUEST_ATTEMPTS_FILENAME = '20260726_000002_request_attempts.ts';+const MODEL_SOURCE_PROVENANCE_FILENAME = '20260726_000003_model_source_provenance.ts';+const MEDIA_MODEL_META_FILENAME = '20260726_000004_media_model_meta.ts';interface SchemaRow {type: string;@@ -74,6 +77,9 @@ describe('migration round trip', () => {PROFILE_CHAIN_BACKFILL_FILENAME,KEY_HEALTH_ERROR_FILENAME,COOLDOWN_PROBE_PROVENANCE_FILENAME,+ REQUEST_ATTEMPTS_FILENAME,+ MODEL_SOURCE_PROVENANCE_FILENAME,+ MEDIA_MODEL_META_FILENAME,]);} finally {db.close();@@ -92,8 +98,8 @@ describe('migration round trip', () => {// post-migration state, tools = 1) so the round trip actually exercises// that migration's down (tools -> 0) and up (tools -> 1).db.prepare(`- INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, supports_tools, supports_vision, enabled)- VALUES ('custom', 'roundtrip-custom', 'Roundtrip Custom', 50, 50, 1, 0, 1)+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, supports_tools, supports_vision, enabled, source)+ VALUES ('custom', 'roundtrip-custom', 'Roundtrip Custom', 50, 50, 1, 0, 1, 'user')`).run();const fullState = snapshotAppState(db);diff --git a/server/src/__tests__/lib/request-attempts.test.ts b/server/src/__tests__/lib/request-attempts.test.tsnew file mode 100644index 00000000..b106f592--- /dev/null+++ b/server/src/__tests__/lib/request-attempts.test.ts@@ -0,0 +1,191 @@+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';++// Durable per-attempt routing traces (P2 #15): the fallback loop records every+// dispatched attempt — failures AND the successful final one — with timing and+// outcome, and persists them to `request_attempts` keyed to the terminal+// `requests` row, in one insert batch after the response finishes. Children+// are pruned with their parents (ON DELETE CASCADE + foreign_keys=ON).++const { mockCheckKeyHealth } = vi.hoisted(() => ({ mockCheckKeyHealth: vi.fn() }));+vi.mock('../../services/health.js', () => ({+ checkKeyHealth: mockCheckKeyHealth,+ markKeyHealthyFromRequest: vi.fn(),+}));++import { initDb, getDb } from '../../db/index.js';+import { runFallbackLoop, newFallbackState, type FallbackHooks } from '../../lib/fallback-loop.js';+import { logRequest } from '../../lib/request-log.js';+import { pruneRequestAnalytics } from '../../services/request-retention.js';+import type { RouteResult } from '../../services/router.js';++// Distinct keyId AND modelDbId per fake route: the router's penalty map and the+// cooldown store are module-global, so shared ids would leak state across tests.+let keySeq = 900;+function fakeRoute(overrides: Partial<RouteResult> = {}): RouteResult {+ const n = ++keySeq;+ return {+ provider: {} as any, modelId: 'fake-model', modelDbId: 787000 + n, apiKey: 'k',+ keyId: n, platform: 'fake', displayName: 'Fake Model',+ rpdLimit: null, tpdLimit: null,+ ...overrides,+ };+}++function hooksSkeleton(overrides: Partial<FallbackHooks>): FallbackHooks {+ return {+ state: newFallbackState(),+ timeBudgetMs: 0,+ route: () => fakeRoute(),+ dispatch: async () => 'done',+ logFailure: () => {},+ onFatal: () => { throw new Error('unexpected onFatal'); },+ onRoutingExhausted: () => { throw new Error('unexpected onRoutingExhausted'); },+ onExhausted: () => { throw new Error('unexpected onExhausted'); },+ ...overrides,+ };+}++interface AttemptRow {+ request_id: number;+ ordinal: number;+ platform: string;+ model_id: string;+ key_ordinal: number;+ outcome: string;+ start_offset_ms: number;+ duration_ms: number;+}++function allAttempts(): AttemptRow[] {+ return getDb().prepare(+ 'SELECT request_id, ordinal, platform, model_id, key_ordinal, outcome, start_offset_ms, duration_ms FROM request_attempts ORDER BY ordinal',+ ).all() as AttemptRow[];+}++beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+});++beforeEach(() => {+ mockCheckKeyHealth.mockReset();+ mockCheckKeyHealth.mockResolvedValue('invalid');+ const db = getDb();+ db.prepare('DELETE FROM request_attempts').run();+ db.prepare('DELETE FROM requests').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+});++describe('per-attempt routing traces', () => {+ it('persists the full multi-attempt ladder, ordered, with error classes and timings, keyed to the terminal success row', async () => {+ const routes = [+ fakeRoute({ platform: 'groq', modelId: 'llama-x' }),+ fakeRoute({ platform: 'google', modelId: 'gemini-y' }),+ fakeRoute({ platform: 'cerebras', modelId: 'qwen-z' }),+ ];++ await runFallbackLoop(hooksSkeleton({+ route: (attempt) => routes[Math.min(attempt, routes.length - 1)],+ dispatch: async (route, attempt) => {+ await new Promise(r => setTimeout(r, 10));+ if (attempt === 0) throw Object.assign(new Error('429 Too Many Requests'), { status: 429 });+ if (attempt === 1) throw new Error('upstream timeout after 10000ms');+ logRequest(route.platform, route.modelId, route.keyId, 'success', 10, 5, 42, null);+ return 'done';+ },+ logFailure: (route, err) =>+ logRequest(route.platform, route.modelId, route.keyId, 'error', 10, 0, 5, err.message),+ }));++ const successRow = getDb().prepare("SELECT id FROM requests WHERE status = 'success'").get() as { id: number };+ const rows = allAttempts();++ expect(rows).toHaveLength(3);+ expect(rows.map(r => r.ordinal)).toEqual([0, 1, 2]);+ expect(rows.map(r => r.outcome)).toEqual(['rate_limited', 'timeout', 'ok']);+ expect(rows.map(r => r.platform)).toEqual(['groq', 'google', 'cerebras']);+ expect(rows.map(r => r.model_id)).toEqual(['llama-x', 'gemini-y', 'qwen-z']);+ // Per-request key ordinals, never raw key ids.+ expect(rows.map(r => r.key_ordinal)).toEqual([1, 2, 3]);+ // Every attempt hangs off the SAME parent: the terminal success row.+ expect(new Set(rows.map(r => r.request_id))).toEqual(new Set([successRow.id]));++ // Timing: offsets are ladder-relative and monotonic; each attempt ran+ // for at least its simulated 10ms.+ expect(rows[0].start_offset_ms).toBeGreaterThanOrEqual(0);+ expect(rows[1].start_offset_ms).toBeGreaterThan(rows[0].start_offset_ms);+ expect(rows[2].start_offset_ms).toBeGreaterThan(rows[1].start_offset_ms);+ for (const r of rows) expect(r.duration_ms).toBeGreaterThanOrEqual(5);++ // The mid-ladder failure rows carry no children of their own.+ const errorIds = getDb().prepare("SELECT id FROM requests WHERE status = 'error'").all() as { id: number }[];+ expect(errorIds).toHaveLength(2);+ for (const { id } of errorIds) {+ const c = getDb().prepare('SELECT COUNT(*) as c FROM request_attempts WHERE request_id = ?').get(id) as { c: number };+ expect(c.c).toBe(0);+ }+ });++ it("persists exactly one 'ok' attempt for a single-attempt success", async () => {+ const route = fakeRoute({ platform: 'groq', modelId: 'solo-model' });+ await runFallbackLoop(hooksSkeleton({+ route: () => route,+ dispatch: async () => {+ logRequest(route.platform, route.modelId, route.keyId, 'success', 3, 7, 11, null);+ return 'done';+ },+ }));++ const parent = getDb().prepare("SELECT id FROM requests WHERE status = 'success'").get() as { id: number };+ const rows = allAttempts();+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ request_id: parent.id,+ ordinal: 0,+ platform: 'groq',+ model_id: 'solo-model',+ key_ordinal: 1,+ outcome: 'ok',+ start_offset_ms: 0,+ });+ expect(rows[0].duration_ms).toBeGreaterThanOrEqual(0);+ });++ it('persists the failure ladder keyed to the last error row when every attempt fails', async () => {+ await runFallbackLoop(hooksSkeleton({+ maxRetries: 2,+ route: () => fakeRoute({ platform: 'fake', modelId: 'always-429' }),+ dispatch: async () => {+ throw Object.assign(new Error('429 Too Many Requests'), { status: 429 });+ },+ logFailure: (route, err) =>+ logRequest(route.platform, route.modelId, route.keyId, 'error', 1, 0, 5, err.message),+ onExhausted: () => {},+ }));++ const lastErrorRow = getDb().prepare('SELECT id FROM requests ORDER BY id DESC LIMIT 1').get() as { id: number };+ const rows = allAttempts();+ expect(rows).toHaveLength(2);+ expect(rows.map(r => r.outcome)).toEqual(['rate_limited', 'rate_limited']);+ expect(new Set(rows.map(r => r.request_id))).toEqual(new Set([lastErrorRow.id]));+ });++ it('prunes request_attempts rows with their parent requests rows (retention)', () => {+ const db = getDb();+ db.prepare(`+ INSERT INTO requests (platform, model_id, status, input_tokens, output_tokens, latency_ms, error, created_at)+ VALUES ('test', 'old-model', 'success', 1, 1, 1, NULL, '2020-01-01 00:00:00')+ `).run();+ const parent = db.prepare('SELECT id FROM requests ORDER BY id DESC LIMIT 1').get() as { id: number };+ db.prepare(`+ INSERT INTO request_attempts (request_id, ordinal, platform, model_id, key_ordinal, outcome, start_offset_ms, duration_ms)+ VALUES (?, 0, 'test', 'old-model', 1, 'rate_limited', 0, 12), (?, 1, 'test', 'old-model', 2, 'ok', 20, 30)+ `).run(parent.id, parent.id);+ expect(allAttempts()).toHaveLength(2);++ const { deleted } = pruneRequestAnalytics({ force: true });+ expect(deleted).toBeGreaterThanOrEqual(1);+ expect(db.prepare('SELECT COUNT(*) as c FROM requests WHERE id = ?').get(parent.id)).toEqual({ c: 0 });+ expect(allAttempts()).toHaveLength(0);+ });+});diff --git a/server/src/__tests__/lib/sampling-params.test.ts b/server/src/__tests__/lib/sampling-params.test.tsindex 3e2e9bd3..3ee4e956 100644--- a/server/src/__tests__/lib/sampling-params.test.ts+++ b/server/src/__tests__/lib/sampling-params.test.ts@@ -41,6 +41,7 @@ describe('extendedBodyParams (per-platform policy)', () => {top_k: 40, min_p: 0.05, seed: 7, presence_penalty: 1, frequency_penalty: -1,repetition_penalty: 1.1, logit_bias: { '50256': -100 }, logprobs: true, top_logprobs: 3,response_format: { type: 'json_object' as const },+ reasoning_effort: 'medium' as const,};it('forwards everything for platforms without a policy', () => {@@ -104,6 +105,52 @@ describe('supportedParametersFor / supportedParametersForPlatforms', () => {});});+describe('reasoning_effort (request-side reasoning control)', () => {+ it('pickSamplingParams forwards the flat field and drops explicit null', () => {+ expect(pickSamplingParams({ reasoning_effort: 'low' })).toEqual({ reasoning_effort: 'low' });+ expect(pickSamplingParams({ reasoning_effort: null })).toEqual({});+ });++ it('tolerates the object form: reasoning:{effort} resolves to reasoning_effort', () => {+ expect(pickSamplingParams({ reasoning: { effort: 'high' } })).toEqual({ reasoning_effort: 'high' });+ });++ it('flat reasoning_effort wins over the object form on conflict', () => {+ expect(pickSamplingParams({ reasoning_effort: 'low', reasoning: { effort: 'high' } }))+ .toEqual({ reasoning_effort: 'low' });+ });++ it('object form without a usable effort is ignored (never forwarded as-is)', () => {+ expect(pickSamplingParams({ reasoning: null })).toEqual({});+ expect(pickSamplingParams({ reasoning: {} })).toEqual({});+ expect(pickSamplingParams({ reasoning: { effort: null } })).toEqual({});+ });++ it('forwarded verbatim on openai-compat platforms without a droplist entry', () => {+ expect(extendedBodyParams('groq', { reasoning_effort: 'medium' }).reasoning_effort).toBe('medium');+ expect(extendedBodyParams('cerebras', { reasoning_effort: 'none' }).reasoning_effort).toBe('none');+ expect(extendedBodyParams('github', { reasoning_effort: 'high' }).reasoning_effort).toBe('high');+ });++ it('stripped for platforms with no support (never 400s a strict upstream)', () => {+ for (const platform of ['mistral', 'cohere', 'cloudflare', 'aihorde']) {+ expect(extendedBodyParams(platform, { reasoning_effort: 'high' })).not.toHaveProperty('reasoning_effort');+ }+ });++ it('a request without the knob sends nothing new (default behavior unchanged)', () => {+ expect(extendedBodyParams('groq', { seed: 1 })).toEqual({ seed: 1 });+ expect(pickSamplingParams({ seed: 1 })).toEqual({ seed: 1 });+ });++ it('advertised in supported_parameters only where it is forwarded', () => {+ expect(supportedParametersFor('groq')).toContain('reasoning_effort');+ expect(supportedParametersFor('cerebras')).toContain('reasoning_effort');+ expect(supportedParametersFor('mistral')).not.toContain('reasoning_effort');+ expect(supportedParametersFor('cohere')).not.toContain('reasoning_effort');+ });+});+describe('live-sweep policy findings (2026-07-11 demo-box validation)', () => {it('kilo: response_format dropped (gateway 400s on it), seed still forwarded', () => {const body = extendedBodyParams('kilo', { seed: 7, response_format: { type: 'json_object' } });diff --git a/server/src/__tests__/lib/think-tags.test.ts b/server/src/__tests__/lib/think-tags.test.tsnew file mode 100644index 00000000..efcdc9fc--- /dev/null+++ b/server/src/__tests__/lib/think-tags.test.ts@@ -0,0 +1,189 @@+import { describe, it, expect } from 'vitest';+import type { ChatCompletionChunk } from '@freellmapi/shared/types.js';+import {+ splitThinkTag,+ extractThinkFromMessage,+ ThinkTagStreamFilter,+ extractThinkTagsFromStream,+} from '../../lib/think-tags.js';++describe('splitThinkTag (non-streaming)', () => {+ it('extracts a leading <think> block into reasoning', () => {+ expect(splitThinkTag('<think>plan the answer</think>Hello!')).toEqual({+ content: 'Hello!',+ reasoning: 'plan the answer',+ });+ });++ it('tolerates whitespace before the opening tag and after the closing tag', () => {+ expect(splitThinkTag('\n <think>hmm</think>\n\nAnswer')).toEqual({+ content: 'Answer',+ reasoning: 'hmm',+ });+ });++ it('leaves a message without an opening tag untouched', () => {+ expect(splitThinkTag('Just a normal answer.')).toEqual({+ content: 'Just a normal answer.',+ reasoning: '',+ });+ });++ it('does NOT extract a tag quoted mid-answer (start-anchored on purpose)', () => {+ const text = 'The model emits <think>…</think> around its reasoning.';+ expect(splitThinkTag(text)).toEqual({ content: text, reasoning: '' });+ });++ it('unclosed tag: the whole body becomes reasoning, nothing is lost', () => {+ expect(splitThinkTag('<think>ran out of tokens mid-thought')).toEqual({+ content: '',+ reasoning: 'ran out of tokens mid-thought',+ });+ });++ it('extracts only the FIRST block; later literal tags stay in content', () => {+ expect(splitThinkTag('<think>a</think>x <think>b</think> y')).toEqual({+ content: 'x <think>b</think> y',+ reasoning: 'a',+ });+ });+});++describe('extractThinkFromMessage', () => {+ it('moves the block into reasoning_content in place', () => {+ const msg: { content?: unknown; reasoning_content?: string } = { content: '<think>why</think>because' };+ extractThinkFromMessage(msg);+ expect(msg.content).toBe('because');+ expect(msg.reasoning_content).toBe('why');+ });++ it('appends to a provider-set reasoning_content instead of clobbering it', () => {+ const msg = { content: '<think>more</think>ok', reasoning_content: 'native' };+ extractThinkFromMessage(msg);+ expect(msg.content).toBe('ok');+ expect(msg.reasoning_content).toBe('native\nmore');+ });++ it('is a no-op for tag-free content and non-string content', () => {+ const plain = { content: 'hello', reasoning_content: undefined as string | undefined };+ extractThinkFromMessage(plain);+ expect(plain).toEqual({ content: 'hello', reasoning_content: undefined });++ const nullContent: { content?: unknown; reasoning_content?: string } = { content: null };+ extractThinkFromMessage(nullContent);+ expect(nullContent.content).toBeNull();+ });+});++describe('ThinkTagStreamFilter (chunk-boundary handling)', () => {+ it('handles the opening tag split across pushes', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('<thi')).toEqual({ content: '', reasoning: '' });+ expect(f.push('nk>deep')).toEqual({ content: '', reasoning: 'deep' });+ expect(f.push(' thought</think>Answer')).toEqual({ content: 'Answer', reasoning: ' thought' });+ expect(f.flush()).toEqual({ content: '', reasoning: '' });+ });++ it('handles the closing tag split across pushes', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('<think>abc</thi')).toEqual({ content: '', reasoning: 'abc' });+ expect(f.push('nk>Done')).toEqual({ content: 'Done', reasoning: '' });+ });++ it('a lone "<" mid-reasoning is held then released as reasoning', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('<think>a <')).toEqual({ content: '', reasoning: 'a ' });+ expect(f.push('b')).toEqual({ content: '', reasoning: '<b' });+ });++ it('unclosed tag at stream end: held partial close-tag bytes flush as reasoning', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('<think>abc</thi')).toEqual({ content: '', reasoning: 'abc' });+ expect(f.flush()).toEqual({ content: '', reasoning: '</thi' });+ });++ it('an undecided opening prefix at stream end flushes as content (text never lost)', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('<thi')).toEqual({ content: '', reasoning: '' });+ expect(f.flush()).toEqual({ content: '<thi', reasoning: '' });+ });++ it('passes non-think text through immediately (no buffering after decision)', () => {+ const f = new ThinkTagStreamFilter();+ expect(f.push('Hello')).toEqual({ content: 'Hello', reasoning: '' });+ // Once decided, even literal tags stream straight through.+ expect(f.push(' <think>x</think>')).toEqual({ content: ' <think>x</think>', reasoning: '' });+ });+});++function chunk(delta: Record<string, unknown>, finish: string | null = null): ChatCompletionChunk {+ return {+ id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'm',+ choices: [{ index: 0, delta: delta as ChatCompletionChunk['choices'][0]['delta'], finish_reason: finish }],+ };+}++async function* gen(chunks: ChatCompletionChunk[]): AsyncGenerator<ChatCompletionChunk> {+ for (const c of chunks) yield c;+}++async function collect(source: AsyncGenerator<ChatCompletionChunk>): Promise<ChatCompletionChunk[]> {+ const out: ChatCompletionChunk[] = [];+ for await (const c of source) out.push(c);+ return out;+}++describe('extractThinkTagsFromStream', () => {+ it('rewrites think content into delta.reasoning_content across split chunks', async () => {+ const out = await collect(extractThinkTagsFromStream(gen([+ chunk({ role: 'assistant' }),+ chunk({ content: '<think>rea' }),+ chunk({ content: 'soning</th' }),+ chunk({ content: 'ink>Answer' }),+ chunk({}, 'stop'),+ ])));+ const reasoning = out.map(c => c.choices?.[0]?.delta?.reasoning_content ?? '').join('');+ const content = out.map(c => c.choices?.[0]?.delta?.content ?? '').join('');+ expect(reasoning).toBe('reasoning');+ expect(content).toBe('Answer');+ });++ it('leaves tag-free streams untouched (fast path)', async () => {+ const src = [chunk({ content: 'Hello ' }), chunk({ content: 'world' }), chunk({}, 'stop')];+ const out = await collect(extractThinkTagsFromStream(gen(src)));+ expect(out).toHaveLength(3);+ expect(out[0].choices[0].delta.content).toBe('Hello ');+ expect(out[0].choices[0].delta.reasoning_content).toBeUndefined();+ expect(out[1].choices[0].delta.content).toBe('world');+ });++ it('unclosed tag at stream end: held bytes flush as a final reasoning chunk', async () => {+ const out = await collect(extractThinkTagsFromStream(gen([+ chunk({ content: '<think>abc</thi' }),+ chunk({}, 'length'),+ ])));+ const tail = out[out.length - 1];+ expect(tail.choices[0].delta.reasoning_content).toBe('</thi');+ const reasoning = out.map(c => c.choices?.[0]?.delta?.reasoning_content ?? '').join('');+ expect(reasoning).toBe('abc</thi');+ expect(out.map(c => c.choices?.[0]?.delta?.content ?? '').join('')).toBe('');+ });++ it('an undecided opening prefix flushes as a final content chunk', async () => {+ const out = await collect(extractThinkTagsFromStream(gen([+ chunk({ content: '<thi' }),+ chunk({}, 'stop'),+ ])));+ const tail = out[out.length - 1];+ expect(tail.choices[0].delta.content).toBe('<thi');+ expect(tail.choices[0].delta.reasoning_content).toBeUndefined();+ });++ it('passes non-content frames (tool calls, usage) through untouched', async () => {+ const toolChunk = chunk({ tool_calls: [{ index: 0, id: 't1', type: 'function', function: { name: 'f', arguments: '{}' } }] });+ const usageChunk = { id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } } as unknown as ChatCompletionChunk;+ const out = await collect(extractThinkTagsFromStream(gen([toolChunk, usageChunk, chunk({}, 'tool_calls')])));+ expect(out[0]).toBe(toolChunk);+ expect(out[1]).toBe(usageChunk);+ });+});diff --git a/server/src/__tests__/providers/google-params.test.ts b/server/src/__tests__/providers/google-params.test.tsindex 18fd454c..aaf72bf5 100644--- a/server/src/__tests__/providers/google-params.test.ts+++ b/server/src/__tests__/providers/google-params.test.ts@@ -72,4 +72,25 @@ describe('toGeminiExtendedConfig', () => {expect(cfg.topK).toBeUndefined();expect(cfg.responseMimeType).toBeUndefined();});++ it('reasoning_effort maps to thinkingConfig with the effort-tier budget', () => {+ expect(toGeminiExtendedConfig({ reasoning_effort: 'low' }).thinkingConfig)+ .toEqual({ thinkingBudget: 1024, includeThoughts: true });+ expect(toGeminiExtendedConfig({ reasoning_effort: 'medium' }).thinkingConfig)+ .toEqual({ thinkingBudget: 8192, includeThoughts: true });+ expect(toGeminiExtendedConfig({ reasoning_effort: 'high' }).thinkingConfig)+ .toEqual({ thinkingBudget: 24576, includeThoughts: true });+ });++ it("reasoning_effort 'none'/'minimal' disables thinking (budget 0)", () => {+ expect(toGeminiExtendedConfig({ reasoning_effort: 'none' }).thinkingConfig)+ .toEqual({ thinkingBudget: 0 });+ expect(toGeminiExtendedConfig({ reasoning_effort: 'minimal' }).thinkingConfig)+ .toEqual({ thinkingBudget: 0 });+ });++ it('no reasoning_effort → no thinkingConfig (model default preserved)', () => {+ expect(toGeminiExtendedConfig({ seed: 1 })).not.toHaveProperty('thinkingConfig');+ expect(toGeminiExtendedConfig(undefined)).not.toHaveProperty('thinkingConfig');+ });});diff --git a/server/src/__tests__/providers/openai-compat.test.ts b/server/src/__tests__/providers/openai-compat.test.tsindex 0fc2b5d9..686c805a 100644--- a/server/src/__tests__/providers/openai-compat.test.ts+++ b/server/src/__tests__/providers/openai-compat.test.ts@@ -695,3 +695,145 @@ describe('extended sampling param passthrough', () => {expect(raw).not.toContain('logit_bias');});});++describe('reasoning: request knob + <think> extraction (P2 #16)', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const mockOk = (content: string, extra: Record<string, unknown> = {}) => ({+ ok: true,+ json: () => Promise.resolve({+ id: 'x', object: 'chat.completion', created: 1, model: 'm',+ choices: [{ index: 0, message: { role: 'assistant', content, ...extra }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ }),+ }) as any;++ function sse(frames: string[]): any {+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ const encoder = new TextEncoder();+ for (const f of frames) controller.enqueue(encoder.encode(f));+ controller.close();+ },+ });+ return { ok: true, body: stream, headers: new Headers() };+ }++ async function collect<T>(g: AsyncGenerator<T>): Promise<T[]> {+ const out: T[] = [];+ for await (const c of g) out.push(c);+ return out;+ }++ const dataFrame = (delta: Record<string, unknown>, finish: string | null = null) =>+ `data: ${JSON.stringify({ id: 's1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`;++ it('forwards reasoning_effort on the wire for a supporting platform', async () => {+ let body: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ body = JSON.parse((init as any).body);+ return mockOk('hi');+ });+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ await p.chatCompletion('k', [{ role: 'user', content: 'q' }], 'm', { reasoning_effort: 'low' });+ expect(body.reasoning_effort).toBe('low');+ });++ it('strips reasoning_effort for a platform whose policy drops it (mistral)', async () => {+ let body: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ body = JSON.parse((init as any).body);+ return mockOk('hi');+ });+ const p = new OpenAICompatProvider({ platform: 'mistral', name: 'T', baseUrl: 'https://x/v1' });+ await p.chatCompletion('k', [{ role: 'user', content: 'q' }], 'm', { reasoning_effort: 'high' });+ expect(body).not.toHaveProperty('reasoning_effort');+ });++ it('sends nothing reasoning-related when the knob is absent (default unchanged)', async () => {+ let raw = '';+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ raw = (init as any).body;+ return mockOk('hi');+ });+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ await p.chatCompletion('k', [{ role: 'user', content: 'q' }], 'm', { temperature: 0 });+ expect(raw).not.toContain('reasoning');+ });++ it('non-streaming: a leading <think> block moves into reasoning_content', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => mockOk('<think>chain of thought</think>The answer is 4.'));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const res = await p.chatCompletion('k', [{ role: 'user', content: '2+2?' }], 'm');+ const msg = res.choices[0].message as any;+ expect(msg.content).toBe('The answer is 4.');+ expect(msg.reasoning_content).toBe('chain of thought');+ });++ it('non-streaming: a think-only message still folds back into content (never empty)', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => mockOk('<think>all reasoning, no answer</think>'));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const res = await p.chatCompletion('k', [{ role: 'user', content: 'q' }], 'm');+ const msg = res.choices[0].message as any;+ expect(msg.content).toBe('all reasoning, no answer');+ expect(msg.reasoning_content).toBe('all reasoning, no answer');+ });++ it('non-streaming: tag-free content is untouched', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => mockOk('plain answer'));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const res = await p.chatCompletion('k', [{ role: 'user', content: 'q' }], 'm');+ const msg = res.choices[0].message as any;+ expect(msg.content).toBe('plain answer');+ expect(msg.reasoning_content).toBeUndefined();+ });++ it('streaming: think content becomes delta.reasoning_content even when the tags split across chunks', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => sse([+ dataFrame({ role: 'assistant' }),+ dataFrame({ content: '<thi' }),+ dataFrame({ content: 'nk>step one, ' }),+ dataFrame({ content: 'step two</th' }),+ dataFrame({ content: 'ink>Final answer' }),+ dataFrame({}, 'stop'),+ 'data: [DONE]\n\n',+ ]));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const chunks = await collect(p.streamChatCompletion('k', [{ role: 'user', content: 'q' }], 'm'));+ const reasoning = chunks.map(c => (c.choices?.[0]?.delta as any)?.reasoning_content ?? '').join('');+ const content = chunks.map(c => c.choices?.[0]?.delta?.content ?? '').join('');+ expect(reasoning).toBe('step one, step two');+ expect(content).toBe('Final answer');+ });++ it('streaming: an unclosed <think> at stream end flushes as reasoning, losing no text', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => sse([+ dataFrame({ content: '<think>truncated thought</thi' }),+ dataFrame({}, 'length'),+ 'data: [DONE]\n\n',+ ]));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const chunks = await collect(p.streamChatCompletion('k', [{ role: 'user', content: 'q' }], 'm'));+ const reasoning = chunks.map(c => (c.choices?.[0]?.delta as any)?.reasoning_content ?? '').join('');+ const content = chunks.map(c => c.choices?.[0]?.delta?.content ?? '').join('');+ expect(reasoning).toBe('truncated thought</thi');+ expect(content).toBe('');+ });++ it('streaming: a tag-free stream is byte-identical (no synthetic frames, no reasoning)', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async () => sse([+ dataFrame({ role: 'assistant' }),+ dataFrame({ content: 'Hello ' }),+ dataFrame({ content: 'world' }),+ dataFrame({}, 'stop'),+ 'data: [DONE]\n\n',+ ]));+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'T', baseUrl: 'https://x/v1' });+ const chunks = await collect(p.streamChatCompletion('k', [{ role: 'user', content: 'q' }], 'm'));+ expect(chunks).toHaveLength(4);+ expect(chunks.map(c => c.choices?.[0]?.delta?.content ?? '').join('')).toBe('Hello world');+ expect(chunks.some(c => (c.choices?.[0]?.delta as any)?.reasoning_content != null)).toBe(false);+ });+});diff --git a/server/src/__tests__/routes/analytics-request-attempts.test.ts b/server/src/__tests__/routes/analytics-request-attempts.test.tsnew file mode 100644index 00000000..24706bf5--- /dev/null+++ b/server/src/__tests__/routes/analytics-request-attempts.test.ts@@ -0,0 +1,107 @@+import { beforeAll, beforeEach, describe, expect, it } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { getDb, initDb } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++// Read surface for per-attempt routing traces: the requests list carries a+// cheap attemptCount per row, and GET /api/analytics/requests/:id returns the+// row plus its ordinal-ordered attempts ladder (machine-readable).++let dashToken = '';++async function request(app: Express, path: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const url = `http://127.0.0.1:${addr.port}${path}`;++ const res = await fetch(url, {+ headers: { Authorization: `Bearer ${dashToken}` },+ });+ const data = await res.json().catch(() => null);+ server.close();++ return { status: res.status, body: data };+}++function insertRequest(status: string, createdAt: string): number {+ const insert = getDb().prepare(`+ INSERT INTO requests (platform, model_id, status, input_tokens, output_tokens, latency_ms, error, created_at)+ VALUES ('cerebras', 'qwen-z', ?, 10, 5, 1234, NULL, ?)+ `).run(status, createdAt);+ return Number(insert.lastInsertRowid);+}++function insertAttempt(requestId: number, ordinal: number, platform: string, modelId: string, keyOrdinal: number, outcome: string, startOffsetMs: number, durationMs: number) {+ getDb().prepare(`+ INSERT INTO request_attempts (request_id, ordinal, platform, model_id, key_ordinal, outcome, start_offset_ms, duration_ms)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ `).run(requestId, ordinal, platform, modelId, keyOrdinal, outcome, startOffsetMs, durationMs);+}++function recentSql(hour: number): string {+ const day = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().slice(0, 10);+ return `${day} ${String(hour).padStart(2, '0')}:00:00`;+}++describe('per-attempt traces in the analytics requests API', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM request_attempts').run();+ getDb().prepare('DELETE FROM requests').run();+ });++ it('includes attemptCount per row in the list payload', async () => {+ const laddered = insertRequest('success', recentSql(10));+ insertAttempt(laddered, 0, 'groq', 'llama-x', 1, 'rate_limited', 0, 210);+ insertAttempt(laddered, 1, 'google', 'gemini-y', 2, 'timeout', 215, 10000);+ insertAttempt(laddered, 2, 'cerebras', 'qwen-z', 3, 'ok', 10220, 900);+ insertRequest('error', recentSql(11)); // mid-ladder row: no children++ const { status, body } = await request(app, '/api/analytics/requests?range=7d');+ expect(status).toBe(200);+ // Newest first: the childless error row, then the laddered success row.+ expect(body.rows.map((r: any) => r.attemptCount)).toEqual([0, 3]);+ });++ it('returns the ordered attempts ladder in the per-request detail payload', async () => {+ const id = insertRequest('success', recentSql(12));+ insertAttempt(id, 0, 'groq', 'llama-x', 1, 'rate_limited', 0, 210);+ insertAttempt(id, 1, 'google', 'gemini-y', 2, 'timeout', 215, 10000);+ insertAttempt(id, 2, 'cerebras', 'qwen-z', 3, 'ok', 10220, 900);++ const { status, body } = await request(app, `/api/analytics/requests/${id}`);+ expect(status).toBe(200);+ expect(body).toMatchObject({+ id,+ platform: 'cerebras',+ modelId: 'qwen-z',+ status: 'success',+ latencyMs: 1234,+ });+ expect(body.attempts).toEqual([+ { ordinal: 0, platform: 'groq', modelId: 'llama-x', keyOrdinal: 1, outcome: 'rate_limited', startOffsetMs: 0, durationMs: 210 },+ { ordinal: 1, platform: 'google', modelId: 'gemini-y', keyOrdinal: 2, outcome: 'timeout', startOffsetMs: 215, durationMs: 10000 },+ { ordinal: 2, platform: 'cerebras', modelId: 'qwen-z', keyOrdinal: 3, outcome: 'ok', startOffsetMs: 10220, durationMs: 900 },+ ]);+ });++ it('returns an empty attempts array for a row without children, and 404/400 for missing/invalid ids', async () => {+ const id = insertRequest('error', recentSql(13));++ const detail = await request(app, `/api/analytics/requests/${id}`);+ expect(detail.status).toBe(200);+ expect(detail.body.attempts).toEqual([]);++ expect((await request(app, '/api/analytics/requests/999999')).status).toBe(404);+ expect((await request(app, '/api/analytics/requests/not-a-number')).status).toBe(400);+ });+});diff --git a/server/src/__tests__/routes/audio-transcriptions.test.ts b/server/src/__tests__/routes/audio-transcriptions.test.tsnew file mode 100644index 00000000..11f2c092--- /dev/null+++ b/server/src/__tests__/routes/audio-transcriptions.test.ts@@ -0,0 +1,274 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { MAX_TRANSCRIPTION_BYTES } from '../../services/media.js';+import { clearCooldownsForKey } from '../../services/ratelimit.js';++const realFetch = globalThis.fetch;++function addKey(platform: string, raw = `${platform}-test-key`): number {+ const { encrypted, iv, authTag } = encrypt(raw);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1)+ `).run(platform, encrypted, iv, authTag);+ return Number(row.lastInsertRowid);+}++function jsonResponse(body: unknown, status = 200) {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+}++/** Seed the catalog-delivered STT registry (media_models, modality+ * 'transcription') exactly as the published `transcriptionModels` fragment+ * would land it via catalog-sync. */+function seedTranscriptionModels(): void {+ const insert = getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES (?, ?, ?, 'transcription', ?, 1, '', ?)+ `);+ insert.run('groq', 'whisper-large-v3-turbo', 'Whisper Large v3 Turbo (Groq)', 0,+ JSON.stringify({ maxBytes: 25 * 1024 * 1024 }));+ insert.run('groq', 'whisper-large-v3', 'Whisper Large v3 (Groq)', 1,+ JSON.stringify({ maxBytes: 25 * 1024 * 1024 }));+ insert.run('cloudflare', '@cf/openai/whisper-large-v3-turbo', 'Whisper Large v3 Turbo (Cloudflare Workers AI)', 2,+ JSON.stringify({ subtitleFormats: ['vtt'], requestStyle: 'json' }));+ insert.run('cloudflare', '@cf/openai/whisper', 'Whisper (Cloudflare Workers AI)', 3,+ JSON.stringify({ subtitleFormats: ['vtt'], requestStyle: 'binary' }));+}++interface MultipartOpts {+ file?: { bytes: Buffer; name: string; type?: string } | null;+ fields?: Record<string, string>;+ auth?: string | null;+}++/** POST multipart/form-data to /v1/audio/transcriptions on a live listener,+ * using the saved real fetch so a mocked globalThis.fetch only intercepts+ * upstream provider calls. */+async function postTranscription(app: Express, opts: MultipartOpts) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const form = new FormData();+ if (opts.file) {+ form.append('file', new Blob([opts.file.bytes], { type: opts.file.type ?? 'audio/wav' }), opts.file.name);+ }+ for (const [k, v] of Object.entries(opts.fields ?? {})) form.append(k, v);+ const headers: Record<string, string> = {};+ if (opts.auth !== null) headers.Authorization = `Bearer ${opts.auth ?? getUnifiedApiKey()}`;+ const res = await realFetch(`http://127.0.0.1:${addr.port}/v1/audio/transcriptions`, {+ method: 'POST',+ headers,+ body: form,+ });+ const raw = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(raw); } catch {}+ return { status: res.status, body: json, raw, headers: res.headers };+}++const AUDIO = Buffer.from('RIFFfakewavbytes');++describe('POST /v1/audio/transcriptions', () => {+ let app: Express;++ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ for (let id = 1; id <= 10; id++) clearCooldownsForKey(id);+ seedTranscriptionModels();+ app = createApp();+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('401 without an API key', async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ auth: null,+ });+ expect(status).toBe(401);+ expect(body.error.type).toBe('authentication_error');+ });++ it('401 with a wrong key', async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ auth: 'freellmapi-wrong-key',+ });+ expect(status).toBe(401);+ expect(body.error.type).toBe('authentication_error');+ });++ it('400 when the file part is missing', async () => {+ const { status, body } = await postTranscription(app, {+ file: null,+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.message).toContain('file');+ });++ it('400 when model is missing', async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ });+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.message).toContain('model');+ });++ it('413 OpenAI-shaped error when the upload exceeds the size limit', async () => {+ const big = Buffer.alloc(MAX_TRANSCRIPTION_BYTES + 1);+ const { status, body } = await postTranscription(app, {+ file: { bytes: big, name: 'big.wav' },+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(413);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.code).toBe('file_too_large');+ });++ it("400 unsupported_format for response_format 'srt'", async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', response_format: 'srt' },+ });+ expect(status).toBe(400);+ expect(body.error.code).toBe('unsupported_format');+ });++ it('400 for an unrecognized response_format', async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', response_format: 'yaml' },+ });+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ });++ it('400 for an out-of-range temperature', async () => {+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', temperature: '3' },+ });+ expect(status).toBe(400);+ expect(body.error.message).toContain('temperature');+ });++ it('default json format returns {"text": ...} and provider headers', async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'hello from groq' })) as any;+ const { status, body, headers } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(200);+ expect(body).toEqual({ text: 'hello from groq' });+ expect(headers.get('x-provider')).toBe('groq');+ });++ it("response_format 'text' returns the plain string", async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'plain words' })) as any;+ const { status, raw, headers } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', response_format: 'text' },+ });+ expect(status).toBe(200);+ expect(raw).toBe('plain words');+ expect(headers.get('content-type')).toContain('text/plain');+ });++ it("response_format 'verbose_json' returns the OpenAI verbose shape when segments exist", async () => {+ addKey('groq');+ const segments = [{ id: 0, start: 0, end: 1, text: 'hi' }];+ globalThis.fetch = vi.fn(async () =>+ jsonResponse({ text: 'hi', language: 'en', duration: 1, segments })) as any;+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', response_format: 'verbose_json' },+ });+ expect(status).toBe(200);+ expect(body.task).toBe('transcribe');+ expect(body.language).toBe('en');+ expect(body.duration).toBe(1);+ expect(body.segments).toEqual(segments);+ });++ it("'verbose_json' falls back to the plain json shape when the provider has no segments", async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'no segments here' })) as any;+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1', response_format: 'verbose_json' },+ });+ expect(status).toBe(200);+ expect(body).toEqual({ text: 'no segments here' });+ });++ it('falls over to cloudflare when groq is rate-limited (429)', async () => {+ addKey('groq');+ addKey('cloudflare', 'acct123:token456');+ globalThis.fetch = vi.fn(async (url: any) => {+ if (String(url).includes('groq.com')) return jsonResponse({ error: { message: 'slow down' } }, 429);+ return jsonResponse({ result: { text: 'cf text' }, success: true });+ }) as any;+ const { status, body, headers } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(200);+ expect(body).toEqual({ text: 'cf text' });+ expect(headers.get('x-provider')).toBe('cloudflare');+ });++ it('429 rate_limit_error when every provider is rate-limited', async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ error: { message: 'slow down' } }, 429)) as any;+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(429);+ expect(body.error.type).toBe('rate_limit_error');+ });++ it("503 with code 'no_transcription_models' when the registry has never been synced", async () => {+ getDb().prepare("DELETE FROM media_models WHERE modality = 'transcription'").run();+ addKey('groq');+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock as any;+ const { status, body } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: 'whisper-1' },+ });+ expect(status).toBe(503);+ expect(body.error.type).toBe('server_error');+ expect(body.error.code).toBe('no_transcription_models');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("response_format 'vtt' streams native subtitles from cloudflare", async () => {+ addKey('cloudflare', 'acct123:token456');+ const vtt = 'WEBVTT\n\n00:00.000 --> 00:01.000\nhello';+ globalThis.fetch = vi.fn(async () =>+ jsonResponse({ result: { text: 'hello', vtt }, success: true })) as any;+ const { status, raw, headers } = await postTranscription(app, {+ file: { bytes: AUDIO, name: 'a.wav' },+ fields: { model: '@cf/openai/whisper', response_format: 'vtt' },+ });+ expect(status).toBe(200);+ expect(raw).toBe(vtt);+ expect(headers.get('content-type')).toContain('text/vtt');+ });+});diff --git a/server/src/__tests__/routes/media-transcription-dashboard.test.ts b/server/src/__tests__/routes/media-transcription-dashboard.test.tsnew file mode 100644index 00000000..60301bf7--- /dev/null+++ b/server/src/__tests__/routes/media-transcription-dashboard.test.ts@@ -0,0 +1,117 @@+import { beforeEach, describe, expect, it } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++// The dashboard Audio tab lists speech-to-text rows (modality='transcription',+// synced from the catalog's `transcriptionModels`) next to TTS. These tests pin+// the contract that page relies on: GET /api/media returns transcription rows+// unfiltered, and PUT /api/media/:id toggles them like any other media row.++let dashToken = '';++async function get(app: Express, path: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ headers: isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {},+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++async function put(app: Express, path: string, body: unknown) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++function seedTranscriptionRows() {+ const insert = getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)+ VALUES (?, ?, ?, 'transcription', ?, 1, ?)+ `);+ insert.run('groq', 'whisper-large-v3', 'Whisper large v3', 1, '~2000 min/day');+ insert.run('cloudflare', '@cf/openai/whisper', 'Whisper', 2, '10 min/day free');+}++describe('transcription models on the media dashboard API', () => {+ let app: Express;++ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ it('lists transcription rows alongside the other media modalities', async () => {+ seedTranscriptionRows();+ getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)+ VALUES ('cloudflare', '@cf/black-forest-labs/flux-1-schnell', 'FLUX.1 [schnell]', 'image', 1, 1, 'free tier')+ `).run();++ const { status, body } = await get(app, '/api/media');+ expect(status).toBe(200);++ const stt = body.models.filter((m: any) => m.modality === 'transcription');+ expect(stt.map((m: any) => `${m.platform}:${m.modelId}`)).toEqual([+ 'groq:whisper-large-v3',+ 'cloudflare:@cf/openai/whisper',+ ]);+ expect(stt[0]).toMatchObject({+ displayName: 'Whisper large v3',+ enabled: true,+ quotaLabel: '~2000 min/day',+ keyCount: 0,+ isCustom: false,+ });+ // Image rows keep their shape — transcription rides along, nothing filtered.+ expect(body.models.some((m: any) => m.modality === 'image')).toBe(true);+ });++ it('counts healthy keys for a transcription row’s platform', async () => {+ seedTranscriptionRows();+ const { encrypted, iv, authTag } = encrypt('not-a-real-key');+ getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES ('groq', 'test', ?, ?, ?, 'healthy', 1)+ `).run(encrypted, iv, authTag);++ const { body } = await get(app, '/api/media');+ const byPlatform = new Map(body.models+ .filter((m: any) => m.modality === 'transcription')+ .map((m: any) => [m.platform, m.keyCount]));+ expect(byPlatform.get('groq')).toBe(1);+ expect(byPlatform.get('cloudflare')).toBe(0);+ });++ it('toggles a transcription row off and back on via PUT /api/media/:id', async () => {+ seedTranscriptionRows();+ const row = getDb().prepare(+ "SELECT id FROM media_models WHERE modality = 'transcription' AND platform = 'groq'",+ ).get() as { id: number };++ expect((await put(app, `/api/media/${row.id}`, { enabled: false })).status).toBe(200);+ let listed = await get(app, '/api/media');+ expect(listed.body.models.find((m: any) => m.id === row.id).enabled).toBe(false);++ expect((await put(app, `/api/media/${row.id}`, { enabled: true })).status).toBe(200);+ listed = await get(app, '/api/media');+ expect(listed.body.models.find((m: any) => m.id === row.id).enabled).toBe(true);+ });+});diff --git a/server/src/__tests__/routes/reasoning-control.test.ts b/server/src/__tests__/routes/reasoning-control.test.tsnew file mode 100644index 00000000..da0f0d89--- /dev/null+++ b/server/src/__tests__/routes/reasoning-control.test.ts@@ -0,0 +1,299 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';+import { effortFromAnthropicThinking } from '../../routes/anthropic.js';++// Request-side reasoning control (reasoning_effort / reasoning:{effort} /+// Anthropic thinking:{budget_tokens}) and inline <think> extraction, driven+// end-to-end through the real routes with a mocked Groq upstream (P2 #16).++let dashToken = '';++async function request(app: Express, path: string, body: any, extraHeaders: Record<string, string> = {}) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...extraHeaders },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(text); } catch { /* SSE body */ }+ return { status: res.status, text, body: json };+}++function openaiHeaders() {+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };+}++function anthropicHeaders() {+ return { 'x-api-key': getUnifiedApiKey(), 'anthropic-version': '2023-06-01' };+}++// Mock Groq's upstream with a canned JSON response and capture the forwarded body.+function mockJson(response: any) {+ const origFetch = global.fetch;+ const captured: { body: any } = { body: null };+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ const urlStr = typeof url === 'string' ? url : url.toString();+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {+ captured.body = JSON.parse(String((init as RequestInit).body));+ return { ok: true, json: () => Promise.resolve(response) } as any;+ }+ return origFetch(url as any, init);+ });+ return captured;+}++function mockStream(body: string) {+ const origFetch = global.fetch;+ const captured: { body: any } = { body: null };+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ const urlStr = typeof url === 'string' ? url : url.toString();+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {+ captured.body = JSON.parse(String((init as RequestInit).body));+ return new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } });+ }+ return origFetch(url as any, init);+ });+ return captured;+}++const textCompletion = (text: string) => ({+ id: 'chatcmpl-x', object: 'chat.completion', created: 1, model: 'openai/gpt-oss-120b',+ choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 },+});++const sse = (...payloads: (object | string)[]) =>+ payloads.map(p => `data: ${typeof p === 'string' ? p : JSON.stringify(p)}\n\n`).join('');++const chunk = (delta: Record<string, unknown>, finish: string | null = null) => ({+ id: 's1', object: 'chat.completion.chunk', created: 1, model: 'openai/gpt-oss-120b',+ choices: [{ index: 0, delta, finish_reason: finish }],+});++/** Parse the OpenAI SSE body into its data payloads. */+function sseData(text: string): any[] {+ const out: any[] = [];+ for (const line of text.split('\n')) {+ if (!line.startsWith('data: ')) continue;+ const data = line.slice(6);+ if (data === '[DONE]') continue;+ try { out.push(JSON.parse(data)); } catch { /* ignore */ }+ }+ return out;+}++/** Parse an Anthropic SSE body into ordered {event, data} pairs. */+function anthropicEvents(text: string): Array<{ event: string; data: any }> {+ const events: Array<{ event: string; data: any }> = [];+ for (const block of text.split('\n\n')) {+ let event: string | null = null;+ let data: string | null = null;+ for (const line of block.split('\n')) {+ if (line.startsWith('event: ')) event = line.slice(7).trim();+ else if (line.startsWith('data: ')) data = line.slice(6);+ }+ if (event && data) { try { events.push({ event, data: JSON.parse(data) }); } catch { /* ignore */ } }+ }+ return events;+}++describe('request-side reasoning control (end-to-end)', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(async () => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM requests').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+ db.prepare('DELETE FROM rate_limit_usage').run();+ const { status } = await request(app, '/api/keys',+ { platform: 'groq', key: 'gsk_reasoning_control_test', label: 't' },+ { Authorization: `Bearer ${dashToken}` });+ expect(status).toBe(201);+ });++ afterEach(() => vi.restoreAllMocks());++ it('accepts reasoning_effort and forwards it to a supporting platform', async () => {+ const captured = mockJson(textCompletion('ok'));+ const { status } = await request(app, '/v1/chat/completions', {+ model: 'auto', reasoning_effort: 'low',+ messages: [{ role: 'user', content: 'hi' }],+ }, openaiHeaders());+ expect(status).toBe(200);+ expect(captured.body.reasoning_effort).toBe('low');+ });++ it('tolerates the object form and normalizes it to reasoning_effort on the wire', async () => {+ const captured = mockJson(textCompletion('ok'));+ const { status } = await request(app, '/v1/chat/completions', {+ model: 'auto', reasoning: { effort: 'high' },+ messages: [{ role: 'user', content: 'hi' }],+ }, openaiHeaders());+ expect(status).toBe(200);+ expect(captured.body.reasoning_effort).toBe('high');+ expect(captured.body).not.toHaveProperty('reasoning');+ });++ it('a no-knob request sends nothing reasoning-related upstream (default unchanged)', async () => {+ const captured = mockJson(textCompletion('ok'));+ const { status } = await request(app, '/v1/chat/completions', {+ model: 'auto',+ messages: [{ role: 'user', content: 'hi' }],+ }, openaiHeaders());+ expect(status).toBe(200);+ expect(JSON.stringify(captured.body)).not.toContain('reasoning');+ });++ it('rejects an unknown effort value with a 400 instead of forwarding garbage', async () => {+ const { status, body } = await request(app, '/v1/chat/completions', {+ model: 'auto', reasoning_effort: 'maximum',+ messages: [{ role: 'user', content: 'hi' }],+ }, openaiHeaders());+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ });++ it('non-streaming: inline <think> is extracted into reasoning_content in the response', async () => {+ mockJson(textCompletion('<think>let me add</think>The answer is 4.'));+ const { status, body } = await request(app, '/v1/chat/completions', {+ model: 'auto',+ messages: [{ role: 'user', content: '2+2?' }],+ }, openaiHeaders());+ expect(status).toBe(200);+ const msg = body.choices[0].message;+ expect(msg.content).toBe('The answer is 4.');+ expect(msg.reasoning_content).toBe('let me add');+ });++ it('streaming: think text arrives as delta.reasoning_content, never as content', async () => {+ mockStream(sse(+ chunk({ role: 'assistant' }),+ chunk({ content: '<think>step ' }),+ chunk({ content: 'one</thi' }),+ chunk({ content: 'nk>Final answer' }),+ chunk({}, 'stop'),+ '[DONE]',+ ));+ const { status, text } = await request(app, '/v1/chat/completions', {+ model: 'auto', stream: true,+ messages: [{ role: 'user', content: 'q' }],+ }, openaiHeaders());+ expect(status).toBe(200);+ const frames = sseData(text);+ const reasoning = frames.map(f => f.choices?.[0]?.delta?.reasoning_content ?? '').join('');+ const content = frames.map(f => f.choices?.[0]?.delta?.content ?? '').join('');+ expect(reasoning).toBe('step one');+ expect(content).toBe('Final answer');+ expect(content).not.toContain('<think>');+ });+});++describe('Anthropic surface: thinking knob + thinking blocks', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ beforeEach(async () => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM requests').run();+ db.prepare('DELETE FROM rate_limit_cooldowns').run();+ db.prepare('DELETE FROM rate_limit_usage').run();+ const { status } = await request(app, '/api/keys',+ { platform: 'groq', key: 'gsk_reasoning_anthropic_test', label: 't' },+ { Authorization: `Bearer ${dashToken}` });+ expect(status).toBe(201);+ });++ afterEach(() => vi.restoreAllMocks());++ it('maps thinking:{budget_tokens} onto the internal effort scale', () => {+ expect(effortFromAnthropicThinking(undefined)).toBeUndefined();+ expect(effortFromAnthropicThinking(null)).toBeUndefined();+ expect(effortFromAnthropicThinking({ type: 'disabled' })).toBe('none');+ expect(effortFromAnthropicThinking({ type: 'enabled' })).toBe('medium');+ expect(effortFromAnthropicThinking({ type: 'enabled', budget_tokens: 1024 })).toBe('low');+ expect(effortFromAnthropicThinking({ type: 'enabled', budget_tokens: 8000 })).toBe('medium');+ expect(effortFromAnthropicThinking({ type: 'enabled', budget_tokens: 32000 })).toBe('high');+ });++ it('forwards the mapped effort to the provider', async () => {+ const captured = mockJson(textCompletion('done'));+ const { status } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5', max_tokens: 64,+ thinking: { type: 'enabled', budget_tokens: 32000 },+ messages: [{ role: 'user', content: 'hi' }],+ }, anthropicHeaders());+ expect(status).toBe(200);+ expect(captured.body.reasoning_effort).toBe('high');+ });++ it('sends nothing when the client sent no thinking knob', async () => {+ const captured = mockJson(textCompletion('done'));+ const { status } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5', max_tokens: 64,+ messages: [{ role: 'user', content: 'hi' }],+ }, anthropicHeaders());+ expect(status).toBe(200);+ expect(JSON.stringify(captured.body)).not.toContain('reasoning');+ });++ it('non-streaming: reasoning output renders as a thinking block before the text block', async () => {+ mockJson(textCompletion('<think>consider the sum</think>It is 4.'));+ const { status, body } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5', max_tokens: 64,+ messages: [{ role: 'user', content: '2+2?' }],+ }, anthropicHeaders());+ expect(status).toBe(200);+ expect(body.content).toEqual([+ { type: 'thinking', thinking: 'consider the sum', signature: '' },+ { type: 'text', text: 'It is 4.' },+ ]);+ });++ it('streaming: thinking block precedes the text block in the SSE sequence', async () => {+ mockStream(sse(+ chunk({ role: 'assistant' }),+ chunk({ content: '<think>plan</think>Answer text' }),+ chunk({}, 'stop'),+ '[DONE]',+ ));+ const { status, text } = await request(app, '/v1/messages', {+ model: 'claude-sonnet-4-5', max_tokens: 64, stream: true,+ messages: [{ role: 'user', content: 'q' }],+ }, anthropicHeaders());+ expect(status).toBe(200);+ const events = anthropicEvents(text);+ const starts = events.filter(e => e.event === 'content_block_start');+ expect(starts.map(s => s.data.content_block.type)).toEqual(['thinking', 'text']);+ const thinkingText = events+ .filter(e => e.event === 'content_block_delta' && e.data.delta.type === 'thinking_delta')+ .map(e => e.data.delta.thinking).join('');+ expect(thinkingText).toBe('plan');+ const answerText = events+ .filter(e => e.event === 'content_block_delta' && e.data.delta.type === 'text_delta')+ .map(e => e.data.delta.text).join('');+ expect(answerText).toBe('Answer text');+ expect(answerText).not.toContain('<think>');+ });+});diff --git a/server/src/__tests__/services/catalog-sync-source.test.ts b/server/src/__tests__/services/catalog-sync-source.test.tsnew file mode 100644index 00000000..f746f751--- /dev/null+++ b/server/src/__tests__/services/catalog-sync-source.test.ts@@ -0,0 +1,208 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { applyCatalog } from '../../services/catalog-sync.js';+import { applyDeclarativeConfig } from '../../services/declarative-config.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++// models.source is the provenance column that lets catalog-sync tell its own+// rows apart from rows the user created. These tests pin the whole contract:+// every write path stamps source honestly, sync still prunes stale catalog+// rows, and sync never deletes or clobbers a source='user' row — including on+// a platform:model_id collision, where the user row wins and the catalog+// entry is skipped.++type AnyCatalog = Parameters<typeof applyCatalog>[1];++function baseModel(over: Partial<AnyCatalog['models'][number]> = {}): AnyCatalog['models'][number] {+ return {+ platform: 'groq',+ modelId: 'test-model',+ displayName: 'Test Model',+ intelligenceRank: 10,+ speedRank: 5,+ sizeLabel: 'Medium',+ limits: { rpm: 30, rpd: 1000, tpm: 6000, tpd: null },+ monthlyTokenBudget: '~1M',+ contextWindow: 8192,+ enabled: true,+ supportsVision: false,+ supportsTools: true,+ ...over,+ };+}++function catalogOf(models: AnyCatalog['models']): AnyCatalog {+ return {+ version: '2099.01.01',+ generatedAt: new Date().toISOString(),+ tier: 'live',+ models,+ quirks: [],+ };+}++/** Snapshot every catalog-owned model as catalog entries so applyCatalog keeps them. */+function existingAsCatalogModels(): AnyCatalog['models'] {+ const rows = getDb()+ .prepare(+ `SELECT platform, model_id, display_name, intelligence_rank, speed_rank, size_label,+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window,+ enabled, supports_vision, supports_tools+ FROM models WHERE source = 'catalog'`,+ )+ .all() as Array<Record<string, unknown>>;+ return rows.map((r) =>+ baseModel({+ platform: r.platform as string,+ modelId: r.model_id as string,+ displayName: r.display_name as string,+ intelligenceRank: r.intelligence_rank as number,+ speedRank: r.speed_rank as number,+ sizeLabel: r.size_label as string,+ limits: {+ rpm: r.rpm_limit as number | null,+ rpd: r.rpd_limit as number | null,+ tpm: r.tpm_limit as number | null,+ tpd: r.tpd_limit as number | null,+ },+ monthlyTokenBudget: r.monthly_token_budget as string,+ contextWindow: r.context_window as number | null,+ enabled: (r.enabled as number) === 1,+ supportsVision: (r.supports_vision as number) === 1,+ supportsTools: (r.supports_tools as number) === 1,+ }),+ );+}++function modelRow(platform: string, modelId: string): { id: number; display_name: string; source: string } | undefined {+ return getDb()+ .prepare('SELECT id, display_name, source FROM models WHERE platform = ? AND model_id = ?')+ .get(platform, modelId) as { id: number; display_name: string; source: string } | undefined;+}++describe('models.source provenance', () => {+ let app: Express;+ let dashToken = '';++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ getDb().prepare("DELETE FROM settings WHERE key = 'active_profile_id'").run();+ app = createApp();+ dashToken = mintDashboardToken();+ });++ async function request(method: string, path: string, body?: unknown) {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data as any };+ }++ it('backfilled the bundled baseline as catalog-owned', () => {+ const row = getDb()+ .prepare("SELECT COUNT(*) AS n FROM models WHERE source = 'catalog'")+ .get() as { n: number };+ expect(row.n).toBeGreaterThan(0);+ });++ it('catalog sync inserts new models with source=catalog', () => {+ const models = existingAsCatalogModels();+ models.push(baseModel({ modelId: 'provenance-new-model' }));+ applyCatalog(getDb(), catalogOf(models));+ expect(modelRow('groq', 'provenance-new-model')?.source).toBe('catalog');+ });++ it('declarative config stamps source=user on models it creates', () => {+ applyDeclarativeConfig({+ customProviders: [{+ baseUrl: 'http://127.0.0.1:9321/v1',+ apiKey: 'local-key',+ label: 'Prov Local',+ models: ['prov-local-chat'],+ }],+ models: [{+ platform: 'groq',+ modelId: 'prov-declarative-model',+ displayName: 'Declared By Hand',+ sizeLabel: 'Large', // deliberately NOT the 'User' convention+ }],+ });+ expect(modelRow('custom', 'prov-local-chat')?.source).toBe('user');+ expect(modelRow('groq', 'prov-declarative-model')?.source).toBe('user');+ });++ it('declarative patch of an existing catalog model keeps it catalog-owned', () => {+ const target = getDb()+ .prepare("SELECT platform, model_id FROM models WHERE source = 'catalog' AND platform = 'groq' ORDER BY id LIMIT 1")+ .get() as { platform: string; model_id: string };+ applyDeclarativeConfig({+ models: [{ platform: target.platform, modelId: target.model_id, displayName: 'Patched Name' }],+ });+ expect(modelRow(target.platform, target.model_id)?.source).toBe('catalog');+ });++ it('POST /api/keys/custom stamps source=user', async () => {+ const res = await request('POST', '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9322/v1',+ apiKey: 'k-' + 'a'.repeat(8),+ model: 'prov-endpoint-model',+ });+ expect(res.status).toBe(201);+ expect(modelRow('custom', 'prov-endpoint-model')?.source).toBe('user');+ });++ it('GET /api/models reports user rows as custom-sourced, catalog rows as catalog', async () => {+ const res = await request('GET', '/api/models');+ expect(res.status).toBe(200);+ const list = res.body as Array<{ platform: string; modelId: string; source: string }>;+ const declared = list.find((m) => m.modelId === 'prov-declarative-model');+ expect(declared?.source).toBe('custom');+ const catalogRow = list.find((m) => m.modelId === 'provenance-new-model');+ expect(catalogRow?.source).toBe('catalog');+ });++ it('sync prunes stale catalog rows but never user rows', () => {+ // The catalog no longer lists provenance-new-model, and it never listed the+ // user's rows. Only the catalog-owned row may be pruned.+ const models = existingAsCatalogModels().filter((m) => m.modelId !== 'provenance-new-model');+ const counts = applyCatalog(getDb(), catalogOf(models));++ expect(modelRow('groq', 'provenance-new-model')).toBeUndefined();+ expect(counts.removed).toBeGreaterThanOrEqual(1);+ // The declaratively-added native-platform model survives even though its+ // size_label ('Large') would have failed the old heuristic guard.+ expect(modelRow('groq', 'prov-declarative-model')?.source).toBe('user');+ expect(modelRow('custom', 'prov-local-chat')?.source).toBe('user');+ expect(modelRow('custom', 'prov-endpoint-model')?.source).toBe('user');+ });++ it('a user row colliding with a catalog id is not clobbered (user wins)', () => {+ const models = existingAsCatalogModels();+ // The catalog starts shipping the same platform:model_id the user declared.+ models.push(baseModel({ modelId: 'prov-declarative-model', displayName: 'Catalog Name', contextWindow: 999 }));+ applyCatalog(getDb(), catalogOf(models));++ const row = getDb()+ .prepare("SELECT display_name, context_window, source FROM models WHERE platform = 'groq' AND model_id = 'prov-declarative-model'")+ .get() as { display_name: string; context_window: number | null; source: string };+ expect(row.source).toBe('user');+ expect(row.display_name).toBe('Declared By Hand');+ expect(row.context_window).not.toBe(999);++ // And when the colliding entry leaves the catalog again, the user row stays.+ applyCatalog(getDb(), catalogOf(existingAsCatalogModels()));+ expect(modelRow('groq', 'prov-declarative-model')?.source).toBe('user');+ });+});diff --git a/server/src/__tests__/services/catalog-sync.test.ts b/server/src/__tests__/services/catalog-sync.test.tsindex 0e725f65..6c266187 100644--- a/server/src/__tests__/services/catalog-sync.test.ts+++ b/server/src/__tests__/services/catalog-sync.test.ts@@ -331,8 +331,14 @@ describe('reapplyCachedCatalog', () => {getDb().prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?').get(victim.platform, victim.modelId),).toBeUndefined();- // Simulate a restart: migrations re-insert the baseline model.- getDb().exec('DROP TABLE migrations');+ // Simulate a restart: re-run the baseline migrations so their+ // INSERT OR IGNORE re-adds the catalog-deleted model. The source-provenance+ // migration (20260726_000003) must stay recorded as applied — in the real+ // timeline its backfill runs exactly once (every install with an applied+ // catalog cache already has a migrations table), and re-running it here+ // would re-classify the baseline's re-inserted rows against the applied+ // catalog instead of leaving them catalog-owned.+ getDb().prepare("DELETE FROM migrations WHERE filename NOT LIKE '20260726_000003%'").run();runMigrationsSync(getDb(), 'up');expect(getDb().prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?').get(victim.platform, victim.modelId),@@ -368,3 +374,131 @@ describe('reapplyCachedCatalog', () => {expect(reapplyCachedCatalog().reapplied).toBe(false);});});++// The speech-to-text registry rides the catalog's dedicated optional+// `transcriptionModels` key (NOT the `models` array — old binaries would+// ingest unknown-modality models entries as chat models) and lands in+// media_models with modality='transcription'. These tests lock the sync,+// prune scoping, enabled-merge, tombstone, and rejection rules.+describe('applyCatalog: transcriptionModels', () => {+ type CatalogTranscription = NonNullable<AnyCatalog['transcriptionModels']>[number];++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ function sttRoster(): CatalogTranscription[] {+ return [+ { platform: 'groq', modelId: 'whisper-large-v3-turbo', displayName: 'Whisper Large v3 Turbo (Groq)', priority: 0, enabled: true, maxBytes: 26214400 },+ { platform: 'groq', modelId: 'whisper-large-v3', displayName: 'Whisper Large v3 (Groq)', priority: 1, enabled: true, maxBytes: 26214400 },+ { platform: 'cloudflare', modelId: '@cf/openai/whisper-large-v3-turbo', displayName: 'Whisper Large v3 Turbo (Cloudflare Workers AI)', priority: 2, enabled: true, subtitleFormats: ['vtt'], requestStyle: 'json' },+ { platform: 'cloudflare', modelId: '@cf/openai/whisper', displayName: 'Whisper (Cloudflare Workers AI)', priority: 3, enabled: true, subtitleFormats: ['vtt'], requestStyle: 'binary' },+ ];+ }++ /** Catalog with an image media model plus (optionally) a STT snapshot. */+ function sttCatalog(entries?: CatalogTranscription[]): AnyCatalog {+ const models = existingAsCatalogModels();+ models.push(baseModel({+ platform: 'cloudflare',+ modelId: '@cf/test/image-model',+ displayName: 'Test Image Model',+ modality: 'image',+ }));+ const catalog = catalogOf(models);+ if (entries) catalog.transcriptionModels = entries;+ return catalog;+ }++ function sttRows(): Array<{ platform: string; model_id: string; enabled: number; priority: number; meta_json: string | null }> {+ return getDb().prepare(`+ SELECT platform, model_id, enabled, priority, meta_json+ FROM media_models+ WHERE modality = 'transcription'+ ORDER BY priority, id+ `).all() as any;+ }++ it('routes entries into media_models with modality, meta_json, and priority order', () => {+ const counts = applyCatalog(getDb(), sttCatalog(sttRoster()));+ expect(counts.inserted).toBeGreaterThanOrEqual(5); // 4 STT + the image row++ const rows = sttRows();+ expect(rows.map(r => `${r.platform}:${r.model_id}`)).toEqual([+ 'groq:whisper-large-v3-turbo',+ 'groq:whisper-large-v3',+ 'cloudflare:@cf/openai/whisper-large-v3-turbo',+ 'cloudflare:@cf/openai/whisper',+ ]);+ expect(JSON.parse(rows[0].meta_json!)).toEqual({ maxBytes: 26214400 });+ expect(JSON.parse(rows[2].meta_json!)).toEqual({ subtitleFormats: ['vtt'], requestStyle: 'json' });+ expect(JSON.parse(rows[3].meta_json!)).toEqual({ subtitleFormats: ['vtt'], requestStyle: 'binary' });++ // The image row landed alongside, in its own modality.+ const image = getDb().prepare(+ "SELECT modality FROM media_models WHERE platform = 'cloudflare' AND model_id = '@cf/test/image-model'",+ ).get() as { modality: string };+ expect(image.modality).toBe('image');+ });++ it('enabled merge: local disable survives a catalog enable; catalog disable forces off', () => {+ getDb().prepare(+ "UPDATE media_models SET enabled = 0 WHERE modality = 'transcription' AND model_id = 'whisper-large-v3'",+ ).run();+ applyCatalog(getDb(), sttCatalog(sttRoster())); // catalog still says enabled+ expect(sttRows().find(r => r.model_id === 'whisper-large-v3')!.enabled).toBe(0);++ getDb().prepare(+ "UPDATE media_models SET enabled = 1 WHERE modality = 'transcription' AND model_id = 'whisper-large-v3'",+ ).run();+ const roster = sttRoster();+ roster.find(m => m.modelId === 'whisper-large-v3')!.enabled = false;+ applyCatalog(getDb(), sttCatalog(roster));+ expect(sttRows().find(r => r.model_id === 'whisper-large-v3')!.enabled).toBe(0);++ // Restore for the following tests.+ applyCatalog(getDb(), sttCatalog(sttRoster()));+ getDb().prepare(+ "UPDATE media_models SET enabled = 1 WHERE modality = 'transcription'",+ ).run();+ });++ it('a catalog without the key leaves existing transcription rows untouched', () => {+ applyCatalog(getDb(), sttCatalog(undefined)); // old payload shape+ expect(sttRows()).toHaveLength(4);+ });++ it('prunes dropped transcription rows, scoped to the modality', () => {+ const roster = sttRoster().filter(m => m.modelId !== '@cf/openai/whisper');+ const counts = applyCatalog(getDb(), sttCatalog(roster));+ expect(counts.removed).toBe(1);+ expect(sttRows().map(r => r.model_id)).not.toContain('@cf/openai/whisper');+ // Image row untouched by the transcription prune.+ expect(getDb().prepare(+ "SELECT id FROM media_models WHERE model_id = '@cf/test/image-model'",+ ).get()).toBeDefined();+ });++ it('skips entries for platforms without a transcription adapter', () => {+ const roster = sttRoster();+ roster.push({ platform: 'nvidia', modelId: 'parakeet-stt', displayName: 'Parakeet', priority: 9, enabled: true });+ const counts = applyCatalog(getDb(), sttCatalog(roster));+ expect(counts.skippedUnknownPlatform).toBeGreaterThanOrEqual(1);+ expect(sttRows().map(r => r.model_id)).not.toContain('parakeet-stt');+ });++ it('tombstoned (user-deleted) transcription models stay deleted', () => {+ recordCatalogModelTombstone(getDb(), 'media', 'groq', 'whisper-large-v3');+ applyCatalog(getDb(), sttCatalog(sttRoster()));+ expect(sttRows().map(r => r.model_id)).not.toContain('whisper-large-v3');+ });++ it('a malformed transcriptionModels key rejects the whole payload', () => {+ const catalog = sttCatalog(sttRoster());+ (catalog as any).transcriptionModels = [{ platform: 'groq' }]; // missing required fields+ setSetting('catalog_applied_json', JSON.stringify(catalog));+ // isCatalog gates both the network and the cached re-apply paths.+ expect(reapplyCachedCatalog().reapplied).toBe(false);+ });+});diff --git a/server/src/__tests__/services/transcription.test.ts b/server/src/__tests__/services/transcription.test.tsnew file mode 100644index 00000000..a3ebde88--- /dev/null+++ b/server/src/__tests__/services/transcription.test.ts@@ -0,0 +1,268 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { runTranscription, MediaError, listMediaModels, MAX_TRANSCRIPTION_BYTES } from '../../services/media.js';+import { isOnCooldown, clearCooldownsForKey } from '../../services/ratelimit.js';++const realFetch = globalThis.fetch;++function addKey(platform: string, raw = `${platform}-test-key`): number {+ const { encrypted, iv, authTag } = encrypt(raw);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1)+ `).run(platform, encrypted, iv, authTag);+ return Number(row.lastInsertRowid);+}++function jsonResponse(body: unknown, status = 200) {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+}++/** Seed the catalog-delivered STT registry (media_models, modality+ * 'transcription') exactly as the published `transcriptionModels` fragment+ * would land it via catalog-sync. */+function seedTranscriptionModels(): void {+ const insert = getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES (?, ?, ?, 'transcription', ?, 1, '', ?)+ `);+ insert.run('groq', 'whisper-large-v3-turbo', 'Whisper Large v3 Turbo (Groq)', 0,+ JSON.stringify({ maxBytes: 25 * 1024 * 1024 }));+ insert.run('groq', 'whisper-large-v3', 'Whisper Large v3 (Groq)', 1,+ JSON.stringify({ maxBytes: 25 * 1024 * 1024 }));+ insert.run('cloudflare', '@cf/openai/whisper-large-v3-turbo', 'Whisper Large v3 Turbo (Cloudflare Workers AI)', 2,+ JSON.stringify({ subtitleFormats: ['vtt'], requestStyle: 'json' }));+ insert.run('cloudflare', '@cf/openai/whisper', 'Whisper (Cloudflare Workers AI)', 3,+ JSON.stringify({ subtitleFormats: ['vtt'], requestStyle: 'binary' }));+}++const AUDIO = Buffer.from('RIFFfakewavbytes');++function params(overrides: Record<string, unknown> = {}) {+ return {+ file: AUDIO,+ filename: 'clip.wav',+ mimeType: 'audio/wav',+ responseFormat: 'json',+ ...overrides,+ } as any;+}++describe('transcription service', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ // Cooldowns live in a module-level map that outlives the per-test :memory:+ // DB; key ids restart at 1 in every test, so stale entries must be purged.+ for (let id = 1; id <= 10; id++) clearCooldownsForKey(id);+ seedTranscriptionModels();+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('registry: enabled DB rows ordered by priority, groq ahead of cloudflare', () => {+ const rows = listMediaModels('transcription');+ expect(rows.map(m => m.platform)).toEqual(['groq', 'groq', 'cloudflare', 'cloudflare']);+ expect(rows.map(m => m.model_id)).toContain('whisper-large-v3-turbo');+ expect(rows.map(m => m.model_id)).toContain('@cf/openai/whisper');+ });++ it('empty registry (never-synced install) → 503 no_transcription_models, no fetch', async () => {+ getDb().prepare("DELETE FROM media_models WHERE modality = 'transcription'").run();+ addKey('groq');+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock as any;+ await expect(runTranscription('auto', params()))+ .rejects.toMatchObject({ status: 503, code: 'no_transcription_models' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('a locally disabled row leaves the chain (pinning it → 400 unknown model)', async () => {+ getDb()+ .prepare("UPDATE media_models SET enabled = 0 WHERE model_id = 'whisper-large-v3'")+ .run();+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'ok' })) as any;+ await expect(runTranscription('whisper-large-v3', params()))+ .rejects.toMatchObject({ status: 400 });+ // auto still routes via the remaining rows.+ const r = await runTranscription('auto', params());+ expect(r.modelId).toBe('whisper-large-v3-turbo');+ });++ it('groq: sends multipart form to the OpenAI-compatible audio endpoint', async () => {+ addKey('groq');+ const fetchMock = vi.fn(async () => jsonResponse({ text: 'hello world' }));+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('whisper-large-v3-turbo', params({ language: 'en', prompt: 'ctx', temperature: 0.2 }));++ expect(r.platform).toBe('groq');+ expect(r.modelId).toBe('whisper-large-v3-turbo');+ expect(r.text).toBe('hello world');++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://api.groq.com/openai/v1/audio/transcriptions');+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer groq-test-key');+ // Content-Type must NOT be set by hand — FormData supplies the boundary.+ expect((init.headers as Record<string, string>)['Content-Type']).toBeUndefined();+ const form = init.body as FormData;+ expect(form).toBeInstanceOf(FormData);+ expect(form.get('model')).toBe('whisper-large-v3-turbo');+ expect(form.get('language')).toBe('en');+ expect(form.get('prompt')).toBe('ctx');+ expect(form.get('temperature')).toBe('0.2');+ expect(form.get('response_format')).toBe('json');+ const file = form.get('file') as File;+ expect(file.name).toBe('clip.wav');+ expect(Buffer.from(await file.arrayBuffer()).equals(AUDIO)).toBe(true);+ });++ it('groq: requests verbose_json upstream and passes segments through', async () => {+ addKey('groq');+ const segments = [{ id: 0, start: 0, end: 1.5, text: 'hello' }];+ const fetchMock = vi.fn(async () =>+ jsonResponse({ text: 'hello', language: 'en', duration: 1.5, segments }));+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('whisper-large-v3', params({ responseFormat: 'verbose_json' }));+ const form = (fetchMock.mock.calls[0][1] as RequestInit).body as FormData;+ expect(form.get('response_format')).toBe('verbose_json');+ expect(r.segments).toEqual(segments);+ expect(r.language).toBe('en');+ expect(r.duration).toBe(1.5);+ });++ it('cloudflare @cf/openai/whisper: raw bytes body, account-scoped URL', async () => {+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn(async () =>+ jsonResponse({ result: { text: 'transcribed', word_count: 1, vtt: 'WEBVTT\n\n1' }, success: true }));+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('@cf/openai/whisper', params());+ expect(r.platform).toBe('cloudflare');+ expect(r.text).toBe('transcribed');+ expect(r.vtt).toContain('WEBVTT');++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://api.cloudflare.com/client/v4/accounts/acct123/ai/run/@cf/openai/whisper');+ const headers = init.headers as Record<string, string>;+ expect(headers.Authorization).toBe('Bearer token456');+ expect(headers['Content-Type']).toBe('application/octet-stream');+ expect(Buffer.from(init.body as Buffer).equals(AUDIO)).toBe(true);+ });++ it('cloudflare whisper-large-v3-turbo: JSON body with base64 audio', async () => {+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn(async () =>+ jsonResponse({ result: { text: 'turbo text', transcription_info: { language: 'en', duration: 2 } }, success: true }));+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('@cf/openai/whisper-large-v3-turbo', params({ language: 'en', prompt: 'hint' }));+ expect(r.text).toBe('turbo text');+ expect(r.language).toBe('en');+ expect(r.duration).toBe(2);++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://api.cloudflare.com/client/v4/accounts/acct123/ai/run/@cf/openai/whisper-large-v3-turbo');+ expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');+ const body = JSON.parse(init.body as string);+ expect(body.audio).toBe(AUDIO.toString('base64'));+ expect(body.language).toBe('en');+ expect(body.initial_prompt).toBe('hint');+ });++ it('falls back to cloudflare when groq returns 429, and benches the groq key', async () => {+ const groqKeyId = addKey('groq');+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn(async (url: string) => {+ if (String(url).includes('groq.com')) {+ return jsonResponse({ error: { message: 'rate limited' } }, 429);+ }+ return jsonResponse({ result: { text: 'cf fallback' }, success: true });+ });+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('auto', params());+ expect(r.platform).toBe('cloudflare');+ expect(r.text).toBe('cf fallback');+ // Both groq models were attempted and benched via the standard cooldown machinery.+ expect(isOnCooldown('groq', 'whisper-large-v3-turbo', groqKeyId)).toBe(true);+ expect(isOnCooldown('groq', 'whisper-large-v3', groqKeyId)).toBe(true);++ // A second request skips the benched groq key entirely.+ fetchMock.mockClear();+ await runTranscription('auto', params());+ const urls = fetchMock.mock.calls.map(c => String(c[0]));+ expect(urls.some(u => u.includes('groq.com'))).toBe(false);+ expect(urls.some(u => u.includes('cloudflare.com'))).toBe(true);+ });++ it("'whisper-1' routes like auto (stock OpenAI clients send it by default)", async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'ok' })) as any;+ const r = await runTranscription('whisper-1', params());+ expect(r.platform).toBe('groq');+ });++ it('unknown model → 400 MediaError', async () => {+ addKey('groq');+ await expect(runTranscription('not-a-model', params()))+ .rejects.toMatchObject({ status: 400 });+ });++ it('vtt restricts the chain to natively capable providers (cloudflare)', async () => {+ addKey('groq');+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn(async () =>+ jsonResponse({ result: { text: 'x', vtt: 'WEBVTT\n\n00:00.000 --> 00:01.000\nx' }, success: true }));+ globalThis.fetch = fetchMock as any;++ const r = await runTranscription('auto', params({ responseFormat: 'vtt' }));+ expect(r.platform).toBe('cloudflare');+ expect(r.vtt).toContain('WEBVTT');+ // groq must never have been attempted — it cannot produce vtt natively.+ expect(fetchMock.mock.calls.every(c => !String(c[0]).includes('groq.com'))).toBe(true);+ });++ it('vtt pinned to a groq model → 400 (not produced natively)', async () => {+ addKey('groq');+ await expect(runTranscription('whisper-large-v3', params({ responseFormat: 'vtt' })))+ .rejects.toMatchObject({ status: 400 });+ });++ it('oversized file → 413 before any provider is called', async () => {+ addKey('groq');+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock as any;+ const big = Buffer.alloc(MAX_TRANSCRIPTION_BYTES + 1);+ await expect(runTranscription('auto', params({ file: big })))+ .rejects.toMatchObject({ status: 413 });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('no usable keys → 503-family MediaError, no fetch', async () => {+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock as any;+ await expect(runTranscription('auto', params())).rejects.toBeInstanceOf(MediaError);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('logs transcription requests with request_type=transcription', async () => {+ addKey('groq');+ globalThis.fetch = vi.fn(async () => jsonResponse({ text: 'logged' })) as any;+ await runTranscription('auto', params());+ const row = getDb()+ .prepare("SELECT platform, model_id, status, request_type FROM requests ORDER BY id DESC LIMIT 1")+ .get() as any;+ expect(row.platform).toBe('groq');+ expect(row.request_type).toBe('transcription');+ expect(row.status).toBe('success');+ });+});diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 99ac28a4..633cde82 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -9,6 +9,9 @@ import * as customModelToolSupport from '../migrations/20260706_000002_custom_moimport * as profileChainBackfill from '../migrations/20260714_000001_profile_chain_backfill.js';import * as keyHealthError from '../migrations/20260720_000001_key_health_error.js';import * as cooldownProbeProvenance from '../migrations/20260726_000001_cooldown_probe_provenance.js';+import * as requestAttempts from '../migrations/20260726_000002_request_attempts.js';+import * as modelSourceProvenance from '../migrations/20260726_000003_model_source_provenance.js';+import * as mediaModelMeta from '../migrations/20260726_000004_media_model_meta.js';export interface MigrationModule {up(db: Db): void;@@ -30,6 +33,9 @@ export const CUSTOM_MODEL_TOOL_SUPPORT_FILENAME = '20260706_000002_custom_model_export const PROFILE_CHAIN_BACKFILL_FILENAME = '20260714_000001_profile_chain_backfill.ts';export const KEY_HEALTH_ERROR_FILENAME = '20260720_000001_key_health_error.ts';export const COOLDOWN_PROBE_PROVENANCE_FILENAME = '20260726_000001_cooldown_probe_provenance.ts';+export const REQUEST_ATTEMPTS_FILENAME = '20260726_000002_request_attempts.ts';+export const MODEL_SOURCE_PROVENANCE_FILENAME = '20260726_000003_model_source_provenance.ts';+export const MEDIA_MODEL_META_FILENAME = '20260726_000004_media_model_meta.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -42,4 +48,7 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: PROFILE_CHAIN_BACKFILL_FILENAME, module: profileChainBackfill },{ filename: KEY_HEALTH_ERROR_FILENAME, module: keyHealthError },{ filename: COOLDOWN_PROBE_PROVENANCE_FILENAME, module: cooldownProbeProvenance },+ { filename: REQUEST_ATTEMPTS_FILENAME, module: requestAttempts },+ { filename: MODEL_SOURCE_PROVENANCE_FILENAME, module: modelSourceProvenance },+ { filename: MEDIA_MODEL_META_FILENAME, module: mediaModelMeta },];diff --git a/server/src/db/migrations/20260726_000002_request_attempts.ts b/server/src/db/migrations/20260726_000002_request_attempts.tsnew file mode 100644index 00000000..c3ed6230--- /dev/null+++ b/server/src/db/migrations/20260726_000002_request_attempts.ts@@ -0,0 +1,46 @@+// Migration: per-attempt routing traces (request_attempts)+// Created: 2026-07-26+//+// DOWN: reversible+//+// When a request walks the failover ladder (groq 429 → google timeout →+// cerebras ok), the `requests` table records isolated rows with no linkage,+// ordering, or per-attempt timing — the journey that explains "why was this+// slow/failed" is invisible. `request_attempts` stores one row per dispatched+// attempt (including the successful final one), keyed to the TERMINAL+// `requests` row of the ladder: provider, model, per-request key ordinal+// (never the internal key id), outcome class, start offset from the ladder's+// start, and duration.+//+// ON DELETE CASCADE ties child rows to the requests retention prune+// (services/request-retention.ts): the connection opens with+// PRAGMA foreign_keys = ON (db/index.ts), so pruning a parent removes its+// attempts with no extra query and no unbounded growth.++import type { Db } from '../types.js';++export function up(db: Db): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS request_attempts (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ request_id INTEGER NOT NULL REFERENCES requests(id) ON DELETE CASCADE,+ ordinal INTEGER NOT NULL,+ platform TEXT NOT NULL,+ model_id TEXT NOT NULL,+ key_ordinal INTEGER NOT NULL,+ outcome TEXT NOT NULL,+ start_offset_ms INTEGER NOT NULL DEFAULT 0,+ duration_ms INTEGER NOT NULL DEFAULT 0+ );++ CREATE INDEX IF NOT EXISTS idx_request_attempts_request_id+ ON request_attempts(request_id, ordinal);+ `);+}++export function down(db: Db): void {+ db.exec(`+ DROP INDEX IF EXISTS idx_request_attempts_request_id;+ DROP TABLE IF EXISTS request_attempts;+ `);+}diff --git a/server/src/db/migrations/20260726_000003_model_source_provenance.ts b/server/src/db/migrations/20260726_000003_model_source_provenance.tsnew file mode 100644index 00000000..f0429029--- /dev/null+++ b/server/src/db/migrations/20260726_000003_model_source_provenance.ts@@ -0,0 +1,82 @@+// Migration: models.source provenance (catalog vs user) for the sync delete guard+// Created: 2026-07-26+//+// DOWN: reversible+//+// catalog-sync prunes chat models that the published catalog no longer lists.+// Before this column the prune had to GUESS which rows it owned from+// platform/key_id/size_label heuristics, so a hand-added model on a native+// platform (declarative config's `models:` entries, admin edits) could be+// silently deleted or clobbered on the next sync as soon as its size_label+// stopped matching the 'User'/'Custom' convention. `source` records who+// created the row at insert time:+// 'catalog' — catalog sync or the bundled baseline migrations+// 'user' — dashboard, custom endpoints, declarative config+//+// The column DEFAULT is 'catalog' on purpose: the baseline migration's+// INSERT OR IGNORE re-seeds (run on every fresh migrations table) must stay+// catalog-owned so reapplyCachedCatalog can prune them again after boot.+// Every user-facing write path sets 'user' explicitly.++import type { Db } from '../types.js';++function hasColumn(db: Db, table: string, column: string): boolean {+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];+ return columns.some((candidate) => candidate.name === column);+}++export function up(db: Db): void {+ if (!hasColumn(db, 'models', 'source')) {+ db.prepare("ALTER TABLE models ADD COLUMN source TEXT NOT NULL DEFAULT 'catalog'").run();+ }++ // Backfill pre-existing rows, strongest signal first: everything the old+ // prune guard already treated as user-owned is user-owned.+ db.prepare(`+ UPDATE models+ SET source = 'user'+ WHERE platform = 'custom'+ OR key_id IS NOT NULL+ OR size_label IN ('User', 'Custom')+ `).run();++ // Then consult the currently-applied catalog (the signed document cached by+ // catalog-sync in settings.catalog_applied_json). A surviving row that the+ // applied catalog does not list — and that the heuristics above did not+ // claim — can only have been added locally: sync prunes catalog-owned+ // leftovers on every apply, so catalog rows absent from the catalog do not+ // linger. With no applied catalog (fresh install, never synced) every+ // remaining row came from the bundled baseline, so the 'catalog' default+ // stands.+ try {+ const setting = db+ .prepare("SELECT value FROM settings WHERE key = 'catalog_applied_json'")+ .get() as { value: string } | undefined;+ if (!setting) return;+ const parsed = JSON.parse(setting.value) as { models?: unknown };+ if (!parsed || !Array.isArray(parsed.models)) return;+ const inCatalog = new Set<string>();+ for (const m of parsed.models as { platform?: unknown; modelId?: unknown }[]) {+ if (typeof m?.platform === 'string' && typeof m?.modelId === 'string') {+ inCatalog.add(`${m.platform}:${m.modelId}`);+ }+ }+ const rows = db+ .prepare("SELECT id, platform, model_id FROM models WHERE source = 'catalog'")+ .all() as { id: number; platform: string; model_id: string }[];+ const markUser = db.prepare("UPDATE models SET source = 'user' WHERE id = ?");+ for (const row of rows) {+ if (!inCatalog.has(`${row.platform}:${row.model_id}`)) markUser.run(row.id);+ }+ } catch {+ // A corrupt cached catalog must not block the migration; rows keep the+ // heuristic-based backfill above, which errs on the side the old guard+ // already enforced.+ }+}++export function down(db: Db): void {+ if (hasColumn(db, 'models', 'source')) {+ db.prepare('ALTER TABLE models DROP COLUMN source').run();+ }+}diff --git a/server/src/db/migrations/20260726_000004_media_model_meta.ts b/server/src/db/migrations/20260726_000004_media_model_meta.tsnew file mode 100644index 00000000..bfdbb5d5--- /dev/null+++ b/server/src/db/migrations/20260726_000004_media_model_meta.ts@@ -0,0 +1,38 @@+// Migration: media_models.meta_json — per-model adapter metadata from the catalog+// Created: 2026-07-26+//+// DOWN: reversible+//+// The transcription (STT) registry moves out of code and into the published+// catalog's `transcriptionModels` array, landing in media_models with+// modality='transcription'. Unlike image/TTS rows, transcription rows carry+// per-model facts the adapters need at request time:+// - subtitleFormats: subtitle formats the provider produces natively (vtt)+// - maxBytes: provider upload ceiling in bytes+// - requestStyle: adapter request flavor where one platform hosts more+// than one deployment style (cloudflare 'json' = base64+// JSON body, 'binary' = raw bytes)+// These ride in one nullable JSON column rather than three sparse columns:+// they are opaque to SQL (never filtered or joined on), only parsed by the+// media service, and future modalities can reuse the column without another+// migration. NULL / absent keys mean "no special capability", which is the+// correct default for every pre-existing image/audio row.++import type { Db } from '../types.js';++function hasColumn(db: Db, table: string, column: string): boolean {+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];+ return columns.some((candidate) => candidate.name === column);+}++export function up(db: Db): void {+ if (!hasColumn(db, 'media_models', 'meta_json')) {+ db.prepare('ALTER TABLE media_models ADD COLUMN meta_json TEXT').run();+ }+}++export function down(db: Db): void {+ if (hasColumn(db, 'media_models', 'meta_json')) {+ db.prepare('ALTER TABLE media_models DROP COLUMN meta_json').run();+ }+}diff --git a/server/src/docs/openapi.ts b/server/src/docs/openapi.tsindex 021f920a..6fe6679b 100644--- a/server/src/docs/openapi.ts+++ b/server/src/docs/openapi.ts@@ -198,6 +198,58 @@ export const openapiSpec = {},},},+ '/audio/transcriptions': {+ post: {+ tags: ['Media'],+ operationId: 'createTranscription',+ summary: 'Transcribe audio (speech-to-text)',+ description:+ 'OpenAI-compatible speech-to-text over free whisper deployments (Groq, Cloudflare Workers AI), ' ++ 'with failover across providers. Multipart upload, held in memory only; maximum file size 25 MB. ' ++ "response_format 'vtt' is only available from providers that produce it natively; 'srt' is not " ++ 'supported and returns 400 unsupported_format. The model registry is delivered by catalog sync; ' ++ "an install that has not yet synced any transcription models returns 503 with code 'no_transcription_models'.",+ requestBody: {+ required: true,+ content: {+ 'multipart/form-data': {+ schema: { $ref: '#/components/schemas/TranscriptionRequest' },+ },+ },+ },+ responses: {+ '200': {+ description: 'The transcription in the requested format.',+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: { text: { type: 'string' } },+ },+ },+ 'text/plain': { schema: { type: 'string' } },+ },+ },+ '400': { $ref: '#/components/responses/BadRequest' },+ '401': { $ref: '#/components/responses/Unauthorized' },+ '413': {+ description: 'The uploaded audio exceeds the 25 MB limit.',+ content: {+ 'application/json': { schema: { $ref: '#/components/schemas/Error' } },+ },+ },+ '429': { $ref: '#/components/responses/RateLimited' },+ '502': { $ref: '#/components/responses/UpstreamError' },+ '503': {+ description:+ "No transcription models synced yet (code 'no_transcription_models'): the registry arrives via catalog sync.",+ content: {+ 'application/json': { schema: { $ref: '#/components/schemas/Error' } },+ },+ },+ },+ },+ },'/responses': {post: {tags: ['Responses'],@@ -568,6 +620,29 @@ export const openapiSpec = {response_format: { type: 'string', example: 'mp3' },},},+ TranscriptionRequest: {+ type: 'object',+ required: ['file', 'model'],+ properties: {+ file: { type: 'string', format: 'binary', description: 'The audio file to transcribe (max 25 MB).' },+ model: {+ type: 'string',+ description: "'whisper-1' or 'auto' lets the router pick; a provider model id (e.g. 'whisper-large-v3-turbo', '@cf/openai/whisper') pins to that deployment.",+ },+ language: { type: 'string', description: 'ISO-639-1 hint forwarded to the provider.' },+ prompt: { type: 'string', description: 'Optional context/spelling hint forwarded to the provider.' },+ temperature: { type: 'number', minimum: 0, maximum: 1 },+ response_format: {+ type: 'string',+ enum: ['json', 'text', 'verbose_json', 'vtt'],+ default: 'json',+ description:+ "'verbose_json' includes segments when the provider returns them (falls back to the plain json shape otherwise). " ++ "'vtt' is only served by providers that produce it natively (Cloudflare Workers AI whisper). " ++ "'srt' is not supported and returns 400 unsupported_format.",+ },+ },+ },ResponseRequest: {type: 'object',required: ['input'],diff --git a/server/src/lib/attempt-trace.ts b/server/src/lib/attempt-trace.tsnew file mode 100644index 00000000..c84360d3--- /dev/null+++ b/server/src/lib/attempt-trace.ts@@ -0,0 +1,70 @@+// Per-request attempt trace: the durable record of the failover ladder one+// proxied request walked (groq 429 → google timeout → cerebras ok). The+// fallback loop collects one AttemptTraceRecord per dispatched attempt —+// including the SUCCESSFUL final one — and request-log.ts persists the batch+// into `request_attempts`, keyed to the terminal `requests` row.+//+// The trace travels on AsyncLocalStorage (same pattern as client-context.ts)+// so logRequest() can report back the id of each `requests` row it writes+// without threading a parameter through every surface's dispatch closure.+// The LAST id noted during a loop run is the terminal row — the success row,+// a committed mid-stream error row, or the final per-attempt failure row —+// and that is the row the batch is keyed to. Calls to logRequest outside a+// fallback-loop run (fusion sub-calls, embeddings, media) see no trace and+// are unaffected.++import { AsyncLocalStorage } from 'async_hooks';+import type { AttemptErrorClass } from './fallback-loop.js';++// 'ok' — the attempt produced the client's response ('done').+// 'committed' — a stream flushed real bytes, then ended without a clean+// finish (mid-stream error the surface rendered honestly, or+// a pre-commit client disconnect the surface swallowed); the+// parent requests row carries the specifics.+// 'client_abort' — the client hung up mid-attempt; the upstream call was+// canceled and no failure bookkeeping ran.+// AttemptErrorClass — the failure class of a failed-and-failed-over attempt.+export type AttemptOutcome = 'ok' | 'committed' | 'client_abort' | AttemptErrorClass;++export interface AttemptTraceRecord {+ // 0-based position in the ladder; the persistence order key.+ ordinal: number;+ platform: string;+ modelId: string;+ // Per-request key ordinal (key1, key2…), same anonymization as the+ // X-Fallback-Trail header — never the internal key id.+ keyOrdinal: number;+ outcome: AttemptOutcome;+ // Milliseconds from the ladder's start to this attempt's dispatch.+ startOffsetMs: number;+ // Milliseconds this attempt ran (for 'ok' streams: until the response+ // finished, i.e. including streaming time).+ durationMs: number;+}++export interface RequestTrace {+ records: AttemptTraceRecord[];+ // Rowid of the most recent `requests` row logged during this trace's run;+ // null until the first logRequest lands (e.g. a client abort on attempt 1).+ lastRequestRowId: number | null;+}++const storage = new AsyncLocalStorage<RequestTrace>();++export function newRequestTrace(): RequestTrace {+ return { records: [], lastRequestRowId: null };+}++export function runWithRequestTrace<T>(trace: RequestTrace, fn: () => T): T {+ return storage.run(trace, fn);+}++export function getRequestTrace(): RequestTrace | undefined {+ return storage.getStore();+}++/** Called by logRequest() after inserting a `requests` row; no-op outside a trace. */+export function noteRequestRowId(id: number | bigint): void {+ const trace = storage.getStore();+ if (trace) trace.lastRequestRowId = Number(id);+}diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.tsindex f9a91033..f02b90b6 100644--- a/server/src/lib/fallback-loop.ts+++ b/server/src/lib/fallback-loop.ts@@ -44,6 +44,8 @@ import { sanitizeProviderErrorMessage } from './error-redaction.js';import { checkKeyHealth, markKeyHealthyFromRequest } from '../services/health.js';import { getSetting } from '../db/index.js';import { newBreaker, recordBreakerFailure } from './guardrails.js';+import { newRequestTrace, runWithRequestTrace, type AttemptOutcome, type RequestTrace } from './attempt-trace.js';+import { persistRequestAttempts } from './request-log.js';// Every surface caps failover hops at the same number.export const FALLBACK_MAX_RETRIES = 20;@@ -720,6 +722,24 @@ export interface FallbackHooks {* routing — lives in the hooks.*/export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {+ // Durable per-attempt trace (P2 #15): every dispatched attempt — including+ // the successful final one — is recorded with timing and outcome, then+ // persisted as one insert batch into `request_attempts`, keyed to the+ // terminal `requests` row of this ladder. The trace rides AsyncLocalStorage+ // so logRequest() (called deep inside the surfaces' dispatch closures) can+ // report back the row ids it writes without any surface changing. The flush+ // runs after the loop returns — i.e. after the response is finished — so it+ // never sits on the client's latency path, and it is a no-op when no+ // `requests` row was written (pure client aborts).+ const trace = newRequestTrace();+ try {+ await runWithRequestTrace(trace, () => runFallbackLoopAttempts(hooks, trace));+ } finally {+ persistRequestAttempts(trace);+ }+}++async function runFallbackLoopAttempts(hooks: FallbackHooks, trace: RequestTrace): Promise<void> {const maxRetries = hooks.maxRetries ?? FALLBACK_MAX_RETRIES;const budgetMs = hooks.timeBudgetMs ?? getFallbackTimeBudgetMs();const startedAt = Date.now();@@ -790,6 +810,23 @@ export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {return;}+ // Per-attempt trace record: pushed exactly once per dispatched attempt, on+ // whichever exit the attempt takes. startOffsetMs/durationMs bracket the+ // dispatch (for a successful stream, durationMs runs until the response+ // finished — that IS the attempt).+ const attemptStartedAt = Date.now();+ const traceAttempt = (outcome: AttemptOutcome): void => {+ trace.records.push({+ ordinal: trace.records.length,+ platform: route.platform,+ modelId: route.modelId,+ keyOrdinal: keyOrdinal(route),+ outcome,+ startOffsetMs: attemptStartedAt - startedAt,+ durationMs: Date.now() - attemptStartedAt,+ });+ };+// Everything from here to the end of the iteration runs inside a finally that// frees the route's in-flight lease. Every exit — success, auth rotation,// retryable continue, fatal, breaker trip, contract violation — passes through@@ -809,6 +846,10 @@ export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {// below still frees the in-flight lease.if (isClientAbortError(err)) {console.log(`[FallbackLoop] client disconnected mid-attempt on ${route.platform}/${route.modelId} — upstream canceled, stopping without benching`);+ // Trace only: persisted iff an earlier failure already wrote a+ // `requests` row (the requests table records nothing for a pure abort,+ // and the trace stays consistent with that).+ traceAttempt('client_abort');return;}hooks.logFailure(route, err, attempt);@@ -817,13 +858,16 @@ export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {// it immediately instead of 502-ing while healthy routes sit idle.recordAuthFailure(route, hooks.state);attempts.push({ platform: route.platform, modelId: route.modelId, keyOrdinal: keyOrdinal(route), errorClass: 'auth' });+ traceAttempt('auth');lastError = err;if (stopIfBreakerTripped()) return;continue;}if (isRetryableError(err)) {recordRetryableFailure(route, err, hooks.state);- attempts.push({ platform: route.platform, modelId: route.modelId, keyOrdinal: keyOrdinal(route), errorClass: classifyAttemptError(err) });+ const errorClass = classifyAttemptError(err);+ attempts.push({ platform: route.platform, modelId: route.modelId, keyOrdinal: keyOrdinal(route), errorClass });+ traceAttempt(errorClass);lastError = err;// skipBench failures (format ignored, hidden-reasoning truncation) are// model behavior, not provider health — recordRetryableFailure already@@ -833,6 +877,7 @@ export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {if (err?.skipBench !== true && stopIfBreakerTripped()) return;continue;}+ traceAttempt(classifyAttemptError(err));hooks.onFatal(route, err, attempt);return;}@@ -851,8 +896,14 @@ export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {);console.error('[FallbackLoop]', violation.message);hooks.logFailure(route, violation, attempt);+ traceAttempt('error');hooks.onFatal(route, violation, attempt);+ return;}+ // Terminal attempt: 'done' produced the response; 'committed' means the+ // stream had already flushed bytes when the attempt ended (mid-stream+ // error or pre-commit disconnect) — the parent row carries the specifics.+ traceAttempt(outcome === 'done' ? 'ok' : 'committed');return;} finally {route.release?.();diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.tsindex ce2d208c..73387018 100644--- a/server/src/lib/proxy.ts+++ b/server/src/lib/proxy.ts@@ -143,7 +143,7 @@ async function resolveDispatcher(): Promise<{ dispatcher: unknown; isSocks: bool* written to `requests.request_type` so the abort message and the row* column agree on terminology.*/-export type ProxyRequestType = 'chat' | 'embedding' | 'image' | 'audio' | 'unknown';+export type ProxyRequestType = 'chat' | 'embedding' | 'image' | 'audio' | 'transcription' | 'unknown';/*** Build an AbortError DOMException whose `message` carries a compact triagediff --git a/server/src/lib/request-log.ts b/server/src/lib/request-log.tsindex bceafa76..a108e1b7 100644--- a/server/src/lib/request-log.ts+++ b/server/src/lib/request-log.ts@@ -1,6 +1,7 @@import { getDb } from '../db/index.js';import { pruneRequestAnalytics } from '../services/request-retention.js';import { getClientContext } from './client-context.js';+import { noteRequestRowId, type RequestTrace } from './attempt-trace.js';type LogTx = ReturnType<typeof getDb>;@@ -66,6 +67,11 @@ export function logRequest(VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(platform, modelId, keyId, status, inputTokens, outputTokens, latencyMs, error, ttfbMs, requestedModel, client.ip, client.userAgent);+ // Report the row id back to the fallback loop's attempt trace (if one is+ // active): the LAST id noted during a loop run is the terminal row the+ // per-attempt batch is keyed to. No-op outside a fallback-loop run.+ if (insert.lastInsertRowid != null) noteRequestRowId(insert.lastInsertRowid);+const createdAt = db.prepare(`SELECT created_at FROM requests WHERE id = ?`).get(insert.lastInsertRowid) as { created_at: string } | undefined;const hour = hourKey(createdAt?.created_at ?? new Date().toISOString().slice(0, 19).replace('T', ' '));const isSuccess = status === 'success' ? 1 : 0;@@ -96,3 +102,30 @@ export function logRequest(console.error('Failed to log request:', e);}}++// Persist a finished attempt trace as one small insert batch keyed to the+// terminal `requests` row of the failover ladder (the success row, a committed+// mid-stream error row, or the last per-attempt failure row). Called once per+// request by the fallback loop AFTER the response is finished, so the write is+// off the client's latency path. Zero-failure single-attempt successes write+// exactly one 'ok' row; a trace with no parent row (e.g. a client abort before+// any attempt was logged) writes nothing — consistent with the `requests`+// table, which records nothing for those either.+export function persistRequestAttempts(trace: RequestTrace): void {+ if (trace.records.length === 0 || trace.lastRequestRowId == null) return;+ try {+ const db = getDb();+ const insert = db.prepare(`+ INSERT INTO request_attempts (request_id, ordinal, platform, model_id, key_ordinal, outcome, start_offset_ms, duration_ms)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ `);+ const tx = db.transaction(() => {+ for (const r of trace.records) {+ insert.run(trace.lastRequestRowId, r.ordinal, r.platform, r.modelId, r.keyOrdinal, r.outcome, r.startOffsetMs, r.durationMs);+ }+ });+ tx();+ } catch (e) {+ console.error('Failed to persist request attempts:', e);+ }+}diff --git a/server/src/lib/sampling-params.ts b/server/src/lib/sampling-params.tsindex 0e832ae8..89951093 100644--- a/server/src/lib/sampling-params.ts+++ b/server/src/lib/sampling-params.ts@@ -24,6 +24,13 @@import { z } from 'zod';import type { Platform } from '@freellmapi/shared/types.js';+// OpenAI's request-side reasoning knob. Wire values as of the current OpenAI+// API: 'minimal'|'low'|'medium'|'high', plus 'none' (gpt-5.1). Forwarded+// verbatim to openai-compat platforms per the policy below; the Google+// adapter maps it natively onto generationConfig.thinkingConfig.+export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high'] as const;+export type ReasoningEffort = typeof REASONING_EFFORTS[number];+// Every field is `.nullable()` because real clients serialize their whole// request struct and send explicit nulls for unset knobs (#200); null is// treated as absent and never forwarded.@@ -45,6 +52,14 @@ export const samplingParamSchemaFields = {schema: z.record(z.string(), z.unknown()).optional(),}).passthrough().optional(),}).passthrough().nullable().optional(),+ reasoning_effort: z.enum(REASONING_EFFORTS).nullable().optional(),+ // Object-form alias some clients send (OpenRouter-style chat clients, and+ // the Responses API's native shape): `reasoning: { effort }`. Resolved into+ // reasoning_effort by pickSamplingParams; the wrapper object itself is never+ // forwarded. Extra keys (summary, max_tokens…) are tolerated and ignored.+ reasoning: z.object({+ effort: z.enum(REASONING_EFFORTS).nullable().optional(),+ }).passthrough().nullable().optional(),// OpenAI's newer alias for max_tokens; surfaces resolve it into max_tokens// themselves (it is not a forwarded param of its own).max_completion_tokens: z.number().int().nullable().optional(),@@ -70,17 +85,22 @@ export interface ExtendedSamplingOptions {logprobs?: boolean;top_logprobs?: number;response_format?: ResponseFormat;+ reasoning_effort?: ReasoningEffort;}export const EXTENDED_SAMPLING_KEYS = ['top_k', 'min_p', 'seed', 'presence_penalty', 'frequency_penalty','repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs',- 'response_format',+ 'response_format', 'reasoning_effort',] as const;export type ExtendedSamplingKey = typeof EXTENDED_SAMPLING_KEYS[number];type ParsedSamplingBody = {[K in ExtendedSamplingKey]?: unknown;+} & {+ // Object-form reasoning alias (see samplingParamSchemaFields); resolved into+ // reasoning_effort below, never forwarded as-is.+ reasoning?: { effort?: unknown } | null;};/**@@ -97,6 +117,14 @@ export function pickSamplingParams(body: ParsedSamplingBody): ExtendedSamplingOpif (key === 'response_format' && (value as { type?: string }).type === 'text') continue;out[key] = value;}+ // Object-form fallback: `reasoning: { effort }` fills reasoning_effort only+ // when the flat field wasn't sent (the explicit flat form wins on conflict).+ if (out.reasoning_effort === undefined) {+ const effort = body.reasoning?.effort;+ if (typeof effort === 'string' && (REASONING_EFFORTS as readonly string[]).includes(effort)) {+ out.reasoning_effort = effort;+ }+ }return out as ExtendedSamplingOptions;}@@ -124,9 +152,10 @@ export interface PlatformParamPolicy {// boundary since routes carry platform ids as plain strings.export const PLATFORM_PARAM_POLICIES: Partial<Record<Platform, PlatformParamPolicy>> = {// Mistral's API is strict (422 on unknown body keys) and names its seed- // `random_seed`. It has no top_k/min_p/logit_bias/logprobs equivalents.+ // `random_seed`. It has no top_k/min_p/logit_bias/logprobs equivalents, and+ // no reasoning_effort (Magistral's reasoning has no request-side knob).mistral: {- drop: ['top_k', 'min_p', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs'],+ drop: ['top_k', 'min_p', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs', 'reasoning_effort'],rename: { seed: 'random_seed' },},// Groq documents logprobs / top_logprobs / logit_bias as unsupported and@@ -136,14 +165,16 @@ export const PLATFORM_PARAM_POLICIES: Partial<Record<Platform, PlatformParamPoli// argument" for knobs outside the OpenAI set.github: { drop: ['top_k', 'min_p', 'repetition_penalty'] },// Gemini's generationConfig has no equivalents for these; the adapter- // translates the rest natively (topK, seed, penalties, responseSchema).+ // translates the rest natively (topK, seed, penalties, responseSchema, and+ // reasoning_effort → thinkingConfig — see toGeminiExtendedConfig).google: { drop: ['min_p', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs'] },// Cohere's OpenAI-compat endpoint covers seed/penalties/response_format;- // the rest have no mapping there.- cohere: { drop: ['top_k', 'min_p', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs'] },+ // the rest (incl. reasoning_effort — Cohere's own knob is a non-OpenAI+ // `thinking` object) have no mapping there.+ cohere: { drop: ['top_k', 'min_p', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs', 'reasoning_effort'] },// Workers AI's OpenAI-compat endpoint parses a known subset; send only what// it understands.- cloudflare: { drop: ['min_p', 'logit_bias', 'logprobs', 'top_logprobs'] },+ cloudflare: { drop: ['min_p', 'logit_bias', 'logprobs', 'top_logprobs', 'reasoning_effort'] },// AI Horde builds its own payload format; none of the extended set maps.aihorde: { drop: [...EXTENDED_SAMPLING_KEYS] },// Kilo's anonymous gateway 400s ("Provider returned error") wheneverdiff --git a/server/src/lib/think-tags.ts b/server/src/lib/think-tags.tsnew file mode 100644index 00000000..f7e233f7--- /dev/null+++ b/server/src/lib/think-tags.ts@@ -0,0 +1,211 @@+import type { ChatCompletionChunk } from '@freellmapi/shared/types.js';++// Inline `<think>…</think>` extraction (DeepSeek-style reasoning models).+//+// Some models serialize their reasoning trace INTO `content` as a leading+// `<think>…</think>` block instead of the separate `reasoning_content` field+// other providers use (Z.ai, Ollama, Gemini thought parts — all already+// normalized elsewhere). Forwarding the tags verbatim makes downstream tools+// render thinking as answer text. This module splits it back out into the+// OpenAI-convention `reasoning_content` field (non-streaming) and+// `delta.reasoning_content` chunks (streaming).+//+// Deliberately conservative: only a `<think>` that OPENS the message (after+// optional whitespace) starts extraction — a model *quoting* the literal tag+// mid-answer is left untouched. Once the block closes, everything after it is+// passed through verbatim (no re-arming), so at most one block per message is+// extracted. Matching is exact and lowercase — the only spelling observed live.+//+// Streaming buffer strategy (the tag can split across chunk boundaries):+// - 'lead': holds at most leading whitespace plus a strict prefix of+// `<think>` (7 chars); decides passthrough the moment a byte diverges.+// - 'thinking': emits reasoning incrementally, holding back only the longest+// trailing run that is a strict prefix of `</think>` (≤ 7 chars).+// - 'passthrough': zero-copy.+// The whole stream is never buffered. An unclosed tag at stream end flushes+// the held bytes as reasoning; an undecided lead buffer (e.g. a message that+// is just "<thi") flushes as content — text is never lost.++const OPEN_TAG = '<think>';+const CLOSE_TAG = '</think>';+// A lead buffer longer than this cannot plausibly be "whitespace before+// <think>" — bail to passthrough so a pathological all-whitespace stream+// can't grow the hold buffer unboundedly.+const MAX_LEAD_HOLD = 512;++export interface ThinkSplit {+ content: string;+ reasoning: string;+}++/** Length of the longest suffix of `s` that is a strict prefix of `tag`. */+function partialTagSuffix(s: string, tag: string): number {+ const max = Math.min(s.length, tag.length - 1);+ for (let len = max; len > 0; len--) {+ if (s.endsWith(tag.slice(0, len))) return len;+ }+ return 0;+}++type FilterState = 'lead' | 'thinking' | 'afterClose' | 'passthrough';++export class ThinkTagStreamFilter {+ private state: FilterState = 'lead';+ // 'lead': optional whitespace + a strict prefix of OPEN_TAG.+ // 'thinking': a strict prefix of CLOSE_TAG.+ // Other states: always empty.+ private pending = '';++ /** Feed a text delta; returns the content/reasoning to emit for it. */+ push(text: string): ThinkSplit {+ let content = '';+ let reasoning = '';+ let input = this.pending + text;+ this.pending = '';++ while (input.length > 0) {+ if (this.state === 'lead') {+ const trimmed = input.replace(/^\s+/, '');+ if (trimmed.length === 0) {+ // All whitespace so far — could still precede a tag. Hold (bounded).+ if (input.length > MAX_LEAD_HOLD) {+ this.state = 'passthrough';+ content += input;+ } else {+ this.pending = input;+ }+ input = '';+ } else if (trimmed.startsWith(OPEN_TAG)) {+ this.state = 'thinking';+ input = trimmed.slice(OPEN_TAG.length);+ } else if (OPEN_TAG.startsWith(trimmed)) {+ // Strict prefix of the tag — wait for the next delta to decide.+ this.pending = input;+ input = '';+ } else {+ // Provably not a think-opened message: everything is content.+ this.state = 'passthrough';+ content += input;+ input = '';+ }+ } else if (this.state === 'thinking') {+ const idx = input.indexOf(CLOSE_TAG);+ if (idx !== -1) {+ reasoning += input.slice(0, idx);+ input = input.slice(idx + CLOSE_TAG.length);+ this.state = 'afterClose';+ } else {+ const hold = partialTagSuffix(input, CLOSE_TAG);+ reasoning += input.slice(0, input.length - hold);+ this.pending = hold > 0 ? input.slice(input.length - hold) : '';+ input = '';+ }+ } else if (this.state === 'afterClose') {+ // Drop the whitespace models emit between `</think>` and the answer.+ const trimmed = input.replace(/^\s+/, '');+ if (trimmed.length > 0) this.state = 'passthrough';+ input = trimmed;+ } else {+ content += input;+ input = '';+ }+ }+ return { content, reasoning };+ }++ /** Stream ended: release whatever is held. Unclosed `<think>` flushes as+ * reasoning; an undecided lead buffer flushes as content. */+ flush(): ThinkSplit {+ const held = this.pending;+ this.pending = '';+ if (this.state === 'thinking') {+ this.state = 'passthrough';+ return { content: '', reasoning: held };+ }+ this.state = 'passthrough';+ return { content: held, reasoning: '' };+ }+}++/** Non-streaming split of a complete message body. Returns the original text+ * as `content` (reasoning: '') when the message doesn't open with `<think>`. */+export function splitThinkTag(text: string): ThinkSplit {+ const filter = new ThinkTagStreamFilter();+ const main = filter.push(text);+ const tail = filter.flush();+ return { content: main.content + tail.content, reasoning: main.reasoning + tail.reasoning };+}++/**+ * In-place extraction for a non-streaming choice message: moves a leading+ * `<think>…</think>` block out of `content` into `reasoning_content`+ * (appending when the provider already set one). No-op for messages without+ * an opening tag, so no-knob/no-tag responses are byte-identical.+ */+export function extractThinkFromMessage(msg: { content?: unknown; reasoning_content?: string }): void {+ if (typeof msg.content !== 'string' || !msg.content.includes(OPEN_TAG)) return;+ const { content, reasoning } = splitThinkTag(msg.content);+ if (reasoning.length === 0) return;+ msg.content = content;+ msg.reasoning_content = msg.reasoning_content && msg.reasoning_content.length > 0+ ? `${msg.reasoning_content}\n${reasoning}`+ : reasoning;+}++/**+ * Streaming wrapper: rewrites `choices[0].delta.content` through the filter,+ * emitting extracted reasoning as `delta.reasoning_content` on the same+ * chunk. Chunks without text (role preambles, tool_call deltas, usage frames,+ * native reasoning deltas) pass through untouched. When the source ends with+ * held bytes (unclosed tag / undecided prefix) a final synthetic chunk+ * carries them, so text is never lost.+ */+export async function* extractThinkTagsFromStream(+ source: AsyncGenerator<ChatCompletionChunk>,+): AsyncGenerator<ChatCompletionChunk> {+ const filter = new ThinkTagStreamFilter();+ let meta: { id: string; model: string; created: number } | null = null;++ for await (const chunk of source) {+ if (chunk?.id) meta = { id: chunk.id, model: chunk.model, created: chunk.created };+ const choice = chunk?.choices?.[0];+ const raw = choice?.delta?.content;+ if (typeof raw !== 'string' || raw.length === 0) {+ yield chunk;+ continue;+ }+ const { content, reasoning } = filter.push(raw);+ if (content === raw && reasoning.length === 0) {+ // Fast path (passthrough state): forward untouched.+ yield chunk;+ continue;+ }+ // Chunks are parsed fresh from JSON per SSE frame, so in-place mutation is+ // safe — same rationale as normalizeOutboundContent.+ choice.delta.content = content;+ if (reasoning.length > 0) {+ choice.delta.reasoning_content = choice.delta.reasoning_content+ ? choice.delta.reasoning_content + reasoning+ : reasoning;+ }+ yield chunk;+ }++ const tail = filter.flush();+ if (tail.content.length > 0 || tail.reasoning.length > 0) {+ yield {+ id: meta?.id ?? `chatcmpl-${Date.now()}`,+ object: 'chat.completion.chunk',+ created: meta?.created ?? Math.floor(Date.now() / 1000),+ model: meta?.model ?? '',+ choices: [{+ index: 0,+ delta: {+ ...(tail.content.length > 0 ? { content: tail.content } : {}),+ ...(tail.reasoning.length > 0 ? { reasoning_content: tail.reasoning } : {}),+ },+ finish_reason: null,+ }],+ };+ }+}diff --git a/server/src/providers/base.ts b/server/src/providers/base.tsindex 4fc0adbe..0a3e4192 100644--- a/server/src/providers/base.ts+++ b/server/src/providers/base.ts@@ -10,6 +10,7 @@ import type { QuotaObservationContext } from '../services/provider-quota.js';import type { ExtendedSamplingOptions } from '../lib/sampling-params.js';import { proxyFetch } from '../lib/proxy.js';import { providerTimeoutMs, streamStallTimeoutMs } from '../lib/provider-timeout.js';+import { extractThinkTagsFromStream } from '../lib/think-tags.js';/** A provider HTTP error carrying the upstream status and, when the response* included a Retry-After header, the parsed delay so the router can bench the@@ -255,8 +256,21 @@ export abstract class BaseProvider {* (several compat shims) still complete normally.** Malformed data lines are skipped, matching previous behavior.+ *+ * The frames additionally pass through the inline `<think>` extractor+ * (lib/think-tags.ts): DeepSeek-style models that serialize their reasoning+ * trace INTO delta.content as a leading `<think>…</think>` block get it+ * moved to delta.reasoning_content, so downstream surfaces never render+ * thinking as answer text. Streams without the tag are forwarded verbatim.*/protected async *readSseStream(+ res: Response,+ inactivityTimeoutMs?: number,+ ): AsyncGenerator<ChatCompletionChunk> {+ yield* extractThinkTagsFromStream(this.readSseFrames(res, inactivityTimeoutMs));+ }++ private async *readSseFrames(res: Response,// The 90s default was hardcoded and silently truncated slow streams — the// gateway ended them with an error frame plus a clean [DONE] that OpenAIdiff --git a/server/src/providers/cloudflare.ts b/server/src/providers/cloudflare.tsindex d48daf8a..08bfefcc 100644--- a/server/src/providers/cloudflare.ts+++ b/server/src/providers/cloudflare.ts@@ -6,6 +6,7 @@ import type {import { BaseProvider, providerHttpError, type CompletionOptions, type KeyValidationResult, type KeyValidationFailure } from './base.js';import { extendedBodyParams } from '../lib/sampling-params.js';import { contentToString } from '../lib/content.js';+import { extractThinkFromMessage } from '../lib/think-tags.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';import { providerTimeoutMs } from '../lib/provider-timeout.js';@@ -94,6 +95,12 @@ export class CloudflareProvider extends BaseProvider {}const data = await res.json() as ChatCompletionResponse;+ // Workers AI hosts DeepSeek-style models that inline their reasoning trace+ // as a leading `<think>…</think>` block in content; move it to+ // reasoning_content (no-op for messages without the tag).+ for (const choice of data.choices ?? []) {+ if (choice?.message) extractThinkFromMessage(choice.message);+ }data._routed_via = { platform: 'cloudflare', model: modelId };return data;}diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 46664332..264dc3ff 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -237,6 +237,16 @@ function sanitizeForGeminiSchema(schema: unknown, insidePropertiesMap: boolean):// declaration, and can ride alongside real function tools in the same array. (#59)const GROUNDING_TOOL_NAMES = new Set(['google_search', 'googlesearch', 'google_search_retrieval']);+// reasoning_effort → Gemini thinkingBudget (tokens). The low/medium/high+// budgets follow the common gateway convention (OpenRouter's effort mapping);+// 'none'/'minimal' disable thinking outright. Models that can't run at the+// requested budget 400 and fail over like any provider-invalid request.+const EFFORT_THINKING_BUDGET: Record<'low' | 'medium' | 'high', number> = {+ low: 1024,+ medium: 8192,+ high: 24576,+};+/*** Extended generationConfig knobs translated from the OpenAI wire: topK,* seed, penalties, and structured output. JSON output conflicts with function@@ -265,6 +275,17 @@ export function toGeminiExtendedConfig(options?: CompletionOptions): Record<striconst schema = rf.type === 'json_schema' ? rf.json_schema?.schema : undefined;if (schema) out.responseSchema = sanitizeForGemini(schema);}+ // Request-side reasoning control: reasoning_effort → thinkingConfig. Only+ // set when the client asked — a request without the knob keeps Gemini's+ // model-default thinking behavior unchanged. includeThoughts surfaces+ // thought summaries so reasoning_content flows back out (see+ // extractReasoningContent).+ const effort = options?.reasoning_effort;+ if (effort) {+ out.thinkingConfig = (effort === 'none' || effort === 'minimal')+ ? { thinkingBudget: 0 }+ : { thinkingBudget: EFFORT_THINKING_BUDGET[effort], includeThoughts: true };+ }return out;}diff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.tsindex d0af2bb9..af512509 100644--- a/server/src/providers/openai-compat.ts+++ b/server/src/providers/openai-compat.ts@@ -8,6 +8,7 @@ import type {import { BaseProvider, providerHttpError, type CompletionOptions, type KeyValidationResult } from './base.js';import { extendedBodyParams } from '../lib/sampling-params.js';import { rescueInlineToolCalls } from '../lib/tool-call-rescue.js';+import { extractThinkFromMessage } from '../lib/think-tags.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';import { providerTimeoutMs } from '../lib/provider-timeout.js';@@ -396,6 +397,12 @@ function normalizeChoices(data: ChatCompletionResponse): void {.map(seg => (typeof seg === 'string' ? seg : (seg.text ?? ''))).join('');}+ // Inline `<think>…</think>` extraction (DeepSeek-style) BEFORE the fold+ // below: a leading think block moves out of content into+ // reasoning_content. Runs before the fold so a think-only message (no+ // answer after the block) still folds back into content and is never+ // returned as an empty assistant message.+ extractThinkFromMessage(msg);// Fold reasoning into content if content is empty AND there are no// tool_calls. With tool_calls present, content=null is the correct OpenAI// shape; folding reasoning would confuse clients that branch on content.diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.tsindex 5ce69a2a..6a0000e2 100644--- a/server/src/routes/analytics.ts+++ b/server/src/routes/analytics.ts@@ -477,7 +477,8 @@ analyticsRouter.get('/requests', (req: Request, res: Response) => {SELECT id, platform, model_id, requested_model, request_type, status,input_tokens, output_tokens, latency_ms, error,client_ip, client_user_agent,- strftime('%Y-%m-%dT%H:%M:%SZ', created_at) as created_at_iso+ strftime('%Y-%m-%dT%H:%M:%SZ', created_at) as created_at_iso,+ (SELECT COUNT(*) FROM request_attempts a WHERE a.request_id = requests.id) as attempt_countFROM requestsWHERE created_at >= ?ORDER BY created_at DESC, id DESC@@ -500,6 +501,71 @@ analyticsRouter.get('/requests', (req: Request, res: Response) => {clientIp: r.client_ip,clientUserAgent: r.client_user_agent,createdAt: r.created_at_iso,+ // Failover-ladder length for this row. Attempts hang off the TERMINAL+ // row of a proxied request; mid-ladder failure rows report 0.+ attemptCount: r.attempt_count,+ })),+ });+});++// Per-request detail: the row plus its durable failover ladder — one entry per+// dispatched attempt (including the successful final one), ordinal-ordered,+// with the failure class and timing of each hop. keyOrdinal is the per-request+// key ordinal (key1, key2…), same anonymization as X-Fallback-Trail — internal+// key ids are never exposed. Attempts are keyed to the ladder's terminal row+// (the success row, or the last failure row when it exhausted), so mid-ladder+// error rows legitimately return an empty attempts array.+analyticsRouter.get('/requests/:id', (req: Request, res: Response) => {+ const id = Number.parseInt(req.params.id as string, 10);+ if (!Number.isInteger(id) || id <= 0) {+ res.status(400).json({ error: 'invalid request id' });+ return;+ }+ const db = getDb();++ const r = db.prepare(`+ SELECT id, platform, model_id, requested_model, request_type, status,+ input_tokens, output_tokens, latency_ms, ttfb_ms, error,+ client_ip, client_user_agent,+ strftime('%Y-%m-%dT%H:%M:%SZ', created_at) as created_at_iso+ FROM requests+ WHERE id = ?+ `).get(id) as any;+ if (!r) {+ res.status(404).json({ error: 'request not found' });+ return;+ }++ const attempts = db.prepare(`+ SELECT ordinal, platform, model_id, key_ordinal, outcome, start_offset_ms, duration_ms+ FROM request_attempts+ WHERE request_id = ?+ ORDER BY ordinal ASC+ `).all(id) as any[];++ res.json({+ id: r.id,+ platform: r.platform,+ modelId: r.model_id,+ requestedModel: r.requested_model,+ requestType: r.request_type,+ status: r.status,+ inputTokens: r.input_tokens,+ outputTokens: r.output_tokens,+ latencyMs: r.latency_ms,+ ttfbMs: r.ttfb_ms,+ error: r.error,+ clientIp: r.client_ip,+ clientUserAgent: r.client_user_agent,+ createdAt: r.created_at_iso,+ attempts: attempts.map(a => ({+ ordinal: a.ordinal,+ platform: a.platform,+ modelId: a.model_id,+ keyOrdinal: a.key_ordinal,+ outcome: a.outcome,+ startOffsetMs: a.start_offset_ms,+ durationMs: a.duration_ms,})),});});diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex 2b4b5f9c..d10974ca 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -21,6 +21,7 @@ import { extractApiToken, timingSafeStringEqual, getStickyModel, setStickyModelimport { runFallbackLoop, newFallbackState, recordUpstreamSuccess, type ExhaustionBody, setFallbackHeaders, setExhaustionHeaders, type AttemptRecord } from '../lib/fallback-loop.js';import { applyTokenBudget, tokenBudgetMessage } from '../lib/guardrails.js';import { resolveAnthropicModel } from '../services/anthropic-map.js';+import type { ReasoningEffort } from '../lib/sampling-params.js';import { buildModelListing } from '../services/model-listing.js';// Anthropic-compatible Messages API (`POST /v1/messages`). This is a thin@@ -87,16 +88,44 @@ const messagesSchema = z.object({stop_sequences: z.array(z.string()).optional(),tools: z.array(anthropicToolSchema).optional(),tool_choice: anthropicToolChoiceSchema.optional(),+ // Anthropic's native extended-thinking knob. Mapped onto the internal+ // reasoning_effort (see effortFromAnthropicThinking) so providers with+ // request-side reasoning control receive it; platforms without support have+ // it stripped by the policy in lib/sampling-params.ts.+ thinking: z.object({+ type: z.enum(['enabled', 'disabled']).optional(),+ budget_tokens: z.number().int().optional(),+ }).passthrough().nullable().optional(),}).passthrough();type AnthropicRequest = z.infer<typeof messagesSchema>;+// Anthropic expresses reasoning control as a token budget; our internal knob+// is OpenAI's coarse effort scale. Thresholds follow Anthropic's own guidance+// bands (minimum budget 1024; multi-10k budgets for hard problems).+export function effortFromAnthropicThinking(+ thinking: { type?: string; budget_tokens?: number } | null | undefined,+): ReasoningEffort | undefined {+ if (!thinking) return undefined;+ if (thinking.type === 'disabled') return 'none';+ const budget = thinking.budget_tokens;+ if (budget == null) return 'medium';+ if (budget < 4096) return 'low';+ if (budget < 16384) return 'medium';+ return 'high';+}+// ── Response shape ──────────────────────────────────────────────────────────type AnthropicStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;interface AnthropicTextBlock { type: 'text'; text: string }interface AnthropicToolUseBlock { type: 'tool_use'; id: string; name: string; input: unknown; thought_signature?: string }-type AnthropicResponseBlock = AnthropicTextBlock | AnthropicToolUseBlock;+// The model's reasoning trace, rendered on Anthropic's native wire shape. The+// signature field is required by the shape but is only meaningful for real+// Anthropic models (replay verification); empty here. Our request converter+// drops thinking blocks on the way in, so replay is safe.+interface AnthropicThinkingBlock { type: 'thinking'; thinking: string; signature: string }+type AnthropicResponseBlock = AnthropicTextBlock | AnthropicToolUseBlock | AnthropicThinkingBlock;interface AnthropicMessageResponse {id: string;@@ -337,6 +366,13 @@ function parseToolInput(raw: string): unknown {function toAnthropicContent(message: ChatMessage | undefined): AnthropicResponseBlock[] {const blocks: AnthropicResponseBlock[] = [];+ // Reasoning output (native provider reasoning_content, or extracted from an+ // inline <think> block by lib/think-tags.ts) → Anthropic thinking block,+ // first per Anthropic convention.+ const reasoning = message?.reasoning_content;+ if (typeof reasoning === 'string' && reasoning.length > 0) {+ blocks.push({ type: 'thinking', thinking: reasoning, signature: '' });+ }const text = contentToString(message?.content ?? '');if (text.length > 0) blocks.push({ type: 'text', text });for (const call of message?.tool_calls ?? []) {@@ -414,7 +450,12 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {const max_tokens = clientMaxTokens?? (budgetCheck.maxTokens != null ? Math.min(DEFAULT_MAX_TOKENS, budgetCheck.maxTokens) : DEFAULT_MAX_TOKENS);- const completionOptions = { temperature, max_tokens, top_p, top_k: body.top_k ?? undefined, tools, tool_choice };+ const completionOptions = {+ temperature, max_tokens, top_p, top_k: body.top_k ?? undefined, tools, tool_choice,+ // Native `thinking: {type, budget_tokens}` → the same internal knob the+ // OpenAI surface's reasoning_effort feeds; absent when the client sent none.+ reasoning_effort: effortFromAnthropicThinking(body.thinking),+ };// Capped output reserve so a large max_tokens can't falsely exclude the model// pool (#470); input + images count in full.const estimatedTotal = estimatedInputTokens + imageCount * IMAGE_TOKEN_ESTIMATE + routingReserveTokens(max_tokens);@@ -638,10 +679,28 @@ async function streamCompletion(messageStarted = true;};+ // Reasoning output (delta.reasoning_content from providers / the <think>+ // extractor, delta.reasoning from Ollama-style upstreams) is buffered and+ // emitted as one complete thinking block right before the first text/tool+ // block. Buffering (not live thinking_delta streaming) keeps the commit+ // point where it was: a stream that produces ONLY reasoning and dies still+ // fails over invisibly, exactly like the OpenAI surface's preamble hold.+ let reasoningBuf = '';+ const flushThinking = () => {+ if (reasoningBuf.length === 0) return;+ const idx = nextIndex++;+ writeSse(res, 'content_block_start', { type: 'content_block_start', index: idx, content_block: { type: 'thinking', thinking: '' } });+ writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: idx, delta: { type: 'thinking_delta', thinking: reasoningBuf } });+ writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: idx });+ outputChars += reasoningBuf.length;+ reasoningBuf = '';+ };+// Commit (if needed), open the text block (if needed), and stream `text`.const emitText = (text: string) => {ensureMessageStart();if (!textBlockOpen) {+ flushThinking(); // thinking block precedes the text blocktextBlockIndex = nextIndex++;writeSse(res, 'content_block_start', { type: 'content_block_start', index: textBlockIndex, content_block: { type: 'text', text: '' } });textBlockOpen = true;@@ -686,6 +745,11 @@ async function streamCompletion(}}+ // Reasoning deltas: providers emit reasoning_content (or Ollama-style+ // `reasoning`); the shared <think> extractor emits reasoning_content.+ const reasoningDelta = choice.delta?.reasoning_content ?? choice.delta?.reasoning;+ if (typeof reasoningDelta === 'string' && reasoningDelta.length > 0) reasoningBuf += reasoningDelta;+const text = typeof choice.delta?.content === 'string' ? choice.delta.content : '';if (text.length === 0) continue;@@ -770,6 +834,9 @@ async function streamCompletion(ensureMessageStart();if (textBlockOpen) writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: textBlockIndex });+ // Residual reasoning: tool-only turns (no text block ever opened) and+ // reasoning that arrived after the text block was already streaming.+ flushThinking();for (const call of completedCalls) {const idx = nextIndex++;diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 848c080d..a956efc0 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -540,9 +540,9 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {INSERT INTO models(platform, model_id, display_name, intelligence_rank, speed_rank, size_label,rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window, enabled, key_id,- supports_tools, supports_vision)+ supports_tools, supports_vision, source)VALUES ('custom', @modelId, @displayName, 50, 50, 'Custom', NULL, NULL, NULL, NULL, '', NULL, 1, @keyId,- COALESCE(@tools, 1), COALESCE(@vision, 0))+ COALESCE(@tools, 1), COALESCE(@vision, 0), 'user')ON CONFLICT(platform, model_id)DO UPDATE SETdisplay_name = excluded.display_name,diff --git a/server/src/routes/models.ts b/server/src/routes/models.tsindex 57ff4a3f..d21ac5fc 100644--- a/server/src/routes/models.ts+++ b/server/src/routes/models.ts@@ -52,6 +52,7 @@ type ModelRow = {platform: string;model_id: string;key_id: number | null;+ source: string;};function dbValue(key: keyof typeof MODEL_FIELD_COLUMNS, value: unknown): unknown {@@ -61,7 +62,7 @@ function dbValue(key: keyof typeof MODEL_FIELD_COLUMNS, value: unknown): unknownfunction fetchModelRow(id: number): ModelRow | undefined {return getDb()- .prepare('SELECT id, platform, model_id, key_id FROM models WHERE id = ?')+ .prepare('SELECT id, platform, model_id, key_id, source FROM models WHERE id = ?').get(id) as ModelRow | undefined;}@@ -240,7 +241,11 @@ modelsRouter.get('/', (_req: Request, res: Response) => {supportsTools: m.supports_tools === 1,priority: m.priority,fallbackEnabled: m.fallback_enabled === 1,- source: m.platform === 'custom' || m.key_id != null ? 'custom' : 'catalog',+ // Real provenance from models.source ('catalog' | 'user'). The dashboard's+ // existing vocabulary for user-added rows is 'custom', so map 1:1 here —+ // this now also flags user models on native platforms (declarative+ // config / admin adds), which the old platform/key_id heuristic missed.+ source: m.source === 'user' ? 'custom' : 'catalog',keyId: m.key_id ?? null,keyLabel: m.key_label ?? null,hasOverrides: Boolean(m.has_overrides),diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 9f839b6a..e3f21b6e 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -6,7 +6,8 @@ import type { ChatMessage, ChatToolCall, ModelListRow } from '@freellmapi/sharedimport { routeRequest, resolveRoutingChain, resolveModelGroupCandidates, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, hasOtherUsableKey, routingReserveTokens, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS, MODEL_FORBIDDEN_COOLDOWN_MS, learnLimitFromError } from '../services/ratelimit.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';-import { runImageGeneration, runSpeech, MediaError } from '../services/media.js';+import { runImageGeneration, runSpeech, runTranscription, MediaError, MAX_TRANSCRIPTION_BYTES } from '../services/media.js';+import multer from 'multer';import { getDb, getUnifiedApiKey } from '../db/index.js';import { contentToString, messageHasImage, normalizeOutboundContent, sanitizeResponse } from '../lib/content.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';@@ -501,7 +502,7 @@ const ImageBody = z.object({});function mediaErrorType(status: number): string {- if (status === 400) return 'invalid_request_error';+ if (status === 400 || status === 413) return 'invalid_request_error';if (status === 401) return 'authentication_error';if (status === 429) return 'rate_limit_error';return 'server_error';@@ -571,6 +572,133 @@ proxyRouter.post('/audio/speech', async (req: Request, res: Response) => {}});+// OpenAI-compatible speech-to-text (/v1/audio/transcriptions). Multipart form+// upload, held in memory only (multer memoryStorage — audio bytes never touch+// disk), routed through the STT provider chain in services/media.ts with the+// same key/failover/cooldown machinery as the other media endpoints. The STT+// registry (media_models, modality='transcription') is maintained by the+// published catalog's `transcriptionModels` array via catalog-sync; on an+// install that has never synced one, the endpoint answers 503 with code+// 'no_transcription_models' until the first sync lands.+//+// response_format: 'json' (default, {"text": ...}), 'text' (plain string),+// 'verbose_json' (OpenAI verbose shape when the provider returns segments,+// graceful fallback to the plain json shape otherwise), 'vtt' (only from+// providers that produce it natively — Cloudflare whisper). 'srt' is not+// produced natively by any configured provider and is refused with 400+// unsupported_format rather than synthesized.+const transcriptionUpload = multer({+ storage: multer.memoryStorage(),+ limits: { fileSize: MAX_TRANSCRIPTION_BYTES, files: 1 },+});++const TRANSCRIPTION_FORMATS = new Set(['json', 'text', 'verbose_json', 'srt', 'vtt']);++function transcriptionBadRequest(res: Response, message: string, code?: string): void {+ res.status(400).json({ error: { message, type: 'invalid_request_error', ...(code ? { code } : {}) } });+}++proxyRouter.post('/audio/transcriptions', (req: Request, res: Response, next) => {+ // Auth before the multipart body is parsed: an unauthenticated caller's+ // upload is never buffered.+ const token = extractApiToken(req);+ const unifiedKey = getUnifiedApiKey();+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {+ res.status(401).json({ error: { message: 'Invalid API key', type: 'authentication_error' } });+ return;+ }+ transcriptionUpload.single('file')(req, res, (err: unknown) => {+ if (err) {+ if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {+ res.status(413).json({+ error: {+ message: `Audio file too large: the maximum upload size is ${MAX_TRANSCRIPTION_BYTES / (1024 * 1024)} MB.`,+ type: 'invalid_request_error',+ code: 'file_too_large',+ },+ });+ return;+ }+ transcriptionBadRequest(res, 'Malformed multipart/form-data upload.');+ return;+ }+ next();+ });+}, async (req: Request, res: Response) => {+ const file = req.file;+ if (!file || !file.buffer?.length) {+ transcriptionBadRequest(res, 'Invalid request: `file` is required (multipart/form-data audio upload).');+ return;+ }+ const model = typeof req.body?.model === 'string' ? req.body.model.trim() : '';+ if (!model) {+ transcriptionBadRequest(res, "Invalid request: `model` is required (use 'whisper-1' or 'auto' to let the router decide).");+ return;+ }+ const rawFormat = typeof req.body?.response_format === 'string' ? req.body.response_format.trim() : '';+ const responseFormat = rawFormat || 'json';+ if (!TRANSCRIPTION_FORMATS.has(responseFormat)) {+ transcriptionBadRequest(res, `Invalid response_format '${responseFormat}'. Supported: json, text, verbose_json, vtt.`);+ return;+ }+ if (responseFormat === 'srt') {+ transcriptionBadRequest(+ res,+ "response_format 'srt' is not supported: no configured provider produces srt natively. Use json, text, verbose_json, or vtt.",+ 'unsupported_format',+ );+ return;+ }+ let temperature: number | undefined;+ if (req.body?.temperature !== undefined && req.body.temperature !== '') {+ temperature = Number(req.body.temperature);+ if (!Number.isFinite(temperature) || temperature < 0 || temperature > 1) {+ transcriptionBadRequest(res, 'Invalid temperature: must be a number between 0 and 1.');+ return;+ }+ }+ const language = typeof req.body?.language === 'string' && req.body.language.trim() ? req.body.language.trim() : undefined;+ const prompt = typeof req.body?.prompt === 'string' && req.body.prompt ? req.body.prompt : undefined;++ try {+ const result = await runTranscription(model, {+ file: file.buffer,+ filename: file.originalname || 'audio',+ mimeType: file.mimetype,+ language,+ prompt,+ temperature,+ responseFormat,+ });+ res.setHeader('X-Provider', result.platform);+ res.setHeader('X-Model', result.modelId);+ if (responseFormat === 'text') {+ res.type('text/plain').send(result.text);+ return;+ }+ if (responseFormat === 'vtt') {+ res.type('text/vtt').send(result.vtt ?? '');+ return;+ }+ if (responseFormat === 'verbose_json' && Array.isArray(result.segments) && result.segments.length > 0) {+ res.json({+ task: 'transcribe',+ language: result.language ?? null,+ duration: result.duration ?? null,+ text: result.text,+ segments: result.segments,+ });+ return;+ }+ res.json({ text: result.text });+ } catch (err: any) {+ const status = err instanceof MediaError ? err.status : 502;+ const httpStatus = status >= 400 && status < 600 ? status : 502;+ const code = err instanceof MediaError && err.code ? { code: err.code } : {};+ res.status(httpStatus).json({ error: { message: `transcription error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status), ...code } });+ }+});+const CompletionBody = z.object({model: z.string().optional(),prompt: z.string(),@@ -1349,6 +1477,9 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {logit_bias: req.body?.logit_bias ?? undefined,logprobs: req.body?.logprobs ?? undefined,top_logprobs: req.body?.top_logprobs ?? undefined,+ // Normalized reasoning knob (flat field or object form) — a different+ // effort asks for a different answer, so it must never collide.+ reasoning_effort: samplingParams.reasoning_effort ?? undefined,}): null;if (cacheKey) {diff --git a/server/src/services/cache.ts b/server/src/services/cache.tsindex 78e175b5..20daf106 100644--- a/server/src/services/cache.ts+++ b/server/src/services/cache.ts@@ -167,6 +167,7 @@ export interface CacheKeyInput {logit_bias?: unknown;logprobs?: unknown;top_logprobs?: unknown;+ reasoning_effort?: unknown;}function normModel(model: string | undefined): string {@@ -198,6 +199,9 @@ export function computeCacheKey(input: CacheKeyInput): string {logit_bias: input.logit_bias,logprobs: input.logprobs,top_logprobs: input.top_logprobs,+ // Absent for requests without the knob (stableStringify drops undefined),+ // so pre-existing cache keys are unaffected.+ reasoning_effort: input.reasoning_effort,});return crypto.createHash('sha256').update(canonical).digest('hex');}diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.tsindex ad38475e..62eed362 100644--- a/server/src/services/catalog-sync.ts+++ b/server/src/services/catalog-sync.ts@@ -2,7 +2,7 @@ import crypto from 'crypto';import type { Db } from '../db/types.js';import { getDb, getSetting, setSetting } from '../db/index.js';import { hasProvider } from '../providers/index.js';-import { MEDIA_PLATFORMS } from './media.js';+import { MEDIA_PLATFORMS, TRANSCRIPTION_PLATFORMS } from './media.js';import { EMBEDDING_PLATFORMS } from './embeddings.js';import type { Platform } from '@freellmapi/shared/types.js';import type { Scheduler } from '../lib/scheduler.js';@@ -121,6 +121,24 @@ interface CatalogEmbedding {quotaLabel: string;}+interface CatalogTranscriptionModel {+ platform: string;+ modelId: string;+ displayName: string;+ /** Failover order within the STT chain, lower first. */+ priority: number;+ enabled: boolean;+ /** Subtitle formats the provider returns natively (e.g. ['vtt']). */+ subtitleFormats?: string[];+ /** Provider upload ceiling in bytes; absent = the route-wide 25 MB cap. */+ maxBytes?: number | null;+ /** Adapter request flavor where one platform hosts more than one deployment+ * style (cloudflare: 'json' = base64 JSON body, 'binary' = raw bytes). */+ requestStyle?: string | null;+ /** Short display note, mirrored into media_models.quota_label. */+ quotaLabel?: string;+}+interface Catalog {version: string;generatedAt: string;@@ -129,6 +147,12 @@ interface Catalog {/** Optional for backward compatibility with catalogs published before the* embedding registry joined the signed freshness feed. */embeddings?: CatalogEmbedding[];+ /** Speech-to-text registry, landing in media_models with+ * modality='transcription'. Deliberately a NEW top-level key rather than+ * more `models` entries: deployed binaries that predate the transcription+ * modality would ingest unknown-modality `models` entries as CHAT models,+ * while an unknown optional key is simply ignored by their isCatalog. */+ transcriptionModels?: CatalogTranscriptionModel[];quirks: CatalogQuirk[];}@@ -162,6 +186,20 @@ function isCatalog(value: unknown): value is Catalog {typeof m?.priority === 'number' &&typeof m?.enabled === 'boolean',))) &&+ (c.transcriptionModels === undefined ||+ (Array.isArray(c.transcriptionModels) &&+ c.transcriptionModels.every(+ (m) =>+ typeof m?.platform === 'string' &&+ typeof m?.modelId === 'string' &&+ typeof m?.displayName === 'string' &&+ typeof m?.priority === 'number' &&+ typeof m?.enabled === 'boolean' &&+ (m.subtitleFormats === undefined ||+ (Array.isArray(m.subtitleFormats) && m.subtitleFormats.every((f) => typeof f === 'string'))) &&+ (m.maxBytes === undefined || m.maxBytes === null || typeof m.maxBytes === 'number') &&+ (m.requestStyle === undefined || m.requestStyle === null || typeof m.requestStyle === 'string'),+ ))) &&c.models.every((m) =>typeof m?.platform === 'string' &&@@ -188,8 +226,10 @@ function routableContextWindow(platform: string, modelId: string, contextWindow:* unless the user has an explicit local override;* - catalog enabled=false force-disables (the model is dead upstream), but* enabled=true never re-enables a model the user turned off themselves;- * - models the user added via custom providers (platform='custom' or bound to- * a key) are never touched;+ * - rows the user created (models.source = 'user': custom providers,+ * declarative config, admin adds) are never updated, never deleted, and+ * never adopted — on a platform:model_id collision the user row wins and+ * the catalog entry is skipped outright;* - catalog models the user deleted stay deleted via tombstones;* - models that vanished from the catalog are deleted, exactly like the* dead-model migrations do (fallback_config row first, FK order).@@ -197,7 +237,7 @@ function routableContextWindow(platform: string, modelId: string, contextWindow:export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['counts']> {const counts = { updated: 0, inserted: 0, removed: 0, skippedUnknownPlatform: 0, quirks: 0 };- const selectModel = db.prepare('SELECT id, enabled FROM models WHERE platform = ? AND model_id = ?');+ const selectModel = db.prepare('SELECT id, enabled, source FROM models WHERE platform = ? AND model_id = ?');const updateModel = db.prepare(`UPDATE models SETdisplay_name = @displayName, intelligence_rank = @intelligenceRank, speed_rank = @speedRank,@@ -210,10 +250,10 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['const insertModel = db.prepare(`INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label,rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window,- enabled, supports_vision, supports_tools)+ enabled, supports_vision, supports_tools, source)VALUES (@platform, @modelId, @displayName, @intelligenceRank, @speedRank, @sizeLabel,@rpm, @rpd, @tpm, @tpd, @monthlyTokenBudget, @contextWindow,- @enabled, @supportsVision, @supportsTools)+ @enabled, @supportsVision, @supportsTools, 'catalog')`);// Generative-media models go to their own table (never the chat router's pool).@@ -228,6 +268,18 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)VALUES (@platform, @modelId, @displayName, @modality, @priority, @enabled, @quotaLabel)`);+ // Transcription rows share media_models but carry adapter metadata in+ // meta_json (subtitle capability, upload ceiling, request flavor).+ const updateTranscription = db.prepare(`+ UPDATE media_models SET+ display_name = @displayName, modality = 'transcription', priority = @priority,+ quota_label = @quotaLabel, enabled = @enabled, meta_json = @metaJson+ WHERE id = @id+ `);+ const insertTranscription = db.prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES (@platform, @modelId, @displayName, 'transcription', @priority, @enabled, @quotaLabel, @metaJson)+ `);const selectEmbedding = db.prepare('SELECT id, enabled FROM embedding_models WHERE platform = ? AND model_id = ?',);@@ -251,6 +303,7 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['const inCatalog = new Set<string>();const inMediaCatalog = new Set<string>();const inEmbeddingCatalog = new Set<string>();+ const inTranscriptionCatalog = new Set<string>();for (const m of catalog.models) {// Media modalities are gated on MEDIA_PLATFORMS (decoupled from the chat@@ -290,7 +343,15 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['if (isCatalogModelTombstoned(db, 'chat', m.platform, m.modelId)) continue;inCatalog.add(`${m.platform}:${m.modelId}`);- const row = selectModel.get(m.platform, m.modelId) as { id: number; enabled: number } | undefined;+ const row = selectModel.get(m.platform, m.modelId) as+ | { id: number; enabled: number; source: string }+ | undefined;+ // Collision rule: if the user hand-added a model and the catalog later+ // ships the same platform:model_id, the user row wins — the catalog+ // neither clobbers its metadata nor adopts it (same spirit as the+ // never-touch rule for custom-provider models). The row also survives+ // the prune below because the delete pass only considers source='catalog'.+ if (row && row.source === 'user') continue;const fields = {displayName: m.displayName,intelligenceRank: m.intelligenceRank,@@ -352,6 +413,40 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['}}+ // Transcription models are their own full snapshot, routed into+ // media_models with modality='transcription' and gated on+ // TRANSCRIPTION_PLATFORMS the way MEDIA_PLATFORMS gates the generative+ // rows. Older catalogs omit this key; keep existing rows untouched then.+ if (catalog.transcriptionModels) {+ for (const m of catalog.transcriptionModels) {+ if (!TRANSCRIPTION_PLATFORMS.has(m.platform)) {+ counts.skippedUnknownPlatform++;+ continue;+ }+ if (isCatalogModelTombstoned(db, 'media', m.platform, m.modelId)) continue;+ inTranscriptionCatalog.add(`${m.platform}:${m.modelId}`);+ const meta: Record<string, unknown> = {};+ if (m.subtitleFormats?.length) meta.subtitleFormats = m.subtitleFormats;+ if (typeof m.maxBytes === 'number') meta.maxBytes = m.maxBytes;+ if (typeof m.requestStyle === 'string') meta.requestStyle = m.requestStyle;+ const fields = {+ displayName: m.displayName,+ priority: m.priority,+ quotaLabel: m.quotaLabel ?? '',+ metaJson: Object.keys(meta).length > 0 ? JSON.stringify(meta) : null,+ };+ const row = selectMedia.get(m.platform, m.modelId) as { id: number; enabled: number } | undefined;+ if (row) {+ const enabled = m.enabled ? row.enabled : 0; // catalog and local disables both win+ updateTranscription.run({ ...fields, id: row.id, enabled });+ counts.updated++;+ } else {+ insertTranscription.run({ ...fields, platform: m.platform, modelId: m.modelId, enabled: m.enabled ? 1 : 0 });+ counts.inserted++;+ }+ }+ }+counts.removed += deleteTombstonedCatalogModels(db);applyAllModelOverrides(db);@@ -369,13 +464,20 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['ensureAllModelsInProfiles(db);// Remove catalog-managed models that the catalog no longer lists.+ // Ownership is decided by the `source` provenance column: only rows the+ // catalog itself created are prune candidates. Rows with source='user'+ // (declarative config, admin adds, custom endpoints) are never deleted+ // here, no matter what their size_label or platform says — that replaces+ // the old size_label NOT IN ('User','Custom') heuristic, which lost user+ // rows whose label didn't follow the convention. The platform/key_id+ // predicates stay as belt and braces.const candidates = db.prepare(`SELECT id, platform, model_idFROM modelsWHERE platform != 'custom'AND key_id IS NULL- AND size_label NOT IN ('User', 'Custom')+ AND source = 'catalog'`).all() as { id: number; platform: string; model_id: string }[];const deleteFb = db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?');@@ -389,9 +491,12 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['}}- // Remove media models the catalog no longer lists (own table, no fallback_config).+ // Remove media models the catalog no longer lists (own table, no+ // fallback_config). Scoped to the generative modalities: transcription+ // rows are maintained by the `transcriptionModels` snapshot below, and+ // must survive here even when its key is absent from an older catalog.const mediaCandidates = db- .prepare('SELECT id, platform, model_id FROM media_models')+ .prepare("SELECT id, platform, model_id FROM media_models WHERE modality != 'transcription'").all() as { id: number; platform: string; model_id: string }[];const deleteMedia = db.prepare('DELETE FROM media_models WHERE id = ?');for (const c of mediaCandidates) {@@ -402,6 +507,22 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['}}+ // Prune transcription rows only when the catalog actually carries the+ // snapshot (mirrors the embeddings rule), scoped to the modality so+ // image/audio rows are never touched by it.+ if (catalog.transcriptionModels) {+ const sttCandidates = db+ .prepare("SELECT id, platform, model_id FROM media_models WHERE modality = 'transcription'")+ .all() as { id: number; platform: string; model_id: string }[];+ for (const c of sttCandidates) {+ if (!TRANSCRIPTION_PLATFORMS.has(c.platform)) continue;+ if (!inTranscriptionCatalog.has(`${c.platform}:${c.model_id}`)) {+ deleteMedia.run(c.id);+ counts.removed++;+ }+ }+ }+if (catalog.embeddings) {const embeddingCandidates = db.prepare(`diff --git a/server/src/services/declarative-config.ts b/server/src/services/declarative-config.tsindex 3ea3743a..2a082810 100644--- a/server/src/services/declarative-config.ts+++ b/server/src/services/declarative-config.ts@@ -211,8 +211,8 @@ function registerCustomProvider(db: Db, input: z.infer<typeof customProviderScheINSERT INTO models(platform, model_id, display_name, intelligence_rank, speed_rank, size_label,rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window,- enabled, supports_vision, supports_tools, key_id)- VALUES ('custom', ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, ?, ?, 1, ?, ?, ?)+ enabled, supports_vision, supports_tools, key_id, source)+ VALUES ('custom', ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, ?, ?, 1, ?, ?, ?, 'user')ON CONFLICT(platform, model_id)DO UPDATE SETdisplay_name = excluded.display_name,@@ -260,16 +260,20 @@ function upsertModel(db: Db, input: z.infer<typeof modelSchema>): void {const platform = input.platform.trim();const modelId = input.modelId.trim();clearCatalogModelTombstone(db, 'chat', platform, modelId);- const existing = db.prepare('SELECT id, platform, model_id, key_id FROM models WHERE platform = ? AND model_id = ?')- .get(platform, modelId) as { id: number; platform: string; model_id: string; key_id: number | null } | undefined;+ const existing = db.prepare('SELECT id, platform, model_id, key_id, source FROM models WHERE platform = ? AND model_id = ?')+ .get(platform, modelId) as { id: number; platform: string; model_id: string; key_id: number | null; source: string } | undefined;if (!existing) {+ // A declaratively-created model is user-owned: catalog sync must never+ // update or prune it (see applyCatalog). Patching an EXISTING catalog row+ // below does NOT flip ownership — the row's existence is still catalog-+ // managed and the edit is recorded as an override instead.db.prepare(`INSERT INTO models(platform, model_id, display_name, intelligence_rank, speed_rank, size_label,rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window,- enabled, supports_vision, supports_tools)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ enabled, supports_vision, supports_tools, source)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'user')`).run(platform,modelId,diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex bcaa7ded..da08cd43 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -11,6 +11,7 @@ import { getDb } from '../db/index.js';import { getClientContext } from '../lib/client-context.js';import { decrypt } from '../lib/crypto.js';import { proxyFetch } from '../lib/proxy.js';+import { isOnCooldown, setCooldown } from './ratelimit.js';/** Platforms with a media adapter below. catalog-sync gates media rows on this* (decoupled from the chat provider registry — e.g. SiliconFlow is media-only). */@@ -19,7 +20,17 @@ export const MEDIA_PLATFORMS = new Set(['nvidia', 'pollinations', 'cloudflare',/** Platforms whose free media path needs no API key (anonymous). */const KEYLESS_CAPABLE = new Set(['pollinations']);-export type MediaModality = 'image' | 'audio';+/** Platforms with a speech-to-text adapter below. catalog-sync gates the+ * catalog's `transcriptionModels` entries on this, the way MEDIA_PLATFORMS+ * gates the generative-media rows. */+export const TRANSCRIPTION_PLATFORMS = new Set(['groq', 'cloudflare']);++// 'transcription' rows live in media_models like the other modalities; they+// arrive via the catalog's dedicated `transcriptionModels` array (see+// catalog-sync), never via migrations. Their per-model adapter metadata+// (native subtitle formats, upload ceiling, request flavor) rides in the+// meta_json column — see TranscriptionMeta below.+export type MediaModality = 'image' | 'audio' | 'transcription';export interface MediaModelRow {id: number;@@ -31,13 +42,17 @@ export interface MediaModelRow {enabled: number;quota_label: string;key_id: number | null;+ meta_json: string | null;}export class MediaError extends Error {status: number;- constructor(message: string, status: number) {+ /** Optional machine-readable error code surfaced in the OpenAI-shaped body. */+ code?: string;+ constructor(message: string, status: number, code?: string) {super(message);this.status = status;+ this.code = code;}}@@ -167,7 +182,7 @@ interface ProviderCredential {baseUrl: string | null;}-function getProviderCredential(row: MediaModelRow): ProviderCredential | null {+function getProviderCredential(row: Pick<MediaModelRow, 'platform' | 'key_id'>): ProviderCredential | null {if (row.key_id != null) {const keyRow = getDb().prepare("SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys WHERE id = ? AND enabled = 1 AND status IN ('healthy', 'unknown') LIMIT 1")@@ -203,7 +218,7 @@ function getProviderCredential(row: MediaModelRow): ProviderCredential | null {async function mediaFetch(url: string,platform: string,- modality: 'image' | 'audio',+ modality: MediaModality,init: RequestInit,): Promise<Response> {const r = await proxyFetch(@@ -466,7 +481,7 @@ function resolveMediaChain(model: string | undefined, modality: MediaModality):return matches;}-function logMedia(row: MediaModelRow, keyId: number | null, status: 'success' | 'error', latencyMs: number, error: string | null): void {+function logMedia(row: Pick<MediaModelRow, 'platform' | 'model_id' | 'modality'>, keyId: number | null, status: 'success' | 'error', latencyMs: number, error: string | null): void {try {const client = getClientContext();getDb()@@ -511,6 +526,240 @@ export async function runImageGeneration(model: string | undefined, params: Imagthrow chainError('image', lastError);}+// ---------------------------------------------------------------------------+// Speech-to-text (/v1/audio/transcriptions)+//+// STT models live in media_models with modality='transcription', maintained+// by the published catalog's `transcriptionModels` array (see catalog-sync)+// — never hardcoded here, never seeded by migrations. The per-platform+// adapters below are pure transport; everything model-specific (native+// subtitle support, upload ceiling, request flavor) rides on the catalog+// entry and lands in the row's meta_json. On an install that has never+// synced a catalog listing transcription models, the endpoint returns an+// OpenAI-shaped 503 with code 'no_transcription_models' until the first+// sync lands. Key selection, failover, cooldowns, and request logging reuse+// the exact same machinery as the other media modalities above.++/** Per-model adapter metadata carried on the catalog entry (meta_json). */+export interface TranscriptionMeta {+ /** Subtitle formats the provider returns natively (e.g. ['vtt']). Formats+ * not produced natively by the chain are refused with 400 at the route. */+ subtitleFormats?: string[];+ /** Provider upload ceiling in bytes; absent = MAX_TRANSCRIPTION_BYTES. */+ maxBytes?: number | null;+ /** Adapter request flavor where one platform hosts more than one deployment+ * style. Cloudflare: 'json' = JSON body with base64 audio (large-v3-turbo),+ * 'binary' = raw bytes (plain whisper, the default). */+ requestStyle?: string | null;+}++/** Global upload ceiling enforced by the route (multer) so it can reject+ * early with a clean OpenAI-shaped 413 instead of buffering an upload no+ * provider can accept. Per-model catalog `maxBytes` may only lower this. */+export const MAX_TRANSCRIPTION_BYTES = 25 * 1024 * 1024;++/** A transcription candidate: a media_models row with its meta decoded. */+interface SttCandidate {+ platform: string;+ modelId: string;+ nativeSubtitles: Set<string>;+ maxBytes: number;+ requestStyle: string | null;+}++function parseTranscriptionMeta(raw: string | null): TranscriptionMeta {+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw) as TranscriptionMeta;+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++function toSttCandidate(row: MediaModelRow): SttCandidate {+ const meta = parseTranscriptionMeta(row.meta_json);+ const maxBytes =+ typeof meta.maxBytes === 'number' && meta.maxBytes > 0+ ? Math.min(meta.maxBytes, MAX_TRANSCRIPTION_BYTES)+ : MAX_TRANSCRIPTION_BYTES;+ return {+ platform: row.platform,+ modelId: row.model_id,+ nativeSubtitles: new Set(Array.isArray(meta.subtitleFormats) ? meta.subtitleFormats : []),+ maxBytes,+ requestStyle: typeof meta.requestStyle === 'string' ? meta.requestStyle : null,+ };+}++/** Model ids that mean "let the router decide". `whisper-1` is what stock+ * OpenAI clients send by default, so it must route rather than 400. */+const TRANSCRIPTION_AUTO_IDS = new Set(['auto', 'whisper-1']);++export interface TranscriptionParams {+ file: Buffer;+ filename: string;+ mimeType?: string;+ language?: string;+ prompt?: string;+ temperature?: number;+ /** 'json' | 'text' | 'verbose_json' | 'vtt' (srt is rejected at the route). */+ responseFormat: string;+}++export interface TranscriptionResult {+ platform: string;+ modelId: string;+ text: string;+ language?: string;+ duration?: number;+ segments?: unknown[];+ vtt?: string;+}++function resolveTranscriptionChain(model: string | undefined, responseFormat: string): SttCandidate[] {+ let chain = listMediaModels('transcription').map(toSttCandidate);+ if (chain.length === 0) {+ // Never-synced install (or the catalog retired every STT model): the+ // registry only ever arrives via catalog-sync, so tell the caller to wait+ // for / trigger a sync rather than pretending the model id is wrong.+ throw new MediaError(+ 'No transcription models are configured yet. The registry arrives via catalog sync; ' ++ 'wait for the next sync (or trigger one from the dashboard) and retry.',+ 503,+ 'no_transcription_models',+ );+ }+ if (model && !TRANSCRIPTION_AUTO_IDS.has(model.toLowerCase())) {+ chain = chain.filter(m => m.modelId === model);+ if (chain.length === 0) {+ throw new MediaError(+ `Unknown transcription model '${model}'. Use 'auto', 'whisper-1', or a provider model id.`,+ 400,+ );+ }+ }+ if (responseFormat === 'vtt') {+ chain = chain.filter(m => m.nativeSubtitles.has('vtt'));+ if (chain.length === 0) {+ throw new MediaError(+ "response_format 'vtt' is only served by providers that produce it natively; " ++ 'the requested model does not.',+ 400,+ );+ }+ }+ return chain;+}++async function callTranscriptionProvider(+ m: SttCandidate,+ credential: ProviderCredential,+ p: TranscriptionParams,+): Promise<Omit<TranscriptionResult, 'platform' | 'modelId'>> {+ const key = credential.key;+ switch (m.platform) {+ case 'groq': {+ // Groq's OpenAI-compatible audio endpoint takes multipart form data.+ // Never set Content-Type by hand — FormData supplies the boundary.+ const form = new FormData();+ form.append('file', new Blob([p.file], { type: p.mimeType || 'application/octet-stream' }), p.filename);+ form.append('model', m.modelId);+ if (p.language) form.append('language', p.language);+ if (p.prompt) form.append('prompt', p.prompt);+ if (p.temperature !== undefined) form.append('temperature', String(p.temperature));+ // Groq supports json/verbose_json/text natively; text is derived locally+ // from the json shape so failover output stays uniform.+ form.append('response_format', p.responseFormat === 'verbose_json' ? 'verbose_json' : 'json');+ const r = await mediaFetch('https://api.groq.com/openai/v1/audio/transcriptions', 'groq', 'transcription', {+ method: 'POST',+ headers: { Authorization: `Bearer ${key}` },+ body: form,+ });+ const j = (await r.json()) as { text?: string; language?: string; duration?: number; segments?: unknown[] };+ if (typeof j.text !== 'string') throw new MediaError('groq returned no transcription text', 502);+ return { text: j.text, language: j.language, duration: j.duration, segments: j.segments };+ }+ case 'cloudflare': {+ const { accountId, token } = parseCfKey(key);+ const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${m.modelId}`;+ const init: RequestInit = m.requestStyle === 'json'+ ? {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({+ audio: p.file.toString('base64'),+ ...(p.language ? { language: p.language } : {}),+ ...(p.prompt ? { initial_prompt: p.prompt } : {}),+ }),+ }+ : {+ method: 'POST',+ headers: { 'Content-Type': 'application/octet-stream', Authorization: `Bearer ${token}` },+ body: p.file,+ };+ const r = await mediaFetch(url, 'cloudflare', 'transcription', init);+ const j = (await r.json()) as {+ result?: {+ text?: string;+ vtt?: string;+ segments?: unknown[];+ transcription_info?: { language?: string; duration?: number };+ };+ };+ const result = j.result;+ if (!result || typeof result.text !== 'string') {+ throw new MediaError('cloudflare returned no transcription text', 502);+ }+ return {+ text: result.text,+ language: result.transcription_info?.language,+ duration: result.transcription_info?.duration,+ segments: result.segments,+ vtt: typeof result.vtt === 'string' ? result.vtt : undefined,+ };+ }+ default:+ throw new MediaError(`no transcription adapter for platform '${m.platform}'`, 500);+ }+}++/** Transcribe audio, failing over across STT providers. 429s bench the+ * (platform, model, key) triple through the standard cooldown machinery so a+ * rate-limited key is skipped on subsequent requests, exactly like chat. */+export async function runTranscription(model: string | undefined, p: TranscriptionParams): Promise<TranscriptionResult> {+ const chain = resolveTranscriptionChain(model, p.responseFormat);+ const usable = chain.filter(m => p.file.length <= m.maxBytes);+ if (usable.length === 0) {+ const maxMb = Math.max(...chain.map(m => m.maxBytes)) / (1024 * 1024);+ throw new MediaError(`Audio file exceeds the ${maxMb} MB provider upload limit.`, 413);+ }+ let lastError: MediaError | null = null;+ for (const m of usable) {+ const credential = getProviderCredential({ platform: m.platform, key_id: null });+ if (!credential) continue; // no usable key for this provider — try the next+ if (credential.id != null && isOnCooldown(m.platform, m.modelId, credential.id)) continue;+ const logRow = { platform: m.platform, model_id: m.modelId, modality: 'transcription' as const };+ const started = Date.now();+ try {+ const out = await callTranscriptionProvider(m, credential, p);+ if (p.responseFormat === 'vtt' && !out.vtt) {+ throw new MediaError('upstream returned no vtt subtitles', 502);+ }+ logMedia(logRow, credential.id, 'success', Date.now() - started, null);+ return { platform: m.platform, modelId: m.modelId, ...out };+ } catch (err: any) {+ const e = err instanceof MediaError ? err : new MediaError(String(err?.message ?? err), 502);+ logMedia(logRow, credential.id, 'error', Date.now() - started, e.message.slice(0, 300));+ if (e.status === 429 && credential.id != null) {+ setCooldown(m.platform, m.modelId, credential.id);+ }+ lastError = e;+ }+ }+ throw chainError('transcription', lastError);+}+/** Synthesize speech, failing over across providers serving the modality. */export async function runSpeech(model: string | undefined, params: SpeechParams): Promise<SpeechResult> {const chain = resolveMediaChain(model, 'audio');diff --git a/server/src/services/model-state.ts b/server/src/services/model-state.tsindex 801d398f..cef802d9 100644--- a/server/src/services/model-state.ts+++ b/server/src/services/model-state.ts@@ -61,7 +61,11 @@ function cleanPatch(patch: ModelOverridePatch): StoredOverrides {return cleaned;}-export function isCatalogManagedModel(row: { platform: string; key_id?: number | null }): boolean {+export function isCatalogManagedModel(row: { platform: string; key_id?: number | null; source?: string }): boolean {+ // `source` is the authoritative provenance (models.source, 'catalog'|'user');+ // callers that select it get an exact answer. The platform/key_id fallback+ // covers callers that don't have the column in hand.+ if (row.source === 'user') return false;return row.platform !== 'custom' && row.key_id == null;}@@ -169,7 +173,7 @@ export function deleteTombstonedCatalogModels(db: Db): number {FROM models mJOIN catalog_model_tombstones tON t.kind = 'chat' AND t.platform = m.platform AND t.model_id = m.model_id- WHERE m.platform != 'custom' AND m.key_id IS NULL+ WHERE m.platform != 'custom' AND m.key_id IS NULL AND m.source != 'user'`).all() as { id: number; platform: string; model_id: string }[];const mediaRows = db.prepare(`SELECT mm.id