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
Issue batch 2: per-key scoring + honest group display, first-byte stream grace, Gemma tools passthrough, toast timing (#605)
Tashfeen99076fc6566f
diff --git a/.env.example b/.env.exampleindex d6a5028b..2a7626ca 100644--- a/.env.example+++ b/.env.example@@ -41,19 +41,30 @@ PORT=3001# Per-provider chat HTTP timeout in milliseconds, named# PROVIDER_TIMEOUT_<PLATFORM> (platform name upper-cased). Overrides the# built-in default for that provider (60s for most OpenAI-compatible platforms,-# 90s NVIDIA, 120s Ollama Cloud / AI Horde / custom providers, 60s Google as-# registered). Set to 0 to disable the timeout entirely. Read at startup.-# Example — give NVIDIA NIM's slow reasoning models 5 minutes:+# 180s NVIDIA, 120s Ollama Cloud / AI Horde / custom providers, 60s Google as+# registered). On streaming requests this value also serves as the FIRST-BYTE+# grace budget: how long the stream may stay silent before its first byte+# (issue #584 — providers like NVIDIA NIM send SSE headers instantly, then+# prefill long prompts for minutes). Set to 0 to disable the timeout entirely.+# Read at startup. Example — give NVIDIA NIM's slow reasoning models 5 minutes:# PROVIDER_TIMEOUT_NVIDIA=300000# Mid-stream inactivity timeout for streaming responses, in milliseconds-# (default: 90000). If an SSE stream goes this long without a single byte, the-# gateway gives up on it (before any output reached the client this fails over-# to the next candidate; after output was sent the stream ends with an error-# frame). Providers that queue heavily on their free tiers can pause longer-# than 90s mid-stream — raise this if streamed responses stop early. Set to 0-# to disable the stall watchdog entirely.+# (default: 90000). If an SSE stream goes this long without a single byte+# AFTER the first byte arrived, the gateway gives up on it (before any output+# reached the client this fails over to the next candidate; after output was+# sent the stream ends with an error frame). Time-to-FIRST-byte is governed by+# the chat timeout above instead (whichever of the two is larger). Providers+# that queue heavily on their free tiers can pause longer than 90s mid-stream —+# raise this if streamed responses stop early. Set to 0 to disable the stall+# watchdog entirely.# PROVIDER_STREAM_STALL_TIMEOUT_MS=90000+#+# Per-provider variant, named PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>+# (platform name upper-cased). Precedence: per-platform > global (above) >+# built-in 90s default. Example — let Ollama Cloud pause 4 minutes mid-stream+# without loosening the watchdog everywhere else:+# PROVIDER_STREAM_STALL_TIMEOUT_OLLAMA=240000# Wall-clock budget for provider failover, in milliseconds (default: 45000).# A request that keeps failing over stops STARTING new attempts once this muchdiff --git a/README.md b/README.mdindex 5e758d0a..74f60936 100644--- a/README.md+++ b/README.md@@ -908,6 +908,9 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full migration CLI and workflow<a href="https://github.com/Arman-Espiar"><img src="https://images.weserv.nl/?url=github.com/Arman-Espiar.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@Arman-Espiar" /></a><a href="https://github.com/MetaMysteries8"><img src="https://images.weserv.nl/?url=github.com/MetaMysteries8.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@MetaMysteries8" /></a><a href="https://github.com/lujun880726"><img src="https://images.weserv.nl/?url=github.com/lujun880726.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@lujun880726" /></a>+<a href="https://github.com/qq97693453"><img src="https://images.weserv.nl/?url=github.com/qq97693453.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@qq97693453" /></a>+<a href="https://github.com/emv33"><img src="https://images.weserv.nl/?url=github.com/emv33.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@emv33" /></a>+<a href="https://github.com/ousamabenyounes"><img src="https://images.weserv.nl/?url=github.com/ousamabenyounes.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@ousamabenyounes" /></a>## Terms of Service reviewdiff --git a/client/package.json b/client/package.jsonindex 6bf5272c..d84c4b84 100644--- a/client/package.json+++ b/client/package.json@@ -7,7 +7,8 @@"dev": "vite","build": "tsc -b && vite build","lint": "eslint .",- "preview": "vite preview"+ "preview": "vite preview",+ "test": "vitest run"},"dependencies": {"@base-ui/react": "^1.3.0",@@ -44,7 +45,8 @@"globals": "^17.4.0","typescript": "~6.0.2","typescript-eslint": "^8.58.0",- "vite": "^8.0.4"+ "vite": "^8.0.4",+ "vitest": "^3.1.3"},"engines": {"node": ">=20.18.0 <25.0.0",diff --git a/client/src/components/model-table.tsx b/client/src/components/model-table.tsxindex 144a78e8..00cb5649 100644--- a/client/src/components/model-table.tsx+++ b/client/src/components/model-table.tsx@@ -34,6 +34,55 @@ export function AxisBar({ value, color }: { value: number | undefined; color: st)}+// The honest replacement for prior-valued bars (#580): a measured axis value+// only exists once a provider has served requests. Before that the bandit uses+// exploration priors (0.5 reliability / 0.6 speed) — rendering those as bars+// reads as a real, suspiciously identical measurement, so unmeasured providers+// get this explicit placeholder instead.+export function AxisNoData() {+ const { t } = useI18n()+ return (+ <Tooltip text={t('models.noDataTitle')}>+ <div className="flex items-center gap-1.5 cursor-help">+ <div className="h-1.5 w-12 rounded-full border border-dashed border-muted-foreground/30" />+ <span className="text-[10px] text-muted-foreground/60 whitespace-nowrap">{t('models.noData')}</span>+ </div>+ </Tooltip>+ )+}++// The min–max of the defined values, or null when none are defined.+function rangeOf(values: (number | undefined)[]): { min: number; max: number } | null {+ const nums = values.filter((v): v is number => v !== undefined)+ if (nums.length === 0) return null+ return { min: Math.min(...nums), max: Math.max(...nums) }+}++// A group's axis as a min–max band across its providers, collapsing to the+// plain single-value bar when the providers agree (or there is only one).+// Groups show the true spread instead of silently promoting the best member's+// number to the whole group (#580).+function AxisRangeBar({ values, color }: { values: (number | undefined)[]; color: string }) {+ const range = rangeOf(values)+ if (range === null) return <AxisBar value={undefined} color={color} />+ const lo = Math.round(range.min * 100)+ const hi = Math.round(range.max * 100)+ if (lo === hi) return <AxisBar value={range.max} color={color} />+ return (+ <div className="flex items-center gap-1.5">+ <div className="relative h-1.5 w-12 rounded-full bg-muted overflow-hidden">+ <div+ className="absolute inset-y-0 rounded-full"+ style={{ left: `${lo}%`, width: `${Math.max(4, hi - lo)}%`, backgroundColor: color }}+ />+ </div>+ <span className="font-mono text-[11px] text-muted-foreground tabular-nums min-w-7 text-right whitespace-nowrap">+ {lo}–{hi}+ </span>+ </div>+ )+}+// The shared table header for the unified model/provider table — used by the// Models page and the per-model detail page so their columns line up.export function ModelTableHead() {@@ -128,8 +177,12 @@ export function RowContent({].filter(Boolean).join(' · ') || cleanQuotaLabel(row.monthlyTokenBudget) || '—'}</div></td>- <td className="py-2 pr-3 align-middle"><AxisBar value={row.reliability} color="#22c55e" /></td>- <td className="py-2 pr-3 align-middle"><AxisBar value={row.speed} color="#3b82f6" /></td>+ {/* Reliability/speed are measured axes: with zero recorded requests the+ scorer only has its exploration priors, so show an explicit "no data"+ state instead of prior-valued bars (#580). Intelligence is catalog+ metadata and stays. */}+ <td className="py-2 pr-3 align-middle">{row.totalRequests === 0 ? <AxisNoData /> : <AxisBar value={row.reliability} color="#22c55e" />}</td>+ <td className="py-2 pr-3 align-middle">{row.totalRequests === 0 ? <AxisNoData /> : <AxisBar value={row.speed} color="#3b82f6" />}</td><td className="py-2 pr-3 align-middle"><AxisBar value={row.intelligence} color="#a855f7" /></td><td className="py-2 pr-3 align-middle font-mono text-[11px] text-muted-foreground tabular-nums">{guard < 0.999 ? `×${guard.toFixed(2)}` : '—'}@@ -168,6 +221,16 @@ export function GroupHeaderCells({ group, rank, dragHandle, onToggleGroup }: {const solo = group.members.length === 1const best = group.members.reduce((b, m) => ((m.score ?? -1) > (b.score ?? -1) ? m : b), group.members[0])const guard = (best.headroom ?? 1) * (best.rateLimit ?? 1)+ // Honest group display (#580): reliability/speed ranges come only from+ // members that were actually measured; when none were, show "no data" rather+ // than the shared exploration priors. Intelligence is catalog metadata, so+ // its range spans every member. The score cell keeps the best member's score+ // (that is what routing would pick) but labels it "best of N" with the+ // per-provider breakdown in a tooltip.+ const measured = group.members.filter(m => (m.totalRequests ?? 0) > 0)+ const scoreBreakdown = group.members+ .map(m => `${providerLabel(m)} ${m.score !== undefined ? m.score.toFixed(3) : '–'}`)+ .join(' · ')const vision = group.members.some(m => m.supportsVision)const tools = group.members.some(m => m.supportsTools)const quota = groupQuotaBadge(group.members, t)@@ -218,11 +281,22 @@ export function GroupHeaderCells({ group, rank, dragHandle, onToggleGroup }: {</span></div></td>- <td className="py-2 pr-3 align-middle"><AxisBar value={best.reliability} color="#22c55e" /></td>- <td className="py-2 pr-3 align-middle"><AxisBar value={best.speed} color="#3b82f6" /></td>- <td className="py-2 pr-3 align-middle"><AxisBar value={best.intelligence} color="#a855f7" /></td>+ <td className="py-2 pr-3 align-middle">{measured.length === 0 ? <AxisNoData /> : <AxisRangeBar values={measured.map(m => m.reliability)} color="#22c55e" />}</td>+ <td className="py-2 pr-3 align-middle">{measured.length === 0 ? <AxisNoData /> : <AxisRangeBar values={measured.map(m => m.speed)} color="#3b82f6" />}</td>+ <td className="py-2 pr-3 align-middle"><AxisRangeBar values={group.members.map(m => m.intelligence)} color="#a855f7" /></td><td className="py-2 pr-3 align-middle font-mono text-[11px] text-muted-foreground tabular-nums">{guard < 0.999 ? `×${guard.toFixed(2)}` : '—'}</td>- <td className="py-2 pr-3 align-middle text-right font-mono text-xs font-medium tabular-nums">{best.score !== undefined ? best.score.toFixed(3) : '–'}</td>+ <td className="py-2 pr-3 align-middle text-right font-mono text-xs font-medium tabular-nums">+ {solo ? (+ best.score !== undefined ? best.score.toFixed(3) : '–'+ ) : (+ <Tooltip text={t('models.perProviderScores', { list: scoreBreakdown })}>+ <span className="inline-flex flex-col items-end cursor-help">+ <span>{best.score !== undefined ? best.score.toFixed(3) : '–'}</span>+ <span className="text-[10px] font-normal text-muted-foreground/60 whitespace-nowrap">{t('models.bestOfN', { count: group.members.length })}</span>+ </span>+ </Tooltip>+ )}+ </td><td className="py-2 pr-3 align-middle text-right" onClick={e => e.stopPropagation()}><Switch checked={anyEnabled} onCheckedChange={(c) => onToggleGroup(group.members.map(m => m.modelDbId), c)} /></td>diff --git a/client/src/components/toaster.tsx b/client/src/components/toaster.tsxindex 94125026..48b81826 100644--- a/client/src/components/toaster.tsx+++ b/client/src/components/toaster.tsx@@ -1,6 +1,7 @@-import { useEffect, useSyncExternalStore } from 'react'+import { useEffect, useRef, useSyncExternalStore } from 'react'import { CircleAlert, CircleCheck, Info, X } from 'lucide-react'import { dismissToast, getToasts, subscribeToasts, type ToastItem } from '@/lib/toast'+import { startToastTimer } from '@/lib/toast-timer'import { useI18n } from '@/i18n'// Bottom-right toast stack. FloatingBar owns bottom-center, so the two never@@ -31,15 +32,38 @@ const ICON_CLASS = {function Toast({ toast }: { toast: ToastItem }) {const { t } = useI18n()+ const nodeRef = useRef<HTMLDivElement>(null)+ // Auto-dismiss with a pausable countdown: hovering the toast or blurring+ // the window suspends it, so reading a message never races the timer.+ // Sticky toasts (duration null — errors by default) never auto-dismiss.useEffect(() => {- const timer = window.setTimeout(() => dismissToast(toast.id), toast.duration)- return () => window.clearTimeout(timer)+ const duration = toast.duration+ if (duration === null) return+ const timer = startToastTimer(duration, () => dismissToast(toast.id))+ if (!document.hasFocus()) timer.pause()+ const onBlur = () => timer.pause()+ const onFocus = () => timer.resume()+ window.addEventListener('blur', onBlur)+ window.addEventListener('focus', onFocus)+ const node = nodeRef.current+ const onEnter = () => timer.pause()+ const onLeave = () => timer.resume()+ node?.addEventListener('mouseenter', onEnter)+ node?.addEventListener('mouseleave', onLeave)+ return () => {+ timer.cancel()+ window.removeEventListener('blur', onBlur)+ window.removeEventListener('focus', onFocus)+ node?.removeEventListener('mouseenter', onEnter)+ node?.removeEventListener('mouseleave', onLeave)+ }}, [toast.id, toast.duration])const Icon = ICONS[toast.kind]return (<div+ ref={nodeRef}role={toast.kind === 'error' ? 'alert' : 'status'}aria-live={toast.kind === 'error' ? 'assertive' : 'polite'}className="pointer-events-auto flex items-start gap-2.5 rounded-2xl border bg-card px-3.5 py-2.5 shadow-lg animate-in slide-in-from-bottom-2 fade-in duration-200"diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex 39726d03..a5d6c903 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -128,8 +128,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} RPD","rateTitle": "Rate-limited — no fixed monthly token budget",- "unifyToggle": "Unify duplicate models",- "unifyToggleHint": "Show a model served by several providers as one item, and fail over across its providers when it's selected.",+ "splitOut": "Don't merge this copy",+ "splitOutHint": "Give this provider's copy its own separate entry instead of merging it into the unified model. You can merge it back from the copy's own page.",+ "splitUndo": "Merge back",+ "splitUndoHint": "This copy is kept separate from its unified model. Merge it back to fail over across all of its providers again.",+ "splitBadge": "kept separate",+ "noData": "no data",+ "noDataTitle": "No requests recorded yet — reliability and speed are unmeasured for this provider.",+ "bestOfN": "best of {count}",+ "perProviderScores": "Per-provider scores: {list}","columnModel": "Model","columnOn": "On","noModelsBefore": "No models available. Add API keys on the ",diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex 0eee2e01..44ef31e1 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -141,8 +141,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} RPD","rateTitle": "Con límite de tasa: sin presupuesto mensual fijo de tokens",- "unifyToggle": "Unificar modelos duplicados",- "unifyToggleHint": "Muestra un modelo servido por varios proveedores como un solo elemento, y conmuta entre sus proveedores cuando se selecciona."+ "splitOut": "No combinar esta copia",+ "splitOutHint": "Da a la copia de este proveedor su propia entrada separada en lugar de combinarla en el modelo unificado. Puedes volver a combinarla desde la página de la copia.",+ "splitUndo": "Volver a combinar",+ "splitUndoHint": "Esta copia se mantiene separada de su modelo unificado. Vuelve a combinarla para conmutar de nuevo entre todos sus proveedores.",+ "splitBadge": "separada",+ "noData": "sin datos",+ "noDataTitle": "Aún no hay solicitudes registradas: la fiabilidad y la velocidad de este proveedor no se han medido.",+ "bestOfN": "mejor de {count}",+ "perProviderScores": "Puntuaciones por proveedor: {list}"},"strategies": {"title": "Estrategia de enrutamiento",diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex aa51f18b..600c2a39 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -141,8 +141,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} RPD","rateTitle": "Limité en débit : pas de budget mensuel de tokens fixe",- "unifyToggle": "Unifier les modèles en double",- "unifyToggleHint": "Afficher un modèle fourni par plusieurs fournisseurs comme un seul élément, et basculer entre ses fournisseurs lorsqu'il est sélectionné."+ "splitOut": "Ne pas fusionner cette copie",+ "splitOutHint": "Donne à la copie de ce fournisseur sa propre entrée séparée au lieu de la fusionner dans le modèle unifié. Vous pourrez la re-fusionner depuis la page de la copie.",+ "splitUndo": "Re-fusionner",+ "splitUndoHint": "Cette copie est gardée séparée de son modèle unifié. Re-fusionnez-la pour basculer à nouveau entre tous ses fournisseurs.",+ "splitBadge": "gardée séparée",+ "noData": "aucune donnée",+ "noDataTitle": "Aucune requête enregistrée pour l'instant — la fiabilité et la vitesse de ce fournisseur ne sont pas mesurées.",+ "bestOfN": "meilleur de {count}",+ "perProviderScores": "Scores par fournisseur : {list}"},"strategies": {"title": "Stratégie de routage",diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 71b52bb2..12754b36 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -116,8 +116,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} GPD","rateTitle": "Limitato — nessun budget mensile fisso di token",- "unifyToggle": "Unifica modelli duplicati",- "unifyToggleHint": "Mostra un modello servito da più fornitori come un unico elemento, con failover tra i fornitori quando selezionato.",+ "splitOut": "Non unire questa copia",+ "splitOutHint": "Dai alla copia di questo fornitore una voce separata invece di unirla nel modello unificato. Puoi riunirla dalla pagina della copia.",+ "splitUndo": "Riunisci",+ "splitUndoHint": "Questa copia è tenuta separata dal suo modello unificato. Riuniscila per tornare al failover tra tutti i suoi fornitori.",+ "splitBadge": "tenuta separata",+ "noData": "nessun dato",+ "noDataTitle": "Nessuna richiesta registrata finora: affidabilità e velocità di questo fornitore non sono misurate.",+ "bestOfN": "migliore di {count}",+ "perProviderScores": "Punteggi per fornitore: {list}","columnModel": "Modello","columnOn": "Attivo","noModelsBefore": "Nessun modello disponibile. Aggiungi chiavi API nella ",diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex 840c920e..1918a720 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -141,8 +141,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} RPD","rateTitle": "Limitado por taxa: sem orçamento fixo de tokens mensal",- "unifyToggle": "Unificar modelos duplicados",- "unifyToggleHint": "Mostra um modelo servido por vários provedores como um único item, e faz failover entre seus provedores quando selecionado."+ "splitOut": "Não mesclar esta cópia",+ "splitOutHint": "Dá à cópia deste provedor uma entrada separada em vez de mesclá-la no modelo unificado. Você pode mesclá-la de volta na página da própria cópia.",+ "splitUndo": "Mesclar de volta",+ "splitUndoHint": "Esta cópia é mantida separada do seu modelo unificado. Mescle-a de volta para voltar a fazer failover entre todos os seus provedores.",+ "splitBadge": "mantida separada",+ "noData": "sem dados",+ "noDataTitle": "Nenhuma solicitação registrada ainda — a confiabilidade e a velocidade deste provedor não foram medidas.",+ "bestOfN": "melhor de {count}",+ "perProviderScores": "Pontuações por provedor: {list}"},"strategies": {"title": "Estratégia de roteamento",diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex 7861c76b..d5ba6c11 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -116,8 +116,15 @@"rateRpm": "{count} RPM","rateRpd": "{count} RPD","rateTitle": "按速率限制——无固定的每月令牌额度",- "unifyToggle": "合并重复模型",- "unifyToggleHint": "将由多个提供方提供的同一模型显示为一项,选中时在其各提供方之间自动故障转移。",+ "splitOut": "不合并此副本",+ "splitOutHint": "让该提供方的副本作为独立条目显示,而不并入统一模型。可在该副本自己的页面上重新合并。",+ "splitUndo": "重新合并",+ "splitUndoHint": "此副本当前独立于其统一模型。重新合并后将再次在其所有提供方之间进行故障转移。",+ "splitBadge": "已独立",+ "noData": "暂无数据",+ "noDataTitle": "尚未记录任何请求——该提供方的可靠性和速度尚未测得。",+ "bestOfN": "{count} 个中的最佳",+ "perProviderScores": "各提供方评分:{list}","columnModel": "模型","columnOn": "启用","noModelsBefore": "暂无可用模型。请先在",diff --git a/client/src/lib/toast-timer.test.ts b/client/src/lib/toast-timer.test.tsnew file mode 100644index 00000000..81fc5a60--- /dev/null+++ b/client/src/lib/toast-timer.test.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { startToastTimer } from './toast-timer'++describe('startToastTimer (#586)', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ it('fires onExpire after the duration', () => {+ const onExpire = vi.fn()+ startToastTimer(5000, onExpire)+ vi.advanceTimersByTime(4999)+ expect(onExpire).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(onExpire).toHaveBeenCalledTimes(1)+ })++ it('pause suspends the countdown indefinitely', () => {+ const onExpire = vi.fn()+ const timer = startToastTimer(5000, onExpire)+ vi.advanceTimersByTime(2000)+ timer.pause()+ vi.advanceTimersByTime(60_000)+ expect(onExpire).not.toHaveBeenCalled()+ })++ it('resume continues with the remaining time, not a fresh duration', () => {+ const onExpire = vi.fn()+ const timer = startToastTimer(5000, onExpire)+ vi.advanceTimersByTime(3000)+ timer.pause()+ vi.advanceTimersByTime(60_000)+ timer.resume()+ vi.advanceTimersByTime(1999)+ expect(onExpire).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(onExpire).toHaveBeenCalledTimes(1)+ })++ it('overlapping holds (hover + window blur) must all release before it runs', () => {+ const onExpire = vi.fn()+ const timer = startToastTimer(5000, onExpire)+ timer.pause() // hover+ timer.pause() // blur+ timer.resume() // pointer leaves, window still blurred+ vi.advanceTimersByTime(60_000)+ expect(onExpire).not.toHaveBeenCalled()+ timer.resume() // window refocused+ vi.advanceTimersByTime(5000)+ expect(onExpire).toHaveBeenCalledTimes(1)+ })++ it('an unmatched resume (focus without a prior blur hold) does not underflow', () => {+ const onExpire = vi.fn()+ const timer = startToastTimer(5000, onExpire)+ timer.resume() // stray focus event+ timer.pause() // hover must still hold+ vi.advanceTimersByTime(60_000)+ expect(onExpire).not.toHaveBeenCalled()+ })++ it('cancel stops it for good, even after a later resume', () => {+ const onExpire = vi.fn()+ const timer = startToastTimer(5000, onExpire)+ timer.cancel()+ timer.resume()+ vi.advanceTimersByTime(60_000)+ expect(onExpire).not.toHaveBeenCalled()+ })+})diff --git a/client/src/lib/toast-timer.ts b/client/src/lib/toast-timer.tsnew file mode 100644index 00000000..5b45dd92--- /dev/null+++ b/client/src/lib/toast-timer.ts@@ -0,0 +1,62 @@+// Pausable countdown behind a toast's auto-dismiss (#586). The Toaster pauses+// it while the pointer is over the toast and while the window is blurred, so+// reading a message never races the timer. Pauses are counted, not boolean:+// hover and blur can overlap, and the timer only runs when every hold has+// been released. Kept free of React/DOM so it can be unit-tested directly.++export interface ToastTimer {+ /** Suspend the countdown; keeps the remaining time. */+ pause(): void+ /** Release one pause hold; the countdown resumes once none remain. */+ resume(): void+ /** Stop for good without firing (unmount / manual dismiss). */+ cancel(): void+}++export function startToastTimer(durationMs: number, onExpire: () => void): ToastTimer {+ let remaining = durationMs+ let startedAt: number | null = null+ let timeout: ReturnType<typeof setTimeout> | undefined+ let holds = 0+ let finished = false++ const expire = () => {+ finished = true+ startedAt = null+ timeout = undefined+ onExpire()+ }++ const run = () => {+ if (finished || holds > 0 || startedAt !== null) return+ startedAt = Date.now()+ timeout = setTimeout(expire, Math.max(0, remaining))+ }++ const halt = () => {+ if (startedAt !== null) {+ remaining -= Date.now() - startedAt+ startedAt = null+ }+ if (timeout !== undefined) {+ clearTimeout(timeout)+ timeout = undefined+ }+ }++ run()+ return {+ pause() {+ holds+++ halt()+ },+ resume() {+ if (holds > 0) holds--+ run()+ },+ cancel() {+ finished = true+ halt()+ },+ }+}diff --git a/client/src/lib/toast.test.ts b/client/src/lib/toast.test.tsnew file mode 100644index 00000000..997dd817--- /dev/null+++ b/client/src/lib/toast.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it, vi } from 'vitest'++// The toast store keeps module-level state, so each test gets a fresh copy of+// the module instead of sharing one mutable list across tests.+async function loadStore() {+ vi.resetModules()+ return await import('./toast')+}++describe('toast store (#586)', () => {+ describe('per-severity default durations', () => {+ it('gives success and info toasts 5000ms', async () => {+ const { toast, getToasts } = await loadStore()+ toast.success('saved')+ toast.info('heads up')+ expect(getToasts().map(t => t.duration)).toEqual([5000, 5000])+ })++ it('makes errors sticky (duration null, no auto-dismiss)', async () => {+ const { toast, getToasts } = await loadStore()+ toast.error('boom')+ expect(getToasts()[0].duration).toBeNull()+ })++ it('lets an explicit per-call duration win, including for errors', async () => {+ const { toast, getToasts } = await loadStore()+ toast.error('transient', 2000)+ toast.success('slow read', 10000)+ expect(getToasts().map(t => t.duration)).toEqual([2000, 10000])+ })+ })++ it('replaces an identical pending toast instead of stacking duplicates', async () => {+ const { toast, getToasts } = await loadStore()+ toast.error('poll failed')+ toast.error('poll failed')+ expect(getToasts()).toHaveLength(1)+ // Same kind but different message, or same message but different kind,+ // must still stack.+ toast.info('poll failed')+ toast.error('other failure')+ expect(getToasts()).toHaveLength(3)+ })++ it('dismissToast removes a toast and ignores unknown ids', async () => {+ const { toast, dismissToast, getToasts } = await loadStore()+ const id = toast.error('boom')+ dismissToast(999)+ expect(getToasts()).toHaveLength(1)+ dismissToast(id)+ expect(getToasts()).toHaveLength(0)+ })++ describe('cap eviction', () => {+ it('caps the stack at 4', async () => {+ const { toast, getToasts } = await loadStore()+ for (let i = 0; i < 6; i++) toast.info(`msg ${i}`)+ expect(getToasts()).toHaveLength(4)+ expect(getToasts().map(t => t.message)).toEqual(['msg 2', 'msg 3', 'msg 4', 'msg 5'])+ })++ it('never evicts an un-dismissed error while non-errors are present', async () => {+ const { toast, getToasts } = await loadStore()+ toast.error('important error') // oldest — the old slice(-4) would drop it+ toast.info('a')+ toast.success('b')+ toast.info('c')+ toast.info('d')+ const kept = getToasts()+ expect(kept).toHaveLength(4)+ expect(kept.map(t => t.message)).toEqual(['important error', 'b', 'c', 'd'])+ })++ it('keeps evicting oldest non-errors as errors accumulate', async () => {+ const { toast, getToasts } = await loadStore()+ toast.info('a')+ toast.error('e1')+ toast.info('b')+ toast.error('e2')+ toast.error('e3')+ toast.error('e4')+ expect(getToasts().map(t => t.message)).toEqual(['e1', 'e2', 'e3', 'e4'])+ })++ it('evicts the oldest error only when the stack is all errors', async () => {+ const { toast, getToasts } = await loadStore()+ for (let i = 0; i < 5; i++) toast.error(`err ${i}`)+ expect(getToasts().map(t => t.message)).toEqual(['err 1', 'err 2', 'err 3', 'err 4'])+ })+ })+})diff --git a/client/src/lib/toast.ts b/client/src/lib/toast.tsindex e7281ede..5609119c 100644--- a/client/src/lib/toast.ts+++ b/client/src/lib/toast.ts@@ -10,8 +10,22 @@ export interface ToastItem {id: numberkind: ToastKindmessage: string- /** Auto-dismiss delay in ms. */- duration: number+ /** Auto-dismiss delay in ms; `null` means sticky until manually dismissed. */+ duration: number | null+}++/** Most toasts kept on screen at once; older ones are evicted (see push). */+const MAX_VISIBLE_TOASTS = 4++// Per-severity auto-dismiss defaults (#586). Success/info give the user a+// comfortable read; errors are sticky — they carry information the user may+// need to act on (and copy), every toast has a dismiss button, identical+// messages are deduped in push, and the cap below still bounds the stack, so+// stickiness cannot pile up unbounded. An explicit per-call duration wins.+const DEFAULT_DURATIONS: Record<ToastKind, number | null> = {+ success: 5000,+ info: 5000,+ error: null,}type Listener = (toasts: ToastItem[]) => void@@ -45,10 +59,18 @@ function push(kind: ToastKind, message: string, duration?: number): number {const id = nextId++// Replace an identical pending toast instead of stacking duplicates (a// failing poll would otherwise pile up the same error every interval).- items = [+ const next = [...items.filter(t => !(t.kind === kind && t.message === message)),- { id, kind, message, duration: duration ?? (kind === 'error' ? 6000 : 3500) },- ].slice(-4)+ { id, kind, message, duration: duration ?? DEFAULT_DURATIONS[kind] },+ ]+ // Enforce the cap without silently evicting an unread error: drop the+ // oldest non-error first, and only evict an error once the stack is all+ // errors (the cap itself always holds).+ while (next.length > MAX_VISIBLE_TOASTS) {+ const victim = next.findIndex(t => t.kind !== 'error')+ next.splice(victim === -1 ? 0 : victim, 1)+ }+ items = nextemit()return id}diff --git a/client/src/pages/ModelDetailPage.tsx b/client/src/pages/ModelDetailPage.tsxindex 1f38998d..6760d32a 100644--- a/client/src/pages/ModelDetailPage.tsx+++ b/client/src/pages/ModelDetailPage.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { Link, useParams } from 'react-router-dom'-import { ChevronLeft, Save, Trash2 } from 'lucide-react'+import { ChevronLeft, Merge, Save, Split, Trash2 } from 'lucide-react'import { useI18n } from '@/i18n'import { apiFetch } from '@/lib/api'import { Button } from '@/components/ui/button'@@ -30,6 +30,20 @@ type ModelSettingsPatch = {fallbackEnabled: boolean}+// The persisted unify overrides (see server model-groups.ts). `splits` forces a+// "platform:model_id" member out of its computed group into its own entry.+type UnifyOverrides = {+ merges: { into: string; keys: string[] }[]+ splits: { member: string; groupKey?: string }[]+}++// What the per-provider split control should do for one member row.+export type SplitAction = {+ kind: 'split' | 'undo'+ pending: boolean+ onClick: () => void+}+// One model's own page: lists every provider that serves it (this model now// fails over across these providers). Reached from the Models list; replaces the// old inline group expansion.@@ -51,6 +65,10 @@ export default function ModelDetailPage() {queryKey: ['unified-key'],queryFn: () => apiFetch('/api/settings/api-key'),})+ const { data: unify } = useQuery<{ enabled: boolean; overrides: UnifyOverrides }>({+ queryKey: ['unify'],+ queryFn: () => apiFetch('/api/settings/unify'),+ })// Toggling a provider persists immediately (no save bar on this page): send the// full entries list with this one flipped, then refresh.@@ -80,6 +98,46 @@ export default function ModelDetailPage() {},})+ // Split a provider's copy out of its unified model (or merge it back).+ // PUT /api/settings/unify replaces the whole overrides object, so send the+ // current merges untouched with the adjusted splits list.+ const splitMutation = useMutation({+ mutationFn: (splits: UnifyOverrides['splits']) =>+ apiFetch('/api/settings/unify', {+ method: 'PUT',+ body: JSON.stringify({ overrides: { merges: unify?.overrides.merges ?? [], splits } }),+ }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['unify'] })+ queryClient.invalidateQueries({ queryKey: ['fallback'] })+ queryClient.invalidateQueries({ queryKey: ['fallback', 'routing'] })+ queryClient.invalidateQueries({ queryKey: ['models'] })+ },+ })++ const splits = unify?.overrides.splits ?? []+ const memberKey = (m: Row) => `${m.platform}:${m.modelId}`+ // The split control for one provider row: offer "keep separate" while the+ // model is merged with siblings, and "merge back" on a copy that was split+ // out (it lives on its own page then, so the undo must live there too).+ function splitActionFor(m: Row, memberCount: number): SplitAction | undefined {+ if (!unify) return undefined+ const isSplit = splits.some(s => s.member === memberKey(m))+ if (isSplit) {+ return {+ kind: 'undo',+ pending: splitMutation.isPending,+ onClick: () => splitMutation.mutate(splits.filter(s => s.member !== memberKey(m))),+ }+ }+ if (memberCount < 2) return undefined+ return {+ kind: 'split',+ pending: splitMutation.isPending,+ onClick: () => splitMutation.mutate([...splits, { member: memberKey(m) }]),+ }+ }+const isManual = (routing?.strategy ?? 'balanced') === 'priority'const scoreById = new Map((routing?.scores ?? []).map(s => [s.modelDbId, s]))@@ -171,6 +229,7 @@ export default function ModelDetailPage() {deleting={modelDeleteMutation.isPending && modelDeleteMutation.variables === m.modelDbId}onSave={(patch) => modelPatchMutation.mutate({ modelDbId: m.modelDbId, patch })}onDelete={() => modelDeleteMutation.mutate(m.modelDbId)}+ splitAction={splitActionFor(m, members.length)}/>))}</div>@@ -214,12 +273,14 @@ function ProviderSettingsRow({deleting,onSave,onDelete,+ splitAction,}: {model: Rowsaving: booleandeleting: booleanonSave: (patch: ModelSettingsPatch) => voidonDelete: () => void+ splitAction?: SplitAction}) {const { t } = useI18n()const [displayName, setDisplayName] = useState(model.displayName)@@ -270,6 +331,26 @@ function ProviderSettingsRow({{t('models.localOverride')}</span>)}+ {splitAction?.kind === 'undo' && (+ <span className="rounded-full bg-amber-600/15 px-1.5 py-0.5 text-[10px] text-amber-700 dark:text-amber-400">+ {t('models.splitBadge')}+ </span>+ )}+ {splitAction && (+ <Tooltip text={t(splitAction.kind === 'split' ? 'models.splitOutHint' : 'models.splitUndoHint')}>+ <Button+ type="button"+ size="xs"+ variant="ghost"+ className="ml-auto text-muted-foreground"+ disabled={splitAction.pending}+ onClick={splitAction.onClick}+ >+ {splitAction.kind === 'split' ? <Split className="size-3" /> : <Merge className="size-3" />}+ {t(splitAction.kind === 'split' ? 'models.splitOut' : 'models.splitUndo')}+ </Button>+ </Tooltip>+ )}</div><div className="grid gap-3 md:grid-cols-[minmax(12rem,1fr)_8rem_auto_auto_auto_auto] md:items-end"><label className="space-y-1 text-xs text-muted-foreground">diff --git a/client/vitest.config.ts b/client/vitest.config.tsnew file mode 100644index 00000000..dfd625a6--- /dev/null+++ b/client/vitest.config.ts@@ -0,0 +1,10 @@+// Standalone vitest config so tests don't load vite.config.ts (whose React ++// Tailwind plugins are pointless for unit tests). Store/timer tests are plain+// TypeScript, so the default node environment is enough — no jsdom.+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ include: ['src/**/*.test.ts'],+ },+})diff --git a/package-lock.json b/package-lock.jsonindex f510e946..344e70f4 100644--- a/package-lock.json+++ b/package-lock.json@@ -56,7 +56,8 @@"globals": "^17.4.0","typescript": "~6.0.2","typescript-eslint": "^8.58.0",- "vite": "^8.0.4"+ "vite": "^8.0.4",+ "vitest": "^3.1.3"},"engines": {"node": ">=20.18.0 <25.0.0",diff --git a/server/src/__tests__/lib/provider-timeout.test.ts b/server/src/__tests__/lib/provider-timeout.test.tsindex 58ec6aa1..531267ab 100644--- a/server/src/__tests__/lib/provider-timeout.test.ts+++ b/server/src/__tests__/lib/provider-timeout.test.ts@@ -13,6 +13,8 @@ afterEach(() => {delete process.env.PROVIDER_TIMEOUT_NVIDIA;delete process.env.PROVIDER_TIMEOUT_GROQ;delete process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS;+ delete process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA;+ delete process.env.PROVIDER_STREAM_STALL_TIMEOUT_GROQ;resetTimeoutWarnings();vi.restoreAllMocks();});@@ -69,4 +71,36 @@ describe('streamStallTimeoutMs', () => {process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '0';expect(streamStallTimeoutMs()).toBe(0);});++ // Per-platform stall override (issue #584): symmetric with+ // PROVIDER_TIMEOUT_<PLATFORM>; per-platform wins over global wins over default.+ it('PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM> wins over the global value', () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '240000';+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA = '30000';+ expect(streamStallTimeoutMs('nvidia')).toBe(30_000);+ // Other platforms stay on the global value.+ expect(streamStallTimeoutMs('groq')).toBe(240_000);+ // And the bare (platform-less) call is unchanged.+ expect(streamStallTimeoutMs()).toBe(240_000);+ });++ it('per-platform override works without a global override (falls back through to the default otherwise)', () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA = '30000';+ expect(streamStallTimeoutMs('nvidia')).toBe(30_000);+ expect(streamStallTimeoutMs('groq')).toBe(DEFAULT_STREAM_STALL_TIMEOUT_MS);+ });++ it('per-platform 0 disables the watchdog for that platform only', () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA = '0';+ expect(streamStallTimeoutMs('nvidia')).toBe(0);+ expect(streamStallTimeoutMs('groq')).toBe(DEFAULT_STREAM_STALL_TIMEOUT_MS);+ });++ it('a malformed per-platform value warns and falls back to the global/default chain', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '240000';+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA = 'ninety';+ expect(streamStallTimeoutMs('nvidia')).toBe(240_000);+ expect(warn).toHaveBeenCalledTimes(1);+ });});diff --git a/server/src/__tests__/providers/google.test.ts b/server/src/__tests__/providers/google.test.tsindex e77595e0..32ea5900 100644--- a/server/src/__tests__/providers/google.test.ts+++ b/server/src/__tests__/providers/google.test.ts@@ -154,7 +154,11 @@ describe('GoogleProvider', () => {expect(capturedBody.contents[0].role).toBe('user');});- it('folds system prompts into user content and strips function tools for Gemma models (#500)', async () => {+ // #500: older Gemma on the Gemini API 400s with "Developer instruction is not+ // enabled" — system prompts must keep folding into the first user turn.+ // #582: tools must NOT be stripped anymore (Gemma 4 has native function+ // calling); the fold and tool pass-through coexist on the same request.+ it('folds system prompts into user content for Gemma models while passing tools through (#500, #582)', async () => {let capturedBody: any;vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {capturedBody = JSON.parse((init as any).body);@@ -188,11 +192,108 @@ describe('GoogleProvider', () => {},);+ // The #500 fold is untouched: no systemInstruction, system text leads contents.expect(capturedBody.systemInstruction).toBeUndefined();- expect(capturedBody.tools).toBeUndefined();- expect(capturedBody.toolConfig).toBeUndefined();expect(capturedBody.contents[0]).toEqual({ role: 'user', parts: [{ text: 'You are helpful' }] });expect(capturedBody.contents[1]).toEqual({ role: 'user', parts: [{ text: 'Hi' }] });+ // The #582 fix: tools reach Gemma instead of being silently deleted.+ expect(capturedBody.tools[0].functionDeclarations[0].name).toBe('get_weather');+ expect(capturedBody.toolConfig.functionCallingConfig.mode).toBe('AUTO');+ });++ it('passes tools/tool_choice through for Gemma on the streaming path (#582)', async () => {+ let capturedBody: any;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ capturedBody = JSON.parse((init as any).body);+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ const encoder = new TextEncoder();+ controller.enqueue(encoder.encode('data: {"candidates":[{"content":{"parts":[{"functionCall":{"id":"call_1","name":"get_weather","args":{"city":"Karachi"}}}]}}]}\n\n'));+ controller.enqueue(encoder.encode('data: {"candidates":[{"content":{"parts":[]},"finishReason":"STOP"}]}\n\n'));+ controller.close();+ },+ });+ return { ok: true, body: stream } as any;+ });++ const chunks: any[] = [];+ for await (const c of provider.streamChatCompletion(+ 'test-key',+ [{ role: 'user', content: 'Weather?' }],+ 'gemma-4-31b-it',+ {+ tools: [{+ type: 'function',+ function: {+ name: 'get_weather',+ description: 'Get weather for a city',+ parameters: { type: 'object', properties: { city: { type: 'string' } } },+ },+ }],+ tool_choice: 'required',+ },+ )) chunks.push(c);++ expect(capturedBody.tools[0].functionDeclarations[0].name).toBe('get_weather');+ expect(capturedBody.toolConfig.functionCallingConfig.mode).toBe('ANY');+ const toolDeltas = chunks.flatMap(c => c.choices[0].delta.tool_calls ?? []);+ expect(toolDeltas).toHaveLength(1);+ expect(toolDeltas[0].function.name).toBe('get_weather');+ expect(chunks[chunks.length - 1].choices[0].finish_reason).toBe('tool_calls');+ });++ it('keeps functionCall/functionResponse history for Gemma multi-turn tool round-trips (#582)', async () => {+ let capturedBody: any;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ capturedBody = JSON.parse((init as any).body);+ return {+ ok: true,+ json: () => Promise.resolve({+ candidates: [{ content: { parts: [{ text: 'Sunny, 31C.' }] }, finishReason: 'STOP' }],+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },+ }),+ } as any;+ });++ await provider.chatCompletion(+ 'test-key',+ [+ { role: 'system', content: 'You are helpful' },+ { role: 'user', content: 'Weather in Karachi?' },+ {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: 'call_gemma_1',+ type: 'function',+ function: { name: 'get_weather', arguments: '{"city":"Karachi"}' },+ }],+ },+ { role: 'tool', tool_call_id: 'call_gemma_1', content: '{"temp": 31}' },+ ],+ 'gemma-4-31b-it',+ {+ tools: [{+ type: 'function',+ function: {+ name: 'get_weather',+ description: 'Get weather for a city',+ parameters: { type: 'object', properties: { city: { type: 'string' } } },+ },+ }],+ },+ );++ // System fold still applies, and the tool round-trip history survives.+ expect(capturedBody.systemInstruction).toBeUndefined();+ expect(capturedBody.contents[0]).toEqual({ role: 'user', parts: [{ text: 'You are helpful' }] });+ const modelEntry = capturedBody.contents.find((c: any) => c.role === 'model');+ expect(modelEntry.parts[0].functionCall.name).toBe('get_weather');+ expect(modelEntry.parts[0].functionCall.args).toEqual({ city: 'Karachi' });+ const responseEntry = capturedBody.contents.find((c: any) =>+ c.parts.some((p: any) => p.functionResponse));+ expect(responseEntry.parts[0].functionResponse.name).toBe('get_weather');+ expect(responseEntry.parts[0].functionResponse.response).toEqual({ temp: 31 });});it('does not expose Gemini thought parts as visible content (#539)', async () => {diff --git a/server/src/__tests__/providers/reasoning-timeouts.test.ts b/server/src/__tests__/providers/reasoning-timeouts.test.tsindex 33dabbe7..eba33267 100644--- a/server/src/__tests__/providers/reasoning-timeouts.test.ts+++ b/server/src/__tests__/providers/reasoning-timeouts.test.ts@@ -23,6 +23,9 @@ describe('reasoning-model chat timeouts', () => {['agnes', 60_000],['opencode', 60_000],['ollama', 120_000], // pre-existing bump; keep it from regressing too+ // NVIDIA NIM prefills 100k-token prompts for minutes before the first SSE+ // byte; this value doubles as the streaming first-byte grace budget (#584).+ ['nvidia', 180_000],] as const)('%s is registered with a %dms chat timeout', (platform, ms) => {const provider = resolveProvider(platform);expect(provider).toBeDefined();diff --git a/server/src/__tests__/providers/stream-first-byte.test.ts b/server/src/__tests__/providers/stream-first-byte.test.tsnew file mode 100644index 00000000..134de12c--- /dev/null+++ b/server/src/__tests__/providers/stream-first-byte.test.ts@@ -0,0 +1,275 @@+import http from 'http';+import type { AddressInfo } from 'net';+import { describe, it, expect, vi, afterEach } from 'vitest';+import { OpenAICompatProvider } from '../../providers/openai-compat.js';+import { GoogleProvider } from '../../providers/google.js';+import { resetTimeoutWarnings } from '../../lib/provider-timeout.js';+import { isClientAbortError, isRetryableError, newClientAbortError } from '../../lib/error-classify.js';+import type { ChatMessage } from '@freellmapi/shared/types.js';+import type { ChatCompletionChunk } from '@freellmapi/shared/types.js';++/**+ * First-byte grace period for streaming (issue #584).+ *+ * The stream stall watchdog (readWithStallTimeout, default 90s) also bounded+ * TIME-TO-FIRST-BYTE: on streaming requests the per-platform chat timeout is+ * disarmed the moment response HEADERS arrive, and providers like NVIDIA NIM+ * send SSE headers instantly then prefill for minutes on 100k-token prompts.+ * Healthy long prefills died at 90s with "stream stalled: no data for 90000ms".+ *+ * The fix gives the FIRST read its own budget — the platform's already-tuned+ * chat timeout (env-overridable via PROVIDER_TIMEOUT_<PLATFORM>), floored at+ * the stall budget so it can never be stricter than before — while subsequent+ * reads keep the mid-stream stall budget (PROVIDER_STREAM_STALL_TIMEOUT_MS,+ * now also per-platform via PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>).+ */++const MESSAGES: ChatMessage[] = [{ role: 'user', content: 'hi' }];++const STALL_ENV_VARS = [+ 'PROVIDER_STREAM_STALL_TIMEOUT_MS',+ 'PROVIDER_STREAM_STALL_TIMEOUT_GROQ',+ 'PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA',+ 'PROVIDER_STREAM_STALL_TIMEOUT_GOOGLE',+ 'PROVIDER_TIMEOUT_GROQ',+ 'PROVIDER_TIMEOUT_GOOGLE',+];++function makeProvider(timeoutMs: number): OpenAICompatProvider {+ return new OpenAICompatProvider({+ platform: 'groq',+ name: 'TestProvider',+ baseUrl: 'https://api.test.com/v1',+ timeoutMs,+ });+}++/** SSE response whose body emits each segment after its own delay (ms from+ * the PREVIOUS segment), then closes. */+function delayedSseResponse(segments: Array<{ afterMs: number; data: string }>): any {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ let at = 0;+ for (const seg of segments) {+ at += seg.afterMs;+ setTimeout(() => {+ try { controller.enqueue(encoder.encode(seg.data)); } catch { /* closed */ }+ }, at);+ }+ setTimeout(() => {+ try { controller.close(); } catch { /* closed */ }+ }, at + 10);+ },+ });+ return { ok: true, body: stream, headers: new Headers() };+}++async function collect(gen: AsyncGenerator<ChatCompletionChunk>): Promise<ChatCompletionChunk[]> {+ const out: ChatCompletionChunk[] = [];+ for await (const chunk of gen) out.push(chunk);+ return out;+}++const CONTENT_FRAME = 'data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]}\n\n';+const FINISH_FRAME = 'data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n';++afterEach(() => {+ for (const name of STALL_ENV_VARS) delete process.env[name];+ resetTimeoutWarnings();+ vi.restoreAllMocks();+});++describe('first-byte grace period (issue #584)', () => {+ it('a stream silent past the stall timeout, then delivering, succeeds under the chat-timeout grace (the #584 repro)', async () => {+ // Stall budget 100ms; chat timeout (= first-byte grace) 1500ms. The+ // upstream sends nothing for 400ms — over the stall budget, within the+ // grace — then a normal completion. Pre-fix this died at the stall budget.+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = makeProvider(1500);+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 400, data: CONTENT_FRAME },+ { afterMs: 10, data: FINISH_FRAME },+ ]));++ const chunks = await collect(provider.streamChatCompletion('k', MESSAGES, 'm'));+ expect(chunks.map(c => c.choices?.[0]?.delta?.content ?? '')).toContain('hello');+ });++ it('a mid-stream gap past the stall timeout still fails fast with the stall message', async () => {+ // First byte arrives instantly (grace satisfied); the stream then goes+ // silent past the stall budget — the watchdog must still fire.+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = makeProvider(1500);+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 0, data: CONTENT_FRAME },+ { afterMs: 600, data: FINISH_FRAME },+ ]));++ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'm')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('stream stalled: no data for 100ms');+ expect(isRetryableError(err)).toBe(true);+ });++ it('no first byte within the grace budget fails with the distinct first-byte message', async () => {+ // Chat timeout 200ms, stall 100ms → first-byte budget max(200,100)=200ms.+ // The upstream stays silent for 800ms. The error must say "no first byte",+ // not "stream stalled" — distinct wording for the attempt-trace summary.+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = makeProvider(200);+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 800, data: CONTENT_FRAME + FINISH_FRAME },+ ]));++ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'm')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('no first byte within 200ms');+ expect(err.message).not.toContain('stream stalled');+ // Fires before any byte reached the client — must fail over invisibly.+ expect(isRetryableError(err)).toBe(true);+ });++ it('the first-byte grace never tightens below the stall budget (short chat timeout)', async () => {+ // Chat timeout 100ms but stall budget 600ms: pre-grace the first read had+ // the full stall budget, and the grace must not make it stricter. First+ // byte at 300ms — over the chat timeout, under the stall budget — succeeds.+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '600';+ const provider = makeProvider(100);+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 300, data: CONTENT_FRAME + FINISH_FRAME },+ ]));++ const chunks = await collect(provider.streamChatCompletion('k', MESSAGES, 'm'));+ expect(chunks.map(c => c.choices?.[0]?.delta?.content ?? '')).toContain('hello');+ });++ it('PROVIDER_TIMEOUT_<PLATFORM>=0 disables the first-byte bound but keeps the mid-stream watchdog', async () => {+ process.env.PROVIDER_TIMEOUT_GROQ = '0';+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = makeProvider(200); // env 0 overrides the constructor value+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 500, data: CONTENT_FRAME }, // way past both budgets: only OK if unbounded+ { afterMs: 600, data: FINISH_FRAME }, // mid-stream gap: watchdog must still fire+ ]));++ const startedAt = Date.now();+ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'm')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('stream stalled: no data for 100ms');+ // The failure must be the MID-STREAM gap (after the 500ms unbounded first+ // byte), not a stall-bounded first read firing at 100ms.+ expect(Date.now() - startedAt).toBeGreaterThan(450);+ });+});++describe('per-platform stall override PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>', () => {+ it('wins over the global PROVIDER_STREAM_STALL_TIMEOUT_MS', async () => {+ // Global would allow the 400ms mid-stream gap; the per-platform 100ms+ // must be the one that fires.+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '60000';+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_GROQ = '100';+ const provider = makeProvider(1500);+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 0, data: CONTENT_FRAME },+ { afterMs: 400, data: FINISH_FRAME },+ ]));++ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'm')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('stream stalled: no data for 100ms');+ });++ it('an override for a DIFFERENT platform leaves this one on the global value', async () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '60000';+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_NVIDIA = '100';+ const provider = makeProvider(1500); // platform groq+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 0, data: CONTENT_FRAME },+ { afterMs: 300, data: FINISH_FRAME },+ ]));++ const chunks = await collect(provider.streamChatCompletion('k', MESSAGES, 'm'));+ expect(chunks.some(c => c.choices?.[0]?.finish_reason === 'stop')).toBe(true);+ });+});++describe('google adapter first-byte grace (own stream reader)', () => {+ const GOOGLE_FRAME = 'data: {"candidates":[{"content":{"parts":[{"text":"hi there"}]},"finishReason":"STOP"}]}\n\n';++ it('a Gemini stream silent past the stall timeout, then delivering, succeeds under the grace', async () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = new GoogleProvider({ timeoutMs: 1500 });+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 400, data: GOOGLE_FRAME },+ ]));++ const chunks = await collect(provider.streamChatCompletion('k', MESSAGES, 'gemini-test'));+ expect(chunks.map(c => c.choices?.[0]?.delta?.content ?? '')).toContain('hi there');+ });++ it('a Gemini stream with no first byte within the grace fails with the first-byte message', async () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = new GoogleProvider({ timeoutMs: 200 });+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 800, data: GOOGLE_FRAME },+ ]));++ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'gemini-test')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('no first byte within 200ms');+ });++ it('a Gemini mid-stream gap past the stall timeout still fails fast', async () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '100';+ const provider = new GoogleProvider({ timeoutMs: 1500 });+ const partial = 'data: {"candidates":[{"content":{"parts":[{"text":"start"}]}}]}\n\n';+ vi.spyOn(global, 'fetch').mockResolvedValue(delayedSseResponse([+ { afterMs: 0, data: partial },+ { afterMs: 500, data: GOOGLE_FRAME },+ ]));++ const err = await collect(provider.streamChatCompletion('k', MESSAGES, 'gemini-test')).then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(err.message).toContain('stream stalled: no data for 100ms');+ });+});++describe('client abort composition under the grace period (#601 non-regression)', () => {+ it('a client abort while waiting for the first byte rejects promptly with the marked reason, not a timeout', async () => {+ // Real loopback upstream: undici's signal wiring is the behavior under+ // test. SSE headers arrive instantly, then no body bytes — the consumer is+ // parked in the FIRST read, under a long grace budget. The disconnect must+ // surface immediately as the marked client abort, not wait out any budget.+ let sawClose!: () => void;+ const closed = new Promise<void>(resolve => { sawClose = resolve; });+ const server = http.createServer((_req, res) => {+ res.on('close', sawClose);+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ // hold the connection open, silent+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as AddressInfo).port;++ try {+ const provider = new OpenAICompatProvider({+ platform: 'groq', name: 'TestProvider',+ baseUrl: `http://127.0.0.1:${port}/v1`,+ timeoutMs: 30_000, // long grace: the abort must NOT wait for it+ });+ const clientAbort = new AbortController();+ const startedAt = Date.now();+ const pending = collect(provider.streamChatCompletion('k', MESSAGES, 'm', { signal: clientAbort.signal }));+ setTimeout(() => clientAbort.abort(newClientAbortError()), 100);++ const err = await pending.then(() => null, e => e);+ expect(err).not.toBeNull();+ expect(isClientAbortError(err)).toBe(true);+ expect(Date.now() - startedAt).toBeLessThan(3000);+ await closed;+ } finally {+ server.closeAllConnections();+ await new Promise<void>(resolve => server.close(() => resolve()));+ }+ });+});diff --git a/server/src/__tests__/routes/proxy-model-groups.test.ts b/server/src/__tests__/routes/proxy-model-groups.test.tsindex 49984951..8904acb2 100644--- a/server/src/__tests__/routes/proxy-model-groups.test.ts+++ b/server/src/__tests__/routes/proxy-model-groups.test.ts@@ -3,7 +3,7 @@ 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 { setUnifyEnabled } from '../../services/model-groups.js';+import { setUnifyEnabled, setUnifyOverrides } from '../../services/model-groups.js';import { setRoutingStrategy } from '../../services/router.js';import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';@@ -82,6 +82,7 @@ describe('Model unification (group the same model across providers)', () => {db.prepare('DELETE FROM rate_limit_cooldowns').run();db.prepare('DELETE FROM rate_limit_usage').run();setUnifyEnabled(true);+ setUnifyOverrides({ merges: [], splits: [] });setRoutingStrategy('priority');addModel('groq', 'tum-groq', 'Test Unify Model', 1);addModel('cerebras', 'tum-cerebras', 'Test Unify Model', 2);@@ -210,6 +211,60 @@ describe('Model unification (group the same model across providers)', () => {expect(body.choices).toBeUndefined(); // no answer from any model});+ it('pinning "platform:model_id" hard-pins that provider — no cross-provider failover (#580)', async () => {+ const orig = global.fetch;+ vi.spyOn(global, 'fetch').mockImplementation(async (url: any, init?: any) => {+ const u = String(url);+ if (u.includes('api.groq.com')) return new Response(JSON.stringify({ error: { message: 'rate limited' } }), { status: 429 });+ if (u.includes('api.cerebras.ai')) return completion('tum-cerebras', 'from cerebras');+ return orig(url, init);+ });++ // The fully-qualified id routes to exactly that provider (priority 2 —+ // priority 1 Groq must NOT be used even though it would sort first).+ const pinned = await request(app, 'POST', '/v1/chat/completions', {+ model: 'cerebras:tum-cerebras',+ messages: [{ role: 'user', content: 'hi' }],+ }, authHeaders());+ expect(pinned.status).toBe(200);+ expect(pinned.headers.get('x-routed-via')).toContain('cerebras');++ // And when the pinned provider is down, the request FAILS instead of+ // silently serving from a sibling provider.+ const down = await request(app, 'POST', '/v1/chat/completions', {+ model: 'groq:tum-groq',+ messages: [{ role: 'user', content: 'hi' }],+ }, authHeaders());+ expect(down.status).toBe(429);+ expect(down.headers.get('x-routed-via') ?? '').not.toContain('cerebras');++ // An unknown platform:model_id keeps the not-found behavior.+ const unknown = await request(app, 'POST', '/v1/chat/completions', {+ model: 'nope:tum-groq',+ messages: [{ role: 'user', content: 'hi' }],+ }, authHeaders());+ expect(unknown.status).toBe(404);+ });++ it('PUT /api/settings/unify splits override un-merges one provider copy (the dashboard opt-out, #580)', async () => {+ const put = await request(app, 'PUT', '/api/settings/unify', {+ overrides: { merges: [], splits: [{ member: 'groq:tum-groq' }] },+ });+ expect(put.status).toBe(200);+ expect(put.body.overrides.splits).toEqual([{ member: 'groq:tum-groq' }]);++ // The split copy is advertised as its own logical model now.+ const { body } = await request(app, 'GET', '/v1/models', undefined, authHeaders());+ const ours = body.data.filter((m: any) => m.name === 'Test Unify Model');+ expect(ours).toHaveLength(2);++ // Removing the split (the UI's undo) collapses them again.+ const undo = await request(app, 'PUT', '/api/settings/unify', { overrides: { merges: [], splits: [] } });+ expect(undo.status).toBe(200);+ const after = await request(app, 'GET', '/v1/models', undefined, authHeaders());+ expect(after.body.data.filter((m: any) => m.name === 'Test Unify Model')).toHaveLength(1);+ });+it('unification is always on: the toggle was removed, so /v1/models stays collapsed even after setUnifyEnabled(false)', async () => {// The unify on/off switch was removed from the product; isUnifyEnabled() now// always returns true, so writing the old setting has no effect.diff --git a/server/src/__tests__/services/model-groups.test.ts b/server/src/__tests__/services/model-groups.test.tsindex 1f73f8a2..8e8c48e5 100644--- a/server/src/__tests__/services/model-groups.test.ts+++ b/server/src/__tests__/services/model-groups.test.ts@@ -145,8 +145,16 @@ describe('resolveRequestedIdToMembers', () => {expect(resolveRequestedIdToMembers('gpt-oss-120b', groups)!.sort()).toEqual([1, 2, 3, 4, 5]);expect(resolveRequestedIdToMembers('@cf/openai/gpt-oss-120b', groups)!.sort()).toEqual([1, 2, 3, 4, 5]);});- it('resolves an explicit "platform:model_id" member', () => {- expect(resolveRequestedIdToMembers('groq:openai/gpt-oss-120b', groups)!.sort()).toEqual([1, 2, 3, 4, 5]);+ it('hard-pins an explicit "platform:model_id" member to ONLY that member (#580)', () => {+ expect(resolveRequestedIdToMembers('groq:openai/gpt-oss-120b', groups)).toEqual([2]);+ expect(resolveRequestedIdToMembers('cloudflare:@cf/openai/gpt-oss-120b', groups)).toEqual([3]);+ });+ it('a bare model_id containing a colon still resolves the whole group (Ollama ids)', () => {+ expect(resolveRequestedIdToMembers('gpt-oss:120b', groups)!.sort()).toEqual([1, 2, 3, 4, 5]);+ });+ it('returns null for an unknown platform:model_id (not-found, not the group)', () => {+ expect(resolveRequestedIdToMembers('nope:gpt-oss-120b', groups)).toBeNull();+ expect(resolveRequestedIdToMembers('groq:not-a-model', groups)).toBeNull();});it('returns null for an unknown id', () => {expect(resolveRequestedIdToMembers('does-not-exist', groups)).toBeNull();diff --git a/server/src/__tests__/services/router-key-bandit.test.ts b/server/src/__tests__/services/router-key-bandit.test.tsnew file mode 100644index 00000000..dce5b92e--- /dev/null+++ b/server/src/__tests__/services/router-key-bandit.test.ts@@ -0,0 +1,160 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { routeRequest, refreshStatsCache, setRoutingStrategy } from '../../services/router.js';+import * as ratelimit from '../../services/ratelimit.js';+import { getDb, initDb } from '../../db/index.js';++// Per-key scoring inside one model (#580): with the group merge, several keys+// (and formerly several providers' identically-named models) share one routing+// bucket. Key selection must not be blind round-robin — a key with a bad track+// record (expired, quota-drained, region-blocked) should be picked less than a+// healthy sibling, while a brand-new key still gets explored.++vi.mock('../../services/ratelimit.js', async () => {+ const actual = await vi.importActual('../../services/ratelimit.js');+ return {+ ...actual,+ canMakeRequest: vi.fn(() => true),+ canUseTokens: vi.fn(() => true),+ isOnCooldown: vi.fn(() => false),+ };+});++vi.mock('../../lib/crypto.js', async () => {+ const actual = await vi.importActual('../../lib/crypto.js');+ return { ...actual, decrypt: vi.fn(() => 'mocked-api-key') };+});++const ORIGINAL_DEV_MODE = process.env.DEV_MODE;+const ORIGINAL_NODE_ENV = process.env.NODE_ENV;++// Insert a model + fallback entry (no key — keys are added separately).+function addModel(opts: {+ platform: string; modelId: string; name: string; priority?: number;+}): number {+ const db = getDb();+ db.prepare(`+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label, monthly_token_budget, enabled)+ VALUES (?, ?, ?, 3, 1, 'Large', '~50M', 1)+ `).run(opts.platform, opts.modelId, opts.name);+ const id = (db.prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?')+ .get(opts.platform, opts.modelId) as { id: number }).id;+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, opts.priority ?? 1);+ return id;+}++function addKey(platform: string, label: string): number {+ const db = getDb();+ db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, ?, 'enc', 'iv', 'tag', 'healthy', 1)+ `).run(platform, label);+ return Number((db.prepare('SELECT id FROM api_keys WHERE platform = ? AND label = ?')+ .get(platform, label) as { id: number }).id);+}++// Insert request rows attributed to a SPECIFIC key (now → age 0, weight 1).+function addKeyHistory(platform: string, modelId: string, keyId: number, opts: {+ successes: number; failures: number; outTokens?: number; latencyMs?: number;+}) {+ const db = getDb();+ const ins = db.prepare(`+ INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, ttfb_ms)+ VALUES (?, ?, ?, ?, 0, ?, ?, ?, NULL)+ `);+ for (let i = 0; i < opts.successes; i++) {+ ins.run(platform, modelId, keyId, 'success', opts.outTokens ?? 100, opts.latencyMs ?? 1000, null);+ }+ for (let i = 0; i < opts.failures; i++) {+ ins.run(platform, modelId, keyId, 'error', 0, opts.latencyMs ?? 1000, 'boom');+ }+}++function pickKeyCounts(runs: number): Record<number, number> {+ const counts: Record<number, number> = {};+ for (let i = 0; i < runs; i++) {+ const r = routeRequest(100);+ counts[r.keyId] = (counts[r.keyId] ?? 0) + 1;+ r.release();+ }+ return counts;+}++describe('per-key bandit selection', () => {+ beforeEach(() => {+ process.env.DEV_MODE = 'true';+ process.env.NODE_ENV = 'test';+ initDb(':memory:');+ getDb().exec('DELETE FROM fallback_config; DELETE FROM api_keys; DELETE FROM models; DELETE FROM requests;');+ vi.clearAllMocks();+ (ratelimit.canMakeRequest as any).mockReturnValue(true);+ (ratelimit.canUseTokens as any).mockReturnValue(true);+ (ratelimit.isOnCooldown as any).mockReturnValue(false);+ setRoutingStrategy('balanced');+ });++ afterEach(() => {+ if (ORIGINAL_DEV_MODE === undefined) delete process.env.DEV_MODE; else process.env.DEV_MODE = ORIGINAL_DEV_MODE;+ if (ORIGINAL_NODE_ENV === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = ORIGINAL_NODE_ENV;+ });++ it('prefers the key with the better recorded success rate', () => {+ addModel({ platform: 'groq', modelId: 'm', name: 'M' });+ const good = addKey('groq', 'good');+ const bad = addKey('groq', 'bad');+ addKeyHistory('groq', 'm', good, { successes: 50, failures: 1 });+ addKeyHistory('groq', 'm', bad, { successes: 4, failures: 40 });+ refreshStatsCache(getDb(), true);++ const counts = pickKeyCounts(300);+ expect(counts[good] ?? 0).toBeGreaterThan((counts[bad] ?? 0) * 3);+ });++ it('still explores a key with no recorded data', () => {+ addModel({ platform: 'groq', modelId: 'm', name: 'M' });+ const seasoned = addKey('groq', 'seasoned');+ const fresh = addKey('groq', 'fresh');+ addKeyHistory('groq', 'm', seasoned, { successes: 40, failures: 2 });+ refreshStatsCache(getDb(), true);++ const counts = pickKeyCounts(300);+ expect(counts[fresh] ?? 0).toBeGreaterThan(0);+ expect(counts[seasoned] ?? 0).toBeGreaterThan(0);+ });++ it('cooldown still excludes a key regardless of its score', () => {+ addModel({ platform: 'groq', modelId: 'm', name: 'M' });+ const good = addKey('groq', 'good');+ const other = addKey('groq', 'other');+ addKeyHistory('groq', 'm', good, { successes: 50, failures: 0 });+ addKeyHistory('groq', 'm', other, { successes: 5, failures: 20 });+ refreshStatsCache(getDb(), true);++ (ratelimit.isOnCooldown as any).mockImplementation(+ (_p: string, _m: string, keyId: number) => keyId === good,+ );+ const counts = pickKeyCounts(50);+ expect(counts[good] ?? 0).toBe(0);+ expect(counts[other]).toBe(50);+ });++ it('a single-key model always routes to that key', () => {+ addModel({ platform: 'groq', modelId: 'm', name: 'M' });+ const only = addKey('groq', 'only');+ addKeyHistory('groq', 'm', only, { successes: 3, failures: 30 });+ refreshStatsCache(getDb(), true);++ const counts = pickKeyCounts(30);+ expect(counts[only]).toBe(30);+ });++ it('with no data on any key, falls back to round-robin rotation', () => {+ addModel({ platform: 'groq', modelId: 'm', name: 'M' });+ const a = addKey('groq', 'a');+ const b = addKey('groq', 'b');+ refreshStatsCache(getDb(), true);++ const counts = pickKeyCounts(40);+ expect(counts[a]).toBe(20);+ expect(counts[b]).toBe(20);+ });+});diff --git a/server/src/lib/error-classify.ts b/server/src/lib/error-classify.tsindex b1c02005..76b82874 100644--- a/server/src/lib/error-classify.ts+++ b/server/src/lib/error-classify.ts@@ -93,6 +93,9 @@ export function isRetryableError(err: any): boolean {|| msg.includes('in-band provider error')|| msg.includes('stream ended unexpectedly')|| msg.includes('stream stalled')+ // First-byte timeout (#584): the grace budget expired before ANY byte+ // reached the client, so the next candidate can serve it invisibly.+ || msg.includes('no first byte')|| msg.includes('unparseable inline tool-call dialect');}diff --git a/server/src/lib/provider-timeout.ts b/server/src/lib/provider-timeout.tsindex 11ec2430..d6a6e96c 100644--- a/server/src/lib/provider-timeout.ts+++ b/server/src/lib/provider-timeout.ts@@ -7,9 +7,16 @@//// PROVIDER_STREAM_STALL_TIMEOUT_MS is the streaming counterpart for the// mid-stream inactivity watchdog (issue #553): how long an SSE stream may go-// without a single byte before the gateway gives up on it. It is global, not-// per-platform: a stall looks the same everywhere, and the per-platform knob-// above already covers the slow-first-byte case.+// without a single byte before the gateway gives up on it.+// PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM> (issue #584) overrides it for one+// platform; precedence is per-platform > global > built-in default (90s).+//+// The stall watchdog does NOT bound time-to-first-byte: the FIRST read of a+// stream gets a grace budget derived from the platform's chat timeout (the+// PROVIDER_TIMEOUT_<PLATFORM> knob above), floored at the stall budget — see+// BaseProvider.readSseStream. Before #584 the stall budget also bounded the+// first byte, which killed healthy long prefills (NVIDIA NIM sends SSE headers+// instantly, then prefills 100k-token prompts for minutes) at 90s.const warned = new Set<string>();@@ -47,10 +54,19 @@ export function providerTimeoutMs(platform: string, defaultMs: number): number {export const DEFAULT_STREAM_STALL_TIMEOUT_MS = 90_000;-/** Effective mid-stream inactivity timeout (PROVIDER_STREAM_STALL_TIMEOUT_MS,- * default 90s, 0 disables). Resolved per call so tests can vary the env. */-export function streamStallTimeoutMs(): number {- return parseTimeoutEnv('PROVIDER_STREAM_STALL_TIMEOUT_MS', DEFAULT_STREAM_STALL_TIMEOUT_MS);+export function streamStallTimeoutEnvName(platform: string): string {+ return `PROVIDER_STREAM_STALL_TIMEOUT_${platform.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;+}++/** Effective mid-stream inactivity timeout, 0 disables. Resolved per call so+ * tests can vary the env. Precedence (#584): the per-platform+ * PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM> when a platform is given and the+ * var is set and valid, else the global PROVIDER_STREAM_STALL_TIMEOUT_MS,+ * else the built-in 90s default. */+export function streamStallTimeoutMs(platform?: string): number {+ const globalMs = parseTimeoutEnv('PROVIDER_STREAM_STALL_TIMEOUT_MS', DEFAULT_STREAM_STALL_TIMEOUT_MS);+ if (!platform) return globalMs;+ return parseTimeoutEnv(streamStallTimeoutEnvName(platform), globalMs);}/** Test hook: forget which malformed values have already been warned about. */diff --git a/server/src/providers/base.ts b/server/src/providers/base.tsindex 0a3e4192..93a49b9f 100644--- a/server/src/providers/base.ts+++ b/server/src/providers/base.ts@@ -94,6 +94,18 @@ export interface ProviderFetchOptions {timeoutBounds?: 'headers' | 'request';}+/** Per-stream timeout wiring for readSseStream (#584). */+export interface SseStreamOptions {+ /** The chat timeout the adapter gave fetchWithTimeout for this request+ * (options.timeoutMs override included). Becomes the first-byte grace+ * budget, floored at the stall budget — see firstByteBudgetMs. Defaults to+ * fetchWithTimeout's own default, providerTimeoutMs(platform, 15000). */+ firstByteTimeoutMs?: number;+ /** Mid-stream inactivity budget; defaults to streamStallTimeoutMs(platform)+ * (per-platform env > global env > 90s). 0 disables the watchdog. */+ stallTimeoutMs?: number;+}+export interface KeyValidationFailure {valid: false;/** Provider-supplied reason suitable for health logs and the local keys UI. */@@ -219,14 +231,17 @@ export abstract class BaseProvider {* One reader.read() bounded by the mid-stream inactivity watchdog (#553).* Shared by readSseStream and adapters that parse their own wire format* (google.ts) so every stream gets the same stall semantics:- * PROVIDER_STREAM_STALL_TIMEOUT_MS, default 90s, 0 disables. Client-abort- * rejections pass through untouched — undici errors the body with the- * request signal's reason, so a disconnect surfaces here as the marked- * error from newClientAbortError, not as a stall.+ * PROVIDER_STREAM_STALL_TIMEOUT_MS (per-platform override+ * PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM>, #584), default 90s, 0 disables.+ * Client-abort rejections pass through untouched — undici errors the body+ * with the request signal's reason, so a disconnect surfaces here as the+ * marked error from newClientAbortError, not as a stall. `timeoutMessage`+ * lets the first-byte read report its distinct wording (#584).*/protected async readWithStallTimeout<T>(read: () => Promise<T>,inactivityTimeoutMs: number,+ timeoutMessage?: string,): Promise<T> {if (inactivityTimeoutMs <= 0) return read();let timer: ReturnType<typeof setTimeout> | undefined;@@ -234,20 +249,46 @@ export abstract class BaseProvider {read(),new Promise<never>((_, reject) => {timer = setTimeout(- () => reject(new Error(`${this.name} stream stalled: no data for ${inactivityTimeoutMs}ms (timeout)`)),+ () => reject(new Error(timeoutMessage ?? `${this.name} stream stalled: no data for ${inactivityTimeoutMs}ms (timeout)`)),inactivityTimeoutMs,);}),]).finally(() => clearTimeout(timer));}+ /**+ * Budget for the FIRST read of a streaming body (issue #584): the platform's+ * chat timeout is already "how slow may the first token be" — tuned per+ * platform at registration and env-overridable via PROVIDER_TIMEOUT_<PLATFORM>+ * — but on streams it is disarmed the moment response HEADERS arrive, and+ * providers like NVIDIA NIM send SSE headers instantly then prefill for+ * minutes. Floored at the stall budget so a platform with a short chat+ * timeout never gets a STRICTER first read than the pre-#584 watchdog gave+ * it. 0 on either side (env-disabled chat timeout, or disabled watchdog)+ * means the first read is unbounded — the client signal still owns+ * "nobody is listening".+ */+ protected firstByteBudgetMs(chatTimeoutMs: number, stallTimeoutMs: number): number {+ if (chatTimeoutMs <= 0 || stallTimeoutMs <= 0) return 0;+ return Math.max(chatTimeoutMs, stallTimeoutMs);+ }++ /** Distinct wording for a first-byte timeout (vs a mid-stream stall) so the+ * attempt-trace error_summary tells slow prefill apart from a dead stream. */+ protected firstByteTimeoutMessage(budgetMs: number): string {+ return `${this.name} stream: no first byte within ${budgetMs}ms (first-byte timeout)`;+ }+/*** Shared SSE reader for OpenAI-wire streaming endpoints (#231 audit).** Hardened against the upstream failure modes observed live:* - Inactivity timeout: fetchWithTimeout's abort timer dies the moment* response HEADERS arrive, so a provider that stalls mid-body used to- * hang the client forever. Each read now has its own deadline.+ * hang the client forever. Each read now has its own deadline. The FIRST+ * read gets a grace budget derived from the platform's chat timeout+ * (#584) — SSE headers can arrive instantly while the model prefills a+ * long prompt for minutes, which is slow, not stalled.* - Abrupt EOF: a stream that ends without `[DONE]` AND without any* `finish_reason` is a truncated generation, not a completion. It used* to end the generator silently (truncation logged as success); it now@@ -265,30 +306,43 @@ export abstract class BaseProvider {*/protected async *readSseStream(res: Response,- inactivityTimeoutMs?: number,+ opts?: SseStreamOptions,): AsyncGenerator<ChatCompletionChunk> {- yield* extractThinkTagsFromStream(this.readSseFrames(res, inactivityTimeoutMs));+ yield* extractThinkTagsFromStream(this.readSseFrames(res, opts));}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 OpenAI- // SDK clients swallow, so responses "just stopped" (issue #553). Operators- // proxying slow free tiers can now raise it (or 0 to disable) via- // PROVIDER_STREAM_STALL_TIMEOUT_MS.- inactivityTimeoutMs = streamStallTimeoutMs(),+ opts?: SseStreamOptions,): AsyncGenerator<ChatCompletionChunk> {const reader = res.body?.getReader();if (!reader) throw new Error('No response body');+ // The 90s default was hardcoded and silently truncated slow streams — the+ // gateway ended them with an error frame plus a clean [DONE] that OpenAI+ // SDK clients swallow, so responses "just stopped" (issue #553). Operators+ // proxying slow free tiers can raise it (or 0 to disable) via+ // PROVIDER_STREAM_STALL_TIMEOUT_MS, or per platform via+ // PROVIDER_STREAM_STALL_TIMEOUT_<PLATFORM> (#584).+ const inactivityTimeoutMs = opts?.stallTimeoutMs ?? streamStallTimeoutMs(this.platform);+ // First-byte grace (#584): adapters pass the same chat timeout they gave+ // fetchWithTimeout; the fallback mirrors fetchWithTimeout's own default so+ // adapters that never tuned either stay on max(15s-or-env, stall) — i.e.+ // exactly the stall budget they had before.+ const chatTimeoutMs = opts?.firstByteTimeoutMs ?? providerTimeoutMs(this.platform, 15000);+ const firstByteMs = this.firstByteBudgetMs(chatTimeoutMs, inactivityTimeoutMs);+const decoder = new TextDecoder();let buffer = '';let sawFinishReason = false;+ let awaitingFirstByte = true;try {while (true) {- const { done, value } = await this.readWithStallTimeout(() => reader.read(), inactivityTimeoutMs);+ const { done, value } = awaitingFirstByte+ ? await this.readWithStallTimeout(() => reader.read(), firstByteMs, this.firstByteTimeoutMessage(firstByteMs))+ : await this.readWithStallTimeout(() => reader.read(), inactivityTimeoutMs);+ awaitingFirstByte = false;if (done) break;buffer += decoder.decode(value, { stream: true });diff --git a/server/src/providers/cloudflare.ts b/server/src/providers/cloudflare.tsindex 08bfefcc..baa5cf4d 100644--- a/server/src/providers/cloudflare.ts+++ b/server/src/providers/cloudflare.ts@@ -151,7 +151,9 @@ export class CloudflareProvider extends BaseProvider {throw providerHttpError(res, `Cloudflare API error ${res.status}: ${(err as any).error?.message ?? (err as any).errors?.[0]?.message ?? res.statusText}`);}- yield* this.readSseStream(res);+ // First-byte grace (#584): reuse the per-model chat timeout (GLM 4.7+ // Flash's 200s included) as the budget for the first stream read.+ yield* this.readSseStream(res, { firstByteTimeoutMs: this.timeoutFor(modelId, options?.timeoutMs) });}async validateKey(apiKey: string, quotaContext?: QuotaObservationContext): Promise<KeyValidationResult> {diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 264dc3ff..71fa53c3 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -114,12 +114,6 @@ function isGemmaModel(modelId: string): boolean {return /(?:^|[/.:])gemma[-_]/.test(normalized);}-function optionsForModel(modelId: string, options?: CompletionOptions): CompletionOptions | undefined {- if (!isGemmaModel(modelId) || !options) return options;- const { tools: _tools, tool_choice: _toolChoice, parallel_tool_calls: _parallelToolCalls, ...rest } = options;- return rest;-}-function systemInstructionText(systemInstruction: { parts?: Array<{ text?: string }> } | undefined): string | null {const text = systemInstruction?.parts?.map(part => part.text ?? '')@@ -128,6 +122,13 @@ function systemInstructionText(systemInstruction: { parts?: Array<{ text?: strinreturn text ? text : null;}+// Gemma models on the Gemini API historically 400 with "Developer instruction+// is not enabled", so system prompts fold into the first user turn instead of+// riding systemInstruction (#500). Older Gemma 3.x still rejects system+// instructions and users can register those ids, so the fold stays. Tools and+// functionCall/functionResponse history are deliberately NOT touched here+// anymore: Gemma 4 supports native function calling, and stripping them made+// the dashboard supports_tools toggle a no-op (#582).function contentsForModel(modelId: string,contents: GeminiContent[],@@ -135,24 +136,13 @@ function contentsForModel(): { contents: GeminiContent[]; systemInstruction?: { parts: Array<{ text: string }> } } {if (!isGemmaModel(modelId)) return { contents, systemInstruction };- const cleaned = contents- .map((entry): GeminiContent | null => {- const parts = entry.parts.filter(part => !part.functionCall && !part.functionResponse);- if (parts.length === 0) return null;- return { ...entry, parts };- })- .filter((entry): entry is GeminiContent => entry !== null);- const safeContents = cleaned.length > 0- ? cleaned- : [{ role: 'user' as const, parts: [{ text: '' }] }];-const systemText = systemInstructionText(systemInstruction);- if (!systemText) return { contents: safeContents };+ if (!systemText) return { contents };return {contents: [{ role: 'user', parts: [{ text: systemText }] },- ...safeContents,+ ...contents,],};}@@ -570,22 +560,21 @@ export class GoogleProvider extends BaseProvider {): Promise<ChatCompletionResponse> {const translated = await toGeminiContents(messages);const request = contentsForModel(modelId, translated.contents, translated.systemInstruction);- const modelOptions = optionsForModel(modelId, options);- const tools = toGeminiTools(modelOptions?.tools);+ const tools = toGeminiTools(options?.tools);const body: Record<string, unknown> = {contents: request.contents,generationConfig: {- temperature: modelOptions?.temperature,- maxOutputTokens: modelOptions?.max_tokens,- topP: modelOptions?.top_p,- stopSequences: toGeminiStopSequences(modelOptions?.stop),- ...toGeminiExtendedConfig(modelOptions),+ temperature: options?.temperature,+ maxOutputTokens: options?.max_tokens,+ topP: options?.top_p,+ stopSequences: toGeminiStopSequences(options?.stop),+ ...toGeminiExtendedConfig(options),},tools,// functionCallingConfig is only valid when real function tools are present;// a grounding-only request (just google_search) must omit it. (#59)- toolConfig: hasFunctionDeclarations(tools) ? toGeminiToolConfig(modelOptions?.tool_choice) : undefined,+ toolConfig: hasFunctionDeclarations(tools) ? toGeminiToolConfig(options?.tool_choice) : undefined,};if (request.systemInstruction) body.systemInstruction = request.systemInstruction;@@ -654,20 +643,19 @@ export class GoogleProvider extends BaseProvider {): AsyncGenerator<ChatCompletionChunk> {const translated = await toGeminiContents(messages);const request = contentsForModel(modelId, translated.contents, translated.systemInstruction);- const modelOptions = optionsForModel(modelId, options);- const tools = toGeminiTools(modelOptions?.tools);+ const tools = toGeminiTools(options?.tools);const body: Record<string, unknown> = {contents: request.contents,generationConfig: {- temperature: modelOptions?.temperature,- maxOutputTokens: modelOptions?.max_tokens,- topP: modelOptions?.top_p,- stopSequences: toGeminiStopSequences(modelOptions?.stop),- ...toGeminiExtendedConfig(modelOptions),+ temperature: options?.temperature,+ maxOutputTokens: options?.max_tokens,+ topP: options?.top_p,+ stopSequences: toGeminiStopSequences(options?.stop),+ ...toGeminiExtendedConfig(options),},tools,- toolConfig: hasFunctionDeclarations(tools) ? toGeminiToolConfig(modelOptions?.tool_choice) : undefined,+ toolConfig: hasFunctionDeclarations(tools) ? toGeminiToolConfig(options?.tool_choice) : undefined,};if (request.systemInstruction) body.systemInstruction = request.systemInstruction;@@ -707,12 +695,19 @@ export class GoogleProvider extends BaseProvider {// Same mid-stream inactivity watchdog as readSseStream (#553): this adapter// parses Gemini's own frame format, so it reads the body itself and used to- // have no bound at all on a stalled read.- const inactivityTimeoutMs = streamStallTimeoutMs();+ // have no bound at all on a stalled read. Same first-byte grace as+ // readSseStream too (#584): the chat timeout that bounded the headers also+ // budgets the first read, floored at the stall budget.+ const inactivityTimeoutMs = streamStallTimeoutMs(this.platform);+ const firstByteMs = this.firstByteBudgetMs(options?.timeoutMs ?? this.timeoutMs, inactivityTimeoutMs);+ let awaitingFirstByte = true;try {while (true) {- const { done, value } = await this.readWithStallTimeout(() => reader.read(), inactivityTimeoutMs);+ const { done, value } = awaitingFirstByte+ ? await this.readWithStallTimeout(() => reader.read(), firstByteMs, this.firstByteTimeoutMessage(firstByteMs))+ : await this.readWithStallTimeout(() => reader.read(), inactivityTimeoutMs);+ awaitingFirstByte = false;if (done) break;buffer += decoder.decode(value, { stream: true });diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex d73d7039..c2dfd94e 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -40,13 +40,16 @@ register(new OpenAICompatProvider({// ("This model only supports single tool-calls at once!"), so pin// parallel_tool_calls to false when tools are present. See issue #255.// Reasoning models (deepseek-v4-pro, llama-4-maverick, llama-3.1/3.3-70b) take-// 30-60s on cold start; the default 15s false-flags them as broken. 90s.+// 30-60s on cold start; the default 15s false-flags them as broken. 180s:+// NIM sends SSE headers instantly, then prefills 100k-token prompts for+// minutes before the first byte, and this value doubles as the streaming+// first-byte grace budget (#584). Env-tunable via PROVIDER_TIMEOUT_NVIDIA.register(new OpenAICompatProvider({platform: 'nvidia',name: 'NVIDIA NIM',baseUrl: 'https://integrate.api.nvidia.com/v1',forceSingleToolCall: true,- timeoutMs: 90_000,+ timeoutMs: 180_000,}));// Mistral - OpenAI-compatiblediff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.tsindex af512509..21752b53 100644--- a/server/src/providers/openai-compat.ts+++ b/server/src/providers/openai-compat.ts@@ -342,7 +342,10 @@ export class OpenAICompatProvider extends BaseProvider {throw providerHttpError(res, `${this.name} API error ${res.status}: ${this.upstreamErrorText(err, res)}`);}- yield* this.readSseStream(res);+ // First-byte grace (#584): the same chat timeout that bounded the headers+ // also budgets the first stream read — NIM-style providers send SSE+ // headers instantly, then prefill long prompts for minutes.+ yield* this.readSseStream(res, { firstByteTimeoutMs: options?.timeoutMs ?? this.timeoutMs });}async validateKey(apiKey: string, quotaContext?: QuotaObservationContext): Promise<KeyValidationResult> {diff --git a/server/src/services/model-groups.ts b/server/src/services/model-groups.tsindex 81286e30..7c266723 100644--- a/server/src/services/model-groups.ts+++ b/server/src/services/model-groups.ts@@ -194,9 +194,13 @@ export function groupRows(rows: GroupableRow[], ov: UnifyOverrides): ModelGroup[/*** Resolve a requested model id to the db ids of its group members, or null.- * Accepts the canonical slug OR any member's `model_id`/"platform:model_id"- * (back-compat: an old per-provider id resolves to the whole group). Member- * order here is incidental — the router re-orders by the active strategy.+ * Accepts the canonical slug OR any member's `model_id` (back-compat: an old+ * per-provider id resolves to the whole group), OR the fully-qualified+ * "platform:model_id" member id — which HARD-PINS to only that member (#580):+ * spelling out the platform is an explicit "this provider's copy" request, so+ * it must not fail over to (or share scores with) the rest of the group.+ * Member order here is incidental — the router re-orders by the active+ * strategy.*/export function resolveRequestedIdToMembers(requested: string, groups: ModelGroup[]): number[] | null {if (!requested) return null;@@ -204,8 +208,16 @@ export function resolveRequestedIdToMembers(requested: string, groups: ModelGrouconst byCanonical = groups.find(g => g.canonicalId === requested);if (byCanonical) return byCanonical.members.map(m => m.model_db_id);+ // Exact "platform:model_id" → just that member. Checked before the bare+ // model_id scan; a bare model_id that itself contains a colon (e.g. Ollama's+ // "gpt-oss:120b") never collides because platforms aren't model-name prefixes.for (const g of groups) {- if (g.members.some(m => m.model_id === requested || memberId(m) === requested)) {+ const exact = g.members.find(m => memberId(m) === requested);+ if (exact) return [exact.model_db_id];+ }++ for (const g of groups) {+ if (g.members.some(m => m.model_id === requested)) {return g.members.map(m => m.model_db_id);}}diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 4a9b2cfa..efaa2ddc 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -345,7 +345,20 @@ interface ModelStats {monthlyUsedTokens: number; // calendar-month usage, for the headroom guardrail}+// Per-key slice of the same window (#580): reliability/speed observed through+// ONE credential of a model. With unified groups, a model's traffic can span+// several keys whose real quality diverges (expired, quota-drained, region-+// blocked keys fail while siblings are fine) — the rolled-up model bucket+// can't see that, so key selection needs its own buckets.+interface KeyStats {+ successes: number; // decay-weighted pseudo-count+ failures: number; // decay-weighted pseudo-count+ tokPerSec: number; // from successful requests only (0 = no data)+ avgTtfbMs: number | null;+}+let statsCache: Map<string, ModelStats> | null = null;+let keyStatsCache: Map<string, KeyStats> | null = null; // "platform:model_id:key_id"let statsCacheTime = 0;function decayWeight(ageDays: number): number {@@ -356,8 +369,12 @@ export function refreshStatsCache(db: Db, force = false): void {if (!force && statsCache && Date.now() - statsCacheTime < CACHE_TTL_MS) return;const since = new Date(Date.now() - WINDOW_MS).toISOString();+ // Grouped by (model, key, day age): still a handful of rows per model — key+ // count × ≤7 day buckets — so the finer grain keeps the same one-query,+ // 60s-cached shape. Aggregated two ways below: rolled up per model (ordering)+ // and per key (in-model key selection, #580).const buckets = db.prepare(`- SELECT platform, model_id,+ SELECT platform, model_id, key_id,CAST((julianday('now') - julianday(created_at)) AS INTEGER) AS age_days,COUNT(*) AS total,SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS successes,@@ -367,27 +384,37 @@ export function refreshStatsCache(db: Db, force = false): void {SUM(CASE WHEN status = 'success' AND ttfb_ms IS NOT NULL THEN 1 ELSE 0 END) AS succ_ttfb_cntFROM requestsWHERE created_at >= ?- GROUP BY platform, model_id, age_days+ GROUP BY platform, model_id, key_id, age_days`).all(since) as Array<{- platform: string; model_id: string; age_days: number; total: number; successes: number;+ platform: string; model_id: string; key_id: number | null; age_days: number; total: number; successes: number;succ_out: number; succ_lat: number; succ_ttfb_sum: number; succ_ttfb_cnt: number;}>;- // Accumulate decay-weighted sums per model.- const acc = new Map<string, {- wSucc: number; wFail: number; wOut: number; wLat: number; wTtfbSum: number; wTtfbCnt: number;- }>();- for (const b of buckets) {- const key = `${b.platform}:${b.model_id}`;- const w = decayWeight(b.age_days);- const a = acc.get(key) ?? { wSucc: 0, wFail: 0, wOut: 0, wLat: 0, wTtfbSum: 0, wTtfbCnt: 0 };+ // Accumulate decay-weighted sums per model AND per key.+ interface Acc { wSucc: number; wFail: number; wOut: number; wLat: number; wTtfbSum: number; wTtfbCnt: number }+ const emptyAcc = (): Acc => ({ wSucc: 0, wFail: 0, wOut: 0, wLat: 0, wTtfbSum: 0, wTtfbCnt: 0 });+ const addBucket = (a: Acc, w: number, b: (typeof buckets)[number]): void => {a.wSucc += w * b.successes;a.wFail += w * (b.total - b.successes);a.wOut += w * b.succ_out;a.wLat += w * b.succ_lat;a.wTtfbSum += w * b.succ_ttfb_sum;a.wTtfbCnt += w * b.succ_ttfb_cnt;- acc.set(key, a);+ };+ const acc = new Map<string, Acc>();+ const keyAcc = new Map<string, Acc>();+ for (const b of buckets) {+ const key = `${b.platform}:${b.model_id}`;+ const w = decayWeight(b.age_days);+ let a = acc.get(key);+ if (!a) acc.set(key, a = emptyAcc());+ addBucket(a, w, b);+ if (b.key_id != null) {+ const kk = `${key}:${b.key_id}`;+ let ka = keyAcc.get(kk);+ if (!ka) keyAcc.set(kk, ka = emptyAcc());+ addBucket(ka, w, b);+ }}// Calendar-month token usage per model, for the headroom guardrail.@@ -417,7 +444,18 @@ export function refreshStatsCache(db: Db, force = false): void {}}+ const nextKeys = new Map<string, KeyStats>();+ for (const [kk, a] of keyAcc) {+ nextKeys.set(kk, {+ successes: a.wSucc,+ failures: a.wFail,+ tokPerSec: a.wLat > 0 ? (a.wOut * 1000) / a.wLat : 0,+ avgTtfbMs: a.wTtfbCnt > 0 ? a.wTtfbSum / a.wTtfbCnt : null,+ });+ }+statsCache = next;+ keyStatsCache = nextKeys;statsCacheTime = Date.now();}@@ -668,16 +706,47 @@ export function resolveRoutingChain(modelString: string | undefined): ResolvedChreturn { chain, strategyKey: `auto:${suffix}` };}+// Weights for the in-model key score (#580). Reliability dominates: the point+// of per-key stats is catching a credential that FAILS (expired, drained,+// region-blocked); speed differences between keys of the same platform+model+// are second-order (account-tier throttling) but still worth a nudge.+const KEY_SCORE_WEIGHTS = { reliability: 0.75, speed: 0.25 };++/**+ * Order a model's candidate keys by a Thompson-sampled per-key score, mirroring+ * orderChain's bandit: reliability is a fresh draw from each key's Beta+ * posterior (so exploration is automatic and proportional to uncertainty — a+ * key with no data samples from the uniform prior and still gets traffic),+ * speed is deterministic. Returns null when NO key has recorded data, telling+ * the caller to keep the legacy round-robin rotation (no signal → no ranking).+ */+function orderKeysByScore(entry: ChainRow, keys: KeyRow[]): KeyRow[] | null {+ if (keys.length < 2 || !keyStatsCache) return null;+ const prefix = `${entry.platform}:${entry.model_id}:`;+ if (!keys.some(k => keyStatsCache!.has(prefix + k.id))) return null;++ return keys+ .map(k => {+ const stats = keyStatsCache!.get(prefix + k.id);+ const { alpha, beta } = reliabilityPosterior(stats?.successes ?? 0, stats?.failures ?? 0);+ const rel = sampleBeta(alpha, beta);+ const spd = speedScore(stats?.tokPerSec ?? 0, stats?.avgTtfbMs ?? null);+ return { k, s: KEY_SCORE_WEIGHTS.reliability * rel + KEY_SCORE_WEIGHTS.speed * spd };+ })+ .sort((a, b) => b.s - a.s || a.k.id - b.k.id)+ .map(x => x.k);+}+/*** Pick a usable key for ONE model and build its RouteResult, or return null if* the model has no key that can serve the request right now (all cooled down,- * over quota, undecryptable, or no provider). This is the per-model key- * round-robin previously inlined in routeRequest, factored out so the fusion- * panel can HARD-PIN a model: rotate across that model's keys without ever+ * over quota, undecryptable, or no provider). Factored out of routeRequest so+ * the fusion panel can HARD-PIN a model: walk that model's keys without ever* falling through to a different model (issue #326 — soft preference collapses- * panel diversity under rate limits). Request-level filters (vision/tools/- * context window) stay in the caller; this only does key selection + accounting- * pre-checks.+ * panel diversity under rate limits). Keys are tried in per-key bandit-score+ * order when any of them has recorded data (#580), else round-robin.+ * Request-level filters (vision/tools/context window) stay in the caller; this+ * only does key selection + accounting pre-checks.*/function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?: Set<string>, diag?: string[]): RouteResult | null {const db = getDb();@@ -709,11 +778,18 @@ function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?:tpd: entry.tpd_limit,};+ // Score-ordered walk over this model's keys (#580): when any key has recorded+ // reliability/speed data, try them best-sampled-score first so a chronically+ // failing key stops soaking up every Nth request. The stats cache is the same+ // 60s-TTL aggregate the model-level bandit uses (refresh is a no-op when+ // fresh, and cheap when not). With no data at all, keep the legacy rotation.+ refreshStatsCache(db);const rrKey = `${entry.platform}:${entry.model_id}`;let idx = roundRobinIndex.get(rrKey) ?? 0;+ const ranked = orderKeysByScore(entry, keys);for (let attempt = 0; attempt < keys.length; attempt++) {- const key = keys[idx % keys.length];+ const key = ranked ? ranked[attempt] : keys[idx % keys.length];idx++;// A custom model belongs to exactly one endpoint (#212); legacy rows